lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
a729a9b34303abdabf24948a2721cfef70b3b295
0
dbeaver/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.mssql.model; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ext.generic.model.*; import org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.exec.DBCQueryTransformProvider; import org.jkiss.dbeaver.model.exec.DBCQueryTransformType; import org.jkiss.dbeaver.model.exec.DBCQueryTransformer; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObjectFilter; import org.jkiss.dbeaver.model.struct.rdb.DBSIndexType; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * SQLServerMetaModel */ public class SQLServerMetaModel extends GenericMetaModel implements DBCQueryTransformProvider { private static final Log log = Log.getLog(SQLServerMetaModel.class); private final boolean sqlServer; public SQLServerMetaModel(boolean sqlServer) { super(); this.sqlServer = sqlServer; } @Override public SQLServerDataSource createDataSourceImpl(DBRProgressMonitor monitor, DBPDataSourceContainer container) throws DBException { return new SQLServerDataSource(monitor, container, this); } @Override public SQLServerDatabase createCatalogImpl(GenericDataSource dataSource, String catalogName) { return new SQLServerDatabase(dataSource, catalogName); } @Override public SQLServerSchema createSchemaImpl(GenericDataSource dataSource, GenericCatalog catalog, String schemaName) throws DBException { return new SQLServerSchema(dataSource, catalog, schemaName); } public String getViewDDL(DBRProgressMonitor monitor, GenericTable sourceObject, Map<String, Object> options) throws DBException { return extractSource(monitor, sourceObject.getDataSource(), sourceObject.getCatalog().getName(), sourceObject.getSchema().getName(), sourceObject.getName()); } @Override public String getProcedureDDL(DBRProgressMonitor monitor, GenericProcedure sourceObject) throws DBException { return extractSource(monitor, sourceObject.getDataSource(), sourceObject.getCatalog().getName(), sourceObject.getSchema().getName(), sourceObject.getName()); } @Override public boolean supportsTriggers(@NotNull GenericDataSource dataSource) { return true; } @Override public List<? extends GenericTrigger> loadTriggers(DBRProgressMonitor monitor, @NotNull GenericStructContainer container, @Nullable GenericTable table) throws DBException { try (JDBCSession session = DBUtils.openMetaSession(monitor, container.getDataSource(), "Read triggers")) { String schema = getSystemSchema(); String catalog = DBUtils.getQuotedIdentifier(container.getCatalog()); StringBuilder query = new StringBuilder("SELECT triggers.name FROM " + catalog + "." + schema + ".sysobjects triggers"); if (table != null) { query.append(",").append(catalog).append(".").append(schema).append(".sysobjects tables"); } query.append("\nWHERE triggers.type = 'TR'\n"); if (table != null) { query.append( "AND triggers.deltrig = tables.id\n" + "AND user_name(tables.uid) = ? AND tables.name = ?"); } try (JDBCPreparedStatement dbStat = session.prepareStatement(query.toString())) { if (table != null) { dbStat.setString(1, table.getSchema().getName()); dbStat.setString(2, table.getName()); } List<GenericTrigger> result = new ArrayList<>(); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String name = JDBCUtils.safeGetString(dbResult, 1); if (name == null) { continue; } name = name.trim(); GenericTrigger trigger = new GenericTrigger(container, table, name, null); result.add(trigger); } } return result; } } catch (SQLException e) { throw new DBException(e, container.getDataSource()); } } @NotNull private String getSystemSchema() { return sqlServer ? "sys" : "dbo"; } @Override public String getTriggerDDL(@NotNull DBRProgressMonitor monitor, @NotNull GenericTrigger trigger) throws DBException { GenericTable table = trigger.getTable(); assert table != null; return extractSource(monitor, table.getDataSource(), table.getCatalog().getName(), table.getSchema().getName(), trigger.getName()); } @Nullable @Override public DBCQueryTransformer createQueryTransformer(@NotNull DBCQueryTransformType type) { if (type == DBCQueryTransformType.RESULT_SET_LIMIT) { //return new QueryTransformerTop(); } return null; } private String extractSource(DBRProgressMonitor monitor, GenericDataSource dataSource, String catalog, String schema, String name) throws DBException { ServerType serverType = getServerType(); String systemSchema = getSystemSchema(); catalog = DBUtils.getQuotedIdentifier(dataSource, catalog); try (JDBCSession session = DBUtils.openMetaSession(monitor, dataSource, "Read source code")) { String mdQuery = serverType == ServerType.SQL_SERVER ? catalog + "." + systemSchema + ".sp_helptext '" + DBUtils.getQuotedIdentifier(dataSource, schema) + "." + DBUtils.getQuotedIdentifier(dataSource, name) + "'" : "SELECT sc.text\n" + "FROM " + catalog + "." + systemSchema + ".sysobjects so\n" + "INNER JOIN " + catalog + "." + systemSchema + ".syscomments sc on sc.id = so.id\n" + "WHERE user_name(so.uid)=? AND so.name=?"; try (JDBCPreparedStatement dbStat = session.prepareStatement(mdQuery)) { if (serverType == ServerType.SYBASE) { dbStat.setString(1, schema); dbStat.setString(2, name); } try (JDBCResultSet dbResult = dbStat.executeQuery()) { StringBuilder sql = new StringBuilder(); while (dbResult.nextRow()) { sql.append(dbResult.getString(1)); } return sql.toString(); } } } catch (SQLException e) { throw new DBException(e, dataSource); } } public ServerType getServerType() { return sqlServer ? ServerType.SQL_SERVER : ServerType.SYBASE; } @Override public SQLServerIndex createIndexImpl(GenericTable table, boolean nonUnique, String qualifier, long cardinality, String indexName, DBSIndexType indexType, boolean persisted) { return new SQLServerIndex(table, nonUnique, qualifier, cardinality, indexName, indexType, persisted); } @Override public String getAutoIncrementClause(GenericTableColumn column) { return "IDENTITY(1,1)"; } @Override public boolean useCatalogInObjectNames() { return false; } @Override public List<GenericSchema> loadSchemas(JDBCSession session, GenericDataSource dataSource, GenericCatalog catalog) throws DBException { if (catalog == null) { // Schemas MUST be in catalog return null; } boolean showAllSchemas = ((SQLServerDataSource) dataSource).isShowAllSchemas(); final DBSObjectFilter schemaFilters = dataSource.getContainer().getObjectFilter(GenericSchema.class, catalog, false); String sysSchema = DBUtils.getQuotedIdentifier(catalog) + "." + getSystemSchema(); String sql; if (showAllSchemas) { if (getServerType() == ServerType.SQL_SERVER && dataSource.isServerVersionAtLeast(9 ,0)) { sql = "SELECT name FROM " + DBUtils.getQuotedIdentifier(catalog) + ".sys.schemas"; } else { sql = "SELECT name FROM " + DBUtils.getQuotedIdentifier(catalog) + ".dbo.sysusers"; } } else { if (getServerType() == ServerType.SQL_SERVER) { sql = "SELECT DISTINCT s.name\n" + "FROM " + sysSchema + ".schemas s, " + sysSchema + ".sysobjects o\n" + "WHERE s.schema_id=o.uid\n" + "ORDER BY 1"; } else { sql = "SELECT DISTINCT u.name\n" + "FROM " + sysSchema + ".sysusers u, " + sysSchema + ".sysobjects o\n" + "WHERE u.uid=o.uid\n" + "ORDER BY 1"; } } try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) { List<GenericSchema> result = new ArrayList<>(); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String name = JDBCUtils.safeGetString(dbResult, 1); if (name == null) { continue; } name = name.trim(); if (schemaFilters != null && !schemaFilters.matches(name)) { // Doesn't match filter continue; } SQLServerSchema schema = createSchemaImpl( dataSource, catalog, name); result.add(schema); } } return result; } catch (SQLException e) { throw new DBException(e, dataSource); } } @Override public boolean supportsSequences(GenericDataSource dataSource) { return getServerType() == ServerType.SQL_SERVER; } @Override public List<GenericSequence> loadSequences(DBRProgressMonitor monitor, GenericStructContainer container) throws DBException { try (JDBCSession session = DBUtils.openMetaSession(monitor, container.getDataSource(), "Read system sequences")) { try (JDBCPreparedStatement dbStat = session.prepareStatement( "SELECT * FROM " + DBUtils.getQuotedIdentifier(container.getCatalog()) + "." + getSystemSchema() + ".sequences WHERE schema_name(schema_id)=?")) { dbStat.setString(1, container.getSchema().getName()); List<GenericSequence> result = new ArrayList<>(); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String name = JDBCUtils.safeGetString(dbResult, "name"); if (name == null) { continue; } name = name.trim(); GenericSequence sequence = new GenericSequence( container, name, null, JDBCUtils.safeGetLong(dbResult, "current_value"), JDBCUtils.safeGetLong(dbResult, "minimum_value"), JDBCUtils.safeGetLong(dbResult, "maximum_value"), JDBCUtils.safeGetLong(dbResult, "increment") ); result.add(sequence); } } return result; } } catch (SQLException e) { throw new DBException(e, container.getDataSource()); } } @Override public SQLServerTable createTableImpl(GenericStructContainer container, String tableName, String tableType, JDBCResultSet dbResult) { return new SQLServerTable(container, tableName, tableType, dbResult); } @Override public boolean isSystemTable(GenericTable table) { return getSystemSchema().equals(table.getSchema().getName()) && table.getName().startsWith("sys"); } }
plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerMetaModel.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.mssql.model; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ext.generic.model.*; import org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.exec.DBCQueryTransformProvider; import org.jkiss.dbeaver.model.exec.DBCQueryTransformType; import org.jkiss.dbeaver.model.exec.DBCQueryTransformer; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObjectFilter; import org.jkiss.dbeaver.model.struct.rdb.DBSIndexType; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * SQLServerMetaModel */ public class SQLServerMetaModel extends GenericMetaModel implements DBCQueryTransformProvider { private static final Log log = Log.getLog(SQLServerMetaModel.class); private final boolean sqlServer; public SQLServerMetaModel(boolean sqlServer) { super(); this.sqlServer = sqlServer; } @Override public SQLServerDataSource createDataSourceImpl(DBRProgressMonitor monitor, DBPDataSourceContainer container) throws DBException { return new SQLServerDataSource(monitor, container, this); } @Override public SQLServerDatabase createCatalogImpl(GenericDataSource dataSource, String catalogName) { return new SQLServerDatabase(dataSource, catalogName); } @Override public SQLServerSchema createSchemaImpl(GenericDataSource dataSource, GenericCatalog catalog, String schemaName) throws DBException { return new SQLServerSchema(dataSource, catalog, schemaName); } public String getViewDDL(DBRProgressMonitor monitor, GenericTable sourceObject, Map<String, Object> options) throws DBException { return extractSource(monitor, sourceObject.getDataSource(), sourceObject.getCatalog().getName(), sourceObject.getSchema().getName(), sourceObject.getName()); } @Override public String getProcedureDDL(DBRProgressMonitor monitor, GenericProcedure sourceObject) throws DBException { return extractSource(monitor, sourceObject.getDataSource(), sourceObject.getCatalog().getName(), sourceObject.getSchema().getName(), sourceObject.getName()); } @Override public boolean supportsTriggers(@NotNull GenericDataSource dataSource) { return true; } @Override public List<? extends GenericTrigger> loadTriggers(DBRProgressMonitor monitor, @NotNull GenericStructContainer container, @Nullable GenericTable table) throws DBException { try (JDBCSession session = DBUtils.openMetaSession(monitor, container.getDataSource(), "Read triggers")) { String schema = getSystemSchema(); String catalog = DBUtils.getQuotedIdentifier(container.getCatalog()); StringBuilder query = new StringBuilder("SELECT triggers.name FROM " + catalog + "." + schema + ".sysobjects triggers"); if (table != null) { query.append(",").append(catalog).append(".").append(schema).append(".sysobjects tables"); } query.append("\nWHERE triggers.type = 'TR'\n"); if (table != null) { query.append( "AND triggers.deltrig = tables.id\n" + "AND user_name(tables.uid) = ? AND tables.name = ?"); } try (JDBCPreparedStatement dbStat = session.prepareStatement(query.toString())) { if (table != null) { dbStat.setString(1, table.getSchema().getName()); dbStat.setString(2, table.getName()); } List<GenericTrigger> result = new ArrayList<>(); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String name = JDBCUtils.safeGetString(dbResult, 1); if (name == null) { continue; } name = name.trim(); GenericTrigger trigger = new GenericTrigger(container, table, name, null); result.add(trigger); } } return result; } } catch (SQLException e) { throw new DBException(e, container.getDataSource()); } } @NotNull private String getSystemSchema() { return sqlServer ? "sys" : "dbo"; } @Override public String getTriggerDDL(@NotNull DBRProgressMonitor monitor, @NotNull GenericTrigger trigger) throws DBException { GenericTable table = trigger.getTable(); assert table != null; return extractSource(monitor, table.getDataSource(), table.getCatalog().getName(), table.getSchema().getName(), trigger.getName()); } @Nullable @Override public DBCQueryTransformer createQueryTransformer(@NotNull DBCQueryTransformType type) { if (type == DBCQueryTransformType.RESULT_SET_LIMIT) { //return new QueryTransformerTop(); } return null; } private String extractSource(DBRProgressMonitor monitor, GenericDataSource dataSource, String catalog, String schema, String name) throws DBException { ServerType serverType = getServerType(); String systemSchema = getSystemSchema(); catalog = DBUtils.getQuotedIdentifier(dataSource, catalog); try (JDBCSession session = DBUtils.openMetaSession(monitor, dataSource, "Read source code")) { String mdQuery = serverType == ServerType.SQL_SERVER ? catalog + "." + systemSchema + ".sp_helptext '" + DBUtils.getQuotedIdentifier(dataSource, schema) + "." + DBUtils.getQuotedIdentifier(dataSource, name) + "'" : "SELECT sc.text\n" + "FROM " + catalog + "." + systemSchema + ".sysobjects so\n" + "INNER JOIN " + catalog + "." + systemSchema + ".syscomments sc on sc.id = so.id\n" + "WHERE user_name(so.uid)=? AND so.name=?"; try (JDBCPreparedStatement dbStat = session.prepareStatement(mdQuery)) { if (serverType == ServerType.SYBASE) { dbStat.setString(1, schema); dbStat.setString(2, name); } try (JDBCResultSet dbResult = dbStat.executeQuery()) { StringBuilder sql = new StringBuilder(); while (dbResult.nextRow()) { sql.append(dbResult.getString(1)); } return sql.toString(); } } } catch (SQLException e) { throw new DBException(e, dataSource); } } public ServerType getServerType() { return sqlServer ? ServerType.SQL_SERVER : ServerType.SYBASE; } @Override public SQLServerIndex createIndexImpl(GenericTable table, boolean nonUnique, String qualifier, long cardinality, String indexName, DBSIndexType indexType, boolean persisted) { return new SQLServerIndex(table, nonUnique, qualifier, cardinality, indexName, indexType, persisted); } @Override public String getAutoIncrementClause(GenericTableColumn column) { return "IDENTITY(1,1)"; } @Override public boolean useCatalogInObjectNames() { return false; } @Override public List<GenericSchema> loadSchemas(JDBCSession session, GenericDataSource dataSource, GenericCatalog catalog) throws DBException { if (catalog == null) { // Schemas MUST be in catalog return null; } boolean showAllSchemas = ((SQLServerDataSource) dataSource).isShowAllSchemas(); final DBSObjectFilter schemaFilters = dataSource.getContainer().getObjectFilter(GenericSchema.class, catalog, false); String sysSchema = DBUtils.getQuotedIdentifier(catalog) + "." + getSystemSchema(); String sql = showAllSchemas ? "SELECT name FROM " + sysSchema + ".sysusers ORDER BY name" : "SELECT DISTINCT u.name\n" + "FROM " + sysSchema + ".sysusers u, " + sysSchema + ".sysobjects o\n" + "WHERE u.uid=o.uid\n" + "ORDER BY 1"; try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) { List<GenericSchema> result = new ArrayList<>(); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String name = JDBCUtils.safeGetString(dbResult, 1); if (name == null) { continue; } name = name.trim(); if (schemaFilters != null && !schemaFilters.matches(name)) { // Doesn't match filter continue; } SQLServerSchema schema = createSchemaImpl( dataSource, catalog, name); result.add(schema); } } return result; } catch (SQLException e) { throw new DBException(e, dataSource); } } @Override public boolean supportsSequences(GenericDataSource dataSource) { return getServerType() == ServerType.SQL_SERVER; } @Override public List<GenericSequence> loadSequences(DBRProgressMonitor monitor, GenericStructContainer container) throws DBException { try (JDBCSession session = DBUtils.openMetaSession(monitor, container.getDataSource(), "Read system sequences")) { try (JDBCPreparedStatement dbStat = session.prepareStatement( "SELECT * FROM " + DBUtils.getQuotedIdentifier(container.getCatalog()) + "." + getSystemSchema() + ".sequences WHERE schema_name(schema_id)=?")) { dbStat.setString(1, container.getSchema().getName()); List<GenericSequence> result = new ArrayList<>(); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { String name = JDBCUtils.safeGetString(dbResult, "name"); if (name == null) { continue; } name = name.trim(); GenericSequence sequence = new GenericSequence( container, name, null, JDBCUtils.safeGetLong(dbResult, "current_value"), JDBCUtils.safeGetLong(dbResult, "minimum_value"), JDBCUtils.safeGetLong(dbResult, "maximum_value"), JDBCUtils.safeGetLong(dbResult, "increment") ); result.add(sequence); } } return result; } } catch (SQLException e) { throw new DBException(e, container.getDataSource()); } } @Override public SQLServerTable createTableImpl(GenericStructContainer container, String tableName, String tableType, JDBCResultSet dbResult) { return new SQLServerTable(container, tableName, tableType, dbResult); } @Override public boolean isSystemTable(GenericTable table) { return getSystemSchema().equals(table.getSchema().getName()) && table.getName().startsWith("sys"); } }
#2750 SQL Server: schema list read fix Former-commit-id: 5c40cf9ab6c64d36ff9ce639f9dba3fccfaea04f
plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerMetaModel.java
#2750 SQL Server: schema list read fix
<ide><path>lugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerMetaModel.java <ide> final DBSObjectFilter schemaFilters = dataSource.getContainer().getObjectFilter(GenericSchema.class, catalog, false); <ide> <ide> String sysSchema = DBUtils.getQuotedIdentifier(catalog) + "." + getSystemSchema(); <del> String sql = <del> showAllSchemas ? <del> "SELECT name FROM " + sysSchema + ".sysusers ORDER BY name" <del> : <del> "SELECT DISTINCT u.name\n" + <del> "FROM " + sysSchema + ".sysusers u, " + sysSchema + ".sysobjects o\n" + <del> "WHERE u.uid=o.uid\n" + <del> "ORDER BY 1"; <add> String sql; <add> if (showAllSchemas) { <add> if (getServerType() == ServerType.SQL_SERVER && dataSource.isServerVersionAtLeast(9 ,0)) { <add> sql = "SELECT name FROM " + DBUtils.getQuotedIdentifier(catalog) + ".sys.schemas"; <add> } else { <add> sql = "SELECT name FROM " + DBUtils.getQuotedIdentifier(catalog) + ".dbo.sysusers"; <add> } <add> } else { <add> if (getServerType() == ServerType.SQL_SERVER) { <add> sql = "SELECT DISTINCT s.name\n" + <add> "FROM " + sysSchema + ".schemas s, " + sysSchema + ".sysobjects o\n" + <add> "WHERE s.schema_id=o.uid\n" + <add> "ORDER BY 1"; <add> } else { <add> sql = "SELECT DISTINCT u.name\n" + <add> "FROM " + sysSchema + ".sysusers u, " + sysSchema + ".sysobjects o\n" + <add> "WHERE u.uid=o.uid\n" + <add> "ORDER BY 1"; <add> } <add> } <ide> <ide> try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) { <ide> List<GenericSchema> result = new ArrayList<>();
Java
apache-2.0
1766b2b375be60266ada3bbb669c2683e0b3624e
0
semonte/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,signed/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,ibinti/intellij-community,kool79/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,clumsy/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,izonder/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,jagguli/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,clumsy/intellij-community,kool79/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,semonte/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,signed/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,FHannes/intellij-community,allotria/intellij-community,fnouama/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,kool79/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,signed/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,slisson/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,wreckJ/intellij-community,samthor/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,kool79/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,clumsy/intellij-community,da1z/intellij-community,kool79/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,izonder/intellij-community,signed/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,amith01994/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,samthor/intellij-community,ahb0327/intellij-community,signed/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,da1z/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,allotria/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,fnouama/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,izonder/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,signed/intellij-community,amith01994/intellij-community,izonder/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,kool79/intellij-community,wreckJ/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,da1z/intellij-community,xfournet/intellij-community,kool79/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,allotria/intellij-community,vladmm/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,izonder/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,xfournet/intellij-community,izonder/intellij-community,jagguli/intellij-community,fnouama/intellij-community,allotria/intellij-community,blademainer/intellij-community,xfournet/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,blademainer/intellij-community,ibinti/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,semonte/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,kool79/intellij-community,amith01994/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,slisson/intellij-community,da1z/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,samthor/intellij-community,ibinti/intellij-community,samthor/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,semonte/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,fitermay/intellij-community,asedunov/intellij-community,vladmm/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,fnouama/intellij-community,slisson/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,apixandru/intellij-community,izonder/intellij-community,slisson/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,vladmm/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,semonte/intellij-community,fitermay/intellij-community,slisson/intellij-community,jagguli/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,signed/intellij-community,fnouama/intellij-community,apixandru/intellij-community,fitermay/intellij-community,vladmm/intellij-community,blademainer/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,retomerz/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,apixandru/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vladmm/intellij-community,izonder/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,hurricup/intellij-community,samthor/intellij-community,izonder/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,FHannes/intellij-community,da1z/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,jagguli/intellij-community,amith01994/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,allotria/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,allotria/intellij-community,fnouama/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.io.zip; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.lang.JarMemoryLoader; import java.io.File; import java.io.IOException; import java.util.*; /** * @author anna * @since 23-Apr-2009 */ @SuppressWarnings("CallToPrintStackTrace") public class ReorderJarsMain { private ReorderJarsMain() { } public static void main(String[] args) { try { final String orderTxtPath = args[0]; final String jarsPath = args[1]; final String destinationPath = args[2]; final String libPath = args.length > 3 ? args[3] : null; final Map<String, List<String>> toReorder = getOrder(new File(orderTxtPath)); final Set<String> ignoredJars = libPath == null ? Collections.<String>emptySet() : loadIgnoredJars(libPath); for (String jarUrl : toReorder.keySet()) { if (ignoredJars.contains(StringUtil.trimStart(jarUrl, "/lib/"))) continue; if (jarUrl.startsWith("/lib/ant")) continue; final File jarFile = new File(jarsPath, jarUrl); if (!jarFile.isFile()) continue; final JBZipFile zipFile = new JBZipFile(jarFile); final List<JBZipEntry> entries = zipFile.getEntries(); final List<String> orderedEntries = toReorder.get(jarUrl); assert orderedEntries.size() <= Short.MAX_VALUE : jarUrl; Collections.sort(entries, new Comparator<JBZipEntry>() { @Override public int compare(JBZipEntry o1, JBZipEntry o2) { if ("META-INF/plugin.xml".equals(o2.getName())) return Integer.MAX_VALUE; if ("META-INF/plugin.xml".equals(o1.getName())) return -Integer.MAX_VALUE; if (orderedEntries.contains(o1.getName())) { return orderedEntries.contains(o2.getName()) ? orderedEntries.indexOf(o1.getName()) - orderedEntries.indexOf(o2.getName()) : -1; } else { return orderedEntries.contains(o2.getName()) ? 1 : 0; } } }); final File tempJarFile = FileUtil.createTempFile("__reorder__", "__reorder__", true); final JBZipFile file = new JBZipFile(tempJarFile); final JBZipEntry sizeEntry = file.getOrCreateEntry(JarMemoryLoader.SIZE_ENTRY); sizeEntry.setData(ZipShort.getBytes(orderedEntries.size())); for (JBZipEntry entry : entries) { final JBZipEntry zipEntry = file.getOrCreateEntry(entry.getName()); zipEntry.setData(entry.getData()); } file.close(); final File resultJarFile = new File(destinationPath, jarUrl); final File resultDir = resultJarFile.getParentFile(); if (!resultDir.isDirectory() && !resultDir.mkdirs()) { throw new IOException("Cannot create: " + resultDir); } try { FileUtil.rename(tempJarFile, resultJarFile); } catch (Exception e) { FileUtil.delete(resultJarFile); throw e; } FileUtil.delete(tempJarFile); } } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } private static Set<String> loadIgnoredJars(String libPath) throws IOException { final File ignoredJarsFile = new File(libPath, "required_for_dist.txt"); final Set<String> ignoredJars = new HashSet<String>(); ContainerUtil.addAll(ignoredJars, FileUtil.loadFile(ignoredJarsFile).split("\r\n")); return ignoredJars; } private static Map<String, List<String>> getOrder(final File loadingFile) throws IOException { final Map<String, List<String>> entriesOrder = new HashMap<String, List<String>>(); final String[] lines = FileUtil.loadFile(loadingFile).split("\n"); for (String line : lines) { line = line.trim(); final int i = line.indexOf(":"); if (i != -1) { final String entry = line.substring(0, i); final String jarUrl = line.substring(i + 1); List<String> entries = entriesOrder.get(jarUrl); if (entries == null) { entries = new ArrayList<String>(); entriesOrder.put(jarUrl, entries); } entries.add(entry); } } return entriesOrder; } }
platform/util/src/com/intellij/util/io/zip/ReorderJarsMain.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.io.zip; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.lang.JarMemoryLoader; import java.io.File; import java.io.IOException; import java.util.*; /** * @author anna * @since 23-Apr-2009 */ @SuppressWarnings("CallToPrintStackTrace") public class ReorderJarsMain { private ReorderJarsMain() { } public static void main(String[] args) { try { final String orderTxtPath = args[0]; final String jarsPath = args[1]; final String destinationPath = args[2]; final String libPath = args.length > 3 ? args[3] : null; final Map<String, List<String>> toReorder = getOrder(new File(orderTxtPath)); final Set<String> ignoredJars = libPath == null ? Collections.<String>emptySet() : loadIgnoredJars(libPath); for (String jarUrl : toReorder.keySet()) { if (ignoredJars.contains(StringUtil.trimStart(jarUrl, "/lib/"))) continue; if (jarUrl.startsWith("/lib/ant")) continue; final File jarFile = new File(jarsPath, jarUrl); if (!jarFile.isFile()) continue; final JBZipFile zipFile = new JBZipFile(jarFile); final List<JBZipEntry> entries = zipFile.getEntries(); final List<String> orderedEntries = toReorder.get(jarUrl); assert orderedEntries.size() <= Short.MAX_VALUE : jarUrl; Collections.sort(entries, new Comparator<JBZipEntry>() { @Override public int compare(JBZipEntry o1, JBZipEntry o2) { if ("META-INF/plugin.xml".equals(o2.getName())) return Integer.MAX_VALUE; if ("META-INF/plugin.xml".equals(o1.getName())) return -Integer.MAX_VALUE; if (orderedEntries.contains(o1.getName())) { return orderedEntries.contains(o2.getName()) ? orderedEntries.indexOf(o1.getName()) - orderedEntries.indexOf(o2.getName()) : -1; } else { return orderedEntries.contains(o2.getName()) ? 1 : 0; } } }); final File tempJarFile = FileUtil.createTempFile("__reorder__", "__reorder__"); final JBZipFile file = new JBZipFile(tempJarFile); final JBZipEntry sizeEntry = file.getOrCreateEntry(JarMemoryLoader.SIZE_ENTRY); sizeEntry.setData(ZipShort.getBytes(orderedEntries.size())); for (JBZipEntry entry : entries) { final JBZipEntry zipEntry = file.getOrCreateEntry(entry.getName()); zipEntry.setData(entry.getData()); } file.close(); final File resultJarFile = new File(destinationPath, jarUrl); final File resultDir = resultJarFile.getParentFile(); if (!resultDir.isDirectory() && !resultDir.mkdirs()) { throw new IOException("Cannot create: " + resultDir); } try { FileUtil.rename(tempJarFile, resultJarFile); } catch (Exception e) { FileUtil.delete(resultJarFile); throw e; } FileUtil.delete(tempJarFile); } } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } private static Set<String> loadIgnoredJars(String libPath) throws IOException { final File ignoredJarsFile = new File(libPath, "required_for_dist.txt"); final Set<String> ignoredJars = new HashSet<String>(); ContainerUtil.addAll(ignoredJars, FileUtil.loadFile(ignoredJarsFile).split("\r\n")); return ignoredJars; } private static Map<String, List<String>> getOrder(final File loadingFile) throws IOException { final Map<String, List<String>> entriesOrder = new HashMap<String, List<String>>(); final String[] lines = FileUtil.loadFile(loadingFile).split("\n"); for (String line : lines) { line = line.trim(); final int i = line.indexOf(":"); if (i != -1) { final String entry = line.substring(0, i); final String jarUrl = line.substring(i + 1); List<String> entries = entriesOrder.get(jarUrl); if (entries == null) { entries = new ArrayList<String>(); entriesOrder.put(jarUrl, entries); } entries.add(entry); } } return entriesOrder; } }
delete temp files in ReorderJars no matter what
platform/util/src/com/intellij/util/io/zip/ReorderJarsMain.java
delete temp files in ReorderJars no matter what
<ide><path>latform/util/src/com/intellij/util/io/zip/ReorderJarsMain.java <ide> /* <del> * Copyright 2000-2013 JetBrains s.r.o. <add> * Copyright 2000-2015 JetBrains s.r.o. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> } <ide> }); <ide> <del> final File tempJarFile = FileUtil.createTempFile("__reorder__", "__reorder__"); <add> final File tempJarFile = FileUtil.createTempFile("__reorder__", "__reorder__", true); <ide> final JBZipFile file = new JBZipFile(tempJarFile); <ide> <ide> final JBZipEntry sizeEntry = file.getOrCreateEntry(JarMemoryLoader.SIZE_ENTRY);
Java
apache-2.0
b91bccb5ec09c55fc9a75114be7f26ff9a8a3e56
0
trombonehero/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights
/* * Copyright 2011 Jonathan Anderson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.footlights.ui.web; import static me.footlights.core.Log.log; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** A request from the client, broken into path, query and fragment. */ public class Request { /** Identify the "/prefix/of/the/path/to/foo.js". */ public String prefix() { int slash = path.indexOf("/", 1); if (slash == -1) return ""; else return path.substring(1, slash); } /** * Strip the path's prefix. * * e.g. "/static/path/to/foo.js" becomes "path/to/foo.js" * @return */ public Request shift() { if (path.isEmpty()) return this; int slash = path.indexOf("/", 1); if (slash == -1) return this; String stripped = path.substring(slash); return new Request(stripped, query, fragment); } /** Construct from an HTTP request string (no body). */ Request(String rawRequest) throws InvalidRequestException { if(!rawRequest.startsWith("GET ")) throw new InvalidRequestException(rawRequest, "does not begin with \"GET \""); if(!rawRequest.matches(".* HTTP/1.[01]$")) throw new InvalidRequestException(rawRequest, "does not end with \" HTTP/1.[01]\""); rawRequest = rawRequest .replaceFirst("^GET ", "") .replaceFirst(" HTTP/1.1", ""); log("Raw request: " + rawRequest); // Parse the fragment String[] tmp = rawRequest.split("#"); if (tmp.length > 1) fragment = tmp[1]; else fragment = null; // Parse the query, if it exists query = new LinkedHashMap<String, String>(); tmp = tmp[0].split("\\?"); if (tmp.length > 1) { for (String pair : tmp[1].split("&")) { String[] keyValue = pair.split("="); String value = (keyValue.length > 1) ? keyValue[1] : null; query.put(keyValue[0], value); } } path = tmp[0]; } private Request(String path, Map<String, String> query, String fragment) { this.path = path; this.query = query; this.fragment = fragment; } /** The path (everything before '&'). */ public String path() { return path; } /** The query (foo=x, bar=y, etc., with no duplicate keys). Never null. */ public Map<String, String> query() { return Collections.unmodifiableMap(query); } /** Everything after the '#'. */ public String fragment() { return fragment; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Request { "); sb.append(path); sb.append("}"); return sb.toString(); } private final String path; private final Map<String, String> query; private final String fragment; }
Client/UI/Web/src/main/java/me/footlights/ui/web/Request.java
/* * Copyright 2011 Jonathan Anderson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.footlights.ui.web; import static me.footlights.core.Log.log; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** A request from the client, broken into path, query and fragment. */ public class Request { /** Identify the "/prefix/of/the/path/to/foo.js". */ public String prefix() { int slash = path.indexOf("/", 1); if (slash == -1) return ""; else return path.substring(1, slash); } /** * Strip the path's prefix. * * e.g. "/static/path/to/foo.js" becomes "path/to/foo.js" * @return */ public Request shift() { String stripped = path.substring(path.indexOf("/", 1)); return new Request(stripped, query, fragment); } /** Construct from an HTTP request string (no body). */ Request(String rawRequest) throws InvalidRequestException { if(!rawRequest.startsWith("GET ")) throw new InvalidRequestException(rawRequest, "does not begin with \"GET \""); if(!rawRequest.matches(".* HTTP/1.[01]$")) throw new InvalidRequestException(rawRequest, "does not end with \" HTTP/1.[01]\""); rawRequest = rawRequest .replaceFirst("^GET ", "") .replaceFirst(" HTTP/1.1", ""); log("Raw request: " + rawRequest); // Parse the fragment String[] tmp = rawRequest.split("#"); if (tmp.length > 1) fragment = tmp[1]; else fragment = null; // Parse the query, if it exists query = new LinkedHashMap<String, String>(); tmp = tmp[0].split("\\?"); if (tmp.length > 1) { for (String pair : tmp[1].split("&")) { String[] keyValue = pair.split("="); String value = (keyValue.length > 1) ? keyValue[1] : null; query.put(keyValue[0], value); } } path = tmp[0]; } private Request(String path, Map<String, String> query, String fragment) { this.path = path; this.query = query; this.fragment = fragment; } /** The path (everything before '&'). */ public String path() { return path; } /** The query (foo=x, bar=y, etc., with no duplicate keys). Never null. */ public Map<String, String> query() { return Collections.unmodifiableMap(query); } /** Everything after the '#'. */ public String fragment() { return fragment; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Request { "); sb.append(path); sb.append("}"); return sb.toString(); } private final String path; private final Map<String, String> query; private final String fragment; }
Fix Request.shift().
Client/UI/Web/src/main/java/me/footlights/ui/web/Request.java
Fix Request.shift().
<ide><path>lient/UI/Web/src/main/java/me/footlights/ui/web/Request.java <ide> */ <ide> public Request shift() <ide> { <del> String stripped = path.substring(path.indexOf("/", 1)); <add> if (path.isEmpty()) return this; <add> <add> int slash = path.indexOf("/", 1); <add> if (slash == -1) return this; <add> <add> String stripped = path.substring(slash); <ide> return new Request(stripped, query, fragment); <ide> } <ide>
JavaScript
bsd-2-clause
5e2431266d715203cb5c86a412e1e41c41647b96
0
sitna/api-sitna,sitna/api-sitna
var SITNA = window.SITNA || {}; var TC = window.TC || {}; SITNA.syncLoadJS = function (url) { var req = new XMLHttpRequest(); req.open("GET", url, false); // 'false': synchronous. req.send(null); var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.type = "text/javascript"; script.text = req.responseText; head.appendChild(script); }; (function () { if (!window.TC || !window.TC.Cfg) { var src; var script; if (document.currentScript) { script = document.currentScript; } else { var scripts = document.getElementsByTagName('script'); script = scripts[scripts.length - 1]; } var src = script.getAttribute('src'); TC.apiLocation = src.substr(0, src.lastIndexOf('/') + 1); SITNA.syncLoadJS(TC.apiLocation + 'tcmap.js'); } })(); /** * <p>Objeto principal de la API, instancia un mapa dentro de un elemento del DOM. Nótese que el constructor es asíncrono, por tanto cualquier código que haga uso de este objeto debería * estar dentro de una función de callback pasada como parámetro al método {{#crossLink "SITNA.Map/loaded:method"}}{{/crossLink}}.</p> * <p>Puede consultar también online el <a href="../../examples/Map.1.html">ejemplo 1</a>, el <a href="../../examples/Map.2.html">ejemplo 2</a> y el <a href="../../examples/Map.3.html">ejemplo 3</a>.</p> * @class SITNA.Map * @constructor * @async * @param {HTMLElement|string} div Elemento del DOM en el que crear el mapa o valor de atributo id de dicho elemento. * @param {object} [options] Objeto de opciones de configuración del mapa. Sus propiedades sobreescriben el objeto de configuración global {{#crossLink "SITNA.Cfg"}}{{/crossLink}}. * @param {string} [options.crs="EPSG:25830"] Código EPSG del sistema de referencia espacial del mapa. * @param {array} [options.initialExtent] Extensión inicial del mapa definida por x mínima, y mínima, x máxima, y máxima. * Esta opción es obligatoria si el sistema de referencia espacial del mapa es distinto del sistema por defecto (ver SITNA.Cfg.{{#crossLink "SITNA.Cfg/crs:property"}}{{/crossLink}}). * Para más información consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/initialExtent:property"}}{{/crossLink}}. * @param {array} [options.maxExtent] Extensión máxima del mapa definida por x mínima, y mínima, x máxima, y máxima. Para más información consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/maxExtent:property"}}{{/crossLink}}. * @param {string} [options.layout] URL de una carpeta de maquetación. Consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones. * @param {array} [options.baseLayers] Lista de identificadores de capa o instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}} para incluir dichas capas como mapas de fondo. * @param {array} [options.workLayers] Lista de identificadores de capa o instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}} para incluir dichas capas como contenido del mapa. * @param {string|number} [options.defaultBaseLayer] Identificador o índice en <code>baseLayers</code> de la capa base por defecto. * @param {SITNA.cfg.MapControlOptions} [options.controls] Opciones de controles de mapa. * @param {SITNA.cfg.StyleOptions} [options.styles] Opciones de estilo de entidades geográficas. * @param {boolean} [options.mouseWheelZoom] La rueda del ratón se puede utilizar para hacer zoom en el mapa. * @param {string} [options.proxy] URL del proxy utilizado para peticiones a dominios remotos (ver SITNA.Cfg.{{#crossLink "SITNA.Cfg/proxy:property"}}{{/crossLink}}). * @example * <div id="mapa"/> * <script> * // Crear un mapa con las opciones por defecto. * var map = new SITNA.Map("mapa"); * </script> * @example * <div id="mapa"/> * <script> * // Crear un mapa en el sistema de referencia WGS 84 con el de mapa de fondo. * var map = new SITNA.Map("mapa", { * crs: "EPSG:4326", * initialExtent: [ // Coordenadas en grados decimales, porque el sistema de referencia espacial es WGS 84. * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * maxExtent: [ * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * baseLayers: [ * SITNA.Consts.layer.IDENA_DYNBASEMAP * ], * defaultBaseLayer: SITNA.Consts.layer.IDENA_DYNBASEMAP, * // Establecemos el mapa de situación con una capa compatible con WGS 84 * controls: { * overviewMap: { * layer: SITNA.Consts.layer.IDENA_DYNBASEMAP * } * } * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear un mapa que tenga como contenido las capas de toponimia y mallas cartográficas del WMS de IDENA. * var map = new SITNA.Map("mapa", { * workLayers: [ * { * id: "topo_mallas", * title: "Toponimia y mallas cartográficas", * type: SITNA.Consts.layerType.WMS, * url: "http://idena.navarra.es/ogc/wms", * layerNames: "IDENA:toponimia,IDENA:mallas" * } * ] * }); * </script> */ /** * Búsqueda actual de consulta de entidad geográfica aplicado al mapa. * property search * type SITNA.Search|null */ SITNA.Map = function (div, options) { var map = this; var tcMap = new TC.Map(div, options); /** * <p>Añade una capa al mapa. Si se le pasa una instancia de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}} como parámetro <code>layer</code> y tiene definida * la propiedad SITNA.cfg.LayerOptions.{{#crossLink "SITNA.cfg.LayerOptions/url:property"}}{{/crossLink}}, establece por defecto el tipo de capa a * {{#crossLink "SITNA.consts.LayerType/KML:property"}}{{/crossLink}} si la URL acaba en ".kml". * El tipo de la capa no puede ser {{#crossLink "SITNA.consts.LayerType/WFS:property"}}{{/crossLink}}.</p> * <p>Puede consultar también online el <a href="../../examples/Map.addLayer.1.html">ejemplo 1</a> y el <a href="../../examples/Map.addLayer.2.html">ejemplo 2</a>.</p> * * @method addLayer * @async * @param {string|SITNA.cfg.LayerOptions} layer Identificador de capa u objeto de opciones de capa. * @param {function} [callback] Función a la que se llama tras ser añadida la capa. * @example * <div id="mapa"></div> * <script> * // Crear un mapa con las opciones por defecto. * var map = new SITNA.Map("mapa"); * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir al mapa la capa de cartografía topográfica de IDENA * map.addLayer(SITNA.Consts.layer.IDENA_CARTO); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear un mapa con las opciones por defecto. * var map = new SITNA.Map("mapa"); * * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir al mapa un documento KML * map.addLayer({ * id: "capa_kml", * title: "Museos en Navarra", * type: SITNA.Consts.layerType.KML, * url: "data/MUSEOSNAVARRA.kml" * }); * }); * </script> */ map.addLayer = function (layer, callback) { tcMap.addLayer(layer, callback); }; /** * <p>Hace visible una capa como mapa de fondo. Esta capa debe existir previamente en la lista de mapas de fondo del mapa.</p> * <p>Puede consultar también online el <a href="../../examples/Map.setBaseLayer.1.html">ejemplo 1</a> y el <a href="../../examples/Map.setBaseLayer.2.html">ejemplo 2</a>.</p> * @method setBaseLayer * @async * @param {string|SITNA.cfg.LayerOptions} layer Identificador de capa u objeto de opciones de capa. * @param {function} [callback] Función al que se llama tras ser establecida la capa como mapa de fondo. * @example * <div id="mapa"></div> * <script> * // Crear mapa con opciones por defecto. Esto incluye la capa del catastro de Navarra entre los mapas de fondo. * var map = new SITNA.Map("mapa"); * // Cuando esté todo cargado establecer como mapa de fondo visible el catastro de Navarra. * map.loaded(function () { * map.setBaseLayer(SITNA.Consts.layer.IDENA_CADASTER); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear mapa con opciones por defecto. * var map = new SITNA.Map("mapa"); * // Cuando el mapa esté cargado, añadir la ortofoto de 1956/1957 como mapa de fondo y establecerla como mapa de fondo visible. * map.loaded(function () { * map.addLayer({ * id: "orto_56_57", * title: "Ortofoto de 1956/1957", * url: "http://idena.navarra.es/ogc/wms", * layerNames: "ortofoto_10000_1957", * isBase: true * }, function () { * map.setBaseLayer("orto_56_57"); * }); * }); * </script> */ map.setBaseLayer = function (layer, callback) { tcMap.setBaseLayer(layer, callback); }; /** * Añade un marcador (un punto asociado a un icono) al mapa. * <p>Puede consultar también online el <a href="../../examples/Map.addMarker.1.html">ejemplo 1</a>, el <a href="../../examples/Map.addMarker.2.html">ejemplo 2</a>, * el <a href="../../examples/Map.addMarker.3.html">ejemplo 3</a> y el <a href="../../examples/Map.addMarker.4.html">ejemplo 4</a>.</p> * @method addMarker * @async * @param {array} coords Coordenadas x e y del punto en las unidades del sistema de referencia del mapa. * @param {object} [options] Objeto de opciones de marcador. * @param {string} [options.group] <p>Nombre de grupo en el que incluir el marcador. Estos grupos se muestran en la tabla de contenidos y en la leyenda.</p> * <p>Todos los marcadores pertenecientes al mismo grupo tienen el mismo icono. Los iconos se asignan automáticamente, rotando por la lista disponible en * SITNA.cfg.MarkerStyleOptions.{{#crossLink "SITNA.cfg.MarkerStyleOptions/classes:property"}}{{/crossLink}}.</p> * @param {string} [options.cssClass] Nombre de clase CSS. El marcador adoptará como icono el valor del atributo <code>background-image</code> de dicha clase. * @param {string} [options.url] URL de archivo de imagen que será el icono del marcador. * @param {number} [options.width] Anchura en píxeles del icono del marcador. * @param {number} [options.height] Altura en píxeles del icono del marcador. * @param {array} [options.anchor] Coordenadas proporcionales (entre 0 y 1) del punto de anclaje del icono al punto del mapa. La coordenada [0, 0] es la esquina superior izquierda del icono. * @param {object} [options.data] Objeto de datos en pares clave/valor para mostrar cuando se pulsa sobre el marcador. Si un valor es una URL, se mostrará como un enlace. * @param {boolean} [options.showPopup] Al añadirse el marcador al mapa se muestra con el bocadillo de información asociada visible por defecto. * @param {string} [options.layer] Identificador de capa de tipo SITNA.consts.LayerType.{{#crossLink "SITNA.consts.LayerType/VECTOR:property"}}{{/crossLink}} en la que se añadirá el marcador. Si no se especifica se creará una capa específica para marcadores. * @example * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir un marcador. * map.addMarker([610749, 4741648]); * // Centrar el mapa en el marcador. * map.zoomToMarkers(); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir marcadores al grupo "Marcadores colgantes" cuyo icono se ancle al punto en el centro hacia abajo. Establecer un icono adecuado. * var markerOptions = { * group: "Marcadores colgantes", * url: "data/colgante.png", * anchor: [0.5, 0] * }; * map.addMarker([610887, 4741244], markerOptions); * map.addMarker([615364, 4657556], markerOptions); * // Centrar el mapa en los marcadores. * map.zoomToMarkers(); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear un mapa con una capa vectorial, centrado en la Ciudadela de Pamplona. * var map = new SITNA.Map("mapa", { * initialExtent: [ * 609627, * 4740225, * 611191, * 4741395 * ], * workLayers: [{ * id: "markers", * title: "Marcadores geográficos", * type: SITNA.Consts.layerType.VECTOR * }] * }); * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir un marcador en la capa "markers", asignarle un grupo para que salga en tabla de contenidos y leyenda. * map.addMarker([610431, 4740837], { * layer: "markers", * group: "Ciudadela" * }); * }); * </script> * @example * <style type="text/css"> * .kiosko { * background-image: url("data/icono-kiosko.png"); * } * </style> * <div id="mapa"></div> * <script> * // SITNA.Cfg.baseLayers[0] (capa por defecto) no es compatible con WGS 84, lo cambiamos por SITNA.Consts.layer.IDENA_DYNBASEMAP. * SITNA.Cfg.baseLayers[0] = SITNA.Consts.layer.IDENA_DYNBASEMAP; * SITNA.Cfg.defaultBaseLayer = SITNA.Consts.layer.IDENA_DYNBASEMAP; * // Añadir información emergente al mapa. * SITNA.Cfg.controls.popup = true; * * // Crear un mapa en el sistema de referencia WGS 84. * var map = new SITNA.Map("mapa", { * crs: "EPSG:4326", * initialExtent: [ // Coordenadas en grados decimales, porque el sistema de referencia espacial es WGS 84. * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * maxExtent: [ * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * // Establecemos el mapa de situación con una capa compatible con WGS 84 * controls: { * overviewMap: { * layer: SITNA.Consts.layer.IDENA_DYNBASEMAP * } * } * }); * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir un marcador con un icono de 40x40 píxeles definido por la clase CSS kiosko. Asignarle unos datos asociados que se muestren por defecto. * map.addMarker([-1.605691, 42.060453], { // Coordenadas en grados decimales porque el mapa está en WGS 84. * cssClass: "kiosko", * width: 40, * height: 40, * data: { * "Nombre": "Plaza de la Constitución, Tudela", * "Sitio web": "http://www.tudela.es/" * }, * showPopup: true * }); * // Centrar el mapa en el marcador. * map.zoomToMarkers(); * }); * </script> */ map.addMarker = function (coords, options) { tcMap.addMarker(coords, options); }; /** * Centra y escala el mapa a la extensión que ocupan todos sus marcadores. * <p>Puede consultar también el ejemplo <a href="../../examples/Map.zoomToMarkers.html">online</a>.</p> * @method zoomToMarkers * @param {object} [options] Objeto de opciones de zoom. * @param {number} [options.pointBoundsRadius=30] Radio en metros del área alrededor del marcador que se respetará al hacer zoom. * @param {number} [options.extentMargin=0.2] Tamaño del margen que se aplicará a la extensión total de todas los marcadores. * El valor es la relación de crecimiento en ancho y alto entre la extensión resultante y la original. Por ejemplo, 0,2 indica un crecimiento del 20% de la extensión, 10% por cada lado. * @async * @example * <div class="controls"> * <div><button id="addMarkerBtn">Añadir marcador aleatorio</button></div> * <div><input type="number" step="1" id="pbrVal" value="30" /> <label for="pbrVal">pointBoundsRadius</label></div> * <div><input type="number" step="0.1" id="emVal" value="0.2" /> <label for="emVal">extentMargin</label></div> * <div><button id="zoomBtn">Hacer zoom a los marcadores</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * // Añadir un marcador en un punto aleatorio * var addRandomMarker = function () { * var xmin = SITNA.Cfg.initialExtent[0]; * var ymin = SITNA.Cfg.initialExtent[1]; * var width = SITNA.Cfg.initialExtent[2] - SITNA.Cfg.initialExtent[0]; * var height = SITNA.Cfg.initialExtent[3] - SITNA.Cfg.initialExtent[1]; * map.addMarker([xmin + Math.random() * width, ymin + Math.random() * height]); * }; * * // Hacer zoom a los marcadores con las opciones elegidas * var zoomToMarkers = function () { * map.zoomToMarkers({ * pointBoundsRadius: parseInt(document.getElementById("pbrVal").value), * extentMargin: parseFloat(document.getElementById("emVal").value) * }); * }; * * document.getElementById("addMarkerBtn").addEventListener("click", addRandomMarker); * document.getElementById("zoomBtn").addEventListener("click", zoomToMarkers); * </script> */ map.zoomToMarkers = function (options) { tcMap.zoomToMarkers(options); }; /** * Añade una función de callback que se ejecutará cuando el mapa, sus controles y todas sus capas se hayan cargado. * * @method loaded * @async * @param {function} callback Función a la que se llama tras la carga del mapa. * @example * // Notificar cuando se haya cargado el mapa. * map.loaded(function () { * console.log("Código del mapa y de sus controles cargado, cargando datos..."); * }); */ map.loaded = function (callback) { tcMap.loaded(callback); }; // Si existe el control featureInfo lo activamos. tcMap.loaded(function () { tcSearch = new TC.control.Search(); tcSearch.register(tcMap); if (!tcMap.activeControl) { var fi = tcMap.getControlsByClass('TC.control.FeatureInfo')[0]; if (fi) { fi.activate(); } } }); /** * <p>Obtiene los valores (id y label) de las entidades geográficas disponibles en la capa de IDENA que corresponda según el parámetro searchType. * <p>Puede consultar también online el <a href="../../examples/Map.getQueryableData.html">ejemplo 1</a>.</p> * * method getQueryableData * async * param {string|SITNA.consts.MapSearchType} searchType Fuente de datos del cual obtendremos los valores disponibles para buscar posteriormente. * param {function} [callback] Función a la que se llama tras obtener los datos. * example * <div id="mapa"></div> * <script> * // Crear un mapa con las opciones por defecto. * var map = new SITNA.Map("mapa"); * * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Retorna un array de objetos (id, label) con todos los municipios de Navarra * map.getQueryableData(SITNA.Consts.mapSearchType.MUNICIPALITY, function (data) { * $.each(data, function (key, value) { * $('#municipality') // Completamos el combo '#municipality' con los datos recibidos * .append($("<option></option>") * .attr("value", value.id) * .text(value.label)); * }); * }); * * // Retorna un array de objetos (id, label) con todas las mancomunidades de residuos de Navarra * map.getQueryableData(SITNA.Consts.mapSearchType.COMMONWEALTH, function (data) { * $.each(data, function (key, value) { * $('#commonwealth') // Completamos el combo '#community' con los datos recibidos * .append($("<option></option>") * .attr("value", value.id) * .text(value.label)); * }); * }); * }); * </script> */ map.getQueryableData = function (searchType, callback) { var queryable = tcSearch.availableSearchTypes[searchType]; if (queryable.queryableData) { if (callback) callback(queryable.queryableData); } else { var params = { request: 'GetFeature', service: 'WFS', typename: queryable.featurePrefix + ':' + queryable.featureType, version: queryable.version, propertyname: (!(queryable.dataIdProperty instanceof Array) ? [queryable.dataIdProperty] : queryable.dataIdProperty) .concat((!(queryable.outputProperties instanceof Array) ? [queryable.outputProperties] : queryable.outputProperties)).join(','), outputformat: TC.Consts.format.JSON }; var url = queryable.url + '?' + $.param(params); $.ajax({ url: url }).done(function (data) { queryable.queryableData = []; if (data.features) { var features = data.features; for (var i = 0; i < features.length; i++) { var f = features[i]; var data = {}; data.id = []; if (!(queryable.dataIdProperty instanceof Array)) queryable.dataIdProperty = [queryable.dataIdProperty]; for (var ip = 0; ip < queryable.dataIdProperty.length; ip++) { if (f.properties.hasOwnProperty(queryable.dataIdProperty[ip])) { data.id.push(f.properties[queryable.dataIdProperty[ip]]); } } data.id = queryable.idPropertiesIdentifier ? data.id.join(queryable.idPropertiesIdentifier) : data.id.join(''); data.label = []; if (!(queryable.outputProperties instanceof Array)) queryable.outputProperties = [queryable.outputProperties]; for (var lbl = 0; lbl < queryable.outputProperties.length; lbl++) { if (f.properties.hasOwnProperty(queryable.outputProperties[lbl])) { data.label.push(f.properties[queryable.outputProperties[lbl]]); } } var add = (data.label instanceof Array && data.label.join('').trim().length > 0) || (!(data.label instanceof Array) && data.label.trim().length > 0); data.label = queryable.outputFormatLabel ? queryable.outputFormatLabel.tcFormat(data.label) : data.label.join('-'); if (add) queryable.queryableData.push(data); } } queryable.queryableData = queryable.queryableData.sort(function (a, b) { if (queryable.idPropertiesIdentifier ? a.id.indexOf(queryable.idPropertiesIdentifier) == -1 : false) { if (tcSearch.removePunctuation(a.label) < tcSearch.removePunctuation(b.label)) return -1; else if (tcSearch.removePunctuation(a.label) > tcSearch.removePunctuation(b.label)) return 1; else return 0; } else { if (tcSearch.removePunctuation(a.label.split(' ')[0]) < tcSearch.removePunctuation(b.label.split(' ')[0])) return -1; else if (tcSearch.removePunctuation(a.label.split(' ')[0]) > tcSearch.removePunctuation(b.label.split(' ')[0])) return 1; else return 0; } }); queryable.queryableData = queryable.queryableData.filter(function (value, index, arr) { if (index < 1) return true; else return value.id !== arr[index - 1].id && value.label !== arr[index - 1].label; }); if (callback) callback(queryable.queryableData); }); } }; /** * <p>Obtiene los valores (id y label) de los municipios disponibles en la capa de IDENA. * <p>Puede consultar también online el <a href="../../examples/Map.getMunicipalities.html">ejemplo 1</a>.</p> * * @method getMunicipalities * @async * @param {function} [callback] Función a la que se llama tras obtener los datos. * @example * <div class="instructions divSelect"> * <div> * Municipios * <select id="municipality" onchange="applyFilter()"> * <option value="-1">Seleccione...</option> * </select> * </div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * // completamos el desplegable * map.getMunicipalities(function (data) { * $.each(data, function (key, value) { * $('#municipality').append($("<option></option>") * .attr("value", value.id) * .text(value.label)); * }); * }); * }); * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change * function applyFilter() { * var id = $('#municipality').find('option:selected').val(); * if (id == -1) * map.removeSearch(); * else { * map.searchMunicipality(id, function (idQuery) { * if (idQuery == null) * alert('No se han encontrado resultados'); * }); * } * }; * </script> */ map.getMunicipalities = function (callback) { map.getQueryableData(SITNA.Consts.mapSearchType.MUNICIPALITY, callback); }; /** * <p>Obtiene los valores (id y label) de los cascos urbanos disponibles en la capa de IDENA. * <p>Puede consultar también online el <a href="../../examples/Map.getUrbanAreas.html">ejemplo 1</a>.</p> * * @method getUrbanAreas * @async * @param {function} [callback] Función a la que se llama tras obtener los datos. * @example * <div class="instructions divSelect"> * <div> * Cascos urbanos * <select id="urban" onchange="applyFilter()"> * <option value="-1">Seleccione...</option> * </select> * </div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * // completamos el desplegable * map.getUrbanAreas(function (data) { * $.each(data, function (key, value) { * $('#urban').append($("<option></option>") * .attr("value", value.id) * .text(value.label)); * }); * }); * }); * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change * function applyFilter() { * var id = $('#urban').find('option:selected').val(); * if (id == -1) * map.removeSearch(); * else { * map.searchUrbanArea(id, function (idQuery) { * if (idQuery == null) * alert('No se han encontrado resultados'); * }); * } * }; * </script> */ map.getUrbanAreas = function (callback) { map.getQueryableData(SITNA.Consts.mapSearchType.URBAN, callback); }; /** * <p>Obtiene los valores (id y label) de las mancomunidades de residuos disponibles en la capa de IDENA. * <p>Puede consultar también online el <a href="../../examples/Map.getCommonwealths.html">ejemplo 1</a>.</p> * * @method getCommonwealths * @async * @param {function} [callback] Función a la que se llama tras obtener los datos. * @example * <div class="instructions divSelect"> * <div> * Mancomunidades de residuos * <select id="commonwealths" onchange="applyFilter()"> * <option value="-1">Seleccione...</option> * </select> * </div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * // completamos el desplegable * map.getCommonwealths(function (data) { * $.each(data, function (key, value) { * $('#commonwealths').append($("<option></option>") * .attr("value", value.id) * .text(value.label)); * }); * }); * }); * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change * function applyFilter() { * var id = $('#commonwealths').find('option:selected').val(); * if (id == -1) * map.removeSearch(); * else { * map.searchCommonwealth(id, function (idQuery) { * if (idQuery == null) * alert('No se han encontrado resultados'); * }); * } * }; * </script> */ map.getCommonwealths = function (callback) { map.getQueryableData(SITNA.Consts.mapSearchType.COMMONWEALTH, callback); }; /** * <p>Obtiene los valores (id y label) de los concejos disponibles en la capa de IDENA. * <p>Puede consultar también online el <a href="../../examples/Map.getCouncils.html">ejemplo 1</a>.</p> * * @method getCouncils * @async * @param {function} [callback] Función a la que se llama tras obtener los datos. * @example * <div class="instructions divSelect"> * <div> * Concejos * <select id="council" onchange="applyFilter()"> * <option value="-1">Seleccione...</option> * </select> * </div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * // completamos el desplegable * map.getCouncils(function (data) { * $.each(data, function (key, value) { * $('#council').append($("<option></option>") * .attr("value", value.id) * .text(value.label)); * }); * }); * }); * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change * function applyFilter() { * var id = $('#council').find('option:selected').val(); * if (id == -1) * map.removeSearch(); * else { * map.searchCouncil(id, function (idQuery) { * if (idQuery == null) * alert('No se han encontrado resultados'); * }); * } * }; * </script> */ map.getCouncils = function (callback) { map.getQueryableData(SITNA.Consts.mapSearchType.COUNCIL, callback); }; /** * <p>Busca la mancomunidad de residuos y pinta en el mapa la entidad geográfica encontrada que corresponda al identificador indicado. * <p>Puede consultar también online el <a href="../../examples/Map.searchCommonwealth.html">ejemplo 1</a>.</p> * * @method searchCommonwealth * @async * @param {string} id Identificador de la entidad geográfica a pintar. * @param {function} [callback] Función a la que se llama tras aplicar el filtro. * @example * <div class="instructions searchCommonwealth"> * <div><button id="searchPamplonaBtn">Buscar Mancomunidad de la Comarca de Pamplona</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * document.getElementById("searchPamplonaBtn").addEventListener("click", search); * }); * * var search = function () { * map.removeSearch(); * map.searchCommonwealth("8", function (idQuery) { * if (idQuery == null) { * alert("No se ha encontrado la mancomunidad con código 8."); * } * }); * }; * </script> */ map.searchCommonwealth = function (id, callback) { map.searchTyped(SITNA.Consts.mapSearchType.COMMONWEALTH, id, callback); }; /** * <p>Busca el concejo que corresponda con el identificador pasado como parámetro y pinta la entidad geográfica encontrada en el mapa. * <p>Puede consultar también online el <a href="../../examples/Map.searchCouncil.html">ejemplo 1</a>.</p> * * @method searchCouncil * @async * @param {string} id Identificador de la entidad geográfica a pintar. * @param {function} [callback] Función a la que se llama tras aplicar el filtro. * @example * <div class="instructions search"> * <div><button id="searchBtn">Buscar concejo Esquíroz (Galar)</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * document.getElementById("searchBtn").addEventListener("click", search); * }); * * var search = function () { * map.removeSearch(); * map.searchCouncil("109#5", function (idQuery) { * if (idQuery == null) { * alert("No se ha encontrado el concejo con código 109#5."); * } * }); * }; * </script> **/ map.searchCouncil = function (id, callback) { map.searchTyped(SITNA.Consts.mapSearchType.COUNCIL, id, callback); }; /** * <p>Busca el casco urbano que corresponda con el identificador pasado como parámetro y pinta la entidad geográfica encontrada en el mapa. * <p>Puede consultar también online el <a href="../../examples/Map.searchUrbanArea.html">ejemplo 1</a>.</p> * * @method searchUrbanArea * @async * @param {string} id Identificador de la entidad geográfica a pintar. * @param {function} [callback] Función a la que se llama tras aplicar el filtro. * @example * <div class="instructions search"> * <div><button id="searchBtn">Buscar casco urbano de Arbizu</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * document.getElementById("searchBtn").addEventListener("click", search); * }); * var search = function () { * map.removeSearch(); * map.searchUrbanArea("27", function (idQuery) { * if (idQuery == null) { * alert("No se ha encontrado el casco urbano con código 27."); * } * }); * }; * </script> **/ map.searchUrbanArea = function (id, callback) { map.searchTyped(SITNA.Consts.mapSearchType.URBAN, id, callback); }; /** * <p>Busca el municipio que corresponda con el identificador pasado como parámetro y pinta la entidad geográfica encontrada en el mapa. * <p>Puede consultar también online el <a href="../../examples/Map.searchMunicipality.html">ejemplo 1</a>.</p> * * @method searchMunicipality * @async * @param {string} id Identificador de la entidad geográfica a pintar. * @param {function} [callback] Función a la que se llama tras aplicar el filtro. * @example * <div class="instructions search"> * <div><button id="searchBtn">Buscar Arbizu</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * map.loaded(function () { * document.getElementById("searchBtn").addEventListener("click", search); * }); * * var search = function () { * map.removeSearch(); * map.searchCouncil("27", function (idQuery) { * if (idQuery == null) { * alert("No se ha encontrado el municipio con código 27."); * } * }); * }; * </script> **/ map.searchMunicipality = function (id, callback) { map.searchTyped(SITNA.Consts.mapSearchType.MUNICIPALITY, id, callback); }; // Busca en la configuración que corresponda según el parámetro searchType el identificador pasado como parámetro map.searchTyped = function (searchType, id, callback) { var idQuery = TC.getUID(); var query = tcSearch.availableSearchTypes[searchType]; if (id instanceof Array && query.goToIdFormat) id = query.goToIdFormat.tcFormat(id); tcSearch._search.data = tcSearch._search.data || []; tcSearch._search.data.push({ dataLayer: query.featureType, dataRole: searchType, id: id, label: "", text: "" }); map.removeSearch(); if (tcSearch.availableSearchTypes[searchType] && !(tcSearch.allowedSearchTypes[searchType])) { tcSearch.allowedSearchTypes = { }; tcSearch.allowedSearchTypes[searchType] = { }; if (!tcSearch.availableSearchTypes[searchType].hasOwnProperty('goTo')) { tcSearch.allowedSearchTypes[searchType] = { goTo: function () { var styles = function (queryStyles, geomType, property) { return queryStyles[geomType][property]; }; var getProperties = function (id) { var filter = []; if (query.idPropertiesIdentifier) id = id.split(query.idPropertiesIdentifier); if (!(id instanceof Array)) id = [id]; for (var i = 0; i < query.dataIdProperty.length; i++) { filter.push({ name: query.dataIdProperty[i], value: id[i], type: TC.Consts.comparison.EQUAL_TO }); } return filter; }; var layerOptions = { id: idQuery, type: SITNA.Consts.layerType.WFS, url: query.url, version: query.version, geometryName: 'the_geom', featurePrefix: query.featurePrefix, featureType: query.featureType, properties: getProperties(id), outputFormat: TC.Consts.format.JSON, styles: { polygon: { fillColor: styles.bind(self, query.styles[query.featureType], 'polygon', 'fillColor'), fillOpacity: styles.bind(self, query.styles[query.featureType], 'polygon', 'fillOpacity'), }, line: { strokeColor: styles.bind(self, query.styles[query.featureType], 'line', 'strokeColor'), strokeOpacity: styles.bind(self, query.styles[query.featureType], 'line', 'strokeOpacity'), strokeWidth: styles.bind(self, query.styles[query.featureType], 'line', 'strokeWidth') } } }; tcMap.addLayer(layerOptions).then(function (layer) { map.search = { layer: layer, type: searchType }; delete tcSearch.allowedSearchTypes[searchType]; }); } }; } } tcMap.one(TC.Consts.event.SEARCHQUERYEMPTY, function (e) { tcMap.toast(tcSearch.EMPTY_RESULTS_LABEL, { type: TC.Consts.msgType.INFO, duration: 5000 }); if (callback) callback(null); }); tcMap.one(TC.Consts.event.FEATURESADD, function (e) { if (e.layer && e.layer.features && e.layer.features.length > 0) tcMap.zoomToFeatures(e.layer.features); map.search = { layer: e.layer, type: searchType }; if (callback) callback(e.layer.id !== idQuery ? e.layer.id : idQuery); }); tcSearch.goToResult(id); }; /** * <p>Busca y pinta en el mapa la entidad geográfica encontrada correspondiente al identificador establecido. * <p>Puede consultar también online el <a href="../../examples/Map.searchFeature.html">ejemplo 1</a>.</p> * * @method searchFeature * @async * @param {string} layer Capa de IDENA en la cual buscar. * @param {string} field Campo de la capa de IDENA en el cual buscar. * @param {string} id Identificador de la entidad geográfica por el cual filtrar. * @param {function} [callback] Función a la que se llama tras aplicar el filtro. * @example * <div class="instructions query"> * <div><label>Capa</label><input type="text" id="capa" placeholder="Nombre capa de IDENA" /> </div> * <div><label>Campo</label><input type="text" id="campo" placeholder="Nombre campo" /> </div> * <div><label>Valor</label><input type="text" id="valor" placeholder="Valor a encontrar" /> </div> * <div><button id="searchBtn">Buscar</button></div> * <div><button id="removeBtn">Eliminar filtro</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * map.loaded(function () { * document.getElementById("searchBtn").addEventListener("click", search); * document.getElementById("removeBtn").addEventListener("click", remove); * }); * * var search = function () { * var capa = document.getElementById("capa").value; * capa = capa.trim(); * * var campo = document.getElementById("campo").value; * campo = campo.trim(); * * var valor = document.getElementById("valor").value; * valor = valor.trim(); * * map.searchFeature(capa, campo, valor, function (idQuery) { * if (idQuery == null) { * alert("No se han encontrado resultados en la capa: " + capa + " en el campo: " + campo + " el valor: " + valor + "."); * } * }); * }; * * // Limpiar el mapa * var remove = function () { * map.removeSearch(); * }; * </script> */ map.searchFeature = function (layer, field, id, callback) { var idQuery = TC.getUID(); var prefix = tcSearch.featurePrefix; map.removeSearch(); layer = (layer || '').trim(); field = (field || '').trim(); id = (id || '').trim(); if (layer.length == 0 || field.length == 0 || id.length == 0) { tcMap.toast(tcSearch.EMPTY_RESULTS_LABEL, { type: TC.Consts.msgType.INFO, duration: 5000 }); if (callback) callback(null); } else { if (layer.indexOf(':') > -1) { prefix = layer.split(':')[0]; layer = layer.split(':')[1]; } var layerOptions = { id: idQuery, type: SITNA.Consts.layerType.WFS, url: tcSearch.url, version: tcSearch.version, geometryName: 'the_geom', featurePrefix: prefix, featureType: layer, maxFeatures: 1, properties: [{ name: field, value: id, type: TC.Consts.comparison.EQUAL_TO }], outputFormat: TC.Consts.format.JSON }; tcMap.one(TC.Consts.event.FEATURESADD, function (e) { if (e.layer && e.layer.features && e.layer.features.length > 0) tcMap.zoomToFeatures(e.layer.features); }); tcMap.one(TC.Consts.event.LAYERUPDATE, function (e) { if (e.layer && e.layer.features && e.layer.features.length == 0) tcMap.toast(tcSearch.EMPTY_RESULTS_LABEL, { type: TC.Consts.msgType.INFO, duration: 5000 }); if (callback) callback(e.layer && e.layer.features && e.layer.features.length == 0 ? null : idQuery); }); tcMap.addLayer(layerOptions).then(function (layer) { map.search = { layer: layer, type: SITNA.Consts.mapSearchType.GENERIC }; }); } }; /** * <p>Elimina del mapa la entidad geográfica encontrada. * <p>Puede consultar también online el <a href="../../examples/Map.removeSearch.html">ejemplo 1</a>.</p> * * @method removeSearch * @async * @param {function} [callback] Función a la que se llama tras eliminar la entidad geográfica. * @example * <div class="instructions query"> * <div><label>Capa</label><input type="text" id="capa" placeholder="Nombre capa de IDENA" /> </div> * <div><label>Campo</label><input type="text" id="campo" placeholder="Nombre campo" /> </div> * <div><label>Valor</label><input type="text" id="valor" placeholder="Valor a encontrar" /> </div> * <div><button id="searchBtn">Buscar</button></div> * <div><button id="removeBtn">Eliminar filtro</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * map.loaded(function () { * document.getElementById("addFilterBtn").addEventListener("click", addFilter); * document.getElementById("removeFilterBtn").addEventListener("click", removeFilter); * }); * * // Establecer como filtro del mapa el municipio Valle de Egüés * var addFilter = function () { * var capa = document.getElementById("capa").value; * capa = capa.trim(); * * var campo = document.getElementById("campo").value; * campo = campo.trim(); * * var valor = document.getElementById("valor").value; * valor = valor.trim(); * * map.setQuery(capa, campo, valor, function (idQuery) { * if (idQuery == null) { * alert("No se han encontrado resultados en la capa: " + capa + " en el campo: " + campo + " el valor: " + valor + "."); * } * }); * }; * * // Limpiar el mapa del filtro * var remove = function () { * map.removeSearch(); * }; * </script> */ map.removeSearch = function (callback) { if (map.search) { if (!tcSearch.availableSearchTypes[map.search.type] || !tcSearch.availableSearchTypes[map.search.type].hasOwnProperty('goTo')) { tcMap.removeLayer(map.search.layer).then(function () { map.search = null; }); } else { for (var i = 0; i < map.search.layer.features.length; i++) { map.search.layer.removeFeature(map.search.layer.features[i]); } map.search = null; } } if (callback) callback(); }; map.search = null; }; /** * Colección de constantes utilizadas por la API. Se recomienda utilizar las propiedades de esta clase estática para referirse a valores conocidos. * No deberían modificarse las propiedades de esta clase. * @class SITNA.Consts * @static */ SITNA.Consts = TC.Consts; /** * Identificadores de capas útiles de IDENA. * @property layer * @type SITNA.consts.Layer * @final */ /** * Identificadores de tipo de capa. * @property layerType * @type SITNA.consts.LayerType * @final */ /** * Identificadores de tipo de consulta al mapa. * property mapSearchType * type SITNA.consts.MapSearchType * final */ /** * Tipos MIME de utilidad. * @property mimeType * @type SITNA.consts.MimeType * @final */ /** * Colección de identificadores de tipo de capa. * No se deberían modificar las propiedades de esta clase. * @class SITNA.consts.LayerType * @static */ /** * Identificador de capa de tipo WMS. * @property WMS * @type string * @final */ /** * Identificador de capa de tipo WMTS. * @property WMTS * @type string * @final */ /** * Identificador de capa de tipo WFS. * @property WFS * @type string * @final */ /** * Identificador de capa de tipo KML. * @property KML * @type string * @final */ /** * Identificador de capa de tipo vectorial. Este tipo de capa es la que se utiliza para dibujar marcadores. * @property VECTOR * @type string * @final */ /** * Colección de identificadores de capas útiles de IDENA. * No se deberían modificar las propiedades de esta clase. * @class SITNA.consts.Layer * @static */ /** * Identificador de la capa de ortofoto 2014 del WMTS de IDENA. Esta capa solo es compatible con el sistema de referencia EPSG:25830. * @property IDENA_ORTHOPHOTO * @type string * @final */ /** * Identificador de la capa de mapa base del WMTS de IDENA. Esta capa solo es compatible con el sistema de referencia EPSG:25830. * @property IDENA_BASEMAP * @type string * @final */ /** * Identificador de la capa de catastro del WMS de IDENA. * @property IDENA_CADASTER * @type string * @final */ /** * Identificador de la capa de cartografía topográfica del WMS de IDENA. * @property IDENA_CARTO * @type string * @final */ /** * Identificador de la capa de la combinación de ortofoto 2014 y mapa base del WMS de IDENA. * @property IDENA_BASEMAP_ORTHOPHOTO * @type string * @final */ /** * Identificador de la capa de relieve en blanco y negro del WMS de IDENA. * @property IDENA_BW_RELIEF * @type string * @final */ /** * Identificador de la capa de mapa base del WMS de IDENA. * @property IDENA_DYNBASEMAP * @type string * @final */ /** * Identificador de la capa de ortofoto 2012 del WMTS de IDENA. Esta capa solo es compatible con el sistema de referencia EPSG:25830. * @property IDENA_ORTHOPHOTO2012 * @type string * @final */ /** * Identificador de una capa en blanco. * @property BLANK * @type string * @final */ /** * Colección de tipos MIME de utilidad. * No se deberían modificar las propiedades de esta clase. * @class SITNA.consts.MimeType * @static */ /** * Tipo MIME de imagen PNG. * @property PNG * @type string * @final */ /** * Tipo MIME de imagen JPEG. * @property JPEG * @type string * @final */ /* * Colección de tipos de filtros. * No se deberían modificar las propiedades de este objeto. * @class SITNA.consts.MapSearchType * @static */ /* * Identificador de filtro de consulta de tipo municipio. * @property MUNICIPALITY * @type string * @final */ /* * Identificador de filtro de consulta de tipo concejo. * @property COUNCIL * @type string * @final */ /* * Identificador de filtro de consulta de tipo casco urbano. * @property URBAN * @type string * @final */ /* * Identificador de filtro de consulta de tipo mancomunidad. * @property COMMONWEALTH * @type string * @final */ /* * Identificador de filtro de consulta de tipo genérico. * @property GENERIC * @type string * @final */ /** * <p>Configuración general de la API. Cualquier llamada a un método o un constructor de la API sin parámetro de opciones toma las opciones de esta clase. * Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>La clase es estática.</p> * @class SITNA.Cfg * @static */ SITNA.Cfg = TC.Cfg; /** * <p>URL del proxy utilizado para peticiones a dominios remotos.</p> * <p>Debido a restricciones de seguridad implementadas en Javascript, a través de <code>XMLHttpRequest</code> no es posible obtener información de dominios distintos al de la página web.</p> * <p>Hay dos maneras de solventar esta restricción. La primera es que el servidor remoto permita el acceso entre dominios estableciendo la cabecera <code>Access-Control-Allow-Origin</code> a * la respuesta HTTP. Dado que esta solución la implementan terceras personas (los administradores del dominio remoto), no siempre es aplicable.</p> * <p>La segunda solución es desplegar en el dominio propio un proxy. Un proxy es un servicio que recibe peticiones HTTP y las redirige a otra URL.</p> * <p>Si la propiedad <code>proxy</code> está establecida, todas las peticiones a dominios remotos las mandará al proxy para que este las redirija. De esta manera no infringimos las reglas de * seguridad de Javascript, dado que el proxy está alojado en el dominio propio.</p> * @property proxy * @type string * @default "" * @example * SITNA.Cfg.proxy = ""; // Las peticiones a http://www.otrodominio.com se hacen directamente * * SITNA.Cfg.proxy = "/cgi-bin/proxy.cgi?url="; // Las peticiones a http://www.otrodominio.com se convierten en peticiones a /cgi-bin/proxy.cgi?url=http://www.otrodominio.com */ /** * <p>Código EPSG del sistema de referencia espacial del mapa.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.crs.html">online</a>.</p> * @property crs * @type string * @default "EPSG:25830" * @example * <div id="mapa"></div> * <script> * // SITNA.Cfg.baseLayers[0] (capa por defecto) no es compatible con WGS 84, lo cambiamos por SITNA.Consts.layer.IDENA_DYNBASEMAP. * SITNA.Cfg.baseLayers[0] = SITNA.Consts.layer.IDENA_DYNBASEMAP; * SITNA.Cfg.defaultBaseLayer = SITNA.Consts.layer.IDENA_DYNBASEMAP; * * // WGS 84 * SITNA.Cfg.crs = "EPSG:4326"; * // Coordenadas en grados decimales, porque el sistema de referencia espacial es WGS 84. * SITNA.Cfg.initialExtent = [-2.848205, 41.789124, -0.321350, 43.557898]; * SITNA.Cfg.maxExtent = [-2.848205, 41.789124, -0.321350, 43.557898]; * * var map = new SITNA.Map("mapa", { * // SITNA.Cfg.baseLayers[0] (capa por defecto) no es compatible con WGS 84, establecer la capa SITNA.Consts.layer.IDENA_DYNBASEMAP en el control de mapa de situación. * controls: { * overviewMap: { * layer: SITNA.Consts.layer.IDENA_DYNBASEMAP * } * } * }); * </script> */ /** * Extensión inicial del mapa definida por x mínima, y mínima, x máxima, y máxima. Estos valores deben estar en las unidades definidas por * el sistema de referencia espacial del mapa. Por defecto la extensión es la de Navarra. * @property initialExtent * @type array * @default [541084.221, 4640788.225, 685574.4632, 4796618.764] */ /** * Extensión máxima del mapa definida por x mínima, y mínima, x máxima, y máxima, de forma que el centro del mapa nunca saldrá fuera de estos límites. Estos valores deben estar en las unidades definidas por * el sistema de referencia espacial del mapa. Por defecto la extensión es la de Navarra y sus alrededores. * @property maxExtent * @type array * @default [480408, 4599748, 742552, 4861892] */ /** * <p>La rueda de scroll del ratón se puede utilizar para hacer zoom en el mapa.</p> * @property mouseWheelZoom * @type boolean * @default true */ /** * <p>Tolerancia en pixels a las consultas de información de capa.</p> * <p>En ciertas capas, por ejemplo las que representan geometrías de puntos, puede ser difícil pulsar precisamente en el punto donde está la entidad geográfica que interesa. * La propiedad <code>pixelTolerance</code> define un área de un número de pixels hacia cada lado del punto de pulsación, de forma que toda entidad geográfica que se interseque con ese área se incluye en el resultado de la consulta.</p> * <p>Por ejemplo, si el valor establecido es 10, toda entidad geográfica que esté dentro de un cuadrado de 21 pixels de lado (10 pixels por cuadrante más el pixel central) centrado en el punto de pulsación * se mostrará en el resultado.</p> * <p><em>A tener en cuenta:</em> Esta propiedad establece el valor de los llamados "parámetros de vendedor" que los servidores de mapas admiten para modificar el comportamiento de las peticiones * <code>getFeatureInfo</code> del standard WMS. Pero este comportamiento puede ser modificado también por otras circunstancias, como los estilos aplicados a las capas en el servidor. * Como estas circunstancias están fuera del ámbito de alcance de esta API, es posible que los resultados obtenidos desde algún servicio WMS sean inesperados en lo referente a <code>pixelTolerance</code>.</p> * @property pixelTolerance * @type number * @default 10 */ /** * <p>Lista de objetos de definición de capa (instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}}) para incluir dichas capas como mapas de fondo.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.baseLayers.html">online</a>.</p> * @property baseLayers * @type array * @default La lista incluye las siguientes capas de IDENA: Ortofoto 2014 (capa por defecto), Mapa base, Catastro, Cartografía topográfica. * @example * <div id="mapa"></div> * <script> * // Establecer un proxy porque se hacen peticiones a otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * * // Añadir PNOA y establecerla como mapa de fondo por defecto. * SITNA.Cfg.baseLayers.push({ * id: "PNOA", * url: "http://www.ign.es/wms-inspire/pnoa-ma", * layerNames: "OI.OrthoimageCoverage", * isBase: true * }); * SITNA.Cfg.defaultBaseLayer = "PNOA"; * * var map = new SITNA.Map("mapa"); * </script> */ /** * Identificador de la capa base por defecto o índice de la capa base por defecto en la lista de capas base del mapa (Consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/baseLayers:property"}}{{/crossLink}}). * @property defaultBaseLayer * @type string|number * @default SITNA.consts.Layer.IDENA_ORTHOPHOTO */ /** * <p>Lista de objetos de definición de capa (instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}}) para incluir dichas capas como contenido del mapa.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.workLayers.html">online</a>.</p> * @property workLayers * @type array * @default [] * @example * <div id="mapa"></div> * <script> * // Establecer un proxy porque se hacen peticiones a otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * SITNA.Cfg.workLayers = [{ * id: "csantiago", * title: "Camino de Santiago", * url: "http://www.ign.es/wms-inspire/camino-santiago", * layerNames: "PS.ProtectedSite,GN.GeographicalNames,AU.AdministrativeUnit" * }]; * var map = new SITNA.Map("mapa"); * </script> */ /** * Opciones de controles de mapa. * @property controls * @type SITNA.cfg.MapControlOptions * @default Se incluyen controles de indicador de espera de carga, atribución, indicador de coordenadas. */ /** * <p>URL de la carpeta de maquetación. Para prescindir de maquetación, establecer esta propiedad a <code>null</code>.</p> * <p>La API busca en la carpeta de maquetación los siguientes archivos:</p> * <ul> * <li><code>markup.html</code>, con código HTML que se inyectará en el elemento del DOM del mapa.</li> * <li><code>config.json</code>, con un objeto JSON que sobreescribirá propiedades de {{#crossLink "SITNA.Cfg"}}{{/crossLink}}.</li> * <li><code>style.css</code>, para personalizar el estilo del visor y sus controles.</li> * <li><code>script.js</code>, para añadir lógica nueva. Este es el lugar idóneo para la lógica de la nueva interfaz definida por el marcado inyectado con <code>markup.html</code>.</li> * <li><code>ie8.css</code>, para adaptar el estilo a Internet Explorer 8, dado que este navegador tiene soporte CSS3 deficiente.</li> * </ul> * <p>Todos estos archivos son opcionales.</p><p>La maquetación por defecto añade los siguientes controles al conjunto por defecto: <code>navBar</code>, <code>basemapSelector</code>, * <code>TOC</code>, <code>legend</code>, <code>scaleBar</code>, <code>search</code>, <code>measure</code>, <code>overviewMap</code> y <code>popup</code>. Puede <a href="../../tc/layout/responsive/responsive.zip">descargar la maquetación por defecto</a>.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.layout.html">online</a>. * Sus archivos de maquetación son <a href="../../examples/layout/example/markup.html">markup.html</a>, <a href="../../examples/layout/example/config.json">config.json</a> y * <a href="../../examples/layout/example/style.css">style.css</a>.</p> * @property layout * @type string * @default "//sitna.tracasa.es/api/tc/layout/responsive" * @example * <div id="mapa"></div> * <script> * // Establecer un proxy porque se hacen peticiones a otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * * SITNA.Cfg.layout = "layout/example"; * var map = new SITNA.Map("mapa"); * </script> */ SITNA.Cfg.layout = TC.apiLocation + 'TC/layout/responsive'; /** * Opciones de estilo de entidades geográficas. * @property styles * @type SITNA.cfg.StyleOptions */ /** * Opciones de capa. * Esta clase no tiene constructor. * @class SITNA.cfg.LayerOptions * @static */ /** * Identificador único de capa. * @property id * @type string */ /** * Título de capa. Este valor se mostrará en la tabla de contenidos y la leyenda. * @property title * @type string|undefined */ /** * Tipo de capa. Si no se especifica se considera que la capa es WMS. La lista de valores posibles está definida en {{#crossLink "SITNA.consts.LayerType"}}{{/crossLink}}. * @property type * @type string|undefined */ /** * URL del servicio OGC o del archivo KML que define la capa. Propiedad obligatoria en capas de tipo WMS, WMTS, WFS y KML. * @property url * @type string|undefined */ /** * Lista separada por comas de los nombres de capa del servicio OGC. * @property layerNames * @type string|undefined */ /** * Nombre de grupo de matrices del servicio WMTS. Propiedad obligatoria para capas de tipo WMTS. * @property matrixSet * @type string|undefined */ /** * Tipo MIME del formato de archivo de imagen a obtener del servicio. Si esta propiedad no está definida, se comprobará si la capa es un mapa de fondo * (consultar propiedad {{#crossLink "SITNA.cfg.LayerOptions/isBase:property"}}{{/crossLink}}). En caso afirmativo, el formato elegido será <code>"image/jpeg"</code>, * de lo contrario el formato será <code>"image/png"</code>. * @property format * @type string|undefined */ /** * La capa se muestra por defecto si forma parte de los mapas de fondo. * @property isDefault * @type boolean|undefined * @deprecated En lugar de esta propiedad es recomendable usar SITNA.Cfg.defaultBaseLayer. */ /** * La capa es un mapa de fondo. * @property isBase * @type boolean|undefined */ /** * Aplicable a capas de tipo WMS y KML. La capa no muestra la jerarquía de grupos de capas en la tabla de contenidos ni en la leyenda. * @property hideTree * @type boolean|undefined */ /** * La capa no aparece en la tabla de contenidos ni en la leyenda. De este modo se puede añadir una superposición de capas de trabajo que el usuario la perciba como parte del mapa de fondo. * @property stealth * @type boolean|undefined */ /** * URL de una imagen en miniatura a mostrar en el selector de mapas de fondo. * @property thumbnail * @type string|undefined */ /** * <p>Opciones de controles de mapa, define qué controles se incluyen en un mapa y qué opciones se pasan a cada control. * Las propiedades de esta clase son de tipo boolean, en cuyo caso define la existencia o no del control asociado, o una instancia de la clase {{#crossLink "SITNA.cfg.ControlOptions"}}{{/crossLink}}. * Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p> * <p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.MapControlOptions * @static */ /** * Los mapas tienen un indicador de espera de carga. * @property loadingIndicator * @type boolean|SITNA.cfg.ControlOptions|undefined * @default true */ /** * Los mapas tienen una barra de navegación con control de zoom. * @property navBar * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen una barra de escala. * @property scaleBar * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un indicador numérico de escala. * @property scale * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un selector numérico de escala. * @property scaleSelector * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un mapa de situación. * @property overviewMap * @type boolean|SITNA.cfg.OverviewMapOptions|undefined * @default false */ /** * Los mapas tienen un selector de mapas de fondo. * @property basemapSelector * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen atribución. La atribución es un texto superpuesto al mapa que actúa como reconocimiento de la procedencia de los datos que se muestran. * @property attribution * @type boolean|SITNA.cfg.ControlOptions|undefined * @default true */ /** * Los mapas tienen una tabla de contenidos mostrando las capas de trabajo y los grupos de marcadores. * @property TOC * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un indicador de coordenadas y de sistema de referencia espacial. * @property coordinates * @type boolean|SITNA.cfg.CoordinatesOptions|undefined * @default true */ /** * Los mapas tienen leyenda. * @property legend * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas muestran los datos asociados a los marcadores cuando se pulsa sobre ellos. * @property popup * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un buscador de entidades geográficas y localizador de coordenadas. * @property search * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un medidor de longitudes, áreas y perímetros. * @property measure * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * <p>Los mapas tienen un control que gestiona los clics del usuario en ellos.</p> * @property click * @type boolean|SITNA.cfg.ClickOptions|undefined * @default false */ /** * <p>Los mapas pueden abrir una ventana de Google StreetView.</p> * @property streetView * @type boolean|SITNA.cfg.StreetViewOptions|undefined * @default true */ /** * Los mapas responden a los clics con un información de las capas cargadas de tipo WMS. Se usa para ello la petición <code>getFeatureInfo</code> del standard WMS. * Puede consultar el ejemplo <a href="../../examples/cfg.MapControlOptions.featureInfo.html">online</a>. * @property featureInfo * @type boolean|SITNA.cfg.ClickOptions|undefined * @default true * @example * <div id="mapa"></div> * <script> * // Activamos el proxy para poder acceder a servicios de otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * // Añadimos el control featureInfo. * SITNA.Cfg.controls.featureInfo = true; * // Añadimos una capa WMS sobre la que hacer las consultas. * SITNA.Cfg.workLayers = [ * { * id: "ocupacionSuelo", * title: "Ocupación del suelo", * type: SITNA.Consts.layerType.WMS, * url: "http://www.ign.es/wms-inspire/ocupacion-suelo", * layerNames: ["LC.LandCoverSurfaces"] * } * ]; * var map = new SITNA.Map("mapa"); * </script> */ /** * Opciones de control. * Esta clase no tiene constructor. * @class SITNA.cfg.ControlOptions * @static */ /** * Elemento del DOM en el que crear el control o valor de atributo id de dicho elemento. * @property div * @type HTMLElement|string|undefined */ /** * Opciones de control de mapa de situación. * Esta clase no tiene constructor. * @class SITNA.cfg.OverviewMapOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * Identificador de capa para usar como mapa de fondo u objeto de opciones de capa. * @property layer * @type string|SITNA.cfg.LayerOptions */ /** * <p>Opciones de control de coordenadas. * Esta clase no tiene constructor.</p> * <p>Puede consultar el ejemplo <a href="../../examples/cfg.CoordinatesOptions.html">online</a>.</p> * @class SITNA.cfg.CoordinatesOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * Determina si se muestran coordenadas geográficas (en EPSG:4326) además de las del mapa, que por defecto son UTM (EPSG:25830). * @property showGeo * @type boolean|undefined * @example * <div id="mapa"/> * <script> * // Hacemos que el control que muestra las coordenadas en pantalla * // muestre también las coordenadas geográficas * SITNA.Cfg.controls.coordinates = { * showGeo: true * }; * var map = new SITNA.Map('map'); * </script> */ /** * Opciones de control de clic. * Esta clase no tiene constructor. * <p>Estas opciones se utilizan si se desea tener un control en el mapa que reaccione a los clic del ratón o los toques en el mapa.</p> * <p>Puede consultar el ejemplo <a href="../../examples/cfg.ClickOptions.html">online</a>.</p> * @class SITNA.cfg.ClickOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * El control asociado está activo, es decir, responde a los clics hechos en el mapa desde que se carga. * @property active * @type boolean|undefined */ /** * Función de callback que gestiona la respuesta al clic. Es válida cualquier función que acepta un parámetro de coordenada, que es un array de dos números. * @property callback * @type function|undefined * @default Una función que escribe en consola las coordenadas pulsadas * @example * <div id="mapa"/> * <script> * // Creamos un mapa con el control de gestión de clics, con una función de callback personalizada * var map = new SITNA.Map("mapa", { * controls: { * click: { * active: true, * callback: function (coord) { * alert("Has pulsado en la posición " + coord[0] + ", " + coord[1]); * } * } * } * }); * </script> */ /** * Opciones de control de Google StreetView. * Esta clase no tiene constructor. * <p>Para incrustar StreetView en el visor se utiliza la versión 3 de la API de Google Maps. Esta se carga automáticamente al instanciar el control.</p> * <p>Puede consultar el ejemplo <a href="../../examples/cfg.StreetViewOptions.html">online</a>.</p> * @class SITNA.cfg.StreetViewOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * Elemento del DOM en el que mostrar la vista de StreetView o valor de atributo id de dicho elemento. * @property viewDiv * @type HTMLElement|string|undefined * @example * <div id="mapa"/> * <div id="sv"/> * <script> * // Creamos un mapa con el control de StreetView. * // La vista de StreetView se debe dibujar en el elemento con identificador "sv". * var map = new SITNA.Map("mapa", { * controls: { * streetView: { * viewDiv: "sv" * } * } * }); * </script> */ ///** // * Opciones de control de búsqueda de entidades geográficas y localizador de coordenadas. // * Esta clase no tiene constructor. // * @class SITNA.cfg.SearchOptions // * @extends SITNA.cfg.ControlOptions // * @static // */ ///** // * URL del servicio WFS que ofrece los datos de las entidades geográficas. // * @property url // * @type string // */ ///** // * Versión del servicio WFS que ofrece los datos de las entidades geográficas. // * @property version // * @type string // */ ///** // * Formato de respuesta del servicio WFS. // * @property outputFormat // * @type string|undefined // */ ///** // * Prefijo de los nombres de entidad geográfica en el servicio WFS que ofrece los datos de las entidades geográficas. // * @property featurePrefix // * @type string // */ ///** // * Nombre del campo de la tabla de entidades geográficas donde se encuentra la geometría. // * @property geometryName // * @type string // */ ///** // * <p>Conjunto de tipos de búsqueda. Debe ser un objeto cuyas propiedades son instancias de la clase {{#crossLink "SITNA.cfg.SearchTypeOptions"}}{{/crossLink}}.</p> // * <p>Puede consultar el ejemplo <a href="../../examples/cfg.SearchOptions.types.html">online</a>.</p> // * @property types // * @type object // * @example // * <div id="mapa"></div> // * <script> // * // Quitar maquetación. Se eliminan así las opciones por defecto del control de búsqueda. // * SITNA.Cfg.layout = null; // * // * // Objeto de opciones de búsqueda de municipios en el servicio WFS de IDENA. // * var searchOptions = { // * url: "http://idena.navarra.es/ogc/wfs", // * version: "1.1.0", // * featurePrefix: "IDENA_WFS", // * geometryName: "SHAPE", // * types: { // * municipality: { // * featureType: "Municipios", // * properties: ["CMUNICIPIO", "MUNICIPIO"] // * } // * } // * }; // * SITNA.Cfg.controls.search = searchOptions; // * var map = new SITNA.Map("mapa"); // * </script> // */ ///** // * <p>Opciones de tipo de búsqueda. Las propiedades de SITNA.cfg.SearchOptions.{{#crossLink "SITNA.cfg.SearchOptions/types:property"}}{{/crossLink}} son instancias de esta clase.</p> // * <p>Esta clase no tiene constructor.</p> // * @class SITNA.cfg.SearchTypeOptions // * @static // */ ///** // * Nombre del tipo de entidad geográfica a buscar. // * @property featureType // * @type string // */ ///** // * Lista de nombres de propiedad a obtener de las entidades geográficas encontradas. // * @property properties // * @type Array // */ /** * Opciones de estilo de entidades geográficas. * Esta clase no tiene constructor. * @class SITNA.cfg.StyleOptions * @static */ /** * Opciones de estilo de marcador (punto de mapa con icono). * @property marker * @type SITNA.cfg.MarkerStyleOptions|undefined */ /** * Opciones de estilo de línea. * @property line * @type SITNA.cfg.LineStyleOptions|undefined */ /** * Opciones de estilo de polígono. * @property polygon * @type SITNA.cfg.PolygonStyleOptions|undefined */ /** * <p>Opciones de estilo de marcador (punto de mapa con icono). * Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.MarkerStyleOptions * @static */ /** * Lista de nombres de clase CSS a utilizar para los iconos de los marcadores. La API extraerá la URL de las imágenes del atributo <code>background-image</code> asociado a la clase. * @property classes * @type Array * @default ["tc-marker1", "tc-marker2", "tc-marker3", "tc-marker4", "tc-marker5"] */ /** * Posicionamiento relativo del icono respecto al punto del mapa, representado por un array de dos números entre 0 y 1, siendo [0, 0] la esquina superior izquierda del icono. * @property anchor * @type Array * @default [.5, 1] */ /** * Anchura en píxeles del icono. * @property width * @type number * @default 32 */ /** * Altura en píxeles del icono. * @property height * @type number * @default 32 */ /** * <p>Opciones de estilo de línea. Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.LineStyleOptions * @static */ /** * Color de trazo de la línea, representado en formato hex triplet (<code>"#RRGGBB"</code>). * @property strokeColor * @type string * @default "#f00" */ /** * Anchura de trazo en píxeles de la línea. * @property width * @type number * @default 2 */ /** * <p>Opciones de estilo de polígono. Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.PolygonStyleOptions * @extends SITNA.cfg.LineStyleOptions * @static */ /** * Color de relleno, representado en formato hex triplet (<code>"#RRGGBB"</code>). * @property fillColor * @type string * @default "#000" */ /** * Opacidad de relleno, valor de 0 a 1. * @property fillOpacity * @type number * @default .3 */ /** * <p>Opciones de marcador. El icono se obtiene de las propiedades {{#crossLink "SITNA.cfg.MarkerOptions/url:property"}}{{/crossLink}}, * {{#crossLink "SITNA.cfg.MarkerOptions/cssClass:property"}}{{/crossLink}} y {{#crossLink "SITNA.cfg.MarkerOptions/group:property"}}{{/crossLink}}, por ese orden de preferencia.</p> * <p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.MarkerOptions * @extends SITNA.cfg.MarkerStyleOptions * @static */ /** * Nombre de grupo en el que incluir el marcador. Estos grupos se muestran en la tabla de contenidos y en la leyenda. * Todos los marcadores pertenecientes al mismo grupo tienen el mismo icono. Los iconos se asignan automáticamente, rotando por la lista disponible en * SITNA.cfg.MarkerStyleOptions.{{#crossLink "SITNA.cfg.MarkerStyleOptions/classes:property"}}{{/crossLink}}. * @property group * @type string|undefined */ /** * Nombre de clase CSS. El marcador adoptará como icono el valor del atributo <code>background-image</code> de dicha clase. * @property cssClass * @type string|undefined */ /** * URL de archivo de imagen que se utilizará para el icono. * @property url * @type string|undefined */ /** * Identificador de la capa vectorial a la que añadir el marcador. * @property layer * @type string|undefined */ /** * Objeto de datos en pares clave/valor para mostrar cuando se pulsa sobre el marcador. * @property data * @type object|undefined */ /** * Al añadirse el marcador al mapa se muestra con el bocadillo de información asociada visible por defecto. * @property showPopup * @type boolean|undefined */ /** * <p>Búsqueda realizada de entidades geográficas en el mapa. Define el tipo de consulta y a qué capa afecta.</p> * <p>Esta clase no tiene constructor.</p> * class SITNA.Search * static */ /** * Tipo de consulta que se está realizando al mapa. * property type * type SITNA.consts.MapSearchType */ /** * Capa del mapa sobre la que se hace la consulta. * property layer * type SITNA.consts.Layer */
sitna.js
var SITNA = window.SITNA || {}; SITNA.syncLoadJS = function (url) { var req = new XMLHttpRequest(); req.open("GET", url, false); // 'false': synchronous. req.send(null); var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.type = "text/javascript"; script.text = req.responseText; head.appendChild(script); }; (function () { if (!window.TC || !window.TC.Cfg) { var src; var script; if (document.currentScript) { script = document.currentScript; } else { var scripts = document.getElementsByTagName('script'); script = scripts[scripts.length - 1]; } var src = script.getAttribute('src'); SITNA.syncLoadJS(src.substr(0, src.lastIndexOf('/') + 1) + 'tcmap.js'); } })(); /** * <p>Objeto principal de la API, instancia un mapa dentro de un elemento del DOM. Nótese que el constructor es asíncrono, por tanto cualquier código que haga uso de este objeto debería * estar dentro de una función de callback pasada como parámetro al método {{#crossLink "SITNA.Map/loaded:method"}}{{/crossLink}}.</p> * <p>Puede consultar también online el <a href="../../examples/Map.1.html">ejemplo 1</a>, el <a href="../../examples/Map.2.html">ejemplo 2</a> y el <a href="../../examples/Map.3.html">ejemplo 3</a>.</p> * @class SITNA.Map * @constructor * @async * @param {HTMLElement|string} div Elemento del DOM en el que crear el mapa o valor de atributo id de dicho elemento. * @param {object} [options] Objeto de opciones de configuración del mapa. Sus propiedades sobreescriben el objeto de configuración global {{#crossLink "SITNA.Cfg"}}{{/crossLink}}. * @param {string} [options.crs="EPSG:25830"] Código EPSG del sistema de referencia espacial del mapa. * @param {array} [options.initialExtent] Extensión inicial del mapa definida por x mínima, y mínima, x máxima, y máxima. * Esta opción es obligatoria si el sistema de referencia espacial del mapa es distinto del sistema por defecto (ver SITNA.Cfg.{{#crossLink "SITNA.Cfg/crs:property"}}{{/crossLink}}). * Para más información consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/initialExtent:property"}}{{/crossLink}}. * @param {array} [options.maxExtent] Extensión máxima del mapa definida por x mínima, y mínima, x máxima, y máxima. Para más información consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/maxExtent:property"}}{{/crossLink}}. * @param {string} [options.layout] URL de una carpeta de maquetación. Consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones. * @param {array} [options.baseLayers] Lista de identificadores de capa o instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}} para incluir dichas capas como mapas de fondo. * @param {array} [options.workLayers] Lista de identificadores de capa o instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}} para incluir dichas capas como contenido del mapa. * @param {string|number} [options.defaultBaseLayer] Identificador o índice en <code>baseLayers</code> de la capa base por defecto. * @param {SITNA.cfg.MapControlOptions} [options.controls] Opciones de controles de mapa. * @param {SITNA.cfg.StyleOptions} [options.styles] Opciones de estilo de entidades geográficas. * @param {boolean} [options.mouseWheelZoom] La rueda del ratón se puede utilizar para hacer zoom en el mapa. * @param {string} [options.proxy] URL del proxy utilizado para peticiones a dominios remotos (ver SITNA.Cfg.{{#crossLink "SITNA.Cfg/proxy:property"}}{{/crossLink}}). * @example * <div id="mapa"/> * <script> * // Crear un mapa con las opciones por defecto. * var map = new SITNA.Map("mapa"); * </script> * @example * <div id="mapa"/> * <script> * // Crear un mapa en el sistema de referencia WGS 84 con el de mapa de fondo. * var map = new SITNA.Map("mapa", { * crs: "EPSG:4326", * initialExtent: [ // Coordenadas en grados decimales, porque el sistema de referencia espacial es WGS 84. * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * maxExtent: [ * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * baseLayers: [ * SITNA.Consts.layer.IDENA_DYNBASEMAP * ], * defaultBaseLayer: SITNA.Consts.layer.IDENA_DYNBASEMAP, * // Establecemos el mapa de situación con una capa compatible con WGS 84 * controls: { * overviewMap: { * layer: SITNA.Consts.layer.IDENA_DYNBASEMAP * } * } * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear un mapa que tenga como contenido las capas de toponimia y mallas cartográficas del WMS de IDENA. * var map = new SITNA.Map("mapa", { * workLayers: [ * { * id: "topo_mallas", * title: "Toponimia y mallas cartográficas", * type: SITNA.Consts.layerType.WMS, * url: "http://idena.navarra.es/ogc/wms", * layerNames: "IDENA:toponimia,IDENA:mallas" * } * ] * }); * </script> */ SITNA.Map = function (div, options) { var map = this; var tcMap = new TC.Map(div, options); /** * <p>Añade una capa al mapa. Si se le pasa una instancia de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}} como parámetro <code>layer</code> y tiene definida * la propiedad SITNA.cfg.LayerOptions.{{#crossLink "SITNA.cfg.LayerOptions/url:property"}}{{/crossLink}}, establece por defecto el tipo de capa a * {{#crossLink "SITNA.consts.LayerType/KML:property"}}{{/crossLink}} si la URL acaba en ".kml". * El tipo de la capa no puede ser {{#crossLink "SITNA.consts.LayerType/WFS:property"}}{{/crossLink}}.</p> * <p>Puede consultar también online el <a href="../../examples/Map.addLayer.1.html">ejemplo 1</a> y el <a href="../../examples/Map.addLayer.2.html">ejemplo 2</a>.</p> * * @method addLayer * @async * @param {string|SITNA.cfg.LayerOptions} layer Identificador de capa u objeto de opciones de capa. * @param {function} [callback] Función a la que se llama tras ser añadida la capa. * @example * <div id="mapa"></div> * <script> * // Crear un mapa con las opciones por defecto. * var map = new SITNA.Map("mapa"); * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir al mapa la capa de cartografía topográfica de IDENA * map.addLayer(SITNA.Consts.layer.IDENA_CARTO); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear un mapa con las opciones por defecto. * var map = new SITNA.Map("mapa"); * * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir al mapa un documento KML * map.addLayer({ * id: "capa_kml", * title: "Museos en Navarra", * type: SITNA.Consts.layerType.KML, * url: "data/MUSEOSNAVARRA.kml" * }); * }); * </script> */ map.addLayer = function (layer, callback) { tcMap.addLayer(layer, callback); }; /** * <p>Hace visible una capa como mapa de fondo. Esta capa debe existir previamente en la lista de mapas de fondo del mapa.</p> * <p>Puede consultar también online el <a href="../../examples/Map.setBaseLayer.1.html">ejemplo 1</a> y el <a href="../../examples/Map.setBaseLayer.2.html">ejemplo 2</a>.</p> * @method setBaseLayer * @async * @param {string|SITNA.cfg.LayerOptions} layer Identificador de capa u objeto de opciones de capa. * @param {function} [callback] Función al que se llama tras ser establecida la capa como mapa de fondo. * @example * <div id="mapa"></div> * <script> * // Crear mapa con opciones por defecto. Esto incluye la capa del catastro de Navarra entre los mapas de fondo. * var map = new SITNA.Map("mapa"); * // Cuando esté todo cargado establecer como mapa de fondo visible el catastro de Navarra. * map.loaded(function () { * map.setBaseLayer(SITNA.Consts.layer.IDENA_CADASTER); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear mapa con opciones por defecto. * var map = new SITNA.Map("mapa"); * // Cuando el mapa esté cargado, añadir la ortofoto de 1956/1957 como mapa de fondo y establecerla como mapa de fondo visible. * map.loaded(function () { * map.addLayer({ * id: "orto_56_57", * title: "Ortofoto de 1956/1957", * url: "http://idena.navarra.es/ogc/wms", * layerNames: "ortofoto_10000_1957", * isBase: true * }, function () { * map.setBaseLayer("orto_56_57"); * }); * }); * </script> */ map.setBaseLayer = function (layer, callback) { tcMap.setBaseLayer(layer, callback); }; /** * Añade un marcador (un punto asociado a un icono) al mapa. * <p>Puede consultar también online el <a href="../../examples/Map.addMarker.1.html">ejemplo 1</a>, el <a href="../../examples/Map.addMarker.2.html">ejemplo 2</a>, * el <a href="../../examples/Map.addMarker.3.html">ejemplo 3</a> y el <a href="../../examples/Map.addMarker.4.html">ejemplo 4</a>.</p> * @method addMarker * @async * @param {array} coords Coordenadas x e y del punto en las unidades del sistema de referencia del mapa. * @param {object} [options] Objeto de opciones de marcador. * @param {string} [options.group] <p>Nombre de grupo en el que incluir el marcador. Estos grupos se muestran en la tabla de contenidos y en la leyenda.</p> * <p>Todos los marcadores pertenecientes al mismo grupo tienen el mismo icono. Los iconos se asignan automáticamente, rotando por la lista disponible en * SITNA.cfg.MarkerStyleOptions.{{#crossLink "SITNA.cfg.MarkerStyleOptions/classes:property"}}{{/crossLink}}.</p> * @param {string} [options.cssClass] Nombre de clase CSS. El marcador adoptará como icono el valor del atributo <code>background-image</code> de dicha clase. * @param {string} [options.url] URL de archivo de imagen que será el icono del marcador. * @param {number} [options.width] Anchura en píxeles del icono del marcador. * @param {number} [options.height] Altura en píxeles del icono del marcador. * @param {array} [options.anchor] Coordenadas proporcionales (entre 0 y 1) del punto de anclaje del icono al punto del mapa. La coordenada [0, 0] es la esquina superior izquierda del icono. * @param {object} [options.data] Objeto de datos en pares clave/valor para mostrar cuando se pulsa sobre el marcador. Si un valor es una URL, se mostrará como un enlace. * @param {boolean} [options.showPopup] Al añadirse el marcador al mapa se muestra con el bocadillo de información asociada visible por defecto. * @param {string} [options.layer] Identificador de capa de tipo SITNA.consts.LayerType.{{#crossLink "SITNA.consts.LayerType/VECTOR:property"}}{{/crossLink}} en la que se añadirá el marcador. Si no se especifica se creará una capa específica para marcadores. * @example * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir un marcador. * map.addMarker([610749, 4741648]); * // Centrar el mapa en el marcador. * map.zoomToMarkers(); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir marcadores al grupo "Marcadores colgantes" cuyo icono se ancle al punto en el centro hacia abajo. Establecer un icono adecuado. * var markerOptions = { * group: "Marcadores colgantes", * url: "data/colgante.png", * anchor: [0.5, 0] * }; * map.addMarker([610887, 4741244], markerOptions); * map.addMarker([615364, 4657556], markerOptions); * // Centrar el mapa en los marcadores. * map.zoomToMarkers(); * }); * </script> * @example * <div id="mapa"></div> * <script> * // Crear un mapa con una capa vectorial, centrado en la Ciudadela de Pamplona. * var map = new SITNA.Map("mapa", { * initialExtent: [ * 609627, * 4740225, * 611191, * 4741395 * ], * workLayers: [{ * id: "markers", * title: "Marcadores geográficos", * type: SITNA.Consts.layerType.VECTOR * }] * }); * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir un marcador en la capa "markers", asignarle un grupo para que salga en tabla de contenidos y leyenda. * map.addMarker([610431, 4740837], { * layer: "markers", * group: "Ciudadela" * }); * }); * </script> * @example * <style type="text/css"> * .kiosko { * background-image: url("data/icono-kiosko.png"); * } * </style> * <div id="mapa"></div> * <script> * // SITNA.Cfg.baseLayers[0] (capa por defecto) no es compatible con WGS 84, lo cambiamos por SITNA.Consts.layer.IDENA_DYNBASEMAP. * SITNA.Cfg.baseLayers[0] = SITNA.Consts.layer.IDENA_DYNBASEMAP; * SITNA.Cfg.defaultBaseLayer = SITNA.Consts.layer.IDENA_DYNBASEMAP; * // Añadir información emergente al mapa. * SITNA.Cfg.controls.popup = true; * * // Crear un mapa en el sistema de referencia WGS 84. * var map = new SITNA.Map("mapa", { * crs: "EPSG:4326", * initialExtent: [ // Coordenadas en grados decimales, porque el sistema de referencia espacial es WGS 84. * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * maxExtent: [ * -2.84820556640625, * 41.78912492257675, * -0.32135009765625, * 43.55789822064767 * ], * // Establecemos el mapa de situación con una capa compatible con WGS 84 * controls: { * overviewMap: { * layer: SITNA.Consts.layer.IDENA_DYNBASEMAP * } * } * }); * // Cuando esté todo cargado proceder a trabajar con el mapa. * map.loaded(function () { * // Añadir un marcador con un icono de 40x40 píxeles definido por la clase CSS kiosko. Asignarle unos datos asociados que se muestren por defecto. * map.addMarker([-1.605691, 42.060453], { // Coordenadas en grados decimales porque el mapa está en WGS 84. * cssClass: "kiosko", * width: 40, * height: 40, * data: { * "Nombre": "Plaza de la Constitución, Tudela", * "Sitio web": "http://www.tudela.es/" * }, * showPopup: true * }); * // Centrar el mapa en el marcador. * map.zoomToMarkers(); * }); * </script> */ map.addMarker = function (coords, options) { tcMap.addMarker(coords, options); }; /** * Centra y escala el mapa a la extensión que ocupan todos sus marcadores. * <p>Puede consultar también el ejemplo <a href="../../examples/Map.zoomToMarkers.html">online</a>.</p> * @method zoomToMarkers * @param {object} [options] Objeto de opciones de zoom. * @param {number} [options.pointBoundsRadius=30] Radio en metros del área alrededor del marcador que se respetará al hacer zoom. * @param {number} [options.extentMargin=0.2] Tamaño del margen que se aplicará a la extensión total de todas los marcadores. * El valor es la relación de crecimiento en ancho y alto entre la extensión resultante y la original. Por ejemplo, 0,2 indica un crecimiento del 20% de la extensión, 10% por cada lado. * @async * @example * <div class="controls"> * <div><button id="addMarkerBtn">Añadir marcador aleatorio</button></div> * <div><input type="number" step="1" id="pbrVal" value="30" /> <label for="pbrVal">pointBoundsRadius</label></div> * <div><input type="number" step="0.1" id="emVal" value="0.2" /> <label for="emVal">extentMargin</label></div> * <div><button id="zoomBtn">Hacer zoom a los marcadores</button></div> * </div> * <div id="mapa"></div> * <script> * // Crear mapa. * var map = new SITNA.Map("mapa"); * * // Añadir un marcador en un punto aleatorio * var addRandomMarker = function () { * var xmin = SITNA.Cfg.initialExtent[0]; * var ymin = SITNA.Cfg.initialExtent[1]; * var width = SITNA.Cfg.initialExtent[2] - SITNA.Cfg.initialExtent[0]; * var height = SITNA.Cfg.initialExtent[3] - SITNA.Cfg.initialExtent[1]; * map.addMarker([xmin + Math.random() * width, ymin + Math.random() * height]); * }; * * // Hacer zoom a los marcadores con las opciones elegidas * var zoomToMarkers = function () { * map.zoomToMarkers({ * pointBoundsRadius: parseInt(document.getElementById("pbrVal").value), * extentMargin: parseFloat(document.getElementById("emVal").value) * }); * }; * * document.getElementById("addMarkerBtn").addEventListener("click", addRandomMarker); * document.getElementById("zoomBtn").addEventListener("click", zoomToMarkers); * </script> */ map.zoomToMarkers = function (options) { tcMap.zoomToMarkers(options); }; /** * Añade una función de callback que se ejecutará cuando el mapa, sus controles y todas sus capas se hayan cargado. * * @method loaded * @async * @param {function} callback Función a la que se llama tras la carga del mapa. * @example * // Notificar cuando se haya cargado el mapa. * map.loaded(function () { * console.log("Código del mapa y de sus controles cargado, cargando datos..."); * }); */ map.loaded = function (callback) { tcMap.loaded(callback); }; // Si existe el control featureInfo lo activamos. tcMap.loaded(function () { if (!tcMap.activeControl) { var fi = tcMap.getControlsByClass('TC.control.FeatureInfo')[0]; if (fi) { fi.activate(); } } }); }; /** * Colección de constantes utilizadas por la API. Se recomienda utilizar las propiedades de esta clase estática para referirse a valores conocidos. * No deberían modificarse las propiedades de esta clase. * @class SITNA.Consts * @static */ SITNA.Consts = TC.Consts; /** * Identificadores de capas útiles de IDENA. * @property layer * @type SITNA.consts.Layer * @final */ /** * Identificadores de tipo de capa. * @property layerType * @type SITNA.consts.LayerType * @final */ /** * Tipos MIME de utilidad. * @property mimeType * @type SITNA.consts.MimeType * @final */ /** * Colección de identificadores de tipo de capa. * No se deberían modificar las propiedades de esta clase. * @class SITNA.consts.LayerType * @static */ /** * Identificador de capa de tipo WMS. * @property WMS * @type string * @final */ /** * Identificador de capa de tipo WMTS. * @property WMTS * @type string * @final */ /** * Identificador de capa de tipo WFS. * @property WFS * @type string * @final */ /** * Identificador de capa de tipo KML. * @property KML * @type string * @final */ /** * Identificador de capa de tipo vectorial. Este tipo de capa es la que se utiliza para dibujar marcadores. * @property VECTOR * @type string * @final */ /** * Colección de identificadores de capas útiles de IDENA. * No se deberían modificar las propiedades de esta clase. * @class SITNA.consts.Layer * @static */ /** * Identificador de la capa de ortofoto 2014 del WMTS de IDENA. Esta capa solo es compatible con el sistema de referencia EPSG:25830. * @property IDENA_ORTHOPHOTO * @type string * @final */ /** * Identificador de la capa de mapa base del WMTS de IDENA. Esta capa solo es compatible con el sistema de referencia EPSG:25830. * @property IDENA_BASEMAP * @type string * @final */ /** * Identificador de la capa de catastro del WMS de IDENA. * @property IDENA_CADASTER * @type string * @final */ /** * Identificador de la capa de cartografía topográfica del WMS de IDENA. * @property IDENA_CARTO * @type string * @final */ /** * Identificador de la capa de la combinación de ortofoto 2014 y mapa base del WMS de IDENA. * @property IDENA_BASEMAP_ORTHOPHOTO * @type string * @final */ /** * Identificador de la capa de relieve en blanco y negro del WMS de IDENA. * @property IDENA_BW_RELIEF * @type string * @final */ /** * Identificador de la capa de mapa base del WMS de IDENA. * @property IDENA_DYNBASEMAP * @type string * @final */ /** * Identificador de la capa de ortofoto 2012 del WMTS de IDENA. Esta capa solo es compatible con el sistema de referencia EPSG:25830. * @property IDENA_ORTHOPHOTO2012 * @type string * @final */ /** * Identificador de una capa en blanco. * @property BLANK * @type string * @final */ /** * Colección de tipos MIME de utilidad. * No se deberían modificar las propiedades de esta clase. * @class SITNA.consts.MimeType * @static */ /** * Tipo MIME de imagen PNG. * @property PNG * @type string * @final */ /** * Tipo MIME de imagen JPEG. * @property JPEG * @type string * @final */ /** * <p>Configuración general de la API. Cualquier llamada a un método o un constructor de la API sin parámetro de opciones toma las opciones de esta clase. * Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>La clase es estática.</p> * @class SITNA.Cfg * @static */ SITNA.Cfg = TC.Cfg; /** * <p>URL del proxy utilizado para peticiones a dominios remotos.</p> * <p>Debido a restricciones de seguridad implementadas en Javascript, a través de <code>XMLHttpRequest</code> no es posible obtener información de dominios distintos al de la página web.</p> * <p>Hay dos maneras de solventar esta restricción. La primera es que el servidor remoto permita el acceso entre dominios estableciendo la cabecera <code>Access-Control-Allow-Origin</code> a * la respuesta HTTP. Dado que esta solución la implementan terceras personas (los administradores del dominio remoto), no siempre es aplicable.</p> * <p>La segunda solución es desplegar en el dominio propio un proxy. Un proxy es un servicio que recibe peticiones HTTP y las redirige a otra URL.</p> * <p>Si la propiedad <code>proxy</code> está establecida, todas las peticiones a dominios remotos las mandará al proxy para que este las redirija. De esta manera no infringimos las reglas de * seguridad de Javascript, dado que el proxy está alojado en el dominio propio.</p> * @property proxy * @type string * @default "" * @example * SITNA.Cfg.proxy = ""; // Las peticiones a http://www.otrodominio.com se hacen directamente * * SITNA.Cfg.proxy = "/cgi-bin/proxy.cgi?url="; // Las peticiones a http://www.otrodominio.com se convierten en peticiones a /cgi-bin/proxy.cgi?url=http://www.otrodominio.com */ /** * <p>Código EPSG del sistema de referencia espacial del mapa.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.crs.html">online</a>.</p> * @property crs * @type string * @default "EPSG:25830" * @example * <div id="mapa"></div> * <script> * // SITNA.Cfg.baseLayers[0] (capa por defecto) no es compatible con WGS 84, lo cambiamos por SITNA.Consts.layer.IDENA_DYNBASEMAP. * SITNA.Cfg.baseLayers[0] = SITNA.Consts.layer.IDENA_DYNBASEMAP; * SITNA.Cfg.defaultBaseLayer = SITNA.Consts.layer.IDENA_DYNBASEMAP; * * // WGS 84 * SITNA.Cfg.crs = "EPSG:4326"; * // Coordenadas en grados decimales, porque el sistema de referencia espacial es WGS 84. * SITNA.Cfg.initialExtent = [-2.848205, 41.789124, -0.321350, 43.557898]; * SITNA.Cfg.maxExtent = [-2.848205, 41.789124, -0.321350, 43.557898]; * * var map = new SITNA.Map("mapa", { * // SITNA.Cfg.baseLayers[0] (capa por defecto) no es compatible con WGS 84, establecer la capa SITNA.Consts.layer.IDENA_DYNBASEMAP en el control de mapa de situación. * controls: { * overviewMap: { * layer: SITNA.Consts.layer.IDENA_DYNBASEMAP * } * } * }); * </script> */ /** * Extensión inicial del mapa definida por x mínima, y mínima, x máxima, y máxima. Estos valores deben estar en las unidades definidas por * el sistema de referencia espacial del mapa. Por defecto la extensión es la de Navarra. * @property initialExtent * @type array * @default [541084.221, 4640788.225, 685574.4632, 4796618.764] */ /** * Extensión máxima del mapa definida por x mínima, y mínima, x máxima, y máxima, de forma que el centro del mapa nunca saldrá fuera de estos límites. Estos valores deben estar en las unidades definidas por * el sistema de referencia espacial del mapa. Por defecto la extensión es la de Navarra y sus alrededores. * @property maxExtent * @type array * @default [480408, 4599748, 742552, 4861892] */ /** * <p>La rueda de scroll del ratón se puede utilizar para hacer zoom en el mapa.</p> * @property mouseWheelZoom * @type boolean * @default true */ /** * <p>Tolerancia en pixels a las consultas de información de capa.</p> * <p>En ciertas capas, por ejemplo las que representan geometrías de puntos, puede ser difícil pulsar precisamente en el punto donde está la entidad geográfica que interesa. * La propiedad <code>pixelTolerance</code> define un área de un número de pixels hacia cada lado del punto de pulsación, de forma que toda entidad geográfica que se interseque con ese área se incluye en el resultado de la consulta.</p> * <p>Por ejemplo, si el valor establecido es 10, toda entidad geográfica que esté dentro de un cuadrado de 21 pixels de lado (10 pixels por cuadrante más el pixel central) centrado en el punto de pulsación * se mostrará en el resultado.</p> * <p><em>A tener en cuenta:</em> Esta propiedad establece el valor de los llamados "parámetros de vendedor" que los servidores de mapas admiten para modificar el comportamiento de las peticiones * <code>getFeatureInfo</code> del standard WMS. Pero este comportamiento puede ser modificado también por otras circunstancias, como los estilos aplicados a las capas en el servidor. * Como estas circunstancias están fuera del ámbito de alcance de esta API, es posible que los resultados obtenidos desde algún servicio WMS sean inesperados en lo referente a <code>pixelTolerance</code>.</p> * @property pixelTolerance * @type number * @default 10 */ /** * <p>Lista de objetos de definición de capa (instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}}) para incluir dichas capas como mapas de fondo.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.baseLayers.html">online</a>.</p> * @property baseLayers * @type array * @default La lista incluye las siguientes capas de IDENA: Ortofoto 2014 (capa por defecto), Mapa base, Catastro, Cartografía topográfica. * @example * <div id="mapa"></div> * <script> * // Establecer un proxy porque se hacen peticiones a otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * * // Añadir PNOA y establecerla como mapa de fondo por defecto. * SITNA.Cfg.baseLayers.push({ * id: "PNOA", * url: "http://www.ign.es/wms-inspire/pnoa-ma", * layerNames: "OI.OrthoimageCoverage", * isBase: true * }); * SITNA.Cfg.defaultBaseLayer = "PNOA"; * * var map = new SITNA.Map("mapa"); * </script> */ /** * Identificador de la capa base por defecto o índice de la capa base por defecto en la lista de capas base del mapa (Consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/baseLayers:property"}}{{/crossLink}}). * @property defaultBaseLayer * @type string|number * @default SITNA.consts.Layer.IDENA_ORTHOPHOTO */ /** * <p>Lista de objetos de definición de capa (instancias de la clase {{#crossLink "SITNA.cfg.LayerOptions"}}{{/crossLink}}) para incluir dichas capas como contenido del mapa.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.workLayers.html">online</a>.</p> * @property workLayers * @type array * @default [] * @example * <div id="mapa"></div> * <script> * // Establecer un proxy porque se hacen peticiones a otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * SITNA.Cfg.workLayers = [{ * id: "csantiago", * title: "Camino de Santiago", * url: "http://www.ign.es/wms-inspire/camino-santiago", * layerNames: "PS.ProtectedSite,GN.GeographicalNames,AU.AdministrativeUnit" * }]; * var map = new SITNA.Map("mapa"); * </script> */ /** * Opciones de controles de mapa. * @property controls * @type SITNA.cfg.MapControlOptions * @default Se incluyen controles de indicador de espera de carga, atribución, indicador de coordenadas. */ /** * <p>URL de la carpeta de maquetación. Para prescindir de maquetación, establecer esta propiedad a <code>null</code>.</p> * <p>La API busca en la carpeta de maquetación los siguientes archivos:</p> * <ul> * <li><code>markup.html</code>, con código HTML que se inyectará en el elemento del DOM del mapa.</li> * <li><code>config.json</code>, con un objeto JSON que sobreescribirá propiedades de {{#crossLink "SITNA.Cfg"}}{{/crossLink}}.</li> * <li><code>style.css</code>, para personalizar el estilo del visor y sus controles.</li> * <li><code>script.js</code>, para añadir lógica nueva. Este es el lugar idóneo para la lógica de la nueva interfaz definida por el marcado inyectado con <code>markup.html</code>.</li> * <li><code>ie8.css</code>, para adaptar el estilo a Internet Explorer 8, dado que este navegador tiene soporte CSS3 deficiente.</li> * </ul> * <p>Todos estos archivos son opcionales.</p><p>La maquetación por defecto añade los siguientes controles al conjunto por defecto: <code>navBar</code>, <code>basemapSelector</code>, * <code>TOC</code>, <code>legend</code>, <code>scaleBar</code>, <code>search</code>, <code>measure</code>, <code>overviewMap</code> y <code>popup</code>. Puede <a href="../../tc/layout/responsive/responsive.zip">descargar la maquetación por defecto</a>.</p> * <p>Puede consultar el ejemplo <a href="../../examples/Cfg.layout.html">online</a>. * Sus archivos de maquetación son <a href="../../examples/layout/example/markup.html">markup.html</a>, <a href="../../examples/layout/example/config.json">config.json</a> y * <a href="../../examples/layout/example/style.css">style.css</a>.</p> * @property layout * @type string * @default "//sitna.tracasa.es/api/tc/layout/responsive" * @example * <div id="mapa"></div> * <script> * // Establecer un proxy porque se hacen peticiones a otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * * SITNA.Cfg.layout = "layout/example"; * var map = new SITNA.Map("mapa"); * </script> */ SITNA.Cfg.layout = TC.apiLocation + 'TC/layout/responsive'; /** * Opciones de estilo de entidades geográficas. * @property styles * @type SITNA.cfg.StyleOptions */ /** * Opciones de capa. * Esta clase no tiene constructor. * @class SITNA.cfg.LayerOptions * @static */ /** * Identificador único de capa. * @property id * @type string */ /** * Título de capa. Este valor se mostrará en la tabla de contenidos y la leyenda. * @property title * @type string|undefined */ /** * Tipo de capa. Si no se especifica se considera que la capa es WMS. La lista de valores posibles está definida en {{#crossLink "SITNA.consts.LayerType"}}{{/crossLink}}. * @property type * @type string|undefined */ /** * URL del servicio OGC o del archivo KML que define la capa. Propiedad obligatoria en capas de tipo WMS, WMTS, WFS y KML. * @property url * @type string|undefined */ /** * Lista separada por comas de los nombres de capa del servicio OGC. * @property layerNames * @type string|undefined */ /** * Nombre de grupo de matrices del servicio WMTS. Propiedad obligatoria para capas de tipo WMTS. * @property matrixSet * @type string|undefined */ /** * Tipo MIME del formato de archivo de imagen a obtener del servicio. Si esta propiedad no está definida, se comprobará si la capa es un mapa de fondo * (consultar propiedad {{#crossLink "SITNA.cfg.LayerOptions/isBase:property"}}{{/crossLink}}). En caso afirmativo, el formato elegido será <code>"image/jpeg"</code>, * de lo contrario el formato será <code>"image/png"</code>. * @property format * @type string|undefined */ /** * La capa se muestra por defecto si forma parte de los mapas de fondo. * @property isDefault * @type boolean|undefined * @deprecated En lugar de esta propiedad es recomendable usar SITNA.Cfg.defaultBaseLayer. */ /** * La capa es un mapa de fondo. * @property isBase * @type boolean|undefined */ /** * Aplicable a capas de tipo WMS y KML. La capa no muestra la jerarquía de grupos de capas en la tabla de contenidos ni en la leyenda. * @property hideTree * @type boolean|undefined */ /** * La capa no aparece en la tabla de contenidos ni en la leyenda. De este modo se puede añadir una superposición de capas de trabajo que el usuario la perciba como parte del mapa de fondo. * @property stealth * @type boolean|undefined */ /** * URL de una imagen en miniatura a mostrar en el selector de mapas de fondo. * @property thumbnail * @type string|undefined */ /** * <p>Opciones de controles de mapa, define qué controles se incluyen en un mapa y qué opciones se pasan a cada control. * Las propiedades de esta clase son de tipo boolean, en cuyo caso define la existencia o no del control asociado, o una instancia de la clase {{#crossLink "SITNA.cfg.ControlOptions"}}{{/crossLink}}. * Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p> * <p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.MapControlOptions * @static */ /** * Los mapas tienen un indicador de espera de carga. * @property loadingIndicator * @type boolean|SITNA.cfg.ControlOptions|undefined * @default true */ /** * Los mapas tienen una barra de navegación con control de zoom. * @property navBar * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen una barra de escala. * @property scaleBar * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un indicador numérico de escala. * @property scale * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un selector numérico de escala. * @property scaleSelector * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un mapa de situación. * @property overviewMap * @type boolean|SITNA.cfg.OverviewMapOptions|undefined * @default false */ /** * Los mapas tienen un selector de mapas de fondo. * @property basemapSelector * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen atribución. La atribución es un texto superpuesto al mapa que actúa como reconocimiento de la procedencia de los datos que se muestran. * @property attribution * @type boolean|SITNA.cfg.ControlOptions|undefined * @default true */ /** * Los mapas tienen una tabla de contenidos mostrando las capas de trabajo y los grupos de marcadores. * @property TOC * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un indicador de coordenadas y de sistema de referencia espacial. * @property coordinates * @type boolean|SITNA.cfg.CoordinatesOptions|undefined * @default true */ /** * Los mapas tienen leyenda. * @property legend * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas muestran los datos asociados a los marcadores cuando se pulsa sobre ellos. * @property popup * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un buscador de entidades geográficas y localizador de coordenadas. * @property search * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * Los mapas tienen un medidor de longitudes, áreas y perímetros. * @property measure * @type boolean|SITNA.cfg.ControlOptions|undefined * @default false */ /** * <p>Los mapas tienen un control que gestiona los clics del usuario en ellos.</p> * @property click * @type boolean|SITNA.cfg.ClickOptions|undefined * @default false */ /** * <p>Los mapas pueden abrir una ventana de Google StreetView.</p> * @property streetView * @type boolean|SITNA.cfg.StreetViewOptions|undefined * @default true */ /** * Los mapas responden a los clics con un información de las capas cargadas de tipo WMS. Se usa para ello la petición <code>getFeatureInfo</code> del standard WMS. * Puede consultar el ejemplo <a href="../../examples/cfg.MapControlOptions.featureInfo.html">online</a>. * @property featureInfo * @type boolean|SITNA.cfg.ClickOptions|undefined * @default true * @example * <div id="mapa"></div> * <script> * // Activamos el proxy para poder acceder a servicios de otro dominio. * SITNA.Cfg.proxy = "proxy.ashx?"; * // Añadimos el control featureInfo. * SITNA.Cfg.controls.featureInfo = true; * // Añadimos una capa WMS sobre la que hacer las consultas. * SITNA.Cfg.workLayers = [ * { * id: "ocupacionSuelo", * title: "Ocupación del suelo", * type: SITNA.Consts.layerType.WMS, * url: "http://www.ign.es/wms-inspire/ocupacion-suelo", * layerNames: ["LC.LandCoverSurfaces"] * } * ]; * var map = new SITNA.Map("mapa"); * </script> */ /** * Opciones de control. * Esta clase no tiene constructor. * @class SITNA.cfg.ControlOptions * @static */ /** * Elemento del DOM en el que crear el control o valor de atributo id de dicho elemento. * @property div * @type HTMLElement|string|undefined */ /** * Opciones de control de mapa de situación. * Esta clase no tiene constructor. * @class SITNA.cfg.OverviewMapOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * Identificador de capa para usar como mapa de fondo u objeto de opciones de capa. * @property layer * @type string|SITNA.cfg.LayerOptions */ /** * <p>Opciones de control de coordenadas. * Esta clase no tiene constructor.</p> * <p>Puede consultar el ejemplo <a href="../../examples/cfg.CoordinatesOptions.html">online</a>.</p> * @class SITNA.cfg.CoordinatesOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * Determina si se muestran coordenadas geográficas (en EPSG:4326) además de las del mapa, que por defecto son UTM (EPSG:25830). * @property showGeo * @type boolean|undefined * @example * <div id="mapa"/> * <script> * // Hacemos que el control que muestra las coordenadas en pantalla * // muestre también las coordenadas geográficas * SITNA.Cfg.controls.coordinates = { * showGeo: true * }; * var map = new SITNA.Map('map'); * </script> */ /** * Opciones de control de clic. * Esta clase no tiene constructor. * <p>Estas opciones se utilizan si se desea tener un control en el mapa que reaccione a los clic del ratón o los toques en el mapa.</p> * <p>Puede consultar el ejemplo <a href="../../examples/cfg.ClickOptions.html">online</a>.</p> * @class SITNA.cfg.ClickOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * El control asociado está activo, es decir, responde a los clics hechos en el mapa desde que se carga. * @property active * @type boolean|undefined */ /** * Función de callback que gestiona la respuesta al clic. Es válida cualquier función que acepta un parámetro de coordenada, que es un array de dos números. * @property callback * @type function|undefined * @default Una función que escribe en consola las coordenadas pulsadas * @example * <div id="mapa"/> * <script> * // Creamos un mapa con el control de gestión de clics, con una función de callback personalizada * var map = new SITNA.Map("mapa", { * controls: { * click: { * active: true, * callback: function (coord) { * alert("Has pulsado en la posición " + coord[0] + ", " + coord[1]); * } * } * } * }); * </script> */ /** * Opciones de control de Google StreetView. * Esta clase no tiene constructor. * <p>Para incrustar StreetView en el visor se utiliza la versión 3 de la API de Google Maps. Esta se carga automáticamente al instanciar el control.</p> * <p>Puede consultar el ejemplo <a href="../../examples/cfg.StreetViewOptions.html">online</a>.</p> * @class SITNA.cfg.StreetViewOptions * @extends SITNA.cfg.ControlOptions * @static */ /** * Elemento del DOM en el que mostrar la vista de StreetView o valor de atributo id de dicho elemento. * @property viewDiv * @type HTMLElement|string|undefined * @example * <div id="mapa"/> * <div id="sv"/> * <script> * // Creamos un mapa con el control de StreetView. * // La vista de StreetView se debe dibujar en el elemento con identificador "sv". * var map = new SITNA.Map("mapa", { * controls: { * streetView: { * viewDiv: "sv" * } * } * }); * </script> */ ///** // * Opciones de control de búsqueda de entidades geográficas y localizador de coordenadas. // * Esta clase no tiene constructor. // * @class SITNA.cfg.SearchOptions // * @extends SITNA.cfg.ControlOptions // * @static // */ ///** // * URL del servicio WFS que ofrece los datos de las entidades geográficas. // * @property url // * @type string // */ ///** // * Versión del servicio WFS que ofrece los datos de las entidades geográficas. // * @property version // * @type string // */ ///** // * Formato de respuesta del servicio WFS. // * @property outputFormat // * @type string|undefined // */ ///** // * Prefijo de los nombres de entidad geográfica en el servicio WFS que ofrece los datos de las entidades geográficas. // * @property featurePrefix // * @type string // */ ///** // * Nombre del campo de la tabla de entidades geográficas donde se encuentra la geometría. // * @property geometryName // * @type string // */ ///** // * <p>Conjunto de tipos de búsqueda. Debe ser un objeto cuyas propiedades son instancias de la clase {{#crossLink "SITNA.cfg.SearchTypeOptions"}}{{/crossLink}}.</p> // * <p>Puede consultar el ejemplo <a href="../../examples/cfg.SearchOptions.types.html">online</a>.</p> // * @property types // * @type object // * @example // * <div id="mapa"></div> // * <script> // * // Quitar maquetación. Se eliminan así las opciones por defecto del control de búsqueda. // * SITNA.Cfg.layout = null; // * // * // Objeto de opciones de búsqueda de municipios en el servicio WFS de IDENA. // * var searchOptions = { // * url: "http://idena.navarra.es/ogc/wfs", // * version: "1.1.0", // * featurePrefix: "IDENA_WFS", // * geometryName: "SHAPE", // * types: { // * municipality: { // * featureType: "Municipios", // * properties: ["CMUNICIPIO", "MUNICIPIO"] // * } // * } // * }; // * SITNA.Cfg.controls.search = searchOptions; // * var map = new SITNA.Map("mapa"); // * </script> // */ ///** // * <p>Opciones de tipo de búsqueda. Las propiedades de SITNA.cfg.SearchOptions.{{#crossLink "SITNA.cfg.SearchOptions/types:property"}}{{/crossLink}} son instancias de esta clase.</p> // * <p>Esta clase no tiene constructor.</p> // * @class SITNA.cfg.SearchTypeOptions // * @static // */ ///** // * Nombre del tipo de entidad geográfica a buscar. // * @property featureType // * @type string // */ ///** // * Lista de nombres de propiedad a obtener de las entidades geográficas encontradas. // * @property properties // * @type Array // */ /** * Opciones de estilo de entidades geográficas. * Esta clase no tiene constructor. * @class SITNA.cfg.StyleOptions * @static */ /** * Opciones de estilo de marcador (punto de mapa con icono). * @property marker * @type SITNA.cfg.MarkerStyleOptions|undefined */ /** * Opciones de estilo de línea. * @property line * @type SITNA.cfg.LineStyleOptions|undefined */ /** * Opciones de estilo de polígono. * @property polygon * @type SITNA.cfg.PolygonStyleOptions|undefined */ /** * <p>Opciones de estilo de marcador (punto de mapa con icono). * Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.MarkerStyleOptions * @static */ /** * Lista de nombres de clase CSS a utilizar para los iconos de los marcadores. La API extraerá la URL de las imágenes del atributo <code>background-image</code> asociado a la clase. * @property classes * @type Array * @default ["tc-marker1", "tc-marker2", "tc-marker3", "tc-marker4", "tc-marker5"] */ /** * Posicionamiento relativo del icono respecto al punto del mapa, representado por un array de dos números entre 0 y 1, siendo [0, 0] la esquina superior izquierda del icono. * @property anchor * @type Array * @default [.5, 1] */ /** * Anchura en píxeles del icono. * @property width * @type number * @default 32 */ /** * Altura en píxeles del icono. * @property height * @type number * @default 32 */ /** * <p>Opciones de estilo de línea. Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.LineStyleOptions * @static */ /** * Color de trazo de la línea, representado en formato hex triplet (<code>"#RRGGBB"</code>). * @property strokeColor * @type string * @default "#f00" */ /** * Anchura de trazo en píxeles de la línea. * @property width * @type number * @default 2 */ /** * <p>Opciones de estilo de polígono. Hay que tener en cuenta que el archivo <code>config.json</code> de una maquetación puede sobreescribir los valores por defecto de las propiedades de esta clase * (consultar SITNA.Cfg.{{#crossLink "SITNA.Cfg/layout:property"}}{{/crossLink}} para ver instrucciones de uso de maquetaciones).</p><p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.PolygonStyleOptions * @extends SITNA.cfg.LineStyleOptions * @static */ /** * Color de relleno, representado en formato hex triplet (<code>"#RRGGBB"</code>). * @property fillColor * @type string * @default "#000" */ /** * Opacidad de relleno, valor de 0 a 1. * @property fillOpacity * @type number * @default .3 */ /** * <p>Opciones de marcador. El icono se obtiene de las propiedades {{#crossLink "SITNA.cfg.MarkerOptions/url:property"}}{{/crossLink}}, * {{#crossLink "SITNA.cfg.MarkerOptions/cssClass:property"}}{{/crossLink}} y {{#crossLink "SITNA.cfg.MarkerOptions/group:property"}}{{/crossLink}}, por ese orden de preferencia.</p> * <p>Esta clase no tiene constructor.</p> * @class SITNA.cfg.MarkerOptions * @extends SITNA.cfg.MarkerStyleOptions * @static */ /** * Nombre de grupo en el que incluir el marcador. Estos grupos se muestran en la tabla de contenidos y en la leyenda. * Todos los marcadores pertenecientes al mismo grupo tienen el mismo icono. Los iconos se asignan automáticamente, rotando por la lista disponible en * SITNA.cfg.MarkerStyleOptions.{{#crossLink "SITNA.cfg.MarkerStyleOptions/classes:property"}}{{/crossLink}}. * @property group * @type string|undefined */ /** * Nombre de clase CSS. El marcador adoptará como icono el valor del atributo <code>background-image</code> de dicha clase. * @property cssClass * @type string|undefined */ /** * URL de archivo de imagen que se utilizará para el icono. * @property url * @type string|undefined */ /** * Identificador de la capa vectorial a la que añadir el marcador. * @property layer * @type string|undefined */ /** * Objeto de datos en pares clave/valor para mostrar cuando se pulsa sobre el marcador. * @property data * @type object|undefined */ /** * Al añadirse el marcador al mapa se muestra con el bocadillo de información asociada visible por defecto. * @property showPopup * @type boolean|undefined */
Add feature search methods Added several methods to search special features in IDENA.
sitna.js
Add feature search methods
<ide><path>itna.js <ide> var SITNA = window.SITNA || {}; <add>var TC = window.TC || {}; <ide> <ide> SITNA.syncLoadJS = function (url) { <ide> var req = new XMLHttpRequest(); <ide> script = scripts[scripts.length - 1]; <ide> } <ide> var src = script.getAttribute('src'); <del> SITNA.syncLoadJS(src.substr(0, src.lastIndexOf('/') + 1) + 'tcmap.js'); <add> TC.apiLocation = src.substr(0, src.lastIndexOf('/') + 1); <add> SITNA.syncLoadJS(TC.apiLocation + 'tcmap.js'); <ide> } <ide> })(); <ide> <ide> * }); <ide> * </script> <ide> */ <add> <add>/** <add> * Búsqueda actual de consulta de entidad geográfica aplicado al mapa. <add> * property search <add> * type SITNA.Search|null <add> */ <add> <ide> SITNA.Map = function (div, options) { <ide> var map = this; <ide> var tcMap = new TC.Map(div, options); <ide> <ide> // Si existe el control featureInfo lo activamos. <ide> tcMap.loaded(function () { <add> <add> tcSearch = new TC.control.Search(); <add> tcSearch.register(tcMap); <add> <ide> if (!tcMap.activeControl) { <ide> var fi = tcMap.getControlsByClass('TC.control.FeatureInfo')[0]; <ide> if (fi) { <ide> } <ide> } <ide> }); <add> <add> /** <add> * <p>Obtiene los valores (id y label) de las entidades geográficas disponibles en la capa de IDENA que corresponda según el parámetro searchType. <add> * <p>Puede consultar también online el <a href="../../examples/Map.getQueryableData.html">ejemplo 1</a>.</p> <add> * <add> * method getQueryableData <add> * async <add> * param {string|SITNA.consts.MapSearchType} searchType Fuente de datos del cual obtendremos los valores disponibles para buscar posteriormente. <add> * param {function} [callback] Función a la que se llama tras obtener los datos. <add> * example <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear un mapa con las opciones por defecto. <add> * var map = new SITNA.Map("mapa"); <add> * <add> * // Cuando esté todo cargado proceder a trabajar con el mapa. <add> * map.loaded(function () { <add> * // Retorna un array de objetos (id, label) con todos los municipios de Navarra <add> * map.getQueryableData(SITNA.Consts.mapSearchType.MUNICIPALITY, function (data) { <add> * $.each(data, function (key, value) { <add> * $('#municipality') // Completamos el combo '#municipality' con los datos recibidos <add> * .append($("<option></option>") <add> * .attr("value", value.id) <add> * .text(value.label)); <add> * }); <add> * }); <add> * <add> * // Retorna un array de objetos (id, label) con todas las mancomunidades de residuos de Navarra <add> * map.getQueryableData(SITNA.Consts.mapSearchType.COMMONWEALTH, function (data) { <add> * $.each(data, function (key, value) { <add> * $('#commonwealth') // Completamos el combo '#community' con los datos recibidos <add> * .append($("<option></option>") <add> * .attr("value", value.id) <add> * .text(value.label)); <add> * }); <add> * }); <add> * }); <add> * </script> <add> */ <add> map.getQueryableData = function (searchType, callback) { <add> var queryable = tcSearch.availableSearchTypes[searchType]; <add> <add> if (queryable.queryableData) { <add> if (callback) <add> callback(queryable.queryableData); <add> } else { <add> var params = { <add> request: 'GetFeature', <add> service: 'WFS', <add> typename: queryable.featurePrefix + ':' + queryable.featureType, <add> version: queryable.version, <add> propertyname: (!(queryable.dataIdProperty instanceof Array) ? [queryable.dataIdProperty] : queryable.dataIdProperty) <add> .concat((!(queryable.outputProperties instanceof Array) ? [queryable.outputProperties] : queryable.outputProperties)).join(','), <add> outputformat: TC.Consts.format.JSON <add> }; <add> <add> var url = queryable.url + '?' + $.param(params); <add> $.ajax({ <add> url: url <add> }).done(function (data) { <add> queryable.queryableData = []; <add> <add> if (data.features) { <add> var features = data.features; <add> <add> for (var i = 0; i < features.length; i++) { <add> var f = features[i]; <add> var data = {}; <add> <add> data.id = []; <add> if (!(queryable.dataIdProperty instanceof Array)) <add> queryable.dataIdProperty = [queryable.dataIdProperty]; <add> <add> for (var ip = 0; ip < queryable.dataIdProperty.length; ip++) { <add> if (f.properties.hasOwnProperty(queryable.dataIdProperty[ip])) { <add> data.id.push(f.properties[queryable.dataIdProperty[ip]]); <add> } <add> } <add> <add> data.id = queryable.idPropertiesIdentifier ? data.id.join(queryable.idPropertiesIdentifier) : data.id.join(''); <add> <add> data.label = []; <add> if (!(queryable.outputProperties instanceof Array)) <add> queryable.outputProperties = [queryable.outputProperties]; <add> <add> for (var lbl = 0; lbl < queryable.outputProperties.length; lbl++) { <add> if (f.properties.hasOwnProperty(queryable.outputProperties[lbl])) { <add> data.label.push(f.properties[queryable.outputProperties[lbl]]); <add> } <add> } <add> <add> var add = (data.label instanceof Array && data.label.join('').trim().length > 0) || (!(data.label instanceof Array) && data.label.trim().length > 0); <add> data.label = queryable.outputFormatLabel ? queryable.outputFormatLabel.tcFormat(data.label) : data.label.join('-'); <add> <add> if (add) <add> queryable.queryableData.push(data); <add> } <add> } <add> <add> queryable.queryableData = queryable.queryableData.sort(function (a, b) { <add> if (queryable.idPropertiesIdentifier ? a.id.indexOf(queryable.idPropertiesIdentifier) == -1 : false) { <add> if (tcSearch.removePunctuation(a.label) < tcSearch.removePunctuation(b.label)) <add> return -1; <add> else if (tcSearch.removePunctuation(a.label) > tcSearch.removePunctuation(b.label)) <add> return 1; <add> else <add> return 0; <add> } else { <add> if (tcSearch.removePunctuation(a.label.split(' ')[0]) < tcSearch.removePunctuation(b.label.split(' ')[0])) <add> return -1; <add> else if (tcSearch.removePunctuation(a.label.split(' ')[0]) > tcSearch.removePunctuation(b.label.split(' ')[0])) <add> return 1; <add> else <add> return 0; <add> } <add> }); <add> queryable.queryableData = queryable.queryableData.filter(function (value, index, arr) { <add> if (index < 1) <add> return true; <add> else <add> return value.id !== arr[index - 1].id && value.label !== arr[index - 1].label; <add> }); <add> <add> if (callback) <add> callback(queryable.queryableData); <add> }); <add> } <add> }; <add> /** <add> * <p>Obtiene los valores (id y label) de los municipios disponibles en la capa de IDENA. <add> * <p>Puede consultar también online el <a href="../../examples/Map.getMunicipalities.html">ejemplo 1</a>.</p> <add> * <add> * @method getMunicipalities <add> * @async <add> * @param {function} [callback] Función a la que se llama tras obtener los datos. <add> * @example <add> * <div class="instructions divSelect"> <add> * <div> <add> * Municipios <add> * <select id="municipality" onchange="applyFilter()"> <add> * <option value="-1">Seleccione...</option> <add> * </select> <add> * </div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * // completamos el desplegable <add> * map.getMunicipalities(function (data) { <add> * $.each(data, function (key, value) { <add> * $('#municipality').append($("<option></option>") <add> * .attr("value", value.id) <add> * .text(value.label)); <add> * }); <add> * }); <add> * }); <add> * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change <add> * function applyFilter() { <add> * var id = $('#municipality').find('option:selected').val(); <add> * if (id == -1) <add> * map.removeSearch(); <add> * else { <add> * map.searchMunicipality(id, function (idQuery) { <add> * if (idQuery == null) <add> * alert('No se han encontrado resultados'); <add> * }); <add> * } <add> * }; <add> * </script> <add> */ <add> map.getMunicipalities = function (callback) { <add> map.getQueryableData(SITNA.Consts.mapSearchType.MUNICIPALITY, callback); <add> }; <add> /** <add> * <p>Obtiene los valores (id y label) de los cascos urbanos disponibles en la capa de IDENA. <add> * <p>Puede consultar también online el <a href="../../examples/Map.getUrbanAreas.html">ejemplo 1</a>.</p> <add> * <add> * @method getUrbanAreas <add> * @async <add> * @param {function} [callback] Función a la que se llama tras obtener los datos. <add> * @example <add> * <div class="instructions divSelect"> <add> * <div> <add> * Cascos urbanos <add> * <select id="urban" onchange="applyFilter()"> <add> * <option value="-1">Seleccione...</option> <add> * </select> <add> * </div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * // completamos el desplegable <add> * map.getUrbanAreas(function (data) { <add> * $.each(data, function (key, value) { <add> * $('#urban').append($("<option></option>") <add> * .attr("value", value.id) <add> * .text(value.label)); <add> * }); <add> * }); <add> * }); <add> * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change <add> * function applyFilter() { <add> * var id = $('#urban').find('option:selected').val(); <add> * if (id == -1) <add> * map.removeSearch(); <add> * else { <add> * map.searchUrbanArea(id, function (idQuery) { <add> * if (idQuery == null) <add> * alert('No se han encontrado resultados'); <add> * }); <add> * } <add> * }; <add> * </script> <add> */ <add> map.getUrbanAreas = function (callback) { <add> map.getQueryableData(SITNA.Consts.mapSearchType.URBAN, callback); <add> }; <add> /** <add> * <p>Obtiene los valores (id y label) de las mancomunidades de residuos disponibles en la capa de IDENA. <add> * <p>Puede consultar también online el <a href="../../examples/Map.getCommonwealths.html">ejemplo 1</a>.</p> <add> * <add> * @method getCommonwealths <add> * @async <add> * @param {function} [callback] Función a la que se llama tras obtener los datos. <add> * @example <add> * <div class="instructions divSelect"> <add> * <div> <add> * Mancomunidades de residuos <add> * <select id="commonwealths" onchange="applyFilter()"> <add> * <option value="-1">Seleccione...</option> <add> * </select> <add> * </div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * // completamos el desplegable <add> * map.getCommonwealths(function (data) { <add> * $.each(data, function (key, value) { <add> * $('#commonwealths').append($("<option></option>") <add> * .attr("value", value.id) <add> * .text(value.label)); <add> * }); <add> * }); <add> * }); <add> * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change <add> * function applyFilter() { <add> * var id = $('#commonwealths').find('option:selected').val(); <add> * if (id == -1) <add> * map.removeSearch(); <add> * else { <add> * map.searchCommonwealth(id, function (idQuery) { <add> * if (idQuery == null) <add> * alert('No se han encontrado resultados'); <add> * }); <add> * } <add> * }; <add> * </script> <add> */ <add> map.getCommonwealths = function (callback) { <add> map.getQueryableData(SITNA.Consts.mapSearchType.COMMONWEALTH, callback); <add> }; <add> /** <add> * <p>Obtiene los valores (id y label) de los concejos disponibles en la capa de IDENA. <add> * <p>Puede consultar también online el <a href="../../examples/Map.getCouncils.html">ejemplo 1</a>.</p> <add> * <add> * @method getCouncils <add> * @async <add> * @param {function} [callback] Función a la que se llama tras obtener los datos. <add> * @example <add> * <div class="instructions divSelect"> <add> * <div> <add> * Concejos <add> * <select id="council" onchange="applyFilter()"> <add> * <option value="-1">Seleccione...</option> <add> * </select> <add> * </div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * // completamos el desplegable <add> * map.getCouncils(function (data) { <add> * $.each(data, function (key, value) { <add> * $('#council').append($("<option></option>") <add> * .attr("value", value.id) <add> * .text(value.label)); <add> * }); <add> * }); <add> * }); <add> * // Establecer como filtro del mapa el valor seleccionado del desplegable que lance el evento change <add> * function applyFilter() { <add> * var id = $('#council').find('option:selected').val(); <add> * if (id == -1) <add> * map.removeSearch(); <add> * else { <add> * map.searchCouncil(id, function (idQuery) { <add> * if (idQuery == null) <add> * alert('No se han encontrado resultados'); <add> * }); <add> * } <add> * }; <add> * </script> <add> */ <add> map.getCouncils = function (callback) { <add> map.getQueryableData(SITNA.Consts.mapSearchType.COUNCIL, callback); <add> }; <add> /** <add> * <p>Busca la mancomunidad de residuos y pinta en el mapa la entidad geográfica encontrada que corresponda al identificador indicado. <add> * <p>Puede consultar también online el <a href="../../examples/Map.searchCommonwealth.html">ejemplo 1</a>.</p> <add> * <add> * @method searchCommonwealth <add> * @async <add> * @param {string} id Identificador de la entidad geográfica a pintar. <add> * @param {function} [callback] Función a la que se llama tras aplicar el filtro. <add> * @example <add> * <div class="instructions searchCommonwealth"> <add> * <div><button id="searchPamplonaBtn">Buscar Mancomunidad de la Comarca de Pamplona</button></div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * document.getElementById("searchPamplonaBtn").addEventListener("click", search); <add> * }); <add> * <add> * var search = function () { <add> * map.removeSearch(); <add> * map.searchCommonwealth("8", function (idQuery) { <add> * if (idQuery == null) { <add> * alert("No se ha encontrado la mancomunidad con código 8."); <add> * } <add> * }); <add> * }; <add> * </script> <add> */ <add> <add> map.searchCommonwealth = function (id, callback) { <add> map.searchTyped(SITNA.Consts.mapSearchType.COMMONWEALTH, id, callback); <add> }; <add> /** <add> * <p>Busca el concejo que corresponda con el identificador pasado como parámetro y pinta la entidad geográfica encontrada en el mapa. <add> * <p>Puede consultar también online el <a href="../../examples/Map.searchCouncil.html">ejemplo 1</a>.</p> <add> * <add> * @method searchCouncil <add> * @async <add> * @param {string} id Identificador de la entidad geográfica a pintar. <add> * @param {function} [callback] Función a la que se llama tras aplicar el filtro. <add> * @example <add> * <div class="instructions search"> <add> * <div><button id="searchBtn">Buscar concejo Esquíroz (Galar)</button></div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * document.getElementById("searchBtn").addEventListener("click", search); <add> * }); <add> * <add> * var search = function () { <add> * map.removeSearch(); <add> * map.searchCouncil("109#5", function (idQuery) { <add> * if (idQuery == null) { <add> * alert("No se ha encontrado el concejo con código 109#5."); <add> * } <add> * }); <add> * }; <add> * </script> <add> **/ <add> map.searchCouncil = function (id, callback) { <add> map.searchTyped(SITNA.Consts.mapSearchType.COUNCIL, id, callback); <add> }; <add> /** <add> * <p>Busca el casco urbano que corresponda con el identificador pasado como parámetro y pinta la entidad geográfica encontrada en el mapa. <add> * <p>Puede consultar también online el <a href="../../examples/Map.searchUrbanArea.html">ejemplo 1</a>.</p> <add> * <add> * @method searchUrbanArea <add> * @async <add> * @param {string} id Identificador de la entidad geográfica a pintar. <add> * @param {function} [callback] Función a la que se llama tras aplicar el filtro. <add> * @example <add> * <div class="instructions search"> <add> * <div><button id="searchBtn">Buscar casco urbano de Arbizu</button></div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * document.getElementById("searchBtn").addEventListener("click", search); <add> * }); <add> * var search = function () { <add> * map.removeSearch(); <add> * map.searchUrbanArea("27", function (idQuery) { <add> * if (idQuery == null) { <add> * alert("No se ha encontrado el casco urbano con código 27."); <add> * } <add> * }); <add> * }; <add> * </script> <add> **/ <add> map.searchUrbanArea = function (id, callback) { <add> map.searchTyped(SITNA.Consts.mapSearchType.URBAN, id, callback); <add> }; <add> /** <add> * <p>Busca el municipio que corresponda con el identificador pasado como parámetro y pinta la entidad geográfica encontrada en el mapa. <add> * <p>Puede consultar también online el <a href="../../examples/Map.searchMunicipality.html">ejemplo 1</a>.</p> <add> * <add> * @method searchMunicipality <add> * @async <add> * @param {string} id Identificador de la entidad geográfica a pintar. <add> * @param {function} [callback] Función a la que se llama tras aplicar el filtro. <add> * @example <add> * <div class="instructions search"> <add> * <div><button id="searchBtn">Buscar Arbizu</button></div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * map.loaded(function () { <add> * document.getElementById("searchBtn").addEventListener("click", search); <add> * }); <add> * <add> * var search = function () { <add> * map.removeSearch(); <add> * map.searchCouncil("27", function (idQuery) { <add> * if (idQuery == null) { <add> * alert("No se ha encontrado el municipio con código 27."); <add> * } <add> * }); <add> * }; <add> * </script> <add> **/ <add> map.searchMunicipality = function (id, callback) { <add> map.searchTyped(SITNA.Consts.mapSearchType.MUNICIPALITY, id, callback); <add> }; <add> // Busca en la configuración que corresponda según el parámetro searchType el identificador pasado como parámetro <add> map.searchTyped = function (searchType, id, callback) { <add> var idQuery = TC.getUID(); <add> var query = tcSearch.availableSearchTypes[searchType]; <add> <add> if (id instanceof Array && query.goToIdFormat) <add> id = query.goToIdFormat.tcFormat(id); <add> <add> tcSearch._search.data = tcSearch._search.data || []; <add> tcSearch._search.data.push({ <add> dataLayer: query.featureType, <add> dataRole: searchType, <add> id: id, <add> label: "", <add> text: "" <add> }); <add> <add> map.removeSearch(); <add> <add> if (tcSearch.availableSearchTypes[searchType] && !(tcSearch.allowedSearchTypes[searchType])) { <add> tcSearch.allowedSearchTypes = { <add> }; <add> tcSearch.allowedSearchTypes[searchType] = { <add> }; <add> <add> if (!tcSearch.availableSearchTypes[searchType].hasOwnProperty('goTo')) { <add> tcSearch.allowedSearchTypes[searchType] = { <add> goTo: function () { <add> var styles = function (queryStyles, geomType, property) { <add> return queryStyles[geomType][property]; <add> }; <add> var getProperties = function (id) { <add> var filter = []; <add> if (query.idPropertiesIdentifier) id = id.split(query.idPropertiesIdentifier); <add> if (!(id instanceof Array)) id = [id]; <add> for (var i = 0; i < query.dataIdProperty.length; i++) { <add> filter.push({ <add> name: query.dataIdProperty[i], value: id[i], type: TC.Consts.comparison.EQUAL_TO <add> }); <add> } <add> return filter; <add> }; <add> var layerOptions = { <add> id: idQuery, <add> type: SITNA.Consts.layerType.WFS, <add> url: query.url, <add> version: query.version, <add> geometryName: 'the_geom', <add> featurePrefix: query.featurePrefix, <add> featureType: query.featureType, <add> properties: getProperties(id), <add> outputFormat: TC.Consts.format.JSON, <add> styles: { <add> polygon: { <add> fillColor: styles.bind(self, query.styles[query.featureType], 'polygon', 'fillColor'), <add> fillOpacity: styles.bind(self, query.styles[query.featureType], 'polygon', 'fillOpacity'), <add> }, <add> line: { <add> strokeColor: styles.bind(self, query.styles[query.featureType], 'line', 'strokeColor'), <add> strokeOpacity: styles.bind(self, query.styles[query.featureType], 'line', 'strokeOpacity'), <add> strokeWidth: styles.bind(self, query.styles[query.featureType], 'line', 'strokeWidth') <add> } <add> } <add> }; <add> <add> tcMap.addLayer(layerOptions).then(function (layer) { <add> map.search = { <add> layer: layer, type: searchType <add> }; <add> delete tcSearch.allowedSearchTypes[searchType]; <add> }); <add> } <add> }; <add> } <add> } <add> <add> tcMap.one(TC.Consts.event.SEARCHQUERYEMPTY, function (e) { <add> tcMap.toast(tcSearch.EMPTY_RESULTS_LABEL, { <add> type: TC.Consts.msgType.INFO, duration: 5000 <add> }); <add> <add> if (callback) <add> callback(null); <add> }); <add> <add> tcMap.one(TC.Consts.event.FEATURESADD, function (e) { <add> if (e.layer && e.layer.features && e.layer.features.length > 0) <add> tcMap.zoomToFeatures(e.layer.features); <add> <add> map.search = { <add> layer: e.layer, type: searchType <add> }; <add> <add> if (callback) <add> callback(e.layer.id !== idQuery ? e.layer.id : idQuery); <add> }); <add> <add> tcSearch.goToResult(id); <add> }; <add> /** <add> * <p>Busca y pinta en el mapa la entidad geográfica encontrada correspondiente al identificador establecido. <add> * <p>Puede consultar también online el <a href="../../examples/Map.searchFeature.html">ejemplo 1</a>.</p> <add> * <add> * @method searchFeature <add> * @async <add> * @param {string} layer Capa de IDENA en la cual buscar. <add> * @param {string} field Campo de la capa de IDENA en el cual buscar. <add> * @param {string} id Identificador de la entidad geográfica por el cual filtrar. <add> * @param {function} [callback] Función a la que se llama tras aplicar el filtro. <add> * @example <add> * <div class="instructions query"> <add> * <div><label>Capa</label><input type="text" id="capa" placeholder="Nombre capa de IDENA" /> </div> <add> * <div><label>Campo</label><input type="text" id="campo" placeholder="Nombre campo" /> </div> <add> * <div><label>Valor</label><input type="text" id="valor" placeholder="Valor a encontrar" /> </div> <add> * <div><button id="searchBtn">Buscar</button></div> <add> * <div><button id="removeBtn">Eliminar filtro</button></div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * <add> * map.loaded(function () { <add> * document.getElementById("searchBtn").addEventListener("click", search); <add> * document.getElementById("removeBtn").addEventListener("click", remove); <add> * }); <add> * <add> * var search = function () { <add> * var capa = document.getElementById("capa").value; <add> * capa = capa.trim(); <add> * <add> * var campo = document.getElementById("campo").value; <add> * campo = campo.trim(); <add> * <add> * var valor = document.getElementById("valor").value; <add> * valor = valor.trim(); <add> * <add> * map.searchFeature(capa, campo, valor, function (idQuery) { <add> * if (idQuery == null) { <add> * alert("No se han encontrado resultados en la capa: " + capa + " en el campo: " + campo + " el valor: " + valor + "."); <add> * } <add> * }); <add> * }; <add> * <add> * // Limpiar el mapa <add> * var remove = function () { <add> * map.removeSearch(); <add> * }; <add> * </script> <add> */ <add> map.searchFeature = function (layer, field, id, callback) { <add> var idQuery = TC.getUID(); <add> var prefix = tcSearch.featurePrefix; <add> <add> map.removeSearch(); <add> <add> layer = (layer || '').trim(); field = (field || '').trim(); id = (id || '').trim(); <add> if (layer.length == 0 || field.length == 0 || id.length == 0) { <add> tcMap.toast(tcSearch.EMPTY_RESULTS_LABEL, { <add> type: TC.Consts.msgType.INFO, duration: 5000 <add> }); <add> <add> if (callback) <add> callback(null); <add> } else { <add> <add> if (layer.indexOf(':') > -1) { <add> prefix = layer.split(':')[0]; <add> layer = layer.split(':')[1]; <add> } <add> <add> var layerOptions = { <add> id: idQuery, <add> type: SITNA.Consts.layerType.WFS, <add> url: tcSearch.url, <add> version: tcSearch.version, <add> geometryName: 'the_geom', <add> featurePrefix: prefix, <add> featureType: layer, <add> maxFeatures: 1, <add> properties: [{ <add> name: field, value: id, type: TC.Consts.comparison.EQUAL_TO <add> }], <add> outputFormat: TC.Consts.format.JSON <add> }; <add> <add> tcMap.one(TC.Consts.event.FEATURESADD, function (e) { <add> if (e.layer && e.layer.features && e.layer.features.length > 0) <add> tcMap.zoomToFeatures(e.layer.features); <add> }); <add> <add> tcMap.one(TC.Consts.event.LAYERUPDATE, function (e) { <add> if (e.layer && e.layer.features && e.layer.features.length == 0) <add> tcMap.toast(tcSearch.EMPTY_RESULTS_LABEL, { <add> type: TC.Consts.msgType.INFO, duration: 5000 <add> }); <add> <add> if (callback) <add> callback(e.layer && e.layer.features && e.layer.features.length == 0 ? null : idQuery); <add> }); <add> <add> <add> tcMap.addLayer(layerOptions).then(function (layer) { <add> map.search = { <add> layer: layer, type: SITNA.Consts.mapSearchType.GENERIC <add> }; <add> }); <add> } <add> }; <add> /** <add> * <p>Elimina del mapa la entidad geográfica encontrada. <add> * <p>Puede consultar también online el <a href="../../examples/Map.removeSearch.html">ejemplo 1</a>.</p> <add> * <add> * @method removeSearch <add> * @async <add> * @param {function} [callback] Función a la que se llama tras eliminar la entidad geográfica. <add> * @example <add> * <div class="instructions query"> <add> * <div><label>Capa</label><input type="text" id="capa" placeholder="Nombre capa de IDENA" /> </div> <add> * <div><label>Campo</label><input type="text" id="campo" placeholder="Nombre campo" /> </div> <add> * <div><label>Valor</label><input type="text" id="valor" placeholder="Valor a encontrar" /> </div> <add> * <div><button id="searchBtn">Buscar</button></div> <add> * <div><button id="removeBtn">Eliminar filtro</button></div> <add> * </div> <add> * <div id="mapa"></div> <add> * <script> <add> * // Crear mapa. <add> * var map = new SITNA.Map("mapa"); <add> * <add> * map.loaded(function () { <add> * document.getElementById("addFilterBtn").addEventListener("click", addFilter); <add> * document.getElementById("removeFilterBtn").addEventListener("click", removeFilter); <add> * }); <add> * <add> * // Establecer como filtro del mapa el municipio Valle de Egüés <add> * var addFilter = function () { <add> * var capa = document.getElementById("capa").value; <add> * capa = capa.trim(); <add> * <add> * var campo = document.getElementById("campo").value; <add> * campo = campo.trim(); <add> * <add> * var valor = document.getElementById("valor").value; <add> * valor = valor.trim(); <add> * <add> * map.setQuery(capa, campo, valor, function (idQuery) { <add> * if (idQuery == null) { <add> * alert("No se han encontrado resultados en la capa: " + capa + " en el campo: " + campo + " el valor: " + valor + "."); <add> * } <add> * }); <add> * }; <add> * <add> * // Limpiar el mapa del filtro <add> * var remove = function () { <add> * map.removeSearch(); <add> * }; <add> * </script> <add> */ <add> map.removeSearch = function (callback) { <add> if (map.search) { <add> if (!tcSearch.availableSearchTypes[map.search.type] || !tcSearch.availableSearchTypes[map.search.type].hasOwnProperty('goTo')) { <add> tcMap.removeLayer(map.search.layer).then(function () { <add> map.search = null; <add> }); <add> } else { <add> for (var i = 0; i < map.search.layer.features.length; i++) { <add> map.search.layer.removeFeature(map.search.layer.features[i]); <add> } <add> map.search = null; <add> } <add> } <add> <add> if (callback) <add> callback(); <add> }; <add> <add> map.search = null; <ide> }; <ide> <ide> <ide> * @final <ide> */ <ide> /** <add> * Identificadores de tipo de consulta al mapa. <add> * property mapSearchType <add> * type SITNA.consts.MapSearchType <add> * final <add> */ <add>/** <ide> * Tipos MIME de utilidad. <ide> * @property mimeType <ide> * @type SITNA.consts.MimeType <ide> /** <ide> * Tipo MIME de imagen JPEG. <ide> * @property JPEG <add> * @type string <add> * @final <add> */ <add> <add>/* <add> * Colección de tipos de filtros. <add> * No se deberían modificar las propiedades de este objeto. <add> * @class SITNA.consts.MapSearchType <add> * @static <add> */ <add>/* <add> * Identificador de filtro de consulta de tipo municipio. <add> * @property MUNICIPALITY <add> * @type string <add> * @final <add> */ <add>/* <add> * Identificador de filtro de consulta de tipo concejo. <add> * @property COUNCIL <add> * @type string <add> * @final <add> */ <add>/* <add> * Identificador de filtro de consulta de tipo casco urbano. <add> * @property URBAN <add> * @type string <add> * @final <add> */ <add>/* <add> * Identificador de filtro de consulta de tipo mancomunidad. <add> * @property COMMONWEALTH <add> * @type string <add> * @final <add> */ <add>/* <add> * Identificador de filtro de consulta de tipo genérico. <add> * @property GENERIC <ide> * @type string <ide> * @final <ide> */ <ide> * @property showPopup <ide> * @type boolean|undefined <ide> */ <add> <add>/** <add> * <p>Búsqueda realizada de entidades geográficas en el mapa. Define el tipo de consulta y a qué capa afecta.</p> <add> * <p>Esta clase no tiene constructor.</p> <add> * class SITNA.Search <add> * static <add> */ <add>/** <add> * Tipo de consulta que se está realizando al mapa. <add> * property type <add> * type SITNA.consts.MapSearchType <add> */ <add>/** <add> * Capa del mapa sobre la que se hace la consulta. <add> * property layer <add> * type SITNA.consts.Layer <add> */
Java
apache-2.0
6d5fde94a17aab2a5b23fa9fa404df86d198125f
0
fitermay/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,jexp/idea2,nicolargo/intellij-community,petteyg/intellij-community,consulo/consulo,michaelgallacher/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,supersven/intellij-community,holmes/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,slisson/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,semonte/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ernestp/consulo,apixandru/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,dslomov/intellij-community,xfournet/intellij-community,blademainer/intellij-community,clumsy/intellij-community,allotria/intellij-community,amith01994/intellij-community,hurricup/intellij-community,clumsy/intellij-community,allotria/intellij-community,kool79/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,consulo/consulo,idea4bsd/idea4bsd,ryano144/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,supersven/intellij-community,samthor/intellij-community,jexp/idea2,orekyuu/intellij-community,samthor/intellij-community,samthor/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ernestp/consulo,retomerz/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,da1z/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,da1z/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,ryano144/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,suncycheng/intellij-community,da1z/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,fnouama/intellij-community,jexp/idea2,apixandru/intellij-community,gnuhub/intellij-community,slisson/intellij-community,ryano144/intellij-community,signed/intellij-community,hurricup/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,adedayo/intellij-community,FHannes/intellij-community,jagguli/intellij-community,jexp/idea2,supersven/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,joewalnes/idea-community,fnouama/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,retomerz/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,jexp/idea2,slisson/intellij-community,ryano144/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ryano144/intellij-community,robovm/robovm-studio,slisson/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,mglukhikh/intellij-community,consulo/consulo,da1z/intellij-community,ernestp/consulo,signed/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fitermay/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,dslomov/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,caot/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,allotria/intellij-community,akosyakov/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,ryano144/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ibinti/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,fnouama/intellij-community,allotria/intellij-community,caot/intellij-community,da1z/intellij-community,izonder/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,semonte/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,dslomov/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,izonder/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,FHannes/intellij-community,blademainer/intellij-community,signed/intellij-community,signed/intellij-community,caot/intellij-community,adedayo/intellij-community,slisson/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,izonder/intellij-community,da1z/intellij-community,semonte/intellij-community,Lekanich/intellij-community,signed/intellij-community,xfournet/intellij-community,diorcety/intellij-community,amith01994/intellij-community,kdwink/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,FHannes/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,holmes/intellij-community,clumsy/intellij-community,asedunov/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,signed/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,blademainer/intellij-community,supersven/intellij-community,xfournet/intellij-community,ibinti/intellij-community,joewalnes/idea-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,signed/intellij-community,gnuhub/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,vladmm/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,signed/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,caot/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,adedayo/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,caot/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,blademainer/intellij-community,robovm/robovm-studio,apixandru/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,FHannes/intellij-community,izonder/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ernestp/consulo,akosyakov/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,amith01994/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,holmes/intellij-community,fitermay/intellij-community,caot/intellij-community,hurricup/intellij-community,slisson/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,samthor/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,asedunov/intellij-community,blademainer/intellij-community,fitermay/intellij-community,diorcety/intellij-community,ibinti/intellij-community,hurricup/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,kool79/intellij-community,da1z/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,supersven/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,retomerz/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,allotria/intellij-community,supersven/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,petteyg/intellij-community,signed/intellij-community,slisson/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,vladmm/intellij-community,joewalnes/idea-community,supersven/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,jagguli/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,kdwink/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,kool79/intellij-community,xfournet/intellij-community,FHannes/intellij-community,samthor/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ryano144/intellij-community,clumsy/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,consulo/consulo,fitermay/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,kool79/intellij-community,da1z/intellij-community,caot/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,caot/intellij-community,petteyg/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,fnouama/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,semonte/intellij-community,ahb0327/intellij-community,semonte/intellij-community,semonte/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,allotria/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,vladmm/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,fitermay/intellij-community,kool79/intellij-community,retomerz/intellij-community,blademainer/intellij-community,caot/intellij-community,vladmm/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ahb0327/intellij-community,jexp/idea2,MER-GROUP/intellij-community,apixandru/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,holmes/intellij-community,xfournet/intellij-community,adedayo/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,samthor/intellij-community,ernestp/consulo,FHannes/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,retomerz/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,kdwink/intellij-community,jexp/idea2,alphafoobar/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,suncycheng/intellij-community,salguarnieri/intellij-community,caot/intellij-community,allotria/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,samthor/intellij-community,samthor/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.vfs; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandAdapter; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandListener; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsDirectoryMapping; import com.intellij.openapi.vcs.VcsListener; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.ex.VirtualFileManagerAdapter; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.i18n.GitBundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * The component tracks Git roots for the project. If roots are mapped incorrectly it * shows balloon that notifies user about the problem and offers to correct root mapping. */ public class GitRootTracker implements VcsListener { /** * The context project */ private final Project myProject; /** * The vcs manager that tracks content roots */ private final ProjectLevelVcsManager myVcsManager; /** * The vcs instance */ private final GitVcs myVcs; /** * If true, the root configuration has been possibly invalidated */ private final AtomicBoolean myRootsInvalidated = new AtomicBoolean(true); /** * If true, there are some configured git roots, or listener has never been run yet */ private final AtomicBoolean myHasGitRoots = new AtomicBoolean(true); /** * If true, the notification is currently active and has not been dismissed yet. */ private final AtomicBoolean myNotificationPosted = new AtomicBoolean(false); /** * The invalid git roots */ private static final String GIT_INVALID_ROOTS_ID = "GIT_INVALID_ROOTS"; /** * The command listener */ private CommandListener myCommandListener; /** * The file listener */ private MyFileListener myFileListener; /** * Listener for refresh events */ private VirtualFileManagerAdapter myVirtualFileManagerListener; /** * Local file system service */ private LocalFileSystem myLocalFileSystem; /** * The constructor * * @param project the project instance */ public GitRootTracker(GitVcs vcs, @NotNull Project project) { if (project.isDefault()) { throw new IllegalArgumentException("The project must not be default"); } myProject = project; myVcs = vcs; myVcsManager = ProjectLevelVcsManager.getInstance(project); myVcsManager.addVcsListener(this); myLocalFileSystem = LocalFileSystem.getInstance(); myCommandListener = new CommandAdapter() { @Override public void commandFinished(CommandEvent event) { if (!myRootsInvalidated.compareAndSet(true, false)) { return; } checkRoots(false); } }; CommandProcessor.getInstance().addCommandListener(myCommandListener); myFileListener = new MyFileListener(); VirtualFileManagerEx fileManager = (VirtualFileManagerEx)VirtualFileManager.getInstance(); fileManager.addVirtualFileListener(myFileListener); myVirtualFileManagerListener = new VirtualFileManagerAdapter() { @Override public void afterRefreshFinish(boolean asynchonous) { if (!myRootsInvalidated.compareAndSet(true, false)) { return; } checkRoots(false); } }; fileManager.addVirtualFileManagerListener(myVirtualFileManagerListener); checkRoots(true); } /** * Dispose the component removing all related listeners */ public void dispose() { myVcsManager.removeVcsListener(this); CommandProcessor.getInstance().removeCommandListener(myCommandListener); VirtualFileManagerEx fileManager = (VirtualFileManagerEx)VirtualFileManager.getInstance(); fileManager.removeVirtualFileListener(myFileListener); fileManager.removeVirtualFileManagerListener(myVirtualFileManagerListener); } /** * {@inheritDoc} */ public void directoryMappingChanged() { if (myProject.isDisposed()) { return; } checkRoots(true); } /** * Check roots for changes. * * @param rootsChanged */ private void checkRoots(boolean rootsChanged) { if (!rootsChanged && !myHasGitRoots.get()) { return; } ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { boolean hasInvalidRoots = false; HashSet<String> rootSet = new HashSet<String>(); for (VcsDirectoryMapping m : myVcsManager.getDirectoryMappings()) { if (!m.getVcs().equals(myVcs.getName())) { continue; } String path = m.getDirectory(); if (path.length() == 0) { VirtualFile baseDir = myProject.getBaseDir(); assert baseDir != null; path = baseDir.getPath(); } VirtualFile root = lookupFile(path); if (root == null) { hasInvalidRoots = true; break; } else { rootSet.add(root.getPath()); } } if (!hasInvalidRoots && rootSet.isEmpty()) { myHasGitRoots.set(false); return; } else { myHasGitRoots.set(true); } if (!hasInvalidRoots) { // check if roots have a problem loop: for (String path : rootSet) { VirtualFile root = lookupFile(path); VirtualFile gitRoot = GitUtil.gitRootOrNull(root); if (gitRoot == null || hasUnmappedSubroots(root, rootSet)) { hasInvalidRoots = true; break; } for (String otherPath : rootSet) { if (otherPath.equals(path)) { continue; } if (otherPath.startsWith(path)) { VirtualFile otherFile = lookupFile(otherPath); if (otherFile == null) { hasInvalidRoots = true; break loop; } VirtualFile otherRoot = GitUtil.gitRootOrNull(otherFile); if (otherRoot == null || otherRoot == root || otherFile != otherRoot) { hasInvalidRoots = true; break loop; } } } } } if (!hasInvalidRoots) { // all roots are correct if (myNotificationPosted.compareAndSet(true, false)) { final Notifications notifications = myProject.getMessageBus().syncPublisher(Notifications.TOPIC); notifications.invalidateAll(GIT_INVALID_ROOTS_ID); } return; } if (myNotificationPosted.compareAndSet(false, true)) { String title = GitBundle.message("root.tracker.message"); final Notifications notifications = myProject.getMessageBus().syncPublisher(Notifications.TOPIC); notifications.notify(GIT_INVALID_ROOTS_ID, title, title, NotificationType.ERROR, new NotificationListener() { @NotNull public Continue perform() { if (fixRoots()) { myNotificationPosted.set(false); return Continue.REMOVE; } else { return Continue.LEAVE; } } public Continue onRemove() { return Continue.LEAVE; } }); } } }); } /** * Check if there are some unmapped subdirectories under git * * @param directory the content root to check * @param rootSet the mapped root set * @return true if there are unmapped subroots */ private static boolean hasUnmappedSubroots(VirtualFile directory, HashSet<String> rootSet) { for (VirtualFile child : directory.getChildren()) { if (child.getName().equals(".git") || !child.isDirectory()) { continue; } if (child.findChild(".git") != null && !rootSet.contains(child.getPath())) { return true; } if (hasUnmappedSubroots(child, rootSet)) { return true; } } return false; } /** * Fix mapped roots * * @return true if roots now in the correct state */ boolean fixRoots() { final List<VcsDirectoryMapping> vcsDirectoryMappings = new ArrayList<VcsDirectoryMapping>(myVcsManager.getDirectoryMappings()); final HashSet<String> mapped = new HashSet<String>(); final HashSet<String> removed = new HashSet<String>(); final HashSet<String> added = new HashSet<String>(); final VirtualFile baseDir = myProject.getBaseDir(); assert baseDir != null; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (Iterator<VcsDirectoryMapping> i = vcsDirectoryMappings.iterator(); i.hasNext();) { VcsDirectoryMapping m = i.next(); String vcsName = myVcs.getName(); if (!vcsName.equals(m.getVcs())) { continue; } String path = m.getDirectory(); if (path.length() == 0) { path = baseDir.getPath(); } VirtualFile file = lookupFile(path); if (file != null && !mapped.add(file.getPath())) { // eliminate duplicates i.remove(); continue; } if (file == null || GitUtil.gitRootOrNull(file) == null) { removed.add(path); } } for (String m : mapped) { VirtualFile file = lookupFile(m); if (file == null) { continue; } addSubroots(file, added, mapped); if (removed.contains(m)) { continue; } VirtualFile root = GitUtil.gitRootOrNull(file); assert root != null; for (String o : mapped) { // the mapped collection is not modified here, so order is being kept if (o.equals(m) || removed.contains(o)) { continue; } if (o.startsWith(m)) { VirtualFile otherFile = lookupFile(m); assert otherFile != null; VirtualFile otherRoot = GitUtil.gitRootOrNull(otherFile); assert otherRoot != null; if (otherRoot == root) { removed.add(o); } else if (otherFile != otherRoot) { added.add(otherRoot.getPath()); removed.add(o); } } } } } }); if (added.isEmpty() && removed.isEmpty()) { Messages.showInfoMessage(myProject, GitBundle.message("fix.roots.valid.message"), GitBundle.message("fix.roots.valid.title")); return true; } GitFixRootsDialog d = new GitFixRootsDialog(myProject, mapped, added, removed); d.show(); if (!d.isOK()) { return false; } for (Iterator<VcsDirectoryMapping> i = vcsDirectoryMappings.iterator(); i.hasNext();) { VcsDirectoryMapping m = i.next(); String path = m.getDirectory(); if (removed.contains(path) || (path.length() == 0 && removed.contains(baseDir.getPath()))) { i.remove(); } } for (String a : added) { vcsDirectoryMappings.add(new VcsDirectoryMapping(a, myVcs.getName())); } myVcsManager.setDirectoryMappings(vcsDirectoryMappings); myVcsManager.updateActiveVcss(); return true; } /** * Look up file in the file system * * @param path the path to lookup * @return the file or null if the file not found */ @Nullable private VirtualFile lookupFile(String path) { return myLocalFileSystem.findFileByPath(path); } /** * Add subroots for the content root * * @param directory the content root to check * @param toAdd collection of roots to be added * @param mapped all mapped git roots */ private static void addSubroots(VirtualFile directory, HashSet<String> toAdd, HashSet<String> mapped) { for (VirtualFile child : directory.getChildren()) { if (!child.isDirectory()) { continue; } if (child.getName().equals(".git") && !mapped.contains(directory.getPath())) { toAdd.add(directory.getPath()); } else { addSubroots(child, toAdd, mapped); } } } /** * The listener for git roots */ private class MyFileListener extends VirtualFileAdapter { /** * Return true if file has git repositories * * @param file the file to check * @return true if file has git repositories */ private boolean hasGitRepositories(VirtualFile file) { if (!file.isDirectory()) { return false; } if (file.getName().equals(".git")) { return true; } for (VirtualFile child : file.getChildren()) { if (hasGitRepositories(child)) { return true; } } return false; } /** * Invalidate git root */ private void invalidate() { myRootsInvalidated.set(true); } /** * {@inheritDoc} */ @Override public void fileCreated(VirtualFileEvent event) { if (!myHasGitRoots.get()) { return; } if (hasGitRepositories(event.getFile())) { invalidate(); } } /** * {@inheritDoc} */ @Override public void beforeFileDeletion(VirtualFileEvent event) { if (!myHasGitRoots.get()) { return; } if (hasGitRepositories(event.getFile())) { invalidate(); } } /** * {@inheritDoc} */ @Override public void fileMoved(VirtualFileMoveEvent event) { if (!myHasGitRoots.get()) { return; } if (hasGitRepositories(event.getFile())) { invalidate(); } } /** * {@inheritDoc} */ @Override public void fileCopied(VirtualFileCopyEvent event) { if (!myHasGitRoots.get()) { return; } if (hasGitRepositories(event.getFile())) { invalidate(); } } } }
plugins/git4idea/src/git4idea/vfs/GitRootTracker.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.vfs; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandAdapter; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandListener; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsDirectoryMapping; import com.intellij.openapi.vcs.VcsListener; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.ex.VirtualFileManagerAdapter; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.i18n.GitBundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * The component tracks Git roots for the project. If roots are mapped incorrectly it * shows balloon that notifies user about the problem and offers to correct root mapping. */ public class GitRootTracker implements VcsListener { /** * The context project */ private final Project myProject; /** * The vcs manager that tracks content roots */ private final ProjectLevelVcsManager myVcsManager; /** * The vcs instance */ private final GitVcs myVcs; /** * If true, the root configuration has been possibly invalidated */ private final AtomicBoolean myRootsInvalidated = new AtomicBoolean(true); /** * If true, the notification is currently active and has not been dismissed yet. */ private final AtomicBoolean myNotificationPosted = new AtomicBoolean(false); /** * The invalid git roots */ private static final String GIT_INVALID_ROOTS_ID = "GIT_INVALID_ROOTS"; /** * The command listener */ private CommandListener myCommandListener; /** * The file listener */ private MyFileListener myFileListener; /** * Listener for refresh events */ private VirtualFileManagerAdapter myVirtualFileManagerListener; /** * Local file system service */ private LocalFileSystem myLocalFileSystem; /** * The constructor * * @param project the project instance */ public GitRootTracker(GitVcs vcs, @NotNull Project project) { if (project.isDefault()) { throw new IllegalArgumentException("The project must not be default"); } myProject = project; myVcs = vcs; myVcsManager = ProjectLevelVcsManager.getInstance(project); myVcsManager.addVcsListener(this); myLocalFileSystem = LocalFileSystem.getInstance(); myCommandListener = new CommandAdapter() { @Override public void commandFinished(CommandEvent event) { if (!myRootsInvalidated.compareAndSet(true, false)) { return; } directoryMappingChanged(); } }; CommandProcessor.getInstance().addCommandListener(myCommandListener); myFileListener = new MyFileListener(); VirtualFileManagerEx fileManager = (VirtualFileManagerEx)VirtualFileManager.getInstance(); fileManager.addVirtualFileListener(myFileListener); myVirtualFileManagerListener = new VirtualFileManagerAdapter() { @Override public void afterRefreshFinish(boolean asynchonous) { if (!myRootsInvalidated.compareAndSet(true, false)) { return; } directoryMappingChanged(); } }; fileManager.addVirtualFileManagerListener(myVirtualFileManagerListener); directoryMappingChanged(); } /** * Dispose the component removing all related listeners */ public void dispose() { myVcsManager.removeVcsListener(this); CommandProcessor.getInstance().removeCommandListener(myCommandListener); VirtualFileManagerEx fileManager = (VirtualFileManagerEx)VirtualFileManager.getInstance(); fileManager.removeVirtualFileListener(myFileListener); fileManager.removeVirtualFileManagerListener(myVirtualFileManagerListener); } /** * {@inheritDoc} */ public void directoryMappingChanged() { if (myProject.isDisposed()) { return; } ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { boolean hasInvalidRoots = false; HashSet<String> rootSet = new HashSet<String>(); for (VcsDirectoryMapping m : myVcsManager.getDirectoryMappings()) { if (!m.getVcs().equals(myVcs.getName())) { continue; } String path = m.getDirectory(); if (path.length() == 0) { VirtualFile baseDir = myProject.getBaseDir(); assert baseDir != null; path = baseDir.getPath(); } VirtualFile root = lookupFile(path); if (root == null) { hasInvalidRoots = true; break; } else { rootSet.add(root.getPath()); } } if (!hasInvalidRoots && rootSet.isEmpty()) { return; } if (!hasInvalidRoots) { // check if roots have a problem loop: for (String path : rootSet) { VirtualFile root = lookupFile(path); VirtualFile gitRoot = GitUtil.gitRootOrNull(root); if (gitRoot == null || hasUnmappedSubroots(root, rootSet)) { hasInvalidRoots = true; break; } for (String otherPath : rootSet) { if (otherPath.equals(path)) { continue; } if (otherPath.startsWith(path)) { VirtualFile otherFile = lookupFile(otherPath); if (otherFile == null) { hasInvalidRoots = true; break loop; } VirtualFile otherRoot = GitUtil.gitRootOrNull(otherFile); if (otherRoot == null || otherRoot == root || otherFile != otherRoot) { hasInvalidRoots = true; break loop; } } } } } if (!hasInvalidRoots) { // all roots are correct if (myNotificationPosted.compareAndSet(true, false)) { final Notifications notifications = myProject.getMessageBus().syncPublisher(Notifications.TOPIC); notifications.invalidateAll(GIT_INVALID_ROOTS_ID); } return; } if (myNotificationPosted.compareAndSet(false, true)) { String title = GitBundle.message("root.tracker.message"); final Notifications notifications = myProject.getMessageBus().syncPublisher(Notifications.TOPIC); notifications.notify(GIT_INVALID_ROOTS_ID, title, title, NotificationType.ERROR, new NotificationListener() { @NotNull public Continue perform() { if (fixRoots()) { myNotificationPosted.set(false); return Continue.REMOVE; } else { return Continue.LEAVE; } } public Continue onRemove() { return Continue.LEAVE; } }); } } }); } /** * Check if there are some unmapped subdirectories under git * * @param directory the content root to check * @param rootSet the mapped root set * @return true if there are unmapped subroots */ private static boolean hasUnmappedSubroots(VirtualFile directory, HashSet<String> rootSet) { for (VirtualFile child : directory.getChildren()) { if (child.getName().equals(".git") || !child.isDirectory()) { continue; } if (child.findChild(".git") != null && !rootSet.contains(child.getPath())) { return true; } if (hasUnmappedSubroots(child, rootSet)) { return true; } } return false; } /** * Fix mapped roots * * @return true if roots now in the correct state */ boolean fixRoots() { final List<VcsDirectoryMapping> vcsDirectoryMappings = new ArrayList<VcsDirectoryMapping>(myVcsManager.getDirectoryMappings()); final HashSet<String> mapped = new HashSet<String>(); final HashSet<String> removed = new HashSet<String>(); final HashSet<String> added = new HashSet<String>(); final VirtualFile baseDir = myProject.getBaseDir(); assert baseDir != null; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (Iterator<VcsDirectoryMapping> i = vcsDirectoryMappings.iterator(); i.hasNext();) { VcsDirectoryMapping m = i.next(); String vcsName = myVcs.getName(); if (!vcsName.equals(m.getVcs())) { continue; } String path = m.getDirectory(); if (path.length() == 0) { path = baseDir.getPath(); } VirtualFile file = lookupFile(path); if (file != null && !mapped.add(file.getPath())) { // eliminate duplicates i.remove(); continue; } if (file == null || GitUtil.gitRootOrNull(file) == null) { removed.add(path); } } for (String m : mapped) { VirtualFile file = lookupFile(m); if (file == null) { continue; } addSubroots(file, added, mapped); if (removed.contains(m)) { continue; } VirtualFile root = GitUtil.gitRootOrNull(file); assert root != null; for (String o : mapped) { // the mapped collection is not modified here, so order is being kept if (o.equals(m) || removed.contains(o)) { continue; } if (o.startsWith(m)) { VirtualFile otherFile = lookupFile(m); assert otherFile != null; VirtualFile otherRoot = GitUtil.gitRootOrNull(otherFile); assert otherRoot != null; if (otherRoot == root) { removed.add(o); } else if (otherFile != otherRoot) { added.add(otherRoot.getPath()); removed.add(o); } } } } } }); if (added.isEmpty() && removed.isEmpty()) { Messages.showInfoMessage(myProject, GitBundle.message("fix.roots.valid.message"), GitBundle.message("fix.roots.valid.title")); return true; } GitFixRootsDialog d = new GitFixRootsDialog(myProject, mapped, added, removed); d.show(); if (!d.isOK()) { return false; } for (Iterator<VcsDirectoryMapping> i = vcsDirectoryMappings.iterator(); i.hasNext();) { VcsDirectoryMapping m = i.next(); String path = m.getDirectory(); if (removed.contains(path) || (path.length() == 0 && removed.contains(baseDir.getPath()))) { i.remove(); } } for (String a : added) { vcsDirectoryMappings.add(new VcsDirectoryMapping(a, myVcs.getName())); } myVcsManager.setDirectoryMappings(vcsDirectoryMappings); myVcsManager.updateActiveVcss(); return true; } /** * Look up file in the file system * * @param path the path to lookup * @return the file or null if the file not found */ @Nullable private VirtualFile lookupFile(String path) { return myLocalFileSystem.findFileByPath(path); } /** * Add subroots for the content root * * @param directory the content root to check * @param toAdd collection of roots to be added * @param mapped all mapped git roots */ private static void addSubroots(VirtualFile directory, HashSet<String> toAdd, HashSet<String> mapped) { for (VirtualFile child : directory.getChildren()) { if (!child.isDirectory()) { continue; } if (child.getName().equals(".git") && !mapped.contains(directory.getPath())) { toAdd.add(directory.getPath()); } else { addSubroots(child, toAdd, mapped); } } } /** * The listener for git roots */ private class MyFileListener extends VirtualFileAdapter { /** * Return true if file has git repositories * * @param file the file to check * @return true if file has git repositories */ private boolean hasGitRepositories(VirtualFile file) { if (!file.isDirectory()) { return false; } if (file.getName().equals(".git")) { return true; } for (VirtualFile child : file.getChildren()) { if (hasGitRepositories(child)) { return true; } } return false; } /** * Invalidate git root */ private void invalidate() { myRootsInvalidated.set(true); } /** * {@inheritDoc} */ @Override public void fileCreated(VirtualFileEvent event) { if (hasGitRepositories(event.getFile())) { invalidate(); } } /** * {@inheritDoc} */ @Override public void beforeFileDeletion(VirtualFileEvent event) { if (hasGitRepositories(event.getFile())) { invalidate(); } } /** * {@inheritDoc} */ @Override public void fileMoved(VirtualFileMoveEvent event) { if (hasGitRepositories(event.getFile())) { invalidate(); } } /** * {@inheritDoc} */ @Override public void fileCopied(VirtualFileCopyEvent event) { if (hasGitRepositories(event.getFile())) { invalidate(); } } } }
git4idea: optimized root tracker to preform fs checks only if there are configured git roots.
plugins/git4idea/src/git4idea/vfs/GitRootTracker.java
git4idea: optimized root tracker to preform fs checks only if there are configured git roots.
<ide><path>lugins/git4idea/src/git4idea/vfs/GitRootTracker.java <ide> */ <ide> private final AtomicBoolean myRootsInvalidated = new AtomicBoolean(true); <ide> /** <add> * If true, there are some configured git roots, or listener has never been run yet <add> */ <add> private final AtomicBoolean myHasGitRoots = new AtomicBoolean(true); <add> /** <ide> * If true, the notification is currently active and has not been dismissed yet. <ide> */ <ide> private final AtomicBoolean myNotificationPosted = new AtomicBoolean(false); <ide> if (!myRootsInvalidated.compareAndSet(true, false)) { <ide> return; <ide> } <del> directoryMappingChanged(); <add> checkRoots(false); <ide> } <ide> }; <ide> CommandProcessor.getInstance().addCommandListener(myCommandListener); <ide> if (!myRootsInvalidated.compareAndSet(true, false)) { <ide> return; <ide> } <del> directoryMappingChanged(); <add> checkRoots(false); <ide> } <ide> }; <ide> fileManager.addVirtualFileManagerListener(myVirtualFileManagerListener); <del> directoryMappingChanged(); <add> checkRoots(true); <ide> } <ide> <ide> /** <ide> */ <ide> public void directoryMappingChanged() { <ide> if (myProject.isDisposed()) { <add> return; <add> } <add> checkRoots(true); <add> } <add> <add> /** <add> * Check roots for changes. <add> * <add> * @param rootsChanged <add> */ <add> private void checkRoots(boolean rootsChanged) { <add> if (!rootsChanged && !myHasGitRoots.get()) { <ide> return; <ide> } <ide> ApplicationManager.getApplication().runReadAction(new Runnable() { <ide> } <ide> } <ide> if (!hasInvalidRoots && rootSet.isEmpty()) { <add> myHasGitRoots.set(false); <ide> return; <add> } <add> else { <add> myHasGitRoots.set(true); <ide> } <ide> if (!hasInvalidRoots) { <ide> // check if roots have a problem <ide> */ <ide> @Override <ide> public void fileCreated(VirtualFileEvent event) { <add> if (!myHasGitRoots.get()) { <add> return; <add> } <ide> if (hasGitRepositories(event.getFile())) { <ide> invalidate(); <ide> } <ide> */ <ide> @Override <ide> public void beforeFileDeletion(VirtualFileEvent event) { <add> if (!myHasGitRoots.get()) { <add> return; <add> } <ide> if (hasGitRepositories(event.getFile())) { <ide> invalidate(); <ide> } <ide> */ <ide> @Override <ide> public void fileMoved(VirtualFileMoveEvent event) { <add> if (!myHasGitRoots.get()) { <add> return; <add> } <ide> if (hasGitRepositories(event.getFile())) { <ide> invalidate(); <ide> } <ide> */ <ide> @Override <ide> public void fileCopied(VirtualFileCopyEvent event) { <add> if (!myHasGitRoots.get()) { <add> return; <add> } <ide> if (hasGitRepositories(event.getFile())) { <ide> invalidate(); <ide> }
Java
bsd-3-clause
error: pathspec 'src/test/java/net/emaze/dysfunctional/time/SleepTest.java' did not match any file(s) known to git
8d4d97d877377fa6f76eea13a51611bbd3dc283a
1
emaze/emaze-dysfunctional,EdMcBane/emaze-dysfunctional
package net.emaze.dysfunctional.time; import java.util.concurrent.TimeUnit; import net.emaze.dysfunctional.tuples.Pair; import org.junit.Assert; import org.junit.Test; /** * * @author rferranti */ public class SleepTest { final long ICE_AGE = 0l; final WarpingTimeStrategy clock = new WarpingTimeStrategy(ICE_AGE); /** * when you don't want to wait for something just leap forward in the future. */ @Test public void sleepMovesTimeToTheFuture() { new Sleep(clock).perform(1l, TimeUnit.MILLISECONDS); final Pair<Long, TimeUnit> currentTime = clock.currentTime(); final long currentTimeInMillis = currentTime.second().toMillis(currentTime.first()); Assert.assertEquals(ICE_AGE + 1, currentTimeInMillis); } }
src/test/java/net/emaze/dysfunctional/time/SleepTest.java
enh: sleep coverage
src/test/java/net/emaze/dysfunctional/time/SleepTest.java
enh: sleep coverage
<ide><path>rc/test/java/net/emaze/dysfunctional/time/SleepTest.java <add>package net.emaze.dysfunctional.time; <add> <add>import java.util.concurrent.TimeUnit; <add>import net.emaze.dysfunctional.tuples.Pair; <add>import org.junit.Assert; <add>import org.junit.Test; <add> <add>/** <add> * <add> * @author rferranti <add> */ <add>public class SleepTest { <add> <add> final long ICE_AGE = 0l; <add> final WarpingTimeStrategy clock = new WarpingTimeStrategy(ICE_AGE); <add> <add> /** <add> * when you don't want to wait for something just leap forward in the future. <add> */ <add> @Test <add> public void sleepMovesTimeToTheFuture() { <add> new Sleep(clock).perform(1l, TimeUnit.MILLISECONDS); <add> final Pair<Long, TimeUnit> currentTime = clock.currentTime(); <add> final long currentTimeInMillis = currentTime.second().toMillis(currentTime.first()); <add> Assert.assertEquals(ICE_AGE + 1, currentTimeInMillis); <add> } <add>}
Java
mit
da8a5f825539d0baa0a472459c3f08567cf5c0fe
0
bluesnap/bluesnap-android-int
package com.bluesnap.androidapi; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import com.bluesnap.androidapi.models.SdkRequest; import com.bluesnap.androidapi.services.BSPaymentRequestException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.fail; /** * Created by oz on 4/4/16. */ @RunWith(AndroidJUnit4.class) public class CurrencyConverterTests extends BSAndroidTestsBase { private static final String TAG = CurrencyConverterTests.class.getSimpleName(); @After public void keepRunning() throws InterruptedException { Thread.sleep(1000); } // public CurrencyConverterTests() { //// ShadowLog.stream = System.out; // System.setProperty("robolectric.logging", "stdout"); // } @Before public void setup() throws InterruptedException { super.getToken(); Log.i(TAG, "=============== Starting rates service tests =================="); } @Test public void convert_USD_to_ILS_and_Back() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("USD"); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "USD", "ILS"); Double reconvertedPrice = blueSnapService.convertPrice(convertedOncePrice, "ILS", "USD"); assertEquals(amount, reconvertedPrice); } @Test public void convert_ILS_to_EUR_and_Back() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("ILS"); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePRice = blueSnapService.convertPrice(amount, "ILS", "EUR"); Double reconvertedPrice = blueSnapService.convertPrice(convertedOncePRice, "EUR", "ILS"); assertEquals(amount, reconvertedPrice); } @Test public void convert_ILS_to_EUR_to_GBP_and_Back() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("ILS"); sdkRequest.setBase(); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "ILS", "EUR"); Double convertedTwicePrice = blueSnapService.convertPrice(convertedOncePrice, "EUR", "GBP"); Double reconvertedUSDPrice = blueSnapService.convertPrice(convertedTwicePrice, "GBP", "ILS"); assertEquals(amount, reconvertedUSDPrice); } @Test public void convert_EUR_to_USD() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 10D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("EUR"); sdkRequest.setBase(); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "EUR", "USD"); // assertEquals("14.42", new BigDecimal(convertedOncePrice).setScale(2, RoundingMode.HALF_UP).toString()); assertEquals("12.88", String.format("%.2f", convertedOncePrice)); } @Test public void convert_EUR_to_ILS_to_USD() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 10.7D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("EUR"); sdkRequest.setBase(); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "EUR", "ILS"); Double convertedTwicePrice = blueSnapService.convertPrice(convertedOncePrice, "ILS", "USD"); assertEquals("13.78", String.format("%.2f", convertedTwicePrice)); } @Test public void non_existing_currency_code() throws InterruptedException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("SOMETHING_BAD"); try { blueSnapService.setSdkRequest(sdkRequest); Double ILSPrice = blueSnapService.convertPrice(amount, "SOMETHING_BAD", "ILS"); fail("Should have trown exception"); } catch (BSPaymentRequestException e) { assertEquals("Currency not found", e.getMessage()); } } @Test public void null_currency_code() throws InterruptedException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); try { blueSnapService.setSdkRequest(sdkRequest); Double ILSPrice = blueSnapService.convertPrice(amount, "SOMETHING_BAD", "ILS"); fail("Should have trown exception"); } catch (BSPaymentRequestException e) { assertEquals("Invalid currency", e.getMessage()); } } }
bluesnap-android/src/androidTest/java/com/bluesnap/androidapi/CurrencyConverterTests.java
package com.bluesnap.androidapi; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import com.bluesnap.androidapi.models.SdkRequest; import com.bluesnap.androidapi.services.BSPaymentRequestException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.fail; /** * Created by oz on 4/4/16. */ @RunWith(AndroidJUnit4.class) public class CurrencyConverterTests extends BSAndroidTestsBase { private static final String TAG = CurrencyConverterTests.class.getSimpleName(); @After public void keepRunning() throws InterruptedException { Thread.sleep(1000); } // public CurrencyConverterTests() { //// ShadowLog.stream = System.out; // System.setProperty("robolectric.logging", "stdout"); // } @Before public void setup() throws InterruptedException { super.getToken(); Log.i(TAG, "=============== Starting rates service tests =================="); } @Test public void convert_USD_to_ILS_and_Back() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("USD"); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "USD", "ILS"); Double reconvertedPrice = blueSnapService.convertPrice(convertedOncePrice, "ILS", "USD"); assertEquals(amount, reconvertedPrice); } @Test public void convert_ILS_to_EUR_and_Back() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("ILS"); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePRice = blueSnapService.convertPrice(amount, "ILS", "EUR"); Double reconvertedPrice = blueSnapService.convertPrice(convertedOncePRice, "EUR", "ILS"); assertEquals(amount, reconvertedPrice); } @Test public void convert_ILS_to_EUR_to_GBP_and_Back() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("ILS"); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "ILS", "EUR"); Double convertedTwicePrice = blueSnapService.convertPrice(convertedOncePrice, "EUR", "GBP"); Double reconvertedUSDPrice = blueSnapService.convertPrice(convertedTwicePrice, "GBP", "ILS"); assertEquals(amount, reconvertedUSDPrice); } @Test public void convert_EUR_to_USD() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 10D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("EUR"); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "EUR", "USD"); // assertEquals("14.42", new BigDecimal(convertedOncePrice).setScale(2, RoundingMode.HALF_UP).toString()); assertEquals("14.42", String.format("%.2f", convertedOncePrice)); } @Test public void convert_EUR_to_ILS_to_USD() throws InterruptedException, BSPaymentRequestException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 10.7D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("EUR"); blueSnapService.setSdkRequest(sdkRequest); Double convertedOncePrice = blueSnapService.convertPrice(amount, "EUR", "ILS"); Double convertedTwicePrice = blueSnapService.convertPrice(amount, "ILS", "USD"); // assertEquals("14.42", new BigDecimal(convertedOncePrice).setScale(2, RoundingMode.HALF_UP).toString()); assertEquals("14.42", String.format("%.2f", convertedTwicePrice)); } @Test public void non_existing_currency_code() throws InterruptedException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); sdkRequest.setCurrencyNameCode("SOMETHING_BAD"); try { blueSnapService.setSdkRequest(sdkRequest); Double ILSPrice = blueSnapService.convertPrice(amount, "SOMETHING_BAD", "ILS"); fail("Should have trown exception"); } catch (BSPaymentRequestException e) { assertEquals("Currency not found", e.getMessage()); } } @Test public void null_currency_code() throws InterruptedException { SdkRequest sdkRequest = new SdkRequest(); Double amount = 30.5D; sdkRequest.setAmount(amount); try { blueSnapService.setSdkRequest(sdkRequest); Double ILSPrice = blueSnapService.convertPrice(amount, "SOMETHING_BAD", "ILS"); fail("Should have trown exception"); } catch (BSPaymentRequestException e) { assertEquals("Invalid currency", e.getMessage()); } } }
fixed tests
bluesnap-android/src/androidTest/java/com/bluesnap/androidapi/CurrencyConverterTests.java
fixed tests
<ide><path>luesnap-android/src/androidTest/java/com/bluesnap/androidapi/CurrencyConverterTests.java <ide> sdkRequest.setAmount(amount); <ide> sdkRequest.setCurrencyNameCode("ILS"); <ide> <del> <add> sdkRequest.setBase(); <ide> blueSnapService.setSdkRequest(sdkRequest); <ide> Double convertedOncePrice = blueSnapService.convertPrice(amount, "ILS", "EUR"); <ide> Double convertedTwicePrice = blueSnapService.convertPrice(convertedOncePrice, "EUR", "GBP"); <ide> sdkRequest.setAmount(amount); <ide> sdkRequest.setCurrencyNameCode("EUR"); <ide> <del> <add> sdkRequest.setBase(); <ide> blueSnapService.setSdkRequest(sdkRequest); <ide> Double convertedOncePrice = blueSnapService.convertPrice(amount, "EUR", "USD"); <ide> // assertEquals("14.42", new BigDecimal(convertedOncePrice).setScale(2, RoundingMode.HALF_UP).toString()); <del> assertEquals("14.42", String.format("%.2f", convertedOncePrice)); <add> assertEquals("12.88", String.format("%.2f", convertedOncePrice)); <ide> } <ide> <ide> @Test <ide> sdkRequest.setAmount(amount); <ide> sdkRequest.setCurrencyNameCode("EUR"); <ide> <del> <add> sdkRequest.setBase(); <ide> blueSnapService.setSdkRequest(sdkRequest); <ide> Double convertedOncePrice = blueSnapService.convertPrice(amount, "EUR", "ILS"); <del> Double convertedTwicePrice = blueSnapService.convertPrice(amount, "ILS", "USD"); <del>// assertEquals("14.42", new BigDecimal(convertedOncePrice).setScale(2, RoundingMode.HALF_UP).toString()); <del> assertEquals("14.42", String.format("%.2f", convertedTwicePrice)); <add> Double convertedTwicePrice = blueSnapService.convertPrice(convertedOncePrice, "ILS", "USD"); <add> assertEquals("13.78", String.format("%.2f", convertedTwicePrice)); <ide> } <ide> <ide>
Java
mit
error: pathspec 'src/FogCube.java' did not match any file(s) known to git
7fccb6360e624c2d36e2efad90a28665173d9da2
1
LTolosa/A-Maze-3D
import org.lwjgl.LWJGLException; import org.lwjgl.Sys; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import org.lwjgl.util.glu.GLU; import org.lwjgl.util.vector.Vector3f; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class FogCube { String windowTitle = "Fog"; public boolean closeRequested = false; long lastFrameTime; // used to calculate delta float triangleAngle; // Angle of rotation for the triangles float quadAngle; // Angle of rotation for the quads float z = -5.0f; float lightAmbient[] = {0.5f, 0.5f, 0.5f, 1.0f}; float lightDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f}; float lightPosition[] = {0.0f, 0.0f, 2.0f, 1.0f}; int fogMode[] = {GL11.GL_EXP, GL11.GL_EXP2, GL11.GL_LINEAR}; int fogfilter = 0; // Change this to see the 3 different types of fog effects! float fogColor[] = {0.5f, 0.5f, 0.5f, 1.0f}; public void run() { createWindow(); getDelta(); // Initialise delta timer initGL(); while (!closeRequested) { pollInput(); updateLogic(getDelta()); renderGL(); Display.update(); } cleanup(); } private void initGL() { /* OpenGL */ int width = Display.getDisplayMode().getWidth(); int height = Display.getDisplayMode().getHeight(); GL11.glViewport(0, 0, width, height); // Reset The Current Viewport GL11.glMatrixMode(GL11.GL_PROJECTION); // Select The Projection Matrix GL11.glLoadIdentity(); // Reset The Projection Matrix GLU.gluPerspective(45.0f, ((float) width / (float) height), 0.1f, 100.0f); // Calculate The Aspect Ratio Of The Window GL11.glMatrixMode(GL11.GL_MODELVIEW); // Select The Modelview Matrix GL11.glLoadIdentity(); // Reset The Modelview Matrix GL11.glShadeModel(GL11.GL_SMOOTH); // Enables Smooth Shading GL11.glEnable(GL11.GL_TEXTURE_2D); // Enable Texture Mapping GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); // Set The Blending Function For Translucency GL11.glClearColor(0.5f, 0.5f, 0.5f, 0.0f); // This Will Clear The Background Color To Black GL11.glClearDepth(1.0f); // Depth Buffer Setup GL11.glEnable(GL11.GL_DEPTH_TEST); // Enables Depth Testing GL11.glDepthFunc(GL11.GL_LESS); // The Type Of Depth Test To Do GL11.glShadeModel(GL11.GL_SMOOTH); // Enables Smooth Color Shading GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST); // Really Nice Perspective Calculations ByteBuffer temp = ByteBuffer.allocateDirect(16); temp.order(ByteOrder.nativeOrder()); temp.asFloatBuffer().put(lightAmbient).flip(); GL11.glLight(GL11.GL_LIGHT1, GL11.GL_AMBIENT, temp.asFloatBuffer()); // Setup The Ambient Light temp.asFloatBuffer().put(lightDiffuse).flip(); GL11.glLight(GL11.GL_LIGHT1, GL11.GL_DIFFUSE, temp.asFloatBuffer()); // Setup The Diffuse Light temp.asFloatBuffer().put(lightPosition).flip(); GL11.glLight(GL11.GL_LIGHT1, GL11.GL_POSITION, temp.asFloatBuffer()); // Position The Light GL11.glEnable(GL11.GL_LIGHT1); // Enable Light One GL11.glFogi(GL11.GL_FOG_MODE, fogMode[fogfilter]); // Fog Mode temp.asFloatBuffer().put(fogColor).flip(); GL11.glFog(GL11.GL_FOG_COLOR, temp.asFloatBuffer()); // Set Fog Color GL11.glFogf(GL11.GL_FOG_DENSITY, 0.35f); // How Dense Will The Fog Be GL11.glHint(GL11.GL_FOG_HINT, GL11.GL_DONT_CARE); // Fog Hint Value GL11.glFogf(GL11.GL_FOG_START, 1.0f); // Fog Start Depth GL11.glFogf(GL11.GL_FOG_END, 5.0f); // Fog End Depth GL11.glEnable(GL11.GL_FOG); // Enables GL_FOG Camera.create(); } private void updateLogic(int delta) { triangleAngle += 0.1f * delta; // Increase The Rotation Variable For The Triangles quadAngle -= 0.05f * delta; // Decrease The Rotation Variable For The Quads } private void renderGL() { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer GL11.glLoadIdentity(); // Reset The View GL11.glTranslatef(0.0f, 0.0f, -7.0f); // Move Right And Into The Screen Camera.apply(); GL11.glBegin(GL11.GL_QUADS); // Start Drawing The Cube GL11.glColor3f(0.0f, 1.0f, 0.0f); // Set The Color To Green GL11.glVertex3f(1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Top) GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Top) GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top) GL11.glVertex3f(1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top) GL11.glColor3f(1.0f, 0.5f, 0.0f); // Set The Color To Orange GL11.glVertex3f(1.0f, -1.0f, 1.0f); // Top Right Of The Quad (Bottom) GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Top Left Of The Quad (Bottom) GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Bottom) GL11.glVertex3f(1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Bottom) GL11.glColor3f(1.0f, 0.0f, 0.0f); // Set The Color To Red GL11.glVertex3f(1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front) GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front) GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Quad (Front) GL11.glVertex3f(1.0f, -1.0f, 1.0f); // Bottom Right Of The Quad (Front) GL11.glColor3f(1.0f, 1.0f, 0.0f); // Set The Color To Yellow GL11.glVertex3f(1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Back) GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Back) GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Back) GL11.glVertex3f(1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Back) GL11.glColor3f(0.0f, 0.0f, 1.0f); // Set The Color To Blue GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left) GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Left) GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Left) GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Quad (Left) GL11.glColor3f(1.0f, 0.0f, 1.0f); // Set The Color To Violet GL11.glVertex3f(1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Right) GL11.glVertex3f(1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right) GL11.glVertex3f(1.0f, -1.0f, 1.0f); // Bottom Left Of The Quad (Right) GL11.glVertex3f(1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Right) GL11.glEnd(); // Done Drawing The Quad } /** * Poll Input */ public void pollInput() { Camera.acceptInput(getDelta()); // scroll through key events while (Keyboard.next()) { if (Keyboard.getEventKeyState()) { if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) closeRequested = true; } if (Display.isCloseRequested()) { closeRequested = true; } } } /** * Calculate how many milliseconds have passed * since last frame. * * @return milliseconds passed since last frame */ public int getDelta() { long time = (Sys.getTime() * 1000) / Sys.getTimerResolution(); int delta = (int) (time - lastFrameTime); lastFrameTime = time; return delta; } private void createWindow() { try { Display.setDisplayMode(new DisplayMode(640, 480)); Display.setVSyncEnabled(true); Display.setTitle(windowTitle); Display.create(); } catch (LWJGLException e) { Sys.alert("Error", "Initialization failed!\n\n" + e.getMessage()); System.exit(0); } } /** * Destroy and clean up resources */ private void cleanup() { Display.destroy(); } public static void main(String[] args) { new FogCube().run(); } public static class Camera { public static float moveSpeed = 0.05f; private static float maxLook = 85; private static float mouseSensitivity = 0.05f; private static Vector3f pos; private static Vector3f rotation; public static void create() { pos = new Vector3f(0, 0, 0); rotation = new Vector3f(0, 0, 0); } public static void apply() { if (rotation.y / 360 > 1) { rotation.y -= 360; } else if (rotation.y / 360 < -1) { rotation.y += 360; } //System.out.println(rotation); GL11.glRotatef(rotation.x, 1, 0, 0); GL11.glRotatef(rotation.y, 0, 1, 0); GL11.glRotatef(rotation.z, 0, 0, 1); GL11.glTranslatef(-pos.x, -pos.y, -pos.z); } public static void acceptInput(float delta) { //System.out.println("delta="+delta); acceptInputRotate(delta); acceptInputMove(delta); } public static void acceptInputRotate(float delta) { if (Mouse.isInsideWindow() && Mouse.isButtonDown(0)) { float mouseDX = Mouse.getDX(); float mouseDY = -Mouse.getDY(); //System.out.println("DX/Y: " + mouseDX + " " + mouseDY); rotation.y += mouseDX * mouseSensitivity * delta; rotation.x += mouseDY * mouseSensitivity * delta; rotation.x = Math.max(-maxLook, Math.min(maxLook, rotation.x)); } } public static void acceptInputMove(float delta) { boolean keyUp = Keyboard.isKeyDown(Keyboard.KEY_W); boolean keyDown = Keyboard.isKeyDown(Keyboard.KEY_S); boolean keyRight = Keyboard.isKeyDown(Keyboard.KEY_D); boolean keyLeft = Keyboard.isKeyDown(Keyboard.KEY_A); boolean keyFast = Keyboard.isKeyDown(Keyboard.KEY_Q); boolean keySlow = Keyboard.isKeyDown(Keyboard.KEY_E); boolean keyFlyUp = Keyboard.isKeyDown(Keyboard.KEY_SPACE); boolean keyFlyDown = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT); float speed; if (keyFast) { speed = moveSpeed * 5; } else if (keySlow) { speed = moveSpeed / 2; } else { speed = moveSpeed; } speed *= delta; if (keyFlyUp) { pos.y += speed; } if (keyFlyDown) { pos.y -= speed; } if (keyDown) { pos.x -= Math.sin(Math.toRadians(rotation.y)) * speed; pos.z += Math.cos(Math.toRadians(rotation.y)) * speed; } if (keyUp) { pos.x += Math.sin(Math.toRadians(rotation.y)) * speed; pos.z -= Math.cos(Math.toRadians(rotation.y)) * speed; } if (keyLeft) { pos.x += Math.sin(Math.toRadians(rotation.y - 90)) * speed; pos.z -= Math.cos(Math.toRadians(rotation.y - 90)) * speed; } if (keyRight) { pos.x += Math.sin(Math.toRadians(rotation.y + 90)) * speed; pos.z -= Math.cos(Math.toRadians(rotation.y + 90)) * speed; } } } }
src/FogCube.java
Added fog to simple cube scene
src/FogCube.java
Added fog to simple cube scene
<ide><path>rc/FogCube.java <add>import org.lwjgl.LWJGLException; <add>import org.lwjgl.Sys; <add>import org.lwjgl.input.Keyboard; <add>import org.lwjgl.input.Mouse; <add>import org.lwjgl.opengl.Display; <add>import org.lwjgl.opengl.DisplayMode; <add>import org.lwjgl.opengl.GL11; <add>import org.lwjgl.util.glu.GLU; <add>import org.lwjgl.util.vector.Vector3f; <add> <add>import java.nio.ByteBuffer; <add>import java.nio.ByteOrder; <add> <add>public class FogCube { <add> <add> String windowTitle = "Fog"; <add> public boolean closeRequested = false; <add> <add> long lastFrameTime; // used to calculate delta <add> <add> float triangleAngle; // Angle of rotation for the triangles <add> float quadAngle; // Angle of rotation for the quads <add> <add> float z = -5.0f; <add> <add> float lightAmbient[] = {0.5f, 0.5f, 0.5f, 1.0f}; <add> float lightDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f}; <add> float lightPosition[] = {0.0f, 0.0f, 2.0f, 1.0f}; <add> int fogMode[] = {GL11.GL_EXP, GL11.GL_EXP2, GL11.GL_LINEAR}; <add> int fogfilter = 0; // Change this to see the 3 different types of fog effects! <add> float fogColor[] = {0.5f, 0.5f, 0.5f, 1.0f}; <add> <add> public void run() { <add> <add> createWindow(); <add> getDelta(); // Initialise delta timer <add> initGL(); <add> <add> while (!closeRequested) { <add> pollInput(); <add> updateLogic(getDelta()); <add> renderGL(); <add> <add> Display.update(); <add> } <add> <add> cleanup(); <add> } <add> <add> private void initGL() { <add> <add> /* OpenGL */ <add> int width = Display.getDisplayMode().getWidth(); <add> int height = Display.getDisplayMode().getHeight(); <add> <add> GL11.glViewport(0, 0, width, height); // Reset The Current Viewport <add> GL11.glMatrixMode(GL11.GL_PROJECTION); // Select The Projection Matrix <add> GL11.glLoadIdentity(); // Reset The Projection Matrix <add> GLU.gluPerspective(45.0f, ((float) width / (float) height), 0.1f, 100.0f); // Calculate The Aspect Ratio Of The Window <add> GL11.glMatrixMode(GL11.GL_MODELVIEW); // Select The Modelview Matrix <add> GL11.glLoadIdentity(); // Reset The Modelview Matrix <add> <add> GL11.glShadeModel(GL11.GL_SMOOTH); // Enables Smooth Shading <add> GL11.glEnable(GL11.GL_TEXTURE_2D); // Enable Texture Mapping <add> GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); // Set The Blending Function For Translucency <add> GL11.glClearColor(0.5f, 0.5f, 0.5f, 0.0f); // This Will Clear The Background Color To Black <add> GL11.glClearDepth(1.0f); // Depth Buffer Setup <add> GL11.glEnable(GL11.GL_DEPTH_TEST); // Enables Depth Testing <add> GL11.glDepthFunc(GL11.GL_LESS); // The Type Of Depth Test To Do <add> GL11.glShadeModel(GL11.GL_SMOOTH); // Enables Smooth Color Shading <add> GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST); // Really Nice Perspective Calculations <add> <add> ByteBuffer temp = ByteBuffer.allocateDirect(16); <add> temp.order(ByteOrder.nativeOrder()); <add> temp.asFloatBuffer().put(lightAmbient).flip(); <add> GL11.glLight(GL11.GL_LIGHT1, GL11.GL_AMBIENT, temp.asFloatBuffer()); // Setup The Ambient Light <add> temp.asFloatBuffer().put(lightDiffuse).flip(); <add> GL11.glLight(GL11.GL_LIGHT1, GL11.GL_DIFFUSE, temp.asFloatBuffer()); // Setup The Diffuse Light <add> temp.asFloatBuffer().put(lightPosition).flip(); <add> GL11.glLight(GL11.GL_LIGHT1, GL11.GL_POSITION, temp.asFloatBuffer()); // Position The Light <add> GL11.glEnable(GL11.GL_LIGHT1); // Enable Light One <add> <add> GL11.glFogi(GL11.GL_FOG_MODE, fogMode[fogfilter]); // Fog Mode <add> temp.asFloatBuffer().put(fogColor).flip(); <add> GL11.glFog(GL11.GL_FOG_COLOR, temp.asFloatBuffer()); // Set Fog Color <add> GL11.glFogf(GL11.GL_FOG_DENSITY, 0.35f); // How Dense Will The Fog Be <add> GL11.glHint(GL11.GL_FOG_HINT, GL11.GL_DONT_CARE); // Fog Hint Value <add> GL11.glFogf(GL11.GL_FOG_START, 1.0f); // Fog Start Depth <add> GL11.glFogf(GL11.GL_FOG_END, 5.0f); // Fog End Depth <add> GL11.glEnable(GL11.GL_FOG); // Enables GL_FOG <add> Camera.create(); <add> } <add> <add> private void updateLogic(int delta) { <add> triangleAngle += 0.1f * delta; // Increase The Rotation Variable For The Triangles <add> quadAngle -= 0.05f * delta; // Decrease The Rotation Variable For The Quads <add> } <add> <add> <add> private void renderGL() { <add> <add> GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer <add> GL11.glLoadIdentity(); // Reset The View <add> GL11.glTranslatef(0.0f, 0.0f, -7.0f); // Move Right And Into The Screen <add> <add> Camera.apply(); <add> GL11.glBegin(GL11.GL_QUADS); // Start Drawing The Cube <add> GL11.glColor3f(0.0f, 1.0f, 0.0f); // Set The Color To Green <add> GL11.glVertex3f(1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Top) <add> GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Top) <add> GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top) <add> GL11.glVertex3f(1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top) <add> <add> GL11.glColor3f(1.0f, 0.5f, 0.0f); // Set The Color To Orange <add> GL11.glVertex3f(1.0f, -1.0f, 1.0f); // Top Right Of The Quad (Bottom) <add> GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Top Left Of The Quad (Bottom) <add> GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Bottom) <add> GL11.glVertex3f(1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Bottom) <add> <add> GL11.glColor3f(1.0f, 0.0f, 0.0f); // Set The Color To Red <add> GL11.glVertex3f(1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front) <add> GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front) <add> GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Quad (Front) <add> GL11.glVertex3f(1.0f, -1.0f, 1.0f); // Bottom Right Of The Quad (Front) <add> <add> GL11.glColor3f(1.0f, 1.0f, 0.0f); // Set The Color To Yellow <add> GL11.glVertex3f(1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Back) <add> GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Back) <add> GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Back) <add> GL11.glVertex3f(1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Back) <add> <add> GL11.glColor3f(0.0f, 0.0f, 1.0f); // Set The Color To Blue <add> GL11.glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left) <add> GL11.glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Left) <add> GL11.glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Left) <add> GL11.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Quad (Left) <add> <add> GL11.glColor3f(1.0f, 0.0f, 1.0f); // Set The Color To Violet <add> GL11.glVertex3f(1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Right) <add> GL11.glVertex3f(1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right) <add> GL11.glVertex3f(1.0f, -1.0f, 1.0f); // Bottom Left Of The Quad (Right) <add> GL11.glVertex3f(1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Right) <add> GL11.glEnd(); // Done Drawing The Quad <add> <add> } <add> <add> /** <add> * Poll Input <add> */ <add> public void pollInput() { <add> Camera.acceptInput(getDelta()); <add> // scroll through key events <add> while (Keyboard.next()) { <add> if (Keyboard.getEventKeyState()) { <add> if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) <add> closeRequested = true; <add> } <add> if (Display.isCloseRequested()) { <add> closeRequested = true; <add> } <add> } <add> } <add> <add> <add> /** <add> * Calculate how many milliseconds have passed <add> * since last frame. <add> * <add> * @return milliseconds passed since last frame <add> */ <add> public int getDelta() { <add> long time = (Sys.getTime() * 1000) / Sys.getTimerResolution(); <add> int delta = (int) (time - lastFrameTime); <add> lastFrameTime = time; <add> <add> return delta; <add> } <add> <add> private void createWindow() { <add> try { <add> Display.setDisplayMode(new DisplayMode(640, 480)); <add> Display.setVSyncEnabled(true); <add> Display.setTitle(windowTitle); <add> Display.create(); <add> } catch (LWJGLException e) { <add> Sys.alert("Error", "Initialization failed!\n\n" + e.getMessage()); <add> System.exit(0); <add> } <add> } <add> <add> /** <add> * Destroy and clean up resources <add> */ <add> private void cleanup() { <add> Display.destroy(); <add> } <add> <add> public static void main(String[] args) { <add> new FogCube().run(); <add> } <add> <add> public static class Camera { <add> public static float moveSpeed = 0.05f; <add> <add> private static float maxLook = 85; <add> <add> private static float mouseSensitivity = 0.05f; <add> <add> private static Vector3f pos; <add> private static Vector3f rotation; <add> <add> public static void create() { <add> pos = new Vector3f(0, 0, 0); <add> rotation = new Vector3f(0, 0, 0); <add> } <add> <add> public static void apply() { <add> if (rotation.y / 360 > 1) { <add> rotation.y -= 360; <add> } else if (rotation.y / 360 < -1) { <add> rotation.y += 360; <add> } <add> <add> //System.out.println(rotation); <add> GL11.glRotatef(rotation.x, 1, 0, 0); <add> GL11.glRotatef(rotation.y, 0, 1, 0); <add> GL11.glRotatef(rotation.z, 0, 0, 1); <add> GL11.glTranslatef(-pos.x, -pos.y, -pos.z); <add> } <add> <add> public static void acceptInput(float delta) { <add> //System.out.println("delta="+delta); <add> acceptInputRotate(delta); <add> acceptInputMove(delta); <add> } <add> <add> public static void acceptInputRotate(float delta) { <add> if (Mouse.isInsideWindow() && Mouse.isButtonDown(0)) { <add> float mouseDX = Mouse.getDX(); <add> float mouseDY = -Mouse.getDY(); <add> //System.out.println("DX/Y: " + mouseDX + " " + mouseDY); <add> rotation.y += mouseDX * mouseSensitivity * delta; <add> rotation.x += mouseDY * mouseSensitivity * delta; <add> rotation.x = Math.max(-maxLook, Math.min(maxLook, rotation.x)); <add> } <add> } <add> <add> public static void acceptInputMove(float delta) { <add> boolean keyUp = Keyboard.isKeyDown(Keyboard.KEY_W); <add> boolean keyDown = Keyboard.isKeyDown(Keyboard.KEY_S); <add> boolean keyRight = Keyboard.isKeyDown(Keyboard.KEY_D); <add> boolean keyLeft = Keyboard.isKeyDown(Keyboard.KEY_A); <add> boolean keyFast = Keyboard.isKeyDown(Keyboard.KEY_Q); <add> boolean keySlow = Keyboard.isKeyDown(Keyboard.KEY_E); <add> boolean keyFlyUp = Keyboard.isKeyDown(Keyboard.KEY_SPACE); <add> boolean keyFlyDown = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT); <add> <add> float speed; <add> <add> if (keyFast) { <add> speed = moveSpeed * 5; <add> } else if (keySlow) { <add> speed = moveSpeed / 2; <add> } else { <add> speed = moveSpeed; <add> } <add> <add> speed *= delta; <add> <add> if (keyFlyUp) { <add> pos.y += speed; <add> } <add> if (keyFlyDown) { <add> pos.y -= speed; <add> } <add> <add> if (keyDown) { <add> pos.x -= Math.sin(Math.toRadians(rotation.y)) * speed; <add> pos.z += Math.cos(Math.toRadians(rotation.y)) * speed; <add> } <add> if (keyUp) { <add> pos.x += Math.sin(Math.toRadians(rotation.y)) * speed; <add> pos.z -= Math.cos(Math.toRadians(rotation.y)) * speed; <add> } <add> if (keyLeft) { <add> pos.x += Math.sin(Math.toRadians(rotation.y - 90)) * speed; <add> pos.z -= Math.cos(Math.toRadians(rotation.y - 90)) * speed; <add> } <add> if (keyRight) { <add> pos.x += Math.sin(Math.toRadians(rotation.y + 90)) * speed; <add> pos.z -= Math.cos(Math.toRadians(rotation.y + 90)) * speed; <add> } <add> } <add> } <add>}
Java
apache-2.0
59b70c772b54b3c17082520d1be959584d9e1e8f
0
ServiceComb/java-chassis,ServiceComb/java-chassis
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.foundation.vertx.http; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.AsyncContext; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.Part; import javax.ws.rs.core.HttpHeaders; import org.apache.servicecomb.foundation.common.http.HttpUtils; import org.apache.servicecomb.foundation.vertx.stream.BufferInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.MultiMap; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.net.SocketAddress; import io.vertx.ext.web.FileUpload; import io.vertx.ext.web.RoutingContext; // wrap vertx http request to Servlet http request public class VertxServerRequestToHttpServletRequest extends AbstractHttpServletRequest { private static final Logger LOGGER = LoggerFactory.getLogger(VertxServerRequestToHttpServletRequest.class); private static final EmptyAsyncContext EMPTY_ASYNC_CONTEXT = new EmptyAsyncContext(); private RoutingContext context; private HttpServerRequest vertxRequest; private Cookie[] cookies; private ServletInputStream inputStream; private String path; private SocketAddress socketAddress; // cache from convert vertx parameters to servlet parameters private Map<String, String[]> parameterMap; private String characterEncoding; public VertxServerRequestToHttpServletRequest(RoutingContext context, String path) { this(context); this.path = path; } public VertxServerRequestToHttpServletRequest(RoutingContext context) { this.context = context; this.vertxRequest = context.request(); this.socketAddress = this.vertxRequest.remoteAddress(); super.setBodyBuffer(context.getBody()); } @Override public void setBodyBuffer(Buffer bodyBuffer) { super.setBodyBuffer(bodyBuffer); context.setBody(bodyBuffer); this.inputStream = null; } @Override public String getContentType() { return this.vertxRequest.getHeader(HttpHeaders.CONTENT_TYPE); } @Override public Cookie[] getCookies() { if (cookies == null) { Set<io.vertx.ext.web.Cookie> vertxCookies = context.cookies(); Cookie tmpCookies[] = new Cookie[vertxCookies.size()]; int idx = 0; for (io.vertx.ext.web.Cookie oneVertxCookie : vertxCookies) { Cookie cookie = new Cookie(oneVertxCookie.getName(), oneVertxCookie.getValue()); tmpCookies[idx] = cookie; idx++; } cookies = tmpCookies; } return cookies; } @Override public String getParameter(String name) { if (parameterMap != null) { String[] values = parameterMap.get(name); return values == null ? null : values[0]; } return this.vertxRequest.getParam(name); } @Override public Enumeration<String> getParameterNames() { if (parameterMap != null) { return Collections.enumeration(parameterMap.keySet()); } return Collections.enumeration(this.vertxRequest.params().names()); } @Override public String[] getParameterValues(String name) { if (parameterMap != null) { return parameterMap.get(name); } List<String> paramList = this.vertxRequest.params().getAll(name); return paramList.toArray(new String[paramList.size()]); } @Override public Map<String, String[]> getParameterMap() { if (parameterMap == null) { Map<String, String[]> paramMap = new HashMap<>(); MultiMap map = this.vertxRequest.params(); for (String name : map.names()) { List<String> valueList = map.getAll(name); paramMap.put(name, map.getAll(name).toArray(new String[valueList.size()])); } parameterMap = paramMap; } return parameterMap; } @Override public void setParameter(String name, String value) { if (parameterMap != null) { parameterMap.put(name, new String[] {value}); return; } vertxRequest.params().set(name, value); } @Override public String getScheme() { return this.vertxRequest.scheme(); } @Override public String getRemoteAddr() { return this.socketAddress.host(); } @Override public String getRemoteHost() { return this.socketAddress.host(); } @Override public int getRemotePort() { return this.socketAddress.port(); } @Override public String getLocalAddr() { return this.vertxRequest.localAddress().host(); } @Override public int getLocalPort() { return this.vertxRequest.localAddress().port(); } @Override public String getHeader(String name) { return this.vertxRequest.getHeader(name); } @Override public Enumeration<String> getHeaders(String name) { return Collections.enumeration(this.vertxRequest.headers().getAll(name)); } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(vertxRequest.headers().names()); } @Override public int getIntHeader(String name) { String header = this.vertxRequest.getHeader(name); if (header == null) { return -1; } return Integer.parseInt(header); } @Override public String getMethod() { return this.vertxRequest.method().name(); } @Override public String getPathInfo() { return this.vertxRequest.path(); } @Override public String getQueryString() { return this.vertxRequest.query(); } @Override public String getRequestURI() { if (this.path == null) { this.path = vertxRequest.path(); } return this.path; } @Override public String getServletPath() { return this.getPathInfo(); } @Override public String getContextPath() { return ""; } @Override public ServletInputStream getInputStream() { if (inputStream == null) { inputStream = new BufferInputStream(context.getBody().getByteBuf()); } return inputStream; } @Override public AsyncContext getAsyncContext() { return EMPTY_ASYNC_CONTEXT; } @Override public Part getPart(String name) { Optional<FileUpload> upload = context.fileUploads() .stream() .filter(fileUpload -> fileUpload.name().equals(name)) .findFirst(); if (!upload.isPresent()) { LOGGER.debug("No such file with name: {}.", name); return null; } final FileUpload fileUpload = upload.get(); return new FileUploadPart(fileUpload); } @Override public Collection<Part> getParts() { Set<FileUpload> fileUploads = context.fileUploads(); return fileUploads.stream().map(FileUploadPart::new).collect(Collectors.toList()); } public RoutingContext getContext() { return context; } @Override public String getCharacterEncoding() { if (characterEncoding == null) { characterEncoding = HttpUtils.getCharsetFromContentType(getContentType()); } return characterEncoding; } }
foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/http/VertxServerRequestToHttpServletRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.foundation.vertx.http; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.AsyncContext; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.Part; import javax.ws.rs.core.HttpHeaders; import org.apache.servicecomb.foundation.common.http.HttpUtils; import org.apache.servicecomb.foundation.vertx.stream.BufferInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.MultiMap; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.net.SocketAddress; import io.vertx.ext.web.FileUpload; import io.vertx.ext.web.RoutingContext; // wrap vertx http request to Servlet http request public class VertxServerRequestToHttpServletRequest extends AbstractHttpServletRequest { private static final Logger LOGGER = LoggerFactory.getLogger(VertxServerRequestToHttpServletRequest.class); private static final EmptyAsyncContext EMPTY_ASYNC_CONTEXT = new EmptyAsyncContext(); private RoutingContext context; private HttpServerRequest vertxRequest; private Cookie[] cookies; private ServletInputStream inputStream; private String path; private SocketAddress socketAddress; // cache from convert vertx parameters to servlet parameters private Map<String, String[]> parameterMap; private String characterEncoding; public VertxServerRequestToHttpServletRequest(RoutingContext context, String path) { this(context); this.path = path; } public VertxServerRequestToHttpServletRequest(RoutingContext context) { this.context = context; this.vertxRequest = context.request(); this.socketAddress = this.vertxRequest.remoteAddress(); super.setBodyBuffer(context.getBody()); } @Override public void setBodyBuffer(Buffer bodyBuffer) { super.setBodyBuffer(bodyBuffer); context.setBody(bodyBuffer); } @Override public String getContentType() { return this.vertxRequest.getHeader(HttpHeaders.CONTENT_TYPE); } @Override public Cookie[] getCookies() { if (cookies == null) { Set<io.vertx.ext.web.Cookie> vertxCookies = context.cookies(); Cookie tmpCookies[] = new Cookie[vertxCookies.size()]; int idx = 0; for (io.vertx.ext.web.Cookie oneVertxCookie : vertxCookies) { Cookie cookie = new Cookie(oneVertxCookie.getName(), oneVertxCookie.getValue()); tmpCookies[idx] = cookie; idx++; } cookies = tmpCookies; } return cookies; } @Override public String getParameter(String name) { if (parameterMap != null) { String[] values = parameterMap.get(name); return values == null ? null : values[0]; } return this.vertxRequest.getParam(name); } @Override public Enumeration<String> getParameterNames() { if (parameterMap != null) { return Collections.enumeration(parameterMap.keySet()); } return Collections.enumeration(this.vertxRequest.params().names()); } @Override public String[] getParameterValues(String name) { if (parameterMap != null) { return parameterMap.get(name); } List<String> paramList = this.vertxRequest.params().getAll(name); return paramList.toArray(new String[paramList.size()]); } @Override public Map<String, String[]> getParameterMap() { if (parameterMap == null) { Map<String, String[]> paramMap = new HashMap<>(); MultiMap map = this.vertxRequest.params(); for (String name : map.names()) { List<String> valueList = map.getAll(name); paramMap.put(name, map.getAll(name).toArray(new String[valueList.size()])); } parameterMap = paramMap; } return parameterMap; } @Override public void setParameter(String name, String value) { if (parameterMap != null) { parameterMap.put(name, new String[] {value}); return; } vertxRequest.params().set(name, value); } @Override public String getScheme() { return this.vertxRequest.scheme(); } @Override public String getRemoteAddr() { return this.socketAddress.host(); } @Override public String getRemoteHost() { return this.socketAddress.host(); } @Override public int getRemotePort() { return this.socketAddress.port(); } @Override public String getLocalAddr() { return this.vertxRequest.localAddress().host(); } @Override public int getLocalPort() { return this.vertxRequest.localAddress().port(); } @Override public String getHeader(String name) { return this.vertxRequest.getHeader(name); } @Override public Enumeration<String> getHeaders(String name) { return Collections.enumeration(this.vertxRequest.headers().getAll(name)); } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(vertxRequest.headers().names()); } @Override public int getIntHeader(String name) { String header = this.vertxRequest.getHeader(name); if (header == null) { return -1; } return Integer.parseInt(header); } @Override public String getMethod() { return this.vertxRequest.method().name(); } @Override public String getPathInfo() { return this.vertxRequest.path(); } @Override public String getQueryString() { return this.vertxRequest.query(); } @Override public String getRequestURI() { if (this.path == null) { this.path = vertxRequest.path(); } return this.path; } @Override public String getServletPath() { return this.getPathInfo(); } @Override public String getContextPath() { return ""; } @Override public ServletInputStream getInputStream() { if (inputStream == null) { inputStream = new BufferInputStream(context.getBody().getByteBuf()); } return inputStream; } @Override public AsyncContext getAsyncContext() { return EMPTY_ASYNC_CONTEXT; } @Override public Part getPart(String name) { Optional<FileUpload> upload = context.fileUploads() .stream() .filter(fileUpload -> fileUpload.name().equals(name)) .findFirst(); if (!upload.isPresent()) { LOGGER.debug("No such file with name: {}.", name); return null; } final FileUpload fileUpload = upload.get(); return new FileUploadPart(fileUpload); } @Override public Collection<Part> getParts() { Set<FileUpload> fileUploads = context.fileUploads(); return fileUploads.stream().map(FileUploadPart::new).collect(Collectors.toList()); } public RoutingContext getContext() { return context; } @Override public String getCharacterEncoding() { if (characterEncoding == null) { characterEncoding = HttpUtils.getCharsetFromContentType(getContentType()); } return characterEncoding; } }
[SCB-1306] When VertxServerRequestToHttpServletRequest modified body,but get inputStream is from original body
foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/http/VertxServerRequestToHttpServletRequest.java
[SCB-1306] When VertxServerRequestToHttpServletRequest modified body,but get inputStream is from original body
<ide><path>oundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/http/VertxServerRequestToHttpServletRequest.java <ide> public void setBodyBuffer(Buffer bodyBuffer) { <ide> super.setBodyBuffer(bodyBuffer); <ide> context.setBody(bodyBuffer); <add> this.inputStream = null; <ide> } <ide> <ide> @Override
JavaScript
mit
077324ad605328f600a5aeac55d7929cda1617df
0
rowhit/jitsu,nodejitsu/jitsu,mbejda/jitsu
/* * logs.js: Commands related to user resources * * (C) 2010, Nodejitsu Inc. * */ var winston = require('winston'), jitsu = require('../../jitsu'); var logs = exports; logs.usage = [ 'The `jitsu logs` commands allow you to read the logs related to your app.', 'The default number of lines to show is 10.', '', 'Example usages:', 'jitsu logs all', 'jitsu logs all <number of lines to show>', 'jitsu logs app <app name>', 'jitsu logs app <app name> <number of lines to show>' ]; // // ### function all (callback) // #### @callback {function} Continuation to pass control to when complete. // Queries the log API and retrieves the logs for all of the user's apps // logs.all = function (amount, callback) { if (!callback) { callback = amount; amount = 10; } jitsu.logs.byUser(amount, function (err, apps) { if (err) { return callback(err); } if (apps.length === 0) { winston.warn('No logs for ' + jitsu.config.get('username').magenta + ' from timespan'); return callback(); } function sortLength (lname, rname) { var llength = apps[lname].data.length, rlength = apps[rname].data.length; if (llength === rlength) { return 0; } return llength > rlength ? 1 : -1; } Object.keys(apps).sort(sortLength).forEach(function (app) { putLogs(apps[app], app, amount, true); }); callback(); }); }; logs.all.usage = [ 'Print the logs from all applications. The default number of', 'lines to show is 10.', 'jits logs all <number of lines to show>', '', 'Example usage:', 'jitsu logs all', 'jitsu logs all 5' ]; // // ### function app (appName, callback) // #### @appName {string} the application to get the logs for // #### @callback {function} Continuation to pass control to when complete. // Queries the log API and retrieves the logs for the specified application // logs.app = function (appName, amount, callback) { // This is defined so that it can get called once all the arguments are // sorted out. var byApp = function (appName, amount, callback) { jitsu.logs.byApp(appName, amount, function (err, results) { if (err) { return callback(err); } putLogs(results, appName, amount); callback(); }); } // Handle missing arguments if (typeof appName === 'function') { callback = appName; jitsu.commands.commands.apps.list( function (err) { if (err) { return callback(err); } else { winston.error('You need to pass an app name'); jitsu.prompt.get(["app name"], function (err, result) { if (err) { // Handle the error winston.error('Prompt error:'); return callback(err); } else { // Plug in the app name and go appName = result["app name"]; byApp(appName, 10, callback); } }); } }); } else if (callback === undefined) { callback = amount; amount = 10; byApp(appName, amount, callback); } else { byApp(appName, amount, callback); } } logs.app.usage = [ 'Print the logs from specified application. The default number of', 'lines to show is 10.', 'jits logs app <app name> <number of lines to show>', '', 'Example usage:', 'jitsu logs app test', 'jitsu logs app test 40' ]; // // ### function putLogs (results, appName, amount, showApp) // #### @results {Object} Logs object to output. // #### @appName {string} App name associated with the log text. // #### @showApp {boolean} Value indicating if the app name should be output. // Parses, formats, and outputs the specified `results` to the user. // function putLogs (results, appName, amount, showApp) { if (results.data.length === 0) { return winston.warn('No logs for ' + appName.magenta + ' in specified timespan'); } var logged = 0, loglength = jitsu.config.get('loglength'); results.data.forEach(function (datum) { if (datum.json && datum.json.desc != null) { datum.json.desc.split('\n').forEach(function (line) { var prefix = showApp ? datum.timestamp.grey + ' ' + datum.json.app.magenta + ': ' : datum.timestamp.grey + ': ' if (line.length > 0 && logged < amount) { if (line.length > loglength) { line = line.substr(0, loglength - 3) + '...'; } winston.data(prefix + line); logged += 1; } }); } }); }
lib/jitsu/commands/logs.js
/* * logs.js: Commands related to user resources * * (C) 2010, Nodejitsu Inc. * */ var winston = require('winston'), jitsu = require('../../jitsu'); var logs = exports; logs.usage = [ 'The `jitsu logs` commands allow you to read the logs related to your app.', 'The default number of lines to show is 10.', '', 'Example usages:', 'jitsu logs all', 'jitsu logs all <number of lines to show>', 'jitsu logs app <app name>', 'jitsu logs app <app name> <number of lines to show>' ]; // // ### function all (callback) // #### @callback {function} Continuation to pass control to when complete. // Queries the log API and retrieves the logs for all of the user's apps // logs.all = function (amount, callback) { if (!callback) { callback = amount; amount = 10; } jitsu.logs.byUser(amount, function (err, apps) { if (err) { return callback(err); } if (apps.length === 0) { winston.warn('No logs for ' + jitsu.config.get('username').magenta + ' from timespan'); return callback(); } function sortLength (lname, rname) { var llength = apps[lname].data.length, rlength = apps[rname].data.length; if (llength === rlength) { return 0; } return llength > rlength ? 1 : -1; } Object.keys(apps).sort(sortLength).forEach(function (app) { putLogs(apps[app], app, amount, true); }); callback(); }); }; logs.all.usage = [ 'Print the logs from all applications. The default number of', 'lines to show is 10.', 'jits logs all <number of lines to show>', '', 'Example usage:', 'jitsu logs all', 'jitsu logs all 5' ]; // // ### function app (appName, callback) // #### @appName {string} the application to get the logs for // #### @callback {function} Continuation to pass control to when complete. // Queries the log API and retrieves the logs for the specified application // logs.app = function (appName, amount, callback) { // This is defined so that it can get called once all the arguments are // sorted out. var byApp = function (appName, amount, callback) { jitsu.logs.byApp(appName, amount, function (err, results) { if (err) { return callback(err); } putLogs(results, appName, amount); callback(); }); } // Handle missing arguments if (typeof appName === 'function') { callback = appName; jitsu.commands.commands.apps.list( function (err) { if (err) { return callback(err); } else { winston.error('You need to pass an app name'); jitsu.prompt.get(["app name"], function (err, result) { if (err) { // Handle the error winston.error('Prompt error:'); return callback(err); } else { // Plug in the app name and go appName = result["app name"]; byApp(appName, 10, callback); } }); } }); } else if (callback === undefined) { callback = amount; amount = 10; byApp(appName, amount, callback); } else { byApp(appName, amount, callback); } } logs.app.usage = [ 'Print the logs from specified application. The default number of', 'lines to show is 10.', 'jits logs app <app name> <number of lines to show>', '', 'Example usage:', 'jitsu logs app test', 'jitsu logs app test 40' ]; // // ### function putLogs (results, appName, amount, showApp) // #### @results {Object} Logs object to output. // #### @appName {string} App name associated with the log text. // #### @showApp {boolean} Value indicating if the app name should be output. // Parses, formats, and outputs the specified `results` to the user. // function putLogs (results, appName, amount, showApp) { if (results.data.length === 0) { return winston.warn('No logs for ' + appName.magenta + ' in specified timespan'); } var logged = 0, loglength = jitsu.config.get('loglength'); results.data.forEach(function (datum) { if (datum.json && data.json.desc != null) { datum.json.desc.split('\n').forEach(function (line) { var prefix = showApp ? datum.timestamp.grey + ' ' + datum.json.app.magenta + ': ' : datum.timestamp.grey + ': ' if (line.length > 0 && logged < amount) { if (line.length > loglength) { line = line.substr(0, loglength - 3) + '...'; } winston.data(prefix + line); logged += 1; } }); } }); }
[fix] Fix for bad log option name.
lib/jitsu/commands/logs.js
[fix] Fix for bad log option name.
<ide><path>ib/jitsu/commands/logs.js <ide> loglength = jitsu.config.get('loglength'); <ide> <ide> results.data.forEach(function (datum) { <del> if (datum.json && data.json.desc != null) { <add> if (datum.json && datum.json.desc != null) { <ide> datum.json.desc.split('\n').forEach(function (line) { <ide> var prefix = showApp <ide> ? datum.timestamp.grey + ' ' + datum.json.app.magenta + ': '
Java
apache-2.0
a9d577f75bb1baf70912b97932b122912b5521e8
0
kryptnostic/kodex
package com.kryptnostic.storage.v2.models; import java.util.UUID; import javax.annotation.concurrent.Immutable; @Immutable public class VersionedObjectKey { private final UUID objectId; private final long version; /** * This is transient because it is recalculated on the first call to hashcode() */ private transient int cachedHashCode; public VersionedObjectKey( UUID objectId, long version ) { this.objectId = objectId; this.version = version; } /** * @return the objectId */ public UUID getObjectId() { return objectId; } /** * @return the version */ public long getVersion() { return version; } public static VersionedObjectKey newRandomKey() { return new VersionedObjectKey( UUID.randomUUID(), 0L ); } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int code = cachedHashCode; if ( code == 0 ) { final int prime = 31; int result = 1; result = prime * result + ( ( objectId == null ) ? 0 : objectId.hashCode() ); result = prime * result + (int) ( version ^ ( version >>> 32 ) ); cachedHashCode = code = result; } return code; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; VersionedObjectKey other = (VersionedObjectKey) obj; if ( objectId == null ) { if ( other.objectId != null ) return false; } else if ( !objectId.equals( other.objectId ) ) return false; if ( version != other.version ) return false; return true; } @Override public String toString() { return new StringBuilder() .append( "{" ) .append( objectId ).append( "/" ).append( version ) .append( "}" ) .toString(); } }
src/main/java/com/kryptnostic/storage/v2/models/VersionedObjectKey.java
package com.kryptnostic.storage.v2.models; import java.util.UUID; import javax.annotation.concurrent.Immutable; @Immutable public class VersionedObjectKey { private final UUID objectId; private final long version; /** * This is transient because it is recalculated on the first call to hashcode() */ private transient int cachedHashCode; public VersionedObjectKey( UUID objectId, long version ) { this.objectId = objectId; this.version = version; } /** * @return the objectId */ public UUID getObjectId() { return objectId; } /** * @return the version */ public long getVersion() { return version; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int code = cachedHashCode; if ( code == 0 ) { final int prime = 31; int result = 1; result = prime * result + ( ( objectId == null ) ? 0 : objectId.hashCode() ); result = prime * result + (int) ( version ^ ( version >>> 32 ) ); cachedHashCode = code = result; } return code; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; VersionedObjectKey other = (VersionedObjectKey) obj; if ( objectId == null ) { if ( other.objectId != null ) return false; } else if ( !objectId.equals( other.objectId ) ) return false; if ( version != other.version ) return false; return true; } @Override public String toString() { return new StringBuilder() .append( "{" ) .append( objectId ).append( "/" ).append( version ) .append( "}" ) .toString(); } }
add a factory to versionedobjectkey for new random keys
src/main/java/com/kryptnostic/storage/v2/models/VersionedObjectKey.java
add a factory to versionedobjectkey for new random keys
<ide><path>rc/main/java/com/kryptnostic/storage/v2/models/VersionedObjectKey.java <ide> return version; <ide> } <ide> <del> /* (non-Javadoc) <add> public static VersionedObjectKey newRandomKey() { <add> return new VersionedObjectKey( UUID.randomUUID(), 0L ); <add> } <add> <add> /* <add> * (non-Javadoc) <ide> * @see java.lang.Object#hashCode() <ide> */ <ide> @Override
Java
apache-2.0
8b9f447917eb4c05e5f4cd7fe5c29b4a8d8fcca5
0
pmcs/parity,pmcs/parity,paritytrading/parity,paritytrading/parity
package com.paritytrading.parity.client; import com.paritytrading.parity.net.poe.POE; class Error { static final String HEADER = "" + "Order ID Reason\n" + "---------------- ------------------"; private final String orderId; private final byte reason; Error(Event.OrderRejected event) { orderId = event.orderId; reason = event.reason; } private String describe(byte reason) { switch (reason) { case POE.ORDER_REJECT_REASON_UNKNOWN_INSTRUMENT: return "Unknown instrument"; case POE.ORDER_REJECT_REASON_INVALID_PRICE: return "Invalid price"; case POE.ORDER_REJECT_REASON_INVALID_QUANTITY: return "Invalid quantity"; default: return "<unknown>"; } } String format() { return String.format("%16s %-18s", orderId, describe(reason)); } }
applications/client/src/main/java/com/paritytrading/parity/client/Error.java
package com.paritytrading.parity.client; import com.paritytrading.parity.net.poe.POE; class Error { static final String HEADER = "" + "Order ID Reason\n" + "---------------- ------------------"; private String orderId; private byte reason; Error(Event.OrderRejected event) { orderId = event.orderId; reason = event.reason; } private String describe(byte reason) { switch (reason) { case POE.ORDER_REJECT_REASON_UNKNOWN_INSTRUMENT: return "Unknown instrument"; case POE.ORDER_REJECT_REASON_INVALID_PRICE: return "Invalid price"; case POE.ORDER_REJECT_REASON_INVALID_QUANTITY: return "Invalid quantity"; default: return "<unknown>"; } } String format() { return String.format("%16s %-18s", orderId, describe(reason)); } }
parity-client: Use 'final' modifier in 'Error'
applications/client/src/main/java/com/paritytrading/parity/client/Error.java
parity-client: Use 'final' modifier in 'Error'
<ide><path>pplications/client/src/main/java/com/paritytrading/parity/client/Error.java <ide> "Order ID Reason\n" + <ide> "---------------- ------------------"; <ide> <del> private String orderId; <del> private byte reason; <add> private final String orderId; <add> private final byte reason; <ide> <ide> Error(Event.OrderRejected event) { <ide> orderId = event.orderId;
JavaScript
isc
445e7d266f417e7d7c277c5742ba41e580996de3
0
aaronlidman/osm-dash
'use strict'; const test = require('tape'); const isotrunc = require('../lib/isotrunc.js'); const fixtures = { '2018': { 'to': { 'year': '2018' }, 'unit': 'year', 'parent': '2018', 'sequence': undefined }, '2018-10': { 'to': { 'year': '2018', 'month': '2018-10' }, 'unit': 'month', 'parent': '2018', 'sequence': 10 }, '2018-10-20': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20' }, 'unit': 'day', 'parent': '2018-10', 'sequence': 20 }, '2018-10-20T12': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12' }, 'unit': 'hour', 'parent': '2018-10-20', 'sequence': 12 }, '2018-10-20T12:05': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12', 'minute': '2018-10-20T12:05' }, 'unit': 'minute', 'parent': '2018-10-20T12', 'sequence': 5 }, '2018-10-20T12:05:26': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12', 'minute': '2018-10-20T12:05' }, 'unit': 'minute', 'parent': '2018-10-20T12', 'sequence': 5 }, '2018-10-20T12:05:26.277Z': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12', 'minute': '2018-10-20T12:05' }, 'unit': 'minute', 'parent': '2018-10-20T12', 'sequence': 5 } }; test('throw error on no input', t => { try { isotrunc(); } catch (e) { t.equal(e.message, 'Must specify an ISOString to truncate'); } t.end(); }); test('isotrunc.to', t => { for (const fixture in fixtures) { for (const unit in fixtures[fixture].to) { t.equal(isotrunc(fixture).to(unit), fixtures[fixture].to[unit], fixture + ' to ' + unit); } } t.end(); }); test('isotrunc.unit', t => { for (const fixture in fixtures) { t.equal(isotrunc(fixture).unit(), fixtures[fixture].unit, fixture + ' unit'); } t.end(); }); test('isotrunc.parent', t => { for (const fixture in fixtures) { t.equal(isotrunc(fixture).parent(), fixtures[fixture].parent, fixture + ' parent'); } t.end(); }); test('isotrunc.sequence', t => { for (const fixture in fixtures) { t.equal(isotrunc(fixture).sequence(), fixtures[fixture].sequence, fixture + ' sequence'); } t.end(); }); test('isotrunc.parts', t => { for (const fixture in fixtures) { t.deepEqual(isotrunc(fixture).parts(), { parent: isotrunc(fixture).parent(), sequence: isotrunc(fixture).sequence() }, fixture + ' parts'); } t.end(); });
test/isotrunc.test.js
'use strict'; const test = require('tape'); const isotrunc = require('../lib/isotrunc.js'); const timeFixtures = { '2018': { 'to': { 'year': '2018' }, 'unit': 'year', 'parent': '2018', 'sequence': undefined }, '2018-10': { 'to': { 'year': '2018', 'month': '2018-10' }, 'unit': 'month', 'parent': '2018', 'sequence': 10 }, '2018-10-20': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20' }, 'unit': 'day', 'parent': '2018-10', 'sequence': 20 }, '2018-10-20T12': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12' }, 'unit': 'hour', 'parent': '2018-10-20', 'sequence': 12 }, '2018-10-20T12:05': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12', 'minute': '2018-10-20T12:05' }, 'unit': 'minute', 'parent': '2018-10-20T12', 'sequence': 5 }, '2018-10-20T12:05:26': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12', 'minute': '2018-10-20T12:05' }, 'unit': 'minute', 'parent': '2018-10-20T12', 'sequence': 5 }, '2018-10-20T12:05:26.277Z': { 'to': { 'year': '2018', 'month': '2018-10', 'day': '2018-10-20', 'hour': '2018-10-20T12', 'minute': '2018-10-20T12:05' }, 'unit': 'minute', 'parent': '2018-10-20T12', 'sequence': 5 } }; test('throw error on no input', t => { try { isotrunc(); } catch (e) { t.equal(e.message, 'Must specify an ISOString to truncate'); } t.end(); }); test('isotrunc.to', t => { for (const fixture in timeFixtures) { for (const unit in timeFixtures[fixture].to) { t.equal(isotrunc(fixture).to(unit), timeFixtures[fixture].to[unit], fixture + ' to ' + unit); } } t.end(); }); test('isotrunc.unit', t => { for (const fixture in timeFixtures) { t.equal(isotrunc(fixture).unit(), timeFixtures[fixture].unit, fixture + ' unit'); } t.end(); }); test('isotrunc.parent', t => { for (const fixture in timeFixtures) { t.equal(isotrunc(fixture).parent(), timeFixtures[fixture].parent, fixture + ' parent'); } t.end(); }); test('isotrunc.sequence', t => { for (const fixture in timeFixtures) { t.equal(isotrunc(fixture).sequence(), timeFixtures[fixture].sequence, fixture + ' sequence'); } t.end(); }); test('isotrunc.parts', t => { for (const fixture in timeFixtures) { t.deepEqual(isotrunc(fixture).parts(), { parent: isotrunc(fixture).parent(), sequence: isotrunc(fixture).sequence() }, fixture + ' parts'); } t.end(); });
A little simpler
test/isotrunc.test.js
A little simpler
<ide><path>est/isotrunc.test.js <ide> const test = require('tape'); <ide> const isotrunc = require('../lib/isotrunc.js'); <ide> <del>const timeFixtures = { <add>const fixtures = { <ide> '2018': { <ide> 'to': { <ide> 'year': '2018' <ide> }); <ide> <ide> test('isotrunc.to', t => { <del> for (const fixture in timeFixtures) { <del> for (const unit in timeFixtures[fixture].to) { <del> t.equal(isotrunc(fixture).to(unit), timeFixtures[fixture].to[unit], fixture + ' to ' + unit); <add> for (const fixture in fixtures) { <add> for (const unit in fixtures[fixture].to) { <add> t.equal(isotrunc(fixture).to(unit), fixtures[fixture].to[unit], fixture + ' to ' + unit); <ide> } <ide> } <ide> t.end(); <ide> }); <ide> <ide> test('isotrunc.unit', t => { <del> for (const fixture in timeFixtures) { <del> t.equal(isotrunc(fixture).unit(), timeFixtures[fixture].unit, fixture + ' unit'); <add> for (const fixture in fixtures) { <add> t.equal(isotrunc(fixture).unit(), fixtures[fixture].unit, fixture + ' unit'); <ide> } <ide> t.end(); <ide> }); <ide> <ide> test('isotrunc.parent', t => { <del> for (const fixture in timeFixtures) { <del> t.equal(isotrunc(fixture).parent(), timeFixtures[fixture].parent, fixture + ' parent'); <add> for (const fixture in fixtures) { <add> t.equal(isotrunc(fixture).parent(), fixtures[fixture].parent, fixture + ' parent'); <ide> } <ide> t.end(); <ide> }); <ide> <ide> test('isotrunc.sequence', t => { <del> for (const fixture in timeFixtures) { <del> t.equal(isotrunc(fixture).sequence(), timeFixtures[fixture].sequence, fixture + ' sequence'); <add> for (const fixture in fixtures) { <add> t.equal(isotrunc(fixture).sequence(), fixtures[fixture].sequence, fixture + ' sequence'); <ide> } <ide> t.end(); <ide> }); <ide> <ide> test('isotrunc.parts', t => { <del> for (const fixture in timeFixtures) { <add> for (const fixture in fixtures) { <ide> t.deepEqual(isotrunc(fixture).parts(), { <ide> parent: isotrunc(fixture).parent(), <ide> sequence: isotrunc(fixture).sequence()
Java
lgpl-2.1
cd2ddfacddbfa9496ebf5f8f23c91db84dcf1309
0
ggiudetti/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.widgets; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.file.CmsObject; import org.opencms.main.OpenCms; import org.opencms.workplace.CmsWorkplaceMessages; import org.opencms.xml.containerpage.I_CmsFormatterBean; import org.opencms.xml.types.CmsXmlDisplayFormatterValue; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; /** * Widget to select a type and formatter combination.<p> */ public class CmsDisplayTypeSelectWidget extends CmsSelectWidget { /** * Formatter option comparator, sorting by type name and rank.<p> */ class FormatterComparator implements Comparator<FormatterOption> { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(FormatterOption o1, FormatterOption o2) { return o1.m_typeName.equals(o2.m_typeName) ? o2.m_rank - o1.m_rank : o1.m_typeName.compareTo(o2.m_typeName); } } /** * Formatter select option.<p> */ class FormatterOption { /** The option key. */ String m_key; /** The option label. */ String m_label; /** The formatter rank. */ int m_rank; /** The type name. */ String m_typeName; /** * Constructor.<p> * * @param key the option key * @param typeName the type name * @param label the option label * @param rank the formatter rank */ FormatterOption(String key, String typeName, String label, int rank) { m_key = key; m_typeName = typeName; m_label = label; m_rank = rank; } } /** * @see org.opencms.widgets.CmsSelectWidget#newInstance() */ @Override public I_CmsWidget newInstance() { return new CmsDisplayTypeSelectWidget(); } /** * @see org.opencms.widgets.A_CmsSelectWidget#parseSelectOptions(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) */ @Override protected List<CmsSelectWidgetOption> parseSelectOptions( CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>(); List<FormatterOption> options = new ArrayList<FormatterOption>(); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(cms, getResourcePath(cms, widgetDialog)); if (config != null) { for (I_CmsFormatterBean formatter : config.getDisplayFormatters(cms)) { for (String typeName : formatter.getResourceTypeNames()) { String label = formatter.getNiceName() + " (" + CmsWorkplaceMessages.getResourceTypeName(wpLocale, typeName) + ")"; options.add( new FormatterOption( typeName + CmsXmlDisplayFormatterValue.SEPARATOR + formatter.getId(), typeName, label, formatter.getRank())); } } } Collections.sort(options, new FormatterComparator()); for (FormatterOption option : options) { result.add(new CmsSelectWidgetOption(option.m_key, false, option.m_label)); } return result; } }
src/org/opencms/widgets/CmsDisplayTypeSelectWidget.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.widgets; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.file.CmsObject; import org.opencms.main.OpenCms; import org.opencms.xml.containerpage.I_CmsFormatterBean; import org.opencms.xml.types.CmsXmlDisplayFormatterValue; import java.util.ArrayList; import java.util.List; /** * Widget to select a type and formatter combination.<p> */ public class CmsDisplayTypeSelectWidget extends CmsSelectWidget { /** * @see org.opencms.widgets.CmsSelectWidget#newInstance() */ @Override public I_CmsWidget newInstance() { return new CmsDisplayTypeSelectWidget(); } /** * @see org.opencms.widgets.A_CmsSelectWidget#parseSelectOptions(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) */ @Override protected List<CmsSelectWidgetOption> parseSelectOptions( CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>(); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(cms, getResourcePath(cms, widgetDialog)); if (config != null) { for (I_CmsFormatterBean formatter : config.getDisplayFormatters(cms)) { for (String typeName : formatter.getResourceTypeNames()) { result.add( new CmsSelectWidgetOption( typeName + CmsXmlDisplayFormatterValue.SEPARATOR + formatter.getId(), false, typeName + ": " + formatter.getNiceName())); } } } return result; } }
Changed formatter select option label and sorting.
src/org/opencms/widgets/CmsDisplayTypeSelectWidget.java
Changed formatter select option label and sorting.
<ide><path>rc/org/opencms/widgets/CmsDisplayTypeSelectWidget.java <ide> import org.opencms.ade.configuration.CmsADEConfigData; <ide> import org.opencms.file.CmsObject; <ide> import org.opencms.main.OpenCms; <add>import org.opencms.workplace.CmsWorkplaceMessages; <ide> import org.opencms.xml.containerpage.I_CmsFormatterBean; <ide> import org.opencms.xml.types.CmsXmlDisplayFormatterValue; <ide> <ide> import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.Comparator; <ide> import java.util.List; <add>import java.util.Locale; <ide> <ide> /** <ide> * Widget to select a type and formatter combination.<p> <ide> */ <ide> public class CmsDisplayTypeSelectWidget extends CmsSelectWidget { <add> <add> /** <add> * Formatter option comparator, sorting by type name and rank.<p> <add> */ <add> class FormatterComparator implements Comparator<FormatterOption> { <add> <add> /** <add> * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) <add> */ <add> public int compare(FormatterOption o1, FormatterOption o2) { <add> <add> return o1.m_typeName.equals(o2.m_typeName) ? o2.m_rank - o1.m_rank : o1.m_typeName.compareTo(o2.m_typeName); <add> } <add> } <add> <add> /** <add> * Formatter select option.<p> <add> */ <add> class FormatterOption { <add> <add> /** The option key. */ <add> String m_key; <add> <add> /** The option label. */ <add> String m_label; <add> <add> /** The formatter rank. */ <add> int m_rank; <add> <add> /** The type name. */ <add> String m_typeName; <add> <add> /** <add> * Constructor.<p> <add> * <add> * @param key the option key <add> * @param typeName the type name <add> * @param label the option label <add> * @param rank the formatter rank <add> */ <add> FormatterOption(String key, String typeName, String label, int rank) { <add> m_key = key; <add> m_typeName = typeName; <add> m_label = label; <add> m_rank = rank; <add> } <add> } <ide> <ide> /** <ide> * @see org.opencms.widgets.CmsSelectWidget#newInstance() <ide> I_CmsWidgetDialog widgetDialog, <ide> I_CmsWidgetParameter param) { <ide> <add> Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); <ide> List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>(); <add> List<FormatterOption> options = new ArrayList<FormatterOption>(); <ide> CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(cms, getResourcePath(cms, widgetDialog)); <ide> if (config != null) { <ide> for (I_CmsFormatterBean formatter : config.getDisplayFormatters(cms)) { <ide> for (String typeName : formatter.getResourceTypeNames()) { <del> result.add( <del> new CmsSelectWidgetOption( <add> String label = formatter.getNiceName() <add> + " (" <add> + CmsWorkplaceMessages.getResourceTypeName(wpLocale, typeName) <add> + ")"; <add> options.add( <add> new FormatterOption( <ide> typeName + CmsXmlDisplayFormatterValue.SEPARATOR + formatter.getId(), <del> false, <del> typeName + ": " + formatter.getNiceName())); <add> typeName, <add> label, <add> formatter.getRank())); <ide> } <ide> } <add> } <add> Collections.sort(options, new FormatterComparator()); <add> for (FormatterOption option : options) { <add> result.add(new CmsSelectWidgetOption(option.m_key, false, option.m_label)); <ide> } <ide> return result; <ide> }
JavaScript
agpl-3.0
717ca3390fedc4e56a0bf1e21c4bb8795e76b80c
0
ygol/odoo,dfang/odoo,bplancher/odoo,Elico-Corp/odoo_OCB,bplancher/odoo,microcom/odoo,microcom/odoo,hip-odoo/odoo,laslabs/odoo,storm-computers/odoo,Elico-Corp/odoo_OCB,ygol/odoo,Elico-Corp/odoo_OCB,Elico-Corp/odoo_OCB,hip-odoo/odoo,hip-odoo/odoo,hip-odoo/odoo,laslabs/odoo,ygol/odoo,dfang/odoo,storm-computers/odoo,bplancher/odoo,storm-computers/odoo,laslabs/odoo,bplancher/odoo,ygol/odoo,ygol/odoo,laslabs/odoo,bplancher/odoo,ygol/odoo,hip-odoo/odoo,laslabs/odoo,dfang/odoo,storm-computers/odoo,microcom/odoo,dfang/odoo,hip-odoo/odoo,laslabs/odoo,microcom/odoo,bplancher/odoo,ygol/odoo,storm-computers/odoo,storm-computers/odoo,Elico-Corp/odoo_OCB,dfang/odoo,microcom/odoo,dfang/odoo,microcom/odoo,Elico-Corp/odoo_OCB
odoo.define('base_import.import', function (require) { "use strict"; var ControlPanelMixin = require('web.ControlPanelMixin'); var core = require('web.core'); var ListView = require('web.ListView'); var Model = require('web.DataModel'); var session = require('web.session'); var Widget = require('web.Widget'); var QWeb = core.qweb; var _t = core._t; var _lt = core._lt; var StateMachine = window.StateMachine; /** * Safari does not deal well at all with raw JSON data being * returned. As a result, we're going to cheat by using a * pseudo-jsonp: instead of getting JSON data in the iframe, we're * getting a ``script`` tag which consists of a function call and * the returned data (the json dump). * * The function is an auto-generated name bound to ``window``, * which calls back into the callback provided here. * * @param {Object} form the form element (DOM or jQuery) to use in the call * @param {Object} attributes jquery.form attributes object * @param {Function} callback function to call with the returned data */ function jsonp(form, attributes, callback) { attributes = attributes || {}; var options = {jsonp: _.uniqueId('import_callback_')}; window[options.jsonp] = function () { delete window[options.jsonp]; callback.apply(null, arguments); }; if ('data' in attributes) { _.extend(attributes.data, options); } else { _.extend(attributes, {data: options}); } _.extend(attributes, { dataType: 'script', }); $(form).ajaxSubmit(attributes); } // if true, the 'Import', 'Export', etc... buttons will be shown ListView.prototype.defaults.import_enabled = true; ListView.include({ /** * Extend the render_buttons function of ListView by adding an event listener * on the import button. * @return {jQuery} the rendered buttons */ render_buttons: function() { var self = this; var add_button = false; if (!this.$buttons) { // Ensures that this is only done once add_button = true; } this._super.apply(this, arguments); // Sets this.$buttons if(add_button) { this.$buttons.on('click', '.o_list_button_import', function() { self.do_action({ type: 'ir.actions.client', tag: 'import', params: { model: self.dataset.model, // self.dataset.get_context() could be a compound? // not sure. action's context should be evaluated // so safer bet. Odd that timezone & al in it // though context: self.getParent().action.context, } }, { on_reverse_breadcrumb: function () { return self.reload(); }, }); return false; }); } return this.$buttons; } }); var DataImport = Widget.extend(ControlPanelMixin, { template: 'ImportView', opts: [ {name: 'encoding', label: _lt("Encoding:"), value: 'utf-8'}, {name: 'separator', label: _lt("Separator:"), value: ','}, {name: 'quoting', label: _lt("Quoting:"), value: '"'} ], events: { // 'change .oe_import_grid input': 'import_dryrun', 'change .oe_import_file': 'loaded_file', 'click .oe_import_file_reload': 'loaded_file', 'change input.oe_import_has_header, .oe_import_options input': 'settings_changed', 'click a.oe_import_toggle': function (e) { e.preventDefault(); var $el = $(e.target); ($el.next().length ? $el.next() : $el.parent().next()) .toggle(); }, 'click .oe_import_report a.oe_import_report_count': function (e) { e.preventDefault(); $(e.target).parent().toggleClass('oe_import_report_showmore'); }, 'click .oe_import_moreinfo_action a': function (e) { e.preventDefault(); // #data will parse the attribute on its own, we don't like // that sort of things var action = JSON.parse($(e.target).attr('data-action')); // FIXME: when JS-side clean_action action.views = _(action.views).map(function (view) { var id = view[0], type = view[1]; return [ id, type !== 'tree' ? type : action.view_type === 'form' ? 'list' : 'tree' ]; }); this.do_action(_.extend(action, { target: 'new', flags: { search_view: true, display_title: true, pager: true, list: {selectable: false} } })); }, }, init: function (parent, action) { this._super.apply(this, arguments); this.action_manager = parent; this.res_model = action.params.model; this.parent_context = action.params.context || {}; // import object id this.id = null; this.Import = new Model('base_import.import'); this.session = session; action.display_name = _t('Import a File'); // Displayed in the breadcrumbs }, start: function () { var self = this; this.setup_encoding_picker(); this.setup_separator_picker(); return $.when( this._super(), this.Import.call('create', [{ 'res_model': this.res_model }]).done(function (id) { self.id = id; self.$('input[name=import_id]').val(id); self.render_buttons(); var status = { breadcrumbs: self.action_manager.get_breadcrumbs(), cp_content: {$buttons: self.$buttons}, }; self.update_control_panel(status); }) ); }, render_buttons: function() { var self = this; this.$buttons = $(QWeb.render("ImportView.buttons", this)); this.$buttons.filter('.o_import_validate').on('click', this.validate.bind(this)); this.$buttons.filter('.o_import_import').on('click', this.import.bind(this)); this.$buttons.filter('.o_import_cancel').on('click', function(e) { e.preventDefault(); self.exit(); }); }, setup_encoding_picker: function () { this.$('input.oe_import_encoding').select2({ width: '160px', query: function (q) { var make = function (term) { return {id: term, text: term}; }; var suggestions = _.map( ('utf-8 utf-16 windows-1252 latin1 latin2 big5 ' + 'gb18030 shift_jis windows-1251 koir8_r').split(/\s+/), make); if (q.term) { suggestions.unshift(make(q.term)); } q.callback({results: suggestions}); }, initSelection: function (e, c) { return c({id: 'utf-8', text: 'utf-8'}); } }).select2('val', 'utf-8'); }, setup_separator_picker: function () { this.$('input.oe_import_separator').select2({ width: '160px', query: function (q) { var suggestions = [ {id: ',', text: _t("Comma")}, {id: ';', text: _t("Semicolon")}, {id: '\t', text: _t("Tab")}, {id: ' ', text: _t("Space")} ]; if (q.term) { suggestions.unshift({id: q.term, text: q.term}); } q.callback({results: suggestions}); }, initSelection: function (e, c) { return c({id: ',', text: _t("Comma")}); }, }); }, import_options: function () { var self = this; var options = { headers: this.$('input.oe_import_has_header').prop('checked') }; _(this.opts).each(function (opt) { options[opt.name] = self.$('input.oe_import_' + opt.name).val(); }); return options; }, //- File & settings change section onfile_loaded: function () { this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', true); if (!this.$('input.oe_import_file').val()) { return; } this.$el.removeClass('oe_import_preview oe_import_error'); var import_toggle = false; var file = this.$('input.oe_import_file')[0].files[0]; // some platforms send text/csv, application/csv, or other things if Excel is prevent if ((file.type && _.last(file.type.split('/')) === "csv") || ( _.last(file.name.split('.')) === "csv")) { import_toggle = true; } this.$el.find('.oe_import_toggle').toggle(import_toggle); jsonp(this.$el, { url: '/base_import/set_file' }, this.proxy('settings_changed')); }, onpreviewing: function () { var self = this; this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', true); this.$el.addClass('oe_import_with_file'); // TODO: test that write // succeeded? this.$el.removeClass('oe_import_preview_error oe_import_error'); this.$el.toggleClass( 'oe_import_noheaders', !this.$('input.oe_import_has_header').prop('checked')); this.Import.call( 'parse_preview', [this.id, this.import_options()]) .done(function (result) { var signal = result.error ? 'preview_failed' : 'preview_succeeded'; self[signal](result); }); }, onpreview_error: function (event, from, to, result) { this.$('.oe_import_options').show(); this.$('.oe_import_file_reload').prop('disabled', false); this.$el.addClass('oe_import_preview_error oe_import_error'); this.$('.oe_import_error_report').html( QWeb.render('ImportView.preview.error', result)); }, onpreview_success: function (event, from, to, result) { this.$buttons.filter('.o_import_import').removeClass('btn-primary'); this.$buttons.filter('.o_import_validate').addClass('btn-primary'); this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', false); this.$el.addClass('oe_import_preview'); this.$('.oe_import_grid').html(QWeb.render('ImportView.preview', result)); if (result.headers.length === 1) { this.$('.oe_import_options').show(); this.onresults(null, null, null, [{ type: 'warning', message: _t("A single column was found in the file, this often means the file separator is incorrect") }]); } var $fields = this.$('.oe_import_fields input'); this.render_fields_matches(result, $fields); var data = this.generate_fields_completion(result); var item_finder = function (id, items) { items = items || data; for (var i=0; i < items.length; ++i) { var item = items[i]; if (item.id === id) { return item; } var val; if (item.children && (val = item_finder(id, item.children))) { return val; } } return ''; }; $fields.select2({ allowClear: true, minimumInputLength: 0, data: data, initSelection: function (element, callback) { var default_value = element.val(); if (!default_value) { callback(''); return; } callback(item_finder(default_value)); }, placeholder: _t('Don\'t import'), width: 'resolve', dropdownCssClass: 'oe_import_selector' }); }, generate_fields_completion: function (root) { var basic = []; var regulars = []; var o2m = []; function traverse(field, ancestors, collection) { var subfields = field.fields; var field_path = ancestors.concat(field); var label = _(field_path).pluck('string').join(' / '); var id = _(field_path).pluck('name').join('/'); // If non-relational, m2o or m2m, collection is regulars if (!collection) { if (field.name === 'id') { collection = basic; } else if (_.isEmpty(subfields) || _.isEqual(_.pluck(subfields, 'name'), ['id', '.id'])) { collection = regulars; } else { collection = o2m; } } collection.push({ id: id, text: label, required: field.required }); for(var i=0, end=subfields.length; i<end; ++i) { traverse(subfields[i], field_path, collection); } } _(root.fields).each(function (field) { traverse(field, []); }); var cmp = function (field1, field2) { return field1.text.localeCompare(field2.text); }; regulars.sort(cmp); o2m.sort(cmp); return basic.concat([ { text: _t("Normal Fields"), children: regulars }, { text: _t("Relation Fields"), children: o2m } ]); }, render_fields_matches: function (result, $fields) { if (_(result.matches).isEmpty()) { return; } $fields.each(function (index, input) { var match = result.matches[index]; if (!match) { return; } var current_field = result; input.value = _(match).chain() .map(function (name) { // WARNING: does both mapping and folding (over the // ``field`` iterator variable) return current_field = _(current_field.fields).find(function (subfield) { return subfield.name === name; }); }) .pluck('name') .value() .join('/'); }); }, //- import itself call_import: function (kwargs) { var fields = this.$('.oe_import_fields input.oe_import_match_field').map(function (index, el) { return $(el).select2('val') || false; }).get(); var tracking_disable = 'tracking_disable' in kwargs ? kwargs.tracking_disable : !this.$('#oe_import_tracking').prop('checked') delete kwargs.tracking_disable kwargs.context = _.extend( {}, this.parent_context, {tracking_disable: tracking_disable} ); return this.Import.call('do', [this.id, fields, this.import_options()], kwargs) .then(undefined, function (error, event) { // In case of unexpected exception, convert // "JSON-RPC error" to an import failure, and // prevent default handling (warning dialog) if (event) { event.preventDefault(); } return $.when([{ type: 'error', record: false, message: error.data.arguments && error.data.arguments[1] || error.message, }]); }) ; }, onvalidate: function () { return this.call_import({ dryrun: true, tracking_disable: true }) .done(this.proxy('validated')); }, onimport: function () { var self = this; return this.call_import({ dryrun: false }).done(function (message) { if (!_.any(message, function (message) { return message.type === 'error'; })) { self['import_succeeded'](); return; } self['import_failed'](message); }); }, onimported: function () { this.exit(); }, exit: function () { this.do_action({ type: 'ir.actions.client', tag: 'history_back' }); }, onresults: function (event, from, to, message) { var no_messages = _.isEmpty(message); this.$buttons.filter('.o_import_import').toggleClass('btn-primary', no_messages); this.$buttons.filter('.o_import_import').toggleClass('btn-default', !no_messages); this.$buttons.filter('.o_import_validate').toggleClass('btn-primary', !no_messages); this.$buttons.filter('.o_import_validate').toggleClass('btn-default', no_messages); if (no_messages) { message.push({ type: 'info', message: _t("Everything seems valid.") }); } // row indexes come back 0-indexed, spreadsheets // display 1-indexed. var offset = 1; // offset more if header if (this.import_options().headers) { offset += 1; } this.$el.addClass('oe_import_error'); this.$('.oe_import_error_report').html( QWeb.render('ImportView.error', { errors: _(message).groupBy('message'), at: function (rows) { var from = rows.from + offset; var to = rows.to + offset; if (from === to) { return _.str.sprintf(_t("at row %d"), from); } return _.str.sprintf(_t("between rows %d and %d"), from, to); }, more: function (n) { return _.str.sprintf(_t("(%d more)"), n); }, info: function (msg) { if (typeof msg === 'string') { return _.str.sprintf( '<div class="oe_import_moreinfo oe_import_moreinfo_message">%s</div>', _.str.escapeHTML(msg)); } if (msg instanceof Array) { return _.str.sprintf( '<div class="oe_import_moreinfo oe_import_moreinfo_choices">%s <ul>%s</ul></div>', _.str.escapeHTML(_t("Here are the possible values:")), _(msg).map(function (msg) { return '<li>' + _.str.escapeHTML(msg) + '</li>'; }).join('')); } // Final should be object, action descriptor return [ '<div class="oe_import_moreinfo oe_import_moreinfo_action">', _.str.sprintf('<a href="#" data-action="%s">', _.str.escapeHTML(JSON.stringify(msg))), _.str.escapeHTML( _t("Get all possible values")), '</a>', '</div>' ].join(''); }, })); }, }); core.action_registry.add('import', DataImport); // FSM-ize DataImport StateMachine.create({ target: DataImport.prototype, events: [ { name: 'loaded_file', from: ['none', 'file_loaded', 'preview_error', 'preview_success', 'results'], to: 'file_loaded' }, { name: 'settings_changed', from: ['file_loaded', 'preview_error', 'preview_success', 'results'], to: 'previewing' }, { name: 'preview_failed', from: 'previewing', to: 'preview_error' }, { name: 'preview_succeeded', from: 'previewing', to: 'preview_success' }, { name: 'validate', from: 'preview_success', to: 'validating' }, { name: 'validate', from: 'results', to: 'validating' }, { name: 'validated', from: 'validating', to: 'results' }, { name: 'import', from: ['preview_success', 'results'], to: 'importing' }, { name: 'import_succeeded', from: 'importing', to: 'imported'}, { name: 'import_failed', from: 'importing', to: 'results' } ] }); });
addons/base_import/static/src/js/import.js
odoo.define('base_import.import', function (require) { "use strict"; var ControlPanelMixin = require('web.ControlPanelMixin'); var core = require('web.core'); var ListView = require('web.ListView'); var Model = require('web.DataModel'); var session = require('web.session'); var Widget = require('web.Widget'); var QWeb = core.qweb; var _t = core._t; var _lt = core._lt; var StateMachine = window.StateMachine; /** * Safari does not deal well at all with raw JSON data being * returned. As a result, we're going to cheat by using a * pseudo-jsonp: instead of getting JSON data in the iframe, we're * getting a ``script`` tag which consists of a function call and * the returned data (the json dump). * * The function is an auto-generated name bound to ``window``, * which calls back into the callback provided here. * * @param {Object} form the form element (DOM or jQuery) to use in the call * @param {Object} attributes jquery.form attributes object * @param {Function} callback function to call with the returned data */ function jsonp(form, attributes, callback) { attributes = attributes || {}; var options = {jsonp: _.uniqueId('import_callback_')}; window[options.jsonp] = function () { delete window[options.jsonp]; callback.apply(null, arguments); }; if ('data' in attributes) { _.extend(attributes.data, options); } else { _.extend(attributes, {data: options}); } _.extend(attributes, { dataType: 'script', }); $(form).ajaxSubmit(attributes); } // if true, the 'Import', 'Export', etc... buttons will be shown ListView.prototype.defaults.import_enabled = true; ListView.include({ /** * Extend the render_buttons function of ListView by adding an event listener * on the import button. * @return {jQuery} the rendered buttons */ render_buttons: function() { var self = this; var add_button = false; if (!this.$buttons) { // Ensures that this is only done once add_button = true; } this._super.apply(this, arguments); // Sets this.$buttons if(add_button) { this.$buttons.on('click', '.o_list_button_import', function() { self.do_action({ type: 'ir.actions.client', tag: 'import', params: { model: self.dataset.model, // self.dataset.get_context() could be a compound? // not sure. action's context should be evaluated // so safer bet. Odd that timezone & al in it // though context: self.getParent().action.context, } }, { on_reverse_breadcrumb: function () { return self.reload(); }, }); return false; }); } return this.$buttons; } }); var DataImport = Widget.extend(ControlPanelMixin, { template: 'ImportView', opts: [ {name: 'encoding', label: _lt("Encoding:"), value: 'utf-8'}, {name: 'separator', label: _lt("Separator:"), value: ','}, {name: 'quoting', label: _lt("Quoting:"), value: '"'} ], events: { // 'change .oe_import_grid input': 'import_dryrun', 'change .oe_import_file': 'loaded_file', 'click .oe_import_file_reload': 'loaded_file', 'change input.oe_import_has_header, .oe_import_options input': 'settings_changed', 'click a.oe_import_toggle': function (e) { e.preventDefault(); var $el = $(e.target); ($el.next().length ? $el.next() : $el.parent().next()) .toggle(); }, 'click .oe_import_report a.oe_import_report_count': function (e) { e.preventDefault(); $(e.target).parent().toggleClass('oe_import_report_showmore'); }, 'click .oe_import_moreinfo_action a': function (e) { e.preventDefault(); // #data will parse the attribute on its own, we don't like // that sort of things var action = JSON.parse($(e.target).attr('data-action')); // FIXME: when JS-side clean_action action.views = _(action.views).map(function (view) { var id = view[0], type = view[1]; return [ id, type !== 'tree' ? type : action.view_type === 'form' ? 'list' : 'tree' ]; }); this.do_action(_.extend(action, { target: 'new', flags: { search_view: true, display_title: true, pager: true, list: {selectable: false} } })); }, }, init: function (parent, action) { this._super.apply(this, arguments); this.action_manager = parent; this.res_model = action.params.model; this.parent_context = action.params.context || {}; // import object id this.id = null; this.Import = new Model('base_import.import'); this.session = session; action.display_name = _t('Import a File'); // Displayed in the breadcrumbs }, start: function () { var self = this; this.setup_encoding_picker(); this.setup_separator_picker(); return $.when( this._super(), this.Import.call('create', [{ 'res_model': this.res_model }]).done(function (id) { self.id = id; self.$('input[name=import_id]').val(id); self.render_buttons(); var status = { breadcrumbs: self.action_manager.get_breadcrumbs(), cp_content: {$buttons: self.$buttons}, }; self.update_control_panel(status); }) ); }, render_buttons: function() { var self = this; this.$buttons = $(QWeb.render("ImportView.buttons", this)); this.$buttons.filter('.o_import_validate').on('click', this.validate.bind(this)); this.$buttons.filter('.o_import_import').on('click', this.import.bind(this)); this.$buttons.filter('.o_import_cancel').on('click', function(e) { e.preventDefault(); self.exit(); }); }, setup_encoding_picker: function () { this.$('input.oe_import_encoding').select2({ width: '160px', query: function (q) { var make = function (term) { return {id: term, text: term}; }; var suggestions = _.map( ('utf-8 utf-16 windows-1252 latin1 latin2 big5 ' + 'gb18030 shift_jis windows-1251 koir8_r').split(/\s+/), make); if (q.term) { suggestions.unshift(make(q.term)); } q.callback({results: suggestions}); }, initSelection: function (e, c) { return c({id: 'utf-8', text: 'utf-8'}); } }).select2('val', 'utf-8'); }, setup_separator_picker: function () { this.$('input.oe_import_separator').select2({ width: '160px', query: function (q) { var suggestions = [ {id: ',', text: _t("Comma")}, {id: ';', text: _t("Semicolon")}, {id: '\t', text: _t("Tab")}, {id: ' ', text: _t("Space")} ]; if (q.term) { suggestions.unshift({id: q.term, text: q.term}); } q.callback({results: suggestions}); }, initSelection: function (e, c) { return c({id: ',', text: _t("Comma")}); }, }); }, import_options: function () { var self = this; var options = { headers: this.$('input.oe_import_has_header').prop('checked') }; _(this.opts).each(function (opt) { options[opt.name] = self.$('input.oe_import_' + opt.name).val(); }); return options; }, //- File & settings change section onfile_loaded: function () { this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', true); if (!this.$('input.oe_import_file').val()) { return; } this.$el.removeClass('oe_import_preview oe_import_error'); var import_toggle = false; var file = this.$('input.oe_import_file')[0].files[0]; // some platforms send text/csv, application/csv, or other things if Excel is prevent if ((file.type && _.last(file.type.split('/')) === "csv") || ( _.last(file.name.split('.')) === "csv")) { import_toggle = true; } this.$el.find('.oe_import_toggle').toggle(import_toggle); jsonp(this.$el, { url: '/base_import/set_file' }, this.proxy('settings_changed')); }, onpreviewing: function () { var self = this; this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', true); this.$el.addClass('oe_import_with_file'); // TODO: test that write // succeeded? this.$el.removeClass('oe_import_preview_error oe_import_error'); this.$el.toggleClass( 'oe_import_noheaders', !this.$('input.oe_import_has_header').prop('checked')); this.Import.call( 'parse_preview', [this.id, this.import_options()]) .done(function (result) { var signal = result.error ? 'preview_failed' : 'preview_succeeded'; self[signal](result); }); }, onpreview_error: function (event, from, to, result) { this.$('.oe_import_options').show(); this.$('.oe_import_file_reload').prop('disabled', false); this.$el.addClass('oe_import_preview_error oe_import_error'); this.$('.oe_import_error_report').html( QWeb.render('ImportView.preview.error', result)); }, onpreview_success: function (event, from, to, result) { this.$buttons.filter('.o_import_import').removeClass('btn-primary'); this.$buttons.filter('.o_import_validate').addClass('btn-primary'); this.$buttons.filter('.o_import_button').add(this.$('.oe_import_file_reload')) .prop('disabled', false); this.$el.addClass('oe_import_preview'); this.$('.oe_import_grid').html(QWeb.render('ImportView.preview', result)); if (result.headers.length === 1) { this.$('.oe_import_options').show(); this.onresults(null, null, null, [{ type: 'warning', message: _t("A single column was found in the file, this often means the file separator is incorrect") }]); } var $fields = this.$('.oe_import_fields input'); this.render_fields_matches(result, $fields); var data = this.generate_fields_completion(result); var item_finder = function (id, items) { items = items || data; for (var i=0; i < items.length; ++i) { var item = items[i]; if (item.id === id) { return item; } var val; if (item.children && (val = item_finder(id, item.children))) { return val; } } return ''; }; $fields.select2({ allowClear: true, minimumInputLength: 0, data: data, initSelection: function (element, callback) { var default_value = element.val(); if (!default_value) { callback(''); return; } callback(item_finder(default_value)); }, placeholder: _t('Don\'t import'), width: 'resolve', dropdownCssClass: 'oe_import_selector' }); }, generate_fields_completion: function (root) { var basic = []; var regulars = []; var o2m = []; function traverse(field, ancestors, collection) { var subfields = field.fields; var field_path = ancestors.concat(field); var label = _(field_path).pluck('string').join(' / '); var id = _(field_path).pluck('name').join('/'); // If non-relational, m2o or m2m, collection is regulars if (!collection) { if (field.name === 'id') { collection = basic; } else if (_.isEmpty(subfields) || _.isEqual(_.pluck(subfields, 'name'), ['id', '.id'])) { collection = regulars; } else { collection = o2m; } } collection.push({ id: id, text: label, required: field.required }); for(var i=0, end=subfields.length; i<end; ++i) { traverse(subfields[i], field_path, collection); } } _(root.fields).each(function (field) { traverse(field, []); }); var cmp = function (field1, field2) { return field1.text.localeCompare(field2.text); }; regulars.sort(cmp); o2m.sort(cmp); return basic.concat([ { text: _t("Normal Fields"), children: regulars }, { text: _t("Relation Fields"), children: o2m } ]); }, render_fields_matches: function (result, $fields) { if (_(result.matches).isEmpty()) { return; } $fields.each(function (index, input) { var match = result.matches[index]; if (!match) { return; } var current_field = result; input.value = _(match).chain() .map(function (name) { // WARNING: does both mapping and folding (over the // ``field`` iterator variable) return current_field = _(current_field.fields).find(function (subfield) { return subfield.name === name; }); }) .pluck('name') .value() .join('/'); }); }, //- import itself call_import: function (kwargs) { var fields = this.$('.oe_import_fields input.oe_import_match_field').map(function (index, el) { return $(el).select2('val') || false; }).get(); var tracking_disable = 'tracking_disable' in kwargs ? kwargs.tracking_disable : !this.$('#oe_import_tracking').prop('checked') delete kwargs.tracking_disable kwargs.context = _.extend( {}, this.parent_context, {tracking_disable: tracking_disable} ); return this.Import.call('do', [this.id, fields, this.import_options()], kwargs) .then(undefined, function (error, event) { // In case of unexpected exception, convert // "JSON-RPC error" to an import failure, and // prevent default handling (warning dialog) if (event) { event.preventDefault(); } return $.when([{ type: 'error', record: false, message: error.data.arguments[1], }]); }) ; }, onvalidate: function () { return this.call_import({ dryrun: true, tracking_disable: true }) .done(this.proxy('validated')); }, onimport: function () { var self = this; return this.call_import({ dryrun: false }).done(function (message) { if (!_.any(message, function (message) { return message.type === 'error'; })) { self['import_succeeded'](); return; } self['import_failed'](message); }); }, onimported: function () { this.exit(); }, exit: function () { this.do_action({ type: 'ir.actions.client', tag: 'history_back' }); }, onresults: function (event, from, to, message) { var no_messages = _.isEmpty(message); this.$buttons.filter('.o_import_import').toggleClass('btn-primary', no_messages); this.$buttons.filter('.o_import_import').toggleClass('btn-default', !no_messages); this.$buttons.filter('.o_import_validate').toggleClass('btn-primary', !no_messages); this.$buttons.filter('.o_import_validate').toggleClass('btn-default', no_messages); if (no_messages) { message.push({ type: 'info', message: _t("Everything seems valid.") }); } // row indexes come back 0-indexed, spreadsheets // display 1-indexed. var offset = 1; // offset more if header if (this.import_options().headers) { offset += 1; } this.$el.addClass('oe_import_error'); this.$('.oe_import_error_report').html( QWeb.render('ImportView.error', { errors: _(message).groupBy('message'), at: function (rows) { var from = rows.from + offset; var to = rows.to + offset; if (from === to) { return _.str.sprintf(_t("at row %d"), from); } return _.str.sprintf(_t("between rows %d and %d"), from, to); }, more: function (n) { return _.str.sprintf(_t("(%d more)"), n); }, info: function (msg) { if (typeof msg === 'string') { return _.str.sprintf( '<div class="oe_import_moreinfo oe_import_moreinfo_message">%s</div>', _.str.escapeHTML(msg)); } if (msg instanceof Array) { return _.str.sprintf( '<div class="oe_import_moreinfo oe_import_moreinfo_choices">%s <ul>%s</ul></div>', _.str.escapeHTML(_t("Here are the possible values:")), _(msg).map(function (msg) { return '<li>' + _.str.escapeHTML(msg) + '</li>'; }).join('')); } // Final should be object, action descriptor return [ '<div class="oe_import_moreinfo oe_import_moreinfo_action">', _.str.sprintf('<a href="#" data-action="%s">', _.str.escapeHTML(JSON.stringify(msg))), _.str.escapeHTML( _t("Get all possible values")), '</a>', '</div>' ].join(''); }, })); }, }); core.action_registry.add('import', DataImport); // FSM-ize DataImport StateMachine.create({ target: DataImport.prototype, events: [ { name: 'loaded_file', from: ['none', 'file_loaded', 'preview_error', 'preview_success', 'results'], to: 'file_loaded' }, { name: 'settings_changed', from: ['file_loaded', 'preview_error', 'preview_success', 'results'], to: 'previewing' }, { name: 'preview_failed', from: 'previewing', to: 'preview_error' }, { name: 'preview_succeeded', from: 'previewing', to: 'preview_success' }, { name: 'validate', from: 'preview_success', to: 'validating' }, { name: 'validate', from: 'results', to: 'validating' }, { name: 'validated', from: 'validating', to: 'results' }, { name: 'import', from: ['preview_success', 'results'], to: 'importing' }, { name: 'import_succeeded', from: 'importing', to: 'imported'}, { name: 'import_failed', from: 'importing', to: 'results' } ] }); });
[FIX] base_import: error message During the import of a file, if the connection is closed (timeout, server shutdown...), a traceback appears. This is because `error.data.arguments` is not defined in this case. opw-682104
addons/base_import/static/src/js/import.js
[FIX] base_import: error message
<ide><path>ddons/base_import/static/src/js/import.js <ide> return $.when([{ <ide> type: 'error', <ide> record: false, <del> message: error.data.arguments[1], <add> message: error.data.arguments && error.data.arguments[1] || error.message, <ide> }]); <ide> }) ; <ide> },
Java
apache-2.0
2dceae8229e235e60e05a029f402d4cea1171685
0
francelabs/datafari,francelabs/datafari,francelabs/datafari,francelabs/datafari,francelabs/datafari
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.francelabs.datafari.transformation.metadatacleaner; import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.manifoldcf.agents.interfaces.IOutputAddActivity; import org.apache.manifoldcf.agents.interfaces.IOutputCheckActivity; import org.apache.manifoldcf.agents.interfaces.RepositoryDocument; import org.apache.manifoldcf.agents.interfaces.ServiceInterruption; import org.apache.manifoldcf.agents.system.Logging; import org.apache.manifoldcf.core.interfaces.ConfigParams; import org.apache.manifoldcf.core.interfaces.IHTTPOutput; import org.apache.manifoldcf.core.interfaces.IPostParameters; import org.apache.manifoldcf.core.interfaces.IThreadContext; import org.apache.manifoldcf.core.interfaces.ManifoldCFException; import org.apache.manifoldcf.core.interfaces.Specification; import org.apache.manifoldcf.core.interfaces.SpecificationNode; import org.apache.manifoldcf.core.interfaces.VersionContext; import com.francelabs.datafari.annotator.exception.RegexException; /** * This connector works as a transformation connector, but does nothing other than logging. * */ public class MetadataCleaner extends org.apache.manifoldcf.agents.transformation.BaseTransformationConnector { public static final String _rcsid = "@(#)$Id$"; private static final String EDIT_SPECIFICATION_JS = "editSpecification.js"; private static final String EDIT_SPECIFICATION_METADATA_CLEANER_HTML = "editSpecification_MetadataCleaner.html"; private static final String VIEW_SPECIFICATION_HTML = "viewSpecification.html"; protected static final String ACTIVITY_CLEAN = "clean"; protected static final String[] activitiesList = new String[] { ACTIVITY_CLEAN }; private static final Logger LOGGER = LogManager.getLogger(MetadataCleaner.class.getName()); /** * Connect. * * @param configParameters is the set of configuration parameters, which in this case describe the root directory. */ @Override public void connect(final ConfigParams configParameters) { super.connect(configParameters); } /** * Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { super.disconnect(); } /** * This method is periodically called for all connectors that are connected but not in active use. */ @Override public void poll() throws ManifoldCFException { } /** * This method is called to assess whether to count this connector instance should actually be counted as being connected. * * @return true if the connector instance is actually connected. */ @Override public boolean isConnected() { return true; } /** * Return a list of activities that this connector generates. The connector does NOT need to be connected before this method is called. * * @return the set of activities. */ @Override public String[] getActivitiesList() { return activitiesList; } /** * Output the configuration header section. This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any * javascript methods that might be needed by the configuration editing HTML. * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. * @param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputConfigurationHeader(final IThreadContext threadContext, final IHTTPOutput out, final Locale locale, final ConfigParams parameters, final List<String> tabsArray) throws ManifoldCFException, IOException { } /** * Output the configuration body section. This method is called in the body section of the connector's configuration page. Its purpose is to present the required form elements for editing. The coder * can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the form is "editconnection". * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. * @param tabName is the current tab name. */ @Override public void outputConfigurationBody(final IThreadContext threadContext, final IHTTPOutput out, final Locale locale, final ConfigParams parameters, final String tabName) throws ManifoldCFException, IOException { } /** * Process a configuration post. This method is called at the start of the connector's configuration page, whenever there is a possibility that form data for a connection has been posted. Its * purpose is to gather form information and modify the configuration parameters accordingly. The name of the posted form is "editconnection". * * @param threadContext is the local thread context. * @param variableContext is the set of variables available from the post, including binary file post information. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. * @return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page). */ @Override public String processConfigurationPost(final IThreadContext threadContext, final IPostParameters variableContext, final Locale locale, final ConfigParams parameters) throws ManifoldCFException { return null; } /** * View configuration. This method is called in the body section of the connector's view configuration page. Its purpose is to present the connection information to the user. The coder can presume * that the HTML that is output from this configuration will be within appropriate <html> and <body> tags. * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. */ @Override public void viewConfiguration(final IThreadContext threadContext, final IHTTPOutput out, final Locale locale, final ConfigParams parameters) throws ManifoldCFException, IOException { } /** * Get an output version string, given an output specification. The output version string is used to uniquely describe the pertinent details of the output specification and the configuration, to * allow the Connector Framework to determine whether a document will need to be output again. Note that the contents of the document cannot be considered by this method, and that a different * version string (defined in IRepositoryConnector) is used to describe the version of the actual document. * * This method presumes that the connector object has been configured, and it is thus able to communicate with the output data store should that be necessary. * * @param os is the current output specification for the job that is doing the crawling. * @return a string, of unlimited length, which uniquely describes output configuration and specification in such a way that if two such strings are equal, the document will not need to be sent * again to the output data store. */ @Override public VersionContext getPipelineDescription(final Specification os) throws ManifoldCFException, ServiceInterruption { final SpecPacker sp = new SpecPacker(os); return new VersionContext(sp.toPackedString(), params, os); } // We intercept checks pertaining to the document format and send modified // checks further down /** * Detect if a mime type is acceptable or not. This method is used to determine whether it makes sense to fetch a document in the first place. * * @param pipelineDescription is the document's pipeline version string, for this connection. * @param mimeType is the mime type of the document. * @param checkActivity is an object including the activities that can be performed by this method. * @return true if the mime type can be accepted by this connector. */ @Override public boolean checkMimeTypeIndexable(final VersionContext pipelineDescription, final String mimeType, final IOutputCheckActivity checkActivity) throws ManifoldCFException, ServiceInterruption { return true; } /** * Pre-determine whether a document (passed here as a File object) is acceptable or not. This method is used to determine whether a document needs to be actually transferred. This hook is provided * mainly to support search engines that only handle a small set of accepted file types. * * @param pipelineDescription is the document's pipeline version string, for this connection. * @param localFile is the local file to check. * @param checkActivity is an object including the activities that can be done by this method. * @return true if the file is acceptable, false if not. */ @Override public boolean checkDocumentIndexable(final VersionContext pipelineDescription, final File localFile, final IOutputCheckActivity checkActivity) throws ManifoldCFException, ServiceInterruption { // Document contents are not germane anymore, unless it looks like Tika // won't accept them. // Not sure how to check that... return true; } /** * Pre-determine whether a document's length is acceptable. This method is used to determine whether to fetch a document in the first place. * * @param pipelineDescription is the document's pipeline version string, for this connection. * @param length is the length of the document. * @param checkActivity is an object including the activities that can be done by this method. * @return true if the file is acceptable, false if not. */ @Override public boolean checkLengthIndexable(final VersionContext pipelineDescription, final long length, final IOutputCheckActivity checkActivity) throws ManifoldCFException, ServiceInterruption { // Always true return true; } /** * Add (or replace) a document in the output data store using the connector. This method presumes that the connector object has been configured, and it is thus able to communicate with the output * data store should that be necessary. The OutputSpecification is *not* provided to this method, because the goal is consistency, and if output is done it must be consistent with the output * description, since that was what was partly used to determine if output should be taking place. So it may be necessary for this method to decode an output description string in order to determine * what should be done. * * @param documentURI is the URI of the document. The URI is presumed to be the unique identifier which the output data store will use to process and serve the document. This URI is * constructed by the repository connector which fetches the document, and is thus universal across all output connectors. * @param outputDescription is the description string that was constructed for this document by the getOutputDescription() method. * @param document is the document data to be processed (handed to the output data store). * @param authorityNameString is the name of the authority responsible for authorizing any access tokens passed in with the repository document. May be null. * @param activities is the handle to an object that the implementer of a pipeline connector may use to perform operations, such as logging processing activity, or sending a modified * document to the next stage in the pipeline. * @return the document status (accepted or permanently rejected). * @throws IOException only if there's a stream error reading the document data. */ @Override public int addOrReplaceDocumentWithException(final String documentURI, final VersionContext pipelineDescription, final RepositoryDocument document, final String authorityNameString, final IOutputAddActivity activities) throws ManifoldCFException, ServiceInterruption, IOException { final SpecPacker spec = new SpecPacker(pipelineDescription.getSpecification()); final long startTime = System.currentTimeMillis(); final Iterator<String> fieldsI = document.getFields(); // As we will replace the metadata with the "cleaned" ones, we need to store them in a separate hashmap final Map<String, Object[]> cleanMetadata = new HashMap<>(); try { // Iterate over all the metadata, delete them and store their cleaned names and values in the cleanMetadata hashmap we just created while (fieldsI.hasNext()) { final String fieldName = fieldsI.next(); // We only keep the metadata if its name is not null if (fieldName != null && !fieldName.isEmpty()) { String cleanFieldName = fieldName; // We apply the all name regex on the name for (final String nameRegex : spec.nameCleaners.keySet()) { cleanFieldName = fieldName.replaceAll(nameRegex, spec.nameCleaners.get(nameRegex)); } // We apply the value regex on the values that are string values Object[] fieldValues = document.getField(fieldName); if (fieldValues instanceof String[]) { for (final String valueRegex : spec.valueCleaners.keySet()) { for (int i = 0; i < fieldValues.length; i++) { if (fieldValues[i] != null) { final String cleanValue = fieldValues[i].toString().replaceAll(valueRegex, spec.valueCleaners.get(valueRegex)); fieldValues[i] = cleanValue; } else { fieldValues[i] = ""; } } } } else if (fieldValues != null && fieldValues.length > 0) { // For values that are not regex we remove all the null values final Set<Integer> indexesToRemove = new HashSet<>(); for (int i = 0; i < fieldValues.length; i++) { if (fieldValues[i] == null) { indexesToRemove.add(i); } } if (fieldValues instanceof Date[]) { final Date[] cleanValues = new Date[fieldValues.length - indexesToRemove.size()]; int cleanValuesCpt = 0; for (int i = 0; i < fieldValues.length; i++) { if (!indexesToRemove.contains(i)) { cleanValues[cleanValuesCpt] = (Date) fieldValues[i]; cleanValuesCpt++; } } fieldValues = cleanValues; } else if (fieldValues instanceof Reader[]) { final Reader[] cleanValues = new Reader[fieldValues.length - indexesToRemove.size()]; int cleanValuesCpt = 0; for (int i = 0; i < fieldValues.length; i++) { if (!indexesToRemove.contains(i)) { cleanValues[cleanValuesCpt] = (Reader) fieldValues[i]; cleanValuesCpt++; } } fieldValues = cleanValues; } } // Store its "cleaned" equivalent only if fieldValues is not null and contains at least one element if (fieldValues != null && fieldValues.length > 0) { cleanMetadata.put(cleanFieldName, fieldValues); } else { LOGGER.warn("Field '" + cleanFieldName + "' of document '" + documentURI + "' ignored because it has null or empty value"); } } // Remove the current metadata fieldsI.remove(); } // Insert again the metadata with their "cleaned" equivalent for (final String cleanFieldName : cleanMetadata.keySet()) { final Object[] cleanValues = cleanMetadata.get(cleanFieldName); if (cleanValues instanceof String[]) { document.addField(cleanFieldName, (String[]) cleanValues); } else if (cleanValues instanceof Date[]) { document.addField(cleanFieldName, (Date[]) cleanValues); } else if (cleanValues instanceof Reader[]) { document.addField(cleanFieldName, (Reader[]) cleanValues); } } activities.recordActivity(startTime, ACTIVITY_CLEAN, document.getBinaryLength(), documentURI, "OK", ""); } catch (final Exception e) { activities.recordActivity(startTime, ACTIVITY_CLEAN, document.getBinaryLength(), documentURI, "KO", e.getMessage()); Logging.ingest.error("Unable to clean document " + documentURI, e); } return activities.sendDocument(documentURI, document); } /** * Obtain the name of the form check javascript method to call. * * @param connectionSequenceNumber is the unique number of this connection within the job. * @return the name of the form check javascript method. */ @Override public String getFormCheckJavascriptMethodName(final int connectionSequenceNumber) { return "s" + connectionSequenceNumber + "_checkSpecification"; } /** * Obtain the name of the form presave check javascript method to call. * * @param connectionSequenceNumber is the unique number of this connection within the job. * @return the name of the form presave check javascript method. */ @Override public String getFormPresaveCheckJavascriptMethodName(final int connectionSequenceNumber) { return "s" + connectionSequenceNumber + "_checkSpecificationForSave"; } protected static void fillInMetadataCleanerSpecification(final Map<String, Object> paramMap, final Specification os) { final Map<String, String> nameCleaners = new HashMap<>(); final Map<String, String> valueCleaners = new HashMap<>(); for (int i = 0; i < os.getChildCount(); i++) { final SpecificationNode sn = os.getChild(i); if (sn.getType().equals(MetadataCleanerConfig.NODE_NAMECLEANER)) { final String nameCleanerRegex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String nameCleanerValue = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); if (nameCleanerRegex != null) { nameCleaners.put(nameCleanerRegex, nameCleanerValue); } } else if (sn.getType().equals(MetadataCleanerConfig.NODE_VALUECLEANER)) { final String valueCleanerRegex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String valueCleanerValue = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); if (valueCleanerRegex != null) { valueCleaners.put(valueCleanerRegex, valueCleanerValue); } } } paramMap.put("NAMECLEANERS", nameCleaners); paramMap.put("VALUECLEANERS", valueCleaners); } /** * Output the specification header section. This method is called in the head section of a job page which has selected a pipeline connection of the current type. Its purpose is to add the required * tabs to the list, and to output any javascript methods that might be needed by the job editing HTML. * * @param out is the output to which any HTML should be sent. * @param locale is the preferred local of the output. * @param os is the current pipeline specification for this connection. * @param connectionSequenceNumber is the unique number of this connection within the job. * @param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputSpecificationHeader(final IHTTPOutput out, final Locale locale, final Specification os, final int connectionSequenceNumber, final List<String> tabsArray) throws ManifoldCFException, IOException { final Map<String, Object> paramMap = new HashMap<>(); paramMap.put("SEQNUM", Integer.toString(connectionSequenceNumber)); tabsArray.add(Messages.getString(locale, "MetadataCleaner.CleanerTabName")); // Fill in the specification header map, using data from all tabs. fillInMetadataCleanerSpecification(paramMap, os); Messages.outputResourceWithVelocity(out, locale, EDIT_SPECIFICATION_JS, paramMap); } /** * Output the specification body section. This method is called in the body section of a job page which has selected a pipeline connection of the current type. Its purpose is to present the required * form elements for editing. The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the form is * "editjob". * * @param out is the output to which any HTML should be sent. * @param locale is the preferred local of the output. * @param os is the current pipeline specification for this job. * @param connectionSequenceNumber is the unique number of this connection within the job. * @param actualSequenceNumber is the connection within the job that has currently been selected. * @param tabName is the current tab name. */ @Override public void outputSpecificationBody(final IHTTPOutput out, final Locale locale, final Specification os, final int connectionSequenceNumber, final int actualSequenceNumber, final String tabName) throws ManifoldCFException, IOException { final Map<String, Object> paramMap = new HashMap<>(); // Set the tab name paramMap.put("TABNAME", tabName); paramMap.put("SEQNUM", Integer.toString(connectionSequenceNumber)); paramMap.put("SELECTEDNUM", Integer.toString(actualSequenceNumber)); fillInMetadataCleanerSpecification(paramMap, os); Messages.outputResourceWithVelocity(out, locale, EDIT_SPECIFICATION_METADATA_CLEANER_HTML, paramMap); } /** * Process a specification post. This method is called at the start of job's edit or view page, whenever there is a possibility that form data for a connection has been posted. Its purpose is to * gather form information and modify the transformation specification accordingly. The name of the posted form is "editjob". * * @param variableContext contains the post data, including binary file-upload information. * @param locale is the preferred local of the output. * @param os is the current pipeline specification for this job. * @param connectionSequenceNumber is the unique number of this connection within the job. * @return null if all is well, or a string error message if there is an error that should prevent saving of the job (and cause a redirection to an error page). */ @Override public String processSpecificationPost(final IPostParameters variableContext, final Locale locale, final Specification os, final int connectionSequenceNumber) throws ManifoldCFException { final String seqPrefix = "s" + connectionSequenceNumber + "_"; String x; // name cleaners x = variableContext.getParameter(seqPrefix + "namecleaner_count"); if (x != null && x.length() > 0) { // About to gather the includefilter nodes, so get rid of the old ones. int i = 0; while (i < os.getChildCount()) { final SpecificationNode node = os.getChild(i); if (node.getType().equals(MetadataCleanerConfig.NODE_NAMECLEANER)) { os.removeChild(i); } else { i++; } } final int count = Integer.parseInt(x); i = 0; while (i < count) { final String prefix = seqPrefix + "namecleaner_"; final String suffix = "_" + Integer.toString(i); final String op = variableContext.getParameter(prefix + "op" + suffix); if (op == null || !op.equals("Delete")) { // Gather the namecleaner. final String regex = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_REGEX + suffix); final String value = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_VALUE + suffix); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_NAMECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } i++; } final String addop = variableContext.getParameter(seqPrefix + "namecleaner_op"); if (addop != null && addop.equals("Add")) { final String regex = variableContext.getParameter(seqPrefix + "namecleaner_regex"); final String value = variableContext.getParameter(seqPrefix + "namecleaner_value"); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_NAMECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } } // value cleaners x = variableContext.getParameter(seqPrefix + "valuecleaner_count"); if (x != null && x.length() > 0) { // About to gather the includefilter nodes, so get rid of the old ones. int i = 0; while (i < os.getChildCount()) { final SpecificationNode node = os.getChild(i); if (node.getType().equals(MetadataCleanerConfig.NODE_VALUECLEANER)) { os.removeChild(i); } else { i++; } } final int count = Integer.parseInt(x); i = 0; while (i < count) { final String prefix = seqPrefix + "valuecleaner_"; final String suffix = "_" + Integer.toString(i); final String op = variableContext.getParameter(prefix + "op" + suffix); if (op == null || !op.equals("Delete")) { // Gather the namecleaner. final String regex = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_REGEX + suffix); final String value = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_VALUE + suffix); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_VALUECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } i++; } final String addop = variableContext.getParameter(seqPrefix + "valuecleaner_op"); if (addop != null && addop.equals("Add")) { final String regex = variableContext.getParameter(seqPrefix + "valuecleaner_regex"); final String value = variableContext.getParameter(seqPrefix + "valuecleaner_value"); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_VALUECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } } return null; } /** * View specification. This method is called in the body section of a job's view page. Its purpose is to present the pipeline specification information to the user. The coder can presume that the * HTML that is output from this configuration will be within appropriate <html> and <body> tags. * * @param out is the output to which any HTML should be sent. * @param locale is the preferred local of the output. * @param connectionSequenceNumber is the unique number of this connection within the job. * @param os is the current pipeline specification for this job. */ @Override public void viewSpecification(final IHTTPOutput out, final Locale locale, final Specification os, final int connectionSequenceNumber) throws ManifoldCFException, IOException { final Map<String, Object> paramMap = new HashMap<>(); paramMap.put("SEQNUM", Integer.toString(connectionSequenceNumber)); fillInMetadataCleanerSpecification(paramMap, os); Messages.outputResourceWithVelocity(out, locale, VIEW_SPECIFICATION_HTML, paramMap); } protected static class SpecPacker { private final Map<String, String> nameCleaners = new HashMap<>(); private final Map<String, String> valueCleaners = new HashMap<>(); public SpecPacker(final Specification os) { for (int i = 0; i < os.getChildCount(); i++) { final SpecificationNode sn = os.getChild(i); if (sn.getType().equals(MetadataCleanerConfig.NODE_NAMECLEANER)) { final String regex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String value = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); nameCleaners.put(regex, value); } else if (sn.getType().equals(MetadataCleanerConfig.NODE_VALUECLEANER)) { final String regex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String value = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); valueCleaners.put(regex, value); } } } public String toPackedString() { final StringBuilder sb = new StringBuilder(); // TODO // packList(sb, nameCleaners, '+'); // packList(sb, valueCleaners, '+'); return sb.toString(); } } /** * Test if there is at least one regular expression that match with the provided sting * * @param regexList the list of regular expressions * @param str the string to test * @return the first matching regex found or null if no matching regex */ private String matchingRegex(final List<String> regexList, final String str) throws RegexException { for (final String regex : regexList) { try { final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(str); if (matcher.find()) { return regex; } } catch (final PatternSyntaxException e) { throw new RegexException(regex, "Invalid regular expression"); } } return null; } }
datafari-metadatacleaner-connector/src/main/java/com/francelabs/datafari/transformation/metadatacleaner/MetadataCleaner.java
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.francelabs.datafari.transformation.metadatacleaner; import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.manifoldcf.agents.interfaces.IOutputAddActivity; import org.apache.manifoldcf.agents.interfaces.IOutputCheckActivity; import org.apache.manifoldcf.agents.interfaces.RepositoryDocument; import org.apache.manifoldcf.agents.interfaces.ServiceInterruption; import org.apache.manifoldcf.agents.system.Logging; import org.apache.manifoldcf.core.interfaces.ConfigParams; import org.apache.manifoldcf.core.interfaces.IHTTPOutput; import org.apache.manifoldcf.core.interfaces.IPostParameters; import org.apache.manifoldcf.core.interfaces.IThreadContext; import org.apache.manifoldcf.core.interfaces.ManifoldCFException; import org.apache.manifoldcf.core.interfaces.Specification; import org.apache.manifoldcf.core.interfaces.SpecificationNode; import org.apache.manifoldcf.core.interfaces.VersionContext; import com.francelabs.datafari.annotator.exception.RegexException; /** * This connector works as a transformation connector, but does nothing other than logging. * */ public class MetadataCleaner extends org.apache.manifoldcf.agents.transformation.BaseTransformationConnector { public static final String _rcsid = "@(#)$Id$"; private static final String EDIT_SPECIFICATION_JS = "editSpecification.js"; private static final String EDIT_SPECIFICATION_METADATA_CLEANER_HTML = "editSpecification_MetadataCleaner.html"; private static final String VIEW_SPECIFICATION_HTML = "viewSpecification.html"; protected static final String ACTIVITY_CLEAN = "clean"; protected static final String[] activitiesList = new String[] { ACTIVITY_CLEAN }; /** * Connect. * * @param configParameters is the set of configuration parameters, which in this case describe the root directory. */ @Override public void connect(final ConfigParams configParameters) { super.connect(configParameters); } /** * Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { super.disconnect(); } /** * This method is periodically called for all connectors that are connected but not in active use. */ @Override public void poll() throws ManifoldCFException { } /** * This method is called to assess whether to count this connector instance should actually be counted as being connected. * * @return true if the connector instance is actually connected. */ @Override public boolean isConnected() { return true; } /** * Return a list of activities that this connector generates. The connector does NOT need to be connected before this method is called. * * @return the set of activities. */ @Override public String[] getActivitiesList() { return activitiesList; } /** * Output the configuration header section. This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any * javascript methods that might be needed by the configuration editing HTML. * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. * @param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputConfigurationHeader(final IThreadContext threadContext, final IHTTPOutput out, final Locale locale, final ConfigParams parameters, final List<String> tabsArray) throws ManifoldCFException, IOException { } /** * Output the configuration body section. This method is called in the body section of the connector's configuration page. Its purpose is to present the required form elements for editing. The coder * can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the form is "editconnection". * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. * @param tabName is the current tab name. */ @Override public void outputConfigurationBody(final IThreadContext threadContext, final IHTTPOutput out, final Locale locale, final ConfigParams parameters, final String tabName) throws ManifoldCFException, IOException { } /** * Process a configuration post. This method is called at the start of the connector's configuration page, whenever there is a possibility that form data for a connection has been posted. Its * purpose is to gather form information and modify the configuration parameters accordingly. The name of the posted form is "editconnection". * * @param threadContext is the local thread context. * @param variableContext is the set of variables available from the post, including binary file post information. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. * @return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page). */ @Override public String processConfigurationPost(final IThreadContext threadContext, final IPostParameters variableContext, final Locale locale, final ConfigParams parameters) throws ManifoldCFException { return null; } /** * View configuration. This method is called in the body section of the connector's view configuration page. Its purpose is to present the connection information to the user. The coder can presume * that the HTML that is output from this configuration will be within appropriate <html> and <body> tags. * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently exist, for this connection being configured. */ @Override public void viewConfiguration(final IThreadContext threadContext, final IHTTPOutput out, final Locale locale, final ConfigParams parameters) throws ManifoldCFException, IOException { } /** * Get an output version string, given an output specification. The output version string is used to uniquely describe the pertinent details of the output specification and the configuration, to * allow the Connector Framework to determine whether a document will need to be output again. Note that the contents of the document cannot be considered by this method, and that a different * version string (defined in IRepositoryConnector) is used to describe the version of the actual document. * * This method presumes that the connector object has been configured, and it is thus able to communicate with the output data store should that be necessary. * * @param os is the current output specification for the job that is doing the crawling. * @return a string, of unlimited length, which uniquely describes output configuration and specification in such a way that if two such strings are equal, the document will not need to be sent * again to the output data store. */ @Override public VersionContext getPipelineDescription(final Specification os) throws ManifoldCFException, ServiceInterruption { final SpecPacker sp = new SpecPacker(os); return new VersionContext(sp.toPackedString(), params, os); } // We intercept checks pertaining to the document format and send modified // checks further down /** * Detect if a mime type is acceptable or not. This method is used to determine whether it makes sense to fetch a document in the first place. * * @param pipelineDescription is the document's pipeline version string, for this connection. * @param mimeType is the mime type of the document. * @param checkActivity is an object including the activities that can be performed by this method. * @return true if the mime type can be accepted by this connector. */ @Override public boolean checkMimeTypeIndexable(final VersionContext pipelineDescription, final String mimeType, final IOutputCheckActivity checkActivity) throws ManifoldCFException, ServiceInterruption { return true; } /** * Pre-determine whether a document (passed here as a File object) is acceptable or not. This method is used to determine whether a document needs to be actually transferred. This hook is provided * mainly to support search engines that only handle a small set of accepted file types. * * @param pipelineDescription is the document's pipeline version string, for this connection. * @param localFile is the local file to check. * @param checkActivity is an object including the activities that can be done by this method. * @return true if the file is acceptable, false if not. */ @Override public boolean checkDocumentIndexable(final VersionContext pipelineDescription, final File localFile, final IOutputCheckActivity checkActivity) throws ManifoldCFException, ServiceInterruption { // Document contents are not germane anymore, unless it looks like Tika // won't accept them. // Not sure how to check that... return true; } /** * Pre-determine whether a document's length is acceptable. This method is used to determine whether to fetch a document in the first place. * * @param pipelineDescription is the document's pipeline version string, for this connection. * @param length is the length of the document. * @param checkActivity is an object including the activities that can be done by this method. * @return true if the file is acceptable, false if not. */ @Override public boolean checkLengthIndexable(final VersionContext pipelineDescription, final long length, final IOutputCheckActivity checkActivity) throws ManifoldCFException, ServiceInterruption { // Always true return true; } /** * Add (or replace) a document in the output data store using the connector. This method presumes that the connector object has been configured, and it is thus able to communicate with the output * data store should that be necessary. The OutputSpecification is *not* provided to this method, because the goal is consistency, and if output is done it must be consistent with the output * description, since that was what was partly used to determine if output should be taking place. So it may be necessary for this method to decode an output description string in order to determine * what should be done. * * @param documentURI is the URI of the document. The URI is presumed to be the unique identifier which the output data store will use to process and serve the document. This URI is * constructed by the repository connector which fetches the document, and is thus universal across all output connectors. * @param outputDescription is the description string that was constructed for this document by the getOutputDescription() method. * @param document is the document data to be processed (handed to the output data store). * @param authorityNameString is the name of the authority responsible for authorizing any access tokens passed in with the repository document. May be null. * @param activities is the handle to an object that the implementer of a pipeline connector may use to perform operations, such as logging processing activity, or sending a modified * document to the next stage in the pipeline. * @return the document status (accepted or permanently rejected). * @throws IOException only if there's a stream error reading the document data. */ @Override public int addOrReplaceDocumentWithException(final String documentURI, final VersionContext pipelineDescription, final RepositoryDocument document, final String authorityNameString, final IOutputAddActivity activities) throws ManifoldCFException, ServiceInterruption, IOException { final SpecPacker spec = new SpecPacker(pipelineDescription.getSpecification()); final long startTime = System.currentTimeMillis(); final Iterator<String> fieldsI = document.getFields(); // As we will replace the metadata with the "cleaned" ones, we need to store them in a separate hashmap final Map<String, Object[]> cleanMetadata = new HashMap<>(); try { // Iterate over all the metadata, delete them and store their cleaned names and values in the cleanMetadata hashmap we just created while (fieldsI.hasNext()) { final String fieldName = fieldsI.next(); String cleanFieldName = fieldName; for (final String nameRegex : spec.nameCleaners.keySet()) { cleanFieldName = fieldName.replaceAll(nameRegex, spec.nameCleaners.get(nameRegex)); } final Object[] fieldValues = document.getField(fieldName); if (fieldValues instanceof String[]) { for (final String valueRegex : spec.valueCleaners.keySet()) { for (int i = 0; i < fieldValues.length; i++) { final String cleanValue = fieldValues[i].toString().replaceAll(valueRegex, spec.valueCleaners.get(valueRegex)); fieldValues[i] = cleanValue; } } } // Remove the current metadata fieldsI.remove(); // Store its "cleaned" equivalent cleanMetadata.put(cleanFieldName, fieldValues); } // Insert again the metadata with their "cleaned" equivalent for (final String cleanFieldName : cleanMetadata.keySet()) { final Object[] cleanValues = cleanMetadata.get(cleanFieldName); if (cleanValues instanceof String[]) { document.addField(cleanFieldName, (String[]) cleanValues); } else if (cleanValues instanceof Date[]) { document.addField(cleanFieldName, (Date[]) cleanValues); } else if (cleanValues instanceof Reader[]) { document.addField(cleanFieldName, (Reader[]) cleanValues); } } activities.recordActivity(startTime, ACTIVITY_CLEAN, document.getBinaryLength(), documentURI, "OK", ""); } catch (final Exception e) { activities.recordActivity(startTime, ACTIVITY_CLEAN, document.getBinaryLength(), documentURI, "KO", e.getMessage()); Logging.ingest.error("Unable to clean document " + documentURI, e); } return activities.sendDocument(documentURI, document); } /** * Obtain the name of the form check javascript method to call. * * @param connectionSequenceNumber is the unique number of this connection within the job. * @return the name of the form check javascript method. */ @Override public String getFormCheckJavascriptMethodName(final int connectionSequenceNumber) { return "s" + connectionSequenceNumber + "_checkSpecification"; } /** * Obtain the name of the form presave check javascript method to call. * * @param connectionSequenceNumber is the unique number of this connection within the job. * @return the name of the form presave check javascript method. */ @Override public String getFormPresaveCheckJavascriptMethodName(final int connectionSequenceNumber) { return "s" + connectionSequenceNumber + "_checkSpecificationForSave"; } protected static void fillInMetadataCleanerSpecification(final Map<String, Object> paramMap, final Specification os) { final Map<String, String> nameCleaners = new HashMap<>(); final Map<String, String> valueCleaners = new HashMap<>(); for (int i = 0; i < os.getChildCount(); i++) { final SpecificationNode sn = os.getChild(i); if (sn.getType().equals(MetadataCleanerConfig.NODE_NAMECLEANER)) { final String nameCleanerRegex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String nameCleanerValue = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); if (nameCleanerRegex != null) { nameCleaners.put(nameCleanerRegex, nameCleanerValue); } } else if (sn.getType().equals(MetadataCleanerConfig.NODE_VALUECLEANER)) { final String valueCleanerRegex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String valueCleanerValue = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); if (valueCleanerRegex != null) { valueCleaners.put(valueCleanerRegex, valueCleanerValue); } } } paramMap.put("NAMECLEANERS", nameCleaners); paramMap.put("VALUECLEANERS", valueCleaners); } /** * Output the specification header section. This method is called in the head section of a job page which has selected a pipeline connection of the current type. Its purpose is to add the required * tabs to the list, and to output any javascript methods that might be needed by the job editing HTML. * * @param out is the output to which any HTML should be sent. * @param locale is the preferred local of the output. * @param os is the current pipeline specification for this connection. * @param connectionSequenceNumber is the unique number of this connection within the job. * @param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputSpecificationHeader(final IHTTPOutput out, final Locale locale, final Specification os, final int connectionSequenceNumber, final List<String> tabsArray) throws ManifoldCFException, IOException { final Map<String, Object> paramMap = new HashMap<>(); paramMap.put("SEQNUM", Integer.toString(connectionSequenceNumber)); tabsArray.add(Messages.getString(locale, "MetadataCleaner.CleanerTabName")); // Fill in the specification header map, using data from all tabs. fillInMetadataCleanerSpecification(paramMap, os); Messages.outputResourceWithVelocity(out, locale, EDIT_SPECIFICATION_JS, paramMap); } /** * Output the specification body section. This method is called in the body section of a job page which has selected a pipeline connection of the current type. Its purpose is to present the required * form elements for editing. The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the form is * "editjob". * * @param out is the output to which any HTML should be sent. * @param locale is the preferred local of the output. * @param os is the current pipeline specification for this job. * @param connectionSequenceNumber is the unique number of this connection within the job. * @param actualSequenceNumber is the connection within the job that has currently been selected. * @param tabName is the current tab name. */ @Override public void outputSpecificationBody(final IHTTPOutput out, final Locale locale, final Specification os, final int connectionSequenceNumber, final int actualSequenceNumber, final String tabName) throws ManifoldCFException, IOException { final Map<String, Object> paramMap = new HashMap<>(); // Set the tab name paramMap.put("TABNAME", tabName); paramMap.put("SEQNUM", Integer.toString(connectionSequenceNumber)); paramMap.put("SELECTEDNUM", Integer.toString(actualSequenceNumber)); fillInMetadataCleanerSpecification(paramMap, os); Messages.outputResourceWithVelocity(out, locale, EDIT_SPECIFICATION_METADATA_CLEANER_HTML, paramMap); } /** * Process a specification post. This method is called at the start of job's edit or view page, whenever there is a possibility that form data for a connection has been posted. Its purpose is to * gather form information and modify the transformation specification accordingly. The name of the posted form is "editjob". * * @param variableContext contains the post data, including binary file-upload information. * @param locale is the preferred local of the output. * @param os is the current pipeline specification for this job. * @param connectionSequenceNumber is the unique number of this connection within the job. * @return null if all is well, or a string error message if there is an error that should prevent saving of the job (and cause a redirection to an error page). */ @Override public String processSpecificationPost(final IPostParameters variableContext, final Locale locale, final Specification os, final int connectionSequenceNumber) throws ManifoldCFException { final String seqPrefix = "s" + connectionSequenceNumber + "_"; String x; // name cleaners x = variableContext.getParameter(seqPrefix + "namecleaner_count"); if (x != null && x.length() > 0) { // About to gather the includefilter nodes, so get rid of the old ones. int i = 0; while (i < os.getChildCount()) { final SpecificationNode node = os.getChild(i); if (node.getType().equals(MetadataCleanerConfig.NODE_NAMECLEANER)) { os.removeChild(i); } else { i++; } } final int count = Integer.parseInt(x); i = 0; while (i < count) { final String prefix = seqPrefix + "namecleaner_"; final String suffix = "_" + Integer.toString(i); final String op = variableContext.getParameter(prefix + "op" + suffix); if (op == null || !op.equals("Delete")) { // Gather the namecleaner. final String regex = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_REGEX + suffix); final String value = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_VALUE + suffix); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_NAMECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } i++; } final String addop = variableContext.getParameter(seqPrefix + "namecleaner_op"); if (addop != null && addop.equals("Add")) { final String regex = variableContext.getParameter(seqPrefix + "namecleaner_regex"); final String value = variableContext.getParameter(seqPrefix + "namecleaner_value"); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_NAMECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } } // value cleaners x = variableContext.getParameter(seqPrefix + "valuecleaner_count"); if (x != null && x.length() > 0) { // About to gather the includefilter nodes, so get rid of the old ones. int i = 0; while (i < os.getChildCount()) { final SpecificationNode node = os.getChild(i); if (node.getType().equals(MetadataCleanerConfig.NODE_VALUECLEANER)) { os.removeChild(i); } else { i++; } } final int count = Integer.parseInt(x); i = 0; while (i < count) { final String prefix = seqPrefix + "valuecleaner_"; final String suffix = "_" + Integer.toString(i); final String op = variableContext.getParameter(prefix + "op" + suffix); if (op == null || !op.equals("Delete")) { // Gather the namecleaner. final String regex = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_REGEX + suffix); final String value = variableContext.getParameter(prefix + MetadataCleanerConfig.ATTRIBUTE_VALUE + suffix); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_VALUECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } i++; } final String addop = variableContext.getParameter(seqPrefix + "valuecleaner_op"); if (addop != null && addop.equals("Add")) { final String regex = variableContext.getParameter(seqPrefix + "valuecleaner_regex"); final String value = variableContext.getParameter(seqPrefix + "valuecleaner_value"); final SpecificationNode node = new SpecificationNode(MetadataCleanerConfig.NODE_VALUECLEANER); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_REGEX, regex); node.setAttribute(MetadataCleanerConfig.ATTRIBUTE_VALUE, value); os.addChild(os.getChildCount(), node); } } return null; } /** * View specification. This method is called in the body section of a job's view page. Its purpose is to present the pipeline specification information to the user. The coder can presume that the * HTML that is output from this configuration will be within appropriate <html> and <body> tags. * * @param out is the output to which any HTML should be sent. * @param locale is the preferred local of the output. * @param connectionSequenceNumber is the unique number of this connection within the job. * @param os is the current pipeline specification for this job. */ @Override public void viewSpecification(final IHTTPOutput out, final Locale locale, final Specification os, final int connectionSequenceNumber) throws ManifoldCFException, IOException { final Map<String, Object> paramMap = new HashMap<>(); paramMap.put("SEQNUM", Integer.toString(connectionSequenceNumber)); fillInMetadataCleanerSpecification(paramMap, os); Messages.outputResourceWithVelocity(out, locale, VIEW_SPECIFICATION_HTML, paramMap); } protected static class SpecPacker { private final Map<String, String> nameCleaners = new HashMap<>(); private final Map<String, String> valueCleaners = new HashMap<>(); public SpecPacker(final Specification os) { for (int i = 0; i < os.getChildCount(); i++) { final SpecificationNode sn = os.getChild(i); if (sn.getType().equals(MetadataCleanerConfig.NODE_NAMECLEANER)) { final String regex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String value = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); nameCleaners.put(regex, value); } else if (sn.getType().equals(MetadataCleanerConfig.NODE_VALUECLEANER)) { final String regex = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_REGEX); final String value = sn.getAttributeValue(MetadataCleanerConfig.ATTRIBUTE_VALUE); valueCleaners.put(regex, value); } } } public String toPackedString() { final StringBuilder sb = new StringBuilder(); // TODO // packList(sb, nameCleaners, '+'); // packList(sb, valueCleaners, '+'); return sb.toString(); } } /** * Test if there is at least one regular expression that match with the provided sting * * @param regexList the list of regular expressions * @param str the string to test * @return the first matching regex found or null if no matching regex */ private String matchingRegex(final List<String> regexList, final String str) throws RegexException { for (final String regex : regexList) { try { final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(str); if (matcher.find()) { return regex; } } catch (final PatternSyntaxException e) { throw new RegexException(regex, "Invalid regular expression"); } } return null; } }
MetadataCleaner connector now removes empty or null metadata names/values
datafari-metadatacleaner-connector/src/main/java/com/francelabs/datafari/transformation/metadatacleaner/MetadataCleaner.java
MetadataCleaner connector now removes empty or null metadata names/values
<ide><path>atafari-metadatacleaner-connector/src/main/java/com/francelabs/datafari/transformation/metadatacleaner/MetadataCleaner.java <ide> import java.io.Reader; <ide> import java.util.Date; <ide> import java.util.HashMap; <add>import java.util.HashSet; <ide> import java.util.Iterator; <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <add>import java.util.Set; <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide> import java.util.regex.PatternSyntaxException; <ide> <add>import org.apache.logging.log4j.LogManager; <add>import org.apache.logging.log4j.Logger; <ide> import org.apache.manifoldcf.agents.interfaces.IOutputAddActivity; <ide> import org.apache.manifoldcf.agents.interfaces.IOutputCheckActivity; <ide> import org.apache.manifoldcf.agents.interfaces.RepositoryDocument; <ide> <ide> protected static final String[] activitiesList = new String[] { ACTIVITY_CLEAN }; <ide> <add> private static final Logger LOGGER = LogManager.getLogger(MetadataCleaner.class.getName()); <add> <ide> /** <ide> * Connect. <ide> * <ide> // Iterate over all the metadata, delete them and store their cleaned names and values in the cleanMetadata hashmap we just created <ide> while (fieldsI.hasNext()) { <ide> final String fieldName = fieldsI.next(); <del> String cleanFieldName = fieldName; <del> for (final String nameRegex : spec.nameCleaners.keySet()) { <del> cleanFieldName = fieldName.replaceAll(nameRegex, spec.nameCleaners.get(nameRegex)); <del> } <del> final Object[] fieldValues = document.getField(fieldName); <del> if (fieldValues instanceof String[]) { <del> for (final String valueRegex : spec.valueCleaners.keySet()) { <add> // We only keep the metadata if its name is not null <add> if (fieldName != null && !fieldName.isEmpty()) { <add> String cleanFieldName = fieldName; <add> // We apply the all name regex on the name <add> for (final String nameRegex : spec.nameCleaners.keySet()) { <add> cleanFieldName = fieldName.replaceAll(nameRegex, spec.nameCleaners.get(nameRegex)); <add> } <add> // We apply the value regex on the values that are string values <add> Object[] fieldValues = document.getField(fieldName); <add> if (fieldValues instanceof String[]) { <add> for (final String valueRegex : spec.valueCleaners.keySet()) { <add> for (int i = 0; i < fieldValues.length; i++) { <add> if (fieldValues[i] != null) { <add> final String cleanValue = fieldValues[i].toString().replaceAll(valueRegex, spec.valueCleaners.get(valueRegex)); <add> fieldValues[i] = cleanValue; <add> } else { <add> fieldValues[i] = ""; <add> } <add> } <add> } <add> } else if (fieldValues != null && fieldValues.length > 0) { <add> // For values that are not regex we remove all the null values <add> final Set<Integer> indexesToRemove = new HashSet<>(); <ide> for (int i = 0; i < fieldValues.length; i++) { <del> final String cleanValue = fieldValues[i].toString().replaceAll(valueRegex, spec.valueCleaners.get(valueRegex)); <del> fieldValues[i] = cleanValue; <add> if (fieldValues[i] == null) { <add> indexesToRemove.add(i); <add> } <add> } <add> if (fieldValues instanceof Date[]) { <add> final Date[] cleanValues = new Date[fieldValues.length - indexesToRemove.size()]; <add> int cleanValuesCpt = 0; <add> for (int i = 0; i < fieldValues.length; i++) { <add> if (!indexesToRemove.contains(i)) { <add> cleanValues[cleanValuesCpt] = (Date) fieldValues[i]; <add> cleanValuesCpt++; <add> } <add> } <add> fieldValues = cleanValues; <add> } else if (fieldValues instanceof Reader[]) { <add> final Reader[] cleanValues = new Reader[fieldValues.length - indexesToRemove.size()]; <add> int cleanValuesCpt = 0; <add> for (int i = 0; i < fieldValues.length; i++) { <add> if (!indexesToRemove.contains(i)) { <add> cleanValues[cleanValuesCpt] = (Reader) fieldValues[i]; <add> cleanValuesCpt++; <add> } <add> } <add> fieldValues = cleanValues; <ide> } <ide> } <del> } <add> <add> // Store its "cleaned" equivalent only if fieldValues is not null and contains at least one element <add> if (fieldValues != null && fieldValues.length > 0) { <add> cleanMetadata.put(cleanFieldName, fieldValues); <add> } else { <add> LOGGER.warn("Field '" + cleanFieldName + "' of document '" + documentURI + "' ignored because it has null or empty value"); <add> } <add> } <add> <ide> // Remove the current metadata <ide> fieldsI.remove(); <del> // Store its "cleaned" equivalent <del> cleanMetadata.put(cleanFieldName, fieldValues); <ide> <ide> } <ide>
Java
apache-2.0
7b46e4fa5137996814df7f6063cae1a9d0d9d182
0
ConnectSDK/Connect-SDK-Android,openflint/Connect-SDK-Android,jaambee/Connect-SDK-Android,AspiroTV/Connect-SDK-Android,happysir/Connect-SDK-Android
/* * DiscoveryManager * Connect SDK * * Copyright (c) 2014 LG Electronics. * Created by Hyun Kook Khang on 19 Jan 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.connectsdk.discovery; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.json.JSONException; import org.json.JSONObject; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.MulticastLock; import android.util.Log; import com.connectsdk.core.Util; import com.connectsdk.device.ConnectableDevice; import com.connectsdk.device.ConnectableDeviceListener; import com.connectsdk.device.ConnectableDeviceStore; import com.connectsdk.device.DefaultConnectableDeviceStore; import com.connectsdk.discovery.provider.CastDiscoveryProvider; import com.connectsdk.discovery.provider.SSDPDiscoveryProvider; import com.connectsdk.discovery.provider.ZeroconfDiscoveryProvider; import com.connectsdk.service.AirPlayService; import com.connectsdk.service.CastService; import com.connectsdk.service.DIALService; import com.connectsdk.service.DLNAService; import com.connectsdk.service.DeviceService; import com.connectsdk.service.DeviceService.PairingType; import com.connectsdk.service.NetcastTVService; import com.connectsdk.service.RokuService; import com.connectsdk.service.WebOSTVService; import com.connectsdk.service.command.ServiceCommandError; import com.connectsdk.service.config.ServiceConfig; import com.connectsdk.service.config.ServiceConfig.ServiceConfigListener; import com.connectsdk.service.config.ServiceDescription; /** * ###Overview * * At the heart of Connect SDK is DiscoveryManager, a multi-protocol service discovery engine with a pluggable architecture. Much of your initial experience with Connect SDK will be with the DiscoveryManager class, as it consolidates discovered service information into ConnectableDevice objects. * * ###In depth * DiscoveryManager supports discovering services of differing protocols by using DiscoveryProviders. Many services are discoverable over [SSDP][0] and are registered to be discovered with the SSDPDiscoveryProvider class. * * As services are discovered on the network, the DiscoveryProviders will notify DiscoveryManager. DiscoveryManager is capable of attributing multiple services, if applicable, to a single ConnectableDevice instance. Thus, it is possible to have a mixed-mode ConnectableDevice object that is theoretically capable of more functionality than a single service can provide. * * DiscoveryManager keeps a running list of all discovered devices and maintains a filtered list of devices that have satisfied any of your CapabilityFilters. This filtered list is used by the DevicePicker when presenting the user with a list of devices. * * Only one instance of the DiscoveryManager should be in memory at a time. To assist with this, DiscoveryManager has static method at sharedManager. * * Example: * * @capability kMediaControlPlay * @code DiscoveryManager.init(getApplicationContext()); DiscoveryManager discoveryManager = DiscoveryManager.getInstance(); discoveryManager.addListener(this); discoveryManager.start(); @endcode * * [0]: http://tools.ietf.org/html/draft-cai-ssdp-v1-03 */ public class DiscoveryManager implements ConnectableDeviceListener, DiscoveryProviderListener, ServiceConfigListener { public static String CONNECT_SDK_VERSION = "1.3.0"; public enum PairingLevel { OFF, ON } // @cond INTERNAL private static DiscoveryManager instance; Context context; ConnectableDeviceStore connectableDeviceStore; int rescanInterval = 10; private ConcurrentHashMap<String, ConnectableDevice> allDevices; private ConcurrentHashMap<String, ConnectableDevice> compatibleDevices; private ConcurrentHashMap<String, Class<? extends DeviceService>> deviceClasses; private CopyOnWriteArrayList<DiscoveryProvider> discoveryProviders; private CopyOnWriteArrayList<DiscoveryManagerListener> discoveryListeners; List<CapabilityFilter> capabilityFilters; MulticastLock multicastLock; BroadcastReceiver receiver; boolean isBroadcastReceiverRegistered = false; Timer rescanTimer; PairingLevel pairingLevel; private boolean mSearching = false; // @endcond /** * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use getApplicationContext() as the Discovery manager could persist longer than the current Activity. * @code DiscoveryManager.init(getApplicationContext()); @endcode */ public static synchronized void init(Context context) { instance = new DiscoveryManager(context); } public static synchronized void destroy() { instance.onDestroy(); } /** * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use getApplicationContext() as the Discovery manager could persist longer than the current Activity. * * This accepts a ConnectableDeviceStore to use instead of the default device store. * @code MyConnectableDeviceStore myDeviceStore = new MyConnectableDeviceStore(); DiscoveryManager.init(getApplicationContext(), myDeviceStore); @endcode */ public static synchronized void init(Context context, ConnectableDeviceStore connectableDeviceStore) { instance = new DiscoveryManager(context, connectableDeviceStore); } /** * Get a shared instance of DiscoveryManager. */ public static synchronized DiscoveryManager getInstance() { if (instance == null) throw new Error("Call DiscoveryManager.init(Context) first"); return instance; } // @cond INTERNAL /** * Create a new instance of DiscoveryManager. * Direct use of this constructor is not recommended. In most cases, * you should use DiscoveryManager.getInstance() instead. */ public DiscoveryManager(Context context) { this(context, new DefaultConnectableDeviceStore(context)); } /** * Create a new instance of DiscoveryManager. * Direct use of this constructor is not recommended. In most cases, * you should use DiscoveryManager.getInstance() instead. */ public DiscoveryManager(Context context, ConnectableDeviceStore connectableDeviceStore) { this.context = context; this.connectableDeviceStore = connectableDeviceStore; allDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2); compatibleDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2); deviceClasses = new ConcurrentHashMap<String, Class<? extends DeviceService>>(4, 0.75f, 2); discoveryProviders = new CopyOnWriteArrayList<DiscoveryProvider>(); discoveryListeners = new CopyOnWriteArrayList<DiscoveryManagerListener>(); WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); multicastLock = wifiMgr.createMulticastLock("Connect SDK"); multicastLock.setReferenceCounted(true); capabilityFilters = new ArrayList<CapabilityFilter>(); pairingLevel = PairingLevel.OFF; receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); switch (networkInfo.getState()) { case CONNECTED: TimerTask task = new TimerTask() { @Override public void run() { if (mSearching) { for (DiscoveryProvider provider : discoveryProviders) { provider.start(); } } } }; Timer t = new Timer(); t.schedule(task, 2000); break; case DISCONNECTED: Log.w("Connect SDK", "Network connection is disconnected"); for (DiscoveryProvider provider : discoveryProviders) { provider.reset(); } allDevices.clear(); for (ConnectableDevice device: compatibleDevices.values()) { handleDeviceLoss(device); } compatibleDevices.clear(); for (DiscoveryProvider provider : discoveryProviders) { provider.stop(); } break; case CONNECTING: break; case DISCONNECTING: break; case SUSPENDED: break; case UNKNOWN: break; } } } }; registerBroadcastReceiver(); } // @endcond private void registerBroadcastReceiver() { if (isBroadcastReceiverRegistered == false) { isBroadcastReceiverRegistered = true; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); context.registerReceiver(receiver, intentFilter); } } private void unregisterBroadcastReceiver() { if (isBroadcastReceiverRegistered == true) { isBroadcastReceiverRegistered = false; context.unregisterReceiver(receiver); } } /** * Listener which should receive discovery updates. It is not necessary to set this listener property unless you are implementing your own device picker. Connect SDK provides a default DevicePicker which acts as a DiscoveryManagerListener, and should work for most cases. * * If you have provided a capabilityFilters array, the listener will only receive update messages for ConnectableDevices which satisfy at least one of the CapabilityFilters. If no capabilityFilters array is provided, the listener will receive update messages for all ConnectableDevice objects that are discovered. */ public void addListener(DiscoveryManagerListener listener) { // notify listener of all devices so far for (ConnectableDevice device: compatibleDevices.values()) { listener.onDeviceAdded(this, device); } discoveryListeners.add(listener); } /** * Removes a previously added listener */ public void removeListener(DiscoveryManagerListener listener) { discoveryListeners.remove(listener); } public void setCapabilityFilters(CapabilityFilter ... capabilityFilters) { setCapabilityFilters(Arrays.asList(capabilityFilters)); } public void setCapabilityFilters(List<CapabilityFilter> capabilityFilters) { this.capabilityFilters = capabilityFilters; for (ConnectableDevice device: compatibleDevices.values()) { handleDeviceLoss(device); } compatibleDevices.clear(); for (ConnectableDevice device: allDevices.values()) { if (deviceIsCompatible(device)) { compatibleDevices.put(device.getIpAddress(), device); handleDeviceAdd(device); } } } /** * Returns the list of capability filters. */ public List<CapabilityFilter> getCapabilityFilters() { return capabilityFilters; } public boolean deviceIsCompatible(ConnectableDevice device) { if (capabilityFilters == null || capabilityFilters.size() == 0) { return true; } boolean isCompatible = false; for (CapabilityFilter filter: this.capabilityFilters) { if (device.hasCapabilities(filter.capabilities)) { isCompatible = true; break; } } return isCompatible; } // @cond INTERNAL /** * Registers a commonly-used set of DeviceServices with DiscoveryManager. This method will be called on first call of startDiscovery if no DeviceServices have been registered. * * - CastDiscoveryProvider * + CastService * - SSDPDiscoveryProvider * + DIALService * + DLNAService (limited to LG TVs, currently) * + NetcastTVService * + RokuService * + WebOSTVService * - ZeroconfDiscoveryProvider * + AirPlayService */ public void registerDefaultDeviceTypes() { registerDeviceService(WebOSTVService.class, SSDPDiscoveryProvider.class); // registerDeviceService(NetcastTVService.class, SSDPDiscoveryProvider.class); registerDeviceService(DLNAService.class, SSDPDiscoveryProvider.class); // includes Netcast registerDeviceService(DIALService.class, SSDPDiscoveryProvider.class); registerDeviceService(RokuService.class, SSDPDiscoveryProvider.class); registerDeviceService(CastService.class, CastDiscoveryProvider.class); registerDeviceService(AirPlayService.class, ZeroconfDiscoveryProvider.class); } /** * Registers a DeviceService with DiscoveryManager and tells it which DiscoveryProvider to use to find it. Each DeviceService has a JSONObject of discovery parameters that its DiscoveryProvider will use to find it. * * @param deviceClass Class for object that should be instantiated when DeviceService is found * @param discoveryClass Class for object that should discover this DeviceService. If a DiscoveryProvider of this class already exists, then the existing DiscoveryProvider will be used. */ public void registerDeviceService(Class<? extends DeviceService> deviceClass, Class<? extends DiscoveryProvider> discoveryClass) { if (!DeviceService.class.isAssignableFrom(deviceClass)) return; if (!DiscoveryProvider.class.isAssignableFrom(discoveryClass)) return; try { DiscoveryProvider discoveryProvider = null; for (DiscoveryProvider dp : discoveryProviders) { if (dp.getClass().isAssignableFrom(discoveryClass)) { discoveryProvider = dp; break; } } if (discoveryProvider == null) { Constructor<? extends DiscoveryProvider> myConstructor = discoveryClass.getConstructor(Context.class); Object myObj = myConstructor.newInstance(new Object[]{context}); discoveryProvider = (DiscoveryProvider) myObj; discoveryProvider.addListener(this); discoveryProviders.add(discoveryProvider); } Method m = deviceClass.getMethod("discoveryParameters"); Object result = m.invoke(null); JSONObject discoveryParameters = (JSONObject) result; String serviceFilter = (String) discoveryParameters.get("serviceId"); deviceClasses.put(serviceFilter, deviceClass); discoveryProvider.addDeviceFilter(discoveryParameters); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } /** * Unregisters a DeviceService with DiscoveryManager. If no other DeviceServices are set to being discovered with the associated DiscoveryProvider, then that DiscoveryProvider instance will be stopped and shut down. * * @param deviceClass Class for DeviceService that should no longer be discovered * @param discoveryClass Class for DiscoveryProvider that is discovering DeviceServices of deviceClass type */ public void unregisterDeviceService(Class<?> deviceClass, Class<?> discoveryClass) { if (!deviceClass.isAssignableFrom(DeviceService.class)) { return; } if (!discoveryClass.isAssignableFrom(DiscoveryProvider.class)) { return; } try { DiscoveryProvider discoveryProvider = null; for (DiscoveryProvider dp: discoveryProviders) { if (dp.getClass().isAssignableFrom(discoveryClass)) { discoveryProvider = dp; break; } } if (discoveryProvider == null) return; Method m = deviceClass.getMethod("discoveryParameters"); Object result = m.invoke(null); JSONObject discoveryParameters = (JSONObject) result; String serviceFilter = (String) discoveryParameters.get("serviceId"); deviceClasses.remove(serviceFilter); discoveryProvider.removeDeviceFilter(discoveryParameters); if (discoveryProvider.isEmpty()) { discoveryProvider.stop(); discoveryProviders.remove(discoveryProvider); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } // @endcond /** * Start scanning for devices on the local network. */ public void start() { if (mSearching) return; if (discoveryProviders == null) { return; } mSearching = true; multicastLock.acquire(); Util.runOnUI(new Runnable() { @Override public void run() { if (discoveryProviders.size() == 0) { registerDefaultDeviceTypes(); } ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWifi.isConnected()) { for (DiscoveryProvider provider : discoveryProviders) { provider.start(); } } else { Log.w("Connect SDK", "Wifi is not connected yet"); Util.runOnUI(new Runnable() { @Override public void run() { for (DiscoveryManagerListener listener : discoveryListeners) listener.onDiscoveryFailed(DiscoveryManager.this, new ServiceCommandError(0, "No wifi connection", null)); } }); } } }); } /** * Stop scanning for devices. * * This method will be called when your app enters a background state. When your app resumes, startDiscovery will be called. */ public void stop() { if (!mSearching) return; mSearching = false; for (DiscoveryProvider provider : discoveryProviders) { provider.stop(); } if (multicastLock.isHeld()) { multicastLock.release(); } } /** * ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL certificates, recent access times, etc are kept in the device store. * * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation, DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided. * * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the ConnectableDeviceStore removeAll method. * * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the time of instantiation with `DiscoveryManager.init(context, null);`. */ public void setConnectableDeviceStore(ConnectableDeviceStore connectableDeviceStore) { this.connectableDeviceStore = connectableDeviceStore; } /** * ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL certificates, recent access times, etc are kept in the device store. * * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation, DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided. * * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the ConnectableDeviceStore removeAll method. * * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the time of instantiation with `DiscoveryManager.init(context, null);`. */ public ConnectableDeviceStore getConnectableDeviceStore() { return connectableDeviceStore; } // @cond INTERNAL public void handleDeviceAdd(ConnectableDevice device) { if (!deviceIsCompatible(device)) return; compatibleDevices.put(device.getIpAddress(), device); for (DiscoveryManagerListener listenter: discoveryListeners) { listenter.onDeviceAdded(this, device); } } public void handleDeviceUpdate(ConnectableDevice device) { if (deviceIsCompatible(device)) { if (device.getIpAddress() != null && compatibleDevices.containsKey(device.getIpAddress())) { for (DiscoveryManagerListener listenter: discoveryListeners) { listenter.onDeviceUpdated(this, device); } } else { handleDeviceAdd(device); } } else { compatibleDevices.remove(device.getIpAddress()); handleDeviceLoss(device); } } public void handleDeviceLoss(ConnectableDevice device) { for (DiscoveryManagerListener listenter: discoveryListeners) { listenter.onDeviceRemoved(this, device); } device.disconnect(); } public boolean isNetcast(ServiceDescription description) { boolean isNetcastTV = false; String modelName = description.getModelName(); String modelDescription = description.getModelDescription(); if (modelName != null && modelName.toUpperCase(Locale.US).equals("LG TV")) { if (modelDescription != null && !(modelDescription.toUpperCase(Locale.US).contains("WEBOS"))) { isNetcastTV = true; } } return isNetcastTV; } // @endcond /** * List of all devices discovered by DiscoveryManager. Each ConnectableDevice object is keyed against its current IP address. */ public Map<String, ConnectableDevice> getAllDevices() { return allDevices; } /** * Filtered list of discovered ConnectableDevices, limited to devices that match at least one of the CapabilityFilters in the capabilityFilters array. Each ConnectableDevice object is keyed against its current IP address. */ public Map<String, ConnectableDevice> getCompatibleDevices() { return compatibleDevices; } /** * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be available. * * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt the user to pair when connecting to the ConnectableDevice. * * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid requiring pairing if possible but some capabilities may not be available. */ public PairingLevel getPairingLevel() { return pairingLevel; } /** * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be available. * * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt the user to pair when connecting to the ConnectableDevice. * * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid requiring pairing if possible but some capabilities may not be available. */ public void setPairingLevel(PairingLevel pairingLevel) { this.pairingLevel = pairingLevel; } // @cond INTERNAL public Context getContext() { return context; } public void onDestroy() { unregisterBroadcastReceiver(); } @Override public void onServiceConfigUpdate(ServiceConfig serviceConfig) { } @Override public void onCapabilityUpdated(ConnectableDevice device, List<String> added, List<String> removed) { handleDeviceUpdate(device); } @Override public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) { } @Override public void onDeviceDisconnected(ConnectableDevice device) { } @Override public void onDeviceReady(ConnectableDevice device) { } @Override public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) { } @Override public void onServiceAdded(DiscoveryProvider provider, ServiceDescription serviceDescription) { Log.d("Connect SDK", "Service added: " + serviceDescription.getFriendlyName() + " (" + serviceDescription.getServiceID() + ")"); boolean deviceIsNew = !allDevices.containsKey(serviceDescription.getIpAddress()); ConnectableDevice device = null; if (deviceIsNew) { if (connectableDeviceStore != null) { device = connectableDeviceStore.getDevice(serviceDescription.getUUID()); if (device != null) { allDevices.put(serviceDescription.getIpAddress(), device); device.setIpAddress(serviceDescription.getIpAddress()); } } } else { device = allDevices.get(serviceDescription.getIpAddress()); } if (device == null) { device = new ConnectableDevice(serviceDescription); device.setIpAddress(serviceDescription.getIpAddress()); allDevices.put(serviceDescription.getIpAddress(), device); deviceIsNew = true; } device.setFriendlyName(serviceDescription.getFriendlyName()); device.setLastDetection(Util.getTime()); device.setLastKnownIPAddress(serviceDescription.getIpAddress()); // TODO: Implement the currentSSID Property in DiscoveryManager // device.setLastSeenOnWifi(currentSSID); addServiceDescriptionToDevice(serviceDescription, device); if (device.getServices().size() == 0) { // we get here when a non-LG DLNA TV is found allDevices.remove(serviceDescription.getIpAddress()); device = null; return; } if (deviceIsNew) handleDeviceAdd(device); else handleDeviceUpdate(device); } @Override public void onServiceRemoved(DiscoveryProvider provider, ServiceDescription serviceDescription) { Log.d("Connect SDK", "onServiceRemoved: friendlyName: " + serviceDescription.getFriendlyName()); ConnectableDevice device = allDevices.get(serviceDescription.getIpAddress()); if (device != null) { device.removeServiceWithId(serviceDescription.getServiceID()); if (device.getServices().isEmpty()) { allDevices.remove(serviceDescription.getIpAddress()); handleDeviceLoss(device); } else { handleDeviceUpdate(device); } } } @Override public void onServiceDiscoveryFailed(DiscoveryProvider provider, ServiceCommandError error) { Log.w("Connect SDK", "DiscoveryProviderListener, Service Discovery Failed"); } @SuppressWarnings("unchecked") public void addServiceDescriptionToDevice(ServiceDescription desc, ConnectableDevice device) { Log.d("Connect SDK", "Adding service " + desc.getServiceID() + " to device with address " + device.getIpAddress() + " and id " + device.getId()); Class<? extends DeviceService> deviceServiceClass; if (isNetcast(desc)) { deviceServiceClass = NetcastTVService.class; Method m; Object result = null; try { m = deviceServiceClass.getMethod("discoveryParameters"); result = m.invoke(null); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (result == null) return; JSONObject discoveryParameters = (JSONObject) result; String serviceId = discoveryParameters.optString("serviceId"); if (serviceId == null || serviceId.length() == 0) return; desc.setServiceID(serviceId); } else { deviceServiceClass = (Class<DeviceService>) deviceClasses.get(desc.getServiceID()); } if (deviceServiceClass == null) return; if (DLNAService.class.isAssignableFrom(deviceServiceClass)) { String netcast = "netcast"; String webos = "webos"; String locationXML = desc.getLocationXML().toLowerCase(); int locNet = locationXML.indexOf(netcast); int locWeb = locationXML.indexOf(webos); if (locNet == -1 && locWeb == -1) return; } ServiceConfig serviceConfig = null; if (connectableDeviceStore != null) serviceConfig = connectableDeviceStore.getServiceConfig(desc.getUUID()); if (serviceConfig == null) serviceConfig = new ServiceConfig(desc); serviceConfig.setListener(DiscoveryManager.this); boolean hasType = false; boolean hasService = false; for (DeviceService service : device.getServices()) { if (service.getServiceDescription().getServiceID().equals(desc.getServiceID())) { hasType = true; if (service.getServiceDescription().getUUID().equals(desc.getUUID())) { hasService = true; } break; } } if (hasType) { if (hasService) { device.setServiceDescription(desc); DeviceService alreadyAddedService = device.getServiceByName(desc.getServiceID()); if (alreadyAddedService != null) alreadyAddedService.setServiceDescription(desc); return; } device.removeServiceByName(desc.getServiceID()); } DeviceService deviceService = DeviceService.getService(deviceServiceClass, desc, serviceConfig); deviceService.setServiceDescription(desc); device.addService(deviceService); } // @endcond }
src/com/connectsdk/discovery/DiscoveryManager.java
/* * DiscoveryManager * Connect SDK * * Copyright (c) 2014 LG Electronics. * Created by Hyun Kook Khang on 19 Jan 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.connectsdk.discovery; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.json.JSONException; import org.json.JSONObject; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.MulticastLock; import android.util.Log; import com.connectsdk.core.Util; import com.connectsdk.device.ConnectableDevice; import com.connectsdk.device.ConnectableDeviceListener; import com.connectsdk.device.ConnectableDeviceStore; import com.connectsdk.device.DefaultConnectableDeviceStore; import com.connectsdk.discovery.provider.CastDiscoveryProvider; import com.connectsdk.discovery.provider.SSDPDiscoveryProvider; import com.connectsdk.discovery.provider.ZeroconfDiscoveryProvider; import com.connectsdk.service.AirPlayService; import com.connectsdk.service.CastService; import com.connectsdk.service.DIALService; import com.connectsdk.service.DLNAService; import com.connectsdk.service.DeviceService; import com.connectsdk.service.DeviceService.PairingType; import com.connectsdk.service.NetcastTVService; import com.connectsdk.service.RokuService; import com.connectsdk.service.WebOSTVService; import com.connectsdk.service.command.ServiceCommandError; import com.connectsdk.service.config.ServiceConfig; import com.connectsdk.service.config.ServiceConfig.ServiceConfigListener; import com.connectsdk.service.config.ServiceDescription; /** * ###Overview * * At the heart of Connect SDK is DiscoveryManager, a multi-protocol service discovery engine with a pluggable architecture. Much of your initial experience with Connect SDK will be with the DiscoveryManager class, as it consolidates discovered service information into ConnectableDevice objects. * * ###In depth * DiscoveryManager supports discovering services of differing protocols by using DiscoveryProviders. Many services are discoverable over [SSDP][0] and are registered to be discovered with the SSDPDiscoveryProvider class. * * As services are discovered on the network, the DiscoveryProviders will notify DiscoveryManager. DiscoveryManager is capable of attributing multiple services, if applicable, to a single ConnectableDevice instance. Thus, it is possible to have a mixed-mode ConnectableDevice object that is theoretically capable of more functionality than a single service can provide. * * DiscoveryManager keeps a running list of all discovered devices and maintains a filtered list of devices that have satisfied any of your CapabilityFilters. This filtered list is used by the DevicePicker when presenting the user with a list of devices. * * Only one instance of the DiscoveryManager should be in memory at a time. To assist with this, DiscoveryManager has static method at sharedManager. * * Example: * * @capability kMediaControlPlay * @code DiscoveryManager.init(getApplicationContext()); DiscoveryManager discoveryManager = DiscoveryManager.getInstance(); discoveryManager.addListener(this); discoveryManager.start(); @endcode * * [0]: http://tools.ietf.org/html/draft-cai-ssdp-v1-03 */ public class DiscoveryManager implements ConnectableDeviceListener, DiscoveryProviderListener, ServiceConfigListener { public static String CONNECT_SDK_VERSION = "1.3.0"; public enum PairingLevel { OFF, ON } // @cond INTERNAL private static DiscoveryManager instance; Context context; ConnectableDeviceStore connectableDeviceStore; int rescanInterval = 10; private ConcurrentHashMap<String, ConnectableDevice> allDevices; private ConcurrentHashMap<String, ConnectableDevice> compatibleDevices; private ConcurrentHashMap<String, Class<? extends DeviceService>> deviceClasses; private CopyOnWriteArrayList<DiscoveryProvider> discoveryProviders; private CopyOnWriteArrayList<DiscoveryManagerListener> discoveryListeners; List<CapabilityFilter> capabilityFilters; MulticastLock multicastLock; BroadcastReceiver receiver; boolean isBroadcastReceiverRegistered = false; Timer rescanTimer; PairingLevel pairingLevel; private boolean mSearching = false; // @endcond /** * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use getApplicationContext() as the Discovery manager could persist longer than the current Activity. * @code DiscoveryManager.init(getApplicationContext()); @endcode */ public static synchronized void init(Context context) { instance = new DiscoveryManager(context); } public static synchronized void destroy() { instance.onDestroy(); } /** * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use getApplicationContext() as the Discovery manager could persist longer than the current Activity. * * This accepts a ConnectableDeviceStore to use instead of the default device store. * @code MyConnectableDeviceStore myDeviceStore = new MyConnectableDeviceStore(); DiscoveryManager.init(getApplicationContext(), myDeviceStore); @endcode */ public static synchronized void init(Context context, ConnectableDeviceStore connectableDeviceStore) { instance = new DiscoveryManager(context, connectableDeviceStore); } /** * Get a shared instance of DiscoveryManager. */ public static synchronized DiscoveryManager getInstance() { if (instance == null) throw new Error("Call DiscoveryManager.init(Context) first"); return instance; } // @cond INTERNAL /** * Create a new instance of DiscoveryManager. * Direct use of this constructor is not recommended. In most cases, * you should use DiscoveryManager.getInstance() instead. */ public DiscoveryManager(Context context) { this(context, new DefaultConnectableDeviceStore(context)); } /** * Create a new instance of DiscoveryManager. * Direct use of this constructor is not recommended. In most cases, * you should use DiscoveryManager.getInstance() instead. */ public DiscoveryManager(Context context, ConnectableDeviceStore connectableDeviceStore) { this.context = context; this.connectableDeviceStore = connectableDeviceStore; allDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2); compatibleDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2); deviceClasses = new ConcurrentHashMap<String, Class<? extends DeviceService>>(4, 0.75f, 2); discoveryProviders = new CopyOnWriteArrayList<DiscoveryProvider>(); discoveryListeners = new CopyOnWriteArrayList<DiscoveryManagerListener>(); WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); multicastLock = wifiMgr.createMulticastLock("Connect SDK"); multicastLock.setReferenceCounted(true); capabilityFilters = new ArrayList<CapabilityFilter>(); pairingLevel = PairingLevel.OFF; receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); switch (networkInfo.getState()) { case CONNECTED: TimerTask task = new TimerTask() { @Override public void run() { if (mSearching) { for (DiscoveryProvider provider : discoveryProviders) { provider.start(); } } } }; Timer t = new Timer(); t.schedule(task, 2000); break; case DISCONNECTED: Log.w("Connect SDK", "Network connection is disconnected"); for (DiscoveryProvider provider : discoveryProviders) { provider.reset(); } allDevices.clear(); for (ConnectableDevice device: compatibleDevices.values()) { handleDeviceLoss(device); } compatibleDevices.clear(); for (DiscoveryProvider provider : discoveryProviders) { provider.stop(); } break; case CONNECTING: break; case DISCONNECTING: break; case SUSPENDED: break; case UNKNOWN: break; } } } }; registerBroadcastReceiver(); } // @endcond private void registerBroadcastReceiver() { if (isBroadcastReceiverRegistered == false) { isBroadcastReceiverRegistered = true; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); context.registerReceiver(receiver, intentFilter); } } private void unregisterBroadcastReceiver() { if (isBroadcastReceiverRegistered == true) { isBroadcastReceiverRegistered = false; context.unregisterReceiver(receiver); } } /** * Listener which should receive discovery updates. It is not necessary to set this listener property unless you are implementing your own device picker. Connect SDK provides a default DevicePicker which acts as a DiscoveryManagerListener, and should work for most cases. * * If you have provided a capabilityFilters array, the listener will only receive update messages for ConnectableDevices which satisfy at least one of the CapabilityFilters. If no capabilityFilters array is provided, the listener will receive update messages for all ConnectableDevice objects that are discovered. */ public void addListener(DiscoveryManagerListener listener) { // notify listener of all devices so far for (ConnectableDevice device: compatibleDevices.values()) { listener.onDeviceAdded(this, device); } discoveryListeners.add(listener); } /** * Removes a previously added listener */ public void removeListener(DiscoveryManagerListener listener) { discoveryListeners.remove(listener); } public void setCapabilityFilters(CapabilityFilter ... capabilityFilters) { setCapabilityFilters(Arrays.asList(capabilityFilters)); } public void setCapabilityFilters(List<CapabilityFilter> capabilityFilters) { this.capabilityFilters = capabilityFilters; for (ConnectableDevice device: compatibleDevices.values()) { handleDeviceLoss(device); } compatibleDevices.clear(); for (ConnectableDevice device: allDevices.values()) { if (deviceIsCompatible(device)) { compatibleDevices.put(device.getIpAddress(), device); handleDeviceAdd(device); } } } /** * Returns the list of capability filters. */ public List<CapabilityFilter> getCapabilityFilters() { return capabilityFilters; } public boolean deviceIsCompatible(ConnectableDevice device) { if (capabilityFilters == null || capabilityFilters.size() == 0) { return true; } boolean isCompatible = false; for (CapabilityFilter filter: this.capabilityFilters) { if (device.hasCapabilities(filter.capabilities)) { isCompatible = true; break; } } return isCompatible; } // @cond INTERNAL /** * Registers a commonly-used set of DeviceServices with DiscoveryManager. This method will be called on first call of startDiscovery if no DeviceServices have been registered. * * - CastDiscoveryProvider * + CastService * - SSDPDiscoveryProvider * + DIALService * + DLNAService (limited to LG TVs, currently) * + NetcastTVService * + RokuService * + WebOSTVService * - ZeroconfDiscoveryProvider * + AirPlayService */ public void registerDefaultDeviceTypes() { registerDeviceService(WebOSTVService.class, SSDPDiscoveryProvider.class); // registerDeviceService(NetcastTVService.class, SSDPDiscoveryProvider.class); registerDeviceService(DLNAService.class, SSDPDiscoveryProvider.class); // includes Netcast registerDeviceService(DIALService.class, SSDPDiscoveryProvider.class); registerDeviceService(RokuService.class, SSDPDiscoveryProvider.class); registerDeviceService(CastService.class, CastDiscoveryProvider.class); registerDeviceService(AirPlayService.class, ZeroconfDiscoveryProvider.class); } /** * Registers a DeviceService with DiscoveryManager and tells it which DiscoveryProvider to use to find it. Each DeviceService has a JSONObject of discovery parameters that its DiscoveryProvider will use to find it. * * @param deviceClass Class for object that should be instantiated when DeviceService is found * @param discoveryClass Class for object that should discover this DeviceService. If a DiscoveryProvider of this class already exists, then the existing DiscoveryProvider will be used. */ public void registerDeviceService(Class<? extends DeviceService> deviceClass, Class<? extends DiscoveryProvider> discoveryClass) { if (!DeviceService.class.isAssignableFrom(deviceClass)) return; if (!DiscoveryProvider.class.isAssignableFrom(discoveryClass)) return; try { DiscoveryProvider discoveryProvider = null; for (DiscoveryProvider dp : discoveryProviders) { if (dp.getClass().isAssignableFrom(discoveryClass)) { discoveryProvider = dp; break; } } if (discoveryProvider == null) { Constructor<? extends DiscoveryProvider> myConstructor = discoveryClass.getConstructor(Context.class); Object myObj = myConstructor.newInstance(new Object[]{context}); discoveryProvider = (DiscoveryProvider) myObj; discoveryProvider.addListener(this); discoveryProviders.add(discoveryProvider); } Method m = deviceClass.getMethod("discoveryParameters"); Object result = m.invoke(null); JSONObject discoveryParameters = (JSONObject) result; String serviceFilter = (String) discoveryParameters.get("serviceId"); deviceClasses.put(serviceFilter, deviceClass); discoveryProvider.addDeviceFilter(discoveryParameters); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } /** * Unregisters a DeviceService with DiscoveryManager. If no other DeviceServices are set to being discovered with the associated DiscoveryProvider, then that DiscoveryProvider instance will be stopped and shut down. * * @param deviceClass Class for DeviceService that should no longer be discovered * @param discoveryClass Class for DiscoveryProvider that is discovering DeviceServices of deviceClass type */ public void unregisterDeviceService(Class<?> deviceClass, Class<?> discoveryClass) { if (!deviceClass.isAssignableFrom(DeviceService.class)) { return; } if (!discoveryClass.isAssignableFrom(DiscoveryProvider.class)) { return; } try { DiscoveryProvider discoveryProvider = null; for (DiscoveryProvider dp: discoveryProviders) { if (dp.getClass().isAssignableFrom(discoveryClass)) { discoveryProvider = dp; break; } } if (discoveryProvider == null) return; Method m = deviceClass.getMethod("discoveryParameters"); Object result = m.invoke(null); JSONObject discoveryParameters = (JSONObject) result; String serviceFilter = (String) discoveryParameters.get("serviceId"); deviceClasses.remove(serviceFilter); discoveryProvider.removeDeviceFilter(discoveryParameters); if (discoveryProvider.isEmpty()) { discoveryProvider.stop(); discoveryProviders.remove(discoveryProvider); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } // @endcond /** * Start scanning for devices on the local network. */ public void start() { if (mSearching) return; if (discoveryProviders == null) { return; } mSearching = true; multicastLock.acquire(); Util.runOnUI(new Runnable() { @Override public void run() { if (discoveryProviders.size() == 0) { registerDefaultDeviceTypes(); } ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWifi.isConnected()) { for (DiscoveryProvider provider : discoveryProviders) { provider.start(); } } else { Log.w("Connect SDK", "Wifi is not connected yet"); Util.runOnUI(new Runnable() { @Override public void run() { for (DiscoveryManagerListener listener : discoveryListeners) listener.onDiscoveryFailed(DiscoveryManager.this, new ServiceCommandError(0, "No wifi connection", null)); } }); } } }); } /** * Stop scanning for devices. * * This method will be called when your app enters a background state. When your app resumes, startDiscovery will be called. */ public void stop() { if (!mSearching) return; mSearching = false; for (DiscoveryProvider provider : discoveryProviders) { provider.stop(); } if (multicastLock.isHeld()) { multicastLock.release(); } } /** * ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL certificates, recent access times, etc are kept in the device store. * * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation, DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided. * * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the ConnectableDeviceStore removeAll method. * * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the time of instantiation with `DiscoveryManager.init(context, null);`. */ public void setConnectableDeviceStore(ConnectableDeviceStore connectableDeviceStore) { this.connectableDeviceStore = connectableDeviceStore; } /** * ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL certificates, recent access times, etc are kept in the device store. * * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation, DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided. * * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the ConnectableDeviceStore removeAll method. * * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the time of instantiation with `DiscoveryManager.init(context, null);`. */ public ConnectableDeviceStore getConnectableDeviceStore() { return connectableDeviceStore; } // @cond INTERNAL public void handleDeviceAdd(ConnectableDevice device) { if (!deviceIsCompatible(device)) return; compatibleDevices.put(device.getIpAddress(), device); for (DiscoveryManagerListener listenter: discoveryListeners) { listenter.onDeviceAdded(this, device); } } public void handleDeviceUpdate(ConnectableDevice device) { if (deviceIsCompatible(device)) { if (device.getIpAddress() != null && compatibleDevices.containsKey(device.getIpAddress())) { for (DiscoveryManagerListener listenter: discoveryListeners) { listenter.onDeviceUpdated(this, device); } } else { handleDeviceAdd(device); } } else { compatibleDevices.remove(device.getIpAddress()); handleDeviceLoss(device); } } public void handleDeviceLoss(ConnectableDevice device) { for (DiscoveryManagerListener listenter: discoveryListeners) { listenter.onDeviceRemoved(this, device); } device.disconnect(); } public boolean isNetcast(ServiceDescription description) { boolean isNetcastTV = false; String modelName = description.getModelName(); String modelDescription = description.getModelDescription(); if (modelName != null && modelName.toUpperCase(Locale.US).equals("LG TV")) { if (modelDescription != null && !(modelDescription.toUpperCase(Locale.US).contains("WEBOS"))) { isNetcastTV = true; } } return isNetcastTV; } // @endcond /** * List of all devices discovered by DiscoveryManager. Each ConnectableDevice object is keyed against its current IP address. */ public Map<String, ConnectableDevice> getAllDevices() { return allDevices; } /** * Filtered list of discovered ConnectableDevices, limited to devices that match at least one of the CapabilityFilters in the capabilityFilters array. Each ConnectableDevice object is keyed against its current IP address. */ public Map<String, ConnectableDevice> getCompatibleDevices() { return compatibleDevices; } /** * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be available. * * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt the user to pair when connecting to the ConnectableDevice. * * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid requiring pairing if possible but some capabilities may not be available. */ public PairingLevel getPairingLevel() { return pairingLevel; } /** * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be available. * * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt the user to pair when connecting to the ConnectableDevice. * * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid requiring pairing if possible but some capabilities may not be available. */ public void setPairingLevel(PairingLevel pairingLevel) { this.pairingLevel = pairingLevel; } // @cond INTERNAL public Context getContext() { return context; } public void onDestroy() { unregisterBroadcastReceiver(); } @Override public void onServiceConfigUpdate(ServiceConfig serviceConfig) { } @Override public void onCapabilityUpdated(ConnectableDevice device, List<String> added, List<String> removed) { handleDeviceUpdate(device); } @Override public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) { } @Override public void onDeviceDisconnected(ConnectableDevice device) { } @Override public void onDeviceReady(ConnectableDevice device) { } @Override public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) { } @Override public void onServiceAdded(DiscoveryProvider provider, ServiceDescription serviceDescription) { Log.d("Connect SDK", "Service added: " + serviceDescription.getFriendlyName() + " (" + serviceDescription.getServiceID() + ")"); boolean deviceIsNew = !allDevices.containsKey(serviceDescription.getIpAddress()); ConnectableDevice device = null; if (deviceIsNew) { if (connectableDeviceStore != null) { device = connectableDeviceStore.getDevice(serviceDescription.getUUID()); if (device != null) { allDevices.put(serviceDescription.getIpAddress(), device); device.setIpAddress(serviceDescription.getIpAddress()); } } } else { device = allDevices.get(serviceDescription.getIpAddress()); } if (device == null) { device = new ConnectableDevice(serviceDescription); device.setIpAddress(serviceDescription.getIpAddress()); allDevices.put(serviceDescription.getIpAddress(), device); deviceIsNew = true; } device.setLastDetection(Util.getTime()); device.setLastKnownIPAddress(serviceDescription.getIpAddress()); // TODO: Implement the currentSSID Property in DiscoveryManager // device.setLastSeenOnWifi(currentSSID); addServiceDescriptionToDevice(serviceDescription, device); if (device.getServices().size() == 0) { // we get here when a non-LG DLNA TV is found allDevices.remove(serviceDescription.getIpAddress()); device = null; return; } if (deviceIsNew) handleDeviceAdd(device); else handleDeviceUpdate(device); } @Override public void onServiceRemoved(DiscoveryProvider provider, ServiceDescription serviceDescription) { Log.d("Connect SDK", "onServiceRemoved: friendlyName: " + serviceDescription.getFriendlyName()); ConnectableDevice device = allDevices.get(serviceDescription.getIpAddress()); if (device != null) { device.removeServiceWithId(serviceDescription.getServiceID()); if (device.getServices().isEmpty()) { allDevices.remove(serviceDescription.getIpAddress()); handleDeviceLoss(device); } else { handleDeviceUpdate(device); } } } @Override public void onServiceDiscoveryFailed(DiscoveryProvider provider, ServiceCommandError error) { Log.w("Connect SDK", "DiscoveryProviderListener, Service Discovery Failed"); } @SuppressWarnings("unchecked") public void addServiceDescriptionToDevice(ServiceDescription desc, ConnectableDevice device) { Log.d("Connect SDK", "Adding service " + desc.getServiceID() + " to device with address " + device.getIpAddress() + " and id " + device.getId()); Class<? extends DeviceService> deviceServiceClass; if (isNetcast(desc)) { deviceServiceClass = NetcastTVService.class; Method m; Object result = null; try { m = deviceServiceClass.getMethod("discoveryParameters"); result = m.invoke(null); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (result == null) return; JSONObject discoveryParameters = (JSONObject) result; String serviceId = discoveryParameters.optString("serviceId"); if (serviceId == null || serviceId.length() == 0) return; desc.setServiceID(serviceId); } else { deviceServiceClass = (Class<DeviceService>) deviceClasses.get(desc.getServiceID()); } if (deviceServiceClass == null) return; if (DLNAService.class.isAssignableFrom(deviceServiceClass)) { String netcast = "netcast"; String webos = "webos"; String locationXML = desc.getLocationXML().toLowerCase(); int locNet = locationXML.indexOf(netcast); int locWeb = locationXML.indexOf(webos); if (locNet == -1 && locWeb == -1) return; } ServiceConfig serviceConfig = null; if (connectableDeviceStore != null) serviceConfig = connectableDeviceStore.getServiceConfig(desc.getUUID()); if (serviceConfig == null) serviceConfig = new ServiceConfig(desc); serviceConfig.setListener(DiscoveryManager.this); boolean hasType = false; boolean hasService = false; for (DeviceService service : device.getServices()) { if (service.getServiceDescription().getServiceID().equals(desc.getServiceID())) { hasType = true; if (service.getServiceDescription().getUUID().equals(desc.getUUID())) { hasService = true; } break; } } if (hasType) { if (hasService) { device.setServiceDescription(desc); DeviceService alreadyAddedService = device.getServiceByName(desc.getServiceID()); if (alreadyAddedService != null) alreadyAddedService.setServiceDescription(desc); return; } device.removeServiceByName(desc.getServiceID()); } DeviceService deviceService = DeviceService.getService(deviceServiceClass, desc, serviceConfig); deviceService.setServiceDescription(desc); device.addService(deviceService); } // @endcond }
Fixed DeviceList doesn't update FriendlyName #123
src/com/connectsdk/discovery/DiscoveryManager.java
Fixed DeviceList doesn't update FriendlyName #123
<ide><path>rc/com/connectsdk/discovery/DiscoveryManager.java <ide> deviceIsNew = true; <ide> } <ide> <add> device.setFriendlyName(serviceDescription.getFriendlyName()); <ide> device.setLastDetection(Util.getTime()); <ide> device.setLastKnownIPAddress(serviceDescription.getIpAddress()); <ide> // TODO: Implement the currentSSID Property in DiscoveryManager
JavaScript
mit
08d24791acaa4ee30836d87a1db000c638ad39ec
0
shexSpec/shex.js,shexSpec/shex.js,shexSpec/shex.js
// **ShExWriter** writes ShEx documents. var util = require('util'); var UNBOUNDED = -1; // Matches a literal as represented in memory by the ShEx library var ShExLiteralMatcher = /^"([^]*)"(?:\^\^(.+)|@([\-a-z]+))?$/i; // rdf:type predicate (for 'a' abbreviation) var RDF_PREFIX = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', RDF_TYPE = RDF_PREFIX + 'type'; // Characters in literals that require escaping var ESCAPE_1 = /["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/, ESCAPE_g = /["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g, ESCAPE_replacements = { '\\': '\\\\', '"': '\\"', '/': '\\/', '\t': '\\t', '\n': '\\n', '\r': '\\r', '\b': '\\b', '\f': '\\f' }; var nodeKinds = { 'iri': "IRI", 'bnode': "BNODE", 'literal': "LITERAL", 'nonliteral': "NONLITERAL" }; var nonLitNodeKinds = { 'iri': "IRI", 'bnode': "BNODE", 'literal': "LITERAL", 'nonliteral': "NONLITERAL" }; // ## Constructor function ShExWriter(outputStream, options) { if (!(this instanceof ShExWriter)) return new ShExWriter(outputStream, options); // Shift arguments if the first argument is not a stream if (outputStream && typeof outputStream.write !== 'function') options = outputStream, outputStream = null; options = options || {}; // If no output stream given, send the output as string through the end callback if (!outputStream) { var output = ''; this._outputStream = { write: function (chunk, encoding, done) { output += chunk; done && done(); }, end: function (done) { done && done(null, output); }, }; this._endStream = true; } else { this._outputStream = outputStream; this._endStream = options.end === undefined ? true : !!options.end; } // Initialize writer, depending on the format this._prefixIRIs = Object.create(null); options.prefixes && this.addPrefixes(options.prefixes); this._error = options.error || _throwError; this.forceParens = !options.simplifyParentheses; // default to false this._expect = options.lax ? noop : expect; } ShExWriter.prototype = { // ## Private methods // ### `_write` writes the argument to the output stream _write: function (string, callback) { this._outputStream.write(string, 'utf8', callback); }, // ### `_writeSchema` writes the shape to the output stream _writeSchema: function (schema, done) { var _ShExWriter = this; this._expect(schema, "type", "Schema"); _ShExWriter.addPrefixes(schema.prefixes); if (schema.base) _ShExWriter._write("BASE " + this._encodeIriOrBlankNode(schema.base) + "\n"); if (schema.startActs) schema.startActs.forEach(function (act) { _ShExWriter._expect(act, "type", "SemAct"); _ShExWriter._write(" %"+ _ShExWriter._encodePredicate(act.name)+ ("code" in act ? "{"+escapeCode(act.code)+"%"+"}" : "%")); }); if (schema.start) _ShExWriter._write("start = " + _ShExWriter._writeShapeExpr(schema.start, done, true, 0).join('') + "\n") if ("shapes" in schema) Object.keys(schema.shapes).forEach(function (label) { _ShExWriter._write( _ShExWriter._encodeShapeName(label, false) + " " + _ShExWriter._writeShapeExpr(schema.shapes[label], done, true, 0).join("")+"\n", done ); }) }, _writeShapeExpr: function (shapeExpr, done, forceBraces, parentPrec) { var _ShExWriter = this; var pieces = []; if (shapeExpr.type === "ShapeRef") pieces.push("@", _ShExWriter._encodeShapeName(shapeExpr.reference)); // !!! []s for precedence! else if (shapeExpr.type === "ShapeExternal") pieces.push("EXTERNAL"); else if (shapeExpr.type === "ShapeAnd") { if (parentPrec > 3) pieces.push("("); shapeExpr.shapeExprs.forEach(function (expr, ord) { if (ord > 0 && // !!! grammar rules too weird here !((shapeExpr.shapeExprs[ord-1].type === "NodeConstraint" && (shapeExpr.shapeExprs[ord ].type === "Shape" || shapeExpr.shapeExprs[ord ].type === "ShapeRef")) || (shapeExpr.shapeExprs[ord ].type === "NodeConstraint" && (shapeExpr.shapeExprs[ord-1].type === "Shape" || shapeExpr.shapeExprs[ord-1].type === "ShapeRef")))) pieces.push(" AND "); pieces = pieces.concat(_ShExWriter._writeShapeExpr(expr, done, false, 3)); }); if (parentPrec > 3) pieces.push(")"); } else if (shapeExpr.type === "ShapeOr") { if (parentPrec > 2) pieces.push("("); shapeExpr.shapeExprs.forEach(function (expr, ord) { if (ord > 0) pieces.push(" OR "); pieces = pieces.concat(_ShExWriter._writeShapeExpr(expr, done, forceBraces, 2)); }); if (parentPrec > 2) pieces.push(")"); } else if (shapeExpr.type === "ShapeNot") { pieces.push("NOT "); pieces = pieces.concat(_ShExWriter._writeShapeExpr(shapeExpr.shapeExpr, done, forceBraces, 1)); } else if (shapeExpr.type === "Shape") { pieces = pieces.concat(_ShExWriter._writeShape(shapeExpr, done, forceBraces)); } else if (shapeExpr.type === "NodeConstraint") { pieces = pieces.concat(_ShExWriter._writeNodeConstraint(shapeExpr, done, forceBraces)); } else throw Error("expected Shape{,And,Or,Ref} or NodeConstraint in " + util.inspect(shapeExpr)); return pieces; }, // ### `_writeShape` writes the shape to the output stream _writeShape: function (shape, done, forceBraces) { var _ShExWriter = this; try { var pieces = []; // guessing push/join is faster than concat this._expect(shape, "type", "Shape"); if (shape.closed) pieces.push("CLOSED "); // if (shape.inherit && shape.inherit.length > 0) { futureWork // pieces.push("&"); // shape.inherit.forEach(function (i, ord) { // if (ord) // pieces.push(" ") // pieces.push(_ShExWriter._encodeShapeName(i, ord > 0)); // }); // pieces.push(" "); // } if (shape.extra && shape.extra.length > 0) { pieces.push("EXTRA "); shape.extra.forEach(function (i, ord) { pieces.push(_ShExWriter._encodeShapeName(i, false)+" "); }); pieces.push(" "); } var empties = ["values", "length", "minlength", "maxlength", "pattern", "flags"]; pieces.push("{\n"); function _writeShapeActions (semActs) { if (!semActs) return; semActs.forEach(function (act) { _ShExWriter._expect(act, "type", "SemAct"); pieces.push(" %", _ShExWriter._encodePredicate(act.name), ("code" in act ? "{"+escapeCode(act.code)+"%"+"}" : "%")); }); } function _writeCardinality (min, max) { if (min === 0 && max === 1) pieces.push("?"); else if (min === 0 && max === UNBOUNDED) pieces.push("*"); else if (min === undefined && max === undefined) ; else if (min === 1 && max === UNBOUNDED) pieces.push("+"); else pieces.push("{", min, ",", (max === UNBOUNDED ? "*" : max), "}"); // by coincidence, both use the same character. } function _writeExpression (expr, indent, parentPrecedence) { function _writeExpressionActions (semActs) { if (semActs) { semActs.forEach(function (act) { _ShExWriter._expect(act, "type", "SemAct"); pieces.push("\n"+indent+" %"); pieces.push(_ShExWriter._encodeValue(act.name)); if ("code" in act) pieces.push("{"+escapeCode(act.code)+"%"+"}"); else pieces.push("%"); }); } } function _exprGroup (exprs, separator, precedence, forceParens) { var needsParens = precedence < parentPrecedence || forceParens; if (needsParens) { pieces.push("("); } exprs.forEach(function (nested, ord) { _writeExpression(nested, indent+" ", precedence) if (ord < exprs.length - 1) pieces.push(separator); }); if (needsParens) { pieces.push(")"); } } function _annotations(annotations) { if (annotations) { annotations.forEach(function (a) { _ShExWriter._expect(a, "type", "Annotation"); pieces.push("//\n"+indent+" "); pieces.push(_ShExWriter._encodeValue(a.predicate)); pieces.push(" "); pieces.push(_ShExWriter._encodeValue(a.object)); }); } } if ("id" in expr) { pieces.push("$"); pieces.push(_ShExWriter._encodeIriOrBlankNode(expr.id, true)); } if (expr.type === "TripleConstraint") { if (expr.inverse) pieces.push("^"); if (expr.negated) pieces.push("!"); pieces.push(indent, _ShExWriter._encodePredicate(expr.predicate), " "); if ("valueExpr" in expr) pieces = pieces.concat(_ShExWriter._writeShapeExpr(expr.valueExpr, done, true, 0)); else pieces.push(". "); _writeCardinality(expr.min, expr.max); _annotations(expr.annotations); _writeExpressionActions(expr.semActs); } else if (expr.type === "OneOf") { var needsParens = "id" in expr || "min" in expr || "max" in expr || "annotations" in expr || "semActs" in expr; _exprGroup(expr.expressions, "\n"+indent+"| ", 1, needsParens || _ShExWriter.forceParens); _writeCardinality(expr.min, expr.max); // t: open1dotclosecardOpt _annotations(expr.annotations); _writeExpressionActions(expr.semActs); } else if (expr.type === "EachOf") { var needsParens = "id" in expr || "min" in expr || "max" in expr || "annotations" in expr || "semActs" in expr; _exprGroup(expr.expressions, ";\n"+indent, 2, needsParens || _ShExWriter.forceParens); _writeCardinality(expr.min, expr.max); // t: open1dotclosecardOpt _annotations(expr.annotations); _writeExpressionActions(expr.semActs); } else if (expr.type === "Inclusion") { pieces.push("&"); pieces.push(_ShExWriter._encodeShapeName(expr.include, false)); } else throw Error("unexpected expr type: " + expr.type); } if (shape.expression) // t: 0, 0Inherit1 _writeExpression(shape.expression, " ", 0); pieces.push("\n}"); _writeShapeActions(shape.semActs); return pieces; } catch (error) { done && done(error); } }, // ### `_writeShape` writes the shape to the output stream _writeNodeConstraint: function (v, done) { var _ShExWriter = this; try { _ShExWriter._expect(v, "type", "NodeConstraint"); var pieces = []; if (v.nodeKind in nodeKinds) pieces.push(nodeKinds[v.nodeKind], " "); else if (v.nodeKind !== undefined) _ShExWriter._error("unexpected nodeKind: " + v.nodeKind); // !!!! this._fillNodeConstraint(pieces, v, done); return pieces; } catch (error) { done && done(error); } }, _fillNodeConstraint: function (pieces, v, done) { var _ShExWriter = this; if (v.datatype && v.values ) _ShExWriter._error("found both datatype and values in " +expr); if (v.datatype) { pieces.push(_ShExWriter._encodeShapeName(v.datatype)); } if (v.values) { pieces.push("["); v.values.forEach(function (t, ord) { if (ord > 1) pieces.push(" "); if (!isTerm(t)) { // expect(t, "type", "IriStemRange"); if (!("type" in t)) runtimeError("expected "+JSON.stringify(t)+" to have a 'type' attribute."); var stemRangeTypes = ["IriStemRange", "LiteralStemRange", "LanguageStemRange"]; if (stemRangeTypes.indexOf(t.type) === -1) runtimeError("expected type attribute '"+t.type+"' to be in '"+stemRangeTypes+"'."); if (!isTerm(t.stem)) { expect(t.stem, "type", "Wildcard"); pieces.push("."); } else { pieces.push(langOrLiteral(t, t.stem) + "~"); } if (t.exclusions) { t.exclusions.forEach(function (c) { pieces.push(" - "); if (!isTerm(c)) { // expect(c, "type", "IriStem"); if (!("type" in c)) runtimeError("expected "+JSON.stringify(c)+" to have a 'type' attribute."); var stemTypes = ["IriStem", "LiteralStem", "LanguageStem"]; if (stemTypes.indexOf(c.type) === -1) runtimeError("expected type attribute '"+c.type+"' to be in '"+stemTypes+"'."); pieces.push(langOrLiteral(t, c.stem) + "~"); } else { pieces.push(langOrLiteral(t, c)); } }); } function langOrLiteral (t, c) { return t.type === "LanguageStemRange" ? "@" + c.value : _ShExWriter._encodeValue(c) } } else { pieces.push(_ShExWriter._encodeValue(t)); } }); pieces.push("]"); } if ('pattern' in v) { var pattern = v.pattern. replace(/\//g, "\\/"); // if (ESCAPE_1.test(pattern)) // pattern = pattern.replace(ESCAPE_g, characterReplacer); var flags = 'flags' in v ? v.flags : ""; pieces.push("/" + pattern + "/" + flags); } ['length', 'minlength', 'maxlength', 'mininclusive', 'minexclusive', 'maxinclusive', 'maxexclusive', 'totaldigits', 'fractiondigits' ].forEach(function (a) { if (v[a]) pieces.push(" ", a, " ", v[a]); }); return pieces; function isTerm (t) { return typeof t !== "object" || "value" in t && Object.keys(t).reduce((r, k) => { return r === false ? r : ["value", "type", "language"].indexOf(k) !== -1; }, true); } }, // ### `_encodeIriOrBlankNode` represents an IRI or blank node _encodeIriOrBlankNode: function (iri, trailingSpace) { trailingSpace = trailingSpace ? ' ' : ''; // A blank node is represented as-is if (iri[0] === '_' && iri[1] === ':') return iri; // Escape special characters if (ESCAPE_1.test(iri)) iri = iri.replace(ESCAPE_g, characterReplacer); // Try to represent the IRI as prefixed name var prefixMatch = this._prefixRegex.exec(iri); return !prefixMatch ? '<' + iri + '>' : (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]) + trailingSpace; }, // ### `_encodeLiteral` represents a literal _encodeLiteral: function (value, type, language) { // Escape special characters if (ESCAPE_1.test(value)) value = value.replace(ESCAPE_g, characterReplacer); // Write the literal, possibly with type or language if (language) return '"' + value + '"@' + language; else if (type) return '"' + value + '"^^' + this._encodeIriOrBlankNode(type); else return '"' + value + '"'; }, // ### `_encodeShapeName` represents a subject _encodeShapeName: function (subject, trailingSpace) { if (subject[0] === '"') throw new Error('A literal as subject is not allowed: ' + subject); return this._encodeIriOrBlankNode(subject, trailingSpace); }, // ### `_encodePredicate` represents a predicate _encodePredicate: function (predicate) { if (predicate[0] === '"') throw new Error('A literal as predicate is not allowed: ' + predicate); return predicate === RDF_TYPE ? 'a' : this._encodeIriOrBlankNode(predicate); }, // ### `_encodeValue` represents an object _encodeValue: function (object) { // Represent an IRI or blank node if (typeof object !== "object") return this._encodeIriOrBlankNode(object); // Represent a literal return this._encodeLiteral(object.value, object.type, object.language); }, // ### `_blockedWrite` replaces `_write` after the writer has been closed _blockedWrite: function () { throw new Error('Cannot write because the writer has been closed.'); }, writeSchema: function (shape, done) { this._writeSchema(shape, done); this.end(done); }, // ### `addShape` adds the shape to the output stream addShape: function (shape, name, done) { this._write( _ShExWriter._encodeShapeName(name, false) + " " + _ShExWriter._writeShapeExpr(shape, done, true, 0).join(""), done ); }, // ### `addShapes` adds the shapes to the output stream addShapes: function (shapes) { for (var i = 0; i < shapes.length; i++) this.addShape(shapes[i]); }, // ### `addPrefix` adds the prefix to the output stream addPrefix: function (prefix, iri, done) { var prefixes = {}; prefixes[prefix] = iri; this.addPrefixes(prefixes, done); }, // ### `addPrefixes` adds the prefixes to the output stream addPrefixes: function (prefixes, done) { // Add all useful prefixes var prefixIRIs = this._prefixIRIs, hasPrefixes = false; for (var prefix in prefixes) { // Verify whether the prefix can be used and does not exist yet var iri = prefixes[prefix]; if (// @@ /[#\/]$/.test(iri) && !! what was that? prefixIRIs[iri] !== (prefix += ':')) { hasPrefixes = true; prefixIRIs[iri] = prefix; // Write prefix this._write('PREFIX ' + prefix + ' <' + iri + '>\n'); } } // Recreate the prefix matcher if (hasPrefixes) { var IRIlist = '', prefixList = ''; for (var prefixIRI in prefixIRIs) { IRIlist += IRIlist ? '|' + prefixIRI : prefixIRI; prefixList += (prefixList ? '|' : '') + prefixIRIs[prefixIRI]; } IRIlist = IRIlist.replace(/[\]\/\(\)\*\+\?\.\\\$]/g, '\\$&'); this._prefixRegex = new RegExp('^(?:' + prefixList + ')[^\/]*$|' + '^(' + IRIlist + ')([a-zA-Z][\\-_a-zA-Z0-9]*)$'); } // End a prefix block with a newline this._write(hasPrefixes ? '\n' : '', done); }, // ### `_prefixRegex` matches a prefixed name or IRI that begins with one of the added prefixes _prefixRegex: /$0^/, // ### `end` signals the end of the output stream end: function (done) { // Disallow further writing this._write = this._blockedWrite; // Try to end the underlying stream, ensuring done is called exactly one time var singleDone = done && function (error, result) { singleDone = null, done(error, result); }; if (this._endStream) { try { return this._outputStream.end(singleDone); } catch (error) { /* error closing stream */ } } singleDone && singleDone(); }, }; // Replaces a character by its escaped version function characterReplacer(character) { // Replace a single character by its escaped version var result = ESCAPE_replacements[character]; if (result === undefined) { // Replace a single character with its 4-bit unicode escape sequence if (character.length === 1) { result = character.charCodeAt(0).toString(16); result = '\\u0000'.substr(0, 6 - result.length) + result; } // Replace a surrogate pair with its 8-bit unicode escape sequence else { result = ((character.charCodeAt(0) - 0xD800) * 0x400 + character.charCodeAt(1) + 0x2400).toString(16); result = '\\U00000000'.substr(0, 10 - result.length) + result; } } return result; } function escapeCode (code) { return code.replace(/\\/g, "\\\\").replace(/%/g, "\\%") } /** _throwError: overridable function to throw Errors(). * * @param func (optional): function at which to truncate stack trace * @param str: error message */ function _throwError (func, str) { if (typeof func !== "function") { str = func; func = _throwError; } var e = new Error(str); Error.captureStackTrace(e, func); throw e; } // Expect property p with value v in object o function expect (o, p, v) { if (!(p in o)) this._error(expect, "expected "+o+" to have a ."+p); if (arguments.length > 2 && o[p] !== v) this._error(expect, "expected "+o[o]+" to equal ."+v); } // The empty function function noop () {} // ## Exports // Export the `ShExWriter` class as a whole. if (typeof require !== 'undefined' && typeof exports !== 'undefined') module.exports = ShExWriter; // node environment
lib/ShExWriter.js
// **ShExWriter** writes ShEx documents. var util = require('util'); var UNBOUNDED = -1; // Matches a literal as represented in memory by the ShEx library var ShExLiteralMatcher = /^"([^]*)"(?:\^\^(.+)|@([\-a-z]+))?$/i; // rdf:type predicate (for 'a' abbreviation) var RDF_PREFIX = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', RDF_TYPE = RDF_PREFIX + 'type'; // Characters in literals that require escaping var ESCAPE_1 = /["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/, ESCAPE_g = /["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g, ESCAPE_replacements = { '\\': '\\\\', '"': '\\"', '/': '\\/', '\t': '\\t', '\n': '\\n', '\r': '\\r', '\b': '\\b', '\f': '\\f' }; var nodeKinds = { 'iri': "IRI", 'bnode': "BNODE", 'literal': "LITERAL", 'nonliteral': "NONLITERAL" }; var nonLitNodeKinds = { 'iri': "IRI", 'bnode': "BNODE", 'literal': "LITERAL", 'nonliteral': "NONLITERAL" }; // ## Constructor function ShExWriter(outputStream, options) { if (!(this instanceof ShExWriter)) return new ShExWriter(outputStream, options); // Shift arguments if the first argument is not a stream if (outputStream && typeof outputStream.write !== 'function') options = outputStream, outputStream = null; options = options || {}; // If no output stream given, send the output as string through the end callback if (!outputStream) { var output = ''; this._outputStream = { write: function (chunk, encoding, done) { output += chunk; done && done(); }, end: function (done) { done && done(null, output); }, }; this._endStream = true; } else { this._outputStream = outputStream; this._endStream = options.end === undefined ? true : !!options.end; } // Initialize writer, depending on the format this._prefixIRIs = Object.create(null); options.prefixes && this.addPrefixes(options.prefixes); this._error = options.error || _throwError; this.forceParens = !options.simplifyParentheses; // default to false this._expect = options.lax ? noop : expect; } ShExWriter.prototype = { // ## Private methods // ### `_write` writes the argument to the output stream _write: function (string, callback) { this._outputStream.write(string, 'utf8', callback); }, // ### `_writeSchema` writes the shape to the output stream _writeSchema: function (schema, done) { var _ShExWriter = this; this._expect(schema, "type", "Schema"); _ShExWriter.addPrefixes(schema.prefixes); if (schema.base) _ShExWriter._write("BASE " + this._encodeIriOrBlankNode(schema.base) + "\n"); if (schema.startActs) schema.startActs.forEach(function (act) { _ShExWriter._expect(act, "type", "SemAct"); _ShExWriter._write(" %"+ _ShExWriter._encodePredicate(act.name)+ ("code" in act ? "{"+escapeCode(act.code)+"%"+"}" : "%")); }); if (schema.start) _ShExWriter._write("start = " + _ShExWriter._writeShapeExpr(schema.start, done, true, 0).join('') + "\n") if ("shapes" in schema) Object.keys(schema.shapes).forEach(function (label) { _ShExWriter._write( _ShExWriter._encodeShapeName(label, false) + " " + _ShExWriter._writeShapeExpr(schema.shapes[label], done, true, 0).join("")+"\n", done ); }) }, _writeShapeExpr: function (shapeExpr, done, forceBraces, parentPrec) { var _ShExWriter = this; var pieces = []; if (shapeExpr.type === "ShapeRef") pieces.push("@", _ShExWriter._encodeShapeName(shapeExpr.reference)); // !!! []s for precedence! else if (shapeExpr.type === "ShapeExternal") pieces.push("EXTERNAL"); else if (shapeExpr.type === "ShapeAnd") { if (parentPrec > 3) pieces.push("("); shapeExpr.shapeExprs.forEach(function (expr, ord) { if (ord > 0 && // !!! grammar rules too weird here !((shapeExpr.shapeExprs[ord-1].type === "NodeConstraint" && (shapeExpr.shapeExprs[ord ].type === "Shape" || shapeExpr.shapeExprs[ord ].type === "ShapeRef")) || (shapeExpr.shapeExprs[ord ].type === "NodeConstraint" && (shapeExpr.shapeExprs[ord-1].type === "Shape" || shapeExpr.shapeExprs[ord-1].type === "ShapeRef")))) pieces.push(" AND "); pieces = pieces.concat(_ShExWriter._writeShapeExpr(expr, done, false, 3)); }); if (parentPrec > 3) pieces.push(")"); } else if (shapeExpr.type === "ShapeOr") { if (parentPrec > 2) pieces.push("("); shapeExpr.shapeExprs.forEach(function (expr, ord) { if (ord > 0) pieces.push(" OR "); pieces = pieces.concat(_ShExWriter._writeShapeExpr(expr, done, forceBraces, 2)); }); if (parentPrec > 2) pieces.push(")"); } else if (shapeExpr.type === "ShapeNot") { pieces.push("NOT "); pieces = pieces.concat(_ShExWriter._writeShapeExpr(shapeExpr.shapeExpr, done, forceBraces, 1)); } else if (shapeExpr.type === "Shape") { pieces = pieces.concat(_ShExWriter._writeShape(shapeExpr, done, forceBraces)); } else if (shapeExpr.type === "NodeConstraint") { pieces = pieces.concat(_ShExWriter._writeNodeConstraint(shapeExpr, done, forceBraces)); } else throw Error("expected Shape{,And,Or,Ref} or NodeConstraint in " + util.inspect(shapeExpr)); return pieces; }, // ### `_writeShape` writes the shape to the output stream _writeShape: function (shape, done, forceBraces) { var _ShExWriter = this; try { var pieces = []; // guessing push/join is faster than concat this._expect(shape, "type", "Shape"); if (shape.closed) pieces.push("CLOSED "); // if (shape.inherit && shape.inherit.length > 0) { futureWork // pieces.push("&"); // shape.inherit.forEach(function (i, ord) { // if (ord) // pieces.push(" ") // pieces.push(_ShExWriter._encodeShapeName(i, ord > 0)); // }); // pieces.push(" "); // } if (shape.extra && shape.extra.length > 0) { pieces.push("EXTRA "); shape.extra.forEach(function (i, ord) { pieces.push(_ShExWriter._encodeShapeName(i, false)+" "); }); pieces.push(" "); } var empties = ["values", "length", "minlength", "maxlength", "pattern", "flags"]; if (shape.expression || (forceBraces && Object.keys(shape).filter(k => { return empties.indexOf(k) !== -1; }).length === 0)) { pieces.push("{\n"); function _writeShapeActions (semActs) { if (!semActs) return; semActs.forEach(function (act) { _ShExWriter._expect(act, "type", "SemAct"); pieces.push(" %", _ShExWriter._encodePredicate(act.name), ("code" in act ? "{"+escapeCode(act.code)+"%"+"}" : "%")); }); } function _writeCardinality (min, max) { if (min === 0 && max === 1) pieces.push("?"); else if (min === 0 && max === UNBOUNDED) pieces.push("*"); else if (min === undefined && max === undefined) ; else if (min === 1 && max === UNBOUNDED) pieces.push("+"); else pieces.push("{", min, ",", (max === UNBOUNDED ? "*" : max), "}"); // by coincidence, both use the same character. } function _writeExpression (expr, indent, parentPrecedence) { function _writeExpressionActions (semActs) { if (semActs) { semActs.forEach(function (act) { _ShExWriter._expect(act, "type", "SemAct"); pieces.push("\n"+indent+" %"); pieces.push(_ShExWriter._encodeValue(act.name)); if ("code" in act) pieces.push("{"+escapeCode(act.code)+"%"+"}"); else pieces.push("%"); }); } } function _exprGroup (exprs, separator, precedence, forceParens) { var needsParens = precedence < parentPrecedence || forceParens; if (needsParens) { pieces.push("("); } exprs.forEach(function (nested, ord) { _writeExpression(nested, indent+" ", precedence) if (ord < exprs.length - 1) pieces.push(separator); }); if (needsParens) { pieces.push(")"); } } function _annotations(annotations) { if (annotations) { annotations.forEach(function (a) { _ShExWriter._expect(a, "type", "Annotation"); pieces.push("//\n"+indent+" "); pieces.push(_ShExWriter._encodeValue(a.predicate)); pieces.push(" "); pieces.push(_ShExWriter._encodeValue(a.object)); }); } } if ("id" in expr) { pieces.push("$"); pieces.push(_ShExWriter._encodeIriOrBlankNode(expr.id, true)); } if (expr.type === "TripleConstraint") { if (expr.inverse) pieces.push("^"); if (expr.negated) pieces.push("!"); pieces.push(indent, _ShExWriter._encodePredicate(expr.predicate), " "); if ("valueExpr" in expr) pieces = pieces.concat(_ShExWriter._writeShapeExpr(expr.valueExpr, done, true, 0)); else pieces.push(". "); _writeCardinality(expr.min, expr.max); _annotations(expr.annotations); _writeExpressionActions(expr.semActs); } else if (expr.type === "OneOf") { var needsParens = "id" in expr || "min" in expr || "max" in expr || "annotations" in expr || "semActs" in expr; _exprGroup(expr.expressions, "\n"+indent+"| ", 1, needsParens || _ShExWriter.forceParens); _writeCardinality(expr.min, expr.max); // t: open1dotclosecardOpt _annotations(expr.annotations); _writeExpressionActions(expr.semActs); } else if (expr.type === "EachOf") { var needsParens = "id" in expr || "min" in expr || "max" in expr || "annotations" in expr || "semActs" in expr; _exprGroup(expr.expressions, ";\n"+indent, 2, needsParens || _ShExWriter.forceParens); _writeCardinality(expr.min, expr.max); // t: open1dotclosecardOpt _annotations(expr.annotations); _writeExpressionActions(expr.semActs); } else if (expr.type === "Inclusion") { pieces.push("&"); pieces.push(_ShExWriter._encodeShapeName(expr.include, false)); } else throw Error("unexpected expr type: " + expr.type); } if (shape.expression) // t: 0, 0Inherit1 _writeExpression(shape.expression, " ", 0); pieces.push("\n}"); } _writeShapeActions(shape.semActs); return pieces; } catch (error) { done && done(error); } }, // ### `_writeShape` writes the shape to the output stream _writeNodeConstraint: function (v, done) { var _ShExWriter = this; try { _ShExWriter._expect(v, "type", "NodeConstraint"); var pieces = []; if (v.nodeKind in nodeKinds) pieces.push(nodeKinds[v.nodeKind], " "); else if (v.nodeKind !== undefined) _ShExWriter._error("unexpected nodeKind: " + v.nodeKind); // !!!! this._fillNodeConstraint(pieces, v, done); return pieces; } catch (error) { done && done(error); } }, _fillNodeConstraint: function (pieces, v, done) { var _ShExWriter = this; if (v.datatype && v.values ) _ShExWriter._error("found both datatype and values in " +expr); if (v.datatype) { pieces.push(_ShExWriter._encodeShapeName(v.datatype)); } if (v.values) { pieces.push("["); v.values.forEach(function (t, ord) { if (ord > 1) pieces.push(" "); if (!isTerm(t)) { // expect(t, "type", "IriStemRange"); if (!("type" in t)) runtimeError("expected "+JSON.stringify(t)+" to have a 'type' attribute."); var stemRangeTypes = ["IriStemRange", "LiteralStemRange", "LanguageStemRange"]; if (stemRangeTypes.indexOf(t.type) === -1) runtimeError("expected type attribute '"+t.type+"' to be in '"+stemRangeTypes+"'."); if (!isTerm(t.stem)) { expect(t.stem, "type", "Wildcard"); pieces.push("."); } else { pieces.push(langOrLiteral(t, t.stem) + "~"); } if (t.exclusions) { t.exclusions.forEach(function (c) { pieces.push(" - "); if (!isTerm(c)) { // expect(c, "type", "IriStem"); if (!("type" in c)) runtimeError("expected "+JSON.stringify(c)+" to have a 'type' attribute."); var stemTypes = ["IriStem", "LiteralStem", "LanguageStem"]; if (stemTypes.indexOf(c.type) === -1) runtimeError("expected type attribute '"+c.type+"' to be in '"+stemTypes+"'."); pieces.push(langOrLiteral(t, c.stem) + "~"); } else { pieces.push(langOrLiteral(t, c)); } }); } function langOrLiteral (t, c) { return t.type === "LanguageStemRange" ? "@" + c.value : _ShExWriter._encodeValue(c) } } else { pieces.push(_ShExWriter._encodeValue(t)); } }); pieces.push("]"); } if ('pattern' in v) { var pattern = v.pattern. replace(/\//g, "\\/"); // if (ESCAPE_1.test(pattern)) // pattern = pattern.replace(ESCAPE_g, characterReplacer); var flags = 'flags' in v ? v.flags : ""; pieces.push("/" + pattern + "/" + flags); } ['length', 'minlength', 'maxlength', 'mininclusive', 'minexclusive', 'maxinclusive', 'maxexclusive', 'totaldigits', 'fractiondigits' ].forEach(function (a) { if (v[a]) pieces.push(" ", a, " ", v[a]); }); return pieces; function isTerm (t) { return typeof t !== "object" || "value" in t && Object.keys(t).reduce((r, k) => { return r === false ? r : ["value", "type", "language"].indexOf(k) !== -1; }, true); } }, // ### `_encodeIriOrBlankNode` represents an IRI or blank node _encodeIriOrBlankNode: function (iri, trailingSpace) { trailingSpace = trailingSpace ? ' ' : ''; // A blank node is represented as-is if (iri[0] === '_' && iri[1] === ':') return iri; // Escape special characters if (ESCAPE_1.test(iri)) iri = iri.replace(ESCAPE_g, characterReplacer); // Try to represent the IRI as prefixed name var prefixMatch = this._prefixRegex.exec(iri); return !prefixMatch ? '<' + iri + '>' : (!prefixMatch[1] ? iri : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]) + trailingSpace; }, // ### `_encodeLiteral` represents a literal _encodeLiteral: function (value, type, language) { // Escape special characters if (ESCAPE_1.test(value)) value = value.replace(ESCAPE_g, characterReplacer); // Write the literal, possibly with type or language if (language) return '"' + value + '"@' + language; else if (type) return '"' + value + '"^^' + this._encodeIriOrBlankNode(type); else return '"' + value + '"'; }, // ### `_encodeShapeName` represents a subject _encodeShapeName: function (subject, trailingSpace) { if (subject[0] === '"') throw new Error('A literal as subject is not allowed: ' + subject); return this._encodeIriOrBlankNode(subject, trailingSpace); }, // ### `_encodePredicate` represents a predicate _encodePredicate: function (predicate) { if (predicate[0] === '"') throw new Error('A literal as predicate is not allowed: ' + predicate); return predicate === RDF_TYPE ? 'a' : this._encodeIriOrBlankNode(predicate); }, // ### `_encodeValue` represents an object _encodeValue: function (object) { // Represent an IRI or blank node if (typeof object !== "object") return this._encodeIriOrBlankNode(object); // Represent a literal return this._encodeLiteral(object.value, object.type, object.language); }, // ### `_blockedWrite` replaces `_write` after the writer has been closed _blockedWrite: function () { throw new Error('Cannot write because the writer has been closed.'); }, writeSchema: function (shape, done) { this._writeSchema(shape, done); this.end(done); }, // ### `addShape` adds the shape to the output stream addShape: function (shape, name, done) { this._write( _ShExWriter._encodeShapeName(name, false) + " " + _ShExWriter._writeShapeExpr(shape, done, true, 0).join(""), done ); }, // ### `addShapes` adds the shapes to the output stream addShapes: function (shapes) { for (var i = 0; i < shapes.length; i++) this.addShape(shapes[i]); }, // ### `addPrefix` adds the prefix to the output stream addPrefix: function (prefix, iri, done) { var prefixes = {}; prefixes[prefix] = iri; this.addPrefixes(prefixes, done); }, // ### `addPrefixes` adds the prefixes to the output stream addPrefixes: function (prefixes, done) { // Add all useful prefixes var prefixIRIs = this._prefixIRIs, hasPrefixes = false; for (var prefix in prefixes) { // Verify whether the prefix can be used and does not exist yet var iri = prefixes[prefix]; if (// @@ /[#\/]$/.test(iri) && !! what was that? prefixIRIs[iri] !== (prefix += ':')) { hasPrefixes = true; prefixIRIs[iri] = prefix; // Write prefix this._write('PREFIX ' + prefix + ' <' + iri + '>\n'); } } // Recreate the prefix matcher if (hasPrefixes) { var IRIlist = '', prefixList = ''; for (var prefixIRI in prefixIRIs) { IRIlist += IRIlist ? '|' + prefixIRI : prefixIRI; prefixList += (prefixList ? '|' : '') + prefixIRIs[prefixIRI]; } IRIlist = IRIlist.replace(/[\]\/\(\)\*\+\?\.\\\$]/g, '\\$&'); this._prefixRegex = new RegExp('^(?:' + prefixList + ')[^\/]*$|' + '^(' + IRIlist + ')([a-zA-Z][\\-_a-zA-Z0-9]*)$'); } // End a prefix block with a newline this._write(hasPrefixes ? '\n' : '', done); }, // ### `_prefixRegex` matches a prefixed name or IRI that begins with one of the added prefixes _prefixRegex: /$0^/, // ### `end` signals the end of the output stream end: function (done) { // Disallow further writing this._write = this._blockedWrite; // Try to end the underlying stream, ensuring done is called exactly one time var singleDone = done && function (error, result) { singleDone = null, done(error, result); }; if (this._endStream) { try { return this._outputStream.end(singleDone); } catch (error) { /* error closing stream */ } } singleDone && singleDone(); }, }; // Replaces a character by its escaped version function characterReplacer(character) { // Replace a single character by its escaped version var result = ESCAPE_replacements[character]; if (result === undefined) { // Replace a single character with its 4-bit unicode escape sequence if (character.length === 1) { result = character.charCodeAt(0).toString(16); result = '\\u0000'.substr(0, 6 - result.length) + result; } // Replace a surrogate pair with its 8-bit unicode escape sequence else { result = ((character.charCodeAt(0) - 0xD800) * 0x400 + character.charCodeAt(1) + 0x2400).toString(16); result = '\\U00000000'.substr(0, 10 - result.length) + result; } } return result; } function escapeCode (code) { return code.replace(/\\/g, "\\\\").replace(/%/g, "\\%") } /** _throwError: overridable function to throw Errors(). * * @param func (optional): function at which to truncate stack trace * @param str: error message */ function _throwError (func, str) { if (typeof func !== "function") { str = func; func = _throwError; } var e = new Error(str); Error.captureStackTrace(e, func); throw e; } // Expect property p with value v in object o function expect (o, p, v) { if (!(p in o)) this._error(expect, "expected "+o+" to have a ."+p); if (arguments.length > 2 && o[p] !== v) this._error(expect, "expected "+o[o]+" to equal ."+v); } // The empty function function noop () {} // ## Exports // Export the `ShExWriter` class as a whole. if (typeof require !== 'undefined' && typeof exports !== 'undefined') module.exports = ShExWriter; // node environment
- old special handling for focus constraints
lib/ShExWriter.js
- old special handling for focus constraints
<ide><path>ib/ShExWriter.js <ide> pieces.push(" "); <ide> } <ide> var empties = ["values", "length", "minlength", "maxlength", "pattern", "flags"]; <del> if (shape.expression || (forceBraces && Object.keys(shape).filter(k => { <del> return empties.indexOf(k) !== -1; <del> }).length === 0)) { <ide> pieces.push("{\n"); <ide> <ide> function _writeShapeActions (semActs) { <ide> if (shape.expression) // t: 0, 0Inherit1 <ide> _writeExpression(shape.expression, " ", 0); <ide> pieces.push("\n}"); <del> } <ide> _writeShapeActions(shape.semActs); <ide> <ide> return pieces;
Java
apache-2.0
a22287e231637432ddeed3889979c09ce64d3ec6
0
rodvar/MFandroidTest
package com.rodvar.mfandroidtest; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.rodvar.mfandroidtest.adapter.CoffeeShopAdapter; import com.rodvar.mfandroidtest.backend.CallMeBack; import com.rodvar.mfandroidtest.backend.task.SearchTask; import com.rodvar.mfandroidtest.model.IBaseModel; import com.rodvar.mfandroidtest.model.Venue; import java.text.DateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; public class CoffeeListActivity extends ActionBarActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final String LAT_KEY = "##LAT##"; private static final String LON_KEY = "##LON##"; private static final String BASE_URL = "https://api.foursquare.com/v2/venues/search?client_id=ACAO2JPKM1MXHQJCK45IIFKRFR2ZVL0QASMCBCG5NPJQWF2G&client_secret=YZCKUYJ1WHUV2QICBXUBEILZI1DMPUIDP5SHV043O04FKBHL&v=20130815&ll=" + LAT_KEY + "," + LON_KEY + "&query=coffee"; private static final long LOCATION_INTERVAL = 10000l; private static final long LOCATION_FASTEST_INTERVAL = 5000l; private CoffeeShopAdapter coffeeShopAdapter; private GoogleApiClient googleApiClient; private LocationRequest locationRequest; private boolean isRequestingLocationUpdates; private Location currentLocation; private String lastUpdateTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.buildGoogleApiClient(); this.createLocationRequest(); setContentView(R.layout.activity_coffee_list); ListView listView = (ListView) this.findViewById(R.id.shopList); this.coffeeShopAdapter = new CoffeeShopAdapter(this, fakeList()); listView.setAdapter(this.coffeeShopAdapter); } private List<Venue> fakeList() { List<Venue> list = new LinkedList<Venue>(); list.add(new Venue("Pepe", "91 Goulburn St", Long.valueOf(23l))); list.add(new Venue("Pregfa", "231 Tuvieja en tanga", Long.valueOf(233l))); list.add(new Venue("Largartoide", "91 Marriot St", Long.valueOf(354l))); list.add(new Venue("Coffeee puto", "343 Marquick St", Long.valueOf(53l))); return list; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_coffee_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onConnected(Bundle connectionHint) { Log.d("LOCATION", "Connected!"); this.currentLocation = LocationServices.FusedLocationApi.getLastLocation( googleApiClient); this.startLocationUpdates(); } @Override public void onLocationChanged(Location location) { currentLocation = location; lastUpdateTime = DateFormat.getTimeInstance().format(new Date()); new SearchTask(new CallMeBack() { @Override public void done(IBaseModel object) { List<Venue> venues = (List<Venue>) object; Toast.makeText(CoffeeListActivity.this, venues.get(0).getName(), Toast.LENGTH_SHORT).show(); } @Override public void onError() { Toast.makeText(CoffeeListActivity.this, "ERROR on call!", Toast.LENGTH_SHORT).show(); } }, this.buildURL()).execute((String[]) null); } private String buildURL() { return BASE_URL.replace(LAT_KEY, String.valueOf(this.currentLocation.getLatitude())).replace(LON_KEY, String.valueOf(this.currentLocation.getLongitude())); } @Override protected void onResume() { super.onResume(); this.checkGPS(); if (googleApiClient.isConnected() && !isRequestingLocationUpdates) this.startLocationUpdates(); else googleApiClient.connect(); } private void checkGPS() { if (!((LocationManager) this.getSystemService(Context.LOCATION_SERVICE)) .isProviderEnabled(LocationManager.GPS_PROVIDER)) { Intent gpsOptionsIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(gpsOptionsIntent); } } @Override protected void onPause() { super.onPause(); this.stopLocationUpdates(); } protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, locationRequest, this); this.isRequestingLocationUpdates = true; } protected void stopLocationUpdates() { try { LocationServices.FusedLocationApi.removeLocationUpdates( googleApiClient, this); this.isRequestingLocationUpdates = false; } catch (Exception e) { Log.e("LOCATION", "Failed", e); } } protected void createLocationRequest() { this.locationRequest = new LocationRequest(); this.locationRequest.setInterval(LOCATION_INTERVAL); this.locationRequest.setFastestInterval(LOCATION_FASTEST_INTERVAL); this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //BALANCED_POWER_ACCURACY } protected synchronized void buildGoogleApiClient() { this.googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { // TODO Log.w("LOCATION", "CONNECTION FAILED"); } @Override public void onConnectionSuspended(int i) { // TODO Log.w("LOCATION", "CONNECTION SUSPENDED"); } }
app/src/main/java/com/rodvar/mfandroidtest/CoffeeListActivity.java
package com.rodvar.mfandroidtest; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.rodvar.mfandroidtest.adapter.CoffeeShopAdapter; import com.rodvar.mfandroidtest.model.Venue; import java.text.DateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; public class CoffeeListActivity extends ActionBarActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final long LOCATION_INTERVAL = 10000l; private static final long LOCATION_FASTEST_INTERVAL = 5000l; private CoffeeShopAdapter coffeeShopAdapter; private GoogleApiClient googleApiClient; private LocationRequest locationRequest; private boolean isRequestingLocationUpdates; private Location currentLocation; private String lastUpdateTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.buildGoogleApiClient(); this.createLocationRequest(); setContentView(R.layout.activity_coffee_list); ListView listView = (ListView) this.findViewById(R.id.shopList); this.coffeeShopAdapter = new CoffeeShopAdapter(this, fakeList()); listView.setAdapter(this.coffeeShopAdapter); } private List<Venue> fakeList() { List<Venue> list = new LinkedList<Venue>(); list.add(new Venue("Pepe", "91 Goulburn St", Long.valueOf(23l))); list.add(new Venue("Pregfa", "231 Tuvieja en tanga", Long.valueOf(233l))); list.add(new Venue("Largartoide", "91 Marriot St", Long.valueOf(354l))); list.add(new Venue("Coffeee puto", "343 Marquick St", Long.valueOf(53l))); return list; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_coffee_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onConnected(Bundle connectionHint) { Log.d("LOCATION", "Connected!"); this.currentLocation = LocationServices.FusedLocationApi.getLastLocation( googleApiClient); this.startLocationUpdates(); } @Override public void onLocationChanged(Location location) { currentLocation = location; lastUpdateTime = DateFormat.getTimeInstance().format(new Date()); Toast.makeText(this, "OK!", Toast.LENGTH_SHORT).show(); // TODO update } @Override protected void onResume() { super.onResume(); this.checkGPS(); if (googleApiClient.isConnected() && !isRequestingLocationUpdates) this.startLocationUpdates(); else googleApiClient.connect(); } private void checkGPS() { if (!((LocationManager) this.getSystemService(Context.LOCATION_SERVICE)) .isProviderEnabled(LocationManager.GPS_PROVIDER)) { Intent gpsOptionsIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(gpsOptionsIntent); } } @Override protected void onPause() { super.onPause(); this.stopLocationUpdates(); } protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, locationRequest, this); this.isRequestingLocationUpdates = true; } protected void stopLocationUpdates() { try { LocationServices.FusedLocationApi.removeLocationUpdates( googleApiClient, this); this.isRequestingLocationUpdates = false; } catch (Exception e) { Log.e("LOCATION", "Failed", e); } } protected void createLocationRequest() { this.locationRequest = new LocationRequest(); this.locationRequest.setInterval(LOCATION_INTERVAL); this.locationRequest.setFastestInterval(LOCATION_FASTEST_INTERVAL); this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //BALANCED_POWER_ACCURACY } protected synchronized void buildGoogleApiClient() { this.googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { // TODO Log.w("LOCATION", "CONNECTION FAILED"); } @Override public void onConnectionSuspended(int i) { // TODO Log.w("LOCATION", "CONNECTION SUSPENDED"); } }
Parsing foursquare response ! :)
app/src/main/java/com/rodvar/mfandroidtest/CoffeeListActivity.java
Parsing foursquare response ! :)
<ide><path>pp/src/main/java/com/rodvar/mfandroidtest/CoffeeListActivity.java <ide> import com.google.android.gms.location.LocationRequest; <ide> import com.google.android.gms.location.LocationServices; <ide> import com.rodvar.mfandroidtest.adapter.CoffeeShopAdapter; <add>import com.rodvar.mfandroidtest.backend.CallMeBack; <add>import com.rodvar.mfandroidtest.backend.task.SearchTask; <add>import com.rodvar.mfandroidtest.model.IBaseModel; <ide> import com.rodvar.mfandroidtest.model.Venue; <ide> <ide> import java.text.DateFormat; <ide> <ide> <ide> public class CoffeeListActivity extends ActionBarActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { <add> <add> private static final String LAT_KEY = "##LAT##"; <add> private static final String LON_KEY = "##LON##"; <add> private static final String BASE_URL = "https://api.foursquare.com/v2/venues/search?client_id=ACAO2JPKM1MXHQJCK45IIFKRFR2ZVL0QASMCBCG5NPJQWF2G&client_secret=YZCKUYJ1WHUV2QICBXUBEILZI1DMPUIDP5SHV043O04FKBHL&v=20130815&ll=" + LAT_KEY + "," + LON_KEY + "&query=coffee"; <ide> <ide> private static final long LOCATION_INTERVAL = 10000l; <ide> private static final long LOCATION_FASTEST_INTERVAL = 5000l; <ide> public void onLocationChanged(Location location) { <ide> currentLocation = location; <ide> lastUpdateTime = DateFormat.getTimeInstance().format(new Date()); <del> Toast.makeText(this, "OK!", Toast.LENGTH_SHORT).show(); <del> // TODO update <add> new SearchTask(new CallMeBack() { <add> @Override <add> public void done(IBaseModel object) { <add> List<Venue> venues = (List<Venue>) object; <add> Toast.makeText(CoffeeListActivity.this, venues.get(0).getName(), Toast.LENGTH_SHORT).show(); <add> } <add> <add> @Override <add> public void onError() { <add> Toast.makeText(CoffeeListActivity.this, "ERROR on call!", Toast.LENGTH_SHORT).show(); <add> } <add> }, this.buildURL()).execute((String[]) null); <add> } <add> <add> private String buildURL() { <add> return BASE_URL.replace(LAT_KEY, String.valueOf(this.currentLocation.getLatitude())).replace(LON_KEY, String.valueOf(this.currentLocation.getLongitude())); <ide> } <ide> <ide> @Override
Java
apache-2.0
e64542e9ffaa5e35996b9c8f4a1c5cab00c0988c
0
JetBrains/xodus,JetBrains/xodus,JetBrains/xodus
/** * Copyright 2010 - 2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.entitystore.util; import jetbrains.exodus.core.dataStructures.hash.LongHashSet; import jetbrains.exodus.core.dataStructures.hash.LongSet; import jetbrains.exodus.entitystore.EntityId; import jetbrains.exodus.entitystore.PersistentEntityId; import jetbrains.exodus.entitystore.iterate.EntityIdSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.BitSet; import java.util.Iterator; import java.util.NoSuchElementException; public class ImmutableSingleTypeEntityIdBitSet implements EntityIdSet { private final int singleTypeId; private final int size; private final long min; private final long max; private final BitSet data; public ImmutableSingleTypeEntityIdBitSet(final int singleTypeId, final long[] source) { this.singleTypeId = singleTypeId; size = source.length; min = source[0]; max = source[size - 1]; final long bitsCount = max - min + 1; if (min < 0 || bitsCount >= Integer.MAX_VALUE) { throw new IllegalArgumentException(); } data = new BitSet((int) bitsCount); for (final long value : source) { data.set((int) (value - min)); } } @Override public EntityIdSet add(@Nullable EntityId id) { throw new UnsupportedOperationException(); } @Override public EntityIdSet add(int typeId, long localId) { throw new UnsupportedOperationException(); } @Override public boolean contains(@Nullable EntityId id) { return id != null && contains(id.getTypeId(), id.getLocalId()); } @Override public boolean contains(int typeId, long localId) { return typeId == singleTypeId && localId >= min && localId <= max && data.get((int) (localId - min)); } @Override public boolean remove(@Nullable EntityId id) { throw new UnsupportedOperationException(); } @Override public boolean remove(int typeId, long localId) { throw new UnsupportedOperationException(); } @Override public int count() { return size; } @Override public Iterator<EntityId> iterator() { return new IdIterator(); } @NotNull @Override public LongSet getTypeSetSnapshot(int typeId) { if (typeId == singleTypeId) { LongHashSet result = new LongHashSet(size); int next = data.nextSetBit(0); while (next != -1) { result.add(next + min); // if (next == Integer.MAX_VALUE) { break; } next = data.nextSetBit(next + 1); } return result; } return LongSet.EMPTY; } class IdIterator implements Iterator<EntityId> { int nextBitIndex = data.nextSetBit(0); @Override public boolean hasNext() { return nextBitIndex != -1; } @Override public EntityId next() { if (nextBitIndex != -1) { final int bitIndex = nextBitIndex; nextBitIndex = data.nextSetBit(nextBitIndex + 1); return new PersistentEntityId(singleTypeId, bitIndex + min); } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } }
entity-store/src/main/java/jetbrains/exodus/entitystore/util/ImmutableSingleTypeEntityIdBitSet.java
/** * Copyright 2010 - 2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.entitystore.util; import jetbrains.exodus.core.dataStructures.hash.LongHashSet; import jetbrains.exodus.core.dataStructures.hash.LongSet; import jetbrains.exodus.entitystore.EntityId; import jetbrains.exodus.entitystore.PersistentEntityId; import jetbrains.exodus.entitystore.iterate.EntityIdSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.BitSet; import java.util.Iterator; import java.util.NoSuchElementException; public class ImmutableSingleTypeEntityIdBitSet implements EntityIdSet { private final int singleTypeId; private final int size; private final long min; private final long max; private final BitSet data; public ImmutableSingleTypeEntityIdBitSet(final int singleTypeId, final long[] source) { this.singleTypeId = singleTypeId; size = source.length; min = source[0]; max = source[size - 1]; final long bitsCount = max - min + 1; if (min < 0 || bitsCount >= Integer.MAX_VALUE) { throw new IllegalArgumentException(); } data = new BitSet(((int) bitsCount)); for (final long value : source) { data.set((int) (value - min)); } } @Override public EntityIdSet add(@Nullable EntityId id) { throw new UnsupportedOperationException(); } @Override public EntityIdSet add(int typeId, long localId) { throw new UnsupportedOperationException(); } @Override public boolean contains(@Nullable EntityId id) { return id != null && contains(id.getTypeId(), id.getLocalId()); } @Override public boolean contains(int typeId, long localId) { return typeId == singleTypeId && localId >= min && localId <= max && data.get((int) (localId - min)); } @Override public boolean remove(@Nullable EntityId id) { throw new UnsupportedOperationException(); } @Override public boolean remove(int typeId, long localId) { throw new UnsupportedOperationException(); } @Override public int count() { return size; } @Override public Iterator<EntityId> iterator() { return new IdIterator(); } @NotNull @Override public LongSet getTypeSetSnapshot(int typeId) { if (typeId == singleTypeId) { LongHashSet result = new LongHashSet(size); int next = data.nextSetBit(0); while (next != -1) { result.add(next + min); // if (nextBitIndex == Integer.MAX_VALUE) { break; } next = data.nextSetBit(next + 1); } return result; } return LongSet.EMPTY; } class IdIterator implements Iterator<EntityId> { int nextBitIndex = data.nextSetBit(0); @Override public boolean hasNext() { return nextBitIndex != -1; } @Override public EntityId next() { if (nextBitIndex != -1) { final int bitIndex = nextBitIndex; nextBitIndex = data.nextSetBit(nextBitIndex + 1); return new PersistentEntityId(singleTypeId, bitIndex + min); } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } }
minor
entity-store/src/main/java/jetbrains/exodus/entitystore/util/ImmutableSingleTypeEntityIdBitSet.java
minor
<ide><path>ntity-store/src/main/java/jetbrains/exodus/entitystore/util/ImmutableSingleTypeEntityIdBitSet.java <ide> if (min < 0 || bitsCount >= Integer.MAX_VALUE) { <ide> throw new IllegalArgumentException(); <ide> } <del> data = new BitSet(((int) bitsCount)); <add> data = new BitSet((int) bitsCount); <ide> for (final long value : source) { <ide> data.set((int) (value - min)); <ide> } <ide> int next = data.nextSetBit(0); <ide> while (next != -1) { <ide> result.add(next + min); <del> // if (nextBitIndex == Integer.MAX_VALUE) { break; } <add> // if (next == Integer.MAX_VALUE) { break; } <ide> next = data.nextSetBit(next + 1); <ide> } <ide> return result;
Java
apache-2.0
137b64e837d56f6aa1571bdde765b85dc256a8df
0
dsyer/maven,dsyer/maven,wangyuesong/maven,xasx/maven,stephenc/maven,Tibor17/maven,atanasenko/maven,rogerchina/maven,Mounika-Chirukuri/maven,kidaa/maven-1,lbndev/maven,likaiwalkman/maven,wangyuesong/maven,njuneau/maven,pkozelka/maven,kidaa/maven-1,wangyuesong0/maven,barthel/maven,cstamas/maven,dsyer/maven,Distrotech/maven,pkozelka/maven,barthel/maven,ChristianSchulte/maven,skitt/maven,runepeter/maven-deploy-plugin-2.8.1,xasx/maven,mcculls/maven,stephenc/maven,barthel/maven,vedmishr/demo1,runepeter/maven-deploy-plugin-2.8.1,ChristianSchulte/maven,njuneau/maven,changbai1980/maven,trajano/maven,olamy/maven,aheritier/maven,changbai1980/maven,xasx/maven,josephw/maven,ChristianSchulte/maven,josephw/maven,likaiwalkman/maven,keith-turner/maven,keith-turner/maven,atanasenko/maven,apache/maven,atanasenko/maven,lbndev/maven,olamy/maven,apache/maven,wangyuesong0/maven,mcculls/maven,kidaa/maven-1,mizdebsk/maven,gorcz/maven,olamy/maven,Mounika-Chirukuri/maven,mizdebsk/maven,mizdebsk/maven,mcculls/maven,keith-turner/maven,skitt/maven,Mounika-Chirukuri/maven,rogerchina/maven,Tibor17/maven,cstamas/maven,wangyuesong/maven,aheritier/maven,changbai1980/maven,vedmishr/demo1,aheritier/maven,gorcz/maven,gorcz/maven,Distrotech/maven,lbndev/maven,apache/maven,pkozelka/maven,karthikjaps/maven,karthikjaps/maven,trajano/maven,trajano/maven,josephw/maven,vedmishr/demo1,njuneau/maven,cstamas/maven,skitt/maven,wangyuesong0/maven,karthikjaps/maven,likaiwalkman/maven,rogerchina/maven,stephenc/maven
package org.apache.maven.artifact.repository; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Describes a set of policies for a repository to use under certain conditions. * * @author <a href="mailto:[email protected]">Brett Porter</a> * @version $Id$ */ public class ArtifactRepositoryPolicy { public static final String UPDATE_POLICY_NEVER = "never"; public static final String UPDATE_POLICY_ALWAYS = "always"; public static final String UPDATE_POLICY_DAILY = "daily"; public static final String UPDATE_POLICY_INTERVAL = "interval"; public static final String CHECKSUM_POLICY_FAIL = "fail"; public static final String CHECKSUM_POLICY_WARN = "warn"; public static final String CHECKSUM_POLICY_IGNORE = "ignore"; private boolean enabled; private String updatePolicy; private String checksumPolicy; public ArtifactRepositoryPolicy() { this( true, null, null ); } public ArtifactRepositoryPolicy( ArtifactRepositoryPolicy policy ) { this( policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy() ); } public ArtifactRepositoryPolicy( boolean enabled, String updatePolicy, String checksumPolicy ) { this.enabled = enabled; if ( updatePolicy == null ) { updatePolicy = UPDATE_POLICY_DAILY; } this.updatePolicy = updatePolicy; if ( checksumPolicy == null ) { checksumPolicy = CHECKSUM_POLICY_WARN; } this.checksumPolicy = checksumPolicy; } public void setEnabled( boolean enabled ) { this.enabled = enabled; } public void setUpdatePolicy( String updatePolicy ) { if ( updatePolicy != null ) { this.updatePolicy = updatePolicy; } } public void setChecksumPolicy( String checksumPolicy ) { if ( checksumPolicy != null ) { this.checksumPolicy = checksumPolicy; } } public boolean isEnabled() { return enabled; } public String getUpdatePolicy() { return updatePolicy; } public String getChecksumPolicy() { return checksumPolicy; } public boolean checkOutOfDate( Date lastModified ) { boolean checkForUpdates = false; if ( UPDATE_POLICY_ALWAYS.equals( updatePolicy ) ) { checkForUpdates = true; } else if ( UPDATE_POLICY_DAILY.equals( updatePolicy ) ) { // Get local midnight boundary Calendar cal = Calendar.getInstance(); cal.set( Calendar.HOUR_OF_DAY, 0 ); cal.set( Calendar.MINUTE, 0 ); cal.set( Calendar.SECOND, 0 ); cal.set( Calendar.MILLISECOND, 0 ); if ( cal.getTime().after( lastModified ) ) { checkForUpdates = true; } } else if ( updatePolicy.startsWith( UPDATE_POLICY_INTERVAL ) ) { String s = updatePolicy.substring( UPDATE_POLICY_INTERVAL.length() + 1 ); int minutes = Integer.valueOf( s ); Calendar cal = Calendar.getInstance(); cal.add( Calendar.MINUTE, -minutes ); if ( cal.getTime().after( lastModified ) ) { checkForUpdates = true; } } // else assume "never" return checkForUpdates; } @Override public String toString() { StringBuilder buffer = new StringBuilder( 64 ); buffer.append( "{enabled=" ); buffer.append( enabled ); buffer.append( ", checksums=" ); buffer.append( checksumPolicy ); buffer.append( ", updates=" ); buffer.append( updatePolicy ); buffer.append( "}" ); return buffer.toString(); } public void merge( ArtifactRepositoryPolicy policy ) { if ( policy != null && policy.isEnabled() ) { setEnabled( true ); if ( ordinalOfChecksumPolicy( policy.getChecksumPolicy() ) < ordinalOfChecksumPolicy( getChecksumPolicy() ) ) { setChecksumPolicy( policy.getChecksumPolicy() ); } if ( ordinalOfUpdatePolicy( policy.getUpdatePolicy() ) < ordinalOfUpdatePolicy( getUpdatePolicy() ) ) { setUpdatePolicy( policy.getUpdatePolicy() ); } } } private int ordinalOfChecksumPolicy( String policy ) { if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals( policy ) ) { return 2; } else if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals( policy ) ) { return 0; } else { return 1; } } private int ordinalOfUpdatePolicy( String policy ) { if ( ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) ) { return 1440; } else if ( ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) ) { return 0; } else if ( policy != null && policy.startsWith( ArtifactRepositoryPolicy.UPDATE_POLICY_INTERVAL ) ) { String s = policy.substring( UPDATE_POLICY_INTERVAL.length() + 1 ); return Integer.valueOf( s ); } else { return Integer.MAX_VALUE; } } }
maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java
package org.apache.maven.artifact.repository; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Describes a set of policies for a repository to use under certain conditions. * * @author <a href="mailto:[email protected]">Brett Porter</a> * @version $Id$ */ public class ArtifactRepositoryPolicy { public static final String UPDATE_POLICY_NEVER = "never"; public static final String UPDATE_POLICY_ALWAYS = "always"; public static final String UPDATE_POLICY_DAILY = "daily"; public static final String UPDATE_POLICY_INTERVAL = "interval"; public static final String CHECKSUM_POLICY_FAIL = "fail"; public static final String CHECKSUM_POLICY_WARN = "warn"; public static final String CHECKSUM_POLICY_IGNORE = "ignore"; private boolean enabled; private String updatePolicy; private String checksumPolicy; public ArtifactRepositoryPolicy() { this( true, null, null ); } public ArtifactRepositoryPolicy( ArtifactRepositoryPolicy policy ) { this( policy.isEnabled(), policy.getUpdatePolicy(), policy.getChecksumPolicy() ); } public ArtifactRepositoryPolicy( boolean enabled, String updatePolicy, String checksumPolicy ) { this.enabled = enabled; if ( updatePolicy == null ) { updatePolicy = UPDATE_POLICY_DAILY; } this.updatePolicy = updatePolicy; if ( checksumPolicy == null ) { checksumPolicy = CHECKSUM_POLICY_WARN; } this.checksumPolicy = checksumPolicy; } public void setEnabled( boolean enabled ) { this.enabled = enabled; } public void setUpdatePolicy( String updatePolicy ) { if ( updatePolicy != null ) { this.updatePolicy = updatePolicy; } } public void setChecksumPolicy( String checksumPolicy ) { if ( checksumPolicy != null ) { this.checksumPolicy = checksumPolicy; } } public boolean isEnabled() { return enabled; } public String getUpdatePolicy() { return updatePolicy; } public String getChecksumPolicy() { return checksumPolicy; } public boolean checkOutOfDate( Date lastModified ) { boolean checkForUpdates = false; if ( UPDATE_POLICY_ALWAYS.equals( updatePolicy ) ) { checkForUpdates = true; } else if ( UPDATE_POLICY_DAILY.equals( updatePolicy ) ) { // Get midnight boundary Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); cal.set( Calendar.HOUR_OF_DAY, 0 ); cal.set( Calendar.MINUTE, 0 ); cal.set( Calendar.SECOND, 0 ); cal.set( Calendar.MILLISECOND, 0 ); if ( cal.getTime().after( lastModified ) ) { checkForUpdates = true; } } else if ( updatePolicy.startsWith( UPDATE_POLICY_INTERVAL ) ) { String s = updatePolicy.substring( UPDATE_POLICY_INTERVAL.length() + 1 ); int minutes = Integer.valueOf( s ); Calendar cal = Calendar.getInstance(); cal.add( Calendar.MINUTE, -minutes ); if ( cal.getTime().after( lastModified ) ) { checkForUpdates = true; } } // else assume "never" return checkForUpdates; } @Override public String toString() { StringBuilder buffer = new StringBuilder( 64 ); buffer.append( "{enabled=" ); buffer.append( enabled ); buffer.append( ", checksums=" ); buffer.append( checksumPolicy ); buffer.append( ", updates=" ); buffer.append( updatePolicy ); buffer.append( "}" ); return buffer.toString(); } public void merge( ArtifactRepositoryPolicy policy ) { if ( policy != null && policy.isEnabled() ) { setEnabled( true ); if ( ordinalOfChecksumPolicy( policy.getChecksumPolicy() ) < ordinalOfChecksumPolicy( getChecksumPolicy() ) ) { setChecksumPolicy( policy.getChecksumPolicy() ); } if ( ordinalOfUpdatePolicy( policy.getUpdatePolicy() ) < ordinalOfUpdatePolicy( getUpdatePolicy() ) ) { setUpdatePolicy( policy.getUpdatePolicy() ); } } } private int ordinalOfChecksumPolicy( String policy ) { if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_FAIL.equals( policy ) ) { return 2; } else if ( ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE.equals( policy ) ) { return 0; } else { return 1; } } private int ordinalOfUpdatePolicy( String policy ) { if ( ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) ) { return 1440; } else if ( ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) ) { return 0; } else if ( policy != null && policy.startsWith( ArtifactRepositoryPolicy.UPDATE_POLICY_INTERVAL ) ) { String s = policy.substring( UPDATE_POLICY_INTERVAL.length() + 1 ); return Integer.valueOf( s ); } else { return Integer.MAX_VALUE; } } }
o Fixed glitch in daily update policy which uses wrong timezone git-svn-id: d3061b52f177ba403f02f0a296a85518da96c313@999860 13f79535-47bb-0310-9956-ffa450edef68
maven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java
o Fixed glitch in daily update policy which uses wrong timezone
<ide><path>aven-artifact/src/main/java/org/apache/maven/artifact/repository/ArtifactRepositoryPolicy.java <ide> } <ide> else if ( UPDATE_POLICY_DAILY.equals( updatePolicy ) ) <ide> { <del> // Get midnight boundary <del> Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); <add> // Get local midnight boundary <add> Calendar cal = Calendar.getInstance(); <ide> <ide> cal.set( Calendar.HOUR_OF_DAY, 0 ); <ide> cal.set( Calendar.MINUTE, 0 );
Java
epl-1.0
ba8fbf6a3aee5cb94d02310c7534268d0d988897
0
opendaylight/packetcable,opendaylight/packetcable
/** @header@ */ package org.pcmm; import org.pcmm.objects.MMVersionInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.umu.cops.common.COPSDebug; import org.umu.cops.prpdp.COPSPdpAgent; import org.umu.cops.prpdp.COPSPdpException; import org.umu.cops.stack.*; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; // import org.umu.cops.prpdp.COPSPdpDataProcess; /** * Core PDP agent for provisioning */ public class PCMMPdpAgent extends COPSPdpAgent { public final static Logger logger = LoggerFactory.getLogger(PCMMPdpAgent.class); /** Well-known port for PCMM */ public static final int WELL_KNOWN_PDP_PORT = 3918; private COPSPepId _pepId; private String _pepIdString; /** * PEP host name */ private String psHost; /** * PEP port */ private int psPort; private Socket socket; /** * Policy data processing object */ private PCMMPdpDataProcess _process; private MMVersionInfo _mminfo; private COPSHandle _handle; private short _transactionID; /** * Creates a PDP Agent * * @param clientType * COPS Client-type * @param process * Object to perform policy data processing */ public PCMMPdpAgent(short clientType, PCMMPdpDataProcess process) { this(clientType, null, WELL_KNOWN_PDP_PORT, process); } /** * Creates a PDP Agent * * @param clientType * COPS Client-type * @param psHost * Host to connect to * @param psPort * Port to connect to * @param process * Object to perform policy data processing */ public PCMMPdpAgent(short clientType, String psHost, int psPort, PCMMPdpDataProcess process) { super(psPort, clientType, null); this._process = process; this.psHost = psHost; } /** * XXX -tek- This is the retooled connect. Not sure if the while forever * loop is needed. Socket accept --> handleClientOpenMsg --> pdpConn.run() * * Below is new Thread(pdpConn).start(); Does that do it? * */ /** * Connects to a PDP * * @param psHost * CMTS host name * @param psPort * CMTS port * @return <tt>true</tt> if PDP accepts the connection; <tt>false</tt> * otherwise * @throws java.net.UnknownHostException * @throws java.io.IOException * @throws COPSException * @throws COPSPdpException */ public boolean connect(String psHost, int psPort) throws IOException, COPSException, COPSPdpException { this.psHost = psHost; this.psPort = psPort; // Create Socket and send OPN InetAddress addr = InetAddress.getByName(psHost); try { socket = new Socket(addr, psPort); } catch (IOException e) { logger.error(COPSDebug.ERROR_SOCKET, e); return (false); } logger.info("PDP Socket Opened"); // Loop through for Incoming messages // server infinite loop // while(true) { // We're waiting for an message try { logger.info("PDP COPSTransceiver.receiveMsg"); COPSMsg msg = COPSTransceiver.receiveMsg(socket); if (msg.getHeader().isAClientOpen()) { logger.info("PDP msg.getHeader().isAClientOpen"); handleClientOpenMsg(socket, msg); } else { try { socket.close(); } catch (Exception ex) { logger.error("Unexpected exception closing socket", ex); } } } catch (Exception e) { // COPSException, IOException try { socket.close(); } catch (Exception ex) { logger.error("Unexpected exception closing socket", ex); } return true; } } return false; } /** * Handles a COPS client-open message * * @param conn * Socket to the PEP * @param msg * <tt>COPSMsg</tt> holding the client-open message * @throws COPSException * @throws IOException */ private void handleClientOpenMsg(Socket conn, COPSMsg msg) throws COPSException, IOException { COPSClientOpenMsg cMsg = (COPSClientOpenMsg) msg; COPSPepId pepId = cMsg.getPepId(); // Validate Client Type if (msg.getHeader().getClientType() != getClientType()) { // Unsupported client type COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError( COPSError.COPS_ERR_UNSUPPORTED_CLIENT_TYPE, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { logger.error("Unexpected error writing COPS data", unae); } throw new COPSException("Unsupported client type"); } // PEPId is mandatory if (pepId == null) { // Mandatory COPS object missing COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError( COPSError.COPS_ERR_MANDATORY_OBJECT_MISSING, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { logger.error("Unexpected error writing COPS data", unae); } throw new COPSException("Mandatory COPS object missing (PEPId)"); } setPepId(pepId); // Support if ((cMsg.getClientSI() != null) ) { _mminfo = new MMVersionInfo(cMsg .getClientSI().getData().getData()); logger.info("CMTS sent MMVersion info : major:" + _mminfo.getMajorVersionNB() + " minor:" + _mminfo.getMinorVersionNB()); } else { // Unsupported objects COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError(COPSError.COPS_ERR_UNKNOWN_OBJECT, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { logger.error("Unexpected error writing COPS data", unae); } throw new COPSException("Unsupported objects (PdpAddress, Integrity)"); } /* */ // Connection accepted COPSHeader ahdr = new COPSHeader(COPSHeader.COPS_OP_CAT, msg .getHeader().getClientType()); COPSKATimer katimer = new COPSKATimer(getKaTimer()); COPSAcctTimer acctTimer = new COPSAcctTimer(getAcctTimer()); COPSClientAcceptMsg acceptMsg = new COPSClientAcceptMsg(); acceptMsg.add(ahdr); acceptMsg.add(katimer); if (getAcctTimer() != 0) acceptMsg.add(acctTimer); acceptMsg.writeData(conn); // XXX - handleRequestMsg try { logger.info("PDP COPSTransceiver.receiveMsg"); COPSMsg rmsg = COPSTransceiver.receiveMsg(socket); // Client-Close if (rmsg.getHeader().isAClientClose()) { logger.info("Client close description - " + ((COPSClientCloseMsg) rmsg).getError().getDescription()); // close the socket COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError(COPSError.COPS_ERR_UNKNOWN_OBJECT, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { logger.error("Unexpected exception writing COPS data", unae); } throw new COPSException("CMTS requetsed Client-Close"); } else { // Request if (rmsg.getHeader().isARequest()) { COPSReqMsg rMsg = (COPSReqMsg) rmsg; _handle = rMsg.getClientHandle(); } else throw new COPSException("Can't understand request"); } } catch (Exception e) { // COPSException, IOException throw new COPSException("Error COPSTransceiver.receiveMsg"); } logger.info("PDPCOPSConnection"); PCMMPdpConnection pdpConn = new PCMMPdpConnection(pepId, conn, _process); pdpConn.setKaTimer(getKaTimer()); if (getAcctTimer() != 0) pdpConn.setAccTimer(getAcctTimer()); // XXX - handleRequestMsg // XXX - check handle is valid PCMMPdpReqStateMan man = new PCMMPdpReqStateMan(getClientType(), _handle.getId().str()); pdpConn.getReqStateMans().put(_handle.getId().str(),man); man.setDataProcess(_process); try { man.initRequestState(conn); } catch (COPSPdpException unae) { } // XXX - End handleRequestMsg logger.info("PDP Thread(pdpConn).start"); new Thread(pdpConn).start(); getConnectionMap().put(pepId.getData().str(), pdpConn); } /** * @return the _psHost */ public String getPsHost() { return psHost; } /** * TODO - make the host immutable * @param _psHost * the _psHost to set */ @Deprecated public void setPsHost(String _psHost) { this.psHost = _psHost; } /** * @return the _psPort */ public int getPsPort() { return psPort; } /** * TODO - make the port immutable * @param _psPort * the _psPort to set */ @Deprecated public void setPsPort(int _psPort) { this.psPort = _psPort; } /** * @return the socket */ public Socket getSocket() { return socket; } /** * TODO - Ensure socket is not overly transient * @param socket * the socket to set */ @Deprecated public void setSocket(Socket socket) { this.socket = socket; } /** * @return the _process */ public PCMMPdpDataProcess getProcess() { return _process; } /** * @param _process * the _process to set */ public void setProcess(PCMMPdpDataProcess _process) { this._process = _process; } /** * Gets the client handle * @return Client's <tt>COPSHandle</tt> */ public COPSHandle getClientHandle() { return _handle; } /** * Gets the PepId * @return <tt>COPSPepId</tt> */ public COPSPepId getPepId() { return _pepId; } public String getPepIdString() { return _pepIdString; } /** * Sets the PepId * TODO - make PEP ID and the associate string immutable or remove altogether * @param pepId - COPSPepId */ @Deprecated public void setPepId(COPSPepId pepId) { _pepId = pepId; _pepIdString = pepId.getData().str(); } /* * (non-Javadoc) * * @see org.pcmm.rcd.IPCMMClient#isConnected() */ public boolean isConnected() { return socket != null && socket.isConnected(); } }
packetcable-driver/src/main/java/org/pcmm/PCMMPdpAgent.java
/** @header@ */ package org.pcmm; import org.pcmm.objects.MMVersionInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.umu.cops.common.COPSDebug; import org.umu.cops.ospep.COPSPepException; import org.umu.cops.prpdp.COPSPdpAgent; import org.umu.cops.prpdp.COPSPdpException; import org.umu.cops.stack.*; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; // import org.umu.cops.prpdp.COPSPdpDataProcess; /** * Core PDP agent for provisioning */ public class PCMMPdpAgent extends COPSPdpAgent { public final static Logger logger = LoggerFactory.getLogger(PCMMPdpAgent.class); /** Well-known port for PCMM */ public static final int WELL_KNOWN_PDP_PORT = 3918; private COPSPepId _pepId; private String _pepIdString; /** * PEP host name */ private String psHost; /** * PEP port */ private int psPort; private Socket socket; /** * Policy data processing object */ private PCMMPdpDataProcess _process; private MMVersionInfo _mminfo; private COPSHandle _handle; private short _transactionID; /** * Creates a PDP Agent * * @param clientType * COPS Client-type * @param process * Object to perform policy data processing */ public PCMMPdpAgent(short clientType, PCMMPdpDataProcess process) { this(clientType, null, WELL_KNOWN_PDP_PORT, process); } /** * Creates a PDP Agent * * @param clientType * COPS Client-type * @param psHost * Host to connect to * @param psPort * Port to connect to * @param process * Object to perform policy data processing */ public PCMMPdpAgent(short clientType, String psHost, int psPort, PCMMPdpDataProcess process) { super(psPort, clientType, null); this._process = process; this.psHost = psHost; } /** * XXX -tek- This is the retooled connect. Not sure if the while forever * loop is needed. Socket accept --> handleClientOpenMsg --> pdpConn.run() * * Below is new Thread(pdpConn).start(); Does that do it? * */ /** * Connects to a PDP * * @param psHost * CMTS host name * @param psPort * CMTS port * @return <tt>true</tt> if PDP accepts the connection; <tt>false</tt> * otherwise * @throws java.net.UnknownHostException * @throws java.io.IOException * @throws COPSException * @throws COPSPepException */ public boolean connect(String psHost, int psPort) throws UnknownHostException, IOException, COPSException, COPSPdpException { this.psHost = psHost; this.psPort = psPort; // Create Socket and send OPN InetAddress addr = InetAddress.getByName(psHost); try { socket = new Socket(addr, psPort); } catch (IOException e) { COPSDebug.err(getClass().getName(), COPSDebug.ERROR_SOCKET, e); return (false); } COPSDebug.err(getClass().getName(), "PDP Socket Opened"); // Loop through for Incoming messages // server infinite loop // while(true) { // We're waiting for an message try { COPSDebug.err(getClass().getName(), "PDP COPSTransceiver.receiveMsg "); COPSMsg msg = COPSTransceiver.receiveMsg(socket); if (msg.getHeader().isAClientOpen()) { COPSDebug.err(getClass().getName(), "PDP msg.getHeader().isAClientOpen"); handleClientOpenMsg(socket, msg); } else { // COPSDebug.err(getClass().getName(), // COPSDebug.ERROR_NOEXPECTEDMSG); try { socket.close(); } catch (Exception ex) { } ; } } catch (Exception e) { // COPSException, IOException // COPSDebug.err(getClass().getName(), // COPSDebug.ERROR_EXCEPTION, // "(" + socket.getInetAddress() + ":" + socket.getPort() + ")", // e); try { socket.close(); } catch (Exception ex) { } ; return true; } } return false; } /** * Handles a COPS client-open message * * @param conn * Socket to the PEP * @param msg * <tt>COPSMsg</tt> holding the client-open message * @throws COPSException * @throws IOException */ private void handleClientOpenMsg(Socket conn, COPSMsg msg) throws COPSException, IOException { COPSClientOpenMsg cMsg = (COPSClientOpenMsg) msg; COPSPepId pepId = cMsg.getPepId(); // Validate Client Type if (msg.getHeader().getClientType() != getClientType()) { // Unsupported client type COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError( COPSError.COPS_ERR_UNSUPPORTED_CLIENT_TYPE, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { } throw new COPSException("Unsupported client type"); } // PEPId is mandatory if (pepId == null) { // Mandatory COPS object missing COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError( COPSError.COPS_ERR_MANDATORY_OBJECT_MISSING, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { } throw new COPSException("Mandatory COPS object missing (PEPId)"); } setPepId(pepId); // Support if ((cMsg.getClientSI() != null) ) { _mminfo = new MMVersionInfo(cMsg .getClientSI().getData().getData()); logger.info("CMTS sent MMVersion info : major:" + _mminfo.getMajorVersionNB() + " minor:" + _mminfo.getMinorVersionNB()); } else { // Unsupported objects COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError(COPSError.COPS_ERR_UNKNOWN_OBJECT, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { } throw new COPSException("Unsupported objects (PdpAddress, Integrity)"); } /* */ // Connection accepted COPSHeader ahdr = new COPSHeader(COPSHeader.COPS_OP_CAT, msg .getHeader().getClientType()); COPSKATimer katimer = new COPSKATimer(getKaTimer()); COPSAcctTimer acctTimer = new COPSAcctTimer(getAcctTimer()); COPSClientAcceptMsg acceptMsg = new COPSClientAcceptMsg(); acceptMsg.add(ahdr); acceptMsg.add(katimer); if (getAcctTimer() != 0) acceptMsg.add(acctTimer); acceptMsg.writeData(conn); // XXX - handleRequestMsg try { COPSDebug.err(getClass().getName(), "PDP COPSTransceiver.receiveMsg "); COPSMsg rmsg = COPSTransceiver.receiveMsg(socket); // Client-Close if (rmsg.getHeader().isAClientClose()) { logger.info("Client close description - " + ((COPSClientCloseMsg) rmsg).getError().getDescription()); // close the socket COPSHeader cHdr = new COPSHeader(COPSHeader.COPS_OP_CC, msg .getHeader().getClientType()); COPSError err = new COPSError(COPSError.COPS_ERR_UNKNOWN_OBJECT, (short) 0); COPSClientCloseMsg closeMsg = new COPSClientCloseMsg(); closeMsg.add(cHdr); closeMsg.add(err); try { closeMsg.writeData(conn); } catch (IOException unae) { } throw new COPSException("CMTS requetsed Client-Close"); } else { // Request if (rmsg.getHeader().isARequest()) { COPSReqMsg rMsg = (COPSReqMsg) rmsg; _handle = rMsg.getClientHandle(); } else throw new COPSException("Can't understand request"); } } catch (Exception e) { // COPSException, IOException throw new COPSException("Error COPSTransceiver.receiveMsg"); } COPSDebug.err(getClass().getName(), "PDPCOPSConnection"); PCMMPdpConnection pdpConn = new PCMMPdpConnection(pepId, conn, _process); pdpConn.setKaTimer(getKaTimer()); if (getAcctTimer() != 0) pdpConn.setAccTimer(getAcctTimer()); // XXX - handleRequestMsg // XXX - check handle is valid PCMMPdpReqStateMan man = new PCMMPdpReqStateMan(getClientType(), _handle.getId().str()); pdpConn.getReqStateMans().put(_handle.getId().str(),man); man.setDataProcess(_process); try { man.initRequestState(conn); } catch (COPSPdpException unae) { } // XXX - End handleRequestMsg COPSDebug.err(getClass().getName(), "PDP Thread(pdpConn).start"); new Thread(pdpConn).start(); getConnectionMap().put(pepId.getData().str(), pdpConn); } /** * @return the _psHost */ public String getPsHost() { return psHost; } /** * @param _psHost * the _psHost to set */ public void setPsHost(String _psHost) { this.psHost = _psHost; } /** * @return the _psPort */ public int getPsPort() { return psPort; } /** * @param _psPort * the _psPort to set */ public void setPsPort(int _psPort) { this.psPort = _psPort; } /** * @return the socket */ public Socket getSocket() { return socket; } /** * @param socket * the socket to set */ public void setSocket(Socket socket) { this.socket = socket; } /** * @return the _process */ public PCMMPdpDataProcess getProcess() { return _process; } /** * @param _process * the _process to set */ public void setProcess(PCMMPdpDataProcess _process) { this._process = _process; } /** * Gets the client handle * @return Client's <tt>COPSHandle</tt> */ public COPSHandle getClientHandle() { return _handle; } /** * Gets the PepId * @return <tt>COPSPepId</tt> */ public COPSPepId getPepId() { return _pepId; } public String getPepIdString() { return _pepIdString; } /** * Sets the PepId * @param pepId - COPSPepId */ public void setPepId(COPSPepId pepId) { _pepId = pepId; _pepIdString = pepId.getData().str(); } /* * (non-Javadoc) * * @see org.pcmm.rcd.IPCMMClient#isConnected() */ public boolean isConnected() { return socket != null && socket.isConnected(); } }
Removal of calls to COPSDebug.err() and replaced with calls to the logger. Change-Id: I0acf0aeb3d4e73c057ea0ca52f2c821a2eea64d7 Signed-off-by: Steven Pisarski <[email protected]>
packetcable-driver/src/main/java/org/pcmm/PCMMPdpAgent.java
Removal of calls to COPSDebug.err() and replaced with calls to the logger.
<ide><path>acketcable-driver/src/main/java/org/pcmm/PCMMPdpAgent.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> import org.umu.cops.common.COPSDebug; <del>import org.umu.cops.ospep.COPSPepException; <ide> import org.umu.cops.prpdp.COPSPdpAgent; <ide> import org.umu.cops.prpdp.COPSPdpException; <ide> import org.umu.cops.stack.*; <ide> import java.io.IOException; <ide> import java.net.InetAddress; <ide> import java.net.Socket; <del>import java.net.UnknownHostException; <ide> <ide> // import org.umu.cops.prpdp.COPSPdpDataProcess; <ide> <ide> * @throws java.net.UnknownHostException <ide> * @throws java.io.IOException <ide> * @throws COPSException <del> * @throws COPSPepException <del> */ <del> public boolean connect(String psHost, int psPort) <del> throws UnknownHostException, IOException, COPSException, <del> COPSPdpException { <add> * @throws COPSPdpException <add> */ <add> public boolean connect(String psHost, int psPort) throws IOException, COPSException, COPSPdpException { <ide> <ide> this.psHost = psHost; <ide> this.psPort = psPort; <ide> try { <ide> socket = new Socket(addr, psPort); <ide> } catch (IOException e) { <del> COPSDebug.err(getClass().getName(), COPSDebug.ERROR_SOCKET, e); <add> logger.error(COPSDebug.ERROR_SOCKET, e); <ide> return (false); <ide> } <del> COPSDebug.err(getClass().getName(), "PDP Socket Opened"); <add> logger.info("PDP Socket Opened"); <ide> // Loop through for Incoming messages <ide> <ide> // server infinite loop <ide> <ide> // We're waiting for an message <ide> try { <del> COPSDebug.err(getClass().getName(), <del> "PDP COPSTransceiver.receiveMsg "); <add> logger.info("PDP COPSTransceiver.receiveMsg"); <ide> COPSMsg msg = COPSTransceiver.receiveMsg(socket); <ide> if (msg.getHeader().isAClientOpen()) { <del> COPSDebug.err(getClass().getName(), <del> "PDP msg.getHeader().isAClientOpen"); <add> logger.info("PDP msg.getHeader().isAClientOpen"); <ide> handleClientOpenMsg(socket, msg); <ide> } else { <del> // COPSDebug.err(getClass().getName(), <del> // COPSDebug.ERROR_NOEXPECTEDMSG); <ide> try { <ide> socket.close(); <ide> } catch (Exception ex) { <add> logger.error("Unexpected exception closing socket", ex); <ide> } <del> ; <ide> } <ide> } catch (Exception e) { // COPSException, IOException <del> // COPSDebug.err(getClass().getName(), <del> // COPSDebug.ERROR_EXCEPTION, <del> // "(" + socket.getInetAddress() + ":" + socket.getPort() + ")", <del> // e); <ide> try { <ide> socket.close(); <ide> } catch (Exception ex) { <add> logger.error("Unexpected exception closing socket", ex); <ide> } <del> ; <ide> return true; <ide> } <ide> } <ide> try { <ide> closeMsg.writeData(conn); <ide> } catch (IOException unae) { <add> logger.error("Unexpected error writing COPS data", unae); <ide> } <ide> <ide> throw new COPSException("Unsupported client type"); <ide> try { <ide> closeMsg.writeData(conn); <ide> } catch (IOException unae) { <add> logger.error("Unexpected error writing COPS data", unae); <ide> } <ide> <ide> throw new COPSException("Mandatory COPS object missing (PEPId)"); <ide> try { <ide> closeMsg.writeData(conn); <ide> } catch (IOException unae) { <add> logger.error("Unexpected error writing COPS data", unae); <ide> } <ide> <ide> throw new COPSException("Unsupported objects (PdpAddress, Integrity)"); <ide> acceptMsg.writeData(conn); <ide> // XXX - handleRequestMsg <ide> try { <del> COPSDebug.err(getClass().getName(), "PDP COPSTransceiver.receiveMsg "); <add> logger.info("PDP COPSTransceiver.receiveMsg"); <ide> COPSMsg rmsg = COPSTransceiver.receiveMsg(socket); <ide> // Client-Close <ide> if (rmsg.getHeader().isAClientClose()) { <ide> try { <ide> closeMsg.writeData(conn); <ide> } catch (IOException unae) { <add> logger.error("Unexpected exception writing COPS data", unae); <ide> } <ide> throw new COPSException("CMTS requetsed Client-Close"); <ide> } else { <ide> throw new COPSException("Error COPSTransceiver.receiveMsg"); <ide> } <ide> <del> COPSDebug.err(getClass().getName(), "PDPCOPSConnection"); <add> logger.info("PDPCOPSConnection"); <ide> PCMMPdpConnection pdpConn = new PCMMPdpConnection(pepId, conn, _process); <ide> pdpConn.setKaTimer(getKaTimer()); <ide> if (getAcctTimer() != 0) <ide> } <ide> // XXX - End handleRequestMsg <ide> <del> COPSDebug.err(getClass().getName(), "PDP Thread(pdpConn).start"); <add> logger.info("PDP Thread(pdpConn).start"); <ide> new Thread(pdpConn).start(); <ide> getConnectionMap().put(pepId.getData().str(), pdpConn); <ide> } <ide> } <ide> <ide> /** <add> * TODO - make the host immutable <ide> * @param _psHost <ide> * the _psHost to set <ide> */ <add> @Deprecated <ide> public void setPsHost(String _psHost) { <ide> this.psHost = _psHost; <ide> } <ide> } <ide> <ide> /** <add> * TODO - make the port immutable <ide> * @param _psPort <ide> * the _psPort to set <ide> */ <add> @Deprecated <ide> public void setPsPort(int _psPort) { <ide> this.psPort = _psPort; <ide> } <ide> } <ide> <ide> /** <add> * TODO - Ensure socket is not overly transient <ide> * @param socket <ide> * the socket to set <ide> */ <add> @Deprecated <ide> public void setSocket(Socket socket) { <ide> this.socket = socket; <ide> } <ide> } <ide> <ide> /** <del> * Sets the PepId <del> * @param pepId - COPSPepId <del> */ <add> * Sets the PepId <add> * TODO - make PEP ID and the associate string immutable or remove altogether <add> * @param pepId - COPSPepId <add> */ <add> @Deprecated <ide> public void setPepId(COPSPepId pepId) { <ide> _pepId = pepId; <ide> _pepIdString = pepId.getData().str();
Java
mit
6baa8820016b89139921e56f639fef77f12af890
0
realdlee/dwitter
package com.codepath.apps.dwitter.activities; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.codepath.apps.dwitter.R; import com.codepath.apps.dwitter.TwitterApplication; import com.codepath.apps.dwitter.TwitterClient; import com.codepath.apps.dwitter.fragments.UserTimelineFragment; import com.codepath.apps.dwitter.models.User; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONObject; import java.text.DecimalFormat; import cz.msebera.android.httpclient.Header; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; public class ProfileActivity extends AppCompatActivity { TwitterClient client; User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); client = TwitterApplication.getRestClient(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); final TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); String screenName = getIntent().getStringExtra("screen_name"); client.getUserInfo(screenName, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { user = User.fromJSON(response); mTitle.setText("@" + user.getScreenName()); populateProfileHeader(user); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.e("error", errorResponse.toString()); super.onFailure(statusCode, headers, throwable, errorResponse); } }); if (savedInstanceState == null) { UserTimelineFragment fragmentUserTimeline = UserTimelineFragment.newInstance(screenName); //display user fragment dynamically FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.flContainer, fragmentUserTimeline); ft.commit(); } } private void populateProfileHeader(User user) { DecimalFormat formatter = new DecimalFormat("#,###,###"); TextView tvName = (TextView) findViewById(R.id.tvName); TextView tvTagline = (TextView) findViewById(R.id.tvTagline); TextView tvFollowers = (TextView) findViewById(R.id.tvFollowers); TextView tvFollowing = (TextView) findViewById(R.id.tvFollowing); ImageView ivProfileImage = (ImageView) findViewById(R.id.ivProfileImage); tvName.setText(user.getName()); tvTagline.setText(user.getTagline()); tvFollowers.setText(formatter.format(user.getFollowersCount()) + " Followers"); tvFollowing.setText(formatter.format(user.getFollowingsCount()) + " Following"); Glide.with(this) .load(user.getProfileImageUrl()) .bitmapTransform(new RoundedCornersTransformation(this, 3, 3)) .into(ivProfileImage); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } }
app/src/main/java/com/codepath/apps/dwitter/activities/ProfileActivity.java
package com.codepath.apps.dwitter.activities; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.codepath.apps.dwitter.R; import com.codepath.apps.dwitter.TwitterApplication; import com.codepath.apps.dwitter.TwitterClient; import com.codepath.apps.dwitter.fragments.UserTimelineFragment; import com.codepath.apps.dwitter.models.User; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; public class ProfileActivity extends AppCompatActivity { TwitterClient client; User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); client = TwitterApplication.getRestClient(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); final TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); String screenName = getIntent().getStringExtra("screen_name"); client.getUserInfo(screenName, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { user = User.fromJSON(response); mTitle.setText("@" + user.getScreenName()); populateProfileHeader(user); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.e("error", errorResponse.toString()); super.onFailure(statusCode, headers, throwable, errorResponse); } }); if (savedInstanceState == null) { UserTimelineFragment fragmentUserTimeline = UserTimelineFragment.newInstance(screenName); //display user fragment dynamically FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.flContainer, fragmentUserTimeline); ft.commit(); } } private void populateProfileHeader(User user) { TextView tvName = (TextView) findViewById(R.id.tvName); TextView tvTagline = (TextView) findViewById(R.id.tvTagline); TextView tvFollowers = (TextView) findViewById(R.id.tvFollowers); TextView tvFollowing = (TextView) findViewById(R.id.tvFollowing); ImageView ivProfileImage = (ImageView) findViewById(R.id.ivProfileImage); tvName.setText(user.getName()); tvTagline.setText(user.getTagline()); tvFollowers.setText(user.getFollowersCount() + " Followers"); tvFollowing.setText(user.getFollowingsCount() + " Following"); Glide.with(this) .load(user.getProfileImageUrl()) .bitmapTransform(new RoundedCornersTransformation(this, 3, 3)) .into(ivProfileImage); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } }
Format large numbers for follower/following counts
app/src/main/java/com/codepath/apps/dwitter/activities/ProfileActivity.java
Format large numbers for follower/following counts
<ide><path>pp/src/main/java/com/codepath/apps/dwitter/activities/ProfileActivity.java <ide> package com.codepath.apps.dwitter.activities; <add> <ide> <ide> import android.os.Bundle; <ide> import android.support.v4.app.FragmentTransaction; <ide> import com.loopj.android.http.JsonHttpResponseHandler; <ide> <ide> import org.json.JSONObject; <add> <add>import java.text.DecimalFormat; <ide> <ide> import cz.msebera.android.httpclient.Header; <ide> import jp.wasabeef.glide.transformations.RoundedCornersTransformation; <ide> } <ide> <ide> private void populateProfileHeader(User user) { <add> DecimalFormat formatter = new DecimalFormat("#,###,###"); <add> <ide> TextView tvName = (TextView) findViewById(R.id.tvName); <ide> TextView tvTagline = (TextView) findViewById(R.id.tvTagline); <ide> TextView tvFollowers = (TextView) findViewById(R.id.tvFollowers); <ide> ImageView ivProfileImage = (ImageView) findViewById(R.id.ivProfileImage); <ide> tvName.setText(user.getName()); <ide> tvTagline.setText(user.getTagline()); <del> tvFollowers.setText(user.getFollowersCount() + " Followers"); <del> tvFollowing.setText(user.getFollowingsCount() + " Following"); <add> tvFollowers.setText(formatter.format(user.getFollowersCount()) + " Followers"); <add> tvFollowing.setText(formatter.format(user.getFollowingsCount()) + " Following"); <ide> Glide.with(this) <ide> .load(user.getProfileImageUrl()) <ide> .bitmapTransform(new RoundedCornersTransformation(this, 3, 3))
Java
mit
b7e35ccb1f633dca5b0bc7ced5843971618f3ce1
0
macc704/KBDeX,macc704/KBDeX,macc704/KBDeX,macc704/KBDeX,macc704/KBDeX
/* * KBDeX.java * Created on Jun 27, 2010 * Copyright(c) 2010 Yoshiaki Matsuzawa, Shizuoka University. All rights reserved. */ package kbdex.app; import java.awt.Frame; import java.awt.Image; import java.awt.image.BufferedImage; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.UIManager; import clib.common.filesystem.CDirectory; import clib.common.filesystem.CFileSystem; import clib.common.system.CEncoding; import clib.common.system.CJavaSystem; import clib.view.dialogs.CErrorDialog; import clib.view.progress.CPanelProcessingMonitor; import kbdex.app.manager.KDDiscourseManager; import kbdex.app.manager.KDiscourseManagerFrame; /** * KBDeX(Knowledge Building Discourse eXplorer) Application * Copyright(c) 2010-2011 Yoshiaki Matsuzawa, Jun Oshima, Ritsuko Oshima at Shizuoka University. All rights reserved. * * <バグ> * TODO 100 戻るときに,ボタン連打すると,計算途中で戻るが反応してしまい,結果,たくさん戻ってしまうように見える. * * <懸案事項> * TODO 10 Hide機能のテスト(リファクタリング後できていなかったものをできるようにしたので) * TODO 10 Graph表示で,タイトルを変えられるようにしたい(何が何だかわからなくなる) * TODO 10 Graph表示, Table表示からのcsv, xls吐出機能,(R,Gnuplotもイイネ!) * * <更新履歴> * 1.10.1 2015.10.02 *  ・kf6 support * * 1.10.0 (gitの操作ミスによって消えた,幻のバージョン) * * 1.9.10 2015.06.28 * ・https support for kf5 * * 1.9.9 2014.12.19 with Frank * ・bugfix * * 1.9.8 2014.12.19 with Frank * ・Multiple View for kf5 * ・FRLayout in default * * 1.9.7 2014.11.28 * ・Color kinds are added to 22 * * 1.9.6 2014.11.18 * ・Fixed CSV file reading problem * * 1.9.5 2014.11.17 * ・Selection Word Saving Bug fix * ・Metrics CSV * * 1.9.4 2014.10.10 * ・Label updated * * 1.9.3 2014.10.10 * ・fixed Turkish problem -> utf8 * ・fixed bug of lifetime * * 1.9.2 2014.09.23 * ・Word Bag for frequency * (plus mark to create a word bag for frequency) * ・ignore word list * (minus mark to suppress detecting the particular word in word selection) * * 1.9.1 2014.09.19 * ・Bugfix for WordBag * ・copy pasting for mac java7 * * 1.9.0 2014.09.19 * ・WordBag * (exclamation mark to make a word bag) * * 1.8.2 2014.08.28 * ・Fixed bug of output-R * * 1.8.1 2014.08.20 * ・CFileがBOMをつけないように,かつBOMを読み飛ばすように変更 * ・辞書なしのエラー処理 * * 1.8.0 2014.08.20 * ・GPL License * ・Launch * ・non-japanese version * * 1.7.2 2014.08.20 * ・HongKongの人の要請で,UTF-8のテキストを扱えるようにする(DefaultをUTF-8,読み込み自動判定にした) * ・WordSelectionでDirtyStateの検知,表示,確認. * ・WordSelection他のDialogSizeを変更 (screenの3/4) * * 1.7.1 2014.07.18 * ・KF5, ファイル名,キャンセルなど細かいミスなどの修正. * * 1.7.0 2014.07.17 * ・KF5に対応 * * 1.6.1 2013.07.13 * ・Java1.7以上でない場合にエラーダイアログを表示する. * * 1.6.0 2013.06.19 * ・大島先生のご要望によりノードアイコン追加 * * 1.5.8 2012.11.09 * ・バグ修正 KDiscourseViewerPanelでTextがソートされない * ・公開にあたり,付属の例を修正 * * 1.5.7 2012.10.26 * ・Monicaのバグ報告により修正 * ・KFから取得時に,時間をModify時でとっていた=>しかしTimeFilterは最初と最後のノートの時刻で判断=>最後のノート以降に更新されたノートが範囲外 * ・対策(1),Crea時間にした * ・対策(2),Defaultの時間範囲を,全てのノートを参照して計算するようにした(多少冗長であるが) * * 1.5.6 2012.10.04 * ・Bodongの要求により viewを指定してKFを読み込めるようにする * ・CommonLibraryを新しいバージョンに入替 * * 1.5.5 2012.03.19 * ・BSLボタン グラフレイアウト機能 指標をDegree Centralityの総和に変更 * * 1.5.4 2012.02.03 * ・BSLボタン グラフレイアウト機能 指標のactive状態をリセットするように対応. * * 1.5.3 2011.12.02 * ・BSLボタン グラフレイアウト機能 (途中だがCLE研究会で発表) * * 1.5.2 2011.11.28  * ・Fontを変えられるようにtemporaryの修正 * * 1.5.1 2011.11.27 学マネKBDeX実験(2)投入 * ・TableMetricsでSSがとれなかったバグを修正 * ・TableMetrics表示時に最新の指標が反映できていなかったバグを修正 * ・Reloadボタンの追加 * * 1.5.0 2011.11.27 学マネKBDeX実験(2)投入 RC * ・時系列メトリクス計算方針の大幅変更 * ・全部キャッシュし,グラフには基本的に全部表示する. * ・現在の位置をインジケータで示す. * ・そこで選んだものだけでなく、シリーズで出てくるすべてのノードを対象とする * ・メトリクス作成インタフェイスの大幅変更 * ・Graph, Nodeが別れていてわかりにくかったので統一. * ・Graph, Tableを作るインタフェイスをActivationと統一し,かつ直感的に分かりやすいように変更 * * 1.4.0 2011.11.14 * ・アニメーション速度調整機能の追加 * * 1.3.9 2011.11.13 学マネKBDeX実験(1)投入 * ・メイン画面全体のスクリーンキャプチャ機能 * ・Noスキップ機能UI調整 * * 1.3.8 2011.11.13 * ・KaniChatCSVの複数同時読み込み機能を追加 * ・スクリーンキャプチャ機能,currentIDがnullの時の不具合を修正 * * 1.3.7 2011.11.12 * ・文字コード周りの整理 * ・data.csv形式の読込み,書出しの文字コードをShift_JISに固定 * ・Import機能の拡充 * ・KaniChatCSV形式の読み込み機能を追加 * ・KF読込も含めて,読み込みまわりのリファクタリングを実施 * ・CSVをcommonsライブラリで読み込むように変更した関係で,CSVの仕様が若干変わった.(改行が入っても良い,下位互換性あり) * ・読込んだときのデフォルトlifetimeを20から無しに変更 * ・スクリーンキャプチャ機能の追加 * * 1.3.6 2011.08.02 * ・DiscourseViewerにNo追加 * ・DiscourseコントローラにNo指定を追加 * ・RelationパネルでUnitダブルクリックでUnit内容表示ウインドウを表示するように * * 1.3.5 2011.07.24 * ・選ぶ単語に重複箇所(ex 自動車,車)単語ハイライト表示部(label)のアサーションに引っかかり, * 正常動作しなくなる問題を修正 * * 1.3.4 2011.05.07 * ・toLast時にGraphが途中描画されないように調整 * ・選択したものが,resetすると消去されてしまう(Tableの選択が解除され,そこで選択がクリアされてしまう)問題をFix * * 1.3.3 2011.05.06 * ・Graphの調整 * ・グラフのラベル選択をできるようにする * ・グラフを直接選択できるようにする * ・グラフの設定画面のレイアウト変更し,少なくても多くても散らばることなく表示される. * ・Graph表示での選択機能に対応.(Graph->Network Network->Graph)両対応 * ・Table表示での選択機能に対応.(新しくNetwork->Tableに対応) * ・英語版サンプルを追加 * * 1.3.2 2011.05.06 * ・時間がかかる処理での進捗表示,およびキャンセル機能を追加(2.5秒後に出る設定) * * 1.3.1 2011.05.05 * ・(解決)Graph表示で,NaNの表示がおかしい. * ・(解決)この先,structureChanged()でソート条件がリセットされてしまう.(暫定的に解決) * ・(解決)リセット時,グラフが以前のバージョンの最後の値で初期化される * ・(解決) Graph表示で,Explanationが見にくい.→Overviewを分離 * ・(解決) Graph表示で,そのものを残しておきたい(コピーしたい.)→コピー,Pinをできるようにした * ・Graph->Table表示をできるようにした. * ・Table->Graph表示をできるようにした. * ・Activeの状態を変えられるようにした(現在の設計上Chartのみ) * ・Overview, Export JPGを分離し,ファイルメニューとした * ・TableにselectAllメニューをつけた(便利) * * 1.3.0 2011.05.05 * ・(内部リファクタリング終了) * ・全体的に内部デザイン一新 * ・InternalFrame版 * ・高速化 * ・プロファイリングに基づくボトルネック部分の高速化.(hashcodeのキャッシングなどで解決) * ・描画タイミングの整理により,不必要なところでの描画をしないようにした * ・メトリクス計算アーキテクチャの整理により,不必要なところで計算しない,かつ一度計算したらキャッシングする * ・MVCアーキテクチャの一段階明確化 * ・Viewがいくつでも作れるようになった. * ・選択をModelにし,メトリクス画面でも選択が可能になった * ・メトリクスのModel化とLazyチェーンアーキテクチャ * ・選択したものだけ計算し,かつ重複計算しない * ・Rを使用して,メトリクスの正確さを検証し直した(invalidにしたときの値の検証は未定) * ・言語プロセッサアーキテクチャ * ・言語が切り替え可能 * ・TimeFilter画面の一新 * ・拡大,縮小が可能 * ・TimeFilterの入れ替えなど,高機能にし,かつ操作の簡便化 * ・新機能 * ・中心化傾向などGraphのメトリクスに対応 * ・新メトリクス対応(クラスター係数など) * ・グラフ表示の便利機能(選択しているもの,およびそのメトリクス列をすべてグラフにする) * ・関係Modelを追加.ダブルクリックで,その詳細が見られる+weightメトリクスに今後対応可能 * ・英語版,日本語版切り替え * ・Discourse Unit単位切り替え * ・生存期間(試し機能) * ・RへのExport機能 * 1.2.1 2011.04.13 * ・WordSelectionViewで ResizeWeightがおかしい→解決しました * 1.2.0 2011.04.12 * ・( リファクタリングの半分が終わった所) * ・数値整列問題はNewTableSorterを使えば解決するらしい ?-> Integerを返すように再設計し解決した * ・HTML表示が遅すぎる ->ボトルネックはJTable->cashで解決した * ・指標でN/Aにすべき所を0にしている(BCの離れ小島など)→対応しました * ・Nの値,NodeがValidかどうかを計算に入れること(BCはOK, 近接中心は未)→対応しました */ public class KBDeX { private static final String VERSION = "1.10.1"; private static final String DATE = "2015.10.02"; private static final String TITLE = "KBDeX Version " + VERSION + " (built at " + DATE + ")"; private static final String DATA_DIR_NAME = "data"; public static CEncoding ENCODING_OUT = CEncoding.UTF8; public static final boolean DEBUG = true; private static KBDeX instance; private KDDiscourseManager dManager; private CPanelProcessingMonitor monitor; public static final KBDeX getInstance() { if (instance == null) { instance = new KBDeX(); } return instance; } private KBDeX() { } public void run() throws Exception { checkJavaVersion(); initializeEncoding(); initializeUI(); dManager = new KDDiscourseManager(getDataDir()); KDiscourseManagerFrame frame = new KDiscourseManagerFrame(dManager, KBDeX.TITLE); frame.openWindowInDefaultSize(); } private void initializeEncoding() { if (CJavaSystem.getInstance().isJapaneseOS()) { ENCODING_OUT = CEncoding.Shift_JIS; } } public void checkJavaVersion() { double version = CJavaSystem.getInstance().getVersion(); if (version < 1.7) { JOptionPane.showMessageDialog(null, "KBDeX requires Java 1.7+ but your Java version is " + version); System.exit(0); } } public void initializeUI() { try { if (CJavaSystem.getInstance().isMac()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty( "com.apple.mrj.application.apple.menu.about.name", "KBDeX"); } // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Exception ex) { ex.printStackTrace(); return; } } public KDDiscourseManager getDiscourseManager() { return dManager; } @Deprecated public CDirectory getDataDir() { return CFileSystem.getExecuteDirectory() .findOrCreateDirectory(DATA_DIR_NAME); } public Image getIconImage32() { return getIconImage("kbdex32x32.png"); } public Image getIconImage16() { return getIconImage("kbdex16x16.png"); } public ImageIcon getImageIcon(String name) { return new ImageIcon(getIconImage(name)); } public Image getIconImage(String name) { return getImage("icons/" + name); } public Image getImage(String path) { try { URL url = KBDeX.class.getResource(path); BufferedImage image = ImageIO.read(url); return image; } catch (Exception ex) { ex.printStackTrace(); return new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); } } public CPanelProcessingMonitor getMonitor() { if (monitor == null) { JFrame frame = new JFrame(); frame.setIconImage(getIconImage16()); monitor = new CPanelProcessingMonitor(frame, false); } return monitor; } public void handleException(Frame owner, Exception ex) { if (DEBUG) { ex.printStackTrace(); } CErrorDialog.show(owner, "ERROR", ex); } }
KBDeX/src/kbdex/app/KBDeX.java
/* * KBDeX.java * Created on Jun 27, 2010 * Copyright(c) 2010 Yoshiaki Matsuzawa, Shizuoka University. All rights reserved. */ package kbdex.app; import java.awt.Frame; import java.awt.Image; import java.awt.image.BufferedImage; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.UIManager; import kbdex.app.manager.KDDiscourseManager; import kbdex.app.manager.KDiscourseManagerFrame; import clib.common.filesystem.CDirectory; import clib.common.filesystem.CFileSystem; import clib.common.system.CEncoding; import clib.common.system.CJavaSystem; import clib.view.dialogs.CErrorDialog; import clib.view.progress.CPanelProcessingMonitor; /** * KBDeX(Knowledge Building Discourse eXplorer) Application * Copyright(c) 2010-2011 Yoshiaki Matsuzawa, Jun Oshima, Ritsuko Oshima at Shizuoka University. All rights reserved. * * <バグ> * TODO 100 戻るときに,ボタン連打すると,計算途中で戻るが反応してしまい,結果,たくさん戻ってしまうように見える. * * <懸案事項> * TODO 10 Hide機能のテスト(リファクタリング後できていなかったものをできるようにしたので) * TODO 10 Graph表示で,タイトルを変えられるようにしたい(何が何だかわからなくなる) * TODO 10 Graph表示, Table表示からのcsv, xls吐出機能,(R,Gnuplotもイイネ!) * * <更新履歴> * 1.9.10 2015.06.28 * ・https support for kf5 * * 1.9.9 2014.12.19 with Frank * ・bugfix * * 1.9.8 2014.12.19 with Frank * ・Multiple View for kf5 * ・FRLayout in default * * 1.9.7 2014.11.28 * ・Color kinds are added to 22 * * 1.9.6 2014.11.18 * ・Fixed CSV file reading problem * * 1.9.5 2014.11.17 * ・Selection Word Saving Bug fix * ・Metrics CSV * * 1.9.4 2014.10.10 * ・Label updated * * 1.9.3 2014.10.10 * ・fixed Turkish problem -> utf8 * ・fixed bug of lifetime * * 1.9.2 2014.09.23 * ・Word Bag for frequency * (plus mark to create a word bag for frequency) * ・ignore word list * (minus mark to suppress detecting the particular word in word selection) * * 1.9.1 2014.09.19 * ・Bugfix for WordBag * ・copy pasting for mac java7 * * 1.9.0 2014.09.19 * ・WordBag * (exclamation mark to make a word bag) * * 1.8.2 2014.08.28 * ・Fixed bug of output-R * * 1.8.1 2014.08.20 * ・CFileがBOMをつけないように,かつBOMを読み飛ばすように変更 * ・辞書なしのエラー処理 * * 1.8.0 2014.08.20 * ・GPL License * ・Launch * ・non-japanese version * * 1.7.2 2014.08.20 * ・HongKongの人の要請で,UTF-8のテキストを扱えるようにする(DefaultをUTF-8,読み込み自動判定にした) * ・WordSelectionでDirtyStateの検知,表示,確認. * ・WordSelection他のDialogSizeを変更 (screenの3/4) * * 1.7.1 2014.07.18 * ・KF5, ファイル名,キャンセルなど細かいミスなどの修正. * * 1.7.0 2014.07.17 * ・KF5に対応 * * 1.6.1 2013.07.13 * ・Java1.7以上でない場合にエラーダイアログを表示する. * * 1.6.0 2013.06.19 * ・大島先生のご要望によりノードアイコン追加 * * 1.5.8 2012.11.09 * ・バグ修正 KDiscourseViewerPanelでTextがソートされない * ・公開にあたり,付属の例を修正 * * 1.5.7 2012.10.26 * ・Monicaのバグ報告により修正 * ・KFから取得時に,時間をModify時でとっていた=>しかしTimeFilterは最初と最後のノートの時刻で判断=>最後のノート以降に更新されたノートが範囲外 * ・対策(1),Crea時間にした * ・対策(2),Defaultの時間範囲を,全てのノートを参照して計算するようにした(多少冗長であるが) * * 1.5.6 2012.10.04 * ・Bodongの要求により viewを指定してKFを読み込めるようにする * ・CommonLibraryを新しいバージョンに入替 * * 1.5.5 2012.03.19 * ・BSLボタン グラフレイアウト機能 指標をDegree Centralityの総和に変更 * * 1.5.4 2012.02.03 * ・BSLボタン グラフレイアウト機能 指標のactive状態をリセットするように対応. * * 1.5.3 2011.12.02 * ・BSLボタン グラフレイアウト機能 (途中だがCLE研究会で発表) * * 1.5.2 2011.11.28  * ・Fontを変えられるようにtemporaryの修正 * * 1.5.1 2011.11.27 学マネKBDeX実験(2)投入 * ・TableMetricsでSSがとれなかったバグを修正 * ・TableMetrics表示時に最新の指標が反映できていなかったバグを修正 * ・Reloadボタンの追加 * * 1.5.0 2011.11.27 学マネKBDeX実験(2)投入 RC * ・時系列メトリクス計算方針の大幅変更 * ・全部キャッシュし,グラフには基本的に全部表示する. * ・現在の位置をインジケータで示す. * ・そこで選んだものだけでなく、シリーズで出てくるすべてのノードを対象とする * ・メトリクス作成インタフェイスの大幅変更 * ・Graph, Nodeが別れていてわかりにくかったので統一. * ・Graph, Tableを作るインタフェイスをActivationと統一し,かつ直感的に分かりやすいように変更 * * 1.4.0 2011.11.14 * ・アニメーション速度調整機能の追加 * * 1.3.9 2011.11.13 学マネKBDeX実験(1)投入 * ・メイン画面全体のスクリーンキャプチャ機能 * ・Noスキップ機能UI調整 * * 1.3.8 2011.11.13 * ・KaniChatCSVの複数同時読み込み機能を追加 * ・スクリーンキャプチャ機能,currentIDがnullの時の不具合を修正 * * 1.3.7 2011.11.12 * ・文字コード周りの整理 * ・data.csv形式の読込み,書出しの文字コードをShift_JISに固定 * ・Import機能の拡充 * ・KaniChatCSV形式の読み込み機能を追加 * ・KF読込も含めて,読み込みまわりのリファクタリングを実施 * ・CSVをcommonsライブラリで読み込むように変更した関係で,CSVの仕様が若干変わった.(改行が入っても良い,下位互換性あり) * ・読込んだときのデフォルトlifetimeを20から無しに変更 * ・スクリーンキャプチャ機能の追加 * * 1.3.6 2011.08.02 * ・DiscourseViewerにNo追加 * ・DiscourseコントローラにNo指定を追加 * ・RelationパネルでUnitダブルクリックでUnit内容表示ウインドウを表示するように * * 1.3.5 2011.07.24 * ・選ぶ単語に重複箇所(ex 自動車,車)単語ハイライト表示部(label)のアサーションに引っかかり, * 正常動作しなくなる問題を修正 * * 1.3.4 2011.05.07 * ・toLast時にGraphが途中描画されないように調整 * ・選択したものが,resetすると消去されてしまう(Tableの選択が解除され,そこで選択がクリアされてしまう)問題をFix * * 1.3.3 2011.05.06 * ・Graphの調整 * ・グラフのラベル選択をできるようにする * ・グラフを直接選択できるようにする * ・グラフの設定画面のレイアウト変更し,少なくても多くても散らばることなく表示される. * ・Graph表示での選択機能に対応.(Graph->Network Network->Graph)両対応 * ・Table表示での選択機能に対応.(新しくNetwork->Tableに対応) * ・英語版サンプルを追加 * * 1.3.2 2011.05.06 * ・時間がかかる処理での進捗表示,およびキャンセル機能を追加(2.5秒後に出る設定) * * 1.3.1 2011.05.05 * ・(解決)Graph表示で,NaNの表示がおかしい. * ・(解決)この先,structureChanged()でソート条件がリセットされてしまう.(暫定的に解決) * ・(解決)リセット時,グラフが以前のバージョンの最後の値で初期化される * ・(解決) Graph表示で,Explanationが見にくい.→Overviewを分離 * ・(解決) Graph表示で,そのものを残しておきたい(コピーしたい.)→コピー,Pinをできるようにした * ・Graph->Table表示をできるようにした. * ・Table->Graph表示をできるようにした. * ・Activeの状態を変えられるようにした(現在の設計上Chartのみ) * ・Overview, Export JPGを分離し,ファイルメニューとした * ・TableにselectAllメニューをつけた(便利) * * 1.3.0 2011.05.05 * ・(内部リファクタリング終了) * ・全体的に内部デザイン一新 * ・InternalFrame版 * ・高速化 * ・プロファイリングに基づくボトルネック部分の高速化.(hashcodeのキャッシングなどで解決) * ・描画タイミングの整理により,不必要なところでの描画をしないようにした * ・メトリクス計算アーキテクチャの整理により,不必要なところで計算しない,かつ一度計算したらキャッシングする * ・MVCアーキテクチャの一段階明確化 * ・Viewがいくつでも作れるようになった. * ・選択をModelにし,メトリクス画面でも選択が可能になった * ・メトリクスのModel化とLazyチェーンアーキテクチャ * ・選択したものだけ計算し,かつ重複計算しない * ・Rを使用して,メトリクスの正確さを検証し直した(invalidにしたときの値の検証は未定) * ・言語プロセッサアーキテクチャ * ・言語が切り替え可能 * ・TimeFilter画面の一新 * ・拡大,縮小が可能 * ・TimeFilterの入れ替えなど,高機能にし,かつ操作の簡便化 * ・新機能 * ・中心化傾向などGraphのメトリクスに対応 * ・新メトリクス対応(クラスター係数など) * ・グラフ表示の便利機能(選択しているもの,およびそのメトリクス列をすべてグラフにする) * ・関係Modelを追加.ダブルクリックで,その詳細が見られる+weightメトリクスに今後対応可能 * ・英語版,日本語版切り替え * ・Discourse Unit単位切り替え * ・生存期間(試し機能) * ・RへのExport機能 * 1.2.1 2011.04.13 * ・WordSelectionViewで ResizeWeightがおかしい→解決しました * 1.2.0 2011.04.12 * ・( リファクタリングの半分が終わった所) * ・数値整列問題はNewTableSorterを使えば解決するらしい ?-> Integerを返すように再設計し解決した * ・HTML表示が遅すぎる ->ボトルネックはJTable->cashで解決した * ・指標でN/Aにすべき所を0にしている(BCの離れ小島など)→対応しました * ・Nの値,NodeがValidかどうかを計算に入れること(BCはOK, 近接中心は未)→対応しました */ public class KBDeX { private static final String VERSION = "1.10.0"; private static final String DATE = "2015.10.02"; private static final String TITLE = "KBDeX Version " + VERSION + " (build on " + DATE + ")"; private static final String DATA_DIR_NAME = "data"; public static CEncoding ENCODING_OUT = CEncoding.UTF8; public static final boolean DEBUG = true; private static KBDeX instance; private KDDiscourseManager dManager; private CPanelProcessingMonitor monitor; public static final KBDeX getInstance() { if (instance == null) { instance = new KBDeX(); } return instance; } private KBDeX() { } public void run() throws Exception { checkJavaVersion(); initializeEncoding(); initializeUI(); dManager = new KDDiscourseManager(getDataDir()); KDiscourseManagerFrame frame = new KDiscourseManagerFrame(dManager, KBDeX.TITLE); frame.openWindowInDefaultSize(); } private void initializeEncoding() { if (CJavaSystem.getInstance().isJapaneseOS()) { ENCODING_OUT = CEncoding.Shift_JIS; } } public void checkJavaVersion() { double version = CJavaSystem.getInstance().getVersion(); if (version < 1.7) { JOptionPane.showMessageDialog(null, "KBDeX requires Java 1.7+ but your Java version is " + version); System.exit(0); } } public void initializeUI() { try { if (CJavaSystem.getInstance().isMac()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty( "com.apple.mrj.application.apple.menu.about.name", "KBDeX"); } // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); UIManager .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Exception ex) { ex.printStackTrace(); return; } } public KDDiscourseManager getDiscourseManager() { return dManager; } @Deprecated public CDirectory getDataDir() { return CFileSystem.getExecuteDirectory().findOrCreateDirectory( DATA_DIR_NAME); } public Image getIconImage32() { return getIconImage("kbdex32x32.png"); } public Image getIconImage16() { return getIconImage("kbdex16x16.png"); } public ImageIcon getImageIcon(String name) { return new ImageIcon(getIconImage(name)); } public Image getIconImage(String name) { return getImage("icons/" + name); } public Image getImage(String path) { try { URL url = KBDeX.class.getResource(path); BufferedImage image = ImageIO.read(url); return image; } catch (Exception ex) { ex.printStackTrace(); return new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); } } public CPanelProcessingMonitor getMonitor() { if (monitor == null) { JFrame frame = new JFrame(); frame.setIconImage(getIconImage16()); monitor = new CPanelProcessingMonitor(frame, false); } return monitor; } public void handleException(Frame owner, Exception ex) { if (DEBUG) { ex.printStackTrace(); } CErrorDialog.show(owner, "ERROR", ex); } }
Updated version comment
KBDeX/src/kbdex/app/KBDeX.java
Updated version comment
<ide><path>BDeX/src/kbdex/app/KBDeX.java <ide> import javax.swing.JOptionPane; <ide> import javax.swing.UIManager; <ide> <del>import kbdex.app.manager.KDDiscourseManager; <del>import kbdex.app.manager.KDiscourseManagerFrame; <ide> import clib.common.filesystem.CDirectory; <ide> import clib.common.filesystem.CFileSystem; <ide> import clib.common.system.CEncoding; <ide> import clib.common.system.CJavaSystem; <ide> import clib.view.dialogs.CErrorDialog; <ide> import clib.view.progress.CPanelProcessingMonitor; <add>import kbdex.app.manager.KDDiscourseManager; <add>import kbdex.app.manager.KDiscourseManagerFrame; <ide> <ide> /** <ide> * KBDeX(Knowledge Building Discourse eXplorer) Application <ide> * TODO 10 Graph表示, Table表示からのcsv, xls吐出機能,(R,Gnuplotもイイネ!) <ide> * <ide> * <更新履歴> <add> * 1.10.1 2015.10.02 <add> *  ・kf6 support <add> * <add> * 1.10.0 (gitの操作ミスによって消えた,幻のバージョン) <add> * <ide> * 1.9.10 2015.06.28 <ide> * ・https support for kf5 <ide> * <ide> */ <ide> public class KBDeX { <ide> <del> private static final String VERSION = "1.10.0"; <add> private static final String VERSION = "1.10.1"; <ide> private static final String DATE = "2015.10.02"; <ide> private static final String TITLE = "KBDeX Version " + VERSION <del> + " (build on " + DATE + ")"; <add> + " (built at " + DATE + ")"; <ide> private static final String DATA_DIR_NAME = "data"; <ide> public static CEncoding ENCODING_OUT = CEncoding.UTF8; <ide> public static final boolean DEBUG = true; <ide> "KBDeX"); <ide> } <ide> // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); <del> UIManager <del> .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); <add> UIManager.setLookAndFeel( <add> "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); <ide> } catch (Exception ex) { <ide> ex.printStackTrace(); <ide> return; <ide> <ide> @Deprecated <ide> public CDirectory getDataDir() { <del> return CFileSystem.getExecuteDirectory().findOrCreateDirectory( <del> DATA_DIR_NAME); <add> return CFileSystem.getExecuteDirectory() <add> .findOrCreateDirectory(DATA_DIR_NAME); <ide> } <ide> <ide> public Image getIconImage32() {
JavaScript
mit
361c071c0b9730fe78fe8b6fc01aa828d504a356
0
gilfillan9/spotify-jukebox,gilfillan9/spotify-jukebox
var spotifyApi = new SpotifyWebApi() var queue; var currentTrack; var trackCache = {}; var loaded = false; var ourIp; var notificationsAllowed = false; var searchPage; $(function () { if (localStorage.getItem("queue") != null) localStorage.setItem("oldQueue", localStorage.getItem("queue")); $.ajaxSetup({ cache: true }); async.series([loadTemplates, loadPages], function () { console.log("Connecting...") var socket = window.socket = io('ws://' + window.location.hostname + "/", {transports: ['websocket']}); socket.on('connect', function () { console.log("Connected to server"); }); socket.on("reconnect", function () { console.log("Reconnected"); $("body").removeClass("disconnected") }) socket.on("disconnect", function () { console.error("Disconnected"); $("body").addClass("disconnected") }) socket.on("playState", function (playing) { console.log("playState", playing) $("footer .play").toggleClass("icon-control-play", !playing).toggleClass("icon-control-pause", !!playing); }) socket.on("ip", function (ip) { ourIp = ip; }); socket.on("playQueue", function (_queue) { queue = _queue; localStorage.setItem("queue", JSON.stringify(queue)); //Save queue (saves from crashes!) $(".shuffle-button").toggleClass("active", queue.shuffled) if (queue.tracks.length > 0) { getTracks(queue.tracks).then(function (tracks) { queue.tracks = tracks; $(".play-queue").html(templates.playQueue({ tracks: tracks })); doneLoaded(); }) } else { doneLoaded(); $(".play-queue ul").html("") } }); socket.on("changedCurrent", function (track) { if (!track) { changedCurrent(track); return; } var id = track.link.split(":")[2]; if ("undefined" !== typeof trackCache[id]) { changedCurrent(trackCache[id]); } else { spotifyApi.getTrack(id).then(function (_track) { trackCache[id] = _track; changedCurrent(_track); }); } }); socket.on("seek", function (time) { $(".duration-slider").val(time); $("footer .current-time").text(formatDuration(time * 1000)); }) socket.on("volume", function (volume) { volume = Math.pow(volume / 21.5, 3); $("footer .volume").val(volume); }) socket.on("isPhone", function (isPhone) { $(".phone-call-on").toggleClass("active", isPhone); }) socket.on("accessToken", function (accessToken) { spotifyApi.setAccessToken(accessToken); if (!loaded) { //Load the current page (or default) var prom; if (window.location.hash != "") { prom = navigateToPath(window.location.hash.slice(1), true); } else { prom = navigateTo("browse"); } prom.then(function () { socket.emit("getQueue"); }) checkNotifications(); } }) socket.on("error", function (message) { console.log(message); doNotification(message, {timeout: 5}) }); socket.on("history", function (history) { if (window.historyFn) { window.historyFn(history); delete window.historyFn; } }) $("body").on("click", "[data-nav]", function () { navigateTo($(this).attr("data-nav")); return false; }); $("footer").on("click", ".play", function () { if ($(this).is(".icon-control-play")) { socket.emit("play"); } else { socket.emit("pause"); } return false; }) $("footer").on("click", ".next", function () { socket.emit("skip"); return false; }); $("footer").on("click", ".back", function () { socket.emit("skipBack"); return false; }) $("footer").on("change", ".volume", function () { var val = parseInt($(this).val()); socket.emit("setVolume", Math.pow(val, 1 / 3) * 21.5); }); $("footer").on("click", ".shuffle-button", function () { socket.emit("toggleShuffle", !$(this).hasClass("active")); }); $("body").on("change", ".duration-slider", function () { socket.emit("seek", parseInt($(this).val())); }); $("body").on("focus", ".search", function () { if ($(this).hasClass("show")) return; $(".search-content").html(templates.searchPage({ emptySearch: true })).addClass("show"); if ($(".search").val() != "") { doSearch($(".search").val()); } else { searchPage = "track"; } setTimeout(function () { $(".search-content").addClass("fadein"); }) }); $("body").on("blur", ".search", function () { if ($(this).val() != "") return; $(".search-content").removeClass("fadein"); setTimeout(function () { $(".search-content").removeClass("show"); }, 500) }); $("body").on("change keypress", ".search", _.debounce(function () { doSearch($(this).val()); }, 1000)) $("body").on("click", ".close-search", function () { $(".search-content").removeClass("fadein") setTimeout(function () { $(".search-content").removeClass("show") }, 500) return false; }) $("body").on("click", ".search-tabs .search-tab", function () { searchPage = $(this).attr("data-tab"); doSearch($(".search").val()) return false; }) $("body").on("click", "[data-uri][data-action]", function () { $(".track-popup").remove(); handleAction($(this).attr("data-action"), $(this).attr("data-uri"), $(this).parents("table").attr("data-uri")) }) $("body").on("dblclick", "[data-uri][data-double-action]", function () { $(".track-popup").remove(); handleAction($(this).attr("data-double-action"), $(this).attr("data-uri"), $(this).parents("table").attr("data-uri")) return false; }) $("body").on("mousedown", "[data-uri][data-double-action]", function (e) { if (e.which == 1) return false; }) $("body").on("click", ".phone-call-on", function () { socket.emit("phoneOn"); return false; }) $("body").on("click", ".phone-call-off", function () { socket.emit("phoneOff"); return false; }) $("body").on("click", "aside.play-queue .vote-buttons button", function () { socket.emit("vote", {uuid: $(this).parents("li").attr("data-uuid"), up: $(this).is(".up")}) return false; }) $("body").on("keypress", function (e) { var $target = $(e.target); if ($target.is("input,textarea,button,select")) return true; if (e.which == 32) { //Space $("button.play").click(); return false; } }) $(".play-queue").on("mouseenter", "li", function (e) { if ($(".track-popup[data-uuid='" + $(this).attr("data-uuid") + "']").length != 0) return; var track = queue.tracks.filter(function (track) { return track.uuid == $(this).attr("data-uuid"); }.bind(this))[0]; var getPromise = track.source ? handleAction("get", track.source) : undefined; Promise.all([getPromise, new Promise(function (resolve) { $(this).data("timeout", setTimeout(resolve, 500)) }.bind(this)) ]).then(function (source) { $(".track-popup").remove(); var $popup = $(templates.trackPopup($.extend({}, track, {source: source[0]}))); $popup.attr("data-uuid", $(this).attr("data-uuid")); $popup.find("img").on("load", function () { $("body").append($popup); $popup.css("top", Math.max(0, Math.min( $(window).height() - $popup.height(), e.pageY - 50 ))) }) }.bind(this)) }); $(".play-queue").on("mouseleave", "li", function (e) { clearTimeout($(this).data("timeout")); var $popup = $(".track-popup[data-uuid='" + $(this).attr("data-uuid") + "']"); var $to = $(e.toElement); try { if (!$.contains($popup[0], $to[0]) && $popup[0] != $to[0]) $popup.remove(); } catch (e) { } }); $("body").on("mouseleave", ".track-popup", function (e) { var $to = $(e.toElement); if ($to.is(".play-queue li[data-uuid]") && $to.attr("data-uuid") == $(this).attr("data-uuid")) { return false; } $(this).remove(); }) window.addEventListener("popstate", function (e) { if (e.state && e.state.page) { navigateTo(e.state.page, e.state.args, true); } else { navigateToPath(window.location.hash.slice(1), true); } }) }) }); function doneLoaded() { if (!loaded) { $("body").removeClass("loading"); setTimeout(function () { $("body").removeClass("showLoader"); }, 500) loaded = true; } } function changedCurrent(track) { currentTrack = track; if (!track) { $("footer .length").text("00:00"); $("footer .duration-wrap .song-name").text(""); } else { $(".duration-slider").attr("max", Math.round(track.duration_ms / 1000)) if (currentPage == "nowPlaying") navigateTo(currentPage); //Refresh the now playing page $("footer .length").text(formatDuration(track.duration_ms)); $("footer .duration-wrap .song-name").text(track.name + ' - ' + track.artists[0].name); doNotification("Now playing", { tag: "nowPlaying", body: track.name, icon: track.album.images[0].url, timeout: 10 }); } } function handleAction(action, uri, data) { var split = action.split("|"); if (split.length == 2) { if (split[0] == "clear") socket.emit("clearQueue"); action = split[split.length - 1]; } var type = uri.split(":")[1]; if (type == "user") type = "playlist"; //Assuming we're not going to use playlists if (action == "add") { switch (type) { case "artist": //Wat break; case "album": socket.emit("addAlbum", uri); break; case "track": var alreadyIn = false; queue.tracks.forEach(function (track) { if (track.uri == uri) alreadyIn = true; }) if (!alreadyIn || confirm("This track is already in the queue, do you want to add it again?")) socket.emit("addTrack", {uri: uri, source: data}); break; case "playlist": socket.emit("addPlaylist", uri); break; } } else if (action == "view") { switch (type) { case "artist": navigateTo("viewArtist", {uri: uri}); break; case "album": navigateTo("viewAlbum", {uri: uri}); break; case "track": navigateTo("viewTrack", {uri: uri}); break; case "playlist": navigateTo("viewPlaylist", {uri: uri}); break; case "category": navigateTo("viewCategory", {id: uri.split(":")[2]}); break; } } else if (action == "get") { switch (type) { case "artist": return spotifyApi.getArtist(uri.split(":").pop()); case "playlist": var splitUri = uri.split(":"); return spotifyApi.getPlaylist(splitUri[2], splitUri.pop()); } } } function doSearch(val) { if (val.length < 2) { $(".search-content").html(templates.searchPage({emptySearch: true})); return; } else { $(".search-content").html(templates.searchPage({ loading: true })); } if (searchPage == "track") { spotifyApi.searchTracks(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ tracks: results.tracks.items })); }); } else if (searchPage == "album") { spotifyApi.searchAlbums(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ albums: results.albums.items })); }) } else if (searchPage == "artist") { spotifyApi.searchArtists(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ artists: results.artists.items })); }) } else if (searchPage == "playlist") { spotifyApi.searchPlaylists(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ playlists: results.playlists.items })); }) } } function navigateToPath(path, noPush) { var hashSplit = path.split("?"); var args = undefined; if (hashSplit.length == 2) { var vars = hashSplit[1].split("&"); var args = {}; vars.forEach(function (val) { var split = val.split("="); args[decodeURIComponent(split[0])] = decodeURIComponent(split[1]); }) } return navigateTo(hashSplit[0], args, noPush); } function navigateTo(_page, args, noPush) { return new Promise(function (resolve, reject) { console.log("Loading page %s", _page, args); var samePage = _page == currentPage; var page = pages[_page]; if ("undefined" == typeof page) { console.log("Invalid page: %s", _page); reject(); return; } $("main").html(templates.pageLoader()); currentPage = page.name; page.fn(args).then(function (data) { var $page = $(page.template(data)); $("main").html($page); setTimeout(function () { if ("function" === typeof page.after) page.after.call({}, $page); resolve(); }) }) $("#nav .left-nav ul li a[data-nav]").removeClass("selected") $("#nav .left-nav ul li a[data-nav='" + currentPage + "']").addClass("selected") samePage || noPush || history.pushState({ page: _page, args: args }, false, "#" + _page + ("undefined" != typeof args ? "?" + $.param(args) : "")); if ($(".search-content").hasClass("fadein")) { $(".search-content").removeClass("fadein") setTimeout(function () { $(".search-content").removeClass("show") }, 500) } }) } function registerPage(name, fn, template, after) { pages[name] = { name: name, fn: fn, template: template, after: after } } var pages = {}; var templates = {}; var currentPage; function formatDuration(ms) { var totalSeconds = Math.round(ms / 1000); var seconds = totalSeconds % 60; var minutes = Math.floor(totalSeconds / 60) % 60; var hours = Math.floor(totalSeconds / (60 * 60)); return (hours > 0 ? hours + ":" : "") + padString(minutes, 2) + ":" + padString(seconds, 2); } function formatTimestamp(ms) { if (!ms) return; var date = new Date(ms); return timeSince(date) + " ago"; } function timeSince(date) { var seconds = Math.floor((new Date() - date) / 1000); var interval = Math.floor(seconds / 31536000); if (interval > 1) { return interval + " years"; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return interval + " months"; } interval = Math.floor(seconds / 86400); if (interval > 1) { return interval + " days"; } interval = Math.floor(seconds / 3600); if (interval > 1) { return interval + " hours"; } interval = Math.floor(seconds / 60); if (interval > 1) { return interval + " minutes"; } return Math.floor(seconds) + " seconds"; } function loadTemplates(cb) { var loaded = false; console.groupCollapsed("Loading Templates"); Handlebars.registerHelper("duration", formatDuration) Handlebars.registerHelper("timestamp", formatTimestamp) $.getJSON("/templates.json").then(function (data) { async.parallel([ function (cb) { async.map(data.templates, function (name, cb) { $.get("/templates/" + name + ".hbs").then(function (data) { templates[name] = Handlebars.compile(data); console.log("Compiled %s", name) cb(); }) }, cb) }, function (cb) { async.map(data.partials, function (name, cb) { $.get("/templates/partials/" + name + ".hbs").then(function (data) { Handlebars.registerPartial(name, data); console.log("Compiled fragment %s", name) cb(); }) }, cb) }], function () { console.groupEnd(); loaded = true; cb(); }); }); setTimeout(function () { if (!loaded) { alert("A problem occurred loading the templates. Reloading...") window.location.reload(); } }, 8 * 1000); } function padString(value, width, padWith) { padWith = padWith || '0'; value = '' + value; return value.length >= width ? value : new Array(width - value.length + 1).join(padWith) + value; } function loadPages(cb) { var loaded = false; console.groupCollapsed("Loading pages"); $.getJSON("/pages.json").then(function (pages) { async.map(pages, function (name, cb) { console.log("Loading page %s", name) $.getScript("/js/pages/" + name).then(function () { console.log("Loaded page %s", name) setTimeout(cb); }, function () { doNotification("Couldn't load page " + name, {timeout: 5}) }); }, function () { loaded = true; console.groupEnd(); cb(); }) }); setTimeout(function () { if (!loaded) { alert("A problem occurred loading the pages. Reloading...") window.location.reload(); } }, 8 * 1000); } function doNotification(title, args, callback) { if (notificationsAllowed) { if (!callback) callback = $.noop; var notification = new Notification(title, args); callback(notification); if ("undefined" !== typeof args.timeout) { setTimeout(function () { notification.close(); }, args.timeout * 1000) } } } function checkNotifications() { try { if (localStorage.getItem("notificationsAllowed") == null) { Notification.requestPermission(function (data) { notificationsAllowed = data == "granted"; localStorage.setItem("notificationsAllowed", notificationsAllowed); }); } else { notificationsAllowed = localStorage.getItem("notificationsAllowed") == "true"; } } catch (e) { notificationsAllowed = false; } } function getTracks(uris) { return new Promise(function (resolve, reject) { if (uris.length == 0) resolve([]); //Don't do nought for an empty list... var uncachedTracks = uris.filter(function (track) { return "undefined" == typeof trackCache["string" === typeof track ? track : track.id] }) var tracksSplit = []; var i, chunk = 50; for (i = 0; i < uncachedTracks.length; i += chunk) { uncachedTracks.slice(i, i + chunk); tracksSplit.push(uncachedTracks.slice(i, i + chunk).map(function (track) { return "string" === typeof track ? track : track.id; })); } async.each(tracksSplit, function (item, cb) { spotifyApi.getTracks(item).then(function (result) { result.tracks.forEach(function (track) { if (track == null) return; trackCache[track.id] = track; }); cb(); }) }, function () { var tracks = uris.map(function (track) { if ("object" === typeof track) { var _track = $.extend({}, trackCache[track.id]); //Make a copy; _track.source = track.source; _track.votes = track.votes; _track.uuid = track.uuid; _track.votesIps = track.votesIps; _track.vote = "undefined" == typeof track.votesIps[ourIp] ? 0 : track.votesIps[ourIp] _track.votedUp = _track.vote == 1; _track.votedDown = _track.vote == -1; } else { var _track = $.extend({}, trackCache[track]); } return _track; }); resolve(tracks) }) }); }
lib/public/js/app.js
var spotifyApi = new SpotifyWebApi() var queue; var currentTrack; var trackCache = {}; var loaded = false; var ourIp; var notificationsAllowed = false; var searchPage; $(function () { if (localStorage.getItem("queue") != null) localStorage.setItem("oldQueue", localStorage.getItem("queue")); $.ajaxSetup({ cache: true }); async.series([loadTemplates, loadPages], function () { console.log("Connecting...") var socket = window.socket = io('ws://' + window.location.hostname + "/", {transports: ['websocket']}); socket.on('connect', function () { console.log("Connected to server"); }); socket.on("reconnect", function () { console.log("Reconnected"); $("body").removeClass("disconnected") }) socket.on("disconnect", function () { console.error("Disconnected"); $("body").addClass("disconnected") }) socket.on("playState", function (playing) { console.log("playState", playing) $("footer .play").toggleClass("icon-control-play", !playing).toggleClass("icon-control-pause", !!playing); }) socket.on("ip", function (ip) { ourIp = ip; }); socket.on("playQueue", function (_queue) { queue = _queue; localStorage.setItem("queue", JSON.stringify(queue)); //Save queue (saves from crashes!) $(".shuffle-button").toggleClass("active", queue.shuffled) if (queue.tracks.length > 0) { getTracks(queue.tracks).then(function (tracks) { queue.tracks = tracks; $(".play-queue").html(templates.playQueue({ tracks: tracks })); doneLoaded(); }) } else { doneLoaded(); $(".play-queue ul").html("") } }); socket.on("changedCurrent", function (track) { if (!track) { changedCurrent(track); return; } var id = track.link.split(":")[2]; if ("undefined" !== typeof trackCache[id]) { changedCurrent(trackCache[id]); } else { spotifyApi.getTrack(id).then(function (_track) { trackCache[id] = _track; changedCurrent(_track); }); } }); socket.on("seek", function (time) { $(".duration-slider").val(time); $("footer .current-time").text(formatDuration(time * 1000)); }) socket.on("volume", function (volume) { volume = Math.pow(volume / 21.5, 3); $("footer .volume").val(volume); }) socket.on("isPhone", function (isPhone) { $(".phone-call-on").toggleClass("active", isPhone); }) socket.on("accessToken", function (accessToken) { spotifyApi.setAccessToken(accessToken); if (!loaded) { //Load the current page (or default) var prom; if (window.location.hash != "") { prom = navigateToPath(window.location.hash.slice(1), true); } else { prom = navigateTo("browse"); } prom.then(function () { socket.emit("getQueue"); }) checkNotifications(); } }) socket.on("error", function (message) { console.log(message); doNotification(message, {timeout: 5}) }); socket.on("history", function (history) { if (window.historyFn) { window.historyFn(history); delete window.historyFn; } }) $("body").on("click", "[data-nav]", function () { navigateTo($(this).attr("data-nav")); return false; }); $("footer").on("click", ".play", function () { if ($(this).is(".icon-control-play")) { socket.emit("play"); } else { socket.emit("pause"); } return false; }) $("footer").on("click", ".next", function () { socket.emit("skip"); return false; }); $("footer").on("click", ".back", function () { socket.emit("skipBack"); return false; }) $("footer").on("change", ".volume", function () { var val = parseInt($(this).val()); socket.emit("setVolume", Math.pow(val, 1 / 3) * 21.5); }); $("footer").on("click", ".shuffle-button", function () { socket.emit("toggleShuffle", !$(this).hasClass("active")); }); $("body").on("change", ".duration-slider", function () { socket.emit("seek", parseInt($(this).val())); }); $("body").on("focus", ".search", function () { if ($(this).hasClass("show")) return; $(".search-content").html(templates.searchPage({ emptySearch: true })).addClass("show"); if ($(".search").val() != "") { doSearch($(".search").val()); } else { searchPage = "track"; } setTimeout(function () { $(".search-content").addClass("fadein"); }) }); $("body").on("blur", ".search", function () { if ($(this).val() != "") return; $(".search-content").removeClass("fadein"); setTimeout(function () { $(".search-content").removeClass("show"); }, 500) }); $("body").on("change keypress", ".search", _.debounce(function () { doSearch($(this).val()); }, 1000)) $("body").on("click", ".close-search", function () { $(".search-content").removeClass("fadein") setTimeout(function () { $(".search-content").removeClass("show") }, 500) return false; }) $("body").on("click", ".search-tabs .search-tab", function () { searchPage = $(this).attr("data-tab"); doSearch($(".search").val()) return false; }) $("body").on("click", "[data-uri][data-action]", function () { $(".track-popup").remove(); handleAction($(this).attr("data-action"), $(this).attr("data-uri"), $(this).parents("table").attr("data-uri")) }) $("body").on("dblclick", "[data-uri][data-double-action]", function () { $(".track-popup").remove(); handleAction($(this).attr("data-double-action"), $(this).attr("data-uri"), $(this).parents("table").attr("data-uri")) return false; }) $("body").on("mousedown", "[data-uri][data-double-action]", function (e) { if (e.which == 1) return false; }) $("body").on("click", ".phone-call-on", function () { socket.emit("phoneOn"); return false; }) $("body").on("click", ".phone-call-off", function () { socket.emit("phoneOff"); return false; }) $("body").on("click", "aside.play-queue .vote-buttons button", function () { socket.emit("vote", {uuid: $(this).parents("li").attr("data-uuid"), up: $(this).is(".up")}) return false; }) $("body").on("keypress", function (e) { var $target = $(e.target); if ($target.is("input,textarea,button,select")) return true; if (e.which == 32) { //Space $("button.play").click(); return false; } }) $(".play-queue").on("mouseenter", "li", function (e) { if ($(".track-popup[data-uuid='" + $(this).attr("data-uuid") + "']").length != 0) return; var track = queue.tracks.filter(function (track) { return track.uuid == $(this).attr("data-uuid"); }.bind(this))[0]; var getPromise = track.source ? handleAction("get", track.source) : undefined; Promise.all([getPromise, new Promise(function (resolve) { $(this).data("timeout", setTimeout(resolve, 500)) }.bind(this)) ]).then(function (source) { $(".track-popup").remove(); var $popup = $(templates.trackPopup($.extend({}, track, {source: source[0]}))); $popup.attr("data-uuid", $(this).attr("data-uuid")); $popup.find("img").on("load", function () { $("body").append($popup); $popup.css("top", Math.max(0, Math.min( $(window).height() - $popup.height(), e.pageY - 50 ))) }) }.bind(this)) }); $(".play-queue").on("mouseleave", "li", function (e) { clearTimeout($(this).data("timeout")); var $popup = $(".track-popup[data-uuid='" + $(this).attr("data-uuid") + "']"); var $to = $(e.toElement); try { if (!$.contains($popup[0], $to[0]) && $popup[0] != $to[0]) $popup.remove(); } catch (e) { } }); $("body").on("mouseleave", ".track-popup", function (e) { var $to = $(e.toElement); if ($to.is(".play-queue li[data-uuid]") && $to.attr("data-uuid") == $(this).attr("data-uuid")) { return false; } $(this).remove(); }) window.addEventListener("popstate", function (e) { if (e.state && e.state.page) { navigateTo(e.state.page, e.state.args, true); } else { navigateToPath(window.location.hash.slice(1), true); } }) }) }); function doneLoaded() { if (!loaded) { $("body").removeClass("loading"); setTimeout(function () { $("body").removeClass("showLoader"); }, 500) loaded = true; } } function changedCurrent(track) { currentTrack = track; if (!track) { $("footer .length").text("00:00"); $("footer .duration-wrap .song-name").text(""); } else { $(".duration-slider").attr("max", Math.round(track.duration_ms / 1000)) if (currentPage == "nowPlaying") navigateTo(currentPage); //Refresh the now playing page $("footer .length").text(formatDuration(track.duration_ms)); $("footer .duration-wrap .song-name").text(track.name + ' - ' + track.artists[0].name); doNotification("Now playing", { tag: "nowPlaying", body: track.name, icon: track.album.images[0].url, timeout: 10 }); } } function handleAction(action, uri, data) { var split = action.split("|"); if (split.length == 2) { if (split[0] == "clear") socket.emit("clearQueue"); action = split[split.length - 1]; } var type = uri.split(":")[1]; if (type == "user") type = "playlist"; //Assuming we're not going to use playlists if (action == "add") { switch (type) { case "artist": //Wat break; case "album": socket.emit("addAlbum", uri); break; case "track": var alreadyIn = false; queue.tracks.forEach(function (track) { if (track.uri == uri) alreadyIn = true; }) if (!alreadyIn || confirm("This track is already in the queue, do you want to add it again?")) socket.emit("addTrack", {uri: uri, source: data}); break; case "playlist": socket.emit("addPlaylist", uri); break; } } else if (action == "view") { switch (type) { case "artist": navigateTo("viewArtist", {uri: uri}); break; case "album": navigateTo("viewAlbum", {uri: uri}); break; case "track": navigateTo("viewTrack", {uri: uri}); break; case "playlist": navigateTo("viewPlaylist", {uri: uri}); break; case "category": navigateTo("viewCategory", {id: uri.split(":")[2]}); break; } } else if (action == "get") { switch (type) { case "artist": return spotifyApi.getArtist(uri.split(":").pop()); case "playlist": var splitUri = uri.split(":"); return spotifyApi.getPlaylist(splitUri[2], splitUri.pop()); } } } function doSearch(val) { if (val.length < 2) { $(".search-content").html(templates.searchPage({emptySearch: true})); return; } else { $(".search-content").html(templates.searchPage({ loading: true })); } if (searchPage == "track") { spotifyApi.searchTracks(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ tracks: results.tracks.items })); }); } else if (searchPage == "album") { spotifyApi.searchAlbums(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ albums: results.albums.items })); }) } else if (searchPage == "artist") { spotifyApi.searchArtists(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ artists: results.artists.items })); }) } else if (searchPage == "playlist") { spotifyApi.searchPlaylists(val, {market: "GB"}).then(function (results) { $(".search-content").html(templates.searchPage({ playlists: results.playlists.items })); }) } } function navigateToPath(path, noPush) { var hashSplit = path.split("?"); var args = undefined; if (hashSplit.length == 2) { var vars = hashSplit[1].split("&"); var args = {}; vars.forEach(function (val) { var split = val.split("="); args[decodeURIComponent(split[0])] = decodeURIComponent(split[1]); }) } return navigateTo(hashSplit[0], args, noPush); } function navigateTo(_page, args, noPush) { return new Promise(function (resolve, reject) { console.log("Loading page %s", _page, args); var samePage = _page == currentPage; var page = pages[_page]; if ("undefined" == typeof page) { console.log("Invalid page: %s", _page); reject(); return; } $("main").html(templates.pageLoader()); currentPage = page.name; page.fn(args).then(function (data) { $("main").html(page.template(data)); resolve(); }) $("#nav .left-nav ul li a[data-nav]").removeClass("selected") $("#nav .left-nav ul li a[data-nav='" + currentPage + "']").addClass("selected") samePage || noPush || history.pushState({ page: _page, args: args }, false, "#" + _page + ("undefined" != typeof args ? "?" + $.param(args) : "")); if ($(".search-content").hasClass("fadein")) { $(".search-content").removeClass("fadein") setTimeout(function () { $(".search-content").removeClass("show") }, 500) } }) } function registerPage(name, fn, template) { pages[name] = { name: name, fn: fn, template: template } } var pages = {}; var templates = {}; var currentPage; function formatDuration(ms) { var totalSeconds = Math.round(ms / 1000); var seconds = totalSeconds % 60; var minutes = Math.floor(totalSeconds / 60) % 60; var hours = Math.floor(totalSeconds / (60 * 60)); return (hours > 0 ? hours + ":" : "") + padString(minutes, 2) + ":" + padString(seconds, 2); } function formatTimestamp(ms) { if (!ms) return; var date = new Date(ms); return timeSince(date) + " ago"; } function timeSince(date) { var seconds = Math.floor((new Date() - date) / 1000); var interval = Math.floor(seconds / 31536000); if (interval > 1) { return interval + " years"; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return interval + " months"; } interval = Math.floor(seconds / 86400); if (interval > 1) { return interval + " days"; } interval = Math.floor(seconds / 3600); if (interval > 1) { return interval + " hours"; } interval = Math.floor(seconds / 60); if (interval > 1) { return interval + " minutes"; } return Math.floor(seconds) + " seconds"; } function loadTemplates(cb) { console.groupCollapsed("Loading Templates"); Handlebars.registerHelper("duration", formatDuration) Handlebars.registerHelper("timestamp", formatTimestamp) $.getJSON("/templates.json").then(function (data) { async.parallel([ function (cb) { async.map(data.templates, function (name, cb) { $.get("/templates/" + name + ".hbs").then(function (data) { templates[name] = Handlebars.compile(data); console.log("Compiled %s", name) cb(); }) }, cb) }, function (cb) { async.map(data.partials, function (name, cb) { $.get("/templates/partials/" + name + ".hbs").then(function (data) { Handlebars.registerPartial(name, data); console.log("Compiled fragment %s", name) cb(); }) }, cb) }], function () { console.groupEnd(); cb(); }); }); } function padString(value, width, padWith) { padWith = padWith || '0'; value = '' + value; return value.length >= width ? value : new Array(width - value.length + 1).join(padWith) + value; } function loadPages(cb) { $.getJSON("/pages.json").then(function (pages) { async.map(pages, function (name, cb) { $.getScript("/js/pages/" + name).then(function () { setTimeout(cb); }); }, cb) }); } function doNotification(title, args, callback) { if (notificationsAllowed) { if (!callback) callback = $.noop; var notification = new Notification(title, args); callback(notification); if ("undefined" !== typeof args.timeout) { setTimeout(function () { notification.close(); }, args.timeout * 1000) } } } function checkNotifications() { try { if (localStorage.getItem("notificationsAllowed") == null) { Notification.requestPermission(function (data) { notificationsAllowed = data == "granted"; localStorage.setItem("notificationsAllowed", notificationsAllowed); }); } else { notificationsAllowed = localStorage.getItem("notificationsAllowed") == "true"; } } catch (e) { notificationsAllowed = false; } } function getTracks(uris) { return new Promise(function (resolve, reject) { var uncachedTracks = uris.filter(function (track) { return "undefined" == typeof trackCache["string" === typeof track ? track : track.id] }) var tracksSplit = []; var i, chunk = 50; for (i = 0; i < uncachedTracks.length; i += chunk) { uncachedTracks.slice(i, i + chunk); tracksSplit.push(uncachedTracks.slice(i, i + chunk).map(function (track) { return "string" === typeof track ? track : track.id; })); } async.each(tracksSplit, function (item, cb) { spotifyApi.getTracks(item).then(function (result) { result.tracks.forEach(function (track) { if (track == null) return; trackCache[track.id] = track; }); cb(); }) }, function () { var tracks = uris.map(function (track) { if ("object" === typeof track) { var _track = $.extend({}, trackCache[track.id]); //Make a copy; _track.source = track.source; _track.votes = track.votes; _track.uuid = track.uuid; _track.votesIps = track.votesIps; _track.vote = "undefined" == typeof track.votesIps[ourIp] ? 0 : track.votesIps[ourIp] _track.votedUp = _track.vote == 1; _track.votedDown = _track.vote == -1; } else { var _track = $.extend({}, trackCache[track]); } return _track; }); resolve(tracks) }) }); }
Added some error checking to the loading of pages and templates. Also allow passing of a function for pages that is called after the page is renders (to attach listeners)
lib/public/js/app.js
Added some error checking to the loading of pages and templates. Also allow passing of a function for pages that is called after the page is renders (to attach listeners)
<ide><path>ib/public/js/app.js <ide> currentPage = page.name; <ide> <ide> page.fn(args).then(function (data) { <del> $("main").html(page.template(data)); <del> resolve(); <add> var $page = $(page.template(data)); <add> $("main").html($page); <add> setTimeout(function () { <add> if ("function" === typeof page.after) page.after.call({}, $page); <add> resolve(); <add> }) <ide> }) <ide> $("#nav .left-nav ul li a[data-nav]").removeClass("selected") <ide> $("#nav .left-nav ul li a[data-nav='" + currentPage + "']").addClass("selected") <ide> }) <ide> } <ide> <del>function registerPage(name, fn, template) { <add>function registerPage(name, fn, template, after) { <ide> pages[name] = { <ide> name: name, <ide> fn: fn, <del> template: template <add> template: template, <add> after: after <ide> } <ide> } <ide> <ide> } <ide> <ide> function loadTemplates(cb) { <add> var loaded = false; <add> <ide> console.groupCollapsed("Loading Templates"); <ide> Handlebars.registerHelper("duration", formatDuration) <ide> Handlebars.registerHelper("timestamp", formatTimestamp) <ide> }, cb) <ide> }], function () { <ide> console.groupEnd(); <add> loaded = true; <ide> cb(); <ide> }); <ide> }); <add> <add> setTimeout(function () { <add> if (!loaded) { <add> alert("A problem occurred loading the templates. Reloading...") <add> window.location.reload(); <add> } <add> }, 8 * 1000); <ide> } <ide> <ide> function padString(value, width, padWith) { <ide> } <ide> <ide> function loadPages(cb) { <add> var loaded = false; <add> console.groupCollapsed("Loading pages"); <ide> $.getJSON("/pages.json").then(function (pages) { <ide> async.map(pages, function (name, cb) { <add> console.log("Loading page %s", name) <ide> $.getScript("/js/pages/" + name).then(function () { <add> console.log("Loaded page %s", name) <ide> setTimeout(cb); <add> }, function () { <add> doNotification("Couldn't load page " + name, {timeout: 5}) <ide> }); <del> }, cb) <add> }, function () { <add> loaded = true; <add> console.groupEnd(); <add> cb(); <add> }) <ide> }); <add> <add> setTimeout(function () { <add> if (!loaded) { <add> alert("A problem occurred loading the pages. Reloading...") <add> window.location.reload(); <add> } <add> }, 8 * 1000); <ide> } <ide> <ide> function doNotification(title, args, callback) { <ide> <ide> function getTracks(uris) { <ide> return new Promise(function (resolve, reject) { <add> if (uris.length == 0) resolve([]); //Don't do nought for an empty list... <ide> var uncachedTracks = uris.filter(function (track) { <ide> return "undefined" == typeof trackCache["string" === typeof track ? track : track.id] <ide> })
JavaScript
apache-2.0
5a8934d63adb9b5e937de7b261e666abc59528af
0
mozilla/gcli,mozilla/gcli,mozilla/gcli
/* * Copyright 2012, Mozilla Foundation and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var Promise = require('./util/promise').Promise; var util = require('./util/util'); var host = require('./util/host'); var l10n = require('./util/l10n'); var view = require('./ui/view'); var Parameter = require('./commands/commands').Parameter; var CommandOutputManager = require('./commands/commands').CommandOutputManager; var Status = require('./types/types').Status; var Conversion = require('./types/types').Conversion; var commandModule = require('./types/command'); var selectionModule = require('./types/selection'); var Argument = require('./types/types').Argument; var ArrayArgument = require('./types/types').ArrayArgument; var NamedArgument = require('./types/types').NamedArgument; var TrueNamedArgument = require('./types/types').TrueNamedArgument; var MergedArgument = require('./types/types').MergedArgument; var ScriptArgument = require('./types/types').ScriptArgument; var RESOLVED = Promise.resolve(undefined); /** * This is a list of the known command line components to enable certain * privileged commands to alter parts of a running command line. It is an array * of objects shaped like: * { conversionContext:..., executionContext:..., mapping:... } * So lookup is O(n) where 'n' is the number of command lines. */ var instances = []; /** * An indexOf that looks-up both types of context */ function instanceIndex(context) { for (var i = 0; i < instances.length; i++) { var instance = instances[i]; if (instance.conversionContext === context || instance.executionContext === context) { return i; } } return -1; } /** * findInstance gets access to a Terminal object given a conversionContext or * an executionContext (it doesn't have to be a terminal object, just whatever * was passed into addMapping() */ exports.getMapping = function(context) { var index = instanceIndex(context); if (index === -1) { console.log('Missing mapping for context: ', context); console.log('Known contexts: ', instances); throw new Error('Missing mapping for context'); } return instances[index].mapping; }; /** * Add a requisition context->terminal mapping */ var addMapping = function(requisition) { if (instanceIndex(requisition.conversionContext) !== -1) { throw new Error('Remote existing mapping before adding a new one'); } instances.push({ conversionContext: requisition.conversionContext, executionContext: requisition.executionContext, mapping: { requisition: requisition } }); }; /** * Remove a requisition context->terminal mapping */ var removeMapping = function(requisition) { var index = instanceIndex(requisition.conversionContext); instances.splice(index, 1); }; /** * Some manual intervention is needed in parsing the { command. */ function getEvalCommand(commands) { if (getEvalCommand._cmd == null) { getEvalCommand._cmd = commands.get(evalCmd.name); } return getEvalCommand._cmd; } /** * Assignment is a link between a parameter and the data for that parameter. * The data for the parameter is available as in the preferred type and as * an Argument for the CLI. * <p>We also record validity information where applicable. * <p>For values, null and undefined have distinct definitions. null means * that a value has been provided, undefined means that it has not. * Thus, null is a valid default value, and common because it identifies an * parameter that is optional. undefined means there is no value from * the command line. * @constructor */ function Assignment(param) { // The parameter that we are assigning to this.param = param; this.conversion = undefined; } /** * Easy accessor for conversion.arg. * This is a read-only property because writes to arg should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'arg', { get: function() { return this.conversion == null ? undefined : this.conversion.arg; }, enumerable: true }); /** * Easy accessor for conversion.value. * This is a read-only property because writes to value should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'value', { get: function() { return this.conversion == null ? undefined : this.conversion.value; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.message */ Object.defineProperty(Assignment.prototype, 'message', { get: function() { if (this.conversion != null && this.conversion.message) { return this.conversion.message; } // ERROR conversions have messages, VALID conversions don't need one, so // we just need to consider INCOMPLETE conversions. if (this.getStatus() === Status.INCOMPLETE) { return l10n.lookupFormat('cliIncompleteParam', [ this.param.name ]); } return ''; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.getPredictions() * @return An array of objects with name and value elements. For example: * [ { name:'bestmatch', value:foo1 }, { name:'next', value:foo2 }, ... ] */ Assignment.prototype.getPredictions = function(context) { return this.conversion == null ? [] : this.conversion.getPredictions(context); }; /** * Accessor for a prediction by index. * This is useful above <tt>getPredictions()[index]</tt> because it normalizes * index to be within the bounds of the predictions, which means that the UI * can maintain an index of which prediction to choose without caring how many * predictions there are. * @param rank The index of the prediction to choose */ Assignment.prototype.getPredictionRanked = function(context, rank) { if (rank == null) { rank = 0; } if (this.isInName()) { return Promise.resolve(undefined); } return this.getPredictions(context).then(function(predictions) { if (predictions.length === 0) { return undefined; } rank = rank % predictions.length; if (rank < 0) { rank = predictions.length + rank; } return predictions[rank]; }.bind(this)); }; /** * Some places want to take special action if we are in the name part of a * named argument (i.e. the '--foo' bit). * Currently this does not take actual cursor position into account, it just * assumes that the cursor is at the end. In the future we will probably want * to take this into account. */ Assignment.prototype.isInName = function() { return this.conversion.arg.type === 'NamedArgument' && this.conversion.arg.prefix.slice(-1) !== ' '; }; /** * Work out what the status of the current conversion is which involves looking * not only at the conversion, but also checking if data has been provided * where it should. * @param arg For assignments with multiple args (e.g. array assignments) we * can narrow the search for status to a single argument. */ Assignment.prototype.getStatus = function(arg) { if (this.param.isDataRequired && !this.conversion.isDataProvided()) { return Status.INCOMPLETE; } // Selection/Boolean types with a defined range of values will say that // '' is INCOMPLETE, but the parameter may be optional, so we don't ask // if the user doesn't need to enter something and hasn't done so. if (!this.param.isDataRequired && this.arg.type === 'BlankArgument') { return Status.VALID; } return this.conversion.getStatus(arg); }; /** * Helper when we're rebuilding command lines. */ Assignment.prototype.toString = function() { return this.conversion.toString(); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Assignment.prototype, '_summaryJson', { get: function() { return { param: this.param.name + '/' + this.param.type.name, defaultValue: this.param.defaultValue, arg: this.conversion.arg._summaryJson, value: this.value, message: this.message, status: this.getStatus().toString() }; }, enumerable: true }); exports.Assignment = Assignment; /** * How to dynamically execute JavaScript code */ var customEval = eval; /** * Setup a function to be called in place of 'eval', generally for security * reasons */ exports.setEvalFunction = function(newCustomEval) { customEval = newCustomEval; }; /** * Remove the binding done by setEvalFunction(). * We purposely set customEval to undefined rather than to 'eval' because there * is an implication of setEvalFunction that we're in a security sensitive * situation. What if we can trick GCLI into calling unsetEvalFunction() at the * wrong time? * So to properly undo the effects of setEvalFunction(), you need to call * setEvalFunction(eval) rather than unsetEvalFunction(), however the latter is * preferred in most cases. */ exports.unsetEvalFunction = function() { customEval = undefined; }; /** * 'eval' command */ var evalCmd = { item: 'command', name: '{', params: [ { name: 'javascript', type: 'javascript', description: '' } ], hidden: true, description: { key: 'cliEvalJavascript' }, exec: function(args, context) { var reply = customEval(args.javascript); return context.typedData(typeof reply, reply); }, isCommandRegexp: /^\s*{\s*/ }; exports.items = [ evalCmd ]; /** * This is a special assignment to reflect the command itself. */ function CommandAssignment(requisition) { var commandParamMetadata = { name: '__command', type: { name: 'command', allowNonExec: false } }; // This is a hack so that rather than reply with a generic description of the // command assignment, we reply with the description of the assigned command, // (using a generic term if there is no assigned command) var self = this; Object.defineProperty(commandParamMetadata, 'description', { get: function() { var value = self.value; return value && value.description ? value.description : 'The command to execute'; }, enumerable: true }); this.param = new Parameter(requisition.system.types, commandParamMetadata); } CommandAssignment.prototype = Object.create(Assignment.prototype); CommandAssignment.prototype.getStatus = function(arg) { return Status.combine( Assignment.prototype.getStatus.call(this, arg), this.conversion.value && this.conversion.value.exec ? Status.VALID : Status.INCOMPLETE ); }; exports.CommandAssignment = CommandAssignment; /** * Special assignment used when ignoring parameters that don't have a home */ function UnassignedAssignment(requisition, arg) { var isIncompleteName = (arg.text.charAt(0) === '-'); this.param = new Parameter(requisition.system.types, { name: '__unassigned', description: l10n.lookup('cliOptions'), type: { name: 'param', requisition: requisition, isIncompleteName: isIncompleteName } }); // It would be nice to do 'conversion = parm.type.parse(arg, ...)' except // that type.parse returns a promise (even though it's synchronous in this // case) if (isIncompleteName) { var lookup = commandModule.getDisplayedParamLookup(requisition); var predictions = selectionModule.findPredictions(arg, lookup); this.conversion = selectionModule.convertPredictions(arg, predictions); } else { var message = l10n.lookup('cliUnusedArg'); this.conversion = new Conversion(undefined, arg, Status.ERROR, message); } this.conversion.assignment = this; } UnassignedAssignment.prototype = Object.create(Assignment.prototype); UnassignedAssignment.prototype.getStatus = function(arg) { return this.conversion.getStatus(); }; var logErrors = true; /** * Allow tests that expect failures to avoid clogging up the console */ Object.defineProperty(exports, 'logErrors', { get: function() { return logErrors; }, set: function(val) { logErrors = val; }, enumerable: true }); /** * A Requisition collects the information needed to execute a command. * * (For a definition of the term, see http://en.wikipedia.org/wiki/Requisition) * This term is used because carries the notion of a work-flow, or process to * getting the information to execute a command correct. * There is little point in a requisition for parameter-less commands because * there is no information to collect. A Requisition is a collection of * assignments of values to parameters, each handled by an instance of * Assignment. * * @param system Allows access to the various plug-in points in GCLI. At a * minimum it must contain commands and types objects. * @param options A set of options to customize how GCLI is used. Includes: * - environment An optional opaque object passed to commands in the * Execution Context. * - document A DOM Document passed to commands using the Execution Context in * order to allow creation of DOM nodes. If missing Requisition will use the * global 'document', or leave undefined. * - commandOutputManager A custom commandOutputManager to which output should * be sent * @constructor */ function Requisition(system, options) { options = options || {}; this.environment = options.environment || {}; this.document = options.document; if (this.document == null) { try { this.document = document; } catch (ex) { // Ignore } } this.commandOutputManager = options.commandOutputManager || new CommandOutputManager(); this.system = system; this.shell = { cwd: '/', // Where we store the current working directory env: {} // Where we store the current environment }; // The command that we are about to execute. // @see setCommandConversion() this.commandAssignment = new CommandAssignment(this); // The object that stores of Assignment objects that we are filling out. // The Assignment objects are stored under their param.name for named // lookup. Note: We make use of the property of Javascript objects that // they are not just hashmaps, but linked-list hashmaps which iterate in // insertion order. // _assignments excludes the commandAssignment. this._assignments = {}; // The count of assignments. Excludes the commandAssignment this.assignmentCount = 0; // Used to store cli arguments in the order entered on the cli this._args = []; // Used to store cli arguments that were not assigned to parameters this._unassigned = []; // Changes can be asynchronous, when one update starts before another // finishes we abandon the former change this._nextUpdateId = 0; // We can set a prefix to typed commands to make it easier to focus on // Allowing us to type "add -a; commit" in place of "git add -a; git commit" this.prefix = ''; addMapping(this); this._setBlankAssignment(this.commandAssignment); // If a command calls context.update then the UI needs some way to be // informed of the change this.onExternalUpdate = util.createEvent('Requisition.onExternalUpdate'); } /** * Avoid memory leaks */ Requisition.prototype.destroy = function() { this.document = undefined; this.environment = undefined; removeMapping(this); }; /** * If we're about to make an asynchronous change when other async changes could * overtake this one, then we want to be able to bail out if overtaken. The * value passed back from beginChange should be passed to endChangeCheckOrder * on completion of calculation, before the results are applied in order to * check that the calculation has not been overtaken */ Requisition.prototype._beginChange = function() { var updateId = this._nextUpdateId; this._nextUpdateId++; return updateId; }; /** * Check to see if another change has started since updateId started. * This allows us to bail out of an update. * It's hard to make updates atomic because until you've responded to a parse * of the command argument, you don't know how to parse the arguments to that * command. */ Requisition.prototype._isChangeCurrent = function(updateId) { return updateId + 1 === this._nextUpdateId; }; /** * See notes on beginChange */ Requisition.prototype._endChangeCheckOrder = function(updateId) { if (updateId + 1 !== this._nextUpdateId) { // An update that started after we did has already finished, so our // changes are out of date. Abandon further work. return false; } return true; }; var legacy = false; /** * Functions and data related to the execution of a command */ Object.defineProperty(Requisition.prototype, 'executionContext', { get: function() { if (this._executionContext == null) { this._executionContext = { defer: function() { return Promise.defer(); }, typedData: function(type, data) { return { isTypedData: true, data: data, type: type }; }, getArgsObject: this.getArgsObject.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._executionContext, 'prefix', { get: function() { return requisition.prefix; }, enumerable: true }); Object.defineProperty(this._executionContext, 'typed', { get: function() { return requisition.toString(); }, enumerable: true }); Object.defineProperty(this._executionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); Object.defineProperty(this._executionContext, 'shell', { get: function() { return requisition.shell; }, enumerable: true }); Object.defineProperty(this._executionContext, 'system', { get: function() { return requisition.system; }, enumerable: true }); if (legacy) { this._executionContext.createView = view.createView; this._executionContext.exec = this.exec.bind(this); this._executionContext.update = this._contextUpdate.bind(this); this._executionContext.updateExec = this._contextUpdateExec.bind(this); Object.defineProperty(this._executionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); } } return this._executionContext; }, enumerable: true }); /** * Functions and data related to the conversion of the output of a command */ Object.defineProperty(Requisition.prototype, 'conversionContext', { get: function() { if (this._conversionContext == null) { this._conversionContext = { defer: function() { return Promise.defer(); }, createView: view.createView, exec: this.exec.bind(this), update: this._contextUpdate.bind(this), updateExec: this._contextUpdateExec.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._conversionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); Object.defineProperty(this._conversionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); Object.defineProperty(this._conversionContext, 'system', { get: function() { return requisition.system; }, enumerable: true }); } return this._conversionContext; }, enumerable: true }); /** * Assignments have an order, so we need to store them in an array. * But we also need named access ... * @return The found assignment, or undefined, if no match was found */ Requisition.prototype.getAssignment = function(nameOrNumber) { var name = (typeof nameOrNumber === 'string') ? nameOrNumber : Object.keys(this._assignments)[nameOrNumber]; return this._assignments[name] || undefined; }; /** * Where parameter name == assignment names - they are the same */ Requisition.prototype.getParameterNames = function() { return Object.keys(this._assignments); }; /** * The overall status is the most severe status. * There is no such thing as an INCOMPLETE overall status because the * definition of INCOMPLETE takes into account the cursor position to say 'this * isn't quite ERROR because the user can fix it by typing', however overall, * this is still an error status. */ Object.defineProperty(Requisition.prototype, 'status', { get : function() { var status = Status.VALID; if (this._unassigned.length !== 0) { var isAllIncomplete = true; this._unassigned.forEach(function(assignment) { if (!assignment.param.type.isIncompleteName) { isAllIncomplete = false; } }); status = isAllIncomplete ? Status.INCOMPLETE : Status.ERROR; } this.getAssignments(true).forEach(function(assignment) { var assignStatus = assignment.getStatus(); if (assignStatus > status) { status = assignStatus; } }, this); if (status === Status.INCOMPLETE) { status = Status.ERROR; } return status; }, enumerable : true }); /** * If ``requisition.status != VALID`` message then return a string which * best describes what is wrong. Generally error messages are delivered by * looking at the error associated with the argument at the cursor, but there * are times when you just want to say 'tell me the worst'. * If ``requisition.status != VALID`` then return ``null``. */ Requisition.prototype.getStatusMessage = function() { if (this.commandAssignment.getStatus() !== Status.VALID) { return l10n.lookup('cliUnknownCommand'); } var assignments = this.getAssignments(); for (var i = 0; i < assignments.length; i++) { if (assignments[i].getStatus() !== Status.VALID) { return assignments[i].message; } } if (this._unassigned.length !== 0) { return l10n.lookup('cliUnusedArg'); } return null; }; /** * Extract the names and values of all the assignments, and return as * an object. */ Requisition.prototype.getArgsObject = function() { var args = {}; this.getAssignments().forEach(function(assignment) { args[assignment.param.name] = assignment.conversion.isDataProvided() ? assignment.value : assignment.param.defaultValue; }, this); return args; }; /** * Access the arguments as an array. * @param includeCommand By default only the parameter arguments are * returned unless (includeCommand === true), in which case the list is * prepended with commandAssignment.arg */ Requisition.prototype.getAssignments = function(includeCommand) { var assignments = []; if (includeCommand === true) { assignments.push(this.commandAssignment); } Object.keys(this._assignments).forEach(function(name) { assignments.push(this.getAssignment(name)); }, this); return assignments; }; /** * There are a few places where we need to know what the 'next thing' is. What * is the user going to be filling out next (assuming they don't enter a named * argument). The next argument is the first in line that is both blank, and * that can be filled in positionally. * @return The next assignment to be used, or null if all the positional * parameters have values. */ Requisition.prototype._getFirstBlankPositionalAssignment = function() { var reply = null; Object.keys(this._assignments).some(function(name) { var assignment = this.getAssignment(name); if (assignment.arg.type === 'BlankArgument' && assignment.param.isPositionalAllowed) { reply = assignment; return true; // i.e. break } return false; }, this); return reply; }; /** * The update process is asynchronous, so there is (unavoidably) a window * where we've worked out the command but don't yet understand all the params. * If we try to do things to a requisition in this window we may get * inconsistent results. Asynchronous promises have made the window bigger. * The only time we've seen this in practice is during focus events due to * clicking on a shortcut. The focus want to check the cursor position while * the shortcut is updating the command line. * This function allows us to detect and back out of this problem. * We should be able to remove this function when all the state in a * requisition can be encapsulated and updated atomically. */ Requisition.prototype.isUpToDate = function() { if (!this._args) { return false; } for (var i = 0; i < this._args.length; i++) { if (this._args[i].assignment == null) { return false; } } return true; }; /** * Look through the arguments attached to our assignments for the assignment * at the given position. * @param {number} cursor The cursor position to query */ Requisition.prototype.getAssignmentAt = function(cursor) { // We short circuit this one because we may have no args, or no args with // any size and the alg below only finds arguments with size. if (cursor === 0) { return this.commandAssignment; } var assignForPos = []; var i, j; for (i = 0; i < this._args.length; i++) { var arg = this._args[i]; var assignment = arg.assignment; // prefix and text are clearly part of the argument for (j = 0; j < arg.prefix.length; j++) { assignForPos.push(assignment); } for (j = 0; j < arg.text.length; j++) { assignForPos.push(assignment); } // suffix is part of the argument only if this is a named parameter, // otherwise it looks forwards if (arg.assignment.arg.type === 'NamedArgument') { // leave the argument as it is } else if (this._args.length > i + 1) { // first to the next argument assignment = this._args[i + 1].assignment; } else { // then to the first blank positional parameter, leaving 'as is' if none var nextAssignment = this._getFirstBlankPositionalAssignment(); if (nextAssignment != null) { assignment = nextAssignment; } } for (j = 0; j < arg.suffix.length; j++) { assignForPos.push(assignment); } } // Possible shortcut, we don't really need to go through all the args // to work out the solution to this return assignForPos[cursor - 1]; }; /** * Extract a canonical version of the input * @return a promise of a string which is the canonical version of what was * typed */ Requisition.prototype.toCanonicalString = function() { var cmd = this.commandAssignment.value ? this.commandAssignment.value.name : this.commandAssignment.arg.text; // Canonically, if we've opened with a { then we should have a } to close var lineSuffix = ''; if (cmd === '{') { var scriptSuffix = this.getAssignment(0).arg.suffix; lineSuffix = (scriptSuffix.indexOf('}') === -1) ? ' }' : ''; } var ctx = this.executionContext; // First stringify all the arguments var argPromise = util.promiseEach(this.getAssignments(), function(assignment) { // Bug 664377: This will cause problems if there is a non-default value // after a default value. Also we need to decide when to use // named parameters in place of positional params. Both can wait. if (assignment.value === assignment.param.defaultValue) { return ''; } var val = assignment.param.type.stringify(assignment.value, ctx); return Promise.resolve(val).then(function(str) { return ' ' + str; }.bind(this)); }.bind(this)); return argPromise.then(function(strings) { return cmd + strings.join('') + lineSuffix; }.bind(this)); }; /** * Reconstitute the input from the args */ Requisition.prototype.toString = function() { if (!this._args) { throw new Error('toString requires a command line. See source.'); } return this._args.map(function(arg) { return arg.toString(); }).join(''); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Requisition.prototype, '_summaryJson', { get: function() { var summary = { $args: this._args.map(function(arg) { return arg._summaryJson; }), _command: this.commandAssignment._summaryJson, _unassigned: this._unassigned.forEach(function(assignment) { return assignment._summaryJson; }) }; Object.keys(this._assignments).forEach(function(name) { summary[name] = this.getAssignment(name)._summaryJson; }.bind(this)); return summary; }, enumerable: true }); /** * When any assignment changes, we might need to update the _args array to * match and inform people of changes to the typed input text. */ Requisition.prototype._setAssignmentInternal = function(assignment, conversion) { var oldConversion = assignment.conversion; assignment.conversion = conversion; assignment.conversion.assignment = assignment; // Do nothing if the conversion is unchanged if (assignment.conversion.equals(oldConversion)) { if (assignment === this.commandAssignment) { this._setBlankArguments(); } return; } // When the command changes, we need to keep a bunch of stuff in sync if (assignment === this.commandAssignment) { this._assignments = {}; var command = this.commandAssignment.value; if (command) { for (var i = 0; i < command.params.length; i++) { var param = command.params[i]; var newAssignment = new Assignment(param); this._setBlankAssignment(newAssignment); this._assignments[param.name] = newAssignment; } } this.assignmentCount = Object.keys(this._assignments).length; } }; /** * Internal function to alter the given assignment using the given arg. * @param assignment The assignment to alter * @param arg The new value for the assignment. An instance of Argument, or an * instance of Conversion, or null to set the blank value. * @param options There are a number of ways to customize how the assignment * is made, including: * - internal: (default:false) External updates are required to do more work, * including adjusting the args in this requisition to stay in sync. * On the other hand non internal changes use beginChange to back out of * changes when overtaken asynchronously. * Setting internal:true effectively means this is being called as part of * the update process. * - matchPadding: (default:false) Alter the whitespace on the prefix and * suffix of the new argument to match that of the old argument. This only * makes sense with internal=false * @return A promise that resolves to undefined when the assignment is complete */ Requisition.prototype.setAssignment = function(assignment, arg, options) { options = options || {}; if (!options.internal) { var originalArgs = assignment.arg.getArgs(); // Update the args array var replacementArgs = arg.getArgs(); var maxLen = Math.max(originalArgs.length, replacementArgs.length); for (var i = 0; i < maxLen; i++) { // If there are no more original args, or if the original arg was blank // (i.e. not typed by the user), we'll just need to add at the end if (i >= originalArgs.length || originalArgs[i].type === 'BlankArgument') { this._args.push(replacementArgs[i]); continue; } var index = this._args.indexOf(originalArgs[i]); if (index === -1) { console.error('Couldn\'t find ', originalArgs[i], ' in ', this._args); throw new Error('Couldn\'t find ' + originalArgs[i]); } // If there are no more replacement args, we just remove the original args // Otherwise swap original args and replacements if (i >= replacementArgs.length) { this._args.splice(index, 1); } else { if (options.matchPadding) { if (replacementArgs[i].prefix.length === 0 && this._args[index].prefix.length !== 0) { replacementArgs[i].prefix = this._args[index].prefix; } if (replacementArgs[i].suffix.length === 0 && this._args[index].suffix.length !== 0) { replacementArgs[i].suffix = this._args[index].suffix; } } this._args[index] = replacementArgs[i]; } } } var updateId = options.internal ? null : this._beginChange(); var setAssignmentInternal = function(conversion) { if (options.internal || this._isChangeCurrent(updateId)) { this._setAssignmentInternal(assignment, conversion); } if (!options.internal) { this._endChangeCheckOrder(updateId); } return Promise.resolve(undefined); }.bind(this); if (arg == null) { var blank = assignment.param.type.getBlank(this.executionContext); return setAssignmentInternal(blank); } if (typeof arg.getStatus === 'function') { // It's not really an arg, it's a conversion already return setAssignmentInternal(arg); } var parsed = assignment.param.type.parse(arg, this.executionContext); return parsed.then(setAssignmentInternal); }; /** * Reset an assignment to its default value. * For internal use only. * Happens synchronously. */ Requisition.prototype._setBlankAssignment = function(assignment) { var blank = assignment.param.type.getBlank(this.executionContext); this._setAssignmentInternal(assignment, blank); }; /** * Reset all the assignments to their default values. * For internal use only. * Happens synchronously. */ Requisition.prototype._setBlankArguments = function() { this.getAssignments().forEach(this._setBlankAssignment.bind(this)); }; /** * Input trace gives us an array of Argument tracing objects, one for each * character in the typed input, from which we can derive information about how * to display this typed input. It's a bit like toString on steroids. * <p> * The returned object has the following members:<ul> * <li>character: The character to which this arg trace refers. * <li>arg: The Argument to which this character is assigned. * <li>part: One of ['prefix'|'text'|suffix'] - how was this char understood * </ul> * <p> * The Argument objects are as output from tokenize() rather than as applied * to Assignments by _assign() (i.e. they are not instances of NamedArgument, * ArrayArgument, etc). * <p> * To get at the arguments applied to the assignments simply call * <tt>arg.assignment.arg</tt>. If <tt>arg.assignment.arg !== arg</tt> then * the arg applied to the assignment will contain the original arg. * See _assign() for details. */ Requisition.prototype.createInputArgTrace = function() { if (!this._args) { throw new Error('createInputMap requires a command line. See source.'); } var args = []; var i; this._args.forEach(function(arg) { for (i = 0; i < arg.prefix.length; i++) { args.push({ arg: arg, character: arg.prefix[i], part: 'prefix' }); } for (i = 0; i < arg.text.length; i++) { args.push({ arg: arg, character: arg.text[i], part: 'text' }); } for (i = 0; i < arg.suffix.length; i++) { args.push({ arg: arg, character: arg.suffix[i], part: 'suffix' }); } }); return args; }; /** * If the last character is whitespace then things that we suggest to add to * the end don't need a space prefix. * While this is quite a niche function, it has 2 benefits: * - it's more correct because we can distinguish between final whitespace that * is part of an unclosed string, and parameter separating whitespace. * - also it's faster than toString() the whole thing and checking the end char * @return true iff the last character is interpreted as parameter separating * whitespace */ Requisition.prototype.typedEndsWithSeparator = function() { if (!this._args) { throw new Error('typedEndsWithSeparator requires a command line. See source.'); } if (this._args.length === 0) { return false; } // This is not as easy as doing (this.toString().slice(-1) === ' ') // See the doc comments above; We're checking for separators, not spaces var lastArg = this._args.slice(-1)[0]; if (lastArg.suffix.slice(-1) === ' ') { return true; } return lastArg.text === '' && lastArg.suffix === '' && lastArg.prefix.slice(-1) === ' '; }; /** * Return an array of Status scores so we can create a marked up * version of the command line input. * @param cursor We only take a status of INCOMPLETE to be INCOMPLETE when the * cursor is actually in the argument. Otherwise it's an error. * @return Array of objects each containing <tt>status</tt> property and a * <tt>string</tt> property containing the characters to which the status * applies. Concatenating the strings in order gives the original input. */ Requisition.prototype.getInputStatusMarkup = function(cursor) { var argTraces = this.createInputArgTrace(); // Generally the 'argument at the cursor' is the argument before the cursor // unless it is before the first char, in which case we take the first. cursor = cursor === 0 ? 0 : cursor - 1; var cTrace = argTraces[cursor]; var markup = []; for (var i = 0; i < argTraces.length; i++) { var argTrace = argTraces[i]; var arg = argTrace.arg; var status = Status.VALID; if (argTrace.part === 'text') { status = arg.assignment.getStatus(arg); // Promote INCOMPLETE to ERROR ... if (status === Status.INCOMPLETE) { // If the cursor is in the prefix or suffix of an argument then we // don't consider it in the argument for the purposes of preventing // the escalation to ERROR. However if this is a NamedArgument, then we // allow the suffix (as space between 2 parts of the argument) to be in. // We use arg.assignment.arg not arg because we're looking at the arg // that got put into the assignment not as returned by tokenize() var isNamed = (cTrace.arg.assignment.arg.type === 'NamedArgument'); var isInside = cTrace.part === 'text' || (isNamed && cTrace.part === 'suffix'); if (arg.assignment !== cTrace.arg.assignment || !isInside) { // And if we're not in the command if (!(arg.assignment instanceof CommandAssignment)) { status = Status.ERROR; } } } } markup.push({ status: status, string: argTrace.character }); } // De-dupe: merge entries where 2 adjacent have same status i = 0; while (i < markup.length - 1) { if (markup[i].status === markup[i + 1].status) { markup[i].string += markup[i + 1].string; markup.splice(i + 1, 1); } else { i++; } } return markup; }; /** * Describe the state of the current input in a way that allows display of * predictions and completion hints * @param start The location of the cursor * @param rank The index of the chosen prediction * @return A promise of an object containing the following properties: * - statusMarkup: An array of Status scores so we can create a marked up * version of the command line input. See getInputStatusMarkup() for details * - unclosedJs: Is the entered command a JS command with no closing '}'? * - directTabText: A promise of the text that we *add* to the command line * when TAB is pressed, to be displayed directly after the cursor. See also * arrowTabText. * - emptyParameters: A promise of the text that describes the arguments that * the user is yet to type. * - arrowTabText: A promise of the text that *replaces* the current argument * when TAB is pressed, generally displayed after a "|->" symbol. See also * directTabText. */ Requisition.prototype.getStateData = function(start, rank) { var typed = this.toString(); var current = this.getAssignmentAt(start); var context = this.executionContext; var predictionPromise = (typed.trim().length !== 0) ? current.getPredictionRanked(context, rank) : Promise.resolve(null); return predictionPromise.then(function(prediction) { // directTabText is for when the current input is a prefix of the completion // arrowTabText is for when we need to use an -> to show what will be used var directTabText = ''; var arrowTabText = ''; var emptyParameters = []; if (typed.trim().length !== 0) { var cArg = current.arg; if (prediction) { var tabText = prediction.name; var existing = cArg.text; // Normally the cursor being just before whitespace means that you are // 'in' the previous argument, which means that the prediction is based // on that argument, however NamedArguments break this by having 2 parts // so we need to prepend the tabText with a space for NamedArguments, // but only when there isn't already a space at the end of the prefix // (i.e. ' --name' not ' --name ') if (current.isInName()) { tabText = ' ' + tabText; } if (existing !== tabText) { // Decide to use directTabText or arrowTabText // Strip any leading whitespace from the user inputted value because // the tabText will never have leading whitespace. var inputValue = existing.replace(/^\s*/, ''); var isStrictCompletion = tabText.indexOf(inputValue) === 0; if (isStrictCompletion && start === typed.length) { // Display the suffix of the prediction as the completion var numLeadingSpaces = existing.match(/^(\s*)/)[0].length; directTabText = tabText.slice(existing.length - numLeadingSpaces); } else { // Display the '-> prediction' at the end of the completer element // \u21E5 is the JS escape right arrow arrowTabText = '\u21E5 ' + tabText; } } } else { // There's no prediction, but if this is a named argument that needs a // value (that is without any) then we need to show that one is needed // For example 'git commit --message ', clearly needs some more text if (cArg.type === 'NamedArgument' && cArg.valueArg == null) { emptyParameters.push('<' + current.param.type.name + '>\u00a0'); } } } // Add a space between the typed text (+ directTabText) and the hints, // making sure we don't add 2 sets of padding if (directTabText !== '') { directTabText += '\u00a0'; // a.k.a &nbsp; } else if (!this.typedEndsWithSeparator()) { emptyParameters.unshift('\u00a0'); } // Calculate the list of parameters to be filled in // We generate an array of emptyParameter markers for each positional // parameter to the current command. // Generally each emptyParameter marker begins with a space to separate it // from whatever came before, unless what comes before ends in a space. this.getAssignments().forEach(function(assignment) { // Named arguments are handled with a group [options] marker if (!assignment.param.isPositionalAllowed) { return; } // No hints if we've got content for this parameter if (assignment.arg.toString().trim() !== '') { return; } // No hints if we have a prediction if (directTabText !== '' && current === assignment) { return; } var text = (assignment.param.isDataRequired) ? '<' + assignment.param.name + '>\u00a0' : '[' + assignment.param.name + ']\u00a0'; emptyParameters.push(text); }.bind(this)); var command = this.commandAssignment.value; var addOptionsMarker = false; // We add an '[options]' marker when there are named parameters that are // not filled in and not hidden, and we don't have any directTabText if (command && command.hasNamedParameters) { command.params.forEach(function(param) { var arg = this.getAssignment(param.name).arg; if (!param.isPositionalAllowed && !param.hidden && arg.type === 'BlankArgument') { addOptionsMarker = true; } }, this); } if (addOptionsMarker) { // Add an nbsp if we don't have one at the end of the input or if // this isn't the first param we've mentioned emptyParameters.push('[options]\u00a0'); } // Is the entered command a JS command with no closing '}'? var unclosedJs = command && command.name === '{' && this.getAssignment(0).arg.suffix.indexOf('}') === -1; return { statusMarkup: this.getInputStatusMarkup(start), unclosedJs: unclosedJs, directTabText: directTabText, arrowTabText: arrowTabText, emptyParameters: emptyParameters }; }.bind(this)); }; /** * Pressing TAB sometimes requires that we add a space to denote that we're on * to the 'next thing'. * @param assignment The assignment to which to append the space */ Requisition.prototype._addSpace = function(assignment) { var arg = assignment.arg.beget({ suffixSpace: true }); if (arg !== assignment.arg) { return this.setAssignment(assignment, arg); } else { return Promise.resolve(undefined); } }; /** * Complete the argument at <tt>cursor</tt>. * Basically the same as: * assignment = getAssignmentAt(cursor); * assignment.value = assignment.conversion.predictions[0]; * Except it's done safely, and with particular care to where we place the * space, which is complex, and annoying if we get it wrong. * * WARNING: complete() can happen asynchronously. * * @param cursor The cursor configuration. Should have start and end properties * which should be set to start and end of the selection. * @param rank The index of the prediction that we should choose. * This number is not bounded by the size of the prediction array, we take the * modulus to get it within bounds * @return A promise which completes (with undefined) when any outstanding * completion tasks are done. */ Requisition.prototype.complete = function(cursor, rank) { var assignment = this.getAssignmentAt(cursor.start); var context = this.executionContext; var predictionPromise = assignment.getPredictionRanked(context, rank); return predictionPromise.then(function(prediction) { var outstanding = []; // Note: Since complete is asynchronous we should perhaps have a system to // bail out of making changes if the command line has changed since TAB // was pressed. It's not yet clear if this will be a problem. if (prediction == null) { // No predictions generally means we shouldn't change anything on TAB, // but TAB has the connotation of 'next thing' and when we're at the end // of a thing that implies that we should add a space. i.e. // 'help<TAB>' -> 'help ' // But we should only do this if the thing that we're 'completing' is // valid and doesn't already end in a space. if (assignment.arg.suffix.slice(-1) !== ' ' && assignment.getStatus() === Status.VALID) { outstanding.push(this._addSpace(assignment)); } // Also add a space if we are in the name part of an assignment, however // this time we don't want the 'push the space to the next assignment' // logic, so we don't use addSpace if (assignment.isInName()) { var newArg = assignment.arg.beget({ prefixPostSpace: true }); outstanding.push(this.setAssignment(assignment, newArg)); } } else { // Mutate this argument to hold the completion var arg = assignment.arg.beget({ text: prediction.name, dontQuote: (assignment === this.commandAssignment) }); var assignPromise = this.setAssignment(assignment, arg); if (!prediction.incomplete) { assignPromise = assignPromise.then(function() { // The prediction is complete, add a space to let the user move-on return this._addSpace(assignment).then(function() { // Bug 779443 - Remove or explain the re-parse if (assignment instanceof UnassignedAssignment) { return this.update(this.toString()); } }.bind(this)); }.bind(this)); } outstanding.push(assignPromise); } return Promise.all(outstanding).then(function() { return true; }.bind(this)); }.bind(this)); }; /** * Replace the current value with the lower value if such a concept exists. */ Requisition.prototype.decrement = function(assignment) { var ctx = this.executionContext; var val = assignment.param.type.decrement(assignment.value, ctx); return Promise.resolve(val).then(function(replacement) { if (replacement != null) { var val = assignment.param.type.stringify(replacement, ctx); return Promise.resolve(val).then(function(str) { var arg = assignment.arg.beget({ text: str }); return this.setAssignment(assignment, arg); }.bind(this)); } }.bind(this)); }; /** * Replace the current value with the higher value if such a concept exists. */ Requisition.prototype.increment = function(assignment) { var ctx = this.executionContext; var val = assignment.param.type.increment(assignment.value, ctx); return Promise.resolve(val).then(function(replacement) { if (replacement != null) { var val = assignment.param.type.stringify(replacement, ctx); return Promise.resolve(val).then(function(str) { var arg = assignment.arg.beget({ text: str }); return this.setAssignment(assignment, arg); }.bind(this)); } }.bind(this)); }; /** * Helper to find the 'data-command' attribute, used by |update()| */ function getDataCommandAttribute(element) { var command = element.getAttribute('data-command'); if (!command) { command = element.querySelector('*[data-command]') .getAttribute('data-command'); } return command; } /** * Designed to be called from context.update(). Acts just like update() except * that it also calls onExternalUpdate() to inform the UI of an unexpected * change to the current command. */ Requisition.prototype._contextUpdate = function(typed) { return this.update(typed).then(function(reply) { this.onExternalUpdate({ typed: typed }); return reply; }.bind(this)); }; /** * Called by the UI when ever the user interacts with a command line input * @param typed The contents of the input field OR an HTML element (or an event * that targets an HTML element) which has a data-command attribute or a child * with the same that contains the command to update with */ Requisition.prototype.update = function(typed) { // Should be "if (typed instanceof HTMLElement)" except Gecko if (typeof typed.querySelector === 'function') { typed = getDataCommandAttribute(typed); } // Should be "if (typed instanceof Event)" except Gecko if (typeof typed.currentTarget === 'object') { typed = getDataCommandAttribute(typed.currentTarget); } var updateId = this._beginChange(); this._args = exports.tokenize(typed); var args = this._args.slice(0); // i.e. clone this._split(args); return this._assign(args).then(function() { return this._endChangeCheckOrder(updateId); }.bind(this)); }; /** * Similar to update('') except that it's guaranteed to execute synchronously */ Requisition.prototype.clear = function() { var arg = new Argument('', '', ''); this._args = [ arg ]; var conversion = commandModule.parse(this.executionContext, arg, false); this.setAssignment(this.commandAssignment, conversion, { internal: true }); }; /** * tokenize() is a state machine. These are the states. */ var In = { /** * The last character was ' '. * Typing a ' ' character will not change the mode * Typing one of '"{ will change mode to SINGLE_Q, DOUBLE_Q or SCRIPT. * Anything else goes into SIMPLE mode. */ WHITESPACE: 1, /** * The last character was part of a parameter. * Typing ' ' returns to WHITESPACE mode. Any other character * (including '"{} which are otherwise special) does not change the mode. */ SIMPLE: 2, /** * We're inside single quotes: ' * Typing ' returns to WHITESPACE mode. Other characters do not change mode. */ SINGLE_Q: 3, /** * We're inside double quotes: " * Typing " returns to WHITESPACE mode. Other characters do not change mode. */ DOUBLE_Q: 4, /** * We're inside { and } * Typing } returns to WHITESPACE mode. Other characters do not change mode. * SCRIPT mode is slightly different from other modes in that spaces between * the {/} delimiters and the actual input are not considered significant. * e.g: " x " is a 3 character string, delimited by double quotes, however * { x } is a 1 character JavaScript surrounded by whitespace and {} * delimiters. * In the short term we assume that the JS routines can make sense of the * extra whitespace, however at some stage we may need to move the space into * the Argument prefix/suffix. * Also we don't attempt to handle nested {}. See bug 678961 */ SCRIPT: 5 }; /** * Split up the input taking into account ', " and {. * We don't consider \t or other classical whitespace characters to split * arguments apart. For one thing these characters are hard to type, but also * if the user has gone to the trouble of pasting a TAB character into the * input field (or whatever it takes), they probably mean it. */ exports.tokenize = function(typed) { // For blank input, place a dummy empty argument into the list if (typed == null || typed.length === 0) { return [ new Argument('', '', '') ]; } if (isSimple(typed)) { return [ new Argument(typed, '', '') ]; } var mode = In.WHITESPACE; // First we swap out escaped characters that are special to the tokenizer. // So a backslash followed by any of ['"{} ] is turned into a unicode private // char so we can swap back later typed = typed .replace(/\\\\/g, '\uF000') .replace(/\\ /g, '\uF001') .replace(/\\'/g, '\uF002') .replace(/\\"/g, '\uF003') .replace(/\\{/g, '\uF004') .replace(/\\}/g, '\uF005'); function unescape2(escaped) { return escaped .replace(/\uF000/g, '\\\\') .replace(/\uF001/g, '\\ ') .replace(/\uF002/g, '\\\'') .replace(/\uF003/g, '\\\"') .replace(/\uF004/g, '\\{') .replace(/\uF005/g, '\\}'); } var i = 0; // The index of the current character var start = 0; // Where did this section start? var prefix = ''; // Stuff that comes before the current argument var args = []; // The array that we're creating var blockDepth = 0; // For JS with nested {} // This is just a state machine. We're going through the string char by char // The 'mode' is one of the 'In' states. As we go, we're adding Arguments // to the 'args' array. while (true) { var c = typed[i]; var str; switch (mode) { case In.WHITESPACE: if (c === '\'') { prefix = typed.substring(start, i + 1); mode = In.SINGLE_Q; start = i + 1; } else if (c === '"') { prefix = typed.substring(start, i + 1); mode = In.DOUBLE_Q; start = i + 1; } else if (c === '{') { prefix = typed.substring(start, i + 1); mode = In.SCRIPT; blockDepth++; start = i + 1; } else if (/ /.test(c)) { // Still whitespace, do nothing } else { prefix = typed.substring(start, i); mode = In.SIMPLE; start = i; } break; case In.SIMPLE: // There is an edge case of xx'xx which we are assuming to // be a single parameter (and same with ") if (c === ' ') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, '')); mode = In.WHITESPACE; start = i; prefix = ''; } break; case In.SINGLE_Q: if (c === '\'') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.DOUBLE_Q: if (c === '"') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.SCRIPT: if (c === '{') { blockDepth++; } else if (c === '}') { blockDepth--; if (blockDepth === 0) { str = unescape2(typed.substring(start, i)); args.push(new ScriptArgument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } } break; } i++; if (i >= typed.length) { // There is nothing else to read - tidy up if (mode === In.WHITESPACE) { if (i !== start) { // There's whitespace at the end of the typed string. Add it to the // last argument's suffix, creating an empty argument if needed. var extra = typed.substring(start, i); var lastArg = args[args.length - 1]; if (!lastArg) { args.push(new Argument('', extra, '')); } else { lastArg.suffix += extra; } } } else if (mode === In.SCRIPT) { str = unescape2(typed.substring(start, i + 1)); args.push(new ScriptArgument(str, prefix, '')); } else { str = unescape2(typed.substring(start, i + 1)); args.push(new Argument(str, prefix, '')); } break; } } return args; }; /** * If the input has no spaces, quotes, braces or escapes, * we can take the fast track. */ function isSimple(typed) { for (var i = 0; i < typed.length; i++) { var c = typed.charAt(i); if (c === ' ' || c === '"' || c === '\'' || c === '{' || c === '}' || c === '\\') { return false; } } return true; } /** * Looks in the commands for a command extension that matches what has been * typed at the command line. */ Requisition.prototype._split = function(args) { // Handle the special case of the user typing { javascript(); } // We use the hidden 'eval' command directly rather than shift()ing one of // the parameters, and parse()ing it. var conversion; if (args[0].type === 'ScriptArgument') { // Special case: if the user enters { console.log('foo'); } then we need to // use the hidden 'eval' command conversion = new Conversion(getEvalCommand(this.system.commands), new ScriptArgument()); this._setAssignmentInternal(this.commandAssignment, conversion); return; } var argsUsed = 1; while (argsUsed <= args.length) { var arg = (argsUsed === 1) ? args[0] : new MergedArgument(args, 0, argsUsed); if (this.prefix != null && this.prefix !== '') { var prefixArg = new Argument(this.prefix, '', ' '); var prefixedArg = new MergedArgument([ prefixArg, arg ]); conversion = commandModule.parse(this.executionContext, prefixedArg, false); if (conversion.value == null) { conversion = commandModule.parse(this.executionContext, arg, false); } } else { conversion = commandModule.parse(this.executionContext, arg, false); } // We only want to carry on if this command is a parent command, // which means that there is a commandAssignment, but not one with // an exec function. if (!conversion.value || conversion.value.exec) { break; } // Previously we needed a way to hide commands depending context. // We have not resurrected that feature yet, but if we do we should // insert code here to ignore certain commands depending on the // context/environment argsUsed++; } // This could probably be re-written to consume args as we go for (var i = 0; i < argsUsed; i++) { args.shift(); } this._setAssignmentInternal(this.commandAssignment, conversion); }; /** * Add all the passed args to the list of unassigned assignments. */ Requisition.prototype._addUnassignedArgs = function(args) { args.forEach(function(arg) { this._unassigned.push(new UnassignedAssignment(this, arg)); }.bind(this)); return RESOLVED; }; /** * Work out which arguments are applicable to which parameters. */ Requisition.prototype._assign = function(args) { // See comment in _split. Avoid multiple updates var noArgUp = { internal: true }; this._unassigned = []; if (!this.commandAssignment.value) { return this._addUnassignedArgs(args); } if (args.length === 0) { this._setBlankArguments(); return RESOLVED; } // Create an error if the command does not take parameters, but we have // been given them ... if (this.assignmentCount === 0) { return this._addUnassignedArgs(args); } // Special case: if there is only 1 parameter, and that's of type // text, then we put all the params into the first param if (this.assignmentCount === 1) { var assignment = this.getAssignment(0); if (assignment.param.type.name === 'string') { var arg = (args.length === 1) ? args[0] : new MergedArgument(args); return this.setAssignment(assignment, arg, noArgUp); } } // Positional arguments can still be specified by name, but if they are // then we need to ignore them when working them out positionally var unassignedParams = this.getParameterNames(); // We collect the arguments used in arrays here before assigning var arrayArgs = {}; // Extract all the named parameters var assignments = this.getAssignments(false); var namedDone = util.promiseEach(assignments, function(assignment) { // Loop over the arguments // Using while rather than loop because we remove args as we go var i = 0; while (i < args.length) { if (!assignment.param.isKnownAs(args[i].text)) { // Skip this parameter and handle as a positional parameter i++; continue; } var arg = args.splice(i, 1)[0]; /* jshint loopfunc:true */ unassignedParams = unassignedParams.filter(function(test) { return test !== assignment.param.name; }); // boolean parameters don't have values, default to false if (assignment.param.type.name === 'boolean') { arg = new TrueNamedArgument(arg); } else { var valueArg = null; if (i + 1 <= args.length) { valueArg = args.splice(i, 1)[0]; } arg = new NamedArgument(arg, valueArg); } if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArgument(arg); return RESOLVED; } else { if (assignment.arg.type === 'BlankArgument') { return this.setAssignment(assignment, arg, noArgUp); } else { return this._addUnassignedArgs(arg.getArgs()); } } } }, this); // What's left are positional parameters: assign in order var positionalDone = namedDone.then(function() { return util.promiseEach(unassignedParams, function(name) { var assignment = this.getAssignment(name); // If not set positionally, and we can't set it non-positionally, // we have to default it to prevent previous values surviving if (!assignment.param.isPositionalAllowed) { this._setBlankAssignment(assignment); return RESOLVED; } // If this is a positional array argument, then it swallows the // rest of the arguments. if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArguments(args); args = []; // The actual assignment to the array parameter is done below return RESOLVED; } // Set assignment to defaults if there are no more arguments if (args.length === 0) { this._setBlankAssignment(assignment); return RESOLVED; } var arg = args.splice(0, 1)[0]; // --foo and -f are named parameters, -4 is a number. So '-' is either // the start of a named parameter or a number depending on the context var isIncompleteName = assignment.param.type.name === 'number' ? /-[-a-zA-Z_]/.test(arg.text) : arg.text.charAt(0) === '-'; if (isIncompleteName) { this._unassigned.push(new UnassignedAssignment(this, arg)); return RESOLVED; } else { return this.setAssignment(assignment, arg, noArgUp); } }, this); }.bind(this)); // Now we need to assign the array argument (if any) var arrayDone = positionalDone.then(function() { return util.promiseEach(Object.keys(arrayArgs), function(name) { var assignment = this.getAssignment(name); return this.setAssignment(assignment, arrayArgs[name], noArgUp); }, this); }.bind(this)); // What's left is can't be assigned, but we need to officially unassign them return arrayDone.then(function() { return this._addUnassignedArgs(args); }.bind(this)); }; /** * Entry point for keyboard accelerators or anything else that wants to execute * a command. * @param options Object describing how the execution should be handled. * (optional). Contains some of the following properties: * - hidden (boolean, default=false) Should the output be hidden from the * commandOutputManager for this requisition * - command/args A fast shortcut to executing a known command with a known * set of parsed arguments. */ Requisition.prototype.exec = function(options) { var command = null; var args = null; var hidden = false; if (options) { if (options.hidden) { hidden = true; } if (options.command != null) { // Fast track by looking up the command directly since passed args // means there is no command line to parse. command = this.system.commands.get(options.command); if (!command) { console.error('Command not found: ' + options.command); } args = options.args; } } if (!command) { command = this.commandAssignment.value; args = this.getArgsObject(); } // Display JavaScript input without the initial { or closing } var typed = this.toString(); if (evalCmd.isCommandRegexp.test(typed)) { typed = typed.replace(evalCmd.isCommandRegexp, ''); // Bug 717763: What if the JavaScript naturally ends with a }? typed = typed.replace(/\s*}\s*$/, ''); } var output = new Output(this.conversionContext, { command: command, args: args, typed: typed, canonical: this.toCanonicalString(), hidden: hidden }); this.commandOutputManager.onOutput({ output: output }); var onDone = function(data) { output.complete(data, false); return output; }; var onError = function(data, ex) { if (logErrors) { if (ex != null) { util.errorHandler(ex); } else { console.error(data); } } if (data != null && typeof data === 'string') { data = data.replace(/^Protocol error: /, ''); // Temp fix for bug 1035296 } data = (data != null && data.isTypedData) ? data : { isTypedData: true, data: data, type: 'error' }; output.complete(data, true); return output; }; if (this.status !== Status.VALID) { var ex = new Error(this.getStatusMessage()); // We only reject a call to exec if GCLI breaks. Errors with commands are // exposed in the 'error' status of the Output object return Promise.resolve(onError(ex)).then(function(output) { this.clear(); return output; }.bind(this)); } else { try { return host.exec(function() { return command.exec(args, this.executionContext); }.bind(this)).then(onDone, onError); } catch (ex) { var data = (typeof ex.message === 'string' && ex.stack != null) ? ex.message : ex; return Promise.resolve(onError(data, ex)); } finally { this.clear(); } } }; /** * Designed to be called from context.updateExec(). Acts just like updateExec() * except that it also calls onExternalUpdate() to inform the UI of an * unexpected change to the current command. */ Requisition.prototype._contextUpdateExec = function(typed, options) { return this.updateExec(typed, options).then(function(reply) { this.onExternalUpdate({ typed: typed }); return reply; }.bind(this)); }; /** * A shortcut for calling update, resolving the promise and then exec. * @param input The string to execute * @param options Passed to exec * @return A promise of an output object */ Requisition.prototype.updateExec = function(input, options) { return this.update(input).then(function() { return this.exec(options); }.bind(this)); }; exports.Requisition = Requisition; /** * A simple object to hold information about the output of a command */ function Output(context, options) { options = options || {}; this.command = options.command || ''; this.args = options.args || {}; this.typed = options.typed || ''; this.canonical = options.canonical || ''; this.hidden = options.hidden === true ? true : false; this.converters = context.system.converters; this.type = undefined; this.data = undefined; this.completed = false; this.error = false; this.start = new Date(); this.promise = new Promise(function(resolve, reject) { this._resolve = resolve; }.bind(this)); } /** * Called when there is data to display, and the command has finished executing * See changed() for details on parameters. */ Output.prototype.complete = function(data, error) { this.end = new Date(); this.completed = true; this.error = error; if (data != null && data.isTypedData) { this.data = data.data; this.type = data.type; } else { this.data = data; this.type = this.command.returnType; if (this.type == null) { this.type = (this.data == null) ? 'undefined' : typeof this.data; } } if (this.type === 'object') { throw new Error('No type from output of ' + this.typed); } this._resolve(); }; /** * Call converters.convert using the data in this Output object */ Output.prototype.convert = function(type, conversionContext) { return this.converters.convert(this.data, this.type, type, conversionContext); }; Output.prototype.toJson = function() { return { typed: this.typed, type: this.type, data: this.data, error: this.error }; }; exports.Output = Output;
lib/gcli/cli.js
/* * Copyright 2012, Mozilla Foundation and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var Promise = require('./util/promise').Promise; var util = require('./util/util'); var host = require('./util/host'); var l10n = require('./util/l10n'); var view = require('./ui/view'); var Parameter = require('./commands/commands').Parameter; var CommandOutputManager = require('./commands/commands').CommandOutputManager; var Status = require('./types/types').Status; var Conversion = require('./types/types').Conversion; var commandModule = require('./types/command'); var selectionModule = require('./types/selection'); var Argument = require('./types/types').Argument; var ArrayArgument = require('./types/types').ArrayArgument; var NamedArgument = require('./types/types').NamedArgument; var TrueNamedArgument = require('./types/types').TrueNamedArgument; var MergedArgument = require('./types/types').MergedArgument; var ScriptArgument = require('./types/types').ScriptArgument; var RESOLVED = Promise.resolve(undefined); /** * This is a list of the known command line components to enable certain * privileged commands to alter parts of a running command line. It is an array * of objects shaped like: * { conversionContext:..., executionContext:..., mapping:... } * So lookup is O(n) where 'n' is the number of command lines. */ var instances = []; /** * An indexOf that looks-up both types of context */ function instanceIndex(context) { for (var i = 0; i < instances.length; i++) { var instance = instances[i]; if (instance.conversionContext === context || instance.executionContext === context) { return i; } } return -1; } /** * findInstance gets access to a Terminal object given a conversionContext or * an executionContext (it doesn't have to be a terminal object, just whatever * was passed into addMapping() */ exports.getMapping = function(context) { var index = instanceIndex(context); if (index === -1) { console.log('Missing mapping for context: ', context); console.log('Known contexts: ', instances); throw new Error('Missing mapping for context'); } return instances[index].mapping; }; /** * Add a requisition context->terminal mapping */ var addMapping = function(requisition) { if (instanceIndex(requisition.conversionContext) !== -1) { throw new Error('Remote existing mapping before adding a new one'); } instances.push({ conversionContext: requisition.conversionContext, executionContext: requisition.executionContext, mapping: { requisition: requisition } }); }; /** * Remove a requisition context->terminal mapping */ var removeMapping = function(requisition) { var index = instanceIndex(requisition.conversionContext); instances.splice(index, 1); }; /** * Some manual intervention is needed in parsing the { command. */ function getEvalCommand(commands) { if (getEvalCommand._cmd == null) { getEvalCommand._cmd = commands.get(evalCmd.name); } return getEvalCommand._cmd; } /** * Assignment is a link between a parameter and the data for that parameter. * The data for the parameter is available as in the preferred type and as * an Argument for the CLI. * <p>We also record validity information where applicable. * <p>For values, null and undefined have distinct definitions. null means * that a value has been provided, undefined means that it has not. * Thus, null is a valid default value, and common because it identifies an * parameter that is optional. undefined means there is no value from * the command line. * @constructor */ function Assignment(param) { // The parameter that we are assigning to this.param = param; this.conversion = undefined; } /** * Easy accessor for conversion.arg. * This is a read-only property because writes to arg should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'arg', { get: function() { return this.conversion == null ? undefined : this.conversion.arg; }, enumerable: true }); /** * Easy accessor for conversion.value. * This is a read-only property because writes to value should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'value', { get: function() { return this.conversion == null ? undefined : this.conversion.value; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.message */ Object.defineProperty(Assignment.prototype, 'message', { get: function() { if (this.conversion != null && this.conversion.message) { return this.conversion.message; } // ERROR conversions have messages, VALID conversions don't need one, so // we just need to consider INCOMPLETE conversions. if (this.getStatus() === Status.INCOMPLETE) { return l10n.lookupFormat('cliIncompleteParam', [ this.param.name ]); } return ''; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.getPredictions() * @return An array of objects with name and value elements. For example: * [ { name:'bestmatch', value:foo1 }, { name:'next', value:foo2 }, ... ] */ Assignment.prototype.getPredictions = function(context) { return this.conversion == null ? [] : this.conversion.getPredictions(context); }; /** * Accessor for a prediction by index. * This is useful above <tt>getPredictions()[index]</tt> because it normalizes * index to be within the bounds of the predictions, which means that the UI * can maintain an index of which prediction to choose without caring how many * predictions there are. * @param rank The index of the prediction to choose */ Assignment.prototype.getPredictionRanked = function(context, rank) { if (rank == null) { rank = 0; } if (this.isInName()) { return Promise.resolve(undefined); } return this.getPredictions(context).then(function(predictions) { if (predictions.length === 0) { return undefined; } rank = rank % predictions.length; if (rank < 0) { rank = predictions.length + rank; } return predictions[rank]; }.bind(this)); }; /** * Some places want to take special action if we are in the name part of a * named argument (i.e. the '--foo' bit). * Currently this does not take actual cursor position into account, it just * assumes that the cursor is at the end. In the future we will probably want * to take this into account. */ Assignment.prototype.isInName = function() { return this.conversion.arg.type === 'NamedArgument' && this.conversion.arg.prefix.slice(-1) !== ' '; }; /** * Work out what the status of the current conversion is which involves looking * not only at the conversion, but also checking if data has been provided * where it should. * @param arg For assignments with multiple args (e.g. array assignments) we * can narrow the search for status to a single argument. */ Assignment.prototype.getStatus = function(arg) { if (this.param.isDataRequired && !this.conversion.isDataProvided()) { return Status.INCOMPLETE; } // Selection/Boolean types with a defined range of values will say that // '' is INCOMPLETE, but the parameter may be optional, so we don't ask // if the user doesn't need to enter something and hasn't done so. if (!this.param.isDataRequired && this.arg.type === 'BlankArgument') { return Status.VALID; } return this.conversion.getStatus(arg); }; /** * Helper when we're rebuilding command lines. */ Assignment.prototype.toString = function() { return this.conversion.toString(); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Assignment.prototype, '_summaryJson', { get: function() { return { param: this.param.name + '/' + this.param.type.name, defaultValue: this.param.defaultValue, arg: this.conversion.arg._summaryJson, value: this.value, message: this.message, status: this.getStatus().toString() }; }, enumerable: true }); exports.Assignment = Assignment; /** * How to dynamically execute JavaScript code */ var customEval = eval; /** * Setup a function to be called in place of 'eval', generally for security * reasons */ exports.setEvalFunction = function(newCustomEval) { customEval = newCustomEval; }; /** * Remove the binding done by setEvalFunction(). * We purposely set customEval to undefined rather than to 'eval' because there * is an implication of setEvalFunction that we're in a security sensitive * situation. What if we can trick GCLI into calling unsetEvalFunction() at the * wrong time? * So to properly undo the effects of setEvalFunction(), you need to call * setEvalFunction(eval) rather than unsetEvalFunction(), however the latter is * preferred in most cases. */ exports.unsetEvalFunction = function() { customEval = undefined; }; /** * 'eval' command */ var evalCmd = { item: 'command', name: '{', params: [ { name: 'javascript', type: 'javascript', description: '' } ], hidden: true, description: { key: 'cliEvalJavascript' }, exec: function(args, context) { var reply = customEval(args.javascript); return context.typedData(typeof reply, reply); }, isCommandRegexp: /^\s*{\s*/ }; exports.items = [ evalCmd ]; /** * This is a special assignment to reflect the command itself. */ function CommandAssignment(requisition) { var commandParamMetadata = { name: '__command', type: { name: 'command', allowNonExec: false } }; // This is a hack so that rather than reply with a generic description of the // command assignment, we reply with the description of the assigned command, // (using a generic term if there is no assigned command) var self = this; Object.defineProperty(commandParamMetadata, 'description', { get: function() { var value = self.value; return value && value.description ? value.description : 'The command to execute'; }, enumerable: true }); this.param = new Parameter(requisition.system.types, commandParamMetadata); } CommandAssignment.prototype = Object.create(Assignment.prototype); CommandAssignment.prototype.getStatus = function(arg) { return Status.combine( Assignment.prototype.getStatus.call(this, arg), this.conversion.value && this.conversion.value.exec ? Status.VALID : Status.INCOMPLETE ); }; exports.CommandAssignment = CommandAssignment; /** * Special assignment used when ignoring parameters that don't have a home */ function UnassignedAssignment(requisition, arg) { var isIncompleteName = (arg.text.charAt(0) === '-'); this.param = new Parameter(requisition.system.types, { name: '__unassigned', description: l10n.lookup('cliOptions'), type: { name: 'param', requisition: requisition, isIncompleteName: isIncompleteName } }); // It would be nice to do 'conversion = parm.type.parse(arg, ...)' except // that type.parse returns a promise (even though it's synchronous in this // case) if (isIncompleteName) { var lookup = commandModule.getDisplayedParamLookup(requisition); var predictions = selectionModule.findPredictions(arg, lookup); this.conversion = selectionModule.convertPredictions(arg, predictions); } else { var message = l10n.lookup('cliUnusedArg'); this.conversion = new Conversion(undefined, arg, Status.ERROR, message); } this.conversion.assignment = this; } UnassignedAssignment.prototype = Object.create(Assignment.prototype); UnassignedAssignment.prototype.getStatus = function(arg) { return this.conversion.getStatus(); }; var logErrors = true; /** * Allow tests that expect failures to avoid clogging up the console */ Object.defineProperty(exports, 'logErrors', { get: function() { return logErrors; }, set: function(val) { logErrors = val; }, enumerable: true }); /** * A Requisition collects the information needed to execute a command. * * (For a definition of the term, see http://en.wikipedia.org/wiki/Requisition) * This term is used because carries the notion of a work-flow, or process to * getting the information to execute a command correct. * There is little point in a requisition for parameter-less commands because * there is no information to collect. A Requisition is a collection of * assignments of values to parameters, each handled by an instance of * Assignment. * * @param system Allows access to the various plug-in points in GCLI. At a * minimum it must contain commands and types objects. * @param options A set of options to customize how GCLI is used. Includes: * - environment An optional opaque object passed to commands in the * Execution Context. * - document A DOM Document passed to commands using the Execution Context in * order to allow creation of DOM nodes. If missing Requisition will use the * global 'document', or leave undefined. * - commandOutputManager A custom commandOutputManager to which output should * be sent * @constructor */ function Requisition(system, options) { options = options || {}; this.environment = options.environment || {}; this.document = options.document; if (this.document == null) { try { this.document = document; } catch (ex) { // Ignore } } this.commandOutputManager = options.commandOutputManager || new CommandOutputManager(); this.system = system; this.shell = { cwd: '/', // Where we store the current working directory env: {} // Where we store the current environment }; // The command that we are about to execute. // @see setCommandConversion() this.commandAssignment = new CommandAssignment(this); // The object that stores of Assignment objects that we are filling out. // The Assignment objects are stored under their param.name for named // lookup. Note: We make use of the property of Javascript objects that // they are not just hashmaps, but linked-list hashmaps which iterate in // insertion order. // _assignments excludes the commandAssignment. this._assignments = {}; // The count of assignments. Excludes the commandAssignment this.assignmentCount = 0; // Used to store cli arguments in the order entered on the cli this._args = []; // Used to store cli arguments that were not assigned to parameters this._unassigned = []; // Changes can be asynchronous, when one update starts before another // finishes we abandon the former change this._nextUpdateId = 0; // We can set a prefix to typed commands to make it easier to focus on // Allowing us to type "add -a; commit" in place of "git add -a; git commit" this.prefix = ''; addMapping(this); this._setBlankAssignment(this.commandAssignment); // If a command calls context.update then the UI needs some way to be // informed of the change this.onExternalUpdate = util.createEvent('Requisition.onExternalUpdate'); } /** * Avoid memory leaks */ Requisition.prototype.destroy = function() { this.document = undefined; this.environment = undefined; removeMapping(this); }; /** * If we're about to make an asynchronous change when other async changes could * overtake this one, then we want to be able to bail out if overtaken. The * value passed back from beginChange should be passed to endChangeCheckOrder * on completion of calculation, before the results are applied in order to * check that the calculation has not been overtaken */ Requisition.prototype._beginChange = function() { var updateId = this._nextUpdateId; this._nextUpdateId++; return updateId; }; /** * Check to see if another change has started since updateId started. * This allows us to bail out of an update. * It's hard to make updates atomic because until you've responded to a parse * of the command argument, you don't know how to parse the arguments to that * command. */ Requisition.prototype._isChangeCurrent = function(updateId) { return updateId + 1 === this._nextUpdateId; }; /** * See notes on beginChange */ Requisition.prototype._endChangeCheckOrder = function(updateId) { if (updateId + 1 !== this._nextUpdateId) { // An update that started after we did has already finished, so our // changes are out of date. Abandon further work. return false; } return true; }; var legacy = false; /** * Functions and data related to the execution of a command */ Object.defineProperty(Requisition.prototype, 'executionContext', { get: function() { if (this._executionContext == null) { this._executionContext = { defer: function() { return Promise.defer(); }, typedData: function(type, data) { return { isTypedData: true, data: data, type: type }; }, getArgsObject: this.getArgsObject.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._executionContext, 'prefix', { get: function() { return requisition.prefix; }, enumerable: true }); Object.defineProperty(this._executionContext, 'typed', { get: function() { return requisition.toString(); }, enumerable: true }); Object.defineProperty(this._executionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); Object.defineProperty(this._executionContext, 'shell', { get: function() { return requisition.shell; }, enumerable: true }); Object.defineProperty(this._executionContext, 'system', { get: function() { return requisition.system; }, enumerable: true }); if (legacy) { this._executionContext.createView = view.createView; this._executionContext.exec = this.exec.bind(this); this._executionContext.update = this._contextUpdate.bind(this); this._executionContext.updateExec = this._contextUpdateExec.bind(this); Object.defineProperty(this._executionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); } } return this._executionContext; }, enumerable: true }); /** * Functions and data related to the conversion of the output of a command */ Object.defineProperty(Requisition.prototype, 'conversionContext', { get: function() { if (this._conversionContext == null) { this._conversionContext = { defer: function() { return Promise.defer(); }, createView: view.createView, exec: this.exec.bind(this), update: this._contextUpdate.bind(this), updateExec: this._contextUpdateExec.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._conversionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); Object.defineProperty(this._conversionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); Object.defineProperty(this._conversionContext, 'system', { get: function() { return requisition.system; }, enumerable: true }); } return this._conversionContext; }, enumerable: true }); /** * Assignments have an order, so we need to store them in an array. * But we also need named access ... * @return The found assignment, or undefined, if no match was found */ Requisition.prototype.getAssignment = function(nameOrNumber) { var name = (typeof nameOrNumber === 'string') ? nameOrNumber : Object.keys(this._assignments)[nameOrNumber]; return this._assignments[name] || undefined; }; /** * Where parameter name == assignment names - they are the same */ Requisition.prototype.getParameterNames = function() { return Object.keys(this._assignments); }; /** * The overall status is the most severe status. * There is no such thing as an INCOMPLETE overall status because the * definition of INCOMPLETE takes into account the cursor position to say 'this * isn't quite ERROR because the user can fix it by typing', however overall, * this is still an error status. */ Object.defineProperty(Requisition.prototype, 'status', { get : function() { var status = Status.VALID; if (this._unassigned.length !== 0) { var isAllIncomplete = true; this._unassigned.forEach(function(assignment) { if (!assignment.param.type.isIncompleteName) { isAllIncomplete = false; } }); status = isAllIncomplete ? Status.INCOMPLETE : Status.ERROR; } this.getAssignments(true).forEach(function(assignment) { var assignStatus = assignment.getStatus(); if (assignStatus > status) { status = assignStatus; } }, this); if (status === Status.INCOMPLETE) { status = Status.ERROR; } return status; }, enumerable : true }); /** * If ``requisition.status != VALID`` message then return a string which * best describes what is wrong. Generally error messages are delivered by * looking at the error associated with the argument at the cursor, but there * are times when you just want to say 'tell me the worst'. * If ``requisition.status != VALID`` then return ``null``. */ Requisition.prototype.getStatusMessage = function() { if (this.commandAssignment.getStatus() !== Status.VALID) { return l10n.lookup('cliUnknownCommand'); } var assignments = this.getAssignments(); for (var i = 0; i < assignments.length; i++) { if (assignments[i].getStatus() !== Status.VALID) { return assignments[i].message; } } if (this._unassigned.length !== 0) { return l10n.lookup('cliUnusedArg'); } return null; }; /** * Extract the names and values of all the assignments, and return as * an object. */ Requisition.prototype.getArgsObject = function() { var args = {}; this.getAssignments().forEach(function(assignment) { args[assignment.param.name] = assignment.conversion.isDataProvided() ? assignment.value : assignment.param.defaultValue; }, this); return args; }; /** * Access the arguments as an array. * @param includeCommand By default only the parameter arguments are * returned unless (includeCommand === true), in which case the list is * prepended with commandAssignment.arg */ Requisition.prototype.getAssignments = function(includeCommand) { var assignments = []; if (includeCommand === true) { assignments.push(this.commandAssignment); } Object.keys(this._assignments).forEach(function(name) { assignments.push(this.getAssignment(name)); }, this); return assignments; }; /** * There are a few places where we need to know what the 'next thing' is. What * is the user going to be filling out next (assuming they don't enter a named * argument). The next argument is the first in line that is both blank, and * that can be filled in positionally. * @return The next assignment to be used, or null if all the positional * parameters have values. */ Requisition.prototype._getFirstBlankPositionalAssignment = function() { var reply = null; Object.keys(this._assignments).some(function(name) { var assignment = this.getAssignment(name); if (assignment.arg.type === 'BlankArgument' && assignment.param.isPositionalAllowed) { reply = assignment; return true; // i.e. break } return false; }, this); return reply; }; /** * The update process is asynchronous, so there is (unavoidably) a window * where we've worked out the command but don't yet understand all the params. * If we try to do things to a requisition in this window we may get * inconsistent results. Asynchronous promises have made the window bigger. * The only time we've seen this in practice is during focus events due to * clicking on a shortcut. The focus want to check the cursor position while * the shortcut is updating the command line. * This function allows us to detect and back out of this problem. * We should be able to remove this function when all the state in a * requisition can be encapsulated and updated atomically. */ Requisition.prototype.isUpToDate = function() { if (!this._args) { return false; } for (var i = 0; i < this._args.length; i++) { if (this._args[i].assignment == null) { return false; } } return true; }; /** * Look through the arguments attached to our assignments for the assignment * at the given position. * @param {number} cursor The cursor position to query */ Requisition.prototype.getAssignmentAt = function(cursor) { // We short circuit this one because we may have no args, or no args with // any size and the alg below only finds arguments with size. if (cursor === 0) { return this.commandAssignment; } var assignForPos = []; var i, j; for (i = 0; i < this._args.length; i++) { var arg = this._args[i]; var assignment = arg.assignment; // prefix and text are clearly part of the argument for (j = 0; j < arg.prefix.length; j++) { assignForPos.push(assignment); } for (j = 0; j < arg.text.length; j++) { assignForPos.push(assignment); } // suffix is part of the argument only if this is a named parameter, // otherwise it looks forwards if (arg.assignment.arg.type === 'NamedArgument') { // leave the argument as it is } else if (this._args.length > i + 1) { // first to the next argument assignment = this._args[i + 1].assignment; } else { // then to the first blank positional parameter, leaving 'as is' if none var nextAssignment = this._getFirstBlankPositionalAssignment(); if (nextAssignment != null) { assignment = nextAssignment; } } for (j = 0; j < arg.suffix.length; j++) { assignForPos.push(assignment); } } // Possible shortcut, we don't really need to go through all the args // to work out the solution to this return assignForPos[cursor - 1]; }; /** * Extract a canonical version of the input * @return a promise of a string which is the canonical version of what was * typed */ Requisition.prototype.toCanonicalString = function() { var cmd = this.commandAssignment.value ? this.commandAssignment.value.name : this.commandAssignment.arg.text; // Canonically, if we've opened with a { then we should have a } to close var lineSuffix = ''; if (cmd === '{') { var scriptSuffix = this.getAssignment(0).arg.suffix; lineSuffix = (scriptSuffix.indexOf('}') === -1) ? ' }' : ''; } var ctx = this.executionContext; // First stringify all the arguments var argPromise = util.promiseEach(this.getAssignments(), function(assignment) { // Bug 664377: This will cause problems if there is a non-default value // after a default value. Also we need to decide when to use // named parameters in place of positional params. Both can wait. if (assignment.value === assignment.param.defaultValue) { return ''; } var val = assignment.param.type.stringify(assignment.value, ctx); return Promise.resolve(val).then(function(str) { return ' ' + str; }.bind(this)); }.bind(this)); return argPromise.then(function(strings) { return cmd + strings.join('') + lineSuffix; }.bind(this)); }; /** * Reconstitute the input from the args */ Requisition.prototype.toString = function() { if (!this._args) { throw new Error('toString requires a command line. See source.'); } return this._args.map(function(arg) { return arg.toString(); }).join(''); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Requisition.prototype, '_summaryJson', { get: function() { var summary = { $args: this._args.map(function(arg) { return arg._summaryJson; }), _command: this.commandAssignment._summaryJson, _unassigned: this._unassigned.forEach(function(assignment) { return assignment._summaryJson; }) }; Object.keys(this._assignments).forEach(function(name) { summary[name] = this.getAssignment(name)._summaryJson; }.bind(this)); return summary; }, enumerable: true }); /** * When any assignment changes, we might need to update the _args array to * match and inform people of changes to the typed input text. */ Requisition.prototype._setAssignmentInternal = function(assignment, conversion) { var oldConversion = assignment.conversion; assignment.conversion = conversion; assignment.conversion.assignment = assignment; // Do nothing if the conversion is unchanged if (assignment.conversion.equals(oldConversion)) { if (assignment === this.commandAssignment) { this._setBlankArguments(); } return; } // When the command changes, we need to keep a bunch of stuff in sync if (assignment === this.commandAssignment) { this._assignments = {}; var command = this.commandAssignment.value; if (command) { for (var i = 0; i < command.params.length; i++) { var param = command.params[i]; var newAssignment = new Assignment(param); this._setBlankAssignment(newAssignment); this._assignments[param.name] = newAssignment; } } this.assignmentCount = Object.keys(this._assignments).length; } }; /** * Internal function to alter the given assignment using the given arg. * @param assignment The assignment to alter * @param arg The new value for the assignment. An instance of Argument, or an * instance of Conversion, or null to set the blank value. * @param options There are a number of ways to customize how the assignment * is made, including: * - internal: (default:false) External updates are required to do more work, * including adjusting the args in this requisition to stay in sync. * On the other hand non internal changes use beginChange to back out of * changes when overtaken asynchronously. * Setting internal:true effectively means this is being called as part of * the update process. * - matchPadding: (default:false) Alter the whitespace on the prefix and * suffix of the new argument to match that of the old argument. This only * makes sense with internal=false * @return A promise that resolves to undefined when the assignment is complete */ Requisition.prototype.setAssignment = function(assignment, arg, options) { options = options || {}; if (!options.internal) { var originalArgs = assignment.arg.getArgs(); // Update the args array var replacementArgs = arg.getArgs(); var maxLen = Math.max(originalArgs.length, replacementArgs.length); for (var i = 0; i < maxLen; i++) { // If there are no more original args, or if the original arg was blank // (i.e. not typed by the user), we'll just need to add at the end if (i >= originalArgs.length || originalArgs[i].type === 'BlankArgument') { this._args.push(replacementArgs[i]); continue; } var index = this._args.indexOf(originalArgs[i]); if (index === -1) { console.error('Couldn\'t find ', originalArgs[i], ' in ', this._args); throw new Error('Couldn\'t find ' + originalArgs[i]); } // If there are no more replacement args, we just remove the original args // Otherwise swap original args and replacements if (i >= replacementArgs.length) { this._args.splice(index, 1); } else { if (options.matchPadding) { if (replacementArgs[i].prefix.length === 0 && this._args[index].prefix.length !== 0) { replacementArgs[i].prefix = this._args[index].prefix; } if (replacementArgs[i].suffix.length === 0 && this._args[index].suffix.length !== 0) { replacementArgs[i].suffix = this._args[index].suffix; } } this._args[index] = replacementArgs[i]; } } } var updateId = options.internal ? null : this._beginChange(); var setAssignmentInternal = function(conversion) { if (options.internal || this._isChangeCurrent(updateId)) { this._setAssignmentInternal(assignment, conversion); } if (!options.internal) { this._endChangeCheckOrder(updateId); } return Promise.resolve(undefined); }.bind(this); if (arg == null) { var blank = assignment.param.type.getBlank(this.executionContext); return setAssignmentInternal(blank); } if (typeof arg.getStatus === 'function') { // It's not really an arg, it's a conversion already return setAssignmentInternal(arg); } var parsed = assignment.param.type.parse(arg, this.executionContext); return parsed.then(setAssignmentInternal); }; /** * Reset an assignment to its default value. * For internal use only. * Happens synchronously. */ Requisition.prototype._setBlankAssignment = function(assignment) { var blank = assignment.param.type.getBlank(this.executionContext); this._setAssignmentInternal(assignment, blank); }; /** * Reset all the assignments to their default values. * For internal use only. * Happens synchronously. */ Requisition.prototype._setBlankArguments = function() { this.getAssignments().forEach(this._setBlankAssignment.bind(this)); }; /** * Input trace gives us an array of Argument tracing objects, one for each * character in the typed input, from which we can derive information about how * to display this typed input. It's a bit like toString on steroids. * <p> * The returned object has the following members:<ul> * <li>character: The character to which this arg trace refers. * <li>arg: The Argument to which this character is assigned. * <li>part: One of ['prefix'|'text'|suffix'] - how was this char understood * </ul> * <p> * The Argument objects are as output from tokenize() rather than as applied * to Assignments by _assign() (i.e. they are not instances of NamedArgument, * ArrayArgument, etc). * <p> * To get at the arguments applied to the assignments simply call * <tt>arg.assignment.arg</tt>. If <tt>arg.assignment.arg !== arg</tt> then * the arg applied to the assignment will contain the original arg. * See _assign() for details. */ Requisition.prototype.createInputArgTrace = function() { if (!this._args) { throw new Error('createInputMap requires a command line. See source.'); } var args = []; var i; this._args.forEach(function(arg) { for (i = 0; i < arg.prefix.length; i++) { args.push({ arg: arg, character: arg.prefix[i], part: 'prefix' }); } for (i = 0; i < arg.text.length; i++) { args.push({ arg: arg, character: arg.text[i], part: 'text' }); } for (i = 0; i < arg.suffix.length; i++) { args.push({ arg: arg, character: arg.suffix[i], part: 'suffix' }); } }); return args; }; /** * If the last character is whitespace then things that we suggest to add to * the end don't need a space prefix. * While this is quite a niche function, it has 2 benefits: * - it's more correct because we can distinguish between final whitespace that * is part of an unclosed string, and parameter separating whitespace. * - also it's faster than toString() the whole thing and checking the end char * @return true iff the last character is interpreted as parameter separating * whitespace */ Requisition.prototype.typedEndsWithSeparator = function() { if (!this._args) { throw new Error('typedEndsWithSeparator requires a command line. See source.'); } if (this._args.length === 0) { return false; } // This is not as easy as doing (this.toString().slice(-1) === ' ') // See the doc comments above; We're checking for separators, not spaces var lastArg = this._args.slice(-1)[0]; if (lastArg.suffix.slice(-1) === ' ') { return true; } return lastArg.text === '' && lastArg.suffix === '' && lastArg.prefix.slice(-1) === ' '; }; /** * Return an array of Status scores so we can create a marked up * version of the command line input. * @param cursor We only take a status of INCOMPLETE to be INCOMPLETE when the * cursor is actually in the argument. Otherwise it's an error. * @return Array of objects each containing <tt>status</tt> property and a * <tt>string</tt> property containing the characters to which the status * applies. Concatenating the strings in order gives the original input. */ Requisition.prototype.getInputStatusMarkup = function(cursor) { var argTraces = this.createInputArgTrace(); // Generally the 'argument at the cursor' is the argument before the cursor // unless it is before the first char, in which case we take the first. cursor = cursor === 0 ? 0 : cursor - 1; var cTrace = argTraces[cursor]; var markup = []; for (var i = 0; i < argTraces.length; i++) { var argTrace = argTraces[i]; var arg = argTrace.arg; var status = Status.VALID; if (argTrace.part === 'text') { status = arg.assignment.getStatus(arg); // Promote INCOMPLETE to ERROR ... if (status === Status.INCOMPLETE) { // If the cursor is in the prefix or suffix of an argument then we // don't consider it in the argument for the purposes of preventing // the escalation to ERROR. However if this is a NamedArgument, then we // allow the suffix (as space between 2 parts of the argument) to be in. // We use arg.assignment.arg not arg because we're looking at the arg // that got put into the assignment not as returned by tokenize() var isNamed = (cTrace.arg.assignment.arg.type === 'NamedArgument'); var isInside = cTrace.part === 'text' || (isNamed && cTrace.part === 'suffix'); if (arg.assignment !== cTrace.arg.assignment || !isInside) { // And if we're not in the command if (!(arg.assignment instanceof CommandAssignment)) { status = Status.ERROR; } } } } markup.push({ status: status, string: argTrace.character }); } // De-dupe: merge entries where 2 adjacent have same status i = 0; while (i < markup.length - 1) { if (markup[i].status === markup[i + 1].status) { markup[i].string += markup[i + 1].string; markup.splice(i + 1, 1); } else { i++; } } return markup; }; /** * Describe the state of the current input in a way that allows display of * predictions and completion hints * @param start The location of the cursor * @param rank The index of the chosen prediction * @return A promise of an object containing the following properties: * - statusMarkup: An array of Status scores so we can create a marked up * version of the command line input. See getInputStatusMarkup() for details * - unclosedJs: Is the entered command a JS command with no closing '}'? * - directTabText: A promise of the text that we *add* to the command line * when TAB is pressed, to be displayed directly after the cursor. See also * arrowTabText. * - emptyParameters: A promise of the text that describes the arguments that * the user is yet to type. * - arrowTabText: A promise of the text that *replaces* the current argument * when TAB is pressed, generally displayed after a "|->" symbol. See also * directTabText. */ Requisition.prototype.getStateData = function(start, rank) { var typed = this.toString(); var current = this.getAssignmentAt(start); var context = this.executionContext; var predictionPromise = (typed.trim().length !== 0) ? current.getPredictionRanked(context, rank) : Promise.resolve(null); return predictionPromise.then(function(prediction) { // directTabText is for when the current input is a prefix of the completion // arrowTabText is for when we need to use an -> to show what will be used var directTabText = ''; var arrowTabText = ''; var emptyParameters = []; if (typed.trim().length !== 0) { var cArg = current.arg; if (prediction) { var tabText = prediction.name; var existing = cArg.text; // Normally the cursor being just before whitespace means that you are // 'in' the previous argument, which means that the prediction is based // on that argument, however NamedArguments break this by having 2 parts // so we need to prepend the tabText with a space for NamedArguments, // but only when there isn't already a space at the end of the prefix // (i.e. ' --name' not ' --name ') if (current.isInName()) { tabText = ' ' + tabText; } if (existing !== tabText) { // Decide to use directTabText or arrowTabText // Strip any leading whitespace from the user inputted value because // the tabText will never have leading whitespace. var inputValue = existing.replace(/^\s*/, ''); var isStrictCompletion = tabText.indexOf(inputValue) === 0; if (isStrictCompletion && start === typed.length) { // Display the suffix of the prediction as the completion var numLeadingSpaces = existing.match(/^(\s*)/)[0].length; directTabText = tabText.slice(existing.length - numLeadingSpaces); } else { // Display the '-> prediction' at the end of the completer element // \u21E5 is the JS escape right arrow arrowTabText = '\u21E5 ' + tabText; } } } else { // There's no prediction, but if this is a named argument that needs a // value (that is without any) then we need to show that one is needed // For example 'git commit --message ', clearly needs some more text if (cArg.type === 'NamedArgument' && cArg.valueArg == null) { emptyParameters.push('<' + current.param.type.name + '>\u00a0'); } } } // Add a space between the typed text (+ directTabText) and the hints, // making sure we don't add 2 sets of padding if (directTabText !== '') { directTabText += '\u00a0'; // a.k.a &nbsp; } else if (!this.typedEndsWithSeparator()) { emptyParameters.unshift('\u00a0'); } // Calculate the list of parameters to be filled in // We generate an array of emptyParameter markers for each positional // parameter to the current command. // Generally each emptyParameter marker begins with a space to separate it // from whatever came before, unless what comes before ends in a space. this.getAssignments().forEach(function(assignment) { // Named arguments are handled with a group [options] marker if (!assignment.param.isPositionalAllowed) { return; } // No hints if we've got content for this parameter if (assignment.arg.toString().trim() !== '') { return; } // No hints if we have a prediction if (directTabText !== '' && current === assignment) { return; } var text = (assignment.param.isDataRequired) ? '<' + assignment.param.name + '>\u00a0' : '[' + assignment.param.name + ']\u00a0'; emptyParameters.push(text); }.bind(this)); var command = this.commandAssignment.value; var addOptionsMarker = false; // We add an '[options]' marker when there are named parameters that are // not filled in and not hidden, and we don't have any directTabText if (command && command.hasNamedParameters) { command.params.forEach(function(param) { var arg = this.getAssignment(param.name).arg; if (!param.isPositionalAllowed && !param.hidden && arg.type === 'BlankArgument') { addOptionsMarker = true; } }, this); } if (addOptionsMarker) { // Add an nbsp if we don't have one at the end of the input or if // this isn't the first param we've mentioned emptyParameters.push('[options]\u00a0'); } // Is the entered command a JS command with no closing '}'? var unclosedJs = command && command.name === '{' && this.getAssignment(0).arg.suffix.indexOf('}') === -1; return { statusMarkup: this.getInputStatusMarkup(start), unclosedJs: unclosedJs, directTabText: directTabText, arrowTabText: arrowTabText, emptyParameters: emptyParameters }; }.bind(this)); }; /** * Pressing TAB sometimes requires that we add a space to denote that we're on * to the 'next thing'. * @param assignment The assignment to which to append the space */ Requisition.prototype._addSpace = function(assignment) { var arg = assignment.arg.beget({ suffixSpace: true }); if (arg !== assignment.arg) { return this.setAssignment(assignment, arg); } else { return Promise.resolve(undefined); } }; /** * Complete the argument at <tt>cursor</tt>. * Basically the same as: * assignment = getAssignmentAt(cursor); * assignment.value = assignment.conversion.predictions[0]; * Except it's done safely, and with particular care to where we place the * space, which is complex, and annoying if we get it wrong. * * WARNING: complete() can happen asynchronously. * * @param cursor The cursor configuration. Should have start and end properties * which should be set to start and end of the selection. * @param rank The index of the prediction that we should choose. * This number is not bounded by the size of the prediction array, we take the * modulus to get it within bounds * @return A promise which completes (with undefined) when any outstanding * completion tasks are done. */ Requisition.prototype.complete = function(cursor, rank) { var assignment = this.getAssignmentAt(cursor.start); var context = this.executionContext; var predictionPromise = assignment.getPredictionRanked(context, rank); return predictionPromise.then(function(prediction) { var outstanding = []; // Note: Since complete is asynchronous we should perhaps have a system to // bail out of making changes if the command line has changed since TAB // was pressed. It's not yet clear if this will be a problem. if (prediction == null) { // No predictions generally means we shouldn't change anything on TAB, // but TAB has the connotation of 'next thing' and when we're at the end // of a thing that implies that we should add a space. i.e. // 'help<TAB>' -> 'help ' // But we should only do this if the thing that we're 'completing' is // valid and doesn't already end in a space. if (assignment.arg.suffix.slice(-1) !== ' ' && assignment.getStatus() === Status.VALID) { outstanding.push(this._addSpace(assignment)); } // Also add a space if we are in the name part of an assignment, however // this time we don't want the 'push the space to the next assignment' // logic, so we don't use addSpace if (assignment.isInName()) { var newArg = assignment.arg.beget({ prefixPostSpace: true }); outstanding.push(this.setAssignment(assignment, newArg)); } } else { // Mutate this argument to hold the completion var arg = assignment.arg.beget({ text: prediction.name, dontQuote: (assignment === this.commandAssignment) }); var assignPromise = this.setAssignment(assignment, arg); if (!prediction.incomplete) { assignPromise = assignPromise.then(function() { // The prediction is complete, add a space to let the user move-on return this._addSpace(assignment).then(function() { // Bug 779443 - Remove or explain the re-parse if (assignment instanceof UnassignedAssignment) { return this.update(this.toString()); } }.bind(this)); }.bind(this)); } outstanding.push(assignPromise); } return Promise.all(outstanding).then(function() { return true; }.bind(this)); }.bind(this)); }; /** * Replace the current value with the lower value if such a concept exists. */ Requisition.prototype.decrement = function(assignment) { var ctx = this.executionContext; var val = assignment.param.type.decrement(assignment.value, ctx); return Promise.resolve(val).then(function(replacement) { if (replacement != null) { var val = assignment.param.type.stringify(replacement, ctx); return Promise.resolve(val).then(function(str) { var arg = assignment.arg.beget({ text: str }); return this.setAssignment(assignment, arg); }.bind(this)); } }.bind(this)); }; /** * Replace the current value with the higher value if such a concept exists. */ Requisition.prototype.increment = function(assignment) { var ctx = this.executionContext; var val = assignment.param.type.increment(assignment.value, ctx); return Promise.resolve(val).then(function(replacement) { if (replacement != null) { var val = assignment.param.type.stringify(replacement, ctx); return Promise.resolve(val).then(function(str) { var arg = assignment.arg.beget({ text: str }); return this.setAssignment(assignment, arg); }.bind(this)); } }.bind(this)); }; /** * Helper to find the 'data-command' attribute, used by |update()| */ function getDataCommandAttribute(element) { var command = element.getAttribute('data-command'); if (!command) { command = element.querySelector('*[data-command]') .getAttribute('data-command'); } return command; } /** * Designed to be called from context.update(). Acts just like update() except * that it also calls onExternalUpdate() to inform the UI of an unexpected * change to the current command. */ Requisition.prototype._contextUpdate = function(typed) { return this.update(typed).then(function(reply) { this.onExternalUpdate({ typed: typed }); return reply; }.bind(this)); }; /** * Called by the UI when ever the user interacts with a command line input * @param typed The contents of the input field OR an HTML element (or an event * that targets an HTML element) which has a data-command attribute or a child * with the same that contains the command to update with */ Requisition.prototype.update = function(typed) { // Should be "if (typed instanceof HTMLElement)" except Gecko if (typeof typed.querySelector === 'function') { typed = getDataCommandAttribute(typed); } // Should be "if (typed instanceof Event)" except Gecko if (typeof typed.currentTarget === 'object') { typed = getDataCommandAttribute(typed.currentTarget); } var updateId = this._beginChange(); this._args = exports.tokenize(typed); var args = this._args.slice(0); // i.e. clone this._split(args); return this._assign(args).then(function() { return this._endChangeCheckOrder(updateId); }.bind(this)); }; /** * Similar to update('') except that it's guaranteed to execute synchronously */ Requisition.prototype.clear = function() { var arg = new Argument('', '', ''); this._args = [ arg ]; var conversion = commandModule.parse(this.executionContext, arg, false); this.setAssignment(this.commandAssignment, conversion, { internal: true }); }; /** * tokenize() is a state machine. These are the states. */ var In = { /** * The last character was ' '. * Typing a ' ' character will not change the mode * Typing one of '"{ will change mode to SINGLE_Q, DOUBLE_Q or SCRIPT. * Anything else goes into SIMPLE mode. */ WHITESPACE: 1, /** * The last character was part of a parameter. * Typing ' ' returns to WHITESPACE mode. Any other character * (including '"{} which are otherwise special) does not change the mode. */ SIMPLE: 2, /** * We're inside single quotes: ' * Typing ' returns to WHITESPACE mode. Other characters do not change mode. */ SINGLE_Q: 3, /** * We're inside double quotes: " * Typing " returns to WHITESPACE mode. Other characters do not change mode. */ DOUBLE_Q: 4, /** * We're inside { and } * Typing } returns to WHITESPACE mode. Other characters do not change mode. * SCRIPT mode is slightly different from other modes in that spaces between * the {/} delimiters and the actual input are not considered significant. * e.g: " x " is a 3 character string, delimited by double quotes, however * { x } is a 1 character JavaScript surrounded by whitespace and {} * delimiters. * In the short term we assume that the JS routines can make sense of the * extra whitespace, however at some stage we may need to move the space into * the Argument prefix/suffix. * Also we don't attempt to handle nested {}. See bug 678961 */ SCRIPT: 5 }; /** * Split up the input taking into account ', " and {. * We don't consider \t or other classical whitespace characters to split * arguments apart. For one thing these characters are hard to type, but also * if the user has gone to the trouble of pasting a TAB character into the * input field (or whatever it takes), they probably mean it. */ exports.tokenize = function(typed) { // For blank input, place a dummy empty argument into the list if (typed == null || typed.length === 0) { return [ new Argument('', '', '') ]; } if (isSimple(typed)) { return [ new Argument(typed, '', '') ]; } var mode = In.WHITESPACE; // First we swap out escaped characters that are special to the tokenizer. // So a backslash followed by any of ['"{} ] is turned into a unicode private // char so we can swap back later typed = typed .replace(/\\\\/g, '\uF000') .replace(/\\ /g, '\uF001') .replace(/\\'/g, '\uF002') .replace(/\\"/g, '\uF003') .replace(/\\{/g, '\uF004') .replace(/\\}/g, '\uF005'); function unescape2(escaped) { return escaped .replace(/\uF000/g, '\\\\') .replace(/\uF001/g, '\\ ') .replace(/\uF002/g, '\\\'') .replace(/\uF003/g, '\\\"') .replace(/\uF004/g, '\\{') .replace(/\uF005/g, '\\}'); } var i = 0; // The index of the current character var start = 0; // Where did this section start? var prefix = ''; // Stuff that comes before the current argument var args = []; // The array that we're creating var blockDepth = 0; // For JS with nested {} // This is just a state machine. We're going through the string char by char // The 'mode' is one of the 'In' states. As we go, we're adding Arguments // to the 'args' array. while (true) { var c = typed[i]; var str; switch (mode) { case In.WHITESPACE: if (c === '\'') { prefix = typed.substring(start, i + 1); mode = In.SINGLE_Q; start = i + 1; } else if (c === '"') { prefix = typed.substring(start, i + 1); mode = In.DOUBLE_Q; start = i + 1; } else if (c === '{') { prefix = typed.substring(start, i + 1); mode = In.SCRIPT; blockDepth++; start = i + 1; } else if (/ /.test(c)) { // Still whitespace, do nothing } else { prefix = typed.substring(start, i); mode = In.SIMPLE; start = i; } break; case In.SIMPLE: // There is an edge case of xx'xx which we are assuming to // be a single parameter (and same with ") if (c === ' ') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, '')); mode = In.WHITESPACE; start = i; prefix = ''; } break; case In.SINGLE_Q: if (c === '\'') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.DOUBLE_Q: if (c === '"') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.SCRIPT: if (c === '{') { blockDepth++; } else if (c === '}') { blockDepth--; if (blockDepth === 0) { str = unescape2(typed.substring(start, i)); args.push(new ScriptArgument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } } break; } i++; if (i >= typed.length) { // There is nothing else to read - tidy up if (mode === In.WHITESPACE) { if (i !== start) { // There's whitespace at the end of the typed string. Add it to the // last argument's suffix, creating an empty argument if needed. var extra = typed.substring(start, i); var lastArg = args[args.length - 1]; if (!lastArg) { args.push(new Argument('', extra, '')); } else { lastArg.suffix += extra; } } } else if (mode === In.SCRIPT) { str = unescape2(typed.substring(start, i + 1)); args.push(new ScriptArgument(str, prefix, '')); } else { str = unescape2(typed.substring(start, i + 1)); args.push(new Argument(str, prefix, '')); } break; } } return args; }; /** * If the input has no spaces, quotes, braces or escapes, * we can take the fast track. */ function isSimple(typed) { for (var i = 0; i < typed.length; i++) { var c = typed.charAt(i); if (c === ' ' || c === '"' || c === '\'' || c === '{' || c === '}' || c === '\\') { return false; } } return true; } /** * Looks in the commands for a command extension that matches what has been * typed at the command line. */ Requisition.prototype._split = function(args) { // Handle the special case of the user typing { javascript(); } // We use the hidden 'eval' command directly rather than shift()ing one of // the parameters, and parse()ing it. var conversion; if (args[0].type === 'ScriptArgument') { // Special case: if the user enters { console.log('foo'); } then we need to // use the hidden 'eval' command conversion = new Conversion(getEvalCommand(this.system.commands), new ScriptArgument()); this._setAssignmentInternal(this.commandAssignment, conversion); return; } var argsUsed = 1; while (argsUsed <= args.length) { var arg = (argsUsed === 1) ? args[0] : new MergedArgument(args, 0, argsUsed); if (this.prefix != null && this.prefix !== '') { var prefixArg = new Argument(this.prefix, '', ' '); var prefixedArg = new MergedArgument([ prefixArg, arg ]); conversion = commandModule.parse(this.executionContext, prefixedArg, false); if (conversion.value == null) { conversion = commandModule.parse(this.executionContext, arg, false); } } else { conversion = commandModule.parse(this.executionContext, arg, false); } // We only want to carry on if this command is a parent command, // which means that there is a commandAssignment, but not one with // an exec function. if (!conversion.value || conversion.value.exec) { break; } // Previously we needed a way to hide commands depending context. // We have not resurrected that feature yet, but if we do we should // insert code here to ignore certain commands depending on the // context/environment argsUsed++; } // This could probably be re-written to consume args as we go for (var i = 0; i < argsUsed; i++) { args.shift(); } this._setAssignmentInternal(this.commandAssignment, conversion); }; /** * Add all the passed args to the list of unassigned assignments. */ Requisition.prototype._addUnassignedArgs = function(args) { args.forEach(function(arg) { this._unassigned.push(new UnassignedAssignment(this, arg)); }.bind(this)); return RESOLVED; }; /** * Work out which arguments are applicable to which parameters. */ Requisition.prototype._assign = function(args) { // See comment in _split. Avoid multiple updates var noArgUp = { internal: true }; this._unassigned = []; if (!this.commandAssignment.value) { return this._addUnassignedArgs(args); } if (args.length === 0) { this._setBlankArguments(); return RESOLVED; } // Create an error if the command does not take parameters, but we have // been given them ... if (this.assignmentCount === 0) { return this._addUnassignedArgs(args); } // Special case: if there is only 1 parameter, and that's of type // text, then we put all the params into the first param if (this.assignmentCount === 1) { var assignment = this.getAssignment(0); if (assignment.param.type.name === 'string') { var arg = (args.length === 1) ? args[0] : new MergedArgument(args); return this.setAssignment(assignment, arg, noArgUp); } } // Positional arguments can still be specified by name, but if they are // then we need to ignore them when working them out positionally var unassignedParams = this.getParameterNames(); // We collect the arguments used in arrays here before assigning var arrayArgs = {}; // Extract all the named parameters var assignments = this.getAssignments(false); var namedDone = util.promiseEach(assignments, function(assignment) { // Loop over the arguments // Using while rather than loop because we remove args as we go var i = 0; while (i < args.length) { if (!assignment.param.isKnownAs(args[i].text)) { // Skip this parameter and handle as a positional parameter i++; continue; } var arg = args.splice(i, 1)[0]; /* jshint loopfunc:true */ unassignedParams = unassignedParams.filter(function(test) { return test !== assignment.param.name; }); // boolean parameters don't have values, default to false if (assignment.param.type.name === 'boolean') { arg = new TrueNamedArgument(arg); } else { var valueArg = null; if (i + 1 <= args.length) { valueArg = args.splice(i, 1)[0]; } arg = new NamedArgument(arg, valueArg); } if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArgument(arg); return RESOLVED; } else { if (assignment.arg.type === 'BlankArgument') { return this.setAssignment(assignment, arg, noArgUp); } else { return this._addUnassignedArgs(arg.getArgs()); } } } }, this); // What's left are positional parameters: assign in order var positionalDone = namedDone.then(function() { return util.promiseEach(unassignedParams, function(name) { var assignment = this.getAssignment(name); // If not set positionally, and we can't set it non-positionally, // we have to default it to prevent previous values surviving if (!assignment.param.isPositionalAllowed) { this._setBlankAssignment(assignment); return RESOLVED; } // If this is a positional array argument, then it swallows the // rest of the arguments. if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArguments(args); args = []; // The actual assignment to the array parameter is done below return RESOLVED; } // Set assignment to defaults if there are no more arguments if (args.length === 0) { this._setBlankAssignment(assignment); return RESOLVED; } var arg = args.splice(0, 1)[0]; // --foo and -f are named parameters, -4 is a number. So '-' is either // the start of a named parameter or a number depending on the context var isIncompleteName = assignment.param.type.name === 'number' ? /-[-a-zA-Z_]/.test(arg.text) : arg.text.charAt(0) === '-'; if (isIncompleteName) { this._unassigned.push(new UnassignedAssignment(this, arg)); return RESOLVED; } else { return this.setAssignment(assignment, arg, noArgUp); } }, this); }.bind(this)); // Now we need to assign the array argument (if any) var arrayDone = positionalDone.then(function() { return util.promiseEach(Object.keys(arrayArgs), function(name) { var assignment = this.getAssignment(name); return this.setAssignment(assignment, arrayArgs[name], noArgUp); }, this); }.bind(this)); // What's left is can't be assigned, but we need to officially unassign them return arrayDone.then(function() { return this._addUnassignedArgs(args); }.bind(this)); }; /** * Entry point for keyboard accelerators or anything else that wants to execute * a command. * @param options Object describing how the execution should be handled. * (optional). Contains some of the following properties: * - hidden (boolean, default=false) Should the output be hidden from the * commandOutputManager for this requisition * - command/args A fast shortcut to executing a known command with a known * set of parsed arguments. */ Requisition.prototype.exec = function(options) { var command = null; var args = null; var hidden = false; if (options) { if (options.hidden) { hidden = true; } if (options.command != null) { // Fast track by looking up the command directly since passed args // means there is no command line to parse. command = this.system.commands.get(options.command); if (!command) { console.error('Command not found: ' + options.command); } args = options.args; } } if (!command) { command = this.commandAssignment.value; args = this.getArgsObject(); } // Display JavaScript input without the initial { or closing } var typed = this.toString(); if (evalCmd.isCommandRegexp.test(typed)) { typed = typed.replace(evalCmd.isCommandRegexp, ''); // Bug 717763: What if the JavaScript naturally ends with a }? typed = typed.replace(/\s*}\s*$/, ''); } var output = new Output(this.conversionContext, { command: command, args: args, typed: typed, canonical: this.toCanonicalString(), hidden: hidden }); this.commandOutputManager.onOutput({ output: output }); var onDone = function(data) { output.complete(data, false); return output; }; var onError = function(data, ex) { if (logErrors) { if (ex != null) { util.errorHandler(ex); } else { console.error(data); } } data = (data != null && data.isTypedData) ? data : { isTypedData: true, data: data, type: 'error' }; output.complete(data, true); return output; }; if (this.status !== Status.VALID) { var ex = new Error(this.getStatusMessage()); // We only reject a call to exec if GCLI breaks. Errors with commands are // exposed in the 'error' status of the Output object return Promise.resolve(onError(ex)).then(function(output) { this.clear(); return output; }.bind(this)); } else { try { return host.exec(function() { return command.exec(args, this.executionContext); }.bind(this)).then(onDone, onError); } catch (ex) { var data = (typeof ex.message === 'string' && ex.stack != null) ? ex.message : ex; return Promise.resolve(onError(data, ex)); } finally { this.clear(); } } }; /** * Designed to be called from context.updateExec(). Acts just like updateExec() * except that it also calls onExternalUpdate() to inform the UI of an * unexpected change to the current command. */ Requisition.prototype._contextUpdateExec = function(typed, options) { return this.updateExec(typed, options).then(function(reply) { this.onExternalUpdate({ typed: typed }); return reply; }.bind(this)); }; /** * A shortcut for calling update, resolving the promise and then exec. * @param input The string to execute * @param options Passed to exec * @return A promise of an output object */ Requisition.prototype.updateExec = function(input, options) { return this.update(input).then(function() { return this.exec(options); }.bind(this)); }; exports.Requisition = Requisition; /** * A simple object to hold information about the output of a command */ function Output(context, options) { options = options || {}; this.command = options.command || ''; this.args = options.args || {}; this.typed = options.typed || ''; this.canonical = options.canonical || ''; this.hidden = options.hidden === true ? true : false; this.converters = context.system.converters; this.type = undefined; this.data = undefined; this.completed = false; this.error = false; this.start = new Date(); this.promise = new Promise(function(resolve, reject) { this._resolve = resolve; }.bind(this)); } /** * Called when there is data to display, and the command has finished executing * See changed() for details on parameters. */ Output.prototype.complete = function(data, error) { this.end = new Date(); this.completed = true; this.error = error; if (data != null && data.isTypedData) { this.data = data.data; this.type = data.type; } else { this.data = data; this.type = this.command.returnType; if (this.type == null) { this.type = (this.data == null) ? 'undefined' : typeof this.data; } } if (this.type === 'object') { throw new Error('No type from output of ' + this.typed); } this._resolve(); }; /** * Call converters.convert using the data in this Output object */ Output.prototype.convert = function(type, conversionContext) { return this.converters.convert(this.data, this.type, type, conversionContext); }; Output.prototype.toJson = function() { return { typed: this.typed, type: this.type, data: this.data, error: this.error }; }; exports.Output = Output;
protocolnoise-1035296: Add string to remove log noise Signed-off-by: Joe Walker <[email protected]>
lib/gcli/cli.js
protocolnoise-1035296: Add string to remove log noise
<ide><path>ib/gcli/cli.js <ide> } <ide> } <ide> <add> if (data != null && typeof data === 'string') { <add> data = data.replace(/^Protocol error: /, ''); // Temp fix for bug 1035296 <add> } <add> <ide> data = (data != null && data.isTypedData) ? data : { <ide> isTypedData: true, <ide> data: data,
Java
mit
9d59c2cb618c92c52a623fd8a1c98021db650795
0
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
/* * Copyright (c) 2010, The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.broadinstitute.sting.gatk.walkers.variantutils; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import org.broadinstitute.sting.commandline.Argument; import org.broadinstitute.sting.commandline.Output; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.variantcontext.VariantContextUtils; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.walkers.Requires; import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.utils.QualityUtils; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.exceptions.UserException; import java.io.PrintStream; import java.util.*; /** * Emits specific fields as dictated by the user from one or more VCF files. */ @Requires(value={}) public class VariantsToTable extends RodWalker<Integer, Integer> { @Output(doc="File to which results should be written",required=true) protected PrintStream out; @Argument(fullName="fields", shortName="F", doc="Fields to emit from the VCF, allows any VCF field, any info field, and some meta fields like nHets", required=true) public ArrayList<String> fieldsToTake = new ArrayList<String>(); @Argument(fullName="showFiltered", shortName="raw", doc="Include filtered records") public boolean showFiltered = false; @Argument(fullName="maxRecords", shortName="M", doc="Maximum number of records to emit, if provided", required=false) public int MAX_RECORDS = -1; int nRecords = 0; @Argument(fullName="keepMultiAllelic", shortName="KMA", doc="If provided, we will not require the site to be biallelic", required=false) public boolean keepMultiAllelic = false; @Argument(fullName="allowMissingData", shortName="AMD", doc="If provided, we will not require every record to contain every field", required=false) public boolean ALLOW_MISSING_DATA = false; public void initialize() { out.println(Utils.join("\t", fieldsToTake)); } public static abstract class Getter { public abstract String get(VariantContext vc); } public static Map<String, Getter> getters = new HashMap<String, Getter>(); static { // #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT getters.put("CHROM", new Getter() { public String get(VariantContext vc) { return vc.getChr(); } }); getters.put("POS", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getStart()); } }); getters.put("REF", new Getter() { public String get(VariantContext vc) { String x = ""; if (vc.hasAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)) { Byte refByte = (Byte)(vc.getAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)); x=x+new String(new byte[]{refByte}); } return x+vc.getReference().getDisplayString(); } }); getters.put("ALT", new Getter() { public String get(VariantContext vc) { StringBuilder x = new StringBuilder(); int n = vc.getAlternateAlleles().size(); if ( n == 0 ) return "."; if (vc.hasAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)) { Byte refByte = (Byte)(vc.getAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)); x.append(new String(new byte[]{refByte})); } for ( int i = 0; i < n; i++ ) { if ( i != 0 ) x.append(","); x.append(vc.getAlternateAllele(i).getDisplayString()); } return x.toString(); } }); getters.put("QUAL", new Getter() { public String get(VariantContext vc) { return Double.toString(vc.getPhredScaledQual()); } }); getters.put("TRANSITION", new Getter() { public String get(VariantContext vc) { if ( vc.isSNP() && vc.isBiallelic() ) return VariantContextUtils.isTransition(vc) ? "1" : "0"; else return "-1"; }}); getters.put("FILTER", new Getter() { public String get(VariantContext vc) { return vc.isNotFiltered() ? "PASS" : Utils.join(",", vc.getFilters()); } }); getters.put("HET", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHetCount()); } }); getters.put("HOM-REF", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHomRefCount()); } }); getters.put("HOM-VAR", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHomVarCount()); } }); getters.put("NO-CALL", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getNoCallCount()); } }); getters.put("VAR", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHetCount() + vc.getHomVarCount()); } }); getters.put("NSAMPLES", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getNSamples()); } }); getters.put("NCALLED", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getNSamples() - vc.getNoCallCount()); } }); getters.put("GQ", new Getter() { public String get(VariantContext vc) { if ( vc.getNSamples() > 1 ) throw new UserException("Cannot get GQ values for multi-sample VCF"); return String.format("%.2f", 10 * vc.getGenotype(0).getNegLog10PError()); }}); } public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { if ( tracker == null ) // RodWalkers can make funky map calls return 0; if ( ++nRecords < MAX_RECORDS || MAX_RECORDS == -1 ) { Collection<VariantContext> vcs = tracker.getAllVariantContexts(ref, context.getLocation()); for ( VariantContext vc : vcs) { if ( (keepMultiAllelic || vc.isBiallelic()) && ( showFiltered || vc.isNotFiltered() ) ) { List<String> vals = extractFields(vc, fieldsToTake, ALLOW_MISSING_DATA); out.println(Utils.join("\t", vals)); } } return 1; } else { if ( nRecords >= MAX_RECORDS ) { logger.warn("Calling sys exit to leave after " + nRecords + " records"); System.exit(0); // todo -- what's the recommend way to abort like this? } return 0; } } private static final boolean isWildCard(String s) { return s.endsWith("*"); } public static List<String> extractFields(VariantContext vc, List<String> fields, boolean allowMissingData) { List<String> vals = new ArrayList<String>(); for ( String field : fields ) { String val = "NA"; if ( getters.containsKey(field) ) { val = getters.get(field).get(vc); } else if ( vc.hasAttribute(field) ) { val = vc.getAttributeAsString(field); } else if ( isWildCard(field) ) { Set<String> wildVals = new HashSet<String>(); for ( Map.Entry<String,Object> elt : vc.getAttributes().entrySet()) { if ( elt.getKey().startsWith(field.substring(0, field.length() - 1)) ) { wildVals.add(elt.getValue().toString()); } } if ( wildVals.size() > 0 ) { List<String> toVal = new ArrayList<String>(wildVals); Collections.sort(toVal); val = Utils.join(",", toVal); } } else if ( ! allowMissingData ) { throw new UserException(String.format("Missing field %s in vc %s at %s", field, vc.getSource(), vc)); } if (field.equals("AF") || field.equals("AC")) { String afo = val; double af=0; if (afo.contains(",")) { String[] afs = afo.split(","); afs[0] = afs[0].substring(1,afs[0].length()); afs[afs.length-1] = afs[afs.length-1].substring(0,afs[afs.length-1].length()-1); double[] afd = new double[afs.length]; for (int k=0; k < afd.length; k++) afd[k] = Double.valueOf(afs[k]); af = MathUtils.arrayMax(afd); //af = Double.valueOf(afs[0]); } else if (!afo.equals("NA")) af = Double.valueOf(afo); val = Double.toString(af); } vals.add(val); } return vals; } public Integer reduceInit() { return 0; } public Integer reduce(Integer counter, Integer sum) { return counter + sum; } public void onTraversalDone(Integer sum) {} }
public/java/src/org/broadinstitute/sting/gatk/walkers/variantutils/VariantsToTable.java
/* * Copyright (c) 2010, The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.broadinstitute.sting.gatk.walkers.variantutils; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import org.broadinstitute.sting.commandline.Argument; import org.broadinstitute.sting.commandline.Output; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.variantcontext.VariantContextUtils; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.walkers.Requires; import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.utils.QualityUtils; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.exceptions.UserException; import java.io.PrintStream; import java.util.*; /** * Emits specific fields as dictated by the user from one or more VCF files. */ @Requires(value={}) public class VariantsToTable extends RodWalker<Integer, Integer> { @Output(doc="File to which results should be written",required=true) protected PrintStream out; @Argument(fullName="fields", shortName="F", doc="Fields to emit from the VCF, allows any VCF field, any info field, and some meta fields like nHets", required=true) public ArrayList<String> fieldsToTake = new ArrayList<String>(); @Argument(fullName="showFiltered", shortName="raw", doc="Include filtered records") public boolean showFiltered = false; @Argument(fullName="maxRecords", shortName="M", doc="Maximum number of records to emit, if provided", required=false) public int MAX_RECORDS = -1; int nRecords = 0; @Argument(fullName="keepMultiAllelic", shortName="KMA", doc="If provided, we will not require the site to be biallelic", required=false) public boolean keepMultiAllelic = false; @Argument(fullName="allowMissingData", shortName="AMD", doc="If provided, we will not require every record to contain every field", required=false) public boolean ALLOW_MISSING_DATA = false; public void initialize() { out.println(Utils.join("\t", fieldsToTake)); } public static abstract class Getter { public abstract String get(VariantContext vc); } public static Map<String, Getter> getters = new HashMap<String, Getter>(); static { // #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT getters.put("CHROM", new Getter() { public String get(VariantContext vc) { return vc.getChr(); } }); getters.put("POS", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getStart()); } }); getters.put("REF", new Getter() { public String get(VariantContext vc) { return vc.getReference().toString(); } }); getters.put("ALT", new Getter() { public String get(VariantContext vc) { StringBuilder x = new StringBuilder(); int n = vc.getAlternateAlleles().size(); if ( n == 0 ) return "."; for ( int i = 0; i < n; i++ ) { if ( i != 0 ) x.append(","); x.append(vc.getAlternateAllele(i).toString()); } return x.toString(); } }); getters.put("QUAL", new Getter() { public String get(VariantContext vc) { return Double.toString(vc.getPhredScaledQual()); } }); getters.put("TRANSITION", new Getter() { public String get(VariantContext vc) { if ( vc.isSNP() && vc.isBiallelic() ) return VariantContextUtils.isTransition(vc) ? "1" : "0"; else return "-1"; }}); getters.put("FILTER", new Getter() { public String get(VariantContext vc) { return vc.isNotFiltered() ? "PASS" : Utils.join(",", vc.getFilters()); } }); getters.put("HET", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHetCount()); } }); getters.put("HOM-REF", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHomRefCount()); } }); getters.put("HOM-VAR", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHomVarCount()); } }); getters.put("NO-CALL", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getNoCallCount()); } }); getters.put("VAR", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getHetCount() + vc.getHomVarCount()); } }); getters.put("NSAMPLES", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getNSamples()); } }); getters.put("NCALLED", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getNSamples() - vc.getNoCallCount()); } }); getters.put("GQ", new Getter() { public String get(VariantContext vc) { if ( vc.getNSamples() > 1 ) throw new UserException("Cannot get GQ values for multi-sample VCF"); return String.format("%.2f", 10 * vc.getGenotype(0).getNegLog10PError()); }}); } public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { if ( tracker == null ) // RodWalkers can make funky map calls return 0; if ( ++nRecords < MAX_RECORDS || MAX_RECORDS == -1 ) { Collection<VariantContext> vcs = tracker.getAllVariantContexts(ref, context.getLocation()); for ( VariantContext vc : vcs) { if ( (keepMultiAllelic || vc.isBiallelic()) && ( showFiltered || vc.isNotFiltered() ) ) { List<String> vals = extractFields(vc, fieldsToTake, ALLOW_MISSING_DATA); out.println(Utils.join("\t", vals)); } } return 1; } else { if ( nRecords >= MAX_RECORDS ) { logger.warn("Calling sys exit to leave after " + nRecords + " records"); System.exit(0); // todo -- what's the recommend way to abort like this? } return 0; } } private static final boolean isWildCard(String s) { return s.endsWith("*"); } public static List<String> extractFields(VariantContext vc, List<String> fields, boolean allowMissingData) { List<String> vals = new ArrayList<String>(); for ( String field : fields ) { String val = "NA"; if ( getters.containsKey(field) ) { val = getters.get(field).get(vc); } else if ( vc.hasAttribute(field) ) { val = vc.getAttributeAsString(field); } else if ( isWildCard(field) ) { Set<String> wildVals = new HashSet<String>(); for ( Map.Entry<String,Object> elt : vc.getAttributes().entrySet()) { if ( elt.getKey().startsWith(field.substring(0, field.length() - 1)) ) { wildVals.add(elt.getValue().toString()); } } if ( wildVals.size() > 0 ) { List<String> toVal = new ArrayList<String>(wildVals); Collections.sort(toVal); val = Utils.join(",", toVal); } } else if ( ! allowMissingData ) { throw new UserException(String.format("Missing field %s in vc %s at %s", field, vc.getSource(), vc)); } if (field.equals("AF") || field.equals("AC")) { String afo = val; double af=0; if (afo.contains(",")) { String[] afs = afo.split(","); afs[0] = afs[0].substring(1,afs[0].length()); afs[afs.length-1] = afs[afs.length-1].substring(0,afs[afs.length-1].length()-1); double[] afd = new double[afs.length]; for (int k=0; k < afd.length; k++) afd[k] = Double.valueOf(afs[k]); af = MathUtils.arrayMax(afd); //af = Double.valueOf(afs[0]); } else if (!afo.equals("NA")) af = Double.valueOf(afo); val = Double.toString(af); } vals.add(val); } return vals; } public Integer reduceInit() { return 0; } public Integer reduce(Integer counter, Integer sum) { return counter + sum; } public void onTraversalDone(Integer sum) {} }
a) Made indel VQSR consensus script operational again, b) Made VariantsToTable more indel-friendly when printing out REF and ALT fields: strip out * from REF and print out alleles in the same way as the VCF so that offline processing is easier
public/java/src/org/broadinstitute/sting/gatk/walkers/variantutils/VariantsToTable.java
a) Made indel VQSR consensus script operational again, b) Made VariantsToTable more indel-friendly when printing out REF and ALT fields: strip out * from REF and print out alleles in the same way as the VCF so that offline processing is easier
<ide><path>ublic/java/src/org/broadinstitute/sting/gatk/walkers/variantutils/VariantsToTable.java <ide> // #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT <ide> getters.put("CHROM", new Getter() { public String get(VariantContext vc) { return vc.getChr(); } }); <ide> getters.put("POS", new Getter() { public String get(VariantContext vc) { return Integer.toString(vc.getStart()); } }); <del> getters.put("REF", new Getter() { public String get(VariantContext vc) { return vc.getReference().toString(); } }); <add> getters.put("REF", new Getter() { <add> public String get(VariantContext vc) { <add> String x = ""; <add> if (vc.hasAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)) { <add> Byte refByte = (Byte)(vc.getAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)); <add> x=x+new String(new byte[]{refByte}); <add> } <add> return x+vc.getReference().getDisplayString(); <add> } <add> }); <ide> getters.put("ALT", new Getter() { <ide> public String get(VariantContext vc) { <ide> StringBuilder x = new StringBuilder(); <ide> int n = vc.getAlternateAlleles().size(); <del> <ide> if ( n == 0 ) return "."; <add> if (vc.hasAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)) { <add> Byte refByte = (Byte)(vc.getAttribute(VariantContext.REFERENCE_BASE_FOR_INDEL_KEY)); <add> x.append(new String(new byte[]{refByte})); <add> } <ide> <ide> for ( int i = 0; i < n; i++ ) { <ide> if ( i != 0 ) x.append(","); <del> x.append(vc.getAlternateAllele(i).toString()); <add> x.append(vc.getAlternateAllele(i).getDisplayString()); <ide> } <ide> return x.toString(); <ide> }
JavaScript
apache-2.0
9c2fecf4547fe45fe0bcf20ae4295b8101d159df
0
AnimatedRNG/cesium,wallw-bits/cesium,hodbauer/cesium,jason-crow/cesium,kiselev-dv/cesium,oterral/cesium,likangning93/cesium,YonatanKra/cesium,oterral/cesium,likangning93/cesium,CesiumGS/cesium,kaktus40/cesium,denverpierce/cesium,geoscan/cesium,NaderCHASER/cesium,likangning93/cesium,ggetz/cesium,jasonbeverage/cesium,geoscan/cesium,likangning93/cesium,AnalyticalGraphicsInc/cesium,jason-crow/cesium,CesiumGS/cesium,aelatgt/cesium,aelatgt/cesium,jason-crow/cesium,emackey/cesium,esraerik/cesium,esraerik/cesium,AnimatedRNG/cesium,kaktus40/cesium,denverpierce/cesium,soceur/cesium,AnimatedRNG/cesium,wallw-bits/cesium,NaderCHASER/cesium,NaderCHASER/cesium,progsung/cesium,hodbauer/cesium,aelatgt/cesium,omh1280/cesium,jason-crow/cesium,omh1280/cesium,progsung/cesium,jasonbeverage/cesium,CesiumGS/cesium,esraerik/cesium,omh1280/cesium,ggetz/cesium,kiselev-dv/cesium,emackey/cesium,emackey/cesium,oterral/cesium,CesiumGS/cesium,CesiumGS/cesium,emackey/cesium,josh-bernstein/cesium,YonatanKra/cesium,denverpierce/cesium,AnimatedRNG/cesium,aelatgt/cesium,kiselev-dv/cesium,likangning93/cesium,soceur/cesium,esraerik/cesium,denverpierce/cesium,YonatanKra/cesium,ggetz/cesium,ggetz/cesium,josh-bernstein/cesium,soceur/cesium,YonatanKra/cesium,AnalyticalGraphicsInc/cesium,wallw-bits/cesium,wallw-bits/cesium,hodbauer/cesium,omh1280/cesium,kiselev-dv/cesium
/*global define*/ define([ '../Core/AssociativeArray', '../Core/Cartesian2', '../Core/Cartesian3', '../Core/Color', '../Core/defined', '../Core/destroyObject', '../Core/DeveloperError', '../Core/NearFarScalar', '../Scene/HorizontalOrigin', '../Scene/LabelCollection', '../Scene/LabelStyle', '../Scene/VerticalOrigin', './Property' ], function( AssociativeArray, Cartesian2, Cartesian3, Color, defined, destroyObject, DeveloperError, NearFarScalar, HorizontalOrigin, LabelCollection, LabelStyle, VerticalOrigin, Property) { "use strict"; var defaultScale = 1.0; var defaultFont = '30px sans-serif'; var defaultStyle = LabelStyle.FILL; var defaultFillColor = Color.WHITE; var defaultOutlineColor = Color.BLACK; var defaultOutlineWidth = 1; var defaultPixelOffset = Cartesian2.ZERO; var defaultEyeOffset = Cartesian3.ZERO; var defaultHorizontalOrigin = HorizontalOrigin.CENTER; var defaultVerticalOrigin = VerticalOrigin.CENTER; var position = new Cartesian3(); var fillColor = new Color(); var outlineColor = new Color(); var eyeOffset = new Cartesian3(); var pixelOffset = new Cartesian2(); var translucencyByDistance = new NearFarScalar(); var pixelOffsetScaleByDistance = new NearFarScalar(); var EntityData = function(entity) { this.entity = entity; this.label = undefined; this.index = undefined; }; /** * A {@link Visualizer} which maps the {@link LabelGraphics} instance * in {@link Entity#label} to a {@link Label}. * @alias LabelVisualizer * @constructor * * @param {Scene} scene The scene the primitives will be rendered in. * @param {EntityCollection} entityCollection The entityCollection to visualize. */ var LabelVisualizer = function(scene, entityCollection) { //>>includeStart('debug', pragmas.debug); if (!defined(scene)) { throw new DeveloperError('scene is required.'); } if (!defined(entityCollection)) { throw new DeveloperError('entityCollection is required.'); } //>>includeEnd('debug'); entityCollection.collectionChanged.addEventListener(LabelVisualizer.prototype._onCollectionChanged, this); this._scene = scene; this._unusedIndexes = []; this._labelCollection = undefined; this._entityCollection = entityCollection; this._items = new AssociativeArray(); this._onCollectionChanged(entityCollection, entityCollection.entities, [], []); }; /** * Updates the primitives created by this visualizer to match their * Entity counterpart at the given time. * * @param {JulianDate} time The time to update to. * @returns {Boolean} This function always returns true. */ LabelVisualizer.prototype.update = function(time) { //>>includeStart('debug', pragmas.debug); if (!defined(time)) { throw new DeveloperError('time is required.'); } //>>includeEnd('debug'); var items = this._items.values; var unusedIndexes = this._unusedIndexes; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var entity = item.entity; var labelGraphics = entity._label; var text; var label = item.label; var show = entity.isAvailable(time) && Property.getValueOrDefault(labelGraphics._show, time, true); if (show) { position = Property.getValueOrUndefined(entity._position, time, position); text = Property.getValueOrUndefined(labelGraphics._text, time); show = defined(position) && defined(text); } if (!show) { //don't bother creating or updating anything else returnLabel(item, unusedIndexes); continue; } if (!defined(label)) { var labelCollection = this._labelCollection; if (!defined(labelCollection)) { labelCollection = new LabelCollection(); this._labelCollection = labelCollection; this._scene.primitives.add(labelCollection); } var length = unusedIndexes.length; if (length > 0) { var index = unusedIndexes.pop(); label.index = index; label = labelCollection.get(index); } else { label = labelCollection.add(); label.index = labelCollection.length - 1; } label.id = entity; item.label = label; } label.show = true; label.position = position; label.text = text; label.scale = Property.getValueOrDefault(labelGraphics._scale, time, defaultScale); label.font = Property.getValueOrDefault(labelGraphics._font, time, defaultFont); label.style = Property.getValueOrDefault(labelGraphics._style, time, defaultStyle); label.fillColor = Property.getValueOrDefault(labelGraphics._fillColor, time, defaultFillColor, fillColor); label.outlineColor = Property.getValueOrDefault(labelGraphics._outlineColor, time, defaultOutlineColor, outlineColor); label.outlineWidth = Property.getValueOrDefault(labelGraphics._outlineWidth, time, defaultOutlineWidth); label.pixelOffset = Property.getValueOrDefault(labelGraphics._pixelOffset, time, defaultPixelOffset, pixelOffset); label.eyeOffset = Property.getValueOrDefault(labelGraphics._eyeOffset, time, defaultEyeOffset, eyeOffset); label.horizontalOrigin = Property.getValueOrDefault(labelGraphics._horizontalOrigin, time, defaultHorizontalOrigin); label.verticalOrigin = Property.getValueOrDefault(labelGraphics._verticalOrigin, time, defaultVerticalOrigin); label.translucencyByDistance = Property.getValueOrUndefined(labelGraphics._translucencyByDistance, time, translucencyByDistance); label.pixelOffsetScaleByDistance = Property.getValueOrUndefined(labelGraphics._pixelOffsetScaleByDistance, time, pixelOffsetScaleByDistance); } return true; }; /** * Returns true if this object was destroyed; otherwise, false. * * @returns {Boolean} True if this object was destroyed; otherwise, false. */ LabelVisualizer.prototype.isDestroyed = function() { return false; }; /** * Removes and destroys all primitives created by this instance. */ LabelVisualizer.prototype.destroy = function() { this._entityCollection.collectionChanged.removeEventListener(LabelVisualizer.prototype._onCollectionChanged, this); if (defined(this._labelCollection)) { this._scene.primitives.remove(this._labelCollection); } return destroyObject(this); }; LabelVisualizer.prototype._onCollectionChanged = function(entityCollection, added, removed, changed) { var i; var entity; var unusedIndexes = this._unusedIndexes; var items = this._items; for (i = added.length - 1; i > -1; i--) { entity = added[i]; if (defined(entity._label) && defined(entity._position)) { items.set(entity.id, new EntityData(entity)); } } for (i = changed.length - 1; i > -1; i--) { entity = changed[i]; if (defined(entity._label) && defined(entity._position)) { if (!items.contains(entity.id)) { items.set(entity.id, new EntityData(entity)); } } else { returnLabel(items.get(entity.id), unusedIndexes); items.remove(entity.id); } } for (i = removed.length - 1; i > -1; i--) { entity = removed[i]; returnLabel(items.get(entity.id), unusedIndexes); items.remove(entity.id); } }; function returnLabel(item, unusedIndexes) { if (defined(item)) { var label = item.label; if (defined(label)) { unusedIndexes.push(item.index); label.show = false; item.label = undefined; item.index = -1; } } } return LabelVisualizer; });
Source/DataSources/LabelVisualizer.js
/*global define*/ define([ '../Core/AssociativeArray', '../Core/Cartesian2', '../Core/Cartesian3', '../Core/Color', '../Core/defined', '../Core/destroyObject', '../Core/DeveloperError', '../Core/NearFarScalar', '../Scene/HorizontalOrigin', '../Scene/LabelCollection', '../Scene/LabelStyle', '../Scene/VerticalOrigin', './Property' ], function( AssociativeArray, Cartesian2, Cartesian3, Color, defined, destroyObject, DeveloperError, NearFarScalar, HorizontalOrigin, LabelCollection, LabelStyle, VerticalOrigin, Property) { "use strict"; var defaultScale = 1.0; var defaultFont = '30px sans-serif'; var defaultStyle = LabelStyle.FILL; var defaultFillColor = Color.WHITE; var defaultOutlineColor = Color.BLACK; var defaultOutlineWidth = 1; var defaultPixelOffset = Cartesian2.ZERO; var defaultEyeOffset = Cartesian3.ZERO; var defaultHorizontalOrigin = HorizontalOrigin.CENTER; var defaultVerticalOrigin = VerticalOrigin.CENTER; var position = new Cartesian3(); var fillColor = new Color(); var outlineColor = new Color(); var eyeOffset = new Cartesian3(); var pixelOffset = new Cartesian2(); var translucencyByDistance = new NearFarScalar(); var pixelOffsetScaleByDistance = new NearFarScalar(); var EntityData = function(entity) { this.entity = entity; this.label = undefined; this.index = undefined; }; /** * A {@link Visualizer} which maps the {@link LabelGraphics} instance * in {@link Entity#label} to a {@link Label}. * @alias LabelVisualizer * @constructor * * @param {Scene} scene The scene the primitives will be rendered in. * @param {EntityCollection} entityCollection The entityCollection to visualize. */ var LabelVisualizer = function(scene, entityCollection) { //>>includeStart('debug', pragmas.debug); if (!defined(scene)) { throw new DeveloperError('scene is required.'); } if (!defined(entityCollection)) { throw new DeveloperError('entityCollection is required.'); } //>>includeEnd('debug'); entityCollection.collectionChanged.addEventListener(LabelVisualizer.prototype._onCollectionChanged, this); this._scene = scene; this._unusedIndexes = []; this._labelCollection = undefined; this._entityCollection = entityCollection; this._items = new AssociativeArray(); this._onCollectionChanged(entityCollection, entityCollection.entities, [], []); }; /** * Updates the primitives created by this visualizer to match their * Entity counterpart at the given time. * * @param {JulianDate} time The time to update to. * @returns {Boolean} This function always returns true. */ LabelVisualizer.prototype.update = function(time) { //>>includeStart('debug', pragmas.debug); if (!defined(time)) { throw new DeveloperError('time is required.'); } //>>includeEnd('debug'); var items = this._items.values; var unusedIndexes = this._unusedIndexes; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var entity = item.entity; var labelGraphics = entity._label; var text; var label = item.label; var show = entity.isAvailable(time) && Property.getValueOrDefault(labelGraphics._show, time, true); if (show) { position = Property.getValueOrUndefined(entity._position, time, position); text = Property.getValueOrUndefined(labelGraphics._text, time); show = defined(position) && defined(text); } if (!show) { //don't bother creating or updating anything else returnLabel(entity, unusedIndexes); continue; } if (!defined(label)) { var labelCollection = this._labelCollection; if (!defined(labelCollection)) { labelCollection = new LabelCollection(); this._labelCollection = labelCollection; this._scene.primitives.add(labelCollection); } var length = unusedIndexes.length; if (length > 0) { var index = unusedIndexes.pop(); label.index = index; label = labelCollection.get(index); } else { label = labelCollection.add(); label.index = labelCollection.length - 1; } label.id = entity; item.label = label; } label.show = true; label.position = position; label.text = text; label.scale = Property.getValueOrDefault(labelGraphics._scale, time, defaultScale); label.font = Property.getValueOrDefault(labelGraphics._font, time, defaultFont); label.style = Property.getValueOrDefault(labelGraphics._style, time, defaultStyle); label.fillColor = Property.getValueOrDefault(labelGraphics._fillColor, time, defaultFillColor, fillColor); label.outlineColor = Property.getValueOrDefault(labelGraphics._outlineColor, time, defaultOutlineColor, outlineColor); label.outlineWidth = Property.getValueOrDefault(labelGraphics._outlineWidth, time, defaultOutlineWidth); label.pixelOffset = Property.getValueOrDefault(labelGraphics._pixelOffset, time, defaultPixelOffset, pixelOffset); label.eyeOffset = Property.getValueOrDefault(labelGraphics._eyeOffset, time, defaultEyeOffset, eyeOffset); label.horizontalOrigin = Property.getValueOrDefault(labelGraphics._horizontalOrigin, time, defaultHorizontalOrigin); label.verticalOrigin = Property.getValueOrDefault(labelGraphics._verticalOrigin, time, defaultVerticalOrigin); label.translucencyByDistance = Property.getValueOrUndefined(labelGraphics._translucencyByDistance, time, translucencyByDistance); label.pixelOffsetScaleByDistance = Property.getValueOrUndefined(labelGraphics._pixelOffsetScaleByDistance, time, pixelOffsetScaleByDistance); } return true; }; /** * Returns true if this object was destroyed; otherwise, false. * * @returns {Boolean} True if this object was destroyed; otherwise, false. */ LabelVisualizer.prototype.isDestroyed = function() { return false; }; /** * Removes and destroys all primitives created by this instance. */ LabelVisualizer.prototype.destroy = function() { this._entityCollection.collectionChanged.removeEventListener(LabelVisualizer.prototype._onCollectionChanged, this); if (defined(this._labelCollection)) { this._scene.primitives.remove(this._labelCollection); } return destroyObject(this); }; LabelVisualizer.prototype._onCollectionChanged = function(entityCollection, added, removed, changed) { var i; var entity; var unusedIndexes = this._unusedIndexes; var items = this._items; for (i = added.length - 1; i > -1; i--) { entity = added[i]; if (defined(entity._label) && defined(entity._position)) { items.set(entity.id, new EntityData(entity)); } } for (i = changed.length - 1; i > -1; i--) { entity = changed[i]; if (defined(entity._label) && defined(entity._position)) { if (!items.contains(entity.id)) { items.set(entity.id, new EntityData(entity)); } } else { returnLabel(items.get(entity.id), unusedIndexes); items.remove(entity.id); } } for (i = removed.length - 1; i > -1; i--) { entity = removed[i]; returnLabel(items.get(entity.id), unusedIndexes); items.remove(entity.id); } }; function returnLabel(item, unusedIndexes) { if (defined(item)) { var label = item.label; if (defined(label)) { unusedIndexes.push(item.index); label.show = false; item.label = undefined; item.index = -1; } } } return LabelVisualizer; });
Fix typo merged from #2223
Source/DataSources/LabelVisualizer.js
Fix typo merged from #2223
<ide><path>ource/DataSources/LabelVisualizer.js <ide> <ide> if (!show) { <ide> //don't bother creating or updating anything else <del> returnLabel(entity, unusedIndexes); <add> returnLabel(item, unusedIndexes); <ide> continue; <ide> } <ide>
Java
apache-2.0
cd30a3235d9989e17b0f3bb8e7bb8e7df434c9b1
0
flexiblepower/powermatcher,flexiblepower/powermatcher,flexiblepower/powermatcher
package net.powermatcher.core.auctioneer.test; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledThreadPoolExecutor; import net.powermatcher.api.data.Bid; import net.powermatcher.api.data.MarketBasis; import net.powermatcher.core.auctioneer.Auctioneer; import net.powermatcher.core.sessions.SessionManager; import net.powermatcher.core.time.SystemTimeService; import net.powermatcher.mock.MockAgent; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * JUnit test for the Auctioneer * * Every test requires a different number agents. In setUp() NR_AGENTS are * instantiated. Every test the desired number of agents can be added and * removed using the functions addAgents() and removeAgents(). */ public class AuctioneerTest { private final static int NR_AGENTS = 21; // This needs to be the same as the MarketBasis created in the Auctioneer private final MarketBasis marketBasis = new MarketBasis("electricity", "EUR", 11, 0, 10); private Map<String, Object> auctioneerProperties; private Auctioneer auctioneer; private MockAgent[] agents; private SessionManager sessionManager; private static final String AUCTIONEER_NAME = "auctioneer"; @Before public void setUp() throws Exception { // Init Auctioneer this.auctioneer = new Auctioneer(); auctioneerProperties = new HashMap<String, Object>(); auctioneerProperties.put("agentId", AUCTIONEER_NAME); auctioneerProperties.put("clusterId", "DefaultCluster"); auctioneerProperties.put("matcherId", AUCTIONEER_NAME); auctioneerProperties.put("commodity", "electricity"); auctioneerProperties.put("currency", "EUR"); auctioneerProperties.put("priceSteps", "11"); auctioneerProperties.put("minimumPrice", "0"); auctioneerProperties.put("maximumPrice", "10"); auctioneerProperties.put("bidTimeout", "600"); auctioneerProperties.put("priceUpdateRate", "1"); auctioneer.setExecutorService(new ScheduledThreadPoolExecutor(10)); auctioneer.setTimeService(new SystemTimeService()); auctioneer.activate(auctioneerProperties); // Init MockAgents this.agents = new MockAgent[NR_AGENTS]; for (int i = 0; i < NR_AGENTS; i++) { String agentId = "agent" + (i + 1); MockAgent newAgent = new MockAgent(agentId); newAgent.setDesiredParentId(AUCTIONEER_NAME); agents[i] = newAgent; } // Session sessionManager = new SessionManager(); sessionManager.addMatcherRole(auctioneer); sessionManager.activate(); } private void addAgents(int number) { for (int i = 0; i < number; i++) { this.sessionManager.addAgentRole(agents[i]); } } private void removeAgents(int number) { for (int i = 0; i < number; i++) { this.sessionManager.removeAgentRole(agents[i]); } } @Test public void noEquilibriumOnDemandSide() { addAgents(3); // run 1 agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); auctioneer.publishNewPrice(); assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); // run 2 agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1 })); auctioneer.publishNewPrice(); assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(3); } @Test public void noEquilibriumOnSupplySide() { addAgents(3); // run 1 agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3 })); auctioneer.publishNewPrice(); assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); // run 2 agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -1, -1, -1, -3, -3, -3, -3 })); auctioneer.publishNewPrice(); assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(3); } @Test public void equilibriumSmallNumberOfBids() { addAgents(3); // run 1 agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, -5, -5, -5, -5, -5, -5 })); auctioneer.publishNewPrice(); assertEquals(5, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); // run 2 agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 })); auctioneer.publishNewPrice(); assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(3); } @Test @Ignore("Check whether there is no issue here. Changed to 7 in order to fix the tests. Original test value was 6.") public void equilibriumLargeSet() { addAgents(20); agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0 })); agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, -4, -4, -4, -4, -4 })); agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 })); agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 })); agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0 })); agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, -6, -6, -6, -6, -6, -6 })); agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 })); agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, -8, -8, -8 })); agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3 })); agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 })); agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -2, -2, -2, -2, -3, -3, -3 })); agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0 })); auctioneer.publishNewPrice(); assertEquals(6, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(20); } @Test public void equilibriumLargerSet() { addAgents(21); agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0 })); agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, -4, -4, -4, -4, -4 })); agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 })); agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 })); agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0 })); agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, -6, -6, -6, -6, -6, -6 })); agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 })); agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, -8, -8, -8 })); agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3 })); agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 })); agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -2, -2, -2, -2, -3, -3, -3 })); agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0 })); agents[20].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); auctioneer.publishNewPrice(); assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(21); } /* * TODO: The behavior tested in this test is outside the scope of this * version * * @Test public void rejectBid() { addAgents(4); agents[0].sendBid(new * Bid(marketBasis, new double[] {5,5,5,5,5,5,5,5,5,5,5})); * agents[1].sendBid(new Bid(marketBasis, new double[] * {4,4,4,4,4,0,0,0,0,0,0})); agents[2].sendBid(new Bid(marketBasis, new * double[] {0,0,0,0,0,-5,-5,-5,-5,-5,-5})); agents[3].sendBid(new * Bid(marketBasis, new double[] {-9,-9,-9,-9, -9,1,1,1,1,1,1})); * auctioneer.publishNewPrice(); assertEquals(5, * agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(4); } */ }
net.powermatcher.core/test/net/powermatcher/core/auctioneer/test/AuctioneerTest.java
package net.powermatcher.core.auctioneer.test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledThreadPoolExecutor; import net.powermatcher.api.data.Bid; import net.powermatcher.api.data.MarketBasis; import net.powermatcher.core.auctioneer.Auctioneer; import net.powermatcher.core.sessions.SessionManager; import net.powermatcher.core.time.SystemTimeService; import net.powermatcher.mock.MockAgent; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * JUnit test for the Auctioneer * * Every test requires a different number agents. In setUp() NR_AGENTS are instantiated. Every test the desired number * of agents can be added and removed using the functions addAgents() and removeAgents(). */ public class AuctioneerTest { private final static int NR_AGENTS = 21; // This needs to be the same as the MarketBasis created in the Auctioneer private final MarketBasis marketBasis = new MarketBasis("electricity", "EUR", 11, 0, 10); private Map<String, Object> auctioneerProperties; private Auctioneer auctioneer; private MockAgent[] agents; private SessionManager sessionManager; private static final String AUCTIONEER_NAME = "auctioneer"; @Before public void setUp() throws Exception { // Init Auctioneer this.auctioneer = new Auctioneer(); auctioneerProperties = new HashMap<String, Object>(); auctioneerProperties.put("agentId", AUCTIONEER_NAME); auctioneerProperties.put("clusterId", "DefaultCluster"); auctioneerProperties.put("matcherId", AUCTIONEER_NAME); auctioneerProperties.put("commodity", "electricity"); auctioneerProperties.put("currency", "EUR"); auctioneerProperties.put("priceSteps", "11"); auctioneerProperties.put("minimumPrice", "0"); auctioneerProperties.put("maximumPrice", "10"); auctioneerProperties.put("bidTimeout", "600"); auctioneerProperties.put("priceUpdateRate", "1"); auctioneer.setExecutorService(new ScheduledThreadPoolExecutor(10)); auctioneer.setTimeService(new SystemTimeService()); auctioneer.activate(auctioneerProperties); // List<String> activeConnections = new ArrayList<String>(); // Init MockAgents this.agents = new MockAgent[NR_AGENTS]; for (int i = 0; i < NR_AGENTS; i++) { String agentId = "agent" + (i + 1); MockAgent newAgent = new MockAgent(agentId); newAgent.setDesiredParentId(AUCTIONEER_NAME); agents[i] = newAgent; //activeConnections.add(agentId + "::" + "auctioneer"); } // Map<String, Object> sessionProperties = new HashMap<String, Object>(); // sessionProperties.put("activeConnections", activeConnections); // Session sessionManager = new SessionManager(); sessionManager.addMatcherRole(auctioneer); sessionManager.activate(); } private void addAgents(int number) { for (int i = 0; i < number; i++) { this.sessionManager.addAgentRole(agents[i]); } } private void removeAgents(int number) { for (int i = 0; i < number; i++) { this.sessionManager.removeAgentRole(agents[i]); } } @Test public void noEquilibriumOnDemandSide() { addAgents(3); // run 1 agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); auctioneer.publishNewPrice(); assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); // run 2 agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1 })); auctioneer.publishNewPrice(); assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(3); } @Test public void noEquilibriumOnSupplySide() { addAgents(3); // run 1 agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3 })); auctioneer.publishNewPrice(); assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); // run 2 agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -1, -1, -1, -3, -3, -3, -3 })); auctioneer.publishNewPrice(); assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(3); } @Test public void equilibriumSmallNumberOfBids() { addAgents(3); // run 1 agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, -5, -5, -5, -5, -5, -5 })); auctioneer.publishNewPrice(); assertEquals(5, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); // run 2 agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 })); auctioneer.publishNewPrice(); assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(3); } @Test @Ignore("Check whether there is no issue here. Changed to 7 in order to fix the tests. Original test value was 6.") public void equilibriumLargeSet() { addAgents(20); agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0 })); agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, -4, -4, -4, -4, -4 })); agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 })); agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 })); agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0 })); agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, -6, -6, -6, -6, -6, -6 })); agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 })); agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, -8, -8, -8 })); agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3 })); agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 })); agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -2, -2, -2, -2, -3, -3, -3 })); agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0 })); auctioneer.publishNewPrice(); assertEquals(6, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(20); } @Test public void equilibriumLargerSet() { addAgents(21); agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0 })); agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, -4, -4, -4, -4, -4 })); agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 })); agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2 })); agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 })); agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0 })); agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, -6, -6, -6, -6, -6, -6 })); agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 })); agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, -8, -8, -8 })); agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3 })); agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 })); agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -2, -2, -2, -2, -3, -3, -3 })); agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0 })); agents[20].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); auctioneer.publishNewPrice(); assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(21); } /* * TODO: The behavior tested in this test is outside the scope of this version * * @Test public void rejectBid() { addAgents(4); agents[0].sendBid(new Bid(marketBasis, new double[] * {5,5,5,5,5,5,5,5,5,5,5})); agents[1].sendBid(new Bid(marketBasis, new double[] {4,4,4,4,4,0,0,0,0,0,0})); * agents[2].sendBid(new Bid(marketBasis, new double[] {0,0,0,0,0,-5,-5,-5,-5,-5,-5})); agents[3].sendBid(new * Bid(marketBasis, new double[] {-9,-9,-9,-9, -9,1,1,1,1,1,1})); auctioneer.publishNewPrice(); assertEquals(5, * agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(4); } */ }
fix core tests with new sessionManager
net.powermatcher.core/test/net/powermatcher/core/auctioneer/test/AuctioneerTest.java
fix core tests with new sessionManager
<ide><path>et.powermatcher.core/test/net/powermatcher/core/auctioneer/test/AuctioneerTest.java <ide> <ide> import static org.junit.Assert.*; <ide> <del>import java.util.ArrayList; <ide> import java.util.HashMap; <del>import java.util.List; <ide> import java.util.Map; <ide> import java.util.concurrent.ScheduledThreadPoolExecutor; <ide> <ide> /** <ide> * JUnit test for the Auctioneer <ide> * <del> * Every test requires a different number agents. In setUp() NR_AGENTS are instantiated. Every test the desired number <del> * of agents can be added and removed using the functions addAgents() and removeAgents(). <add> * Every test requires a different number agents. In setUp() NR_AGENTS are <add> * instantiated. Every test the desired number of agents can be added and <add> * removed using the functions addAgents() and removeAgents(). <ide> */ <ide> public class AuctioneerTest { <ide> <del> private final static int NR_AGENTS = 21; <del> <del> // This needs to be the same as the MarketBasis created in the Auctioneer <del> private final MarketBasis marketBasis = new MarketBasis("electricity", "EUR", 11, 0, 10); <del> private Map<String, Object> auctioneerProperties; <del> <del> private Auctioneer auctioneer; <del> private MockAgent[] agents; <del> <del> private SessionManager sessionManager; <del> <del> private static final String AUCTIONEER_NAME = "auctioneer"; <del> <del> @Before <del> public void setUp() throws Exception { <del> // Init Auctioneer <del> this.auctioneer = new Auctioneer(); <del> <del> auctioneerProperties = new HashMap<String, Object>(); <del> auctioneerProperties.put("agentId", AUCTIONEER_NAME); <del> auctioneerProperties.put("clusterId", "DefaultCluster"); <del> auctioneerProperties.put("matcherId", AUCTIONEER_NAME); <del> auctioneerProperties.put("commodity", "electricity"); <del> auctioneerProperties.put("currency", "EUR"); <del> auctioneerProperties.put("priceSteps", "11"); <del> auctioneerProperties.put("minimumPrice", "0"); <del> auctioneerProperties.put("maximumPrice", "10"); <del> auctioneerProperties.put("bidTimeout", "600"); <del> auctioneerProperties.put("priceUpdateRate", "1"); <del> <del> auctioneer.setExecutorService(new ScheduledThreadPoolExecutor(10)); <del> auctioneer.setTimeService(new SystemTimeService()); <del> auctioneer.activate(auctioneerProperties); <del> <del>// List<String> activeConnections = new ArrayList<String>(); <del> <del> // Init MockAgents <del> this.agents = new MockAgent[NR_AGENTS]; <del> for (int i = 0; i < NR_AGENTS; i++) { <del> String agentId = "agent" + (i + 1); <del> MockAgent newAgent = new MockAgent(agentId); <del> <del> newAgent.setDesiredParentId(AUCTIONEER_NAME); <del> <del> agents[i] = newAgent; <del> //activeConnections.add(agentId + "::" + "auctioneer"); <del> } <del> <del>// Map<String, Object> sessionProperties = new HashMap<String, Object>(); <del>// sessionProperties.put("activeConnections", activeConnections); <del> <del> // Session <del> sessionManager = new SessionManager(); <del> sessionManager.addMatcherRole(auctioneer); <del> sessionManager.activate(); <del> } <del> <del> private void addAgents(int number) { <del> for (int i = 0; i < number; i++) { <del> this.sessionManager.addAgentRole(agents[i]); <del> } <del> } <del> <del> private void removeAgents(int number) { <del> for (int i = 0; i < number; i++) { <del> this.sessionManager.removeAgentRole(agents[i]); <del> } <del> } <del> <del> @Test <del> public void noEquilibriumOnDemandSide() { <del> addAgents(3); <del> // run 1 <del> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); <del> auctioneer.publishNewPrice(); <del> assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> <del> // run 2 <del> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1 })); <del> auctioneer.publishNewPrice(); <del> assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> removeAgents(3); <del> } <del> <del> @Test <del> public void noEquilibriumOnSupplySide() { <del> addAgents(3); <del> // run 1 <del> agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3 })); <del> auctioneer.publishNewPrice(); <del> assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> <del> // run 2 <del> agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -4, -4, -4, -4, -4, -4 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -1, -1, -1, -3, -3, -3, -3 })); <del> auctioneer.publishNewPrice(); <del> assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> removeAgents(3); <del> } <del> <del> @Test <del> public void equilibriumSmallNumberOfBids() { <del> addAgents(3); <del> // run 1 <del> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, -5, -5, -5, -5, -5, -5 })); <del> auctioneer.publishNewPrice(); <del> assertEquals(5, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> <del> // run 2 <del> agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, -4, -4, -4, -4 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 })); <del> auctioneer.publishNewPrice(); <del> assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> removeAgents(3); <del> } <del> <del> @Test <del> @Ignore("Check whether there is no issue here. Changed to 7 in order to fix the tests. Original test value was 6.") <del> public void equilibriumLargeSet() { <del> addAgents(20); <del> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); <del> agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })); <del> agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); <del> agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); <del> agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0 })); <del> agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, -4, -4, -4, -4, -4 })); <del> agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 })); <del> agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2 })); <del> agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 })); <del> agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0 })); <del> agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, -6, -6, -6, -6, -6, -6 })); <del> agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); <del> agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 })); <del> agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, -8, -8, -8 })); <del> agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3 })); <del> agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 })); <del> agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -2, -2, -2, -2, -3, -3, -3 })); <del> agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0 })); <del> auctioneer.publishNewPrice(); <del> <del> assertEquals(6, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> removeAgents(20); <del> } <del> <del> @Test <del> public void equilibriumLargerSet() { <del> addAgents(21); <del> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 })); <del> agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 })); <del> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 })); <del> agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })); <del> agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); <del> agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); <del> agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0 })); <del> agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, -4, -4, -4, -4, -4 })); <del> agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 })); <del> agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2 })); <del> agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 })); <del> agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0 })); <del> agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, -6, -6, -6, -6, -6, -6 })); <del> agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); <del> agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 })); <del> agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, 0, 0, -8, -8, -8 })); <del> agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3 })); <del> agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 })); <del> agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, -2, -2, -2, -2, -3, -3, -3 })); <del> agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0 })); <del> agents[20].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 })); <del> auctioneer.publishNewPrice(); <del> assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <del> removeAgents(21); <del> } <del> <del> /* <del> * TODO: The behavior tested in this test is outside the scope of this version <del> * <del> * @Test public void rejectBid() { addAgents(4); agents[0].sendBid(new Bid(marketBasis, new double[] <del> * {5,5,5,5,5,5,5,5,5,5,5})); agents[1].sendBid(new Bid(marketBasis, new double[] {4,4,4,4,4,0,0,0,0,0,0})); <del> * agents[2].sendBid(new Bid(marketBasis, new double[] {0,0,0,0,0,-5,-5,-5,-5,-5,-5})); agents[3].sendBid(new <del> * Bid(marketBasis, new double[] {-9,-9,-9,-9, -9,1,1,1,1,1,1})); auctioneer.publishNewPrice(); assertEquals(5, <del> * agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(4); } <del> */ <add> private final static int NR_AGENTS = 21; <add> <add> // This needs to be the same as the MarketBasis created in the Auctioneer <add> private final MarketBasis marketBasis = new MarketBasis("electricity", <add> "EUR", 11, 0, 10); <add> private Map<String, Object> auctioneerProperties; <add> <add> private Auctioneer auctioneer; <add> private MockAgent[] agents; <add> <add> private SessionManager sessionManager; <add> <add> private static final String AUCTIONEER_NAME = "auctioneer"; <add> <add> @Before <add> public void setUp() throws Exception { <add> // Init Auctioneer <add> this.auctioneer = new Auctioneer(); <add> <add> auctioneerProperties = new HashMap<String, Object>(); <add> auctioneerProperties.put("agentId", AUCTIONEER_NAME); <add> auctioneerProperties.put("clusterId", "DefaultCluster"); <add> auctioneerProperties.put("matcherId", AUCTIONEER_NAME); <add> auctioneerProperties.put("commodity", "electricity"); <add> auctioneerProperties.put("currency", "EUR"); <add> auctioneerProperties.put("priceSteps", "11"); <add> auctioneerProperties.put("minimumPrice", "0"); <add> auctioneerProperties.put("maximumPrice", "10"); <add> auctioneerProperties.put("bidTimeout", "600"); <add> auctioneerProperties.put("priceUpdateRate", "1"); <add> <add> auctioneer.setExecutorService(new ScheduledThreadPoolExecutor(10)); <add> auctioneer.setTimeService(new SystemTimeService()); <add> auctioneer.activate(auctioneerProperties); <add> <add> // Init MockAgents <add> this.agents = new MockAgent[NR_AGENTS]; <add> for (int i = 0; i < NR_AGENTS; i++) { <add> String agentId = "agent" + (i + 1); <add> MockAgent newAgent = new MockAgent(agentId); <add> newAgent.setDesiredParentId(AUCTIONEER_NAME); <add> agents[i] = newAgent; <add> } <add> <add> // Session <add> sessionManager = new SessionManager(); <add> sessionManager.addMatcherRole(auctioneer); <add> sessionManager.activate(); <add> } <add> <add> private void addAgents(int number) { <add> for (int i = 0; i < number; i++) { <add> this.sessionManager.addAgentRole(agents[i]); <add> } <add> } <add> <add> private void removeAgents(int number) { <add> for (int i = 0; i < number; i++) { <add> this.sessionManager.removeAgentRole(agents[i]); <add> } <add> } <add> <add> @Test <add> public void noEquilibriumOnDemandSide() { <add> addAgents(3); <add> // run 1 <add> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, <add> 5, 5, 5, 5, 5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 4, <add> 4, 4, 4, 4, 4 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, <add> 3, 3, 3, 3, 3 })); <add> auctioneer.publishNewPrice(); <add> assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> <add> // run 2 <add> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, <add> 5, 5, 5, 5, 5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 2, <add> 2, 2, 2, 2, 2 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 1, <add> 1, 1, 1, 1, 1 })); <add> auctioneer.publishNewPrice(); <add> assertEquals(10, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> removeAgents(3); <add> } <add> <add> @Test <add> public void noEquilibriumOnSupplySide() { <add> addAgents(3); <add> // run 1 <add> agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, <add> -5, -5, -5, -5, -5, -5, -5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, <add> -4, -4, -4, -4, -4, -4, -4 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { -3, -3, -3, -3, <add> -3, -3, -3, -3, -3, -3, -3 })); <add> auctioneer.publishNewPrice(); <add> assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> <add> // run 2 <add> agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, <add> -5, -5, -5, -5, -5, -5, -5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, <add> -2, -4, -4, -4, -4, -4, -4 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, <add> -1, -1, -1, -3, -3, -3, -3 })); <add> auctioneer.publishNewPrice(); <add> assertEquals(0, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> removeAgents(3); <add> } <add> <add> @Test <add> public void equilibriumSmallNumberOfBids() { <add> addAgents(3); <add> // run 1 <add> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, <add> 5, 5, 5, 5, 5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, 0, <add> 0, 0, 0, 0, 0 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, <add> -5, -5, -5, -5, -5, -5 })); <add> auctioneer.publishNewPrice(); <add> assertEquals(5, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> <add> // run 2 <add> agents[0].sendBid(new Bid(marketBasis, new double[] { -5, -5, -5, -5, <add> -5, -5, -5, -5, -5, -5, -5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, <add> 0, -4, -4, -4, -4 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { 9, 9, 9, 9, 9, 9, <add> 9, 9, 9, 9, 9 })); <add> auctioneer.publishNewPrice(); <add> assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> removeAgents(3); <add> } <add> <add> @Test <add> @Ignore("Check whether there is no issue here. Changed to 7 in order to fix the tests. Original test value was 6.") <add> public void equilibriumLargeSet() { <add> addAgents(20); <add> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, <add> 5, 5, 5, 5, 5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, <add> -4, -4, -4, -4, -4, -4, -4 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, <add> 3, 3, 3, 3, 3 })); <add> agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, <add> -2, -2, -2, -2, -2, -2, -2 })); <add> agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1 })); <add> agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0 })); <add> agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, <add> 0, 0, 0, 0, 0 })); <add> agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, <add> -4, -4, -4, -4, -4 })); <add> agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, <add> 0, 0, 0, 0, 0 })); <add> agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, <add> -2, -2, -2, -2, -2, -2 })); <add> agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, <add> 1, 1, 0, 0, 0, 0 })); <add> agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, <add> 7, 7, 0, 0, 0, 0 })); <add> agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, <add> -6, -6, -6, -6, -6, -6 })); <add> agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, <add> 8, 8, 8, 8, 8, 8 })); <add> agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, <add> -9, -9, -9, -9, -9, -9, -9 })); <add> agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, <add> 0, 0, 0, -8, -8, -8 })); <add> agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, <add> 4, 3, 3, 3, 3, 3 })); <add> agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, <add> 1, 1, 1, 0, 0, 0 })); <add> agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, <add> -2, -2, -2, -2, -3, -3, -3 })); <add> agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, <add> 6, 0, 0, 0, 0, 0 })); <add> auctioneer.publishNewPrice(); <add> <add> assertEquals(6, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> removeAgents(20); <add> } <add> <add> @Test <add> public void equilibriumLargerSet() { <add> addAgents(21); <add> agents[0].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 5, <add> 5, 5, 5, 5, 5 })); <add> agents[1].sendBid(new Bid(marketBasis, new double[] { -4, -4, -4, -4, <add> -4, -4, -4, -4, -4, -4, -4 })); <add> agents[2].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 3, 3, <add> 3, 3, 3, 3, 3 })); <add> agents[3].sendBid(new Bid(marketBasis, new double[] { -2, -2, -2, -2, <add> -2, -2, -2, -2, -2, -2, -2 })); <add> agents[4].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1 })); <add> agents[5].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0 })); <add> agents[6].sendBid(new Bid(marketBasis, new double[] { 5, 5, 5, 5, 5, 0, <add> 0, 0, 0, 0, 0 })); <add> agents[7].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, 0, <add> -4, -4, -4, -4, -4 })); <add> agents[8].sendBid(new Bid(marketBasis, new double[] { 3, 3, 3, 3, 0, 0, <add> 0, 0, 0, 0, 0 })); <add> agents[9].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -2, -2, <add> -2, -2, -2, -2, -2, -2 })); <add> agents[10].sendBid(new Bid(marketBasis, new double[] { 1, 1, 1, 1, 1, <add> 1, 1, 0, 0, 0, 0 })); <add> agents[11].sendBid(new Bid(marketBasis, new double[] { 7, 7, 7, 7, 7, <add> 7, 7, 0, 0, 0, 0 })); <add> agents[12].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, -6, -6, <add> -6, -6, -6, -6, -6, -6 })); <add> agents[13].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, <add> 8, 8, 8, 8, 8, 8 })); <add> agents[14].sendBid(new Bid(marketBasis, new double[] { -9, -9, -9, -9, <add> -9, -9, -9, -9, -9, -9, -9 })); <add> agents[15].sendBid(new Bid(marketBasis, new double[] { 0, 0, 0, 0, 0, <add> 0, 0, 0, -8, -8, -8 })); <add> agents[16].sendBid(new Bid(marketBasis, new double[] { 4, 4, 4, 4, 4, <add> 4, 3, 3, 3, 3, 3 })); <add> agents[17].sendBid(new Bid(marketBasis, new double[] { 2, 2, 2, 2, 1, <add> 1, 1, 1, 0, 0, 0 })); <add> agents[18].sendBid(new Bid(marketBasis, new double[] { -1, -1, -1, -1, <add> -2, -2, -2, -2, -3, -3, -3 })); <add> agents[19].sendBid(new Bid(marketBasis, new double[] { 6, 6, 6, 6, 6, <add> 6, 0, 0, 0, 0, 0 })); <add> agents[20].sendBid(new Bid(marketBasis, new double[] { 8, 8, 8, 8, 8, <add> 8, 8, 8, 8, 8, 8 })); <add> auctioneer.publishNewPrice(); <add> assertEquals(7, agents[0].getLastPriceUpdate().getCurrentPrice(), 0); <add> removeAgents(21); <add> } <add> <add> /* <add> * TODO: The behavior tested in this test is outside the scope of this <add> * version <add> * <add> * @Test public void rejectBid() { addAgents(4); agents[0].sendBid(new <add> * Bid(marketBasis, new double[] {5,5,5,5,5,5,5,5,5,5,5})); <add> * agents[1].sendBid(new Bid(marketBasis, new double[] <add> * {4,4,4,4,4,0,0,0,0,0,0})); agents[2].sendBid(new Bid(marketBasis, new <add> * double[] {0,0,0,0,0,-5,-5,-5,-5,-5,-5})); agents[3].sendBid(new <add> * Bid(marketBasis, new double[] {-9,-9,-9,-9, -9,1,1,1,1,1,1})); <add> * auctioneer.publishNewPrice(); assertEquals(5, <add> * agents[0].getLastPriceUpdate().getCurrentPrice(), 0); removeAgents(4); } <add> */ <ide> <ide> }
Java
apache-2.0
599f2bbae2347caacb2f1f3a16d9f078530b4229
0
OpenConext/OpenConext-api,OpenConext/OpenConext-api
/* * Copyright 2012 SURFnet bv, The Netherlands * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.surfnet.coin.teams.service.impl; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import org.springframework.util.Assert; public abstract class AbstractGrouperDaoImpl { protected static String SQL_FIND_ALL_TEAMS_ROWCOUNT = "select count(distinct gg.name) " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + "and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) "; protected static String SQL_FIND_ALL_TEAMS = "select distinct gg.name, gg.display_name ,gg.description, " + "gs.name as stem_name, gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + " and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) " + "order by gg.name limit ? offset ?"; protected static String SQL_FIND_TEAMS_LIKE_GROUPNAME_ROWCOUNT = "select count(distinct gg.name) " + "from grouper_groups gg, grouper_stems gs, grouper_members gm," + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + " and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) " + "and upper(gg.name) like ?"; protected static String SQL_FIND_TEAMS_LIKE_GROUPNAME = "select distinct gg.name, gg.display_name ,gg.description, gs.name as stem_name, " + "gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm," + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + " and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) " + "and upper(gg.name) like ? order by gg.name limit ? offset ?"; protected static String SQL_FIND_ALL_TEAMS_BY_MEMBER_ROWCOUNT = "select count(distinct gg.name) from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? and gs.name != 'etc'"; protected static String SQL_FIND_ALL_TEAMS_BY_MEMBER = "select distinct gg.name, gg.display_name ,gg.description, gs.name as stem_name, gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, grouper_fields gf " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? " + "and gs.name != 'etc' " + "and gf.id = gms.field_id and gf.name = 'members' " + "order by gg.name limit ? offset ?"; protected static String SQL_FIND_TEAMS_BY_MEMBER_ROWCOUNT = "select count(distinct gg.name) " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? and upper(gg.name) like ?"; protected static String SQL_FIND_TEAMS_BY_MEMBER = "select distinct gg.name, gg.display_name ,gg.description, gs.name as stem_name, gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, grouper_fields gf " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? " + "and gs.name != 'etc' " + "and gf.id = gms.field_id and gf.name = 'members' " + "and upper(gg.name) like ? order by gg.name limit ? offset ?"; protected static String SQL_FIND_STEMS_BY_MEMBER = "select distinct gs.name, gs.display_name, gs.description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? " + "and gs.name != 'etc' "; protected static final String SQL_ROLES_BY_TEAMS = " select gf.name as fieldname, " + "gg.name as groupname from grouper_memberships gms, " + "grouper_groups gg, grouper_fields gf, " + " grouper_stems gs, grouper_members gm where " + " gms.field_id = gf.id and gms.owner_group_id = gg.id and " + " gms.member_id = gm.id " + " and gm.subject_id = ? " + " and gg.parent_stem = gs.id " + " and gs.name != 'etc' " + " and (gf.name = 'admins' or gf.name = 'updaters') order by gg.name "; /** * Pad a string with SQL wildcards * @param part the string to search for * @return padded string */ protected String wildCard(String part) { Assert.hasText(part); part = ("%" + part + "%").toUpperCase(); return part; } protected static final String SQL_ROLES_BY_TEAM_AND_MEMBERS = "select gm.subject_id as subject_id, " + "gf.name as fieldname, gg.name as groupname from grouper_memberships gms, " + "grouper_groups gg, grouper_fields gf, grouper_stems gs, grouper_members gm " + "where gms.field_id = gf.id and gms.owner_group_id = gg.id and gms.member_id = gm.id " + "and gg.parent_stem = gs.id and gs.name != 'etc' and subject_id in (?) " + "and (gf.name = 'admins' or gf.name = 'updaters') and gg.name = ? "; protected static final String SQL_MEMBERS_BY_TEAM = " select distinct gm.subject_id as subject_id " + "from grouper_memberships gms, grouper_groups gg, grouper_stems gs, " + "grouper_members gm where gms.owner_group_id = gg.id and gms.member_id = gm.id " + "and gg.parent_stem = gs.id and gs.name != 'etc' and gm.subject_id != 'GrouperSystem' " + "and gm.subject_id != 'GrouperAll' and gg.name = ? order by gm.subject_id limit ? offset ?"; protected static final String SQL_ADD_MEMBER_COUNT_TO_TEAMS = "select gg.name as groupname, " + "count(distinct gms.member_id) as membercount from " + " grouper_groups gg, grouper_stems gs, grouper_members gm, " + " grouper_memberships gms " + " where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gm.subject_type = 'person' " + " and gs.name != 'etc' " + " and gg.id in (select distinct(ggo.id) from grouper_groups ggo, grouper_members gmo, grouper_memberships gmso " + " where gmso.member_id = gmo.id and gmso.owner_group_id = ggo.id and gmo.subject_id = ?) " + " group by gg.name "; /** * Template method Row Mapper that only extracts the fields from the resultset, leaving creation * of a concrete group to implementations. * @param <T> the group class to create. */ public abstract static class GrouperRowMapper<T> implements RowMapper<T> { public abstract T createObj(String id, String name, String description); @Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { String id = rs.getString("name"); String name = rs.getString("display_name"); name = name.substring(name.lastIndexOf(':') + 1); String description = rs.getString("description"); return createObj(id, name, description); } } protected static int limitCheck(int limit) { return limit < 1 ? Integer.MAX_VALUE : limit; } }
coin-api-external-groups/src/main/java/nl/surfnet/coin/teams/service/impl/AbstractGrouperDaoImpl.java
/* * Copyright 2012 SURFnet bv, The Netherlands * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.surfnet.coin.teams.service.impl; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import org.springframework.util.Assert; public abstract class AbstractGrouperDaoImpl { protected static String SQL_FIND_ALL_TEAMS_ROWCOUNT = "select count(distinct gg.name) " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + "and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) "; protected static String SQL_FIND_ALL_TEAMS = "select distinct gg.name, gg.display_name ,gg.description, " + "gs.name as stem_name, gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + " and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) " + "order by gg.name limit ? offset ?"; protected static String SQL_FIND_TEAMS_LIKE_GROUPNAME_ROWCOUNT = "select count(distinct gg.name) " + "from grouper_groups gg, grouper_stems gs, grouper_members gm," + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + " and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) " + "and upper(gg.name) like ?"; protected static String SQL_FIND_TEAMS_LIKE_GROUPNAME = "select distinct gg.name, gg.display_name ,gg.description, gs.name as stem_name, " + "gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm," + "grouper_memberships gms, " + " grouper_fields gf, grouper_group_set ggs " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + " and gs.name != 'etc' " + " and ggs.field_id = gf.id " + " and gg.id = ggs.owner_group_id " + "and gms.owner_id = ggs.member_id " + " and gms.field_id = ggs.member_field_id " + "and ((gf.type = 'access' and gf.name = 'viewers') or gm.subject_id = ?) " + "and upper(gg.name) like ? order by gg.name limit ? offset ?"; protected static String SQL_FIND_ALL_TEAMS_BY_MEMBER_ROWCOUNT = "select count(distinct gg.name) from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? and gs.name != 'etc'"; protected static String SQL_FIND_ALL_TEAMS_BY_MEMBER = "select distinct gg.name, gg.display_name ,gg.description, gs.name as stem_name, gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, grouper_fields gf " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? " + "and gs.name != 'etc' " + "and gf.id = gms.field_id and gf.name = 'members' " + "order by gg.name limit ? offset ?"; protected static String SQL_FIND_TEAMS_BY_MEMBER_ROWCOUNT = "select count(distinct gg.name) " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? and upper(gg.name) like ?"; protected static String SQL_FIND_TEAMS_BY_MEMBER = "select distinct gg.name, gg.display_name ,gg.description, gs.name as stem_name, gs.display_name as stem_display_name, gs.description as stem_description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms, grouper_fields gf " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? " + "and gs.name != 'etc' " + "and gf.id = gms.field_id and gf.name = 'members' " + "and upper(gg.name) like ? order by gg.name limit ? offset ?"; protected static String SQL_FIND_STEMS_BY_MEMBER = "select distinct gs.name, gs.display_name, gs.description " + "from grouper_groups gg, grouper_stems gs, grouper_members gm, " + "grouper_memberships gms " + "where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " + "and gm.subject_id = ? " + "and gs.name != 'etc' "; protected static final String SQL_ROLES_BY_TEAMS = " select gf.name as fieldname, " + "gg.name as groupname from grouper_memberships gms, " + "grouper_groups gg, grouper_fields gf, " + " grouper_stems gs, grouper_members gm where " + " gms.field_id = gf.id and gms.owner_group_id = gg.id and " + " gms.member_id = gm.id " + " and gm.subject_id = ? " + " and gg.parent_stem = gs.id " + " and gs.name != 'etc' " + " and (gf.name = 'admins' or gf.name = 'updaters') order by gg.name "; /** * Pad a string with SQL wildcards * @param part the string to search for * @return padded string */ protected String wildCard(String part) { Assert.hasText(part); part = ("%" + part + "%").toUpperCase(); return part; } protected static final String SQL_ROLES_BY_TEAM_AND_MEMBERS = "select gm.subject_id as subject_id, " + "gf.name as fieldname, gg.name as groupname from grouper_memberships gms, " + "grouper_groups gg, grouper_fields gf, grouper_stems gs, grouper_members gm " + "where gms.field_id = gf.id and gms.owner_group_id = gg.id and gms.member_id = gm.id " + "and gg.parent_stem = gs.id and gs.name != 'etc' and subject_id in (?) " + "and (gf.name = 'admins' or gf.name = 'updaters') and gg.name = ? "; protected static final String SQL_MEMBERS_BY_TEAM = " select distinct gm.subject_id as subject_id " + "from grouper_memberships gms, grouper_groups gg, grouper_stems gs, " + "grouper_members gm where gms.owner_group_id = gg.id and gms.member_id = gm.id " + "and gg.parent_stem = gs.id and gs.name != 'etc' and gm.subject_id != 'GrouperSystem' " + "and gm.subject_id != 'GrouperAll' and gg.name = ? order by gm.subject_id limit ? offset ?"; /** * Template method Row Mapper that only extracts the fields from the resultset, leaving creation * of a concrete group to implementations. * @param <T> the group class to create. */ public abstract static class GrouperRowMapper<T> implements RowMapper<T> { public abstract T createObj(String id, String name, String description); @Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { String id = rs.getString("name"); String name = rs.getString("display_name"); name = name.substring(name.lastIndexOf(':') + 1); String description = rs.getString("description"); return createObj(id, name, description); } } protected static int limitCheck(int limit) { return limit < 1 ? Integer.MAX_VALUE : limit; } }
added query DD_MEMBER_COUNT_TO_TEAMS
coin-api-external-groups/src/main/java/nl/surfnet/coin/teams/service/impl/AbstractGrouperDaoImpl.java
added query DD_MEMBER_COUNT_TO_TEAMS
<ide><path>oin-api-external-groups/src/main/java/nl/surfnet/coin/teams/service/impl/AbstractGrouperDaoImpl.java <ide> "and gg.parent_stem = gs.id and gs.name != 'etc' and gm.subject_id != 'GrouperSystem' " + <ide> "and gm.subject_id != 'GrouperAll' and gg.name = ? order by gm.subject_id limit ? offset ?"; <ide> <add> protected static final String SQL_ADD_MEMBER_COUNT_TO_TEAMS = "select gg.name as groupname, " + <add> "count(distinct gms.member_id) as membercount from " <add> + " grouper_groups gg, grouper_stems gs, grouper_members gm, " <add> + " grouper_memberships gms " <add> + " where gg.parent_stem = gs.id and gms.member_id = gm.id and gms.owner_group_id = gg.id " <add> + " and gm.subject_type = 'person' " <add> + " and gs.name != 'etc' " <add> + " and gg.id in (select distinct(ggo.id) from grouper_groups ggo, grouper_members gmo, grouper_memberships gmso " <add> + " where gmso.member_id = gmo.id and gmso.owner_group_id = ggo.id and gmo.subject_id = ?) " <add> + " group by gg.name "; <add> <ide> /** <ide> * Template method Row Mapper that only extracts the fields from the resultset, leaving creation <ide> * of a concrete group to implementations.
JavaScript
mit
30c48af8453fbf5467c6f4e6be506d39cce016cf
0
CSTARS/poplar-3pg-model
var io = require('./lib/io'); var run = require('./lib/run')(io); module.exports = run; // test for npm
index.js
var io = require('./lib/io'); var run = require('./lib/run')(io); module.exports = run;
adding test for npm
index.js
adding test for npm
<ide><path>ndex.js <ide> <ide> <ide> module.exports = run; <add>// test for npm
Java
bsd-3-clause
6a5f945c473f43a5948d28bcd02bd5536936e1e5
0
jjj5311/PrisonPearl,BlackXnt/PrisonPearl,suirad/PrisonPearl,Civcraft/PrisonPearl
package com.untamedears.PrisonPearl; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.BlockState; import org.bukkit.block.DoubleChest; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.util.Vector; public class PrisonPearl { private short id; private String imprisonedname; private InventoryHolder holder; private Item item; public PrisonPearl(short id, String imprisonedname, InventoryHolder holder) { this.id = id; this.imprisonedname = imprisonedname; this.holder = holder; } public short getID() { return id; } public String getImprisonedName() { return imprisonedname; } public Player getImprisonedPlayer() { return Bukkit.getPlayerExact(imprisonedname); } public InventoryHolder getHolder() { return holder; } public Entity getHolderEntity() { if (holder instanceof Entity) return (Entity)holder; else return null; } public BlockState getHolderBlockState() { if (holder instanceof BlockState) { return (BlockState)holder; } else if (holder instanceof DoubleChest) { return (BlockState)((DoubleChest)holder).getLeftSide(); } else { return null; } } public Location getLocation() { if (holder != null) { if (holder instanceof Entity) { return ((Entity)holder).getLocation(); } else if (holder instanceof BlockState) { return ((BlockState)holder).getLocation(); } else if (holder instanceof DoubleChest) { return ((DoubleChest)holder).getLocation(); } else { System.err.println("PrisonPearl " + id + " has an unexpected holder: " + holder); return new Location(Bukkit.getWorlds().get(0), 0, 0, 0); } } else if (item != null) { return item.getLocation(); } else { System.err.println("PrisonPearl " + id + " has no holder nor item"); return new Location(Bukkit.getWorlds().get(0), 0, 0, 0); } } public String getHolderName() { Entity entity; BlockState state; if ((entity = getHolderEntity()) != null) { if (entity instanceof Player) { return ((Player)entity).getDisplayName(); } else { System.err.println("PrisonPearl " + id + " is held by a non-player entity"); return "an unknown entity"; } } else if ((state = getHolderBlockState()) != null) { switch (state.getType()) { case CHEST: return "a chest"; case FURNACE: return "a furnace"; case BREWING_STAND: return "a brewing stand"; case DISPENSER: return "a dispenser"; default: System.err.println("PrisonPearl " + id + " is inside an unknown block"); return "an unknown block"; } } else { System.err.println("PrisonPearl " + id + " has no holder nor item"); return "unknown"; } } public String describeLocation() { Location loc = getLocation(); Vector vec = loc.toVector(); String str = loc.getWorld().getName() + " " + vec.getBlockX() + " " + vec.getBlockY() + " " + vec.getBlockZ(); if (holder != null) return "held by " + getHolderName() + " at " + str; else return "located at " + str; } public void setHolder(InventoryHolder holder) { this.holder = holder; item = null; } public void setItem(Item item) { holder = null; this.item = item; } }
src/com/untamedears/PrisonPearl/PrisonPearl.java
package com.untamedears.PrisonPearl; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.BlockState; import org.bukkit.block.DoubleChest; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.util.Vector; public class PrisonPearl { private short id; private String imprisonedname; private InventoryHolder holder; private Item item; public PrisonPearl(short id, String imprisonedname, InventoryHolder holder) { this.id = id; this.imprisonedname = imprisonedname; this.holder = holder; } public short getID() { return id; } public String getImprisonedName() { return imprisonedname; } public Player getImprisonedPlayer() { return Bukkit.getPlayerExact(imprisonedname); } public InventoryHolder getHolder() { return holder; } public Entity getHolderEntity() { if (holder instanceof Entity) return (Entity)holder; else return null; } public BlockState getHolderBlockState() { if (holder instanceof BlockState) { return (BlockState)holder; } else if (holder instanceof DoubleChest) { return (BlockState)((DoubleChest)holder).getLeftSide(); } else { return null; } } public Location getLocation() { if (holder != null) { if (holder instanceof Entity) { return ((Entity)holder).getLocation(); } else if (holder instanceof BlockState) { return ((BlockState)holder).getLocation(); } else if (holder instanceof DoubleChest) { return ((DoubleChest)holder).getLocation(); } else { return null; // TODO log these } } else if (item != null) { return item.getLocation(); } else { return null; // TODO log these } } public String getHolderName() { Entity entity; BlockState state; if ((entity = getHolderEntity()) != null) { if (entity instanceof Player) { return ((Player)entity).getDisplayName(); } else { return "an unknown entity"; // TODO log these } } else if ((state = getHolderBlockState()) != null) { switch (state.getType()) { case CHEST: return "a chest"; case FURNACE: return "a furnace"; case BREWING_STAND: return "a brewing stand"; case DISPENSER: return "a dispenser"; default: return "an unknown block"; // TODO log these } } else { return null; // TODO log these (really shouldn't happen) } } public String describeLocation() { Location loc = getLocation(); Vector vec = loc.toVector(); String str = loc.getWorld().getName() + " " + vec.getBlockX() + " " + vec.getBlockY() + " " + vec.getBlockZ(); if (holder != null) return "held by " + getHolderName() + " at " + str; else return "located at " + str; } public void setHolder(InventoryHolder holder) { this.holder = holder; item = null; } public void setItem(Item item) { holder = null; this.item = item; } }
Cleaned up some TODOs in PrisonPearl
src/com/untamedears/PrisonPearl/PrisonPearl.java
Cleaned up some TODOs in PrisonPearl
<ide><path>rc/com/untamedears/PrisonPearl/PrisonPearl.java <ide> } else if (holder instanceof DoubleChest) { <ide> return ((DoubleChest)holder).getLocation(); <ide> } else { <del> return null; // TODO log these <add> System.err.println("PrisonPearl " + id + " has an unexpected holder: " + holder); <add> return new Location(Bukkit.getWorlds().get(0), 0, 0, 0); <ide> } <ide> } else if (item != null) { <ide> return item.getLocation(); <ide> } else { <del> return null; // TODO log these <add> System.err.println("PrisonPearl " + id + " has no holder nor item"); <add> return new Location(Bukkit.getWorlds().get(0), 0, 0, 0); <ide> } <ide> } <ide> <ide> if (entity instanceof Player) { <ide> return ((Player)entity).getDisplayName(); <ide> } else { <del> return "an unknown entity"; // TODO log these <add> System.err.println("PrisonPearl " + id + " is held by a non-player entity"); <add> return "an unknown entity"; <ide> } <ide> } else if ((state = getHolderBlockState()) != null) { <ide> switch (state.getType()) { <ide> case DISPENSER: <ide> return "a dispenser"; <ide> default: <del> return "an unknown block"; // TODO log these <add> System.err.println("PrisonPearl " + id + " is inside an unknown block"); <add> return "an unknown block"; <ide> } <ide> } else { <del> return null; // TODO log these (really shouldn't happen) <add> System.err.println("PrisonPearl " + id + " has no holder nor item"); <add> return "unknown"; <ide> } <ide> } <ide>
Java
lgpl-2.1
954c49fda48a6d18ff650846a9429d4a6312fb31
0
jimregan/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2020 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev.diff; import org.jetbrains.annotations.NotNull; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.Languages; import org.languagetool.rules.Rule; import org.languagetool.tools.StringTools; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; /** * Converts plain text results of Main or SentenceSourceChecker to HTML, sorted by rule id. */ public class ResultToHtml { private static final int THRESHOLD = 0; private final Map<String, String> ruleIdToCategoryId = new HashMap<>(); private FileWriter fw; public ResultToHtml(Language lang) { JLanguageTool lt = new JLanguageTool(lang); for (Rule rule : lt.getAllRules()) { ruleIdToCategoryId.put(rule.getId(), rule.getCategory().getId().toString()); } } public void run(String inputFile, String outputFile) throws IOException { try { fw = new FileWriter(outputFile); LightRuleMatchParser parser = new LightRuleMatchParser(); List<LightRuleMatch> matches = parser.parseOutput(new File(inputFile)); matches.sort((k, v) -> { String catIdK = getCategoryId(k); String catIdV = getCategoryId(v); if (catIdK.equals(catIdV)) { return k.getFullRuleId().compareTo(v.getFullRuleId()); } else { return catIdK.compareTo(catIdV); } } ); printHtml(inputFile, matches); } finally { fw.close(); } } private void printHtml(String filename, List<LightRuleMatch> matches) throws IOException { print("<!doctype html>"); print("<!-- generated by " + ResultToHtml.class.getSimpleName() + " on " + new Date() + " -->"); print("<html>"); print("<head>"); print(" <title>Sorted " + filename + "</title>"); print(" <meta http-equiv=\"content-type\" content=\"charset=utf-8\">"); print(" <style>"); print(" .sentence { color: #000; }"); print(" .message { color: #777; }"); print(" .marker { text-decoration: underline; background-color: #ffe8e8 }"); print(" li { margin-bottom: 8px; }"); print(" </style>"); print("</head>"); print("<body>"); print(matches.size() + " total matches<br>"); Map<String, Integer> matchToCount = getMatchToCount(matches); printToc(matches, matchToCount); String prevRuleId = ""; String prevCategoryId = ""; boolean listStarted = false; int skipped = 0; for (LightRuleMatch match : matches) { String categoryId = getCategoryId(match); if (!match.getFullRuleId().equals(prevRuleId)) { if (listStarted) { print("</ol>"); } if (!categoryId.equals(prevCategoryId)) { print("<h1>Category " + categoryId + "</h1>"); } Integer count = matchToCount.get(match.getFullRuleId()); if (count >= THRESHOLD) { String tempOff = match.getStatus() == LightRuleMatch.Status.temp_off ? "[temp_off]" : ""; print("<a name='" + match.getFullRuleId() + "'></a><h3>" + match.getFullRuleId() + " " + tempOff + " (" + count + " matches)</h3>"); print("Source: " + match.getRuleSource() + "<br><br>"); print("<ol>"); listStarted = true; } else { skipped++; } } print("<li>"); print(" <span class='message'>" + match.getMessage() + "</span><br>"); print(" <span class='sentence'>" + StringTools.escapeHTML(match.getContext()) .replaceFirst("&lt;span class='marker'&gt;", "<span class='marker'>") .replaceFirst("&lt;/span&gt;", "</span>") + "</span><br>"); print("</li>"); prevRuleId = match.getFullRuleId(); prevCategoryId = categoryId; } print("</ol>"); print("Note: " + skipped + " rules have been skipped because they matched fewer than " + THRESHOLD + " times"); print("</body>"); print("</html>"); } @NotNull private String getCategoryId(LightRuleMatch match) { String categoryId = ruleIdToCategoryId.get(match.getRuleId()); if (categoryId == null) { categoryId = "unknown"; // some rules cannot be mapped, as the rule ids might have changes since the input was generated } return categoryId; } private void printToc(List<LightRuleMatch> matches, Map<String, Integer> matchToCount) throws IOException { String prevRuleId = ""; String prevCategoryId = ""; print("<h1>TOC</h1>"); Map<String, Integer> rulesInCategory = new HashMap<>(); for (LightRuleMatch match : matches) { String ruleId = match.getFullRuleId(); String categoryId = getCategoryId(match); if (!ruleId.equals(prevRuleId)) { if (!categoryId.equals(prevCategoryId)) { printRulesInCategory(rulesInCategory); rulesInCategory.clear(); print("<h3>Category " + categoryId + "</h3>"); } Integer count = matchToCount.get(ruleId); if (count >= THRESHOLD) { rulesInCategory.put(ruleId, count); //print("<a href='#" + ruleId + "'>" + ruleId + " (" + count + ")</a><br>"); } } prevRuleId = ruleId; prevCategoryId = categoryId; } printRulesInCategory(rulesInCategory); print("<br>"); } private void printRulesInCategory(Map<String, Integer> rulesInCategory) throws IOException { if (rulesInCategory.size() > 0) { Map<String, Integer> sorted = rulesInCategory.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); for (Map.Entry<String, Integer> entry : sorted.entrySet()) { print("<a href='#" + entry.getKey() + "'>" + entry.getKey() + " (" + entry.getValue() + ")</a><br>"); } } } private Map<String, Integer> getMatchToCount(List<LightRuleMatch> matches) { Map<String, Integer> catToCount = new HashMap<>(); for (LightRuleMatch match : matches) { String id = match.getFullRuleId(); if (catToCount.containsKey(id)) { catToCount.put(id, catToCount.get(id) + 1); } else { catToCount.put(id, 1); } } return catToCount; } private void print(String s) throws IOException { //System.out.println(s); fw.write(s); fw.write('\n'); } public static void main(String[] args) throws IOException { if (args.length != 3) { System.out.println("Usage: " + ResultToHtml.class.getSimpleName() + " <langCode> <plainTextResult> <outputFile>"); System.out.println(" <plainTextResult> is the result of e.g. Main or SentenceSourceChecker"); System.exit(1); } ResultToHtml prg = new ResultToHtml(Languages.getLanguageForShortCode(args[0])); prg.run(args[1], args[2]); } }
languagetool-dev/src/main/java/org/languagetool/dev/diff/ResultToHtml.java
/* LanguageTool, a natural language style checker * Copyright (C) 2020 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev.diff; import org.jetbrains.annotations.NotNull; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.Languages; import org.languagetool.rules.Rule; import org.languagetool.tools.StringTools; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; /** * Converts plain text results of Main or SentenceSourceChecker to HTML, sorted by rule id. */ public class ResultToHtml { private static final int THRESHOLD = 0; private final Map<String, String> ruleIdToCategoryId = new HashMap<>(); private FileWriter fw; public ResultToHtml(Language lang) { JLanguageTool lt = new JLanguageTool(lang); for (Rule rule : lt.getAllRules()) { ruleIdToCategoryId.put(rule.getId(), rule.getCategory().getId().toString()); } } public void run(String inputFile, String outputFile) throws IOException { try { fw = new FileWriter(outputFile); LightRuleMatchParser parser = new LightRuleMatchParser(); List<LightRuleMatch> matches = parser.parseOutput(new File(inputFile)); matches.sort((k, v) -> { String catIdK = getCategoryId(k); String catIdV = getCategoryId(v); if (catIdK.equals(catIdV)) { return k.getFullRuleId().compareTo(v.getFullRuleId()); } else { return catIdK.compareTo(catIdV); } } ); printHtml(inputFile, matches); } finally { fw.close(); } } private void printHtml(String filename, List<LightRuleMatch> matches) throws IOException { print("<!doctype html>"); print("<!-- generated by " + ResultToHtml.class.getSimpleName() + " on " + new Date() + " -->"); print("<html>"); print("<head>"); print(" <title>Sorted " + filename + "</title>"); print(" <meta http-equiv=\"content-type\" content=\"charset=utf-8\">"); print(" <style>"); print(" .sentence { color: #000; }"); print(" .message { color: #777; }"); print(" .marker { text-decoration: underline; background-color: #ffe8e8 }"); print(" li { margin-bottom: 8px; }"); print(" </style>"); print("</head>"); print("<body>"); print(matches.size() + " total matches<br>"); Map<String, Integer> matchToCount = getMatchToCount(matches); printToc(matches, matchToCount); String prevRuleId = ""; String prevCategoryId = ""; boolean listStarted = false; int skipped = 0; for (LightRuleMatch match : matches) { String categoryId = getCategoryId(match); if (!match.getFullRuleId().equals(prevRuleId)) { if (listStarted) { print("</ol>"); } if (!categoryId.equals(prevCategoryId)) { print("<h1>Category " + categoryId + "</h1>"); } Integer count = matchToCount.get(match.getFullRuleId()); if (count >= THRESHOLD) { String tempOff = match.getStatus() == LightRuleMatch.Status.temp_off ? "[temp_off]" : ""; print("<a name='" + match.getFullRuleId() + "'></a><h3>" + match.getFullRuleId() + " " + tempOff + " (" + count + " matches)</h3>"); print("Source: " + match.getRuleSource() + "<br><br>"); print("<ol>"); listStarted = true; } else { skipped++; } } print("<li>"); print(" <span class='message'>" + match.getMessage() + "</span><br>"); print(" <span class='sentence'>" + StringTools.escapeHTML(match.getContext()) .replaceFirst("&lt;span class='marker'&gt;", "<span class='marker'>") .replaceFirst("&lt;/span&gt;", "</span>") + "</span><br>"); print("</li>"); prevRuleId = match.getFullRuleId(); prevCategoryId = categoryId; } print("</ol>"); print("Note: " + skipped + " rules have been skipped because they matched fewer than " + THRESHOLD + " times"); print("</body>"); print("</html>"); } @NotNull private String getCategoryId(LightRuleMatch match) { String categoryId = ruleIdToCategoryId.get(match.getRuleId()); if (categoryId == null) { categoryId = "unknown"; // some rules cannot be mapped, as the rule ids might have changes since the input was generated } return categoryId; } private void printToc(List<LightRuleMatch> matches, Map<String, Integer> matchToCount) throws IOException { String prevRuleId = ""; String prevCategoryId = ""; print("<h1>TOC</h1>"); Map<String, Integer> rulesInCategory = new HashMap<>(); for (LightRuleMatch match : matches) { String ruleId = match.getFullRuleId(); String categoryId = getCategoryId(match); if (!ruleId.equals(prevRuleId)) { if (!categoryId.equals(prevCategoryId)) { printRulesInCategory(rulesInCategory); rulesInCategory.clear(); print("<h3>Category " + categoryId + "</h3>"); } Integer count = matchToCount.get(ruleId); if (count >= THRESHOLD) { rulesInCategory.put(ruleId, count); //print("<a href='#" + ruleId + "'>" + ruleId + " (" + count + ")</a><br>"); } } prevRuleId = ruleId; prevCategoryId = categoryId; } printRulesInCategory(rulesInCategory); print("<br>"); } private void printRulesInCategory(Map<String, Integer> rulesInCategory) { if (rulesInCategory.size() > 0) { Map<String, Integer> sorted = rulesInCategory.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); sorted.forEach((k, v) -> { try { print("<a href='#" + k + "'>" + k + " (" + v + ")</a><br>"); } catch (IOException e) { e.printStackTrace(); } }); } } private Map<String, Integer> getMatchToCount(List<LightRuleMatch> matches) { Map<String, Integer> catToCount = new HashMap<>(); for (LightRuleMatch match : matches) { String id = match.getFullRuleId(); if (catToCount.containsKey(id)) { catToCount.put(id, catToCount.get(id) + 1); } else { catToCount.put(id, 1); } } return catToCount; } private void print(String s) throws IOException { //System.out.println(s); fw.write(s); fw.write('\n'); } public static void main(String[] args) throws IOException { if (args.length != 3) { System.out.println("Usage: " + ResultToHtml.class.getSimpleName() + " <langCode> <plainTextResult> <outputFile>"); System.out.println(" <plainTextResult> is the result of e.g. Main or SentenceSourceChecker"); System.exit(1); } ResultToHtml prg = new ResultToHtml(Languages.getLanguageForShortCode(args[0])); prg.run(args[1], args[2]); } }
ResultToHtml: throw IOexception
languagetool-dev/src/main/java/org/languagetool/dev/diff/ResultToHtml.java
ResultToHtml: throw IOexception
<ide><path>anguagetool-dev/src/main/java/org/languagetool/dev/diff/ResultToHtml.java <ide> print("<br>"); <ide> } <ide> <del> private void printRulesInCategory(Map<String, Integer> rulesInCategory) { <add> private void printRulesInCategory(Map<String, Integer> rulesInCategory) throws IOException { <ide> if (rulesInCategory.size() > 0) { <ide> Map<String, Integer> sorted = rulesInCategory.entrySet().stream() <ide> .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) <ide> .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); <del> sorted.forEach((k, v) -> { <del> try { <del> print("<a href='#" + k + "'>" + k + " (" + v + ")</a><br>"); <del> } catch (IOException e) { <del> e.printStackTrace(); <del> } <del> }); <add> for (Map.Entry<String, Integer> entry : sorted.entrySet()) { <add> print("<a href='#" + entry.getKey() + "'>" + entry.getKey() + " (" + entry.getValue() + ")</a><br>"); <add> } <ide> } <ide> } <ide>
JavaScript
mit
6bf4036fa06706e4e1c3ca4be42d9a6ac0d796cd
0
czarandy/mtgptresults,czarandy/mtgptresults,czarandy/mtgptresults
'use strict'; var _ = require('underscore'); var deepcopy = require('deepcopy'); var Helper = require('./../lib/helper.js'); var unidecode = require('unidecode'); module.exports = function(grunt) { function nameToID(name) { return unidecode(name).toLowerCase().replace(/[^a-z-]/g, '-'); } var _tournaments = null; function loadTournaments() { if (_tournaments) { return _tournaments; } _tournaments = {}; grunt.file.recurse('./data/', function(abspath, rootdir, subdir, filename) { if (filename.endsWith('.json')) { var tid = filename.replace('.json', ''); _tournaments[tid] = grunt.file.readJSON(abspath); _tournaments[tid].standings = _.map( _tournaments[tid].standings, function(p) { p.id = nameToID(p.name); return p; } ); } }); return _tournaments; } function jsonToStr(json) { return JSON.stringify(json, null, 4); } function buildTournaments() { grunt.file.write( './build/data/tournaments.js', 'window.Tournaments = ' + jsonToStr(loadTournaments()) ); } function buildRecent() { var tournaments = loadTournaments(); var list = []; _.each(tournaments, function(tournament) { var topN = tournament.team ? 12 : 8; var recent = deepcopy(tournament); recent.top = recent.standings.slice(0, topN); delete recent.standings; list.push(recent); }); grunt.file.write( './build/data/recent.js', 'window.Recent = ' + jsonToStr( _.sortBy(list, function(item) { return -Helper.getDate(item.date); }) ) ); } var _players = null; function loadPlayers() { if (_players) { return _players; } var tournaments = loadTournaments(); var players = {}; _.each(tournaments, function(tournament) { var standings = tournament.standings; _.each(standings, function(standing, index) { if (!(standing.id in players)) { players[standing.id] = { id: standing.id, name: standing.name, tournaments: [], stats: { money: 0, points: 0, total: 0, t1: 0, t8: 0, t16: 0 } }; } var finish = Helper.getPlayerIndex( index, tournament.team, tournament.team2hg ) + 1; var t = { finish: finish, propoints: standing.propoints, tid: tournament.id, money: standing.money }; if (standing.rank) { t.rank = standing.rank; } players[standing.id].tournaments.push(t); ++players[standing.id].stats.total; players[standing.id].stats.money += (standing.money || 0); players[standing.id].stats.points += (standing.propoints || 0); if (finish === 1) { ++players[standing.id].stats.t1; } if ((tournament.team && finish <= 4) || (!tournament.team && finish <= 8)) { ++players[standing.id].stats.t8; } if ((tournament.team && finish <= 8) || (!tournament.team && finish <= 16)) { ++players[standing.id].stats.t16; } }); }); players = _.mapObject(players, function(player) { if (player.stats.t8 > 0 && player.stats.total >= 10) { player.stats.t8pct = Math.floor(100 * player.stats.t8 / player.stats.total); } else { player.stats.t8pct = 0; } return { id: player.id, name: player.name, tournaments: _.sortBy(player.tournaments, function(tournament) { return -Helper.getDate(tournaments[tournament.tid].date); }), stats: player.stats }; }); _players = players; return _players; } function buildPlayers() { var players = loadPlayers(); grunt.file.write('./build/data/players.js', 'window.Players = ' + jsonToStr(players)); } function buildMetadata() { var players = loadPlayers(); var metadata = grunt.file.readJSON('./data/players.json'); _.each(players, function(player) { if (!metadata[player.name]) { grunt.log.writeln('Adding player: ' + player.name); metadata[player.name] = {}; } }); grunt.file.write('./data/players.json', jsonToStr(metadata)); } return { 'js': ['eslint', 'ava', 'browserify'], 'css': ['sass'], 'json': ['jsonlint'], 'tournaments': buildTournaments, 'players': buildPlayers, 'recent': buildRecent, 'metadata': buildMetadata, 'build-data': ['tournaments', 'players', 'recent'], 'default': ['build-data', 'copy', 'css', 'js', 'json'], 'serve': ['default', 'connect'], 'prod': ['default', 'uglify', 'gh-pages'] }; };
grunt/aliases.js
'use strict'; var _ = require('underscore'); var deepcopy = require('deepcopy'); var Helper = require('./../lib/helper.js'); var unidecode = require('unidecode'); module.exports = function(grunt) { function nameToID(name) { return unidecode(name).toLowerCase().replace(/[^a-z-]/g, '-'); } var _tournaments = null; function loadTournaments() { if (_tournaments) { return _tournaments; } _tournaments = {}; grunt.file.recurse('./data/', function(abspath, rootdir, subdir, filename) { if (filename.endsWith('.json')) { var tid = filename.replace('.json', ''); _tournaments[tid] = grunt.file.readJSON(abspath); _tournaments[tid].standings = _.map( _tournaments[tid].standings, function(p) { p.id = nameToID(p.name); return p; } ); } }); return _tournaments; } function jsonToStr(json) { return JSON.stringify(json, null, 4); } function buildTournaments() { grunt.file.write( './build/data/tournaments.js', 'window.Tournaments = ' + jsonToStr(loadTournaments()) ); } function buildRecent() { var tournaments = loadTournaments(); var list = []; _.each(tournaments, function(tournament) { var topN = tournament.team ? 12 : 8; var recent = deepcopy(tournament); recent.top = recent.standings.slice(0, topN); delete recent.standings; list.push(recent); }); grunt.file.write( './build/data/recent.js', 'window.Recent = ' + jsonToStr( _.sortBy(list, function(item) { return -Helper.getDate(item.date); }) ) ); } function buildPlayers() { var tournaments = loadTournaments(); var players = {}; _.each(tournaments, function(tournament) { var standings = tournament.standings; _.each(standings, function(standing, index) { if (!(standing.id in players)) { players[standing.id] = { id: standing.id, name: standing.name, tournaments: [], stats: { money: 0, points: 0, total: 0, t1: 0, t8: 0, t16: 0 } }; } var finish = Helper.getPlayerIndex( index, tournament.team, tournament.team2hg ) + 1; var t = { finish: finish, propoints: standing.propoints, tid: tournament.id, money: standing.money }; if (standing.rank) { t.rank = standing.rank; } players[standing.id].tournaments.push(t); ++players[standing.id].stats.total; players[standing.id].stats.money += (standing.money || 0); players[standing.id].stats.points += (standing.propoints || 0); if (finish === 1) { ++players[standing.id].stats.t1; } if ((tournament.team && finish <= 4) || (!tournament.team && finish <= 8)) { ++players[standing.id].stats.t8; } if ((tournament.team && finish <= 8) || (!tournament.team && finish <= 16)) { ++players[standing.id].stats.t16; } }); }); players = _.mapObject(players, function(player) { if (player.stats.t8 > 0 && player.stats.total >= 10) { player.stats.t8pct = Math.floor(100 * player.stats.t8 / player.stats.total); } else { player.stats.t8pct = 0; } return { id: player.id, name: player.name, tournaments: _.sortBy(player.tournaments, function(tournament) { return -Helper.getDate(tournaments[tournament.tid].date); }), stats: player.stats }; }); grunt.file.write('./build/data/players.js', 'window.Players = ' + jsonToStr(players)); } return { 'js': ['eslint', 'ava', 'browserify'], 'css': ['sass'], 'json': ['jsonlint'], 'tournaments': buildTournaments, 'players': buildPlayers, 'recent': buildRecent, 'build-data': ['tournaments', 'players', 'recent'], 'default': ['build-data', 'copy', 'css', 'js', 'json'], 'serve': ['default', 'connect'], 'prod': ['default', 'uglify', 'gh-pages'] }; };
added alias to build metadata
grunt/aliases.js
added alias to build metadata
<ide><path>runt/aliases.js <ide> ); <ide> } <ide> <del> function buildPlayers() { <add> var _players = null; <add> function loadPlayers() { <add> if (_players) { <add> return _players; <add> } <ide> var tournaments = loadTournaments(); <ide> var players = {}; <ide> _.each(tournaments, function(tournament) { <ide> stats: player.stats <ide> }; <ide> }); <add> _players = players; <add> return _players; <add> } <add> <add> function buildPlayers() { <add> var players = loadPlayers(); <ide> grunt.file.write('./build/data/players.js', 'window.Players = ' + jsonToStr(players)); <add> } <add> <add> function buildMetadata() { <add> var players = loadPlayers(); <add> var metadata = grunt.file.readJSON('./data/players.json'); <add> _.each(players, function(player) { <add> if (!metadata[player.name]) { <add> grunt.log.writeln('Adding player: ' + player.name); <add> metadata[player.name] = {}; <add> } <add> }); <add> grunt.file.write('./data/players.json', jsonToStr(metadata)); <ide> } <ide> <ide> return { <ide> 'tournaments': buildTournaments, <ide> 'players': buildPlayers, <ide> 'recent': buildRecent, <add> 'metadata': buildMetadata, <ide> 'build-data': ['tournaments', 'players', 'recent'], <ide> 'default': ['build-data', 'copy', 'css', 'js', 'json'], <ide> 'serve': ['default', 'connect'],
Java
apache-2.0
945379a5827cc11e9cf8d60b804608c33d8e2ff2
0
SjoerdvGestel/TravisCI-android-sample,SjoerdvGestel/TravisCI-android-sample
package com.afrogleap.travis.sample; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class ExampleUnitTest { @Before public void setUp() throws Exception { ShadowLog.stream = System.out; } @Test public void a0_shouldAlwaysPass() throws Exception { Assert.assertTrue(true); } @Test public void a1_calcTest() throws Exception { int val = 2+2+2; Assert.assertEquals(val, 6); } }
app/src/test/java/com/afrogleap/travis/sample/ExampleUnitTest.java
package com.afrogleap.travis.sample; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class ExampleUnitTest { @Before public void setUp() throws Exception { ShadowLog.stream = System.out; } @Test public void a0_shouldAlwaysPass() throws Exception { Assert.assertTrue(true); } @Test public void a1_calcTest() throws Exception { int val = 2+2+2; Assert.assertEquals(val, 7); //error } }
fixed test, now it should run till end
app/src/test/java/com/afrogleap/travis/sample/ExampleUnitTest.java
fixed test, now it should run till end
<ide><path>pp/src/test/java/com/afrogleap/travis/sample/ExampleUnitTest.java <ide> public void a1_calcTest() throws Exception { <ide> int val = 2+2+2; <ide> <del> Assert.assertEquals(val, 7); //error <add> Assert.assertEquals(val, 6); <ide> } <ide> }
Java
mit
26d0acd3bc263ee4517960e57675b0cb4976d64d
0
PLOS/wombat,PLOS/wombat,PLOS/wombat,PLOS/wombat
package org.ambraproject.wombat.service.remote; import com.google.common.base.Optional; import org.ambraproject.wombat.util.UrlParamBuilder; import org.apache.http.Header; import org.springframework.beans.factory.annotation.Autowired; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; public class ContentRepoServiceImpl implements ContentRepoService { @Autowired private SoaService soaService; @Autowired private CachedRemoteService<InputStream> cachedRemoteStreamer; private URI contentRepoAddress; private String repoBucketName; private void setRepoConfig() throws IOException { Map<String,Object> repoConfig = (Map<String, Object>) soaService.requestObject("config?type=repo", Map.class); Object address = repoConfig.get("contentRepoAddress"); if (address != null){ try { contentRepoAddress = new URI(address.toString()); } catch (URISyntaxException e) { throw new RuntimeException("Invalid content repo URI returned from service", e); } } Object bucket = repoConfig.get("repoBucketName"); if (bucket != null){ repoBucketName = bucket.toString(); } } private URI getContentRepoAddress() throws IOException { if (contentRepoAddress == null) { setRepoConfig(); if (contentRepoAddress == null) { throw new RuntimeException("No content repo URI returned from service"); } } return contentRepoAddress; } private String getRepoBucketName() throws IOException { if (repoBucketName == null) { setRepoConfig(); if (repoBucketName == null) { throw new RuntimeException("No repository bucket name returned from service"); } } return repoBucketName; } /** * Requests a file from the content repository. Returns the full response. * * @param key content repo key * @param version content repo version * @return the response from the content repo * @throws IOException * @throws org.ambraproject.wombat.service.EntityNotFoundException if the repository does not provide the file */ @Override public AssetServiceResponse request(String key, Optional<Integer> version, Header... headers) throws IOException { URI contentRepoAddress = getContentRepoAddress(); if ("file".equals(contentRepoAddress.getScheme())) { return requestInDevMode(contentRepoAddress, key, version); } String contentRepoAddressStr = contentRepoAddress.toString(); if (contentRepoAddressStr.endsWith("/")) { contentRepoAddressStr = contentRepoAddressStr.substring(0, contentRepoAddressStr.length() - 1); } UrlParamBuilder requestParams = UrlParamBuilder.params().add("key", key); if (version.isPresent()) { requestParams.add("version", version.get().toString()); } String repoBucketName = getRepoBucketName(); URI requestAddress = URI.create(String.format("%s/objects/%s?%s", contentRepoAddressStr, repoBucketName, requestParams.format())); return AssetServiceResponse.wrap(cachedRemoteStreamer.getResponse(requestAddress, headers)); } private AssetServiceResponse requestInDevMode(URI contentRepoAddress, String key, Optional<Integer> version) throws FileNotFoundException { File path = new File(contentRepoAddress.getPath(), key); return AssetServiceResponse.wrap(path); } }
src/main/java/org/ambraproject/wombat/service/remote/ContentRepoServiceImpl.java
package org.ambraproject.wombat.service.remote; import com.google.common.base.Optional; import org.ambraproject.wombat.util.UrlParamBuilder; import org.apache.http.Header; import org.springframework.beans.factory.annotation.Autowired; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; public class ContentRepoServiceImpl implements ContentRepoService { @Autowired private SoaService soaService; @Autowired private CachedRemoteService<InputStream> cachedRemoteStreamer; private URI contentRepoAddress; private String repoBucketName; private void setRepoConfig() throws IOException { Map<String,Object> repoConfig = (Map<String, Object>) soaService.requestObject("config?type=repo", Map.class); if (repoConfig.containsKey("contentRepoAddress")){ try { contentRepoAddress = new URI(repoConfig.get("contentRepoAddress").toString()); } catch (URISyntaxException e) { throw new RuntimeException("Invalid content repo URI returned from service", e); } } else { throw new RuntimeException("No content repo URI returned from service"); } if (repoConfig.containsKey("repoBucketName")){ repoBucketName = repoConfig.get("repoBucketName").toString(); } } private URI getContentRepoAddress() throws IOException { if (contentRepoAddress == null) { setRepoConfig(); } return contentRepoAddress; } private String getRepoBucketName() throws IOException { if (repoBucketName == null) { setRepoConfig(); if (repoBucketName == null) { throw new RuntimeException("No repository bucket name returned from service"); } } return repoBucketName; } /** * Requests a file from the content repository. Returns the full response. * * @param key content repo key * @param version content repo version * @return the response from the content repo * @throws IOException * @throws org.ambraproject.wombat.service.EntityNotFoundException if the repository does not provide the file */ @Override public AssetServiceResponse request(String key, Optional<Integer> version, Header... headers) throws IOException { URI contentRepoAddress = getContentRepoAddress(); if ("file".equals(contentRepoAddress.getScheme())) { return requestInDevMode(contentRepoAddress, key, version); } String contentRepoAddressStr = contentRepoAddress.toString(); if (contentRepoAddressStr.endsWith("/")) { contentRepoAddressStr = contentRepoAddressStr.substring(0, contentRepoAddressStr.length() - 1); } UrlParamBuilder requestParams = UrlParamBuilder.params().add("key", key); if (version.isPresent()) { requestParams.add("version", version.get().toString()); } String repoBucketName = getRepoBucketName(); URI requestAddress = URI.create(String.format("%s/objects/%s?%s", contentRepoAddressStr, repoBucketName, requestParams.format())); return AssetServiceResponse.wrap(cachedRemoteStreamer.getResponse(requestAddress, headers)); } private AssetServiceResponse requestInDevMode(URI contentRepoAddress, String key, Optional<Integer> version) throws FileNotFoundException { File path = new File(contentRepoAddress.getPath(), key); return AssetServiceResponse.wrap(path); } }
DPRO-100 refactored repo config retrieval to support Gson null value serialization
src/main/java/org/ambraproject/wombat/service/remote/ContentRepoServiceImpl.java
DPRO-100 refactored repo config retrieval to support Gson null value serialization
<ide><path>rc/main/java/org/ambraproject/wombat/service/remote/ContentRepoServiceImpl.java <ide> <ide> private void setRepoConfig() throws IOException { <ide> Map<String,Object> repoConfig = (Map<String, Object>) soaService.requestObject("config?type=repo", Map.class); <del> if (repoConfig.containsKey("contentRepoAddress")){ <add> Object address = repoConfig.get("contentRepoAddress"); <add> if (address != null){ <ide> try { <del> contentRepoAddress = new URI(repoConfig.get("contentRepoAddress").toString()); <add> contentRepoAddress = new URI(address.toString()); <ide> } catch (URISyntaxException e) { <ide> throw new RuntimeException("Invalid content repo URI returned from service", e); <ide> } <del> } else { <del> throw new RuntimeException("No content repo URI returned from service"); <ide> } <del> if (repoConfig.containsKey("repoBucketName")){ <del> repoBucketName = repoConfig.get("repoBucketName").toString(); <add> Object bucket = repoConfig.get("repoBucketName"); <add> if (bucket != null){ <add> repoBucketName = bucket.toString(); <ide> } <ide> <ide> } <ide> private URI getContentRepoAddress() throws IOException { <ide> if (contentRepoAddress == null) { <ide> setRepoConfig(); <add> if (contentRepoAddress == null) { <add> throw new RuntimeException("No content repo URI returned from service"); <add> } <ide> } <ide> return contentRepoAddress; <del> <ide> } <ide> <ide> private String getRepoBucketName() throws IOException {
Java
apache-2.0
32ed938538056da7eae61da231ea4e2d8867f002
0
powertac/powertac-core
/* * Copyright (c) 2012 by the original author * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powertac.samplebroker.core; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.pool.PooledConnectionFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.powertac.common.config.ConfigurableValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.connection.CachingConnectionFactory; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.MessageListener; import java.util.concurrent.Executor; /** * @author Nguyen Nguyen, John Collins */ @Service public class JmsManagementService { static private Logger log = LogManager.getLogger(JmsManagementService.class); @Resource(name = "jmsFactory") private ConnectionFactory connectionFactory; @Autowired private Executor taskExecutor; @Autowired private BrokerPropertiesService brokerPropertiesService; // configurable parameters private String serverQueueName = "serverInput"; private String jmsBrokerUrl = "tcp://localhost:61616"; // JMS artifacts private boolean connectionOpen = false; private DefaultMessageListenerContainer container; public void init (String overridenBrokerUrl, String serverQueueName) { brokerPropertiesService.configureMe(this); this.serverQueueName = serverQueueName; if (overridenBrokerUrl != null && !overridenBrokerUrl.isEmpty()) { setJmsBrokerUrl(overridenBrokerUrl); } ActiveMQConnectionFactory amqConnectionFactory = null; if (connectionFactory instanceof PooledConnectionFactory) { PooledConnectionFactory pooledConnectionFactory = (PooledConnectionFactory) connectionFactory; if (pooledConnectionFactory.getConnectionFactory() instanceof ActiveMQConnectionFactory) { amqConnectionFactory = (ActiveMQConnectionFactory) pooledConnectionFactory .getConnectionFactory(); } } else if (connectionFactory instanceof CachingConnectionFactory) { CachingConnectionFactory cachingConnectionFactory = (CachingConnectionFactory) connectionFactory; if (cachingConnectionFactory.getTargetConnectionFactory() instanceof ActiveMQConnectionFactory) { amqConnectionFactory = (ActiveMQConnectionFactory) cachingConnectionFactory .getTargetConnectionFactory(); } } if (amqConnectionFactory != null) { amqConnectionFactory.setBrokerURL(getJmsBrokerUrl()); Connection connection; try { connection = amqConnectionFactory.createConnection(); connection.start(); } catch (JMSException e) { // TODO Auto-generated catch block log.error(e.toString()); } } } public void registerMessageListener (MessageListener listener, String destinationName) { log.info("registerMessageListener(" + destinationName + ", " + listener + ")"); container = new DefaultMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setDestinationName(destinationName); container.setMessageListener(listener); container.setTaskExecutor(taskExecutor); container.afterPropertiesSet(); container.start(); } public synchronized void shutdown () { Runnable callback = new Runnable() { @Override public void run () { closeConnection(); } }; container.stop(callback); while (connectionOpen) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } private synchronized void closeConnection () { //session.close(); //connection.close(); connectionOpen = false; notifyAll(); } public String getServerQueueName () { return serverQueueName; } /** * @param serverQueueName the serverQueueName to set */ public void setServerQueueName (String serverQueueName) { this.serverQueueName = serverQueueName; } /** * @return the jmsBrokerUrl */ public String getJmsBrokerUrl () { return jmsBrokerUrl; } /** * @param jmsBrokerUrl the jmsBrokerUrl to set */ @ConfigurableValue(valueType = "String", description = "JMS broker URL to use") public void setJmsBrokerUrl (String jmsBrokerUrl) { this.jmsBrokerUrl = jmsBrokerUrl; } }
src/main/java/org/powertac/samplebroker/core/JmsManagementService.java
/* * Copyright (c) 2012 by the original author * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powertac.samplebroker.core; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.pool.PooledConnectionFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.powertac.common.config.ConfigurableValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.connection.CachingConnectionFactory; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.jms.ConnectionFactory; import javax.jms.MessageListener; import java.util.concurrent.Executor; /** * @author Nguyen Nguyen, John Collins */ @Service public class JmsManagementService { static private Logger log = LogManager.getLogger(JmsManagementService.class); @Resource(name = "jmsFactory") private ConnectionFactory connectionFactory; @Autowired private Executor taskExecutor; @Autowired private BrokerPropertiesService brokerPropertiesService; // configurable parameters private String serverQueueName = "serverInput"; private String jmsBrokerUrl = "tcp://localhost:61616"; // JMS artifacts private boolean connectionOpen = false; private DefaultMessageListenerContainer container; public void init (String overridenBrokerUrl, String serverQueueName) { brokerPropertiesService.configureMe(this); this.serverQueueName = serverQueueName; if (overridenBrokerUrl != null && !overridenBrokerUrl.isEmpty()) { setJmsBrokerUrl(overridenBrokerUrl); } ActiveMQConnectionFactory amqConnectionFactory = null; if (connectionFactory instanceof PooledConnectionFactory) { PooledConnectionFactory pooledConnectionFactory = (PooledConnectionFactory) connectionFactory; if (pooledConnectionFactory.getConnectionFactory() instanceof ActiveMQConnectionFactory) { amqConnectionFactory = (ActiveMQConnectionFactory) pooledConnectionFactory .getConnectionFactory(); } } else if (connectionFactory instanceof CachingConnectionFactory) { CachingConnectionFactory cachingConnectionFactory = (CachingConnectionFactory) connectionFactory; if (cachingConnectionFactory.getTargetConnectionFactory() instanceof ActiveMQConnectionFactory) { amqConnectionFactory = (ActiveMQConnectionFactory) cachingConnectionFactory .getTargetConnectionFactory(); } } if (amqConnectionFactory != null) { amqConnectionFactory.setBrokerURL(getJmsBrokerUrl()); } } public void registerMessageListener (MessageListener listener, String destinationName) { log.info("registerMessageListener(" + destinationName + ", " + listener + ")"); container = new DefaultMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setDestinationName(destinationName); container.setMessageListener(listener); container.setTaskExecutor(taskExecutor); container.afterPropertiesSet(); container.start(); } public synchronized void shutdown () { Runnable callback = new Runnable() { @Override public void run () { closeConnection(); } }; container.stop(callback); while (connectionOpen) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } private synchronized void closeConnection () { //session.close(); //connection.close(); connectionOpen = false; notifyAll(); } public String getServerQueueName () { return serverQueueName; } /** * @param serverQueueName the serverQueueName to set */ public void setServerQueueName (String serverQueueName) { this.serverQueueName = serverQueueName; } /** * @return the jmsBrokerUrl */ public String getJmsBrokerUrl () { return jmsBrokerUrl; } /** * @param jmsBrokerUrl the jmsBrokerUrl to set */ @ConfigurableValue(valueType = "String", description = "JMS broker URL to use") public void setJmsBrokerUrl (String jmsBrokerUrl) { this.jmsBrokerUrl = jmsBrokerUrl; } }
resolve obscure, intermittent amq error
src/main/java/org/powertac/samplebroker/core/JmsManagementService.java
resolve obscure, intermittent amq error
<ide><path>rc/main/java/org/powertac/samplebroker/core/JmsManagementService.java <ide> import org.springframework.stereotype.Service; <ide> <ide> import javax.annotation.Resource; <add>import javax.jms.Connection; <ide> import javax.jms.ConnectionFactory; <add>import javax.jms.JMSException; <ide> import javax.jms.MessageListener; <add> <ide> import java.util.concurrent.Executor; <ide> <ide> <ide> <ide> if (amqConnectionFactory != null) { <ide> amqConnectionFactory.setBrokerURL(getJmsBrokerUrl()); <add> Connection connection; <add> try { <add> connection = amqConnectionFactory.createConnection(); <add> connection.start(); <add> } <add> catch (JMSException e) { <add> // TODO Auto-generated catch block <add> log.error(e.toString()); <add> } <ide> } <ide> } <ide>
Java
apache-2.0
0b08bfc732c3a52cf2a424bbd4af0785385fc2f3
0
UnderwaterApps/submarine,zepplondon/submarine
package com.submarine.chartboost; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import org.robovm.apple.uikit.UIViewController; import org.robovm.pods.chartboost.*; import java.util.ArrayList; /** * Created by mariam on 1/11/16. */ public class IOSChartBoost implements ChartBoostListener { private ChartboostDelegate chartboostDelegate; public IOSChartBoost(final IOSApplication.Delegate appDelegate) { initDelegate(appDelegate); } @Override public void onCreate(String appId, String appSignature, ArrayList<String> locations) { Chartboost.start(appId, appSignature, chartboostDelegate); Chartboost.setAutoCacheAds(true); // Chartboost.setShouldRequestInterstitialsInFirstSession(false); for (String location : locations) { System.out.println("name: "+location); Chartboost.cacheInterstitial(location); } System.out.println("cache more apps!"); Chartboost.cacheMoreApps(CBLocation.Default); } @Override public boolean hasInterstitial(String locationName) { return Chartboost.hasInterstitial(locationName); } @Override public void showInterstisial(String locationName) { System.out.println("show "+locationName+" interstitial"); Chartboost.showInterstitial(locationName); } @Override public void cacheInterstisial(String locationName) { Chartboost.cacheInterstitial(locationName); } @Override public void showMoreApps() { System.out.println("show more apps"); Chartboost.showMoreApps(CBLocation.Default); } @Override public void cacheMoreApps() { Chartboost.cacheMoreApps(CBLocation.Default); } @Override public void onStart() { } @Override public void onResume() { } @Override public void onPause() { } @Override public void onStop() { } @Override public void onDestroy() { } @Override public boolean onBackPressed() { return false; } private void initDelegate(final IOSApplication.Delegate applicationDelegate) { chartboostDelegate = new ChartboostDelegateAdapter() { /** * This is used to control when an interstitial should or * should not be displayed The default is true, and that * will let an interstitial display as normal If it's not * okay to display an interstitial, return false. * <p/> * For example: during gameplay, return false. * <p/> * Is fired on: -Interstitial is loaded & ready to display */ @Override public boolean shouldDisplayInterstitial(String location) { System.out.println("about to display interstitial at location " + location); // For example: // if the user has left the main menu and is currently // playing your game, return false; // Otherwise return true to display the interstitial return true; } @Override public boolean shouldDisplayMoreApps(String location) { return true; } @Override public boolean shouldDisplayRewardedVideo(String location) { return true; } @Override public boolean shouldRequestInterstitial(String location) { return true; } /** * This is called when an interstitial has failed to load. * The error enum specifies the reason of the failure */ @Override public void didFailToLoadInterstitial(String location, CBLoadError error) { switch (error) { case InternetUnavailable: System.out.println("Failed to load Interstitial, no Internet connection !"); break; case Internal: System.out.println("Failed to load Interstitial, internal error !"); break; case NetworkFailure: System.out.println("Failed to load Interstitial, network error !"); break; case WrongOrientation: System.out.println("Failed to load Interstitial, wrong orientation !"); break; case TooManyConnections: System.out.println("Failed to load Interstitial, too many connections !"); break; case FirstSessionInterstitialsDisabled: System.out.println("Failed to load Interstitial, first session !"); break; case NoAdFound: System.out.println("Failed to load Interstitial, no ad found !"); break; case SessionNotStarted: System.out.println("Failed to load Interstitial, session not started !"); break; case NoLocationFound: System.out.println("Failed to load Interstitial, missing location parameter !"); break; default: System.out.println("Failed to load Interstitial, unknown error !"); break; } } /** * Passes in the location name that has successfully been * cached. * <p/> * Is fired on: - All assets loaded - Triggered by * cacheInterstitial * <p/> * Notes: - Similar to this is: * (BOOL)hasCachedInterstitial:(NSString *)location; Which * will return true if a cached interstitial exists for that * location */ @Override public void didCacheInterstitial(String location) { System.out.println("interstitial cached at location " + location); } /** * This is called when the more apps page has failed to load * for any reason * <p/> * Is fired on: - No network connection - No more apps page * has been created (add a more apps page in the dashboard) * - No publishing campaign matches for that user (add more * campaigns to your more apps page) -Find this inside the * App > Edit page in the Chartboost dashboard */ @Override public void didFailToLoadMoreApps(CBLoadError error) { switch (error) { case InternetUnavailable: System.out.println("Failed to load More Apps, no Internet connection !"); break; case Internal: System.out.println("Failed to load More Apps, internal error !"); break; case NetworkFailure: System.out.println("Failed to load More Apps, network error !"); break; case WrongOrientation: System.out.println("Failed to load More Apps, wrong orientation !"); break; case TooManyConnections: System.out.println("Failed to load More Apps, too many connections !"); break; case FirstSessionInterstitialsDisabled: System.out.println("Failed to load More Apps, first session !"); break; case NoAdFound: System.out.println("Failed to load More Apps, no ad found !"); break; case SessionNotStarted: System.out.println("Failed to load More Apps, session not started !"); break; case NoLocationFound: System.out.println("Failed to load More Apps, missing location parameter !"); break; default: System.out.println("Failed to load More Apps, unknown error !"); break; } } /** * This is called when an interstitial is dismissed * <p/> * Is fired on: - Interstitial click - Interstitial close */ @Override public void didDismissInterstitial(String location) { System.out.println("dismissed interstitial at location " + location); } /** * This is called when the more apps page is dismissed * <p/> * Is fired on: - More Apps click - More Apps close */ @Override public void didDismissMoreApps(String location) { System.out.println("dismissed more apps page at location " + location); } /** * This is called when a rewarded video has been viewed * <p/> * Is fired on: - Rewarded video completed view */ @Override public void didCompleteRewardedVideo(String location, int reward) { System.out.println(String.format( "completed rewarded video view at location %s with reward amount %d", location, reward)); } /* * * This is called when a Rewarded Video has failed to load. * The error enum specifies the reason of the failure */ @Override public void didFailToLoadRewardedVideo(String location, CBLoadError error) { switch (error) { case InternetUnavailable: System.out.println("Failed to load Rewarded Video, no Internet connection !"); break; case Internal: System.out.println("Failed to load Rewarded Video, internal error !"); break; case NetworkFailure: System.out.println("Failed to load Rewarded Video, network error !"); break; case WrongOrientation: System.out.println("Failed to load Rewarded Video, wrong orientation !"); break; case TooManyConnections: System.out.println("Failed to load Rewarded Video, too many connections !"); break; case FirstSessionInterstitialsDisabled: System.out.println("Failed to load Rewarded Video, first session !"); break; case NoAdFound: System.out.println("Failed to load Rewarded Video, no ad found !"); break; case SessionNotStarted: System.out.println("Failed to load Rewarded Video, session not started !"); break; case NoLocationFound: System.out.println("Failed to load Rewarded Video, missing location parameter !"); break; default: System.out.println("Failed to load Rewarded Video, unknown error !"); break; } } /** * Called after an interstitial has been displayed on the * screen. */ @Override public void didDisplayInterstitial(String location) { System.out.println("Did display interstitial"); // We might want to pause our in-game audio, lets double check that an ad is visible if (Chartboost.isAnyViewVisible()) { // Use this function anywhere in your logic where // you need to know if an ad is visible or not. System.out.println("Pause audio"); } } /** * Called after an InPlay object has been loaded from the * Chartboost API servers and cached locally. * <p/> * Implement to be notified of when an InPlay object has * been loaded from the Chartboost API servers and cached * locally for a given CBLocation. * * @param location The location for the Chartboost * impression type. */ @Override public void didCacheInPlay(String location) { System.out.println("Successfully cached inPlay"); UIViewController vc = applicationDelegate.getWindow().getRootViewController(); // vc.renderInPlay(Chartboost.getInPlay(location)); //TODO uncomment and fix the line above } /** * Called after a InPlay has attempted to load from the * Chartboost API servers but failed. * <p/> * Implement to be notified of when an InPlay has attempted * to load from the Chartboost API servers but failed for a * given CBLocation. * * @param location The location for the Chartboost * impression type. * @param error The reason for the error defined via a * CBLoadError. */ @Override public void didFailToLoadInPlay(String location, CBLoadError error) { String errorString = ""; switch (error) { case InternetUnavailable: errorString = "Failed to load In Play, no Internet connection !"; break; case Internal: errorString = "Failed to load In Play, internal error !"; break; case NetworkFailure: errorString = "Failed to load In Play, network error !"; break; case WrongOrientation: errorString = "Failed to load In Play, wrong orientation !"; break; case TooManyConnections: errorString = "Failed to load In Play, too many connections !"; break; case FirstSessionInterstitialsDisabled: errorString = "Failed to load In Play, first session !"; break; case NoAdFound: errorString = "Failed to load In Play, no ad found !"; break; case SessionNotStarted: errorString = "Failed to load In Play, session not started !"; break; case NoLocationFound: errorString = "Failed to load In Play, missing location parameter !"; break; default: errorString = "Failed to load In Play, unknown error !"; break; } System.out.println(errorString); UIViewController vc = applicationDelegate.getWindow().getRootViewController(); // vc.renderInPlayError(errorString); //TODO uncomment and fix the line above } }; } }
chartboost/ios/src/com/submarine/chartboost/IOSChartBoost.java
package com.submarine.chartboost; import org.robovm.pods.chartboost.CBLocation; import org.robovm.pods.chartboost.Chartboost; import org.robovm.pods.chartboost.ChartboostDelegate; import java.util.ArrayList; /** * Created by mariam on 1/11/16. */ public class IOSChartBoost implements ChartBoostListener { private ChartboostDelegate delegate; public IOSChartBoost(ChartboostDelegate delegate) { this.delegate = delegate; } @Override public void onCreate(String appId, String appSignature, ArrayList<String> locations) { Chartboost.start(appId, appSignature, delegate); // Chartboost.setShouldRequestInterstitialsInFirstSession(false); for (String location : locations) { System.out.println("name: "+location); Chartboost.cacheInterstitial(location); } System.out.println("cache more apps!"); Chartboost.cacheMoreApps(CBLocation.Default); } @Override public boolean hasInterstitial(String locationName) { return Chartboost.hasInterstitial(locationName); } @Override public void showInterstisial(String locationName) { System.out.println("show "+locationName+" interstitial"); Chartboost.showInterstitial(locationName); } @Override public void cacheInterstisial(String locationName) { Chartboost.cacheInterstitial(locationName); } @Override public void showMoreApps() { System.out.println("show more apps"); Chartboost.showMoreApps(CBLocation.Default); } @Override public void cacheMoreApps() { Chartboost.cacheMoreApps(CBLocation.Default); } @Override public void onStart() { } @Override public void onResume() { } @Override public void onPause() { } @Override public void onStop() { } @Override public void onDestroy() { } @Override public boolean onBackPressed() { return false; } }
move chartboost func to submarine
chartboost/ios/src/com/submarine/chartboost/IOSChartBoost.java
move chartboost func to submarine
<ide><path>hartboost/ios/src/com/submarine/chartboost/IOSChartBoost.java <ide> package com.submarine.chartboost; <ide> <del>import org.robovm.pods.chartboost.CBLocation; <del>import org.robovm.pods.chartboost.Chartboost; <del>import org.robovm.pods.chartboost.ChartboostDelegate; <add>import com.badlogic.gdx.backends.iosrobovm.IOSApplication; <add>import org.robovm.apple.uikit.UIViewController; <add>import org.robovm.pods.chartboost.*; <ide> <ide> import java.util.ArrayList; <ide> <ide> */ <ide> public class IOSChartBoost implements ChartBoostListener { <ide> <del> private ChartboostDelegate delegate; <del> <del> public IOSChartBoost(ChartboostDelegate delegate) { <del> this.delegate = delegate; <add> private ChartboostDelegate chartboostDelegate; <add> <add> public IOSChartBoost(final IOSApplication.Delegate appDelegate) { <add> initDelegate(appDelegate); <add> <ide> } <ide> <ide> @Override <ide> public void onCreate(String appId, String appSignature, ArrayList<String> locations) { <ide> <del> Chartboost.start(appId, appSignature, delegate); <add> Chartboost.start(appId, appSignature, chartboostDelegate); <add> Chartboost.setAutoCacheAds(true); <ide> // Chartboost.setShouldRequestInterstitialsInFirstSession(false); <ide> <ide> for (String location : locations) { <ide> return false; <ide> } <ide> <add> private void initDelegate(final IOSApplication.Delegate applicationDelegate) { <add> chartboostDelegate = new ChartboostDelegateAdapter() { <add> /** <add> * This is used to control when an interstitial should or <add> * should not be displayed The default is true, and that <add> * will let an interstitial display as normal If it's not <add> * okay to display an interstitial, return false. <add> * <p/> <add> * For example: during gameplay, return false. <add> * <p/> <add> * Is fired on: -Interstitial is loaded & ready to display <add> */ <add> @Override <add> public boolean shouldDisplayInterstitial(String location) { <add> System.out.println("about to display interstitial at location " + location); <add> <add> // For example: <add> // if the user has left the main menu and is currently <add> // playing your game, return false; <add> <add> // Otherwise return true to display the interstitial <add> return true; <add> } <add> <add> <add> @Override <add> public boolean shouldDisplayMoreApps(String location) { <add> return true; <add> } <add> <add> @Override <add> public boolean shouldDisplayRewardedVideo(String location) { <add> return true; <add> } <add> <add> @Override <add> public boolean shouldRequestInterstitial(String location) { <add> return true; <add> } <add> <add> /** <add> * This is called when an interstitial has failed to load. <add> * The error enum specifies the reason of the failure <add> */ <add> @Override <add> public void didFailToLoadInterstitial(String location, CBLoadError error) { <add> switch (error) { <add> case InternetUnavailable: <add> System.out.println("Failed to load Interstitial, no Internet connection !"); <add> break; <add> case Internal: <add> System.out.println("Failed to load Interstitial, internal error !"); <add> break; <add> case NetworkFailure: <add> System.out.println("Failed to load Interstitial, network error !"); <add> break; <add> case WrongOrientation: <add> System.out.println("Failed to load Interstitial, wrong orientation !"); <add> break; <add> case TooManyConnections: <add> System.out.println("Failed to load Interstitial, too many connections !"); <add> break; <add> case FirstSessionInterstitialsDisabled: <add> System.out.println("Failed to load Interstitial, first session !"); <add> break; <add> case NoAdFound: <add> System.out.println("Failed to load Interstitial, no ad found !"); <add> break; <add> case SessionNotStarted: <add> System.out.println("Failed to load Interstitial, session not started !"); <add> break; <add> case NoLocationFound: <add> System.out.println("Failed to load Interstitial, missing location parameter !"); <add> break; <add> default: <add> System.out.println("Failed to load Interstitial, unknown error !"); <add> break; <add> } <add> } <add> <add> /** <add> * Passes in the location name that has successfully been <add> * cached. <add> * <p/> <add> * Is fired on: - All assets loaded - Triggered by <add> * cacheInterstitial <add> * <p/> <add> * Notes: - Similar to this is: <add> * (BOOL)hasCachedInterstitial:(NSString *)location; Which <add> * will return true if a cached interstitial exists for that <add> * location <add> */ <add> @Override <add> public void didCacheInterstitial(String location) { <add> System.out.println("interstitial cached at location " + location); <add> } <add> <add> /** <add> * This is called when the more apps page has failed to load <add> * for any reason <add> * <p/> <add> * Is fired on: - No network connection - No more apps page <add> * has been created (add a more apps page in the dashboard) <add> * - No publishing campaign matches for that user (add more <add> * campaigns to your more apps page) -Find this inside the <add> * App > Edit page in the Chartboost dashboard <add> */ <add> @Override <add> public void didFailToLoadMoreApps(CBLoadError error) { <add> switch (error) { <add> case InternetUnavailable: <add> System.out.println("Failed to load More Apps, no Internet connection !"); <add> break; <add> case Internal: <add> System.out.println("Failed to load More Apps, internal error !"); <add> break; <add> case NetworkFailure: <add> System.out.println("Failed to load More Apps, network error !"); <add> break; <add> case WrongOrientation: <add> System.out.println("Failed to load More Apps, wrong orientation !"); <add> break; <add> case TooManyConnections: <add> System.out.println("Failed to load More Apps, too many connections !"); <add> break; <add> case FirstSessionInterstitialsDisabled: <add> System.out.println("Failed to load More Apps, first session !"); <add> break; <add> case NoAdFound: <add> System.out.println("Failed to load More Apps, no ad found !"); <add> break; <add> case SessionNotStarted: <add> System.out.println("Failed to load More Apps, session not started !"); <add> break; <add> case NoLocationFound: <add> System.out.println("Failed to load More Apps, missing location parameter !"); <add> break; <add> default: <add> System.out.println("Failed to load More Apps, unknown error !"); <add> break; <add> } <add> } <add> <add> /** <add> * This is called when an interstitial is dismissed <add> * <p/> <add> * Is fired on: - Interstitial click - Interstitial close <add> */ <add> @Override <add> public void didDismissInterstitial(String location) { <add> System.out.println("dismissed interstitial at location " + location); <add> } <add> <add> /** <add> * This is called when the more apps page is dismissed <add> * <p/> <add> * Is fired on: - More Apps click - More Apps close <add> */ <add> @Override <add> public void didDismissMoreApps(String location) { <add> System.out.println("dismissed more apps page at location " + location); <add> } <add> <add> /** <add> * This is called when a rewarded video has been viewed <add> * <p/> <add> * Is fired on: - Rewarded video completed view <add> */ <add> @Override <add> public void didCompleteRewardedVideo(String location, int reward) { <add> System.out.println(String.format( <add> "completed rewarded video view at location %s with reward amount %d", location, reward)); <add> } <add> <add> /* <add> * <add> * This is called when a Rewarded Video has failed to load. <add> * The error enum specifies the reason of the failure <add> */ <add> @Override <add> public void didFailToLoadRewardedVideo(String location, CBLoadError error) { <add> switch (error) { <add> case InternetUnavailable: <add> System.out.println("Failed to load Rewarded Video, no Internet connection !"); <add> break; <add> case Internal: <add> System.out.println("Failed to load Rewarded Video, internal error !"); <add> break; <add> case NetworkFailure: <add> System.out.println("Failed to load Rewarded Video, network error !"); <add> break; <add> case WrongOrientation: <add> System.out.println("Failed to load Rewarded Video, wrong orientation !"); <add> break; <add> case TooManyConnections: <add> System.out.println("Failed to load Rewarded Video, too many connections !"); <add> break; <add> case FirstSessionInterstitialsDisabled: <add> System.out.println("Failed to load Rewarded Video, first session !"); <add> break; <add> case NoAdFound: <add> System.out.println("Failed to load Rewarded Video, no ad found !"); <add> break; <add> case SessionNotStarted: <add> System.out.println("Failed to load Rewarded Video, session not started !"); <add> break; <add> case NoLocationFound: <add> System.out.println("Failed to load Rewarded Video, missing location parameter !"); <add> break; <add> default: <add> System.out.println("Failed to load Rewarded Video, unknown error !"); <add> break; <add> } <add> } <add> <add> /** <add> * Called after an interstitial has been displayed on the <add> * screen. <add> */ <add> @Override <add> public void didDisplayInterstitial(String location) { <add> System.out.println("Did display interstitial"); <add> <add>// We might want to pause our in-game audio, lets double check that an ad is visible <add> if (Chartboost.isAnyViewVisible()) { <add> // Use this function anywhere in your logic where <add> // you need to know if an ad is visible or not. <add> System.out.println("Pause audio"); <add> } <add> } <add> <add> /** <add> * Called after an InPlay object has been loaded from the <add> * Chartboost API servers and cached locally. <add> * <p/> <add> * Implement to be notified of when an InPlay object has <add> * been loaded from the Chartboost API servers and cached <add> * locally for a given CBLocation. <add> * <add> * @param location The location for the Chartboost <add> * impression type. <add> */ <add> @Override <add> public void didCacheInPlay(String location) { <add> System.out.println("Successfully cached inPlay"); <add> UIViewController vc = applicationDelegate.getWindow().getRootViewController(); <add>// vc.renderInPlay(Chartboost.getInPlay(location)); <add> //TODO uncomment and fix the line above <add> } <add> <add> /** <add> * Called after a InPlay has attempted to load from the <add> * Chartboost API servers but failed. <add> * <p/> <add> * Implement to be notified of when an InPlay has attempted <add> * to load from the Chartboost API servers but failed for a <add> * given CBLocation. <add> * <add> * @param location The location for the Chartboost <add> * impression type. <add> * @param error The reason for the error defined via a <add> * CBLoadError. <add> */ <add> @Override <add> public void didFailToLoadInPlay(String location, CBLoadError error) { <add> String errorString = ""; <add> switch (error) { <add> case InternetUnavailable: <add> errorString = "Failed to load In Play, no Internet connection !"; <add> break; <add> case Internal: <add> errorString = "Failed to load In Play, internal error !"; <add> break; <add> case NetworkFailure: <add> errorString = "Failed to load In Play, network error !"; <add> break; <add> case WrongOrientation: <add> errorString = "Failed to load In Play, wrong orientation !"; <add> break; <add> case TooManyConnections: <add> errorString = "Failed to load In Play, too many connections !"; <add> break; <add> case FirstSessionInterstitialsDisabled: <add> errorString = "Failed to load In Play, first session !"; <add> break; <add> case NoAdFound: <add> errorString = "Failed to load In Play, no ad found !"; <add> break; <add> case SessionNotStarted: <add> errorString = "Failed to load In Play, session not started !"; <add> break; <add> case NoLocationFound: <add> errorString = "Failed to load In Play, missing location parameter !"; <add> break; <add> default: <add> errorString = "Failed to load In Play, unknown error !"; <add> break; <add> } <add> <add> System.out.println(errorString); <add> <add> UIViewController vc = applicationDelegate.getWindow().getRootViewController(); <add>// vc.renderInPlayError(errorString); <add> //TODO uncomment and fix the line above <add> } <add> <add> }; <add> } <add> <ide> }
Java
apache-2.0
b13895d6bebc57fd9da8909f6ffa35203031eb72
0
RWTH-i5-IDSG/jamocha,RWTH-i5-IDSG/jamocha
/** * Copyright 2007 Alexander Wilden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://jamocha.sourceforge.net/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jamocha.parser; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import org.jamocha.parser.clips.CLIPSFormatter; import org.jamocha.parser.clips.CLIPSParser; import org.jamocha.parser.cool.COOLParser; import org.jamocha.parser.sfp.SFPParser; /** * The ParserFactory generates all known Parsers for CLIPS-Code or other * languages needed when working with Jamocha. * * @author Alexander Wilden <[email protected]> */ public class ParserFactory { private static String defaultParser = "clips"; public static void setDefaultParser(String parserName) throws ParserNotFoundException { if (parserName != null && parserName.length() > 0) { defaultParser = parserName; // This is just to test if the specified Parser exists. If not we // can // throw an exception. getParser(parserName, new StringReader("")); } } public static String getDefaultParser() { return defaultParser; } public static Parser getParser(Reader reader) { try { return getParser(defaultParser, reader); } catch (ParserNotFoundException e) { // This shouldn't happen because the exception is thrown already // before when setting the default parser. e.printStackTrace(); } return null; } public static Parser getParser(InputStream stream) { try { return getParser(defaultParser, stream); } catch (ParserNotFoundException e) { // This shouldn't happen because the exception is thrown already // before when setting the default parser. e.printStackTrace(); } return null; } public static Parser getParser(String parserName, Reader reader) throws ParserNotFoundException { if (parserName.equalsIgnoreCase("cool")) { return new COOLParser(reader); } else if (parserName.equalsIgnoreCase("clips")) { return new CLIPSParser(reader); } else if (parserName.equalsIgnoreCase("sfp")) { return new SFPParser(reader); } else { throw new ParserNotFoundException("The Parser with the name \"" + parserName + "\" could not be found."); } } public static Parser getParser(String parserName, InputStream stream) throws ParserNotFoundException { if (parserName.equalsIgnoreCase("cool")) { return new COOLParser(stream); } else if (parserName.equalsIgnoreCase("clips")) { return new CLIPSParser(stream); } else if (parserName.equalsIgnoreCase("sfp")) { return new SFPParser(stream); } else { throw new ParserNotFoundException("The Parser with the name \"" + parserName + "\" could not be found."); } } /** * Returns the Formatter without indentation belonging to the default * Parser. * * @return The Formatter of the default parser. */ public static Formatter getFormatter() { return getFormatter(false); } /** * Returns the Formatter belonging to the default Parser. * * @param indentation * if <code>true</code> the Formatter uses indentation. * @return The Formatter of the default parser. */ public static Formatter getFormatter(boolean indentation) { try { return getFormatter(defaultParser, indentation); } catch (ParserNotFoundException e) { // Should never happen } return null; } /** * Returns the Formatter without indentation belonging to a specified * Parser. Parser. * * @param parserName * Name of the spcecific Parser. * @return The Formatter of the default parser. * @throws ParserNotFoundException */ public static Formatter getFormatter(String parserName) throws ParserNotFoundException { return getFormatter(parserName, false); } /** * Returns the Formatter belonging to a specified Parser. * * @param parserName * Name of the spcecific Parser. * @param indentation * if <code>true</code> the Formatter uses indentation. * @return The Formatter of the parser. * @throws ParserNotFoundException */ public static Formatter getFormatter(String parserName, boolean indentation) throws ParserNotFoundException { if (parserName.equalsIgnoreCase("cool")) { return new CLIPSFormatter(indentation); // return new COOLFormatter(); } else if (parserName.equalsIgnoreCase("clips")) { return new CLIPSFormatter(indentation); } else if (parserName.equalsIgnoreCase("sfp")) { return new CLIPSFormatter(indentation); } else { throw new ParserNotFoundException("The Parser with the name \"" + parserName + "\" could not be found."); } } }
src/main/org/jamocha/parser/ParserFactory.java
/** * Copyright 2007 Alexander Wilden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://jamocha.sourceforge.net/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jamocha.parser; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import org.jamocha.parser.clips.CLIPSFormatter; import org.jamocha.parser.clips.CLIPSParser; import org.jamocha.parser.cool.COOLParser; /** * The ParserFactory generates all known Parsers for CLIPS-Code or other * languages needed when working with Jamocha. * * @author Alexander Wilden <[email protected]> */ public class ParserFactory { private static String defaultParser = "clips"; public static void setDefaultParser(String parserName) throws ParserNotFoundException { if (parserName != null && parserName.length() > 0) { defaultParser = parserName; // This is just to test if the specified Parser exists. If not we // can // throw an exception. getParser(parserName, new StringReader("")); } } public static String getDefaultParser() { return defaultParser; } public static Parser getParser(Reader reader) { try { return getParser(defaultParser, reader); } catch (ParserNotFoundException e) { // This shouldn't happen because the exception is thrown already // before when setting the default parser. e.printStackTrace(); } return null; } public static Parser getParser(InputStream stream) { try { return getParser(defaultParser, stream); } catch (ParserNotFoundException e) { // This shouldn't happen because the exception is thrown already // before when setting the default parser. e.printStackTrace(); } return null; } public static Parser getParser(String parserName, Reader reader) throws ParserNotFoundException { if (parserName.equalsIgnoreCase("cool")) { return new COOLParser(reader); } else if (parserName.equalsIgnoreCase("clips")) { return new CLIPSParser(reader); } else { throw new ParserNotFoundException("The Parser with the name \"" + parserName + "\" could not be found."); } } public static Parser getParser(String parserName, InputStream stream) throws ParserNotFoundException { if (parserName.equalsIgnoreCase("cool")) { return new COOLParser(stream); } else if (parserName.equalsIgnoreCase("clips")) { return new CLIPSParser(stream); } else { throw new ParserNotFoundException("The Parser with the name \"" + parserName + "\" could not be found."); } } /** * Returns the Formatter without indentation belonging to the default * Parser. * * @return The Formatter of the default parser. */ public static Formatter getFormatter() { return getFormatter(false); } /** * Returns the Formatter belonging to the default Parser. * * @param indentation * if <code>true</code> the Formatter uses indentation. * @return The Formatter of the default parser. */ public static Formatter getFormatter(boolean indentation) { try { return getFormatter(defaultParser, indentation); } catch (ParserNotFoundException e) { // Should never happen } return null; } /** * Returns the Formatter without indentation belonging to a specified * Parser. Parser. * * @param parserName * Name of the spcecific Parser. * @return The Formatter of the default parser. * @throws ParserNotFoundException */ public static Formatter getFormatter(String parserName) throws ParserNotFoundException { return getFormatter(parserName, false); } /** * Returns the Formatter belonging to a specified Parser. * * @param parserName * Name of the spcecific Parser. * @param indentation * if <code>true</code> the Formatter uses indentation. * @return The Formatter of the parser. * @throws ParserNotFoundException */ public static Formatter getFormatter(String parserName, boolean indentation) throws ParserNotFoundException { if (parserName.equalsIgnoreCase("cool")) { return new CLIPSFormatter(indentation); // return new COOLFormatter(); } else if (parserName.equalsIgnoreCase("clips")) { return new CLIPSFormatter(indentation); } else { throw new ParserNotFoundException("The Parser with the name \"" + parserName + "\" could not be found."); } } }
- integrated SFPParser into ParserFactory. It can be used via -parser sfp Doesn't work yet!! git-svn-id: 9643e93313b82f5e4da82d8413267a0daa4b5472@779 2cd91b7d-3b21-0410-a5f4-f42db4f24360
src/main/org/jamocha/parser/ParserFactory.java
- integrated SFPParser into ParserFactory. It can be used via -parser sfp Doesn't work yet!!
<ide><path>rc/main/org/jamocha/parser/ParserFactory.java <ide> import org.jamocha.parser.clips.CLIPSFormatter; <ide> import org.jamocha.parser.clips.CLIPSParser; <ide> import org.jamocha.parser.cool.COOLParser; <add>import org.jamocha.parser.sfp.SFPParser; <ide> <ide> /** <ide> * The ParserFactory generates all known Parsers for CLIPS-Code or other <ide> return new COOLParser(reader); <ide> } else if (parserName.equalsIgnoreCase("clips")) { <ide> return new CLIPSParser(reader); <add> } else if (parserName.equalsIgnoreCase("sfp")) { <add> return new SFPParser(reader); <ide> } else { <ide> throw new ParserNotFoundException("The Parser with the name \"" <ide> + parserName + "\" could not be found."); <ide> return new COOLParser(stream); <ide> } else if (parserName.equalsIgnoreCase("clips")) { <ide> return new CLIPSParser(stream); <add> } else if (parserName.equalsIgnoreCase("sfp")) { <add> return new SFPParser(stream); <ide> } else { <ide> throw new ParserNotFoundException("The Parser with the name \"" <ide> + parserName + "\" could not be found."); <ide> // return new COOLFormatter(); <ide> } else if (parserName.equalsIgnoreCase("clips")) { <ide> return new CLIPSFormatter(indentation); <add> } else if (parserName.equalsIgnoreCase("sfp")) { <add> return new CLIPSFormatter(indentation); <ide> } else { <ide> throw new ParserNotFoundException("The Parser with the name \"" <ide> + parserName + "\" could not be found.");
Java
apache-2.0
795ea0a2f344d45c2c4984ceb7ebc04527e366d0
0
winningsix/hive,asonipsl/hive,wisgood/hive,winningsix/hive,WANdisco/amplab-hive,asonipsl/hive,winningsix/hive,winningsix/hive,WANdisco/amplab-hive,WANdisco/hive,WANdisco/hive,WANdisco/hive,winningsix/hive,wisgood/hive,asonipsl/hive,WANdisco/amplab-hive,winningsix/hive,WANdisco/hive,winningsix/hive,wisgood/hive,WANdisco/amplab-hive,wisgood/hive,WANdisco/hive,wisgood/hive,asonipsl/hive,asonipsl/hive,WANdisco/hive,WANdisco/amplab-hive,wisgood/hive,asonipsl/hive,WANdisco/amplab-hive,wisgood/hive,winningsix/hive,WANdisco/hive,asonipsl/hive,wisgood/hive,WANdisco/amplab-hive,WANdisco/hive,asonipsl/hive,WANdisco/amplab-hive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.lockmgr.zookeeper; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.ErrorMsg; import org.apache.hadoop.hive.ql.lockmgr.HiveLock; import org.apache.hadoop.hive.ql.lockmgr.HiveLockManager; import org.apache.hadoop.hive.ql.lockmgr.HiveLockManagerCtx; import org.apache.hadoop.hive.ql.lockmgr.HiveLockMode; import org.apache.hadoop.hive.ql.lockmgr.HiveLockObj; import org.apache.hadoop.hive.ql.lockmgr.HiveLockObject; import org.apache.hadoop.hive.ql.lockmgr.HiveLockObject.HiveLockObjectData; import org.apache.hadoop.hive.ql.lockmgr.LockException; import org.apache.hadoop.hive.ql.metadata.DummyPartition; import org.apache.hadoop.hive.ql.metadata.Hive; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.session.SessionState.LogHelper; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import com.google.common.annotations.VisibleForTesting; public class ZooKeeperHiveLockManager implements HiveLockManager { HiveLockManagerCtx ctx; public static final Log LOG = LogFactory.getLog("ZooKeeperHiveLockManager"); static final private LogHelper console = new LogHelper(LOG); private ZooKeeper zooKeeper; // All the locks are created under this parent private String parent; private int sessionTimeout; private String quorumServers; private int sleepTime; private int numRetriesForLock; private int numRetriesForUnLock; private static String clientIp; static { clientIp = "UNKNOWN"; try { InetAddress clientAddr = InetAddress.getLocalHost(); clientIp = clientAddr.getHostAddress(); } catch (Exception e1) { } } public ZooKeeperHiveLockManager() { } /** * @param conf The hive configuration * Get the quorum server address from the configuration. The format is: * host1:port, host2:port.. **/ @VisibleForTesting static String getQuorumServers(HiveConf conf) { String[] hosts = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_QUORUM).split(","); String port = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CLIENT_PORT); StringBuilder quorum = new StringBuilder(); for(int i=0; i<hosts.length; i++) { quorum.append(hosts[i].trim()); if (!hosts[i].contains(":")) { // if the hostname doesn't contain a port, add the configured port to hostname quorum.append(":"); quorum.append(port); } if (i != hosts.length-1) quorum.append(","); } return quorum.toString(); } /** * @param ctx The lock manager context (containing the Hive configuration file) * Start the ZooKeeper client based on the zookeeper cluster specified in the conf. **/ public void setContext(HiveLockManagerCtx ctx) throws LockException { this.ctx = ctx; HiveConf conf = ctx.getConf(); sessionTimeout = conf.getIntVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT); quorumServers = ZooKeeperHiveLockManager.getQuorumServers(conf); sleepTime = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_SLEEP_BETWEEN_RETRIES) * 1000; numRetriesForLock = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_NUMRETRIES); numRetriesForUnLock = conf.getIntVar(HiveConf.ConfVars.HIVE_UNLOCK_NUMRETRIES); try { renewZookeeperInstance(sessionTimeout, quorumServers); parent = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_NAMESPACE); try { zooKeeper.create("/" + parent, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException e) { // ignore if the parent already exists if (e.code() != KeeperException.Code.NODEEXISTS) { LOG.warn("Unexpected ZK exception when creating parent node /" + parent, e); } } } catch (Exception e) { LOG.error("Failed to create ZooKeeper object: ", e); throw new LockException(ErrorMsg.ZOOKEEPER_CLIENT_COULD_NOT_BE_INITIALIZED.getMsg()); } } @Override public void refresh() { HiveConf conf = ctx.getConf(); sleepTime = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_SLEEP_BETWEEN_RETRIES) * 1000; numRetriesForLock = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_NUMRETRIES); numRetriesForUnLock = conf.getIntVar(HiveConf.ConfVars.HIVE_UNLOCK_NUMRETRIES); } private void renewZookeeperInstance(int sessionTimeout, String quorumServers) throws InterruptedException, IOException { if (zooKeeper != null) { return; } zooKeeper = new ZooKeeper(quorumServers, sessionTimeout, new DummyWatcher()); } /** * @param key object to be locked * Get the name of the last string. For eg. if you need to lock db/T/ds=1=/hr=1, * the last name would be db/T/ds=1/hr=1 **/ private static String getLastObjectName(String parent, HiveLockObject key) { return "/" + parent + "/" + key.getName(); } /** * @param key object to be locked * Get the list of names for all the parents. * For eg: if you need to lock db/T/ds=1/hr=1, the following list will be returned: * {db, db/T, db/T/ds=1, db/T/ds=1/hr=1} **/ private List<String> getObjectNames(HiveLockObject key) { List<String> parents = new ArrayList<String>(); String curParent = "/" + parent + "/"; String[] names = key.getName().split("/"); for (String name : names) { curParent = curParent + name; parents.add(curParent); curParent = curParent + "/"; } return parents; } /** * @param lockObjects List of objects and the modes of the locks requested * @param keepAlive Whether the lock is to be persisted after the statement * * Acuire all the locks. Release all the locks and return null if any lock * could not be acquired. **/ public List<HiveLock> lock(List<HiveLockObj> lockObjects, boolean keepAlive) throws LockException { // Sort the objects first. You are guaranteed that if a partition is being locked, // the table has already been locked Collections.sort(lockObjects, new Comparator<HiveLockObj>() { @Override public int compare(HiveLockObj o1, HiveLockObj o2) { int cmp = o1.getName().compareTo(o2.getName()); if (cmp == 0) { if (o1.getMode() == o2.getMode()) { return cmp; } // EXCLUSIVE locks occur before SHARED locks if (o1.getMode() == HiveLockMode.EXCLUSIVE) { return -1; } return +1; } return cmp; } }); // walk the list and acquire the locks - if any lock cant be acquired, release all locks, sleep // and retry HiveLockObj prevLockObj = null; List<HiveLock> hiveLocks = new ArrayList<HiveLock>(); for (HiveLockObj lockObject : lockObjects) { // No need to acquire a lock twice on the same object // It is ensured that EXCLUSIVE locks occur before SHARED locks on the same object if ((prevLockObj != null) && (prevLockObj.getName().equals(lockObject.getName()))) { prevLockObj = lockObject; continue; } HiveLock lock = null; try { lock = lock(lockObject.getObj(), lockObject.getMode(), keepAlive, true); } catch (LockException e) { console.printError("Error in acquireLocks..." ); LOG.error("Error in acquireLocks...", e); lock = null; } if (lock == null) { releaseLocks(hiveLocks); return null; } hiveLocks.add(lock); prevLockObj = lockObject; } return hiveLocks; } /** * @param hiveLocks * list of hive locks to be released Release all the locks specified. If some of the * locks have already been released, ignore them **/ public void releaseLocks(List<HiveLock> hiveLocks) { if (hiveLocks != null) { int len = hiveLocks.size(); for (int pos = len-1; pos >= 0; pos--) { HiveLock hiveLock = hiveLocks.get(pos); try { LOG.info(" about to release lock for " + hiveLock.getHiveLockObject().getName()); unlock(hiveLock); } catch (LockException e) { // The lock may have been released. Ignore and continue LOG.warn("Error when releasing lock", e); } } } } /** * @param key * The object to be locked * @param mode * The mode of the lock * @param keepAlive * Whether the lock is to be persisted after the statement Acuire the * lock. Return null if a conflicting lock is present. **/ public ZooKeeperHiveLock lock(HiveLockObject key, HiveLockMode mode, boolean keepAlive) throws LockException { return lock(key, mode, keepAlive, false); } /** * @param name * The name of the zookeeper child * @param data * The data for the zookeeper child * @param mode * The mode in which the child needs to be created * @throws KeeperException * @throws InterruptedException **/ private String createChild(String name, byte[] data, CreateMode mode) throws KeeperException, InterruptedException { return zooKeeper.create(name, data, Ids.OPEN_ACL_UNSAFE, mode); } private String getLockName(String parent, HiveLockMode mode) { return parent + "/" + "LOCK-" + mode + "-"; } private ZooKeeperHiveLock lock (HiveLockObject key, HiveLockMode mode, boolean keepAlive, boolean parentCreated) throws LockException { int tryNum = 1; ZooKeeperHiveLock ret = null; do { try { if (tryNum > 1) { Thread.sleep(sleepTime); prepareRetry(); } ret = lockPrimitive(key, mode, keepAlive, parentCreated); if (ret != null) { break; } tryNum++; } catch (Exception e1) { tryNum++; if (e1 instanceof KeeperException) { KeeperException e = (KeeperException) e1; switch (e.code()) { case CONNECTIONLOSS: case OPERATIONTIMEOUT: LOG.warn("Possibly transient ZooKeeper exception: ", e); break; default: LOG.error("Serious Zookeeper exception: ", e); break; } } if (tryNum >= numRetriesForLock) { throw new LockException(e1); } } } while (tryNum < numRetriesForLock); return ret; } private ZooKeeperHiveLock lockPrimitive(HiveLockObject key, HiveLockMode mode, boolean keepAlive, boolean parentCreated) throws KeeperException, InterruptedException { String res; // If the parents have already been created, create the last child only List<String> names = new ArrayList<String>(); String lastName; HiveLockObjectData lockData = key.getData(); lockData.setClientIp(clientIp); if (parentCreated) { lastName = getLastObjectName(parent, key); names.add(lastName); } else { names = getObjectNames(key); lastName = names.get(names.size() - 1); } // Create the parents first for (String name : names) { try { res = createChild(name, new byte[0], CreateMode.PERSISTENT); } catch (KeeperException e) { if (e.code() != KeeperException.Code.NODEEXISTS) { //if the exception is not 'NODEEXISTS', re-throw it throw e; } } } res = createChild(getLockName(lastName, mode), key.getData().toString() .getBytes(), keepAlive ? CreateMode.PERSISTENT_SEQUENTIAL : CreateMode.EPHEMERAL_SEQUENTIAL); int seqNo = getSequenceNumber(res, getLockName(lastName, mode)); if (seqNo == -1) { zooKeeper.delete(res, -1); return null; } List<String> children = zooKeeper.getChildren(lastName, false); String exLock = getLockName(lastName, HiveLockMode.EXCLUSIVE); String shLock = getLockName(lastName, HiveLockMode.SHARED); for (String child : children) { child = lastName + "/" + child; // Is there a conflicting lock on the same object with a lower sequence // number int childSeq = seqNo; if (child.startsWith(exLock)) { childSeq = getSequenceNumber(child, exLock); } if ((mode == HiveLockMode.EXCLUSIVE) && child.startsWith(shLock)) { childSeq = getSequenceNumber(child, shLock); } if ((childSeq >= 0) && (childSeq < seqNo)) { zooKeeper.delete(res, -1); console.printError("conflicting lock present for " + key.getDisplayName() + " mode " + mode); return null; } } return new ZooKeeperHiveLock(res, key, mode); } /* Remove the lock specified */ public void unlock(HiveLock hiveLock) throws LockException { unlockWithRetry(ctx.getConf(), zooKeeper, hiveLock, parent); } private void unlockWithRetry(HiveConf conf, ZooKeeper zkpClient, HiveLock hiveLock, String parent) throws LockException { int tryNum = 0; do { try { tryNum++; if (tryNum > 1) { Thread.sleep(sleepTime); prepareRetry(); } unlockPrimitive(conf, zkpClient, hiveLock, parent); break; } catch (Exception e) { if (tryNum >= numRetriesForUnLock) { String name = ((ZooKeeperHiveLock)hiveLock).getPath(); LOG.error("Node " + name + " can not be deleted after " + numRetriesForUnLock + " attempts."); throw new LockException(e); } } } while (tryNum < numRetriesForUnLock); return; } /* Remove the lock specified */ @VisibleForTesting static void unlockPrimitive(HiveConf conf, ZooKeeper zkpClient, HiveLock hiveLock, String parent) throws LockException { ZooKeeperHiveLock zLock = (ZooKeeperHiveLock)hiveLock; HiveLockObject obj = zLock.getHiveLockObject(); String name = getLastObjectName(parent, obj); try { zkpClient.delete(zLock.getPath(), -1); // Delete the parent node if all the children have been deleted List<String> children = zkpClient.getChildren(name, false); if (children == null || children.isEmpty()) { zkpClient.delete(name, -1); } } catch (KeeperException.NoNodeException nne) { //can happen in retrying deleting the zLock after exceptions like InterruptedException //or in a race condition where parent has already been deleted by other process when it //is to be deleted. Both cases should not raise error LOG.debug("Node " + zLock.getPath() + " or its parent has already been deleted."); } catch (KeeperException.NotEmptyException nee) { //can happen in a race condition where another process adds a zLock under this parent //just before it is about to be deleted. It should not be a problem since this parent //can eventually be deleted by the process which hold its last child zLock LOG.debug("Node " + name + " to be deleted is not empty."); } catch (Exception e) { //exceptions including InterruptException and other KeeperException LOG.error("Failed to release ZooKeeper lock: ", e); throw new LockException(e); } } /* Release all locks - including PERSISTENT locks */ public static void releaseAllLocks(HiveConf conf) throws Exception { ZooKeeper zkpClient = null; try { int sessionTimeout = conf.getIntVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT); String quorumServers = getQuorumServers(conf); Watcher dummWatcher = new DummyWatcher(); zkpClient = new ZooKeeper(quorumServers, sessionTimeout, dummWatcher); String parent = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_NAMESPACE); List<HiveLock> locks = getLocks(conf, zkpClient, null, parent, false, false); Exception lastExceptionGot = null; if (locks != null) { for (HiveLock lock : locks) { try { unlockPrimitive(conf, zkpClient, lock, parent); } catch (Exception e) { lastExceptionGot = e; } } } // if we got exception during doing the unlock, rethrow it here if(lastExceptionGot != null) { throw lastExceptionGot; } } catch (Exception e) { LOG.error("Failed to release all locks: ", e); throw new Exception(ErrorMsg.ZOOKEEPER_CLIENT_COULD_NOT_BE_INITIALIZED.getMsg()); } finally { if (zkpClient != null) { zkpClient.close(); zkpClient = null; } } } /* Get all locks */ public List<HiveLock> getLocks(boolean verifyTablePartition, boolean fetchData) throws LockException { return getLocks(ctx.getConf(), zooKeeper, null, parent, verifyTablePartition, fetchData); } /* Get all locks for a particular object */ public List<HiveLock> getLocks(HiveLockObject key, boolean verifyTablePartitions, boolean fetchData) throws LockException { return getLocks(ctx.getConf(), zooKeeper, key, parent, verifyTablePartitions, fetchData); } /** * @param conf Hive configuration * @param zkpClient The ZooKeeper client * @param key The object to be compared against - if key is null, then get all locks **/ private static List<HiveLock> getLocks(HiveConf conf, ZooKeeper zkpClient, HiveLockObject key, String parent, boolean verifyTablePartition, boolean fetchData) throws LockException { List<HiveLock> locks = new ArrayList<HiveLock>(); List<String> children; boolean recurse = true; String commonParent; try { if (key != null) { commonParent = "/" + parent + "/" + key.getName(); children = zkpClient.getChildren(commonParent, false); recurse = false; } else { commonParent = "/" + parent; children = zkpClient.getChildren(commonParent, false); } } catch (Exception e) { // no locks present return locks; } Queue<String> childn = new LinkedList<String>(); if (children != null && !children.isEmpty()) { for (String child : children) { childn.add(commonParent + "/" + child); } } while (true) { String curChild = childn.poll(); if (curChild == null) { return locks; } if (recurse) { try { children = zkpClient.getChildren(curChild, false); for (String child : children) { childn.add(curChild + "/" + child); } } catch (Exception e) { // nothing to do } } HiveLockMode mode = getLockMode(conf, curChild); if (mode == null) { continue; } HiveLockObjectData data = null; // set the lock object with a dummy data, and then do a set if needed. HiveLockObject obj = getLockObject(conf, curChild, mode, data, parent, verifyTablePartition); if (obj == null) { continue; } if ((key == null) || (obj.getName().equals(key.getName()))) { if (fetchData) { try { data = new HiveLockObjectData(new String(zkpClient.getData(curChild, new DummyWatcher(), null))); data.setClientIp(clientIp); } catch (Exception e) { LOG.error("Error in getting data for " + curChild, e); // ignore error } } obj.setData(data); HiveLock lck = (HiveLock)(new ZooKeeperHiveLock(curChild, obj, mode)); locks.add(lck); } } } /** Remove all redundant nodes **/ private void removeAllRedundantNodes() { try { renewZookeeperInstance(sessionTimeout, quorumServers); checkRedundantNode("/" + parent); if (zooKeeper != null) { zooKeeper.close(); zooKeeper = null; } } catch (Exception e) { LOG.warn("Exception while removing all redundant nodes", e); } } private void checkRedundantNode(String node) { try { // Nothing to do if it is a lock mode if (getLockMode(ctx.getConf(), node) != null) { return; } List<String> children = zooKeeper.getChildren(node, false); for (String child : children) { checkRedundantNode(node + "/" + child); } children = zooKeeper.getChildren(node, false); if ((children == null) || (children.isEmpty())) { zooKeeper.delete(node, -1); } } catch (Exception e) { LOG.warn("Error in checkRedundantNode for node " + node, e); } } /* Release all transient locks, by simply closing the client */ public void close() throws LockException { try { if (zooKeeper != null) { zooKeeper.close(); zooKeeper = null; } if (HiveConf.getBoolVar(ctx.getConf(), HiveConf.ConfVars.HIVE_ZOOKEEPER_CLEAN_EXTRA_NODES)) { removeAllRedundantNodes(); } } catch (Exception e) { LOG.error("Failed to close zooKeeper client: " + e); throw new LockException(e); } } /** * Get the sequence number from the path. The sequence number is always at the end of the path. **/ private int getSequenceNumber(String resPath, String path) { String tst = resPath.substring(path.length()); try { return (new Integer(tst)).intValue(); } catch (Exception e) { return -1; // invalid number } } /** * Get the object from the path of the lock. * The object may correspond to a table, a partition or a parent to a partition. * For eg: if Table T is partitioned by ds, hr and ds=1/hr=1 is a valid partition, * the lock may also correspond to T@ds=1, which is not a valid object * @param verifyTablePartition **/ private static HiveLockObject getLockObject(HiveConf conf, String path, HiveLockMode mode, HiveLockObjectData data, String parent, boolean verifyTablePartition) throws LockException { try { Hive db = Hive.get(conf); int indx = path.lastIndexOf("LOCK-" + mode.toString()); String objName = path.substring(("/" + parent + "/").length(), indx-1); String[] names = objName.split("/"); if (names.length < 2) { return null; } if (!verifyTablePartition) { return new HiveLockObject(names, data); } // do not throw exception if table does not exist Table tab = db.getTable(names[0], names[1], false); if (tab == null) { return null; } if (names.length == 2) { return new HiveLockObject(tab, data); } Map<String, String> partSpec = new HashMap<String, String>(); for (indx = 2; indx < names.length; indx++) { String[] partVals = names[indx].split("="); partSpec.put(partVals[0], partVals[1]); } Partition partn; try { partn = db.getPartition(tab, partSpec, false); } catch (HiveException e) { partn = null; } if (partn == null) { return new HiveLockObject(new DummyPartition(tab, path, partSpec), data); } return new HiveLockObject(partn, data); } catch (Exception e) { LOG.error("Failed to create ZooKeeper object: " + e); throw new LockException(e); } } private static Pattern shMode = Pattern.compile("^.*-(SHARED)-([0-9]+)$"); private static Pattern exMode = Pattern.compile("^.*-(EXCLUSIVE)-([0-9]+)$"); /* Get the mode of the lock encoded in the path */ private static HiveLockMode getLockMode(HiveConf conf, String path) { Matcher shMatcher = shMode.matcher(path); Matcher exMatcher = exMode.matcher(path); if (shMatcher.matches()) { return HiveLockMode.SHARED; } if (exMatcher.matches()) { return HiveLockMode.EXCLUSIVE; } return null; } public static class DummyWatcher implements Watcher { public void process(org.apache.zookeeper.WatchedEvent event) { } } @Override public void prepareRetry() throws LockException { try { if (zooKeeper != null && zooKeeper.getState() == ZooKeeper.States.CLOSED) { // Reconnect if the connection is closed. zooKeeper = null; } renewZookeeperInstance(sessionTimeout, quorumServers); } catch (Exception e) { throw new LockException(e); } } }
ql/src/java/org/apache/hadoop/hive/ql/lockmgr/zookeeper/ZooKeeperHiveLockManager.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.lockmgr.zookeeper; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.ErrorMsg; import org.apache.hadoop.hive.ql.lockmgr.HiveLock; import org.apache.hadoop.hive.ql.lockmgr.HiveLockManager; import org.apache.hadoop.hive.ql.lockmgr.HiveLockManagerCtx; import org.apache.hadoop.hive.ql.lockmgr.HiveLockMode; import org.apache.hadoop.hive.ql.lockmgr.HiveLockObj; import org.apache.hadoop.hive.ql.lockmgr.HiveLockObject; import org.apache.hadoop.hive.ql.lockmgr.HiveLockObject.HiveLockObjectData; import org.apache.hadoop.hive.ql.lockmgr.LockException; import org.apache.hadoop.hive.ql.metadata.DummyPartition; import org.apache.hadoop.hive.ql.metadata.Hive; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.session.SessionState.LogHelper; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import com.google.common.annotations.VisibleForTesting; public class ZooKeeperHiveLockManager implements HiveLockManager { HiveLockManagerCtx ctx; public static final Log LOG = LogFactory.getLog("ZooKeeperHiveLockManager"); static final private LogHelper console = new LogHelper(LOG); private ZooKeeper zooKeeper; // All the locks are created under this parent private String parent; private int sessionTimeout; private String quorumServers; private int sleepTime; private int numRetriesForLock; private int numRetriesForUnLock; private static String clientIp; static { clientIp = "UNKNOWN"; try { InetAddress clientAddr = InetAddress.getLocalHost(); clientIp = clientAddr.getHostAddress(); } catch (Exception e1) { } } public ZooKeeperHiveLockManager() { } /** * @param conf The hive configuration * Get the quorum server address from the configuration. The format is: * host1:port, host2:port.. **/ @VisibleForTesting static String getQuorumServers(HiveConf conf) { String[] hosts = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_QUORUM).split(","); String port = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CLIENT_PORT); StringBuilder quorum = new StringBuilder(); for(int i=0; i<hosts.length; i++) { quorum.append(hosts[i].trim()); if (!hosts[i].contains(":")) { // if the hostname doesn't contain a port, add the configured port to hostname quorum.append(":"); quorum.append(port); } if (i != hosts.length-1) quorum.append(","); } return quorum.toString(); } /** * @param ctx The lock manager context (containing the Hive configuration file) * Start the ZooKeeper client based on the zookeeper cluster specified in the conf. **/ public void setContext(HiveLockManagerCtx ctx) throws LockException { this.ctx = ctx; HiveConf conf = ctx.getConf(); sessionTimeout = conf.getIntVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT); quorumServers = ZooKeeperHiveLockManager.getQuorumServers(conf); sleepTime = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_SLEEP_BETWEEN_RETRIES) * 1000; numRetriesForLock = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_NUMRETRIES); numRetriesForUnLock = conf.getIntVar(HiveConf.ConfVars.HIVE_UNLOCK_NUMRETRIES); try { renewZookeeperInstance(sessionTimeout, quorumServers); parent = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_NAMESPACE); try { zooKeeper.create("/" + parent, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException e) { // ignore if the parent already exists if (e.code() != KeeperException.Code.NODEEXISTS) { LOG.warn("Unexpected ZK exception when creating parent node /" + parent, e); } } } catch (Exception e) { LOG.error("Failed to create ZooKeeper object: ", e); throw new LockException(ErrorMsg.ZOOKEEPER_CLIENT_COULD_NOT_BE_INITIALIZED.getMsg()); } } @Override public void refresh() { HiveConf conf = ctx.getConf(); sleepTime = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_SLEEP_BETWEEN_RETRIES) * 1000; numRetriesForLock = conf.getIntVar(HiveConf.ConfVars.HIVE_LOCK_NUMRETRIES); numRetriesForUnLock = conf.getIntVar(HiveConf.ConfVars.HIVE_UNLOCK_NUMRETRIES); } private void renewZookeeperInstance(int sessionTimeout, String quorumServers) throws InterruptedException, IOException { if (zooKeeper != null) { return; } zooKeeper = new ZooKeeper(quorumServers, sessionTimeout, new DummyWatcher()); } /** * @param key object to be locked * Get the name of the last string. For eg. if you need to lock db/T/ds=1=/hr=1, * the last name would be db/T/ds=1/hr=1 **/ private static String getLastObjectName(String parent, HiveLockObject key) { return "/" + parent + "/" + key.getName(); } /** * @param key object to be locked * Get the list of names for all the parents. * For eg: if you need to lock db/T/ds=1/hr=1, the following list will be returned: * {db, db/T, db/T/ds=1, db/T/ds=1/hr=1} **/ private List<String> getObjectNames(HiveLockObject key) { List<String> parents = new ArrayList<String>(); String curParent = "/" + parent + "/"; String[] names = key.getName().split("/"); for (String name : names) { curParent = curParent + name; parents.add(curParent); curParent = curParent + "/"; } return parents; } /** * @param lockObjects List of objects and the modes of the locks requested * @param keepAlive Whether the lock is to be persisted after the statement * * Acuire all the locks. Release all the locks and return null if any lock * could not be acquired. **/ public List<HiveLock> lock(List<HiveLockObj> lockObjects, boolean keepAlive) throws LockException { // Sort the objects first. You are guaranteed that if a partition is being locked, // the table has already been locked Collections.sort(lockObjects, new Comparator<HiveLockObj>() { @Override public int compare(HiveLockObj o1, HiveLockObj o2) { int cmp = o1.getName().compareTo(o2.getName()); if (cmp == 0) { if (o1.getMode() == o2.getMode()) { return cmp; } // EXCLUSIVE locks occur before SHARED locks if (o1.getMode() == HiveLockMode.EXCLUSIVE) { return -1; } return +1; } return cmp; } }); // walk the list and acquire the locks - if any lock cant be acquired, release all locks, sleep // and retry HiveLockObj prevLockObj = null; List<HiveLock> hiveLocks = new ArrayList<HiveLock>(); for (HiveLockObj lockObject : lockObjects) { // No need to acquire a lock twice on the same object // It is ensured that EXCLUSIVE locks occur before SHARED locks on the same object if ((prevLockObj != null) && (prevLockObj.getName().equals(lockObject.getName()))) { prevLockObj = lockObject; continue; } HiveLock lock = null; try { lock = lock(lockObject.getObj(), lockObject.getMode(), keepAlive, true); } catch (LockException e) { console.printError("Error in acquireLocks..." ); LOG.error("Error in acquireLocks...", e); lock = null; } if (lock == null) { releaseLocks(hiveLocks); return null; } hiveLocks.add(lock); prevLockObj = lockObject; } return hiveLocks; } /** * @param hiveLocks * list of hive locks to be released Release all the locks specified. If some of the * locks have already been released, ignore them **/ public void releaseLocks(List<HiveLock> hiveLocks) { if (hiveLocks != null) { int len = hiveLocks.size(); for (int pos = len-1; pos >= 0; pos--) { HiveLock hiveLock = hiveLocks.get(pos); try { LOG.info(" about to release lock for " + hiveLock.getHiveLockObject().getName()); unlock(hiveLock); } catch (LockException e) { // The lock may have been released. Ignore and continue LOG.warn("Error when releasing lock", e); } } } } /** * @param key * The object to be locked * @param mode * The mode of the lock * @param keepAlive * Whether the lock is to be persisted after the statement Acuire the * lock. Return null if a conflicting lock is present. **/ public ZooKeeperHiveLock lock(HiveLockObject key, HiveLockMode mode, boolean keepAlive) throws LockException { return lock(key, mode, keepAlive, false); } /** * @param name * The name of the zookeeper child * @param data * The data for the zookeeper child * @param mode * The mode in which the child needs to be created * @throws KeeperException * @throws InterruptedException **/ private String createChild(String name, byte[] data, CreateMode mode) throws KeeperException, InterruptedException { return zooKeeper.create(name, data, Ids.OPEN_ACL_UNSAFE, mode); } private String getLockName(String parent, HiveLockMode mode) { return parent + "/" + "LOCK-" + mode + "-"; } private ZooKeeperHiveLock lock (HiveLockObject key, HiveLockMode mode, boolean keepAlive, boolean parentCreated) throws LockException { int tryNum = 1; ZooKeeperHiveLock ret = null; do { try { if (tryNum > 1) { Thread.sleep(sleepTime); prepareRetry(); } ret = lockPrimitive(key, mode, keepAlive, parentCreated); if (ret != null) { break; } tryNum++; } catch (Exception e1) { tryNum++; if (e1 instanceof KeeperException) { KeeperException e = (KeeperException) e1; switch (e.code()) { case CONNECTIONLOSS: case OPERATIONTIMEOUT: LOG.warn("Possibly transient ZooKeeper exception: ", e); break; default: LOG.error("Serious Zookeeper exception: ", e); break; } } if (tryNum >= numRetriesForLock) { throw new LockException(e1); } } } while (tryNum < numRetriesForLock); return ret; } private ZooKeeperHiveLock lockPrimitive(HiveLockObject key, HiveLockMode mode, boolean keepAlive, boolean parentCreated) throws KeeperException, InterruptedException { String res; // If the parents have already been created, create the last child only List<String> names = new ArrayList<String>(); String lastName; HiveLockObjectData lockData = key.getData(); lockData.setClientIp(clientIp); if (parentCreated) { lastName = getLastObjectName(parent, key); names.add(lastName); } else { names = getObjectNames(key); lastName = names.get(names.size() - 1); } // Create the parents first for (String name : names) { try { res = createChild(name, new byte[0], CreateMode.PERSISTENT); } catch (KeeperException e) { if (e.code() != KeeperException.Code.NODEEXISTS) { //if the exception is not 'NODEEXISTS', re-throw it throw e; } } } res = createChild(getLockName(lastName, mode), key.getData().toString() .getBytes(), keepAlive ? CreateMode.PERSISTENT_SEQUENTIAL : CreateMode.EPHEMERAL_SEQUENTIAL); int seqNo = getSequenceNumber(res, getLockName(lastName, mode)); if (seqNo == -1) { zooKeeper.delete(res, -1); return null; } List<String> children = zooKeeper.getChildren(lastName, false); String exLock = getLockName(lastName, HiveLockMode.EXCLUSIVE); String shLock = getLockName(lastName, HiveLockMode.SHARED); for (String child : children) { child = lastName + "/" + child; // Is there a conflicting lock on the same object with a lower sequence // number int childSeq = seqNo; if (child.startsWith(exLock)) { childSeq = getSequenceNumber(child, exLock); } if ((mode == HiveLockMode.EXCLUSIVE) && child.startsWith(shLock)) { childSeq = getSequenceNumber(child, shLock); } if ((childSeq >= 0) && (childSeq < seqNo)) { zooKeeper.delete(res, -1); console.printError("conflicting lock present for " + key.getDisplayName() + " mode " + mode); return null; } } return new ZooKeeperHiveLock(res, key, mode); } /* Remove the lock specified */ public void unlock(HiveLock hiveLock) throws LockException { unlockWithRetry(ctx.getConf(), zooKeeper, hiveLock, parent); } private void unlockWithRetry(HiveConf conf, ZooKeeper zkpClient, HiveLock hiveLock, String parent) throws LockException { int tryNum = 0; do { try { tryNum++; if (tryNum > 1) { Thread.sleep(sleepTime); prepareRetry(); } unlockPrimitive(conf, zkpClient, hiveLock, parent); break; } catch (Exception e) { if (tryNum >= numRetriesForUnLock) { throw new LockException(e); } } } while (tryNum < numRetriesForUnLock); return; } /* Remove the lock specified */ @VisibleForTesting static void unlockPrimitive(HiveConf conf, ZooKeeper zkpClient, HiveLock hiveLock, String parent) throws LockException { ZooKeeperHiveLock zLock = (ZooKeeperHiveLock)hiveLock; try { // can throw KeeperException.NoNodeException, which might mean something is wrong zkpClient.delete(zLock.getPath(), -1); // Delete the parent node if all the children have been deleted HiveLockObject obj = zLock.getHiveLockObject(); String name = getLastObjectName(parent, obj); try { List<String> children = zkpClient.getChildren(name, false); if (children == null || children.isEmpty()) { zkpClient.delete(name, -1); } } catch (KeeperException.NoNodeException e) { LOG.debug("Node " + name + " previously deleted when attempting to delete."); } } catch (Exception e) { LOG.error("Failed to release ZooKeeper lock: ", e); throw new LockException(e); } } /* Release all locks - including PERSISTENT locks */ public static void releaseAllLocks(HiveConf conf) throws Exception { ZooKeeper zkpClient = null; try { int sessionTimeout = conf.getIntVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT); String quorumServers = getQuorumServers(conf); Watcher dummWatcher = new DummyWatcher(); zkpClient = new ZooKeeper(quorumServers, sessionTimeout, dummWatcher); String parent = conf.getVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_NAMESPACE); List<HiveLock> locks = getLocks(conf, zkpClient, null, parent, false, false); Exception lastExceptionGot = null; if (locks != null) { for (HiveLock lock : locks) { try { unlockPrimitive(conf, zkpClient, lock, parent); } catch (Exception e) { lastExceptionGot = e; } } } // if we got exception during doing the unlock, rethrow it here if(lastExceptionGot != null) { throw lastExceptionGot; } } catch (Exception e) { LOG.error("Failed to release all locks: ", e); throw new Exception(ErrorMsg.ZOOKEEPER_CLIENT_COULD_NOT_BE_INITIALIZED.getMsg()); } finally { if (zkpClient != null) { zkpClient.close(); zkpClient = null; } } } /* Get all locks */ public List<HiveLock> getLocks(boolean verifyTablePartition, boolean fetchData) throws LockException { return getLocks(ctx.getConf(), zooKeeper, null, parent, verifyTablePartition, fetchData); } /* Get all locks for a particular object */ public List<HiveLock> getLocks(HiveLockObject key, boolean verifyTablePartitions, boolean fetchData) throws LockException { return getLocks(ctx.getConf(), zooKeeper, key, parent, verifyTablePartitions, fetchData); } /** * @param conf Hive configuration * @param zkpClient The ZooKeeper client * @param key The object to be compared against - if key is null, then get all locks **/ private static List<HiveLock> getLocks(HiveConf conf, ZooKeeper zkpClient, HiveLockObject key, String parent, boolean verifyTablePartition, boolean fetchData) throws LockException { List<HiveLock> locks = new ArrayList<HiveLock>(); List<String> children; boolean recurse = true; String commonParent; try { if (key != null) { commonParent = "/" + parent + "/" + key.getName(); children = zkpClient.getChildren(commonParent, false); recurse = false; } else { commonParent = "/" + parent; children = zkpClient.getChildren(commonParent, false); } } catch (Exception e) { // no locks present return locks; } Queue<String> childn = new LinkedList<String>(); if (children != null && !children.isEmpty()) { for (String child : children) { childn.add(commonParent + "/" + child); } } while (true) { String curChild = childn.poll(); if (curChild == null) { return locks; } if (recurse) { try { children = zkpClient.getChildren(curChild, false); for (String child : children) { childn.add(curChild + "/" + child); } } catch (Exception e) { // nothing to do } } HiveLockMode mode = getLockMode(conf, curChild); if (mode == null) { continue; } HiveLockObjectData data = null; // set the lock object with a dummy data, and then do a set if needed. HiveLockObject obj = getLockObject(conf, curChild, mode, data, parent, verifyTablePartition); if (obj == null) { continue; } if ((key == null) || (obj.getName().equals(key.getName()))) { if (fetchData) { try { data = new HiveLockObjectData(new String(zkpClient.getData(curChild, new DummyWatcher(), null))); data.setClientIp(clientIp); } catch (Exception e) { LOG.error("Error in getting data for " + curChild, e); // ignore error } } obj.setData(data); HiveLock lck = (HiveLock)(new ZooKeeperHiveLock(curChild, obj, mode)); locks.add(lck); } } } /** Remove all redundant nodes **/ private void removeAllRedundantNodes() { try { renewZookeeperInstance(sessionTimeout, quorumServers); checkRedundantNode("/" + parent); if (zooKeeper != null) { zooKeeper.close(); zooKeeper = null; } } catch (Exception e) { LOG.warn("Exception while removing all redundant nodes", e); } } private void checkRedundantNode(String node) { try { // Nothing to do if it is a lock mode if (getLockMode(ctx.getConf(), node) != null) { return; } List<String> children = zooKeeper.getChildren(node, false); for (String child : children) { checkRedundantNode(node + "/" + child); } children = zooKeeper.getChildren(node, false); if ((children == null) || (children.isEmpty())) { zooKeeper.delete(node, -1); } } catch (Exception e) { LOG.warn("Error in checkRedundantNode for node " + node, e); } } /* Release all transient locks, by simply closing the client */ public void close() throws LockException { try { if (zooKeeper != null) { zooKeeper.close(); zooKeeper = null; } if (HiveConf.getBoolVar(ctx.getConf(), HiveConf.ConfVars.HIVE_ZOOKEEPER_CLEAN_EXTRA_NODES)) { removeAllRedundantNodes(); } } catch (Exception e) { LOG.error("Failed to close zooKeeper client: " + e); throw new LockException(e); } } /** * Get the sequence number from the path. The sequence number is always at the end of the path. **/ private int getSequenceNumber(String resPath, String path) { String tst = resPath.substring(path.length()); try { return (new Integer(tst)).intValue(); } catch (Exception e) { return -1; // invalid number } } /** * Get the object from the path of the lock. * The object may correspond to a table, a partition or a parent to a partition. * For eg: if Table T is partitioned by ds, hr and ds=1/hr=1 is a valid partition, * the lock may also correspond to T@ds=1, which is not a valid object * @param verifyTablePartition **/ private static HiveLockObject getLockObject(HiveConf conf, String path, HiveLockMode mode, HiveLockObjectData data, String parent, boolean verifyTablePartition) throws LockException { try { Hive db = Hive.get(conf); int indx = path.lastIndexOf("LOCK-" + mode.toString()); String objName = path.substring(("/" + parent + "/").length(), indx-1); String[] names = objName.split("/"); if (names.length < 2) { return null; } if (!verifyTablePartition) { return new HiveLockObject(names, data); } // do not throw exception if table does not exist Table tab = db.getTable(names[0], names[1], false); if (tab == null) { return null; } if (names.length == 2) { return new HiveLockObject(tab, data); } Map<String, String> partSpec = new HashMap<String, String>(); for (indx = 2; indx < names.length; indx++) { String[] partVals = names[indx].split("="); partSpec.put(partVals[0], partVals[1]); } Partition partn; try { partn = db.getPartition(tab, partSpec, false); } catch (HiveException e) { partn = null; } if (partn == null) { return new HiveLockObject(new DummyPartition(tab, path, partSpec), data); } return new HiveLockObject(partn, data); } catch (Exception e) { LOG.error("Failed to create ZooKeeper object: " + e); throw new LockException(e); } } private static Pattern shMode = Pattern.compile("^.*-(SHARED)-([0-9]+)$"); private static Pattern exMode = Pattern.compile("^.*-(EXCLUSIVE)-([0-9]+)$"); /* Get the mode of the lock encoded in the path */ private static HiveLockMode getLockMode(HiveConf conf, String path) { Matcher shMatcher = shMode.matcher(path); Matcher exMatcher = exMode.matcher(path); if (shMatcher.matches()) { return HiveLockMode.SHARED; } if (exMatcher.matches()) { return HiveLockMode.EXCLUSIVE; } return null; } public static class DummyWatcher implements Watcher { public void process(org.apache.zookeeper.WatchedEvent event) { } } @Override public void prepareRetry() throws LockException { try { if (zooKeeper != null && zooKeeper.getState() == ZooKeeper.States.CLOSED) { // Reconnect if the connection is closed. zooKeeper = null; } renewZookeeperInstance(sessionTimeout, quorumServers); } catch (Exception e) { throw new LockException(e); } } }
HIVE-6082 - Certain KeeperException should be ignored in ZooKeeperHiveLockManage.unlockPrimitive (Chaoyu Tang via Brock Noland) git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1554316 13f79535-47bb-0310-9956-ffa450edef68
ql/src/java/org/apache/hadoop/hive/ql/lockmgr/zookeeper/ZooKeeperHiveLockManager.java
HIVE-6082 - Certain KeeperException should be ignored in ZooKeeperHiveLockManage.unlockPrimitive (Chaoyu Tang via Brock Noland)
<ide><path>l/src/java/org/apache/hadoop/hive/ql/lockmgr/zookeeper/ZooKeeperHiveLockManager.java <ide> break; <ide> } catch (Exception e) { <ide> if (tryNum >= numRetriesForUnLock) { <add> String name = ((ZooKeeperHiveLock)hiveLock).getPath(); <add> LOG.error("Node " + name + " can not be deleted after " + numRetriesForUnLock + " attempts."); <ide> throw new LockException(e); <ide> } <ide> } <ide> static void unlockPrimitive(HiveConf conf, ZooKeeper zkpClient, <ide> HiveLock hiveLock, String parent) throws LockException { <ide> ZooKeeperHiveLock zLock = (ZooKeeperHiveLock)hiveLock; <del> try { <del> // can throw KeeperException.NoNodeException, which might mean something is wrong <add> HiveLockObject obj = zLock.getHiveLockObject(); <add> String name = getLastObjectName(parent, obj); <add> try { <ide> zkpClient.delete(zLock.getPath(), -1); <ide> <ide> // Delete the parent node if all the children have been deleted <del> HiveLockObject obj = zLock.getHiveLockObject(); <del> String name = getLastObjectName(parent, obj); <del> <del> try { <del> List<String> children = zkpClient.getChildren(name, false); <del> if (children == null || children.isEmpty()) { <del> zkpClient.delete(name, -1); <del> } <del> } catch (KeeperException.NoNodeException e) { <del> LOG.debug("Node " + name + " previously deleted when attempting to delete."); <del> } <del> } catch (Exception e) { <add> List<String> children = zkpClient.getChildren(name, false); <add> if (children == null || children.isEmpty()) { <add> zkpClient.delete(name, -1); <add> } <add> } catch (KeeperException.NoNodeException nne) { <add> //can happen in retrying deleting the zLock after exceptions like InterruptedException <add> //or in a race condition where parent has already been deleted by other process when it <add> //is to be deleted. Both cases should not raise error <add> LOG.debug("Node " + zLock.getPath() + " or its parent has already been deleted."); <add> } catch (KeeperException.NotEmptyException nee) { <add> //can happen in a race condition where another process adds a zLock under this parent <add> //just before it is about to be deleted. It should not be a problem since this parent <add> //can eventually be deleted by the process which hold its last child zLock <add> LOG.debug("Node " + name + " to be deleted is not empty."); <add> } catch (Exception e) { <add> //exceptions including InterruptException and other KeeperException <ide> LOG.error("Failed to release ZooKeeper lock: ", e); <ide> throw new LockException(e); <ide> }
Java
apache-2.0
7d68cbe5fbb41204eaa3c23ce9b3e4966455a998
0
keith-turner/accumulo,apache/accumulo,ctubbsii/accumulo,joshelser/accumulo,ctubbsii/accumulo,phrocker/accumulo,ivakegg/accumulo,ctubbsii/accumulo,adamjshook/accumulo,apache/accumulo,phrocker/accumulo-1,wjsl/jaredcumulo,ivakegg/accumulo,ctubbsii/accumulo,dhutchis/accumulo,wjsl/jaredcumulo,lstav/accumulo,joshelser/accumulo,lstav/accumulo,joshelser/accumulo,milleruntime/accumulo,mjwall/accumulo,mikewalch/accumulo,lstav/accumulo,keith-turner/accumulo,phrocker/accumulo,wjsl/jaredcumulo,dhutchis/accumulo,dhutchis/accumulo,keith-turner/accumulo,milleruntime/accumulo,adamjshook/accumulo,dhutchis/accumulo,apache/accumulo,lstav/accumulo,phrocker/accumulo-1,phrocker/accumulo,mjwall/accumulo,lstav/accumulo,ivakegg/accumulo,milleruntime/accumulo,joshelser/accumulo,keith-turner/accumulo,keith-turner/accumulo,phrocker/accumulo,dhutchis/accumulo,mikewalch/accumulo,lstav/accumulo,phrocker/accumulo-1,ctubbsii/accumulo,milleruntime/accumulo,dhutchis/accumulo,mikewalch/accumulo,keith-turner/accumulo,adamjshook/accumulo,phrocker/accumulo-1,dhutchis/accumulo,ivakegg/accumulo,mjwall/accumulo,mikewalch/accumulo,apache/accumulo,wjsl/jaredcumulo,mikewalch/accumulo,joshelser/accumulo,phrocker/accumulo-1,apache/accumulo,mikewalch/accumulo,mjwall/accumulo,phrocker/accumulo,keith-turner/accumulo,joshelser/accumulo,ivakegg/accumulo,mikewalch/accumulo,milleruntime/accumulo,adamjshook/accumulo,joshelser/accumulo,mikewalch/accumulo,dhutchis/accumulo,phrocker/accumulo,wjsl/jaredcumulo,adamjshook/accumulo,ctubbsii/accumulo,mjwall/accumulo,adamjshook/accumulo,apache/accumulo,adamjshook/accumulo,ivakegg/accumulo,phrocker/accumulo,dhutchis/accumulo,milleruntime/accumulo,adamjshook/accumulo,mjwall/accumulo,phrocker/accumulo-1,mjwall/accumulo,wjsl/jaredcumulo,milleruntime/accumulo,ivakegg/accumulo,adamjshook/accumulo,phrocker/accumulo,lstav/accumulo,wjsl/jaredcumulo,phrocker/accumulo,phrocker/accumulo-1,wjsl/jaredcumulo,joshelser/accumulo,ctubbsii/accumulo,apache/accumulo
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.examples.wikisearch.iterator; import java.io.IOException; import java.util.Collection; import java.util.Collections; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.PartialKey; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.accumulo.core.security.ColumnVisibility; import org.apache.accumulo.examples.wikisearch.parser.EventFields; import org.apache.accumulo.examples.wikisearch.parser.EventFields.FieldValue; import org.apache.commons.collections.map.LRUMap; import org.apache.hadoop.io.Text; public class EvaluatingIterator extends AbstractEvaluatingIterator { public static final String NULL_BYTE_STRING = "\u0000"; LRUMap visibilityMap = new LRUMap(); public EvaluatingIterator() { super(); } public EvaluatingIterator(AbstractEvaluatingIterator other, IteratorEnvironment env) { super(other, env); } public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new EvaluatingIterator(this, env); } @Override public PartialKey getKeyComparator() { return PartialKey.ROW_COLFAM; } @Override public Key getReturnKey(Key k) { // If we were using column visibility, then we would get the merged visibility here and use it in the key. // Remove the COLQ from the key and use the combined visibility Key r = new Key(k.getRowData().getBackingArray(), k.getColumnFamilyData().getBackingArray(), NULL_BYTE, k.getColumnVisibility().getBytes(), k.getTimestamp(), k.isDeleted(), false); return r; } @Override public void fillMap(EventFields event, Key key, Value value) { // If we were using column visibility, we would have to merge them here. // Pull the datatype from the colf in case we need to do anything datatype specific. // String colf = key.getColumnFamily().toString(); // String datatype = colf.substring(0, colf.indexOf(NULL_BYTE_STRING)); // For the partitioned table, the field name and field value are stored in the column qualifier // separated by a \0. String colq = key.getColumnQualifier().toString();// .toLowerCase(); int idx = colq.indexOf(NULL_BYTE_STRING); String fieldName = colq.substring(0, idx); String fieldValue = colq.substring(idx + 1); event.put(fieldName, new FieldValue(getColumnVisibility(key), fieldValue.getBytes())); } /** * @param key * @return */ public ColumnVisibility getColumnVisibility(Key key) { ColumnVisibility result = (ColumnVisibility) visibilityMap.get(key.getColumnVisibility()); if (result != null) return result; result = new ColumnVisibility(key.getColumnVisibility().getBytes()); visibilityMap.put(key.getColumnVisibility(), result); return result; } /** * Don't accept this key if the colf starts with 'fi' */ @Override public boolean isKeyAccepted(Key key) throws IOException { if (key.getColumnFamily().toString().startsWith("fi")) { Key copy = new Key(key.getRow(), new Text("fi\01")); Collection<ByteSequence> columnFamilies = Collections.emptyList(); this.iterator.seek(new Range(copy, copy), columnFamilies, true); if (this.iterator.hasTop()) return isKeyAccepted(this.iterator.getTopKey()); return true; } return true; } }
examples/wikisearch/query/src/main/java/org/apache/accumulo/examples/wikisearch/iterator/EvaluatingIterator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.examples.wikisearch.iterator; import java.io.IOException; import java.util.Collection; import java.util.Collections; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.PartialKey; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.accumulo.core.security.ColumnVisibility; import org.apache.accumulo.examples.wikisearch.parser.EventFields; import org.apache.accumulo.examples.wikisearch.parser.EventFields.FieldValue; import org.apache.hadoop.io.Text; public class EvaluatingIterator extends AbstractEvaluatingIterator { public static final String NULL_BYTE_STRING = "\u0000"; public EvaluatingIterator() { super(); } public EvaluatingIterator(AbstractEvaluatingIterator other, IteratorEnvironment env) { super(other, env); } public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new EvaluatingIterator(this, env); } @Override public PartialKey getKeyComparator() { return PartialKey.ROW_COLFAM; } @Override public Key getReturnKey(Key k) { // If we were using column visibility, then we would get the merged visibility here and use it in the key. // Remove the COLQ from the key and use the combined visibility Key r = new Key(k.getRowData().getBackingArray(), k.getColumnFamilyData().getBackingArray(), NULL_BYTE, k.getColumnVisibility().getBytes(), k.getTimestamp(), k.isDeleted(), false); return r; } @Override public void fillMap(EventFields event, Key key, Value value) { // If we were using column visibility, we would have to merge them here. // Pull the datatype from the colf in case we need to do anything datatype specific. // String colf = key.getColumnFamily().toString(); // String datatype = colf.substring(0, colf.indexOf(NULL_BYTE_STRING)); // For the partitioned table, the field name and field value are stored in the column qualifier // separated by a \0. String colq = key.getColumnQualifier().toString();// .toLowerCase(); int idx = colq.indexOf(NULL_BYTE_STRING); String fieldName = colq.substring(0, idx); String fieldValue = colq.substring(idx + 1); event.put(fieldName, new FieldValue(new ColumnVisibility(key.getColumnVisibility().getBytes()), fieldValue.getBytes())); } /** * Don't accept this key if the colf starts with 'fi' */ @Override public boolean isKeyAccepted(Key key) throws IOException { if (key.getColumnFamily().toString().startsWith("fi")) { Key copy = new Key(key.getRow(), new Text("fi\01")); Collection<ByteSequence> columnFamilies = Collections.emptyList(); this.iterator.seek(new Range(copy, copy), columnFamilies, true); if (this.iterator.hasTop()) return isKeyAccepted(this.iterator.getTopKey()); return true; } return true; } }
ACCUMULO-474: merge to trunk git-svn-id: ee25ee0bfe882ec55abc48667331b454c011093e@1302915 13f79535-47bb-0310-9956-ffa450edef68
examples/wikisearch/query/src/main/java/org/apache/accumulo/examples/wikisearch/iterator/EvaluatingIterator.java
ACCUMULO-474: merge to trunk
<ide><path>xamples/wikisearch/query/src/main/java/org/apache/accumulo/examples/wikisearch/iterator/EvaluatingIterator.java <ide> import org.apache.accumulo.core.security.ColumnVisibility; <ide> import org.apache.accumulo.examples.wikisearch.parser.EventFields; <ide> import org.apache.accumulo.examples.wikisearch.parser.EventFields.FieldValue; <add>import org.apache.commons.collections.map.LRUMap; <ide> import org.apache.hadoop.io.Text; <ide> <ide> <ide> public class EvaluatingIterator extends AbstractEvaluatingIterator { <ide> <ide> public static final String NULL_BYTE_STRING = "\u0000"; <add> LRUMap visibilityMap = new LRUMap(); <ide> <ide> public EvaluatingIterator() { <ide> super(); <ide> String fieldName = colq.substring(0, idx); <ide> String fieldValue = colq.substring(idx + 1); <ide> <del> event.put(fieldName, new FieldValue(new ColumnVisibility(key.getColumnVisibility().getBytes()), fieldValue.getBytes())); <add> event.put(fieldName, new FieldValue(getColumnVisibility(key), fieldValue.getBytes())); <add> } <add> <add> /** <add> * @param key <add> * @return <add> */ <add> public ColumnVisibility getColumnVisibility(Key key) { <add> ColumnVisibility result = (ColumnVisibility) visibilityMap.get(key.getColumnVisibility()); <add> if (result != null) <add> return result; <add> result = new ColumnVisibility(key.getColumnVisibility().getBytes()); <add> visibilityMap.put(key.getColumnVisibility(), result); <add> return result; <ide> } <ide> <ide> /**
Java
mit
error: pathspec 'src/test/java/org/eluder/coveralls/maven/plugin/source/MultiSourceLoaderTest.java' did not match any file(s) known to git
0af25aa89a4d0e932311f02482a82d7d29eb358f
1
andrioli/coveralls-maven-plugin,velo/coveralls-maven-plugin,manish-hike/coveralls-maven-plugin,trautonen/coveralls-maven-plugin,andrioli/coveralls-maven-plugin,velo/coveralls-maven-plugin,manish-hike/coveralls-maven-plugin,velo/coveralls-maven-plugin,andrioli/coveralls-maven-plugin,trautonen/coveralls-maven-plugin,trautonen/coveralls-maven-plugin,psiniemi/coveralls-maven-plugin,manish-hike/coveralls-maven-plugin,psiniemi/coveralls-maven-plugin,psiniemi/coveralls-maven-plugin
package org.eluder.coveralls.maven.plugin.source; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.when; import java.io.IOException; import org.eluder.coveralls.maven.plugin.domain.Source; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MultiSourceLoaderTest { @Mock private SourceLoader sl1; @Mock private SourceLoader sl2; private Source s1 = new Source("source", "{ 1 }"); private Source s2 = new Source("source", "{ 2 }"); @Test(expected = IOException.class) public void testMissingSource() throws Exception { creaMultiSourceLoader().load("source"); } @Test public void testPrimarySource() throws Exception { when(sl1.load("source")).thenReturn(s1); when(sl2.load("source")).thenReturn(s2); Source source = creaMultiSourceLoader().load("source"); assertSame(s1, source); } @Test public void testSecondarySource() throws Exception { when(sl2.load("source")).thenReturn(s2); Source source = creaMultiSourceLoader().load("source"); assertSame(s2, source); } private MultiSourceLoader creaMultiSourceLoader() { return new MultiSourceLoader().add(sl1).add(sl2); } }
src/test/java/org/eluder/coveralls/maven/plugin/source/MultiSourceLoaderTest.java
Tests for multi source loader.
src/test/java/org/eluder/coveralls/maven/plugin/source/MultiSourceLoaderTest.java
Tests for multi source loader.
<ide><path>rc/test/java/org/eluder/coveralls/maven/plugin/source/MultiSourceLoaderTest.java <add>package org.eluder.coveralls.maven.plugin.source; <add> <add>import static org.junit.Assert.assertSame; <add>import static org.mockito.Mockito.when; <add> <add>import java.io.IOException; <add> <add>import org.eluder.coveralls.maven.plugin.domain.Source; <add>import org.junit.Test; <add>import org.junit.runner.RunWith; <add>import org.mockito.Mock; <add>import org.mockito.runners.MockitoJUnitRunner; <add> <add>@RunWith(MockitoJUnitRunner.class) <add>public class MultiSourceLoaderTest { <add> <add> @Mock <add> private SourceLoader sl1; <add> <add> @Mock <add> private SourceLoader sl2; <add> <add> private Source s1 = new Source("source", "{ 1 }"); <add> <add> private Source s2 = new Source("source", "{ 2 }"); <add> <add> @Test(expected = IOException.class) <add> public void testMissingSource() throws Exception { <add> creaMultiSourceLoader().load("source"); <add> } <add> <add> @Test <add> public void testPrimarySource() throws Exception { <add> when(sl1.load("source")).thenReturn(s1); <add> when(sl2.load("source")).thenReturn(s2); <add> Source source = creaMultiSourceLoader().load("source"); <add> assertSame(s1, source); <add> } <add> <add> @Test <add> public void testSecondarySource() throws Exception { <add> when(sl2.load("source")).thenReturn(s2); <add> Source source = creaMultiSourceLoader().load("source"); <add> assertSame(s2, source); <add> } <add> <add> private MultiSourceLoader creaMultiSourceLoader() { <add> return new MultiSourceLoader().add(sl1).add(sl2); <add> } <add>}
Java
apache-2.0
cda2769ce0e3d9bb6980838279304433320c461b
0
KurtStam/fabric8,sobkowiak/fuse,mwringe/fabric8,rnc/fabric8,janstey/fuse-1,mwringe/fabric8,sobkowiak/fabric8,chirino/fuse,jonathanchristison/fabric8,rmarting/fuse,hekonsek/fabric8,jboss-fuse/fuse,dhirajsb/fabric8,gnodet/fuse,zmhassan/fabric8,jimmidyson/fabric8,dejanb/fuse,punkhorn/fuse,PhilHardwick/fabric8,hekonsek/fabric8,cunningt/fuse,tadayosi/fuse,aslakknutsen/fabric8,jimmidyson/fabric8,opensourceconsultant/fuse,punkhorn/fabric8,opensourceconsultant/fuse,janstey/fabric8,chirino/fabric8v2,gnodet/fuse,dhirajsb/fuse,gashcrumb/fabric8,dejanb/fuse,gashcrumb/fabric8,christian-posta/fabric8,mwringe/fabric8,rajdavies/fabric8,rmarting/fuse,christian-posta/fabric8,joelschuster/fuse,jboss-fuse/fuse,sobkowiak/fabric8,rnc/fabric8,chirino/fabric8,jludvice/fabric8,christian-posta/fabric8,dejanb/fuse,punkhorn/fabric8,jludvice/fabric8,rajdavies/fabric8,jonathanchristison/fabric8,zmhassan/fabric8,rajdavies/fabric8,jboss-fuse/fuse,mwringe/fabric8,rmarting/fuse,janstey/fuse-1,rhuss/fabric8,rnc/fabric8,dhirajsb/fabric8,jonathanchristison/fabric8,punkhorn/fuse,rnc/fabric8,zmhassan/fabric8,christian-posta/fabric8,hekonsek/fabric8,rhuss/fabric8,avano/fabric8,jimmidyson/fabric8,avano/fabric8,opensourceconsultant/fuse,chirino/fabric8,EricWittmann/fabric8,dhirajsb/fabric8,gashcrumb/fabric8,jimmidyson/fabric8,jludvice/fabric8,sobkowiak/fabric8,gnodet/fuse,chirino/fabric8,janstey/fuse,EricWittmann/fabric8,tadayosi/fuse,ffang/fuse-1,migue/fabric8,EricWittmann/fabric8,gashcrumb/fabric8,janstey/fabric8,KurtStam/fabric8,chirino/fabric8v2,KurtStam/fabric8,aslakknutsen/fabric8,KurtStam/fabric8,dhirajsb/fuse,rnc/fabric8,hekonsek/fabric8,migue/fabric8,PhilHardwick/fabric8,janstey/fuse-1,punkhorn/fabric8,rajdavies/fabric8,ffang/fuse-1,jonathanchristison/fabric8,PhilHardwick/fabric8,janstey/fuse,chirino/fuse,chirino/fabric8v2,gnodet/fuse,chirino/fabric8,migue/fabric8,EricWittmann/fabric8,jimmidyson/fabric8,avano/fabric8,ffang/fuse-1,janstey/fabric8,aslakknutsen/fabric8,zmhassan/fabric8,avano/fabric8,punkhorn/fabric8,janstey/fuse,cunningt/fuse,rhuss/fabric8,joelschuster/fuse,joelschuster/fuse,hekonsek/fabric8,rhuss/fabric8,sobkowiak/fuse,PhilHardwick/fabric8,jludvice/fabric8,janstey/fuse,dhirajsb/fabric8,chirino/fabric8v2,sobkowiak/fabric8,migue/fabric8
/** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.fabric.configadmin; import java.io.IOException; import java.io.InterruptedIOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs; import org.fusesource.fabric.zookeeper.ZkPath; import org.fusesource.fabric.zookeeper.utils.InterpolationHelper; import org.linkedin.zookeeper.client.IZKClient; import org.linkedin.zookeeper.client.LifecycleListener; import org.linkedin.zookeeper.tracker.NodeEvent; import org.linkedin.zookeeper.tracker.NodeEventsListener; import org.linkedin.zookeeper.tracker.TrackedNode; import org.linkedin.zookeeper.tracker.ZKStringDataReader; import org.linkedin.zookeeper.tracker.ZooKeeperTreeTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZooKeeperConfigAdminBridge implements NodeEventsListener<String>, LifecycleListener { public static final String PARENTS = "parents"; // = Profile.PARENTS; public static final String DELETED = "#deleted#"; public static final String FABRIC_ZOOKEEPER_PID = "fabric.zookeeper.pid"; public static final String FILEINSTALL = "felix.fileinstall.filename"; public static final String PROFILE_PROP_REGEX = "profile:[\\w\\.\\-]*/[\\w\\.\\-]*"; private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperConfigAdminBridge.class); private IZKClient zooKeeper; private ConfigurationAdmin configAdmin; private String name; private String version; private String node; private String resolutionPolicy; private Map<String, ZooKeeperTreeTracker<String>> trees = new ConcurrentHashMap<String, ZooKeeperTreeTracker<String>>(); private volatile boolean tracking = false; public void init() throws Exception { } public void destroy() throws Exception { for (ZooKeeperTreeTracker<String> tree : trees.values()) { tree.destroy(); } trees.clear(); } public void onConnected() { try { trees = new ConcurrentHashMap<String, ZooKeeperTreeTracker<String>>(); tracking = true; try { // Find our root node String versionNode = ZkPath.CONFIG_CONTAINER.getPath(name); if (zooKeeper.exists(versionNode) == null) { ZkPath.createContainerPaths(zooKeeper, name, null, "fabric"); } version = zooKeeper.getStringData(versionNode); if (version == null) { throw new IllegalStateException("Configuration for node " + name + " not found at " + ZkPath.CONFIG_CONTAINER.getPath(name)); } track(versionNode); node = ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, name); if (zooKeeper.exists(node) == null) { zooKeeper.createWithParents(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } track(node); resolutionPolicy = ZkPath.CONTAINER_RESOLVER.getPath(name); track(resolutionPolicy); } finally { tracking = false; } onEvents(null); } catch (Exception e) { LOGGER.warn("Exception when tracking configurations. This exception will be ignored.", e); } } public void onDisconnected() { } protected ZooKeeperTreeTracker<String> track(String path) throws InterruptedException, KeeperException, IOException { ZooKeeperTreeTracker<String> tree = trees.get(path); if (tree == null) { if (zooKeeper.exists(path) != null) { tree = new ZooKeeperTreeTracker<String>(zooKeeper, new ZKStringDataReader(), path); trees.put(path, tree); tree.track(this); String[] parents = getParents(tree.getTree().get(path)); for (String parent : parents) { track(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent)); } } else { // If the node does not exist yet, we track the parent to make // sure we receive the node creation event String p = ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version); if (!trees.containsKey(p)) { tree = new ZooKeeperTreeTracker<String>(zooKeeper, new ZKStringDataReader(), p, 1); trees.put(p, tree); tree.track(this); } return null; } } return tree; } static public Properties toProperties(String source) throws IOException { Properties rc = new Properties(); rc.load(new StringReader(source)); return rc; } static public String stripSuffix(String value, String suffix) { if (value.endsWith(suffix)) { return value.substring(0, value.length() - suffix.length()); } else { return value; } } public Map<String, Hashtable> load(Set<String> pids) throws IOException { final Map<String, Hashtable> configs = new HashMap<String, Hashtable>(); for (String pid : pids) { try { Hashtable props = new Hashtable(); load(pid, node, props); configs.put(pid, props); } catch (InterruptedException e) { throw (IOException) new InterruptedIOException("Error loading pid " + pid).initCause(e); } catch (KeeperException e) { throw (IOException) new IOException("Error loading pid " + pid).initCause(e); } } for (Map.Entry<String, Hashtable> entry : configs.entrySet()) { Hashtable props = entry.getValue(); InterpolationHelper.performSubstitution(props, new InterpolationHelper.SubstitutionCallback() { public String getValue(String key) { if (key.startsWith("zk:")) { try { return new String(ZkPath.loadURL(zooKeeper, key), "UTF-8"); } catch (KeeperException.ConnectionLossException e) { throw new RuntimeException(e); } catch (Exception e) { LOGGER.warn("Could not load zk value: {}. This exception will be ignored.", key, e); } } else if (key.matches(PROFILE_PROP_REGEX)) { String pid = key.substring("profile:".length(), key.indexOf("/")); String propertyKey = key.substring(key.indexOf("/") + 1); Hashtable targetProps = configs.get(pid); if (targetProps != null && targetProps.containsKey(propertyKey)) { return (String) targetProps.get(propertyKey); } else { return key; } } else { String value = key; BundleContext context = getBundleContext(); if (context != null) { value = context.getProperty(key); } if (value == null) { value = System.getProperty(key, ""); } return value; } return key; } }); } return configs; } private static BundleContext getBundleContext() { try { return FrameworkUtil.getBundle(ZooKeeperConfigAdminBridge.class).getBundleContext(); } catch (Throwable t) { return null; } } private void load(String pid, String node, Dictionary dict) throws KeeperException, InterruptedException, IOException { ZooKeeperTreeTracker<String> tree = track(node); TrackedNode<String> root = tree != null ? tree.getTree().get(node) : null; String[] parents = getParents(root); for (String parent : parents) { load(pid, ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent), dict); } TrackedNode<String> cfg = tree != null ? tree.getTree().get(node + "/" + pid + ".properties") : null; if (cfg != null) { //if (cfg != null && !DELETED.equals(cfg.getData())) { Properties properties = toProperties(cfg.getData()); // clear out the dict if it had a deleted key. if (properties.remove(DELETED) != null) { Enumeration keys = dict.keys(); while (keys.hasMoreElements()) { dict.remove(keys.nextElement()); } } for (Map.Entry<Object, Object> entry : properties.entrySet()) { if (DELETED.equals(entry.getValue())) { dict.remove(entry.getKey()); } else { dict.put(entry.getKey(), entry.getValue()); } } } } private String[] getParents(TrackedNode<String> root) throws IOException { String[] parents; if (root != null && root.getData() != null) { Properties props = toProperties(root.getData()); // For compatibility, check if we have instead the list of parents if (props.size() == 1) { String key = props.stringPropertyNames().iterator().next(); if (!key.equals(PARENTS)) { String val = props.getProperty(key); props.remove(key); props.setProperty(PARENTS, val.isEmpty() ? key : key + " " + val); } } parents = props.getProperty(PARENTS, "").split(" "); } else { parents = new String[0]; } return parents; } private Set<String> getPids() throws KeeperException, InterruptedException, IOException { Set<String> pids = new HashSet<String>(); getPids(node, pids); return pids; } private void getPids(String node, Set<String> pids) throws KeeperException, InterruptedException, IOException { ZooKeeperTreeTracker<String> tree = track(node); TrackedNode<String> root = tree != null ? tree.getTree().get(node) : null; String[] parents = getParents(root); for (String parent : parents) { getPids(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent), pids); } for (String pid : getChildren(tree, node)) { if (pid.endsWith(".properties")) { pid = stripSuffix(pid, ".properties"); pids.add(pid); } } } protected List<String> getChildren(ZooKeeperTreeTracker<String> tree, String node) { List<String> children = new ArrayList<String>(); if (tree != null) { Pattern p = Pattern.compile(node + "/[^/]*"); for (String c : tree.getTree().keySet()) { if (p.matcher(c).matches()) { children.add(c.substring(c.lastIndexOf('/') + 1)); } } } return children; } public void onEvents(Collection<NodeEvent<String>> nodeEvents) { LOGGER.trace("onEvents", nodeEvents); try { if (!tracking) { String version = zooKeeper.getStringData(ZkPath.CONFIG_CONTAINER.getPath(name)); if (zooKeeper.exists(ZkPath.CONTAINER_IP.getPath(name)) != null) { String resolutionPointer = zooKeeper.getStringData(ZkPath.CONTAINER_IP.getPath(name)); resolutionPolicy = zooKeeper.getStringData(ZkPath.CONTAINER_RESOLVER.getPath(name)); if (resolutionPointer == null || !resolutionPointer.contains(resolutionPolicy)) { zooKeeper.setData(ZkPath.CONTAINER_IP.getPath(name), "${zk:" + name + "/" + resolutionPolicy + "}"); } } if (!this.version.equals(version)) { this.version = version; node = ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, name); track(node); } final Set<String> pids = getPids(); Map<String, Hashtable> pidProperties = load(pids); List<Configuration> configs = asList(getConfigAdmin().listConfigurations("(" + FABRIC_ZOOKEEPER_PID + "=*)")); for (String pid : pids) { Hashtable c = pidProperties.get(pid); String p[] = parsePid(pid); //Get the configuration by fabric zookeeper pid, pid and factory pid. Configuration config = getConfiguration(pid, p[0], p[1]); configs.remove(config); Dictionary props = config.getProperties(); Hashtable old = props != null ? new Hashtable() : null; if (old != null) { for (Enumeration e = props.keys(); e.hasMoreElements(); ) { Object key = e.nextElement(); Object val = props.get(key); old.put(key, val); } old.remove(FABRIC_ZOOKEEPER_PID); old.remove(org.osgi.framework.Constants.SERVICE_PID); old.remove(ConfigurationAdmin.SERVICE_FACTORYPID); } if (!c.equals(old)) { LOGGER.info("Updating configuration {}", config.getPid()); c.put(FABRIC_ZOOKEEPER_PID, pid); if (config.getBundleLocation() != null) { config.setBundleLocation(null); } config.update(c); } else { LOGGER.info("Ignoring configuration {} (no changes)", config.getPid()); } } for (Configuration config : configs) { LOGGER.info("Deleting configuration {}", config.getPid()); config.delete(); } } LOGGER.trace("onEvents done"); } catch (Exception e) { LOGGER.warn("Exception when tracking configurations. This exception will be ignored.", e); } } public static <T> List<T> asList(T... a) { List<T> l = new ArrayList<T>(); if (a != null) { Collections.addAll(l, a); } return l; } /** * Splits a pid into service and factory pid. * * @param pid The pid to parse. * @return An arrays which contains the pid[0] the pid and pid[1] the factory pid if applicable. */ String[] parsePid(String pid) { int n = pid.indexOf('-'); if (n > 0) { String factoryPid = pid.substring(n + 1); pid = pid.substring(0, n); return new String[]{pid, factoryPid}; } else { return new String[]{pid, null}; } } Configuration getConfiguration(String zooKeeperPid, String pid, String factoryPid) throws Exception { String filter = "(" + FABRIC_ZOOKEEPER_PID + "=" + zooKeeperPid + ")"; Configuration[] oldConfiguration = getConfigAdmin().listConfigurations(filter); if (oldConfiguration != null && oldConfiguration.length > 0) { return oldConfiguration[0]; } else { Configuration newConfiguration; if (factoryPid != null) { newConfiguration = getConfigAdmin().createFactoryConfiguration(pid, null); } else { newConfiguration = getConfigAdmin().getConfiguration(pid, null); } return newConfiguration; } } public IZKClient getZooKeeper() { return zooKeeper; } public void setZooKeeper(IZKClient zooKeeper) { this.zooKeeper = zooKeeper; } public ConfigurationAdmin getConfigAdmin() { return configAdmin; } public void setConfigAdmin(ConfigurationAdmin configAdmin) { this.configAdmin = configAdmin; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
fabric/fabric-configadmin/src/main/java/org/fusesource/fabric/configadmin/ZooKeeperConfigAdminBridge.java
/** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.fabric.configadmin; import java.io.IOException; import java.io.InterruptedIOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs; import org.fusesource.fabric.zookeeper.ZkPath; import org.fusesource.fabric.zookeeper.utils.InterpolationHelper; import org.linkedin.zookeeper.client.IZKClient; import org.linkedin.zookeeper.client.LifecycleListener; import org.linkedin.zookeeper.tracker.NodeEvent; import org.linkedin.zookeeper.tracker.NodeEventsListener; import org.linkedin.zookeeper.tracker.TrackedNode; import org.linkedin.zookeeper.tracker.ZKStringDataReader; import org.linkedin.zookeeper.tracker.ZooKeeperTreeTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZooKeeperConfigAdminBridge implements NodeEventsListener<String>, LifecycleListener { public static final String PARENTS = "parents"; // = Profile.PARENTS; public static final String DELETED = "#deleted#"; public static final String FABRIC_ZOOKEEPER_PID = "fabric.zookeeper.pid"; public static final String FILEINSTALL = "felix.fileinstall.filename"; private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperConfigAdminBridge.class); private IZKClient zooKeeper; private ConfigurationAdmin configAdmin; private String name; private String version; private String node; private String resolutionPolicy; private Map<String, ZooKeeperTreeTracker<String>> trees = new ConcurrentHashMap<String, ZooKeeperTreeTracker<String>>(); private volatile boolean tracking = false; public void init() throws Exception { } public void destroy() throws Exception { for (ZooKeeperTreeTracker<String> tree : trees.values()) { tree.destroy(); } trees.clear(); } public void onConnected() { try { trees = new ConcurrentHashMap<String, ZooKeeperTreeTracker<String>>(); tracking = true; try { // Find our root node String versionNode = ZkPath.CONFIG_CONTAINER.getPath(name); if (zooKeeper.exists(versionNode) == null) { ZkPath.createContainerPaths(zooKeeper, name, null, "fabric"); } version = zooKeeper.getStringData(versionNode); if (version == null) { throw new IllegalStateException("Configuration for node " + name + " not found at " + ZkPath.CONFIG_CONTAINER.getPath(name)); } track(versionNode); node = ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, name); if (zooKeeper.exists(node) == null) { zooKeeper.createWithParents(node, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } track(node); resolutionPolicy = ZkPath.CONTAINER_RESOLVER.getPath(name); track(resolutionPolicy); } finally { tracking = false; } onEvents(null); } catch (Exception e) { LOGGER.warn("Exception when tracking configurations. This exception will be ignored.", e); } } public void onDisconnected() { } protected ZooKeeperTreeTracker<String> track(String path) throws InterruptedException, KeeperException, IOException { ZooKeeperTreeTracker<String> tree = trees.get(path); if (tree == null) { if (zooKeeper.exists(path) != null) { tree = new ZooKeeperTreeTracker<String>(zooKeeper, new ZKStringDataReader(), path); trees.put(path, tree); tree.track(this); String[] parents = getParents(tree.getTree().get(path)); for (String parent : parents) { track(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent)); } } else { // If the node does not exist yet, we track the parent to make // sure we receive the node creation event String p = ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version); if (!trees.containsKey(p)) { tree = new ZooKeeperTreeTracker<String>(zooKeeper, new ZKStringDataReader(), p, 1); trees.put(p, tree); tree.track(this); } return null; } } return tree; } static public Properties toProperties(String source) throws IOException { Properties rc = new Properties(); rc.load(new StringReader(source)); return rc; } static public String stripSuffix(String value, String suffix) { if(value.endsWith(suffix)) { return value.substring(0, value.length() -suffix.length()); } else { return value; } } public Dictionary load(String pid) throws IOException { try { Hashtable props = new Hashtable(); load(pid, node, props); InterpolationHelper.performSubstitution(props, new InterpolationHelper.SubstitutionCallback() { public String getValue(String key) { if (key.startsWith("zk:")) { try { return new String(ZkPath.loadURL(zooKeeper, key), "UTF-8"); } catch (KeeperException.ConnectionLossException e) { throw new RuntimeException(e); } catch (Exception e) { LOGGER.warn("Could not load zk value: {}. This exception will be ignored.", key, e); } } else { String value = key; BundleContext context = getBundleContext(); if (context != null) { value = context.getProperty(key); } if (value == null) { value = System.getProperty(key, ""); } return value; } return key; } }); return props; } catch (InterruptedException e) { throw (IOException) new InterruptedIOException("Error loading pid " + pid).initCause(e); } catch (KeeperException e) { throw (IOException) new IOException("Error loading pid " + pid).initCause(e); } } private static BundleContext getBundleContext() { try { return FrameworkUtil.getBundle(ZooKeeperConfigAdminBridge.class).getBundleContext(); } catch (Throwable t) { return null; } } private void load(String pid, String node, Dictionary dict) throws KeeperException, InterruptedException, IOException { ZooKeeperTreeTracker<String> tree = track(node); TrackedNode<String> root = tree != null ? tree.getTree().get(node) : null; String[] parents = getParents(root); for (String parent : parents) { load(pid, ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent), dict); } TrackedNode<String> cfg = tree != null ? tree.getTree().get(node + "/" + pid+".properties") : null; if (cfg != null) { //if (cfg != null && !DELETED.equals(cfg.getData())) { Properties properties = toProperties(cfg.getData()); // clear out the dict if it had a deleted key. if( properties.remove(DELETED)!=null ) { Enumeration keys = dict.keys(); while (keys.hasMoreElements()) { dict.remove(keys.nextElement()); } } for (Map.Entry<Object, Object> entry: properties.entrySet()){ if( DELETED.equals(entry.getValue()) ) { dict.remove(entry.getKey()); } else { dict.put(entry.getKey(), entry.getValue()); } } } } private String[] getParents(TrackedNode<String> root) throws IOException { String[] parents; if (root != null && root.getData() != null) { Properties props = toProperties(root.getData()); // For compatibility, check if we have instead the list of parents if (props.size() == 1) { String key = props.stringPropertyNames().iterator().next(); if (!key.equals(PARENTS)) { String val = props.getProperty(key); props.remove(key); props.setProperty(PARENTS, val.isEmpty() ? key : key + " " + val); } } parents = props.getProperty(PARENTS, "").split(" "); } else { parents = new String[0]; } return parents; } private Set<String> getPids() throws KeeperException, InterruptedException, IOException { Set<String> pids = new HashSet<String>(); getPids(node, pids); return pids; } private void getPids(String node, Set<String> pids) throws KeeperException, InterruptedException, IOException { ZooKeeperTreeTracker<String> tree = track(node); TrackedNode<String> root = tree != null ? tree.getTree().get(node) : null; String[] parents = getParents(root); for (String parent : parents) { getPids(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent), pids); } for (String pid : getChildren(tree, node)) { if(pid.endsWith(".properties")) { pid = stripSuffix(pid, ".properties"); pids.add(pid); } } } protected List<String> getChildren(ZooKeeperTreeTracker<String> tree, String node) { List<String> children = new ArrayList<String>(); if (tree != null) { Pattern p = Pattern.compile(node + "/[^/]*"); for (String c : tree.getTree().keySet()) { if (p.matcher(c).matches()) { children.add(c.substring(c.lastIndexOf('/') + 1)); } } } return children; } public void onEvents(Collection<NodeEvent<String>> nodeEvents) { LOGGER.trace("onEvents", nodeEvents); try { if (!tracking) { String version = zooKeeper.getStringData(ZkPath.CONFIG_CONTAINER.getPath(name)); if (zooKeeper.exists(ZkPath.CONTAINER_IP.getPath(name)) != null) { String resolutionPointer = zooKeeper.getStringData(ZkPath.CONTAINER_IP.getPath(name)); resolutionPolicy = zooKeeper.getStringData(ZkPath.CONTAINER_RESOLVER.getPath(name)); if (resolutionPointer == null || !resolutionPointer.contains(resolutionPolicy)) { zooKeeper.setData(ZkPath.CONTAINER_IP.getPath(name), "${zk:" + name + "/" + resolutionPolicy + "}"); } } if (!this.version.equals(version)) { this.version = version; node = ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(version, name); track(node); } final Set<String> pids = getPids(); List<Configuration> configs = asList(getConfigAdmin().listConfigurations("(" + FABRIC_ZOOKEEPER_PID + "=*)")); for (String pid : pids) { Dictionary c = load(pid); String p[] = parsePid(pid); Configuration config = getConfiguration(pid, p[0], p[1]); configs.remove(config); Dictionary props = config.getProperties(); Hashtable old = props != null ? new Hashtable() : null; if (old != null) { for (Enumeration e = props.keys(); e.hasMoreElements();) { Object key = e.nextElement(); Object val = props.get(key); old.put(key, val); } old.remove(FABRIC_ZOOKEEPER_PID); old.remove(org.osgi.framework.Constants.SERVICE_PID); old.remove(ConfigurationAdmin.SERVICE_FACTORYPID); } if (!c.equals(old)) { LOGGER.info("Updating configuration {}", config.getPid()); c.put(FABRIC_ZOOKEEPER_PID, pid); if (config.getBundleLocation() != null) { config.setBundleLocation(null); } config.update(c); } else { LOGGER.info("Ignoring configuration {} (no changes)", config.getPid()); } } for (Configuration config : configs) { LOGGER.info("Deleting configuration {}", config.getPid()); config.delete(); } } LOGGER.trace("onEvents done"); } catch (Exception e) { LOGGER.warn("Exception when tracking configurations. This exception will be ignored.", e); } } public static <T> List<T> asList(T... a) { List<T> l = new ArrayList<T>(); if (a != null) { Collections.addAll(l, a); } return l; } String[] parsePid(String pid) { int n = pid.indexOf('-'); if (n > 0) { String factoryPid = pid.substring(n + 1); pid = pid.substring(0, n); return new String[]{pid, factoryPid}; } else { return new String[]{pid, null}; } } Configuration getConfiguration(String zooKeeperPid, String pid, String factoryPid) throws Exception { String filter = "(" + FABRIC_ZOOKEEPER_PID + "=" + zooKeeperPid + ")"; Configuration[] oldConfiguration = getConfigAdmin().listConfigurations(filter); if (oldConfiguration != null && oldConfiguration.length > 0) { return oldConfiguration[0]; } else { Configuration newConfiguration; if (factoryPid != null) { newConfiguration = getConfigAdmin().createFactoryConfiguration(pid, null); } else { newConfiguration = getConfigAdmin().getConfiguration(pid, null); } return newConfiguration; } } public IZKClient getZooKeeper() { return zooKeeper; } public void setZooKeeper(IZKClient zooKeeper) { this.zooKeeper = zooKeeper; } public ConfigurationAdmin getConfigAdmin() { return configAdmin; } public void setConfigAdmin(ConfigurationAdmin configAdmin) { this.configAdmin = configAdmin; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
[FABRIC-211] Zookeeper configadmin bridge will now perform variable substitution using the placeholder ${profile:pid/key}.
fabric/fabric-configadmin/src/main/java/org/fusesource/fabric/configadmin/ZooKeeperConfigAdminBridge.java
[FABRIC-211] Zookeeper configadmin bridge will now perform variable substitution using the placeholder ${profile:pid/key}.
<ide><path>abric/fabric-configadmin/src/main/java/org/fusesource/fabric/configadmin/ZooKeeperConfigAdminBridge.java <ide> import java.util.Collections; <ide> import java.util.Dictionary; <ide> import java.util.Enumeration; <add>import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.Hashtable; <ide> import java.util.List; <ide> import java.util.Set; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.regex.Pattern; <del> <ide> import org.apache.zookeeper.CreateMode; <ide> import org.apache.zookeeper.KeeperException; <ide> import org.apache.zookeeper.ZooDefs; <ide> <ide> public static final String FILEINSTALL = "felix.fileinstall.filename"; <ide> <add> public static final String PROFILE_PROP_REGEX = "profile:[\\w\\.\\-]*/[\\w\\.\\-]*"; <add> <ide> private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperConfigAdminBridge.class); <ide> <ide> private IZKClient zooKeeper; <ide> } <ide> <ide> static public String stripSuffix(String value, String suffix) { <del> if(value.endsWith(suffix)) { <del> return value.substring(0, value.length() -suffix.length()); <add> if (value.endsWith(suffix)) { <add> return value.substring(0, value.length() - suffix.length()); <ide> } else { <ide> return value; <ide> } <ide> } <ide> <del> public Dictionary load(String pid) throws IOException { <del> try { <del> Hashtable props = new Hashtable(); <del> load(pid, node, props); <add> public Map<String, Hashtable> load(Set<String> pids) throws IOException { <add> final Map<String, Hashtable> configs = new HashMap<String, Hashtable>(); <add> for (String pid : pids) { <add> try { <add> Hashtable props = new Hashtable(); <add> load(pid, node, props); <add> configs.put(pid, props); <add> } catch (InterruptedException e) { <add> throw (IOException) new InterruptedIOException("Error loading pid " + pid).initCause(e); <add> } catch (KeeperException e) { <add> throw (IOException) new IOException("Error loading pid " + pid).initCause(e); <add> } <add> } <add> <add> for (Map.Entry<String, Hashtable> entry : configs.entrySet()) { <add> Hashtable props = entry.getValue(); <ide> InterpolationHelper.performSubstitution(props, new InterpolationHelper.SubstitutionCallback() { <ide> public String getValue(String key) { <ide> if (key.startsWith("zk:")) { <ide> } catch (Exception e) { <ide> LOGGER.warn("Could not load zk value: {}. This exception will be ignored.", key, e); <ide> } <add> } else if (key.matches(PROFILE_PROP_REGEX)) { <add> String pid = key.substring("profile:".length(), key.indexOf("/")); <add> String propertyKey = key.substring(key.indexOf("/") + 1); <add> Hashtable targetProps = configs.get(pid); <add> if (targetProps != null && targetProps.containsKey(propertyKey)) { <add> return (String) targetProps.get(propertyKey); <add> } else { <add> return key; <add> } <ide> } else { <ide> String value = key; <ide> BundleContext context = getBundleContext(); <ide> return key; <ide> } <ide> }); <del> return props; <del> } catch (InterruptedException e) { <del> throw (IOException) new InterruptedIOException("Error loading pid " + pid).initCause(e); <del> } catch (KeeperException e) { <del> throw (IOException) new IOException("Error loading pid " + pid).initCause(e); <del> } <add> } <add> return configs; <ide> } <ide> <ide> private static BundleContext getBundleContext() { <ide> for (String parent : parents) { <ide> load(pid, ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent), dict); <ide> } <del> TrackedNode<String> cfg = tree != null ? tree.getTree().get(node + "/" + pid+".properties") : null; <add> TrackedNode<String> cfg = tree != null ? tree.getTree().get(node + "/" + pid + ".properties") : null; <ide> if (cfg != null) { <del> //if (cfg != null && !DELETED.equals(cfg.getData())) { <add> //if (cfg != null && !DELETED.equals(cfg.getData())) { <ide> Properties properties = toProperties(cfg.getData()); <ide> <ide> // clear out the dict if it had a deleted key. <del> if( properties.remove(DELETED)!=null ) { <add> if (properties.remove(DELETED) != null) { <ide> Enumeration keys = dict.keys(); <ide> while (keys.hasMoreElements()) { <ide> dict.remove(keys.nextElement()); <ide> } <ide> } <ide> <del> for (Map.Entry<Object, Object> entry: properties.entrySet()){ <del> if( DELETED.equals(entry.getValue()) ) { <add> for (Map.Entry<Object, Object> entry : properties.entrySet()) { <add> if (DELETED.equals(entry.getValue())) { <ide> dict.remove(entry.getKey()); <ide> } else { <ide> dict.put(entry.getKey(), entry.getValue()); <ide> getPids(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, parent), pids); <ide> } <ide> for (String pid : getChildren(tree, node)) { <del> if(pid.endsWith(".properties")) { <add> if (pid.endsWith(".properties")) { <ide> pid = stripSuffix(pid, ".properties"); <ide> pids.add(pid); <ide> } <ide> track(node); <ide> } <ide> final Set<String> pids = getPids(); <add> Map<String, Hashtable> pidProperties = load(pids); <ide> List<Configuration> configs = asList(getConfigAdmin().listConfigurations("(" + FABRIC_ZOOKEEPER_PID + "=*)")); <ide> for (String pid : pids) { <del> Dictionary c = load(pid); <add> Hashtable c = pidProperties.get(pid); <ide> String p[] = parsePid(pid); <add> //Get the configuration by fabric zookeeper pid, pid and factory pid. <ide> Configuration config = getConfiguration(pid, p[0], p[1]); <ide> configs.remove(config); <ide> Dictionary props = config.getProperties(); <ide> Hashtable old = props != null ? new Hashtable() : null; <ide> if (old != null) { <del> for (Enumeration e = props.keys(); e.hasMoreElements();) { <add> for (Enumeration e = props.keys(); e.hasMoreElements(); ) { <ide> Object key = e.nextElement(); <ide> Object val = props.get(key); <ide> old.put(key, val); <ide> return l; <ide> } <ide> <add> /** <add> * Splits a pid into service and factory pid. <add> * <add> * @param pid The pid to parse. <add> * @return An arrays which contains the pid[0] the pid and pid[1] the factory pid if applicable. <add> */ <ide> String[] parsePid(String pid) { <ide> int n = pid.indexOf('-'); <ide> if (n > 0) {
Java
mit
246605733559858e9d76d1e4ee22e9d272f8c3ad
0
meeroslaph/bionic-qa-selenium
package tests.tickets; import org.testng.Assert; import org.testng.annotations.Test; import pages.HomePage; import pages.TicketsPage; import tests.BaseTest; import utils.Log4Test; public class BuyInfantTicketsTest extends BaseTest { @Test(dataProvider = "tickets", dataProviderClass = TicketsData.class) public void buyInfantTickets(int adults, int children, int infants) { HomePage homePage = new HomePage(driver); homePage.openAirTicketsPage(); TicketsPage ticketsPage = new TicketsPage(driver); ticketsPage.buyTickets(adults, children, infants); Assert.assertTrue(ticketsPage.isErrorMessageDisplayed(), Log4Test.error("Error pop-up is not displayed.")); } }
src/test/java/tests/tickets/BuyInfantTicketsTest.java
package tests.tickets; import org.testng.Assert; import org.testng.annotations.Test; import pages.HomePage; import pages.TicketsPage; import tests.BaseTest; import utils.Log4Test; public class BuyInfantTicketsTest extends BaseTest { @Test(dataProvider = "tickets", dataProviderClass = TicketsData.class) public void buyInfantTickets(int adults, int children, int infants) { HomePage homePage = new HomePage(driver); homePage.openAirTicketsPage(); TicketsPage ticketsPage = new TicketsPage(driver); ticketsPage.buyTickets(adults, children, infants); Assert.assertTrue(ticketsPage.isError(), Log4Test.error("Error pop-up is not displayed.")); } }
Updated method usage.
src/test/java/tests/tickets/BuyInfantTicketsTest.java
Updated method usage.
<ide><path>rc/test/java/tests/tickets/BuyInfantTicketsTest.java <ide> homePage.openAirTicketsPage(); <ide> TicketsPage ticketsPage = new TicketsPage(driver); <ide> ticketsPage.buyTickets(adults, children, infants); <del> Assert.assertTrue(ticketsPage.isError(), Log4Test.error("Error pop-up is not displayed.")); <add> Assert.assertTrue(ticketsPage.isErrorMessageDisplayed(), Log4Test.error("Error pop-up is not displayed.")); <ide> } <ide> }
Java
apache-2.0
d1cba3ae5a14c52aab36c3162dfe0656df8689b8
0
jitsi/jitsi,damencho/jitsi,HelioGuilherme66/jitsi,procandi/jitsi,gpolitis/jitsi,Metaswitch/jitsi,bebo/jitsi,jitsi/jitsi,procandi/jitsi,HelioGuilherme66/jitsi,mckayclarey/jitsi,marclaporte/jitsi,ringdna/jitsi,459below/jitsi,bhatvv/jitsi,ibauersachs/jitsi,dkcreinoso/jitsi,ibauersachs/jitsi,laborautonomo/jitsi,pplatek/jitsi,cobratbq/jitsi,tuijldert/jitsi,gpolitis/jitsi,procandi/jitsi,damencho/jitsi,level7systems/jitsi,tuijldert/jitsi,pplatek/jitsi,damencho/jitsi,laborautonomo/jitsi,bebo/jitsi,jibaro/jitsi,ringdna/jitsi,cobratbq/jitsi,mckayclarey/jitsi,jitsi/jitsi,459below/jitsi,bhatvv/jitsi,ibauersachs/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,cobratbq/jitsi,459below/jitsi,martin7890/jitsi,iant-gmbh/jitsi,ringdna/jitsi,iant-gmbh/jitsi,dkcreinoso/jitsi,marclaporte/jitsi,martin7890/jitsi,dkcreinoso/jitsi,level7systems/jitsi,459below/jitsi,jibaro/jitsi,Metaswitch/jitsi,pplatek/jitsi,level7systems/jitsi,damencho/jitsi,damencho/jitsi,mckayclarey/jitsi,jibaro/jitsi,gpolitis/jitsi,tuijldert/jitsi,HelioGuilherme66/jitsi,ringdna/jitsi,mckayclarey/jitsi,cobratbq/jitsi,HelioGuilherme66/jitsi,bhatvv/jitsi,procandi/jitsi,459below/jitsi,HelioGuilherme66/jitsi,level7systems/jitsi,laborautonomo/jitsi,cobratbq/jitsi,dkcreinoso/jitsi,mckayclarey/jitsi,procandi/jitsi,bebo/jitsi,Metaswitch/jitsi,ibauersachs/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,bebo/jitsi,pplatek/jitsi,martin7890/jitsi,bhatvv/jitsi,ibauersachs/jitsi,pplatek/jitsi,level7systems/jitsi,bebo/jitsi,martin7890/jitsi,ringdna/jitsi,tuijldert/jitsi,gpolitis/jitsi,jitsi/jitsi,dkcreinoso/jitsi,Metaswitch/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,gpolitis/jitsi,jitsi/jitsi,bhatvv/jitsi,laborautonomo/jitsi,jibaro/jitsi,laborautonomo/jitsi,jibaro/jitsi,martin7890/jitsi,tuijldert/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.protocol.sip; import gov.nist.javax.sip.address.*; import gov.nist.javax.sip.header.*; import gov.nist.javax.sip.message.*; import net.java.sip.communicator.impl.protocol.sip.security.*; import net.java.sip.communicator.impl.protocol.sip.xcap.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.version.Version; import net.java.sip.communicator.util.*; import org.osgi.framework.*; import javax.sip.*; import javax.sip.address.*; import javax.sip.header.*; import javax.sip.message.*; import java.net.*; import java.net.URI; import java.text.*; import java.util.*; /** * A SIP implementation of the Protocol Provider Service. * * @author Emil Ivov * @author Lubomir Marinov * @author Alan Kelly * @author Grigorii Balutsel */ public class ProtocolProviderServiceSipImpl extends AbstractProtocolProviderService implements SipListener, RegistrationStateChangeListener { /** * Our class logger. */ private static final Logger logger = Logger.getLogger(ProtocolProviderServiceSipImpl.class); /** * The identifier of the account that this provider represents. */ private AccountID accountID = null; /** * We use this to lock access to initialization. */ private final Object initializationLock = new Object(); /** * indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * A list of all events registered for this provider. */ private final List<String> registeredEvents = new ArrayList<String>(); /** * The AddressFactory used to create URLs ans Address objects. */ private AddressFactory addressFactory; /** * The HeaderFactory used to create SIP message headers. */ private HeaderFactory headerFactory; /** * The Message Factory used to create SIP messages. */ private SipMessageFactory messageFactory; /** * The class in charge of event dispatching and managing common JAIN-SIP * resources */ private static SipStackSharing sipStackSharing = null; /** * A table mapping SIP methods to method processors (every processor must * implement the SipListener interface). Whenever a new message arrives we * extract its method and hand it to the processor instance registered */ private final Hashtable<String, List<MethodProcessor>> methodProcessors = new Hashtable<String, List<MethodProcessor>>(); /** * The name of the property under which the user may specify the number of * the port where they would prefer us to bind our sip socket. */ private static final String PREFERRED_SIP_PORT = "net.java.sip.communicator.service.protocol.sip.PREFERRED_SIP_PORT"; /** * Property used in default settings if we want to override the system * property for java.net.preferIPv6Addresses, with values true or false. */ private static final String PREFER_IPV6_ADDRESSES = "net.java.sip.communicator.impl.protocol.sip.PREFER_IPV6_ADDRESSES"; /** * The name of the property under which the user may specify the number of * seconds that registrations take to expire. */ private static final String REGISTRATION_EXPIRATION = "net.java.sip.communicator.impl.protocol.sip.REGISTRATION_EXPIRATION"; /** * The name of the property under which the user may specify a transport * to use for destinations whose preferred transport is unknown. */ private static final String DEFAULT_TRANSPORT = "net.java.sip.communicator.impl.protocol.sip.DEFAULT_TRANSPORT"; /** * Default number of times that our requests can be forwarded. */ private static final int MAX_FORWARDS = 70; /** * Keep-alive method can be - register,options or udp */ public static final String KEEP_ALIVE_METHOD = "KEEP_ALIVE_METHOD"; /** * The interval for keep-alive */ public static final String KEEP_ALIVE_INTERVAL = "KEEP_ALIVE_INTERVAL"; /** * The name of the property under which the user may specify whether to use * or not XCAP. */ public static final String XCAP_ENABLE = "XCAP_ENABLE"; /** * The name of the property under which the user may specify whether to use * original sip creadetials for the XCAP. */ public static final String XCAP_USE_SIP_CREDETIALS = "XCAP_USE_SIP_CREDETIALS"; /** * The name of the property under which the user may specify the XCAP server * uri. */ public static final String XCAP_SERVER_URI = "XCAP_SERVER_URI"; /** * The name of the property under which the user may specify the XCAP user. */ public static final String XCAP_USER = "XCAP_USER"; /** * The name of the property under which the user may specify the XCAP user * password. */ public static final String XCAP_PASSWORD = "XCAP_PASSWORD"; /** * Presence content for image. */ public static final String PRES_CONTENT_IMAGE_NAME = "sip_communicator"; /** * The default maxForwards header that we use in our requests. */ private MaxForwardsHeader maxForwardsHeader = null; /** * The header that we use to identify ourselves. */ private UserAgentHeader userAgentHeader = null; /** * The name that we want to send others when calling or chatting with them. */ private String ourDisplayName = null; /** * Our current connection with the registrar. */ private SipRegistrarConnection sipRegistrarConnection = null; /** * The SipSecurityManager instance that would be taking care of our * authentications. */ private SipSecurityManager sipSecurityManager = null; /** * The string representing our outbound proxy if we have one (remains null * if we are not using a proxy). */ private String outboundProxyString = null; /** * The address and port of an outbound proxy if we have one (remains null * if we are not using a proxy). */ private InetSocketAddress outboundProxySocketAddress = null; /** * The transport used by our outbound proxy (remains null * if we are not using a proxy). */ private String outboundProxyTransport = null; /** * The logo corresponding to the jabber protocol. */ private ProtocolIconSipImpl protocolIcon; /** * The presence status set supported by this provider */ private SipStatusEnum sipStatusEnum; /** * The XCAP client. */ private final XCapClient xCapClient = new XCapClientImpl(); /** * A list of early processors that can do early processing of received * messages (requests or responses). */ private final List<SipMessageProcessor> earlyProcessors = new ArrayList<SipMessageProcessor>(); /** * Gets the XCAP client. * * @return the XCAP client. */ public XCapClient getXCapClient() { return xCapClient; } /** * Returns the AccountID that uniquely identifies the account represented by * this instance of the ProtocolProviderService. * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Returns the state of the registration of this protocol provider with the * corresponding registration service. * @return ProviderRegistrationState */ public RegistrationState getRegistrationState() { if(this.sipRegistrarConnection == null ) { return RegistrationState.UNREGISTERED; } return sipRegistrarConnection.getRegistrationState(); } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for * example). If the name of the protocol has been enumerated in * ProtocolNames then the value returned by this method must be the same as * the one in ProtocolNames. * @return a String containing the short name of the protocol this service * is implementing (most often that would be a name in ProtocolNames). */ public String getProtocolName() { return ProtocolNames.SIP; } /** * Register a new event taken in account by this provider. This is usefull * to generate the Allow-Events header of the OPTIONS responses and to * generate 489 responses. * * @param event The event to register */ public void registerEvent(String event) { synchronized (this.registeredEvents) { if (!this.registeredEvents.contains(event)) { this.registeredEvents.add(event); } } } /** * Returns the list of all the registered events for this provider. * * @return The list of all the registered events */ public List<String> getKnownEventsList() { return this.registeredEvents; } /** * Overrides * {@link AbstractProtocolProviderService#fireRegistrationStateChanged( * RegistrationState, RegistrationState, int, String)} in order to add * enabling/disabling XCAP functionality in accord with the current * <tt>RegistrationState</tt> of this * <tt>ProtocolProviderServiceSipImpl</tt>. * * @param oldState the state that the provider had before the change * occurred * @param newState the state that the provider is currently in * @param reasonCode a value corresponding to one of the REASON_XXX fields * of the <tt>RegistrationStateChangeEvent</tt> class, indicating the reason * for this state transition * @param reason a <tt>String</tt> further explaining the reason code or * <tt>null</tt> if no such explanation is necessary * @see AbstractProtocolProviderService#fireRegistrationStateChanged( * RegistrationState, RegistrationState, int, String) */ @Override public void fireRegistrationStateChanged(RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) { if (newState.equals(RegistrationState.REGISTERED)) { try { boolean enableXCap = accountID.getAccountPropertyBoolean(XCAP_ENABLE, true); boolean useSipCredetials = accountID.getAccountPropertyBoolean( XCAP_USE_SIP_CREDETIALS, true); String serverUri = accountID.getAccountPropertyString(XCAP_SERVER_URI); String username = accountID.getAccountPropertyString( ProtocolProviderFactory.USER_ID); Address userAddress = parseAddressString(username); String password; if (useSipCredetials) { username = ((SipUri)userAddress.getURI()).getUser(); password = SipActivator.getProtocolProviderFactory(). loadPassword(accountID); } else { username = accountID.getAccountPropertyString(XCAP_USER); password = accountID.getAccountPropertyString(XCAP_PASSWORD); } // Connect to xcap server if(enableXCap && serverUri != null) { URI uri = new URI(serverUri.trim()); if(uri.getHost() != null && uri.getPath() != null) { xCapClient.connect(uri, userAddress, username, password); } } } catch (Exception e) { logger.error("Error while connecting to XCAP server. " + "Contact list won't be saved", e); } } else if (newState.equals(RegistrationState.UNREGISTERING) || newState.equals(RegistrationState.CONNECTION_FAILED)) { xCapClient.disconnect(); } super.fireRegistrationStateChanged(oldState, newState, reasonCode, reason); } /** * Starts the registration process. Connection details such as * registration server, user name/number are provided through the * configuration service through implementation specific properties. * * @param authority the security authority that will be used for resolving * any security challenges that may be returned during the * registration or at any moment while wer're registered. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(SecurityAuthority authority) throws OperationFailedException { if(!isInitialized) { throw new OperationFailedException( "Provided must be initialized before being able to register." , OperationFailedException.GENERAL_ERROR); } if (isRegistered()) { return; } sipStackSharing.addSipListener(this); // be warned when we will unregister, so that we can // then remove us as SipListener this.addRegistrationStateChangeListener(this); // Enable the user name modification. Setting this property to true // we'll allow the user to change the user name stored in the given //authority. authority.setUserNameEditable(true); //init the security manager before doing the actual registration to //avoid being asked for credentials before being ready to provide them sipSecurityManager.setSecurityAuthority(authority); // We check here if the sipRegistrarConnection is initialized. This is // needed in case that in the initialization process we had no internet // connection and resolving the registrar failed. if (sipRegistrarConnection == null) initRegistrarConnection((SipAccountID) accountID); // The same here, we check if the outbound proxy is initialized in case // through the initialization process there was no internet connection. if (outboundProxySocketAddress == null) initOutboundProxy((SipAccountID)accountID, 0); //connect to the Registrar. if (sipRegistrarConnection != null) sipRegistrarConnection.register(); } /** * Ends the registration of this protocol provider with the current * registration service. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void unregister() throws OperationFailedException { if(getRegistrationState().equals(RegistrationState.UNREGISTERED) || getRegistrationState().equals(RegistrationState.UNREGISTERING) || getRegistrationState().equals(RegistrationState.CONNECTION_FAILED)) { return; } sipRegistrarConnection.unregister(); sipSecurityManager.setSecurityAuthority(null); } /** * Initializes the service implementation, and puts it in a state where it * could interoperate with other services. * * @param sipAddress the account id/uin/screenname of the account that we're * about to create * @param accountID the identifier of the account that this protocol * provider represents. * * @throws OperationFailedException with code INTERNAL_ERROR if we fail * initializing the SIP Stack. * @throws java.lang.IllegalArgumentException if one or more of the account * properties have invalid values. * * @see net.java.sip.communicator.service.protocol.AccountID */ protected void initialize(String sipAddress, SipAccountID accountID) throws OperationFailedException, IllegalArgumentException { synchronized (initializationLock) { this.accountID = accountID; String protocolIconPath = accountID .getAccountPropertyString(ProtocolProviderFactory.PROTOCOL_ICON_PATH); if (protocolIconPath == null) protocolIconPath = "resources/images/protocol/sip"; this.protocolIcon = new ProtocolIconSipImpl(protocolIconPath); this.sipStatusEnum = new SipStatusEnum(protocolIconPath); boolean isProxyValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_ADDRESS_VALIDATED, false); //init the proxy, we had to have at least one address configured // so use it, if it fails later we will use next one if(!isProxyValidated) initOutboundProxy(accountID, 0); //init proxy port int preferredSipPort = ListeningPoint.PORT_5060; String proxyPortStr = SipActivator.getConfigurationService(). getString(PREFERRED_SIP_PORT); if (proxyPortStr != null && proxyPortStr.length() > 0) { try { preferredSipPort = Integer.parseInt(proxyPortStr); } catch (NumberFormatException ex) { logger.error( proxyPortStr + " is not a valid port value. Expected an integer" , ex); } if (preferredSipPort > NetworkUtils.MAX_PORT_NUMBER) { logger.error(preferredSipPort + " is larger than " + NetworkUtils.MAX_PORT_NUMBER + " and does not " + "therefore represent a valid port number."); } } if(sipStackSharing == null) sipStackSharing = new SipStackSharing(); // get the presence options boolean enablePresence = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.IS_PRESENCE_ENABLED, true); boolean forceP2P = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.FORCE_P2P_MODE, true); int pollingValue = accountID.getAccountPropertyInt( ProtocolProviderFactory.POLLING_PERIOD, 30); int subscriptionExpiration = accountID.getAccountPropertyInt( ProtocolProviderFactory.SUBSCRIPTION_EXPIRATION, 3600); //create SIP factories. headerFactory = new HeaderFactoryImpl(); addressFactory = new AddressFactoryImpl(); //initialize our display name ourDisplayName = accountID.getAccountPropertyString( ProtocolProviderFactory.DISPLAY_NAME); if(ourDisplayName == null || ourDisplayName.trim().length() == 0) { ourDisplayName = accountID.getUserID(); } boolean isServerValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.SERVER_ADDRESS_VALIDATED, false); //create a connection with the registrar if(!isServerValidated) initRegistrarConnection(accountID); //init our call processor OperationSetBasicTelephonySipImpl opSetBasicTelephonySipImpl = new OperationSetBasicTelephonySipImpl(this); addSupportedOperationSet( OperationSetBasicTelephony.class, opSetBasicTelephonySipImpl); addSupportedOperationSet( OperationSetAdvancedTelephony.class, opSetBasicTelephonySipImpl); // init ZRTP (OperationSetBasicTelephonySipImpl implements // OperationSetSecureTelephony) addSupportedOperationSet( OperationSetSecureTelephony.class, opSetBasicTelephonySipImpl); //init presence op set. OperationSetPersistentPresence opSetPersPresence = new OperationSetPresenceSipImpl(this, enablePresence, forceP2P, pollingValue, subscriptionExpiration); addSupportedOperationSet( OperationSetPersistentPresence.class, opSetPersPresence); //also register with standard presence addSupportedOperationSet( OperationSetPresence.class, opSetPersPresence); if (enablePresence) { // init instant messaging OperationSetBasicInstantMessagingSipImpl opSetBasicIM = new OperationSetBasicInstantMessagingSipImpl(this); addSupportedOperationSet( OperationSetBasicInstantMessaging.class, opSetBasicIM); // init typing notifications addSupportedOperationSet( OperationSetTypingNotifications.class, new OperationSetTypingNotificationsSipImpl( this, opSetBasicIM)); OperationSetServerStoredAccountInfo opSetSSAccountInfo = new OperationSetServerStoredAccountInfoSipImpl(this); // init avatar addSupportedOperationSet( OperationSetServerStoredAccountInfo.class, opSetSSAccountInfo); addSupportedOperationSet( OperationSetAvatar.class, new OperationSetAvatarSipImpl(this, opSetSSAccountInfo)); } // OperationSetVideoTelephony addSupportedOperationSet( OperationSetVideoTelephony.class, new OperationSetVideoTelephonySipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopStreaming addSupportedOperationSet( OperationSetDesktopStreaming.class, new OperationSetDesktopStreamingSipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopSharingServer addSupportedOperationSet( OperationSetDesktopSharingServer.class, new OperationSetDesktopSharingServerSipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopSharingClient addSupportedOperationSet( OperationSetDesktopSharingClient.class, new OperationSetDesktopSharingClientSipImpl(this)); // init DTMF (from JM Heitz) addSupportedOperationSet( OperationSetDTMF.class, new OperationSetDTMFSipImpl(this)); addSupportedOperationSet( OperationSetTelephonyConferencing.class, new OperationSetTelephonyConferencingSipImpl(this)); addSupportedOperationSet( OperationSetMessageWaiting.class, new OperationSetMessageWaitingSipImpl(this)); //initialize our OPTIONS handler new ClientCapabilities(this); //init the security manager this.sipSecurityManager = new SipSecurityManager(accountID); sipSecurityManager.setHeaderFactory(headerFactory); // register any available custom extensions ProtocolProviderExtensions.registerCustomOperationSets(this); isInitialized = true; } } /** * Adds a specific <tt>OperationSet</tt> implementation to the set of * supported <tt>OperationSet</tt>s of this instance. Serves as a type-safe * wrapper around {@link #supportedOperationSets} which works with class * names instead of <tt>Class</tt> and also shortens the code which performs * such additions. * * @param <T> the exact type of the <tt>OperationSet</tt> implementation to * be added * @param opsetClass the <tt>Class</tt> of <tt>OperationSet</tt> under the * name of which the specified implementation is to be added * @param opset the <tt>OperationSet</tt> implementation to be added */ @Override protected <T extends OperationSet> void addSupportedOperationSet( Class<T> opsetClass, T opset) { super.addSupportedOperationSet(opsetClass, opset); } /** * Removes an <tt>OperationSet</tt> implementation from the set of * supported <tt>OperationSet</tt>s for this instance. * * @param <T> the exact type of the <tt>OperationSet</tt> implementation to * be added * @param opsetClass the <tt>Class</tt> of <tt>OperationSet</tt> under the * name of which the specified implementation is to be added */ @Override protected <T extends OperationSet> void removeSupportedOperationSet( Class<T> opsetClass) { super.removeSupportedOperationSet(opsetClass); } /** * Never called. * * @param exceptionEvent the IOExceptionEvent containing the cause. */ public void processIOException(IOExceptionEvent exceptionEvent) {} /** * Processes a Response received on a SipProvider upon which this * SipListener is registered. * <p> * * @param responseEvent the responseEvent fired from the SipProvider to the * SipListener representing a Response received from the network. */ public void processResponse(ResponseEvent responseEvent) { ClientTransaction clientTransaction = responseEvent .getClientTransaction(); if (clientTransaction == null) { if (logger.isDebugEnabled()) logger.debug("ignoring a transactionless response"); return; } Response response = responseEvent.getResponse(); earlyProcessMessage(responseEvent); String method = ( (CSeqHeader) response.getHeader(CSeqHeader.NAME)) .getMethod(); //find the object that is supposed to take care of responses with the //corresponding method List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) if (processor.processResponse(responseEvent)) break; } } /** * Processes a retransmit or expiration Timeout of an underlying * {@link Transaction} handled by this SipListener. This Event notifies the * application that a retransmission or transaction Timer expired in the * SipProvider's transaction state machine. The TimeoutEvent encapsulates * the specific timeout type and the transaction identifier either client or * server upon which the timeout occurred. The type of Timeout can by * determined by: * <code>timeoutType = timeoutEvent.getTimeout().getValue();</code> * * @param timeoutEvent - * the timeoutEvent received indicating either the message * retransmit or transaction timed out. */ public void processTimeout(TimeoutEvent timeoutEvent) { Transaction transaction; if(timeoutEvent.isServerTransaction()) transaction = timeoutEvent.getServerTransaction(); else transaction = timeoutEvent.getClientTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) logger.debug("ignoring a transactionless timeout event"); return; } earlyProcessMessage(timeoutEvent); Request request = transaction.getRequest(); if (logger.isDebugEnabled()) logger.debug("received timeout for req=" + request); //find the object that is supposed to take care of responses with the //corresponding method String method = request.getMethod(); List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processTimeout(timeoutEvent)) { break; } } } } /** * Process an asynchronously reported TransactionTerminatedEvent. * When a transaction transitions to the Terminated state, the stack * keeps no further records of the transaction. This notification can be used by * applications to clean up any auxiliary data that is being maintained * for the given transaction. * * @param transactionTerminatedEvent -- an event that indicates that the * transaction has transitioned into the terminated state. * @since v1.2 */ public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) { Transaction transaction; if(transactionTerminatedEvent.isServerTransaction()) transaction = transactionTerminatedEvent.getServerTransaction(); else transaction = transactionTerminatedEvent.getClientTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) logger.debug( "ignoring a transactionless transaction terminated event"); return; } Request request = transaction.getRequest(); //find the object that is supposed to take care of responses with the //corresponding method String method = request.getMethod(); List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processTransactionTerminated( transactionTerminatedEvent)) { break; } } } } /** * Process an asynchronously reported DialogTerminatedEvent. * When a dialog transitions to the Terminated state, the stack * keeps no further records of the dialog. This notification can be used by * applications to clean up any auxiliary data that is being maintained * for the given dialog. * * @param dialogTerminatedEvent -- an event that indicates that the * dialog has transitioned into the terminated state. * @since v1.2 */ public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { if (logger.isDebugEnabled()) logger.debug("Dialog terminated for req=" + dialogTerminatedEvent.getDialog()); } /** * Processes a Request received on a SipProvider upon which this SipListener * is registered. * <p> * @param requestEvent requestEvent fired from the SipProvider to the * SipListener representing a Request received from the network. */ public void processRequest(RequestEvent requestEvent) { Request request = requestEvent.getRequest(); if(getRegistrarConnection() != null && !getRegistrarConnection().isRegistrarless() && !getRegistrarConnection().isRequestFromSameConnection(request)) { logger.warn("Received request not from our proxy, ignoring it! " + "Request:" + request); if (requestEvent.getServerTransaction() != null) { try { requestEvent.getServerTransaction().terminate(); } catch (Throwable e) { logger.warn("Failed to properly terminate transaction for " +"a rogue request. Well ... so be it " + "Request:" + request); } } return; } earlyProcessMessage(requestEvent); // test if an Event header is present and known EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME); if (eventHeader != null) { boolean eventKnown; synchronized (this.registeredEvents) { eventKnown = this.registeredEvents.contains( eventHeader.getEventType()); } if (!eventKnown) { // send a 489 / Bad Event response ServerTransaction serverTransaction = requestEvent .getServerTransaction(); if (serverTransaction == null) { try { serverTransaction = SipStackSharing. getOrCreateServerTransaction(requestEvent); } catch (TransactionAlreadyExistsException ex) { //let's not scare the user and only log a message logger.error("Failed to create a new server" + "transaction for an incoming request\n" + "(Next message contains the request)" , ex); return; } catch (TransactionUnavailableException ex) { //let's not scare the user and only log a message logger.error("Failed to create a new server" + "transaction for an incoming request\n" + "(Next message contains the request)" , ex); return; } } Response response = null; try { response = this.getMessageFactory().createResponse( Response.BAD_EVENT, request); } catch (ParseException e) { logger.error("failed to create the 489 response", e); return; } try { serverTransaction.sendResponse(response); return; } catch (SipException e) { logger.error("failed to send the response", e); } catch (InvalidArgumentException e) { // should not happen logger.error("invalid argument provided while trying" + " to send the response", e); } } } String method = request.getMethod(); //find the object that is supposed to take care of responses with the //corresponding method List<MethodProcessor> processors = methodProcessors.get(method); //raise this flag if at least one processor handles the request. boolean processedAtLeastOnce = false; if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processRequest(requestEvent)) { processedAtLeastOnce = true; break; } } } //send an error response if no one processes this if (!processedAtLeastOnce) { ServerTransaction serverTransaction; try { serverTransaction = SipStackSharing.getOrCreateServerTransaction(requestEvent); if (serverTransaction == null) { logger.warn("Could not create a transaction for a " +"non-supported method " + request.getMethod()); return; } TransactionState state = serverTransaction.getState(); if( TransactionState.TRYING.equals(state)) { Response response = this.getMessageFactory().createResponse( Response.NOT_IMPLEMENTED, request); serverTransaction.sendResponse(response); } } catch (Throwable exc) { logger.warn("Could not respond to a non-supported method " + request.getMethod(), exc); } } } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for shutdown/garbage * collection. */ public void shutdown() { if(!isInitialized) { return; } // don't run in Thread cause shutting down may finish before // we were able to unregister new ShutdownThread().run(); } /** * The thread that we use in order to send our unREGISTER request upon * system shut down. */ protected class ShutdownThread implements Runnable { /** * Shutdowns operation sets that need it then calls the * <tt>SipRegistrarConnection.unregister()</tt> method. */ public void run() { if (logger.isTraceEnabled()) logger.trace("Killing the SIP Protocol Provider."); //kill all active calls OperationSetBasicTelephonySipImpl telephony = (OperationSetBasicTelephonySipImpl)getOperationSet( OperationSetBasicTelephony.class); telephony.shutdown(); if(isRegistered()) { try { //create a listener that would notify us when //un-registration has completed. ShutdownUnregistrationBlockListener listener = new ShutdownUnregistrationBlockListener(); addRegistrationStateChangeListener(listener); //do the un-registration unregister(); //leave ourselves time to complete un-registration (may include //2 REGISTER requests in case notification is needed.) listener.waitForEvent(3000L); } catch (OperationFailedException ex) { //we're shutting down so we need to silence the exception here logger.error( "Failed to properly unregister before shutting down. " + getAccountID() , ex); } } headerFactory = null; messageFactory = null; addressFactory = null; sipSecurityManager = null; methodProcessors.clear(); isInitialized = false; } } /** * Initializes and returns an ArrayList with a single ViaHeader * containing a localhost address usable with the specified * s<tt>destination</tt>. This ArrayList may be used when sending * requests to that destination. * <p> * @param intendedDestination The address of the destination that the * request using the via headers will be sent to. * * @return ViaHeader-s list to be used when sending requests. * @throws OperationFailedException code INTERNAL_ERROR if a ParseException * occurs while initializing the array list. * */ public ArrayList<ViaHeader> getLocalViaHeaders(Address intendedDestination) throws OperationFailedException { return getLocalViaHeaders((SipURI)intendedDestination.getURI()); } /** * Initializes and returns an ArrayList with a single ViaHeader * containing a localhost address usable with the specified * s<tt>destination</tt>. This ArrayList may be used when sending * requests to that destination. * <p> * @param intendedDestination The address of the destination that the * request using the via headers will be sent to. * * @return ViaHeader-s list to be used when sending requests. * @throws OperationFailedException code INTERNAL_ERROR if a ParseException * occurs while initializing the array list. * */ public ArrayList<ViaHeader> getLocalViaHeaders(SipURI intendedDestination) throws OperationFailedException { ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>(); ListeningPoint srcListeningPoint = getListeningPoint(intendedDestination.getTransportParam()); try { InetSocketAddress targetAddress = getIntendedDestination(intendedDestination); InetAddress localAddress = SipActivator .getNetworkAddressManagerService().getLocalHost( targetAddress.getAddress()); int localPort = srcListeningPoint.getPort(); String transport = srcListeningPoint.getTransport(); if (ListeningPoint.TCP.equalsIgnoreCase(transport)) //|| ListeningPoint.TLS.equalsIgnoreCase(transport) { InetSocketAddress localSockAddr = sipStackSharing.getLocalAddressForDestination( targetAddress.getAddress(), targetAddress.getPort(), localAddress, transport); localPort = localSockAddr.getPort(); } ViaHeader viaHeader = headerFactory.createViaHeader( localAddress.getHostAddress(), localPort, transport, null ); viaHeaders.add(viaHeader); if (logger.isDebugEnabled()) logger.debug("generated via headers:" + viaHeader); return viaHeaders; } catch (ParseException ex) { logger.error( "A ParseException occurred while creating Via Headers!", ex); throw new OperationFailedException( "A ParseException occurred while creating Via Headers!" ,OperationFailedException.INTERNAL_ERROR ,ex); } catch (InvalidArgumentException ex) { logger.error( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort(), ex); throw new OperationFailedException( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort() ,OperationFailedException.INTERNAL_ERROR ,ex); } catch (java.io.IOException ex) { logger.error( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort(), ex); throw new OperationFailedException( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort() ,OperationFailedException.NETWORK_FAILURE ,ex); } } /** * Initializes and returns this provider's default maxForwardsHeader field * using the value specified by MAX_FORWARDS. * * @return an instance of a MaxForwardsHeader that can be used when * sending requests * * @throws OperationFailedException with code INTERNAL_ERROR if MAX_FORWARDS * has an invalid value. */ public MaxForwardsHeader getMaxForwardsHeader() throws OperationFailedException { if (maxForwardsHeader == null) { try { maxForwardsHeader = headerFactory.createMaxForwardsHeader( MAX_FORWARDS); if (logger.isDebugEnabled()) logger.debug("generated max forwards: " + maxForwardsHeader.toString()); } catch (InvalidArgumentException ex) { throw new OperationFailedException( "A problem occurred while creating MaxForwardsHeader" , OperationFailedException.INTERNAL_ERROR , ex); } } return maxForwardsHeader; } /** * Returns a Contact header containing a sip URI based on a localhost * address. * * @param intendedDestination the destination that we plan to be sending * this contact header to. * * @return a Contact header based upon a local inet address. */ public ContactHeader getContactHeader(Address intendedDestination) { return getContactHeader((SipURI)intendedDestination.getURI()); } /** * Returns a Contact header containing a sip URI based on a localhost * address and therefore usable in REGISTER requests only. * * @param intendedDestination the destination that we plan to be sending * this contact header to. * * @return a Contact header based upon a local inet address. */ public ContactHeader getContactHeader(SipURI intendedDestination) { ContactHeader registrationContactHeader = null; ListeningPoint srcListeningPoint = getListeningPoint(intendedDestination); InetSocketAddress targetAddress = getIntendedDestination(intendedDestination); try { //find the address to use with the target InetAddress localAddress = SipActivator .getNetworkAddressManagerService() .getLocalHost(targetAddress.getAddress()); SipURI contactURI = addressFactory.createSipURI( getAccountID().getUserID() , localAddress.getHostAddress() ); String transport = srcListeningPoint.getTransport(); contactURI.setTransportParam(transport); int localPort = srcListeningPoint.getPort(); //if we are using tcp, make sure that we include the port of the //socket that we are actually using and not that of LP if (ListeningPoint.TCP.equalsIgnoreCase(transport) || ListeningPoint.TLS.equalsIgnoreCase(transport)) { InetSocketAddress localSockAddr = sipStackSharing.getLocalAddressForDestination( targetAddress.getAddress(), targetAddress.getPort(), localAddress, transport); localPort = localSockAddr.getPort(); } contactURI.setPort(localPort); // set a custom param to ease incoming requests dispatching in case // we have several registrar accounts with the same username String paramValue = getContactAddressCustomParamValue(); if (paramValue != null) { contactURI.setParameter( SipStackSharing.CONTACT_ADDRESS_CUSTOM_PARAM_NAME, paramValue); } Address contactAddress = addressFactory.createAddress( contactURI ); String ourDisplayName = getOurDisplayName(); if (ourDisplayName != null) { contactAddress.setDisplayName(ourDisplayName); } registrationContactHeader = headerFactory.createContactHeader( contactAddress); if (logger.isDebugEnabled()) logger.debug("generated contactHeader:" + registrationContactHeader); } catch (ParseException ex) { logger.error( "A ParseException occurred while creating From Header!", ex); throw new IllegalArgumentException( "A ParseException occurred while creating From Header!" , ex); } catch (java.io.IOException ex) { logger.error( "A ParseException occurred while creating From Header!", ex); throw new IllegalArgumentException( "A ParseException occurred while creating From Header!" , ex); } return registrationContactHeader; } /** * Returns null for a registraless account, a value for the contact address * custom parameter otherwise. This will help the dispatching of incoming * requests between accounts with the same username. For address-of-record * [email protected], the returned value woud be example_com. * * @return null for a registraless account, a value for the * "registering_acc" contact address parameter otherwise */ public String getContactAddressCustomParamValue() { SipRegistrarConnection src = getRegistrarConnection(); if (src != null && !src.isRegistrarless()) { // if we don't replace the dots in the hostname, we get // "476 No Server Address in Contacts Allowed" // from certain registrars (ippi.fr for instance) String hostValue = ((SipURI) src.getAddressOfRecord().getURI()) .getHost().replace('.', '_'); return hostValue; } return null; } /** * Returns the AddressFactory used to create URLs ans Address objects. * * @return the AddressFactory used to create URLs ans Address objects. */ public AddressFactory getAddressFactory() { return addressFactory; } /** * Returns the HeaderFactory used to create SIP message headers. * * @return the HeaderFactory used to create SIP message headers. */ public HeaderFactory getHeaderFactory() { return headerFactory; } /** * Returns the Message Factory used to create SIP messages. * * @return the Message Factory used to create SIP messages. */ public SipMessageFactory getMessageFactory() { if (messageFactory == null) { messageFactory = new SipMessageFactory(this, new MessageFactoryImpl()); } return messageFactory; } /** * Returns all running instances of ProtocolProviderServiceSipImpl * * @return all running instances of ProtocolProviderServiceSipImpl */ public static Set<ProtocolProviderServiceSipImpl> getAllInstances() { try { Set<ProtocolProviderServiceSipImpl> instances = new HashSet<ProtocolProviderServiceSipImpl>(); BundleContext context = SipActivator.getBundleContext(); ServiceReference[] references = context.getServiceReferences( ProtocolProviderService.class.getName(), null ); for(ServiceReference reference : references) { Object service = context.getService(reference); if(service instanceof ProtocolProviderServiceSipImpl) instances.add((ProtocolProviderServiceSipImpl) service); } return instances; } catch(InvalidSyntaxException ex) { if (logger.isDebugEnabled()) logger.debug("Problem parcing an osgi expression", ex); // should never happen so crash if it ever happens throw new RuntimeException( "getServiceReferences() wasn't supposed to fail!" ); } } /** * Returns the default listening point that we use for communication over * <tt>transport</tt>. * * @param transport the transport that the returned listening point needs * to support. * * @return the default listening point that we use for communication over * <tt>transport</tt> or null if no such transport is supported. */ public ListeningPoint getListeningPoint(String transport) { if(logger.isTraceEnabled()) logger.trace("Query for a " + transport + " listening point"); //override the transport in case we have an outbound proxy. if(getOutboundProxy() != null) { if (logger.isTraceEnabled()) logger.trace("Will use proxy address"); transport = outboundProxyTransport; } if( transport == null || transport.trim().length() == 0 || ( ! transport.trim().equalsIgnoreCase(ListeningPoint.TCP) && ! transport.trim().equalsIgnoreCase(ListeningPoint.UDP) && ! transport.trim().equalsIgnoreCase(ListeningPoint.TLS))) { transport = getDefaultTransport(); } ListeningPoint lp = null; if(transport.equalsIgnoreCase(ListeningPoint.UDP)) { lp = sipStackSharing.getLP(ListeningPoint.UDP); } else if(transport.equalsIgnoreCase(ListeningPoint.TCP)) { lp = sipStackSharing.getLP(ListeningPoint.TCP); } else if(transport.equalsIgnoreCase(ListeningPoint.TLS)) { lp = sipStackSharing.getLP(ListeningPoint.TLS); } if(logger.isTraceEnabled()) { logger.trace("Returning LP " + lp + " for transport [" + transport + "] and "); } return lp; } /** * Returns the default listening point that we should use to contact the * intended destination. * * @param intendedDestination the address that we will be trying to contact * through the listening point we are trying to obtain. * * @return the listening point that we should use to contact the * intended destination. */ public ListeningPoint getListeningPoint(Address intendedDestination) { return getListeningPoint((SipURI)intendedDestination.getURI()); } /** * Returns the default listening point that we should use to contact the * intended destination. * * @param intendedDestination the address that we will be trying to contact * through the listening point we are trying to obtain. * * @return the listening point that we should use to contact the * intended destination. */ public ListeningPoint getListeningPoint(SipURI intendedDestination) { String transport = intendedDestination.getTransportParam(); return getListeningPoint(transport); } /** * Returns the default jain sip provider that we use for communication over * <tt>transport</tt>. * * @param transport the transport that the returned provider needs * to support. * * @return the default jain sip provider that we use for communication over * <tt>transport</tt> or null if no such transport is supported. */ public SipProvider getJainSipProvider(String transport) { return sipStackSharing.getJainSipProvider(transport); } /** * Reurns the currently valid sip security manager that everyone should * use to authenticate SIP Requests. * @return the currently valid instace of a SipSecurityManager that everyone * sould use to authenticate SIP Requests. */ public SipSecurityManager getSipSecurityManager() { return sipSecurityManager; } /** * Initializes the SipRegistrarConnection that this class will be using. * * @param accountID the ID of the account that this registrar is associated * with. * @throws java.lang.IllegalArgumentException if one or more account * properties have invalid values. */ private void initRegistrarConnection(SipAccountID accountID) throws IllegalArgumentException { //First init the registrar address String registrarAddressStr = accountID .getAccountPropertyString(ProtocolProviderFactory.SERVER_ADDRESS); //if there is no registrar address, parse the user_id and extract it //from the domain part of the SIP URI. if (registrarAddressStr == null) { String userID = accountID .getAccountPropertyString(ProtocolProviderFactory.USER_ID); int index = userID.indexOf('@'); if ( index > -1 ) registrarAddressStr = userID.substring( index+1); } //if we still have no registrar address or if the registrar address //string is one of our local host addresses this means the users does //not want to use a registrar connection if(registrarAddressStr == null || registrarAddressStr.trim().length() == 0) { initRegistrarlessConnection(accountID); return; } //from this point on we are certain to have a registrar. InetSocketAddress[] registrarSocketAddresses = null; //registrar transport String registrarTransport = accountID.getAccountPropertyString( ProtocolProviderFactory.PREFERRED_TRANSPORT); if(registrarTransport != null && registrarTransport.length() > 0) { if( ! registrarTransport.equals(ListeningPoint.UDP) && !registrarTransport.equals(ListeningPoint.TCP) && !registrarTransport.equals(ListeningPoint.TLS)) { throw new IllegalArgumentException(registrarTransport + " is not a valid transport protocol. Transport must be " +"left blanc or set to TCP, UDP or TLS."); } } else { registrarTransport = getDefaultTransport(); } //init registrar port int registrarPort = ListeningPoint.PORT_5060; try { // if port is set we must use the explicitly set settings and // skip SRV queries if(accountID.getAccountProperty( ProtocolProviderFactory.SERVER_PORT) != null) { ArrayList<InetSocketAddress> registrarSocketAddressesList = new ArrayList<InetSocketAddress>(); // get only AAAA and A records resolveAddresses( registrarAddressStr, registrarSocketAddressesList, checkPreferIPv6Addresses(), registrarPort ); registrarSocketAddresses = registrarSocketAddressesList .toArray(new InetSocketAddress[0]); } else { ArrayList<InetSocketAddress> registrarSocketAddressesList = new ArrayList<InetSocketAddress>(); ArrayList<String> registrarTransports = new ArrayList<String>(); resolveSipAddress( registrarAddressStr, registrarTransport, registrarSocketAddressesList, registrarTransports, accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_AUTO_CONFIG, false)); registrarTransport = registrarTransports.get(0); registrarSocketAddresses = registrarSocketAddressesList .toArray(new InetSocketAddress[0]); } // We should set here the property to indicate that the server // address is validated. When we load stored accounts we check // this property in order to prevent checking again the server // address. And this is needed because in the case we don't have // network while loading the application we still want to have our // accounts loaded. if(registrarSocketAddresses != null && registrarSocketAddresses.length > 0) accountID.putAccountProperty( ProtocolProviderFactory.SERVER_ADDRESS_VALIDATED, Boolean.toString(true)); } catch (UnknownHostException ex) { if (logger.isDebugEnabled()) logger.debug(registrarAddressStr + " appears to be an either invalid" + " or inaccessible address.", ex); boolean isServerValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.SERVER_ADDRESS_VALIDATED, false); /* * We should check here if the server address was already validated. * When we load stored accounts we want to prevent checking again * the server address. This is needed because in the case we don't * have network while loading the application we still want to have * our accounts loaded. */ if (!isServerValidated) { throw new IllegalArgumentException( registrarAddressStr + " appears to be an either invalid" + " or inaccessible address.", ex); } } // If the registrar address is null we don't need to continue. // If we still have problems with initializing the registrar we are // telling the user. We'll enter here only if the server has been // already validated (this means that the account is already created // and we're trying to login, but we have no internet connection). if(registrarSocketAddresses == null || registrarSocketAddresses.length == 0) { fireRegistrationStateChanged( RegistrationState.UNREGISTERED, RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_SERVER_NOT_FOUND, "Invalid or inaccessible server address."); return; } // check if user has overridden the registrar port. registrarPort = accountID.getAccountPropertyInt( ProtocolProviderFactory.SERVER_PORT, registrarPort); if (registrarPort > NetworkUtils.MAX_PORT_NUMBER) { throw new IllegalArgumentException(registrarPort + " is larger than " + NetworkUtils.MAX_PORT_NUMBER + " and does not therefore represent a valid port number."); } //init expiration timeout int expires = SipActivator.getConfigurationService().getInt( REGISTRATION_EXPIRATION, SipRegistrarConnection.DEFAULT_REGISTRATION_EXPIRATION); //Initialize our connection with the registrar try { this.sipRegistrarConnection = new SipRegistrarConnection( registrarSocketAddresses , registrarTransport , expires , this); } catch (ParseException ex) { //this really shouldn't happen as we're using InetAddress-es logger.error("Failed to create a registrar connection with " +registrarSocketAddresses[0].getAddress().getHostAddress() , ex); throw new IllegalArgumentException( "Failed to create a registrar connection with " + registrarSocketAddresses[0].getAddress().getHostAddress() + ": " + ex.getMessage()); } } /** * Initializes the SipRegistrarConnection that this class will be using. * * @param accountID the ID of the account that this registrar is associated * with. * @throws java.lang.IllegalArgumentException if one or more account * properties have invalid values. */ private void initRegistrarlessConnection(SipAccountID accountID) throws IllegalArgumentException { //registrar transport String registrarTransport = accountID .getAccountPropertyString(ProtocolProviderFactory.PREFERRED_TRANSPORT); if(registrarTransport != null && registrarTransport.length() > 0) { if( ! registrarTransport.equals(ListeningPoint.UDP) && !registrarTransport.equals(ListeningPoint.TCP) && !registrarTransport.equals(ListeningPoint.TLS)) { throw new IllegalArgumentException(registrarTransport + " is not a valid transport protocol. Transport must be " +"left blanc or set to TCP, UDP or TLS."); } } else { registrarTransport = ListeningPoint.UDP; } //Initialize our connection with the registrar this.sipRegistrarConnection = new SipRegistrarlessConnection(this, registrarTransport); } /** * Returns the SIP address of record (Display Name <[email protected]>) that * this account is created for. The method takes into account whether or * not we are running in Registar or "No Registar" mode and either returns * the AOR we are using to register or an address constructed using the * local address. * * @param intendedDestination the destination that we would be using the * local address to communicate with. * * @return our Address Of Record that we should use in From headers. */ public Address getOurSipAddress(Address intendedDestination) { return getOurSipAddress((SipURI)intendedDestination.getURI()); } /** * Returns the SIP address of record (Display Name <[email protected]>) that * this account is created for. The method takes into account whether or * not we are running in Registar or "No Registar" mode and either returns * the AOR we are using to register or an address constructed using the * local address * * @param intendedDestination the destination that we would be using the * local address to communicate with. * . * @return our Address Of Record that we should use in From headers. */ public Address getOurSipAddress(SipURI intendedDestination) { SipRegistrarConnection src = getRegistrarConnection(); if( src != null && !src.isRegistrarless() ) return src.getAddressOfRecord(); //we are apparently running in "No Registrar" mode so let's create an //address by ourselves. InetSocketAddress destinationAddr = getIntendedDestination(intendedDestination); InetAddress localHost = SipActivator.getNetworkAddressManagerService() .getLocalHost(destinationAddr.getAddress()); String userID = getAccountID().getUserID(); try { SipURI ourSipURI = getAddressFactory() .createSipURI(userID, localHost.getHostAddress()); ListeningPoint lp = getListeningPoint(intendedDestination); ourSipURI.setTransportParam(lp.getTransport()); ourSipURI.setPort(lp.getPort()); Address ourSipAddress = getAddressFactory() .createAddress(getOurDisplayName(), ourSipURI); ourSipAddress.setDisplayName(getOurDisplayName()); return ourSipAddress; } catch (ParseException exc) { if (logger.isTraceEnabled()) logger.trace("Failed to create our SIP AOR address", exc); // this should never happen since we are using InetAddresses // everywhere so parsing could hardly go wrong. throw new IllegalArgumentException( "Failed to create our SIP AOR address" , exc); } } /** * In case we are using an outbound proxy this method returns * a suitable string for use with Router. * The method returns <tt>null</tt> otherwise. * * @return the string of our outbound proxy if we are using one and * <tt>null</tt> otherwise. */ public String getOutboundProxyString() { return this.outboundProxyString; } /** * In case we are using an outbound proxy this method returns its address. * The method returns <tt>null</tt> otherwise. * * @return the address of our outbound proxy if we are using one and * <tt>null</tt> otherwise. */ public InetSocketAddress getOutboundProxy() { return this.outboundProxySocketAddress; } /** * In case we are using an outbound proxy this method returns the transport * we are using to connect to it. The method returns <tt>null</tt> * otherwise. * * @return the transport used to connect to our outbound proxy if we are * using one and <tt>null</tt> otherwise. */ public String getOutboundProxyTransport() { return this.outboundProxyTransport; } /** * Extracts all properties concerning the usage of an outbound proxy for * this account. * @param accountID the account whose outbound proxy we are currently * initializing. * @param ix index of the address to use. */ void initOutboundProxy(SipAccountID accountID, int ix) { //First init the proxy address String proxyAddressStr = accountID .getAccountPropertyString(ProtocolProviderFactory. PROXY_ADDRESS); boolean proxyAddressAndPortEntered = false; if(proxyAddressStr == null || proxyAddressStr.trim().length() == 0) { proxyAddressStr = accountID .getAccountPropertyString(ProtocolProviderFactory. SERVER_ADDRESS); if(proxyAddressStr == null || proxyAddressStr.trim().length() == 0) { /* registrarless account */ return; } } else { if(accountID.getAccountProperty(ProtocolProviderFactory.PROXY_PORT) != null) { proxyAddressAndPortEntered = true; } } InetAddress proxyAddress = null; //init proxy port int proxyPort = ListeningPoint.PORT_5060; //proxy transport String proxyTransport = accountID.getAccountPropertyString( ProtocolProviderFactory.PREFERRED_TRANSPORT); if (proxyTransport != null && proxyTransport.length() > 0) { if (!proxyTransport.equals(ListeningPoint.UDP) && !proxyTransport.equals(ListeningPoint.TCP) && !proxyTransport.equals(ListeningPoint.TLS)) { throw new IllegalArgumentException(proxyTransport + " is not a valid transport protocol. Transport must be " + "left blank or set to TCP, UDP or TLS."); } } else { proxyTransport = getDefaultTransport(); } try { //check if user has overridden proxy port. proxyPort = accountID.getAccountPropertyInt( ProtocolProviderFactory.PROXY_PORT, proxyPort); if (proxyPort > NetworkUtils.MAX_PORT_NUMBER) { throw new IllegalArgumentException(proxyPort + " is larger than " + NetworkUtils.MAX_PORT_NUMBER + " and does not therefore represent a valid port number."); } InetSocketAddress proxySocketAddress = null; if(accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_AUTO_CONFIG, false)) { ArrayList<InetSocketAddress> proxySocketAddressesList = new ArrayList<InetSocketAddress>(); ArrayList<String> proxyTransportsList = new ArrayList<String>(); resolveSipAddress( proxyAddressStr, proxyTransport, proxySocketAddressesList, proxyTransportsList, true); proxyTransport = proxyTransportsList.get(ix); proxySocketAddress = proxySocketAddressesList.get(ix); } else { // according rfc3263 if proxy address and port are // explicitly entered don't make SRV queries if(proxyAddressAndPortEntered) { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); resolveAddresses( proxyAddressStr, addresses, checkPreferIPv6Addresses(), proxyPort); // only set if enough results found if(addresses.size() > ix) proxySocketAddress = addresses.get(ix); } else { ArrayList<InetSocketAddress> proxySocketAddressesList = new ArrayList<InetSocketAddress>(); ArrayList<String> proxyTransportsList = new ArrayList<String>(); resolveSipAddress( proxyAddressStr, proxyTransport, proxySocketAddressesList, proxyTransportsList, false); proxyTransport = proxyTransportsList.get(ix); proxySocketAddress = proxySocketAddressesList.get(ix); } } if(proxySocketAddress == null) throw new UnknownHostException(); proxyAddress = proxySocketAddress.getAddress(); proxyPort = proxySocketAddress.getPort(); if (logger.isTraceEnabled()) logger.trace("Setting proxy address = " + proxyAddressStr); // We should set here the property to indicate that the proxy // address is validated. When we load stored accounts we check // this property in order to prevent checking again the proxy // address. this is needed because in the case we don't have // network while loading the application we still want to have // our accounts loaded. accountID.putAccountProperty( ProtocolProviderFactory.PROXY_ADDRESS_VALIDATED, Boolean.toString(true)); } catch (UnknownHostException ex) { logger.error(proxyAddressStr + " appears to be an either invalid" + " or inaccessible address.", ex); boolean isProxyValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_ADDRESS_VALIDATED, false); // We should check here if the proxy address was already validated. // When we load stored accounts we want to prevent checking again the // proxy address. This is needed because in the case we don't have // network while loading the application we still want to have our // accounts loaded. if (!isProxyValidated) { throw new IllegalArgumentException( proxyAddressStr + " appears to be an either invalid or" + " inaccessible address.", ex); } } // Return if no proxy is specified or if the proxyAddress is null. if(proxyAddress == null) { return; } StringBuilder proxyStringBuffer = new StringBuilder(proxyAddress.getHostAddress()); if(proxyAddress instanceof Inet6Address) { proxyStringBuffer.insert(0, '['); proxyStringBuffer.append(']'); } proxyStringBuffer.append(':'); proxyStringBuffer.append(Integer.toString(proxyPort)); proxyStringBuffer.append('/'); proxyStringBuffer.append(proxyTransport); //done parsing. init properties. this.outboundProxyString = proxyStringBuffer.toString(); //store a reference to our sip proxy so that we can use it when //constructing via and contact headers. this.outboundProxySocketAddress = new InetSocketAddress(proxyAddress, proxyPort); this.outboundProxyTransport = proxyTransport; } /** * Registers <tt>methodProcessor</tt> in the <tt>methorProcessors</tt> table * so that it would receives all messages in a transaction initiated by a * <tt>method</tt> request. If any previous processors exist for the same * method, they will be replaced by this one. * * @param method a String representing the SIP method that we're registering * the processor for (e.g. INVITE, REGISTER, or SUBSCRIBE). * @param methodProcessor a <tt>MethodProcessor</tt> implementation that * would handle all messages received within a <tt>method</tt> * transaction. */ public void registerMethodProcessor(String method, MethodProcessor methodProcessor) { List<MethodProcessor> processors = methodProcessors.get(method); if (processors == null) { processors = new LinkedList<MethodProcessor>(); methodProcessors.put(method, processors); } else { /* * Prevent the registering of multiple instances of one and the same * OperationSet class and take only the latest registration into * account. */ Iterator<MethodProcessor> processorIter = processors.iterator(); Class<? extends MethodProcessor> methodProcessorClass = methodProcessor.getClass(); /* * EventPackageSupport and its extenders provide a generic mechanizm * for building support for a specific event package so allow them * to register multiple instances of one and the same class as long * as they are handling different event packages. */ String eventPackage = (methodProcessor instanceof EventPackageSupport) ? ((EventPackageSupport) methodProcessor).getEventPackage() : null; while (processorIter.hasNext()) { MethodProcessor processor = processorIter.next(); if (!processor.getClass().equals(methodProcessorClass)) continue; if ((eventPackage != null) && (processor instanceof EventPackageSupport) && !eventPackage .equals( ((EventPackageSupport) processor) .getEventPackage())) continue; processorIter.remove(); } } processors.add(methodProcessor); } /** * Unregisters <tt>methodProcessor</tt> from the <tt>methorProcessors</tt> * table so that it won't receive further messages in a transaction * initiated by a <tt>method</tt> request. * * @param method the name of the method whose processor we'd like to * unregister. * @param methodProcessor the <tt>MethodProcessor</tt> that we'd like to * unregister. */ public void unregisterMethodProcessor(String method, MethodProcessor methodProcessor) { List<MethodProcessor> processors = methodProcessors.get(method); if ((processors != null) && processors.remove(methodProcessor) && (processors.size() <= 0)) { methodProcessors.remove(method); } } /** * Returns the transport that we should use if we have no clear idea of our * destination's preferred transport. The method would first check if * we are running behind an outbound proxy and if so return its transport. * If no outbound proxy is set, the method would check the contents of the * DEFAULT_TRANSPORT property and return it if not null. Otherwise the * method would return UDP; * * @return The first non null password of the following: * a) the transport we use to communicate with our registrar * b) the transport of our outbound proxy, * c) the transport specified by the DEFAULT_TRANSPORT property, UDP. */ public String getDefaultTransport() { SipRegistrarConnection srConnection = getRegistrarConnection(); if( srConnection != null) { String registrarTransport = srConnection.getTransport(); if( registrarTransport != null && registrarTransport.length() > 0) { return registrarTransport; } } if(outboundProxySocketAddress != null && outboundProxyTransport != null) { return outboundProxyTransport; } else { String userSpecifiedDefaultTransport = SipActivator.getConfigurationService() .getString(DEFAULT_TRANSPORT); if(userSpecifiedDefaultTransport != null) { return userSpecifiedDefaultTransport; } else { String defTransportDefaultValue = SipActivator.getResources() .getSettingsString(DEFAULT_TRANSPORT); if(!StringUtils.isNullOrEmpty(defTransportDefaultValue)) return defTransportDefaultValue; else return ListeningPoint.UDP; } } } /** * Returns the provider that corresponds to the transport returned by * getDefaultTransport(). Equivalent to calling * getJainSipProvider(getDefaultTransport()) * * @return the Jain SipProvider that corresponds to the transport returned * by getDefaultTransport(). */ public SipProvider getDefaultJainSipProvider() { return getJainSipProvider(getDefaultTransport()); } /** * Returns the listening point that corresponds to the transport returned by * getDefaultTransport(). Equivalent to calling * getListeningPoint(getDefaultTransport()) * * @return the Jain SipProvider that corresponds to the transport returned * by getDefaultTransport(). */ public ListeningPoint getDefaultListeningPoint() { return getListeningPoint(getDefaultTransport()); } /** * Returns the display name string that the user has set as a display name * for this account. * * @return the display name string that the user has set as a display name * for this account. */ public String getOurDisplayName() { return ourDisplayName; } /** * Returns a User Agent header that could be used for signing our requests. * * @return a <tt>UserAgentHeader</tt> that could be used for signing our * requests. */ public UserAgentHeader getSipCommUserAgentHeader() { if(userAgentHeader == null) { try { List<String> userAgentTokens = new LinkedList<String>(); Version ver = SipActivator.getVersionService().getCurrentVersion(); userAgentTokens.add(ver.getApplicationName()); userAgentTokens.add(ver.toString()); String osName = System.getProperty("os.name"); userAgentTokens.add(osName); userAgentHeader = this.headerFactory.createUserAgentHeader(userAgentTokens); } catch (ParseException ex) { //shouldn't happen return null; } } return userAgentHeader; } /** * Send an error response with the <tt>errorCode</tt> code using * <tt>serverTransaction</tt> and do not surface exceptions. The method * is useful when we are sending the error response in a stack initiated * operation and don't have the possibility to escalate potential * exceptions, so we can only log them. * * @param serverTransaction the transaction that we'd like to send an error * response in. * @param errorCode the code that the response should have. */ public void sayErrorSilently(ServerTransaction serverTransaction, int errorCode) { try { sayError(serverTransaction, errorCode); } catch (OperationFailedException exc) { if (logger.isDebugEnabled()) logger.debug("Failed to send an error " + errorCode + " response", exc); } } /** * Sends an ACK request in the specified dialog. * * @param clientTransaction the transaction that resulted in the ACK we are * about to send (MUST be an INVITE transaction). * * @throws InvalidArgumentException if there is a problem with the supplied * CSeq ( for example <= 0 ). * @throws SipException if the CSeq does not relate to a previously sent * INVITE or if the Method that created the Dialog is not an INVITE ( for * example SUBSCRIBE) or if we fail to send the INVITE for whatever reason. */ public void sendAck(ClientTransaction clientTransaction) throws SipException, InvalidArgumentException { Request ack = messageFactory.createAck(clientTransaction); clientTransaction.getDialog().sendAck(ack); } /** * Send an error response with the <tt>errorCode</tt> code using * <tt>serverTransaction</tt>. * * @param serverTransaction the transaction that we'd like to send an error * response in. * @param errorCode the code that the response should have. * * @throws OperationFailedException if we failed constructing or sending a * SIP Message. */ public void sayError(ServerTransaction serverTransaction, int errorCode) throws OperationFailedException { Request request = serverTransaction.getRequest(); Response errorResponse = null; try { errorResponse = getMessageFactory().createResponse( errorCode, request); //we used to be adding a To tag here and we shouldn't. 3261 says: //"Dialogs are created through [...] non-failure responses". and //we are using this method for failure responses only. } catch (ParseException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to construct an OK response to an INVITE request", OperationFailedException.INTERNAL_ERROR, ex, logger); } try { serverTransaction.sendResponse(errorResponse); if (logger.isDebugEnabled()) logger.debug("sent response: " + errorResponse); } catch (Exception ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send an OK response to an INVITE request", OperationFailedException.INTERNAL_ERROR, ex, logger); } } /** * Sends a specific <tt>Request</tt> through a given * <tt>SipProvider</tt> as part of the conversation associated with a * specific <tt>Dialog</tt>. * * @param sipProvider the <tt>SipProvider</tt> to send the specified * request through * @param request the <tt>Request</tt> to send through * <tt>sipProvider</tt> * @param dialog the <tt>Dialog</tt> as part of which the specified * <tt>request</tt> is to be sent * * @throws OperationFailedException if creating a transaction or sending * the <tt>request</tt> fails. */ public void sendInDialogRequest(SipProvider sipProvider, Request request, Dialog dialog) throws OperationFailedException { ClientTransaction clientTransaction = null; try { clientTransaction = sipProvider.getNewClientTransaction(request); } catch (TransactionUnavailableException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to create a client transaction for request:\n" + request, OperationFailedException.INTERNAL_ERROR, ex, logger); } try { dialog.sendRequest(clientTransaction); } catch (SipException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send request:\n" + request, OperationFailedException.NETWORK_FAILURE, ex, logger); } if (logger.isDebugEnabled()) logger.debug("Sent request:\n" + request); } /** * Returns a List of Strings corresponding to all methods that we have a * processor for. * * @return a List of methods that we support. */ public List<String> getSupportedMethods() { return new ArrayList<String>(methodProcessors.keySet()); } /** * A utility class that allows us to block until we receive a * <tt>RegistrationStateChangeEvent</tt> notifying us of an unregistration. */ private static class ShutdownUnregistrationBlockListener implements RegistrationStateChangeListener { /** * The list where we store <tt>RegistationState</tt>s received while * waiting. */ public List<RegistrationState> collectedNewStates = new LinkedList<RegistrationState>(); /** * The method would simply register all received events so that they * could be available for later inspection by the unit tests. In the * case where a registration event notifying us of a completed * registration is seen, the method would call notifyAll(). * * @param evt ProviderStatusChangeEvent the event describing the * status change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { if (logger.isDebugEnabled()) logger.debug("Received a RegistrationStateChangeEvent: " + evt); collectedNewStates.add(evt.getNewState()); if (evt.getNewState().equals(RegistrationState.UNREGISTERED)) { if (logger.isDebugEnabled()) logger.debug( "We're unregistered and will notify those who wait"); synchronized (this) { notifyAll(); } } } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor milliseconds pass (whichever happens first). * * @param waitFor the number of milliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { if (logger.isTraceEnabled()) logger.trace("Waiting for a " +"RegistrationStateChangeEvent.UNREGISTERED"); synchronized (this) { if (collectedNewStates.contains( RegistrationState.UNREGISTERED)) { if (logger.isTraceEnabled()) logger.trace("Event already received. " + collectedNewStates); return; } try { wait(waitFor); if (collectedNewStates.size() > 0) if (logger.isTraceEnabled()) logger.trace( "Received a RegistrationStateChangeEvent."); else if (logger.isTraceEnabled()) logger.trace( "No RegistrationStateChangeEvent received for " + waitFor + "ms."); } catch (InterruptedException ex) { if (logger.isDebugEnabled()) logger.debug( "Interrupted while waiting for a " +"RegistrationStateChangeEvent" , ex); } } } } /** * Returns the sip protocol icon. * @return the sip protocol icon */ public ProtocolIcon getProtocolIcon() { return protocolIcon; } /** * Returns the current instance of <tt>SipStatusEnum</tt>. * * @return the current instance of <tt>SipStatusEnum</tt>. */ SipStatusEnum getSipStatusEnum() { return sipStatusEnum; } /** * Returns the current instance of <tt>SipRegistrarConnection</tt>. * @return SipRegistrarConnection */ SipRegistrarConnection getRegistrarConnection() { return sipRegistrarConnection; } /** * Parses the the <tt>uriStr</tt> string and returns a JAIN SIP URI. * * @param uriStr a <tt>String</tt> containing the uri to parse. * * @return a URI object corresponding to the <tt>uriStr</tt> string. * @throws ParseException if uriStr is not properly formatted. */ public Address parseAddressString(String uriStr) throws ParseException { uriStr = uriStr.trim(); //we don't know how to handle the "tel:" scheme ... or rather we handle //it same as sip so replace: if(uriStr.toLowerCase().startsWith("tel:")) uriStr = "sip:" + uriStr.substring("tel:".length()); //Handle default domain name (i.e. transform 1234 -> [email protected]) //assuming that if no domain name is specified then it should be the //same as ours. if (uriStr.indexOf('@') == -1) { //if we have a registrar, then we could append its domain name as //default SipRegistrarConnection src = getRegistrarConnection(); if(src != null && !src.isRegistrarless() ) { uriStr = uriStr + "@" + ((SipURI)src.getAddressOfRecord().getURI()).getHost(); } //else this could only be a host ... but this should work as is. } //Let's be uri fault tolerant and add the sip: scheme if there is none. if (!uriStr.toLowerCase().startsWith("sip:")) //no sip scheme { uriStr = "sip:" + uriStr; } Address toAddress = getAddressFactory().createAddress(uriStr); return toAddress; } /** * Tries to resolve <tt>address</tt> into a valid InetSocketAddress using * an <tt>SRV</tt> query where it exists and A/AAAA where it doesn't. * If there is no SRV,A or AAAA records return the socket address created * with the supplied <tt>address</tt>, so we can keep old behaviour. * When letting underling libs and java to resolve the address. * * @param address the address we'd like to resolve. * @param transport the protocol that we'd like to use when accessing * address. * @param resultAddresses the list that will be filled with the result * addresses. An <tt>InetSocketAddress</tt> instances containing the * <tt>SRV</tt> record for <tt>address</tt> if one has been defined and the * A/AAAA record where it hasn't. * @param resultTransports the transports for the <tt>resultAddresses</tt>. * @param resolveProtocol if the protocol should be resolved * @return the transports that is used, when the <tt>transport</tt> is with * value Auto we resolve the address with NAPTR query, if no NAPTR record * we will use the default one. * * @throws UnknownHostException if <tt>address</tt> is not a valid host * address. */ public void resolveSipAddress( String address, String transport, List<InetSocketAddress> resultAddresses, List<String> resultTransports, boolean resolveProtocol) throws UnknownHostException { //we need to resolve the address only if its a hostname. if(NetworkUtils.isValidIPAddress(address)) { InetAddress addressObj = NetworkUtils.getInetAddress(address); //this is an ip address so we need to return default ports since //we can't get them from a DNS. int port = ListeningPoint.PORT_5060; if(transport.equalsIgnoreCase(ListeningPoint.TLS)) port = ListeningPoint.PORT_5061; resultTransports.add(transport); resultAddresses.add(new InetSocketAddress(addressObj, port)); // as its ip address return, no dns is needed. return; } boolean preferIPv6Addresses = checkPreferIPv6Addresses(); // first make NAPTR resolve to get protocol, if needed if(resolveProtocol) { try { String[][] naptrRecords = NetworkUtils.getNAPTRRecords(address); if(naptrRecords != null && naptrRecords.length > 0) { for(String[] rec : naptrRecords) { resolveSRV( rec[2], rec[1], resultAddresses, resultTransports, preferIPv6Addresses, true); } // NAPTR found use only it if(logger.isInfoEnabled()) logger.info("Found NAPRT record and using it:" + resultAddresses); // return only if found something if(resultAddresses.size() > 0 && resultTransports.size() > 0) return; } } catch (ParseException e) { logger.error("Error parsing dns record.", e); } } //try to obtain SRV mappings from the DNS try { resolveSRV( address, transport, resultAddresses, resultTransports, preferIPv6Addresses, false); } catch (ParseException e) { logger.error("Error parsing dns record.", e); } //no SRV means default ports int defaultPort = ListeningPoint.PORT_5060; if(transport.equalsIgnoreCase(ListeningPoint.TLS)) defaultPort = ListeningPoint.PORT_5061; ArrayList<InetSocketAddress> tempResultAddresses = new ArrayList<InetSocketAddress>(); // after checking SRVs, lets add and AAAA and A records resolveAddresses( address, tempResultAddresses, preferIPv6Addresses, defaultPort); for(InetSocketAddress a : tempResultAddresses) { if(!resultAddresses.contains(a)) { resultAddresses.add(a); resultTransports.add(transport); } } // make sure we don't return empty array if(resultAddresses.size() == 0) { resultAddresses.add(new InetSocketAddress(address, defaultPort)); resultTransports.add(transport); // there were no SRV mappings so we only need to A/AAAA resolve the // address. Do this before we instantiate the // resulting InetSocketAddress because its constructor // suppresses UnknownHostException-s and we want to know if // something goes wrong. InetAddress addressObj = InetAddress.getByName(address); } } /** * Resolves the given address. Resolves A and AAAA records and returns * them in <tt>resultAddresses</tt> ordered according * <tt>preferIPv6Addresses</tt> option. * @param address the address to resolve. * @param resultAddresses the List in which we provide the result. * @param preferIPv6Addresses whether ipv6 address should go before ipv4. * @param defaultPort the port to use for the result address. * @throws UnknownHostException its not supposed to be thrown, cause * the address we use is an ip address. */ private void resolveAddresses( String address, List<InetSocketAddress> resultAddresses, boolean preferIPv6Addresses, int defaultPort) throws UnknownHostException { //we need to resolve the address only if its a hostname. if(NetworkUtils.isValidIPAddress(address)) { InetAddress addressObj = NetworkUtils.getInetAddress(address); resultAddresses.add(new InetSocketAddress(addressObj, defaultPort)); // as its ip address return, no dns is needed. return; } InetSocketAddress addressObj4 = null; InetSocketAddress addressObj6 = null; try { addressObj4 = NetworkUtils.getARecord(address, defaultPort); } catch (ParseException ex) { logger.error("Error parsing dns record.", ex); } try { addressObj6 = NetworkUtils.getAAAARecord(address, defaultPort); } catch (ParseException ex) { logger.error("Error parsing dns record.", ex); } if(preferIPv6Addresses) { if(addressObj6 != null && !resultAddresses.contains(addressObj6)) resultAddresses.add(addressObj6); if(addressObj4 != null && !resultAddresses.contains(addressObj4)) resultAddresses.add(addressObj4); } else { if(addressObj4 != null && !resultAddresses.contains(addressObj4)) resultAddresses.add(addressObj4); if(addressObj6 != null && !resultAddresses.contains(addressObj6)) resultAddresses.add(addressObj6); } if(addressObj4 == null && addressObj6 == null) logger.warn("No AAAA and A record found for " + address); } /** * Tries to resolve <tt>address</tt> into a valid InetSocketAddress using * an <tt>SRV</tt> query where it exists and A/AAAA where it doesn't. The * method assumes that the transport that we'll be using when connecting to * address is the one that has been defined as default for this provider. * * @param address the address we'd like to resolve. * * @return an <tt>InetSocketAddress</tt> instance containing the * <tt>SRV</tt> record for <tt>address</tt> if one has been defined and the * A/AAAA record where it hasn't. * * @throws UnknownHostException if <tt>address</tt> is not a valid host * address. */ public InetSocketAddress resolveSipAddress(String address) throws UnknownHostException { ArrayList<InetSocketAddress> socketAddressesList = new ArrayList<InetSocketAddress>(); resolveSipAddress(address, getDefaultTransport(), socketAddressesList, new ArrayList<String>(), getAccountID().getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_AUTO_CONFIG, false)); return socketAddressesList.get(0); } /** * Resolves the SRV records add their corresponding AAAA and A records * in the <tt>resultAddresses</tt> ordered by the preference * <tt>preferIPv6Addresses</tt> and their corresponding <tt>transport</tt> * in the <tt>resultTransports</tt>. * @param address the address to resolve. * @param transport the transport to use * @param resultAddresses the result address after resolve. * @param resultTransports and the addresses transports. * @param preferIPv6Addresses is ipv6 addresses are preferred over ipv4. * @param srvQueryString is the supplied address is of type * _sip(s)._protocol.address, a string ready for srv queries, used * when we have a NAPTR returned records with value <tt>true</tt>. * @throws ParseException exception when parsing dns address */ private void resolveSRV(String address, String transport, List<InetSocketAddress> resultAddresses, List<String> resultTransports, boolean preferIPv6Addresses, boolean srvQueryString) throws ParseException { SRVRecord srvRecords[] = null; if(srvQueryString) { srvRecords = NetworkUtils.getSRVRecords(address); } else { srvRecords = NetworkUtils.getSRVRecords( transport.equalsIgnoreCase(ListeningPoint.TLS) ? "sips" : "sip", transport.equalsIgnoreCase(ListeningPoint.UDP) ? ListeningPoint.UDP : ListeningPoint.TCP, address); } if(srvRecords != null) { ArrayList<InetSocketAddress> tempResultAddresses = new ArrayList<InetSocketAddress>(); for(SRVRecord s : srvRecords) { // add corresponding A and AAAA records // to the host address from SRV records try { // as these are already resolved addresses (the SRV res.) // lets get it without triggering a PTR resolveAddresses( s.getTarget(), tempResultAddresses, preferIPv6Addresses, s.getPort()); } catch(UnknownHostException e) { logger.warn("Address unknown:" + s.getTarget(), e); } /* add and every SRV address itself if not already there if(!tempResultAddresses.contains(s)) tempResultAddresses.add(s); */ if (logger.isTraceEnabled()) logger.trace("Returned SRV " + s); } for(InetSocketAddress a : tempResultAddresses) { if(!resultAddresses.contains(a)) { resultAddresses.add(a); resultTransports.add(transport); } } } } /** * Returns the <tt>InetAddress</tt> that is most likely to be to be used * as a next hop when contacting the specified <tt>destination</tt>. This is * an utility method that is used whenever we have to choose one of our * local addresses to put in the Via, Contact or (in the case of no * registrar accounts) From headers. The method also takes into account * the existence of an outbound proxy and in that case returns its address * as the next hop. * * @param destination the destination that we would contact. * * @return the <tt>InetSocketAddress</tt> that is most likely to be to be * used as a next hop when contacting the specified <tt>destination</tt>. * * @throws IllegalArgumentException if <tt>destination</tt> is not a valid * host/ip/fqdn */ public InetSocketAddress getIntendedDestination(Address destination) throws IllegalArgumentException { return getIntendedDestination((SipURI)destination.getURI()); } /** * Returns the <tt>InetAddress</tt> that is most likely to be to be used * as a next hop when contacting the specified <tt>destination</tt>. This is * an utility method that is used whenever we have to choose one of our * local addresses to put in the Via, Contact or (in the case of no * registrar accounts) From headers. The method also takes into account * the existence of an outbound proxy and in that case returns its address * as the next hop. * * @param destination the destination that we would contact. * * @return the <tt>InetSocketAddress</tt> that is most likely to be to be * used as a next hop when contacting the specified <tt>destination</tt>. * * @throws IllegalArgumentException if <tt>destination</tt> is not a valid * host/ip/fqdn */ public InetSocketAddress getIntendedDestination(SipURI destination) throws IllegalArgumentException { return getIntendedDestination(destination.getHost()); } /** * Returns the <tt>InetAddress</tt> that is most likely to be to be used * as a next hop when contacting the specified <tt>destination</tt>. This is * an utility method that is used whenever we have to choose one of our * local addresses to put in the Via, Contact or (in the case of no * registrar accounts) From headers. The method also takes into account * the existence of an outbound proxy and in that case returns its address * as the next hop. * * @param host the destination that we would contact. * * @return the <tt>InetSocketAddress</tt> that is most likely to be to be * used as a next hop when contacting the specified <tt>destination</tt>. * * @throws IllegalArgumentException if <tt>destination</tt> is not a valid * host/ip/fqdn. */ public InetSocketAddress getIntendedDestination(String host) throws IllegalArgumentException { // Address InetSocketAddress destinationInetAddress = null; //resolveSipAddress() verifies whether our destination is valid //but the destination could only be known to our outbound proxy //if we have one. If this is the case replace the destination //address with that of the proxy.(report by Dan Bogos) InetSocketAddress outboundProxy = getOutboundProxy(); if(outboundProxy != null) { if (logger.isTraceEnabled()) logger.trace("Will use proxy address"); destinationInetAddress = outboundProxy; } else { try { destinationInetAddress = resolveSipAddress(host); } catch (UnknownHostException ex) { throw new IllegalArgumentException( host + " is not a valid internet address.", ex); } } if(logger.isDebugEnabled()) logger.debug("Returning address " + destinationInetAddress + " for destination " + host); return destinationInetAddress; } /** * Stops dispatching SIP messages to a SIP protocol provider service * once it's been unregistered. * * @param event the change event in the registration state of a provider. */ public void registrationStateChanged(RegistrationStateChangeEvent event) { if(event.getNewState() == RegistrationState.UNREGISTERED || event.getNewState() == RegistrationState.CONNECTION_FAILED) { ProtocolProviderServiceSipImpl listener = (ProtocolProviderServiceSipImpl) event.getProvider(); sipStackSharing.removeSipListener(listener); listener.removeRegistrationStateChangeListener(this); } } /** * Logs a specific message and associated <tt>Throwable</tt> cause as an * error using the current <tt>Logger</tt> and then throws a new * <tt>OperationFailedException</tt> with the message, a specific error code * and the cause. * * @param message the message to be logged and then wrapped in a new * <tt>OperationFailedException</tt> * @param errorCode the error code to be assigned to the new * <tt>OperationFailedException</tt> * @param cause the <tt>Throwable</tt> that has caused the necessity to log * an error and have a new <tt>OperationFailedException</tt> thrown * @param logger the logger that we'd like to log the error <tt>message</tt> * and <tt>cause</tt>. * * @throws OperationFailedException the exception that we wanted this method * to throw. */ public static void throwOperationFailedException( String message, int errorCode, Throwable cause, Logger logger) throws OperationFailedException { logger.error(message, cause); if(cause == null) throw new OperationFailedException(message, errorCode); else throw new OperationFailedException(message, errorCode, cause); } /** * Check is property java.net.preferIPv6Addresses has default value * set in the application using our property: * net.java.sip.communicator.impl.protocol.sip.PREFER_IPV6_ADDRESSES * if not set - use setting from the system property. * @return is property java.net.preferIPv6Addresses <code>"true"</code>. */ public static boolean checkPreferIPv6Addresses() { String defaultSetting = SipActivator.getResources().getSettingsString( PREFER_IPV6_ADDRESSES); if(!StringUtils.isNullOrEmpty(defaultSetting)) return Boolean.parseBoolean(defaultSetting); // if there is no default setting return the system wide value. return Boolean.getBoolean("java.net.preferIPv6Addresses"); } /** * Registers early message processor. * @param processor early message processor. */ void addEarlyMessageProcessor(SipMessageProcessor processor) { synchronized (earlyProcessors) { if (!earlyProcessors.contains(processor)) { this.earlyProcessors.add(processor); } } } /** * Removes the early message processor. * @param processor early message processor. */ void removeEarlyMessageProcessor(SipMessageProcessor processor) { synchronized (earlyProcessors) { this.earlyProcessors.remove(processor); } } /** * Early process an incoming message from interested listeners. * @param message the message to process. */ void earlyProcessMessage(EventObject message) { synchronized(earlyProcessors) { for (SipMessageProcessor listener : earlyProcessors) { try { if(message instanceof RequestEvent) listener.processMessage((RequestEvent)message); else if(message instanceof ResponseEvent) listener.processResponse((ResponseEvent)message, null); else if(message instanceof TimeoutEvent) listener.processTimeout((TimeoutEvent)message, null); } catch(Throwable t) { logger.error("Error pre-processing message", t); } } } } }
src/net/java/sip/communicator/impl/protocol/sip/ProtocolProviderServiceSipImpl.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.protocol.sip; import gov.nist.javax.sip.address.*; import gov.nist.javax.sip.header.*; import gov.nist.javax.sip.message.*; import net.java.sip.communicator.impl.protocol.sip.security.*; import net.java.sip.communicator.impl.protocol.sip.xcap.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.version.Version; import net.java.sip.communicator.util.*; import org.osgi.framework.*; import javax.sip.*; import javax.sip.address.*; import javax.sip.header.*; import javax.sip.message.*; import java.net.*; import java.net.URI; import java.text.*; import java.util.*; /** * A SIP implementation of the Protocol Provider Service. * * @author Emil Ivov * @author Lubomir Marinov * @author Alan Kelly * @author Grigorii Balutsel */ public class ProtocolProviderServiceSipImpl extends AbstractProtocolProviderService implements SipListener, RegistrationStateChangeListener { /** * Our class logger. */ private static final Logger logger = Logger.getLogger(ProtocolProviderServiceSipImpl.class); /** * The identifier of the account that this provider represents. */ private AccountID accountID = null; /** * We use this to lock access to initialization. */ private final Object initializationLock = new Object(); /** * indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * A list of all events registered for this provider. */ private final List<String> registeredEvents = new ArrayList<String>(); /** * The AddressFactory used to create URLs ans Address objects. */ private AddressFactory addressFactory; /** * The HeaderFactory used to create SIP message headers. */ private HeaderFactory headerFactory; /** * The Message Factory used to create SIP messages. */ private SipMessageFactory messageFactory; /** * The class in charge of event dispatching and managing common JAIN-SIP * resources */ private static SipStackSharing sipStackSharing = null; /** * A table mapping SIP methods to method processors (every processor must * implement the SipListener interface). Whenever a new message arrives we * extract its method and hand it to the processor instance registered */ private final Hashtable<String, List<MethodProcessor>> methodProcessors = new Hashtable<String, List<MethodProcessor>>(); /** * The name of the property under which the user may specify the number of * the port where they would prefer us to bind our sip socket. */ private static final String PREFERRED_SIP_PORT = "net.java.sip.communicator.service.protocol.sip.PREFERRED_SIP_PORT"; /** * Property used in default settings if we want to override the system * property for java.net.preferIPv6Addresses, with values true or false. */ private static final String PREFER_IPV6_ADDRESSES = "net.java.sip.communicator.impl.protocol.sip.PREFER_IPV6_ADDRESSES"; /** * The name of the property under which the user may specify the number of * seconds that registrations take to expire. */ private static final String REGISTRATION_EXPIRATION = "net.java.sip.communicator.impl.protocol.sip.REGISTRATION_EXPIRATION"; /** * The name of the property under which the user may specify a transport * to use for destinations whose preferred transport is unknown. */ private static final String DEFAULT_TRANSPORT = "net.java.sip.communicator.impl.protocol.sip.DEFAULT_TRANSPORT"; /** * Default number of times that our requests can be forwarded. */ private static final int MAX_FORWARDS = 70; /** * Keep-alive method can be - register,options or udp */ public static final String KEEP_ALIVE_METHOD = "KEEP_ALIVE_METHOD"; /** * The interval for keep-alive */ public static final String KEEP_ALIVE_INTERVAL = "KEEP_ALIVE_INTERVAL"; /** * The name of the property under which the user may specify whether to use * or not XCAP. */ public static final String XCAP_ENABLE = "XCAP_ENABLE"; /** * The name of the property under which the user may specify whether to use * original sip creadetials for the XCAP. */ public static final String XCAP_USE_SIP_CREDETIALS = "XCAP_USE_SIP_CREDETIALS"; /** * The name of the property under which the user may specify the XCAP server * uri. */ public static final String XCAP_SERVER_URI = "XCAP_SERVER_URI"; /** * The name of the property under which the user may specify the XCAP user. */ public static final String XCAP_USER = "XCAP_USER"; /** * The name of the property under which the user may specify the XCAP user * password. */ public static final String XCAP_PASSWORD = "XCAP_PASSWORD"; /** * Presence content for image. */ public static final String PRES_CONTENT_IMAGE_NAME = "sip_communicator"; /** * The default maxForwards header that we use in our requests. */ private MaxForwardsHeader maxForwardsHeader = null; /** * The header that we use to identify ourselves. */ private UserAgentHeader userAgentHeader = null; /** * The name that we want to send others when calling or chatting with them. */ private String ourDisplayName = null; /** * Our current connection with the registrar. */ private SipRegistrarConnection sipRegistrarConnection = null; /** * The SipSecurityManager instance that would be taking care of our * authentications. */ private SipSecurityManager sipSecurityManager = null; /** * The string representing our outbound proxy if we have one (remains null * if we are not using a proxy). */ private String outboundProxyString = null; /** * The address and port of an outbound proxy if we have one (remains null * if we are not using a proxy). */ private InetSocketAddress outboundProxySocketAddress = null; /** * The transport used by our outbound proxy (remains null * if we are not using a proxy). */ private String outboundProxyTransport = null; /** * The logo corresponding to the jabber protocol. */ private ProtocolIconSipImpl protocolIcon; /** * The presence status set supported by this provider */ private SipStatusEnum sipStatusEnum; /** * The XCAP client. */ private final XCapClient xCapClient = new XCapClientImpl(); /** * A list of early processors that can do early processing of received * messages (requests or responses). */ private final List<SipMessageProcessor> earlyProcessors = new ArrayList<SipMessageProcessor>(); /** * Gets the XCAP client. * * @return the XCAP client. */ public XCapClient getXCapClient() { return xCapClient; } /** * Returns the AccountID that uniquely identifies the account represented by * this instance of the ProtocolProviderService. * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Returns the state of the registration of this protocol provider with the * corresponding registration service. * @return ProviderRegistrationState */ public RegistrationState getRegistrationState() { if(this.sipRegistrarConnection == null ) { return RegistrationState.UNREGISTERED; } return sipRegistrarConnection.getRegistrationState(); } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for * example). If the name of the protocol has been enumerated in * ProtocolNames then the value returned by this method must be the same as * the one in ProtocolNames. * @return a String containing the short name of the protocol this service * is implementing (most often that would be a name in ProtocolNames). */ public String getProtocolName() { return ProtocolNames.SIP; } /** * Register a new event taken in account by this provider. This is usefull * to generate the Allow-Events header of the OPTIONS responses and to * generate 489 responses. * * @param event The event to register */ public void registerEvent(String event) { synchronized (this.registeredEvents) { if (!this.registeredEvents.contains(event)) { this.registeredEvents.add(event); } } } /** * Returns the list of all the registered events for this provider. * * @return The list of all the registered events */ public List<String> getKnownEventsList() { return this.registeredEvents; } /** * Overrides * {@link AbstractProtocolProviderService#fireRegistrationStateChanged( * RegistrationState, RegistrationState, int, String)} in order to add * enabling/disabling XCAP functionality in accord with the current * <tt>RegistrationState</tt> of this * <tt>ProtocolProviderServiceSipImpl</tt>. * * @param oldState the state that the provider had before the change * occurred * @param newState the state that the provider is currently in * @param reasonCode a value corresponding to one of the REASON_XXX fields * of the <tt>RegistrationStateChangeEvent</tt> class, indicating the reason * for this state transition * @param reason a <tt>String</tt> further explaining the reason code or * <tt>null</tt> if no such explanation is necessary * @see AbstractProtocolProviderService#fireRegistrationStateChanged( * RegistrationState, RegistrationState, int, String) */ @Override public void fireRegistrationStateChanged(RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) { if (newState.equals(RegistrationState.REGISTERED)) { try { boolean enableXCap = accountID.getAccountPropertyBoolean(XCAP_ENABLE, true); boolean useSipCredetials = accountID.getAccountPropertyBoolean( XCAP_USE_SIP_CREDETIALS, true); String serverUri = accountID.getAccountPropertyString(XCAP_SERVER_URI); String username = accountID.getAccountPropertyString( ProtocolProviderFactory.USER_ID); Address userAddress = parseAddressString(username); String password; if (useSipCredetials) { username = ((SipUri)userAddress.getURI()).getUser(); password = SipActivator.getProtocolProviderFactory(). loadPassword(accountID); } else { username = accountID.getAccountPropertyString(XCAP_USER); password = accountID.getAccountPropertyString(XCAP_PASSWORD); } // Connect to xcap server if(enableXCap && serverUri != null) { URI uri = new URI(serverUri.trim()); if(uri.getHost() != null && uri.getPath() != null) { xCapClient.connect(uri, userAddress, username, password); } } } catch (Exception e) { logger.error("Error while connecting to XCAP server. " + "Contact list won't be saved", e); } } else if (newState.equals(RegistrationState.UNREGISTERING) || newState.equals(RegistrationState.CONNECTION_FAILED)) { xCapClient.disconnect(); } super.fireRegistrationStateChanged(oldState, newState, reasonCode, reason); } /** * Starts the registration process. Connection details such as * registration server, user name/number are provided through the * configuration service through implementation specific properties. * * @param authority the security authority that will be used for resolving * any security challenges that may be returned during the * registration or at any moment while wer're registered. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(SecurityAuthority authority) throws OperationFailedException { if(!isInitialized) { throw new OperationFailedException( "Provided must be initialized before being able to register." , OperationFailedException.GENERAL_ERROR); } if (isRegistered()) { return; } sipStackSharing.addSipListener(this); // be warned when we will unregister, so that we can // then remove us as SipListener this.addRegistrationStateChangeListener(this); // Enable the user name modification. Setting this property to true // we'll allow the user to change the user name stored in the given //authority. authority.setUserNameEditable(true); //init the security manager before doing the actual registration to //avoid being asked for credentials before being ready to provide them sipSecurityManager.setSecurityAuthority(authority); // We check here if the sipRegistrarConnection is initialized. This is // needed in case that in the initialization process we had no internet // connection and resolving the registrar failed. if (sipRegistrarConnection == null) initRegistrarConnection((SipAccountID) accountID); // The same here, we check if the outbound proxy is initialized in case // through the initialization process there was no internet connection. if (outboundProxySocketAddress == null) initOutboundProxy((SipAccountID)accountID, 0); //connect to the Registrar. if (sipRegistrarConnection != null) sipRegistrarConnection.register(); } /** * Ends the registration of this protocol provider with the current * registration service. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void unregister() throws OperationFailedException { if(getRegistrationState().equals(RegistrationState.UNREGISTERED) || getRegistrationState().equals(RegistrationState.UNREGISTERING) || getRegistrationState().equals(RegistrationState.CONNECTION_FAILED)) { return; } sipRegistrarConnection.unregister(); sipSecurityManager.setSecurityAuthority(null); } /** * Initializes the service implementation, and puts it in a state where it * could interoperate with other services. * * @param sipAddress the account id/uin/screenname of the account that we're * about to create * @param accountID the identifier of the account that this protocol * provider represents. * * @throws OperationFailedException with code INTERNAL_ERROR if we fail * initializing the SIP Stack. * @throws java.lang.IllegalArgumentException if one or more of the account * properties have invalid values. * * @see net.java.sip.communicator.service.protocol.AccountID */ protected void initialize(String sipAddress, SipAccountID accountID) throws OperationFailedException, IllegalArgumentException { synchronized (initializationLock) { this.accountID = accountID; String protocolIconPath = accountID .getAccountPropertyString(ProtocolProviderFactory.PROTOCOL_ICON_PATH); if (protocolIconPath == null) protocolIconPath = "resources/images/protocol/sip"; this.protocolIcon = new ProtocolIconSipImpl(protocolIconPath); this.sipStatusEnum = new SipStatusEnum(protocolIconPath); boolean isProxyValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_ADDRESS_VALIDATED, false); //init the proxy, we had to have at least one address configured // so use it, if it fails later we will use next one if(!isProxyValidated) initOutboundProxy(accountID, 0); //init proxy port int preferredSipPort = ListeningPoint.PORT_5060; String proxyPortStr = SipActivator.getConfigurationService(). getString(PREFERRED_SIP_PORT); if (proxyPortStr != null && proxyPortStr.length() > 0) { try { preferredSipPort = Integer.parseInt(proxyPortStr); } catch (NumberFormatException ex) { logger.error( proxyPortStr + " is not a valid port value. Expected an integer" , ex); } if (preferredSipPort > NetworkUtils.MAX_PORT_NUMBER) { logger.error(preferredSipPort + " is larger than " + NetworkUtils.MAX_PORT_NUMBER + " and does not " + "therefore represent a valid port number."); } } if(sipStackSharing == null) sipStackSharing = new SipStackSharing(); // get the presence options boolean enablePresence = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.IS_PRESENCE_ENABLED, true); boolean forceP2P = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.FORCE_P2P_MODE, true); int pollingValue = accountID.getAccountPropertyInt( ProtocolProviderFactory.POLLING_PERIOD, 30); int subscriptionExpiration = accountID.getAccountPropertyInt( ProtocolProviderFactory.SUBSCRIPTION_EXPIRATION, 3600); //create SIP factories. headerFactory = new HeaderFactoryImpl(); addressFactory = new AddressFactoryImpl(); //initialize our display name ourDisplayName = accountID.getAccountPropertyString( ProtocolProviderFactory.DISPLAY_NAME); if(ourDisplayName == null || ourDisplayName.trim().length() == 0) { ourDisplayName = accountID.getUserID(); } boolean isServerValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.SERVER_ADDRESS_VALIDATED, false); //create a connection with the registrar if(!isServerValidated) initRegistrarConnection(accountID); //init our call processor OperationSetBasicTelephonySipImpl opSetBasicTelephonySipImpl = new OperationSetBasicTelephonySipImpl(this); addSupportedOperationSet( OperationSetBasicTelephony.class, opSetBasicTelephonySipImpl); addSupportedOperationSet( OperationSetAdvancedTelephony.class, opSetBasicTelephonySipImpl); // init ZRTP (OperationSetBasicTelephonySipImpl implements // OperationSetSecureTelephony) addSupportedOperationSet( OperationSetSecureTelephony.class, opSetBasicTelephonySipImpl); //init presence op set. OperationSetPersistentPresence opSetPersPresence = new OperationSetPresenceSipImpl(this, enablePresence, forceP2P, pollingValue, subscriptionExpiration); addSupportedOperationSet( OperationSetPersistentPresence.class, opSetPersPresence); //also register with standard presence addSupportedOperationSet( OperationSetPresence.class, opSetPersPresence); if (enablePresence) { // init instant messaging OperationSetBasicInstantMessagingSipImpl opSetBasicIM = new OperationSetBasicInstantMessagingSipImpl(this); addSupportedOperationSet( OperationSetBasicInstantMessaging.class, opSetBasicIM); // init typing notifications addSupportedOperationSet( OperationSetTypingNotifications.class, new OperationSetTypingNotificationsSipImpl( this, opSetBasicIM)); OperationSetServerStoredAccountInfo opSetSSAccountInfo = new OperationSetServerStoredAccountInfoSipImpl(this); // init avatar addSupportedOperationSet( OperationSetServerStoredAccountInfo.class, opSetSSAccountInfo); addSupportedOperationSet( OperationSetAvatar.class, new OperationSetAvatarSipImpl(this, opSetSSAccountInfo)); } // OperationSetVideoTelephony addSupportedOperationSet( OperationSetVideoTelephony.class, new OperationSetVideoTelephonySipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopStreaming addSupportedOperationSet( OperationSetDesktopStreaming.class, new OperationSetDesktopStreamingSipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopSharingServer addSupportedOperationSet( OperationSetDesktopSharingServer.class, new OperationSetDesktopSharingServerSipImpl( opSetBasicTelephonySipImpl)); // OperationSetDesktopSharingClient addSupportedOperationSet( OperationSetDesktopSharingClient.class, new OperationSetDesktopSharingClientSipImpl(this)); // init DTMF (from JM Heitz) addSupportedOperationSet( OperationSetDTMF.class, new OperationSetDTMFSipImpl(this)); addSupportedOperationSet( OperationSetTelephonyConferencing.class, new OperationSetTelephonyConferencingSipImpl(this)); addSupportedOperationSet( OperationSetMessageWaiting.class, new OperationSetMessageWaitingSipImpl(this)); //initialize our OPTIONS handler new ClientCapabilities(this); //init the security manager this.sipSecurityManager = new SipSecurityManager(accountID); sipSecurityManager.setHeaderFactory(headerFactory); // register any available custom extensions ProtocolProviderExtensions.registerCustomOperationSets(this); isInitialized = true; } } /** * Adds a specific <tt>OperationSet</tt> implementation to the set of * supported <tt>OperationSet</tt>s of this instance. Serves as a type-safe * wrapper around {@link #supportedOperationSets} which works with class * names instead of <tt>Class</tt> and also shortens the code which performs * such additions. * * @param <T> the exact type of the <tt>OperationSet</tt> implementation to * be added * @param opsetClass the <tt>Class</tt> of <tt>OperationSet</tt> under the * name of which the specified implementation is to be added * @param opset the <tt>OperationSet</tt> implementation to be added */ @Override protected <T extends OperationSet> void addSupportedOperationSet( Class<T> opsetClass, T opset) { super.addSupportedOperationSet(opsetClass, opset); } /** * Removes an <tt>OperationSet</tt> implementation from the set of * supported <tt>OperationSet</tt>s for this instance. * * @param <T> the exact type of the <tt>OperationSet</tt> implementation to * be added * @param opsetClass the <tt>Class</tt> of <tt>OperationSet</tt> under the * name of which the specified implementation is to be added */ @Override protected <T extends OperationSet> void removeSupportedOperationSet( Class<T> opsetClass) { super.removeSupportedOperationSet(opsetClass); } /** * Never called. * * @param exceptionEvent the IOExceptionEvent containing the cause. */ public void processIOException(IOExceptionEvent exceptionEvent) {} /** * Processes a Response received on a SipProvider upon which this * SipListener is registered. * <p> * * @param responseEvent the responseEvent fired from the SipProvider to the * SipListener representing a Response received from the network. */ public void processResponse(ResponseEvent responseEvent) { ClientTransaction clientTransaction = responseEvent .getClientTransaction(); if (clientTransaction == null) { if (logger.isDebugEnabled()) logger.debug("ignoring a transactionless response"); return; } Response response = responseEvent.getResponse(); earlyProcessMessage(responseEvent); String method = ( (CSeqHeader) response.getHeader(CSeqHeader.NAME)) .getMethod(); //find the object that is supposed to take care of responses with the //corresponding method List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) if (processor.processResponse(responseEvent)) break; } } /** * Processes a retransmit or expiration Timeout of an underlying * {@link Transaction} handled by this SipListener. This Event notifies the * application that a retransmission or transaction Timer expired in the * SipProvider's transaction state machine. The TimeoutEvent encapsulates * the specific timeout type and the transaction identifier either client or * server upon which the timeout occurred. The type of Timeout can by * determined by: * <code>timeoutType = timeoutEvent.getTimeout().getValue();</code> * * @param timeoutEvent - * the timeoutEvent received indicating either the message * retransmit or transaction timed out. */ public void processTimeout(TimeoutEvent timeoutEvent) { Transaction transaction; if(timeoutEvent.isServerTransaction()) transaction = timeoutEvent.getServerTransaction(); else transaction = timeoutEvent.getClientTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) logger.debug("ignoring a transactionless timeout event"); return; } earlyProcessMessage(timeoutEvent); Request request = transaction.getRequest(); if (logger.isDebugEnabled()) logger.debug("received timeout for req=" + request); //find the object that is supposed to take care of responses with the //corresponding method String method = request.getMethod(); List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processTimeout(timeoutEvent)) { break; } } } } /** * Process an asynchronously reported TransactionTerminatedEvent. * When a transaction transitions to the Terminated state, the stack * keeps no further records of the transaction. This notification can be used by * applications to clean up any auxiliary data that is being maintained * for the given transaction. * * @param transactionTerminatedEvent -- an event that indicates that the * transaction has transitioned into the terminated state. * @since v1.2 */ public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) { Transaction transaction; if(transactionTerminatedEvent.isServerTransaction()) transaction = transactionTerminatedEvent.getServerTransaction(); else transaction = transactionTerminatedEvent.getClientTransaction(); if (transaction == null) { if (logger.isDebugEnabled()) logger.debug( "ignoring a transactionless transaction terminated event"); return; } Request request = transaction.getRequest(); //find the object that is supposed to take care of responses with the //corresponding method String method = request.getMethod(); List<MethodProcessor> processors = methodProcessors.get(method); if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processTransactionTerminated( transactionTerminatedEvent)) { break; } } } } /** * Process an asynchronously reported DialogTerminatedEvent. * When a dialog transitions to the Terminated state, the stack * keeps no further records of the dialog. This notification can be used by * applications to clean up any auxiliary data that is being maintained * for the given dialog. * * @param dialogTerminatedEvent -- an event that indicates that the * dialog has transitioned into the terminated state. * @since v1.2 */ public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { if (logger.isDebugEnabled()) logger.debug("Dialog terminated for req=" + dialogTerminatedEvent.getDialog()); } /** * Processes a Request received on a SipProvider upon which this SipListener * is registered. * <p> * @param requestEvent requestEvent fired from the SipProvider to the * SipListener representing a Request received from the network. */ public void processRequest(RequestEvent requestEvent) { Request request = requestEvent.getRequest(); if(getRegistrarConnection() != null && !getRegistrarConnection().isRegistrarless() && !getRegistrarConnection().isRequestFromSameConnection(request)) { logger.warn("Received request not from our proxy, ignoring it! " + "Request:" + request); if (requestEvent.getServerTransaction() != null) { try { requestEvent.getServerTransaction().terminate(); } catch (Throwable e) { logger.warn("Failed to properly terminate transaction for " +"a rogue request. Well ... so be it " + "Request:" + request); } } return; } earlyProcessMessage(requestEvent); // test if an Event header is present and known EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME); if (eventHeader != null) { boolean eventKnown; synchronized (this.registeredEvents) { eventKnown = this.registeredEvents.contains( eventHeader.getEventType()); } if (!eventKnown) { // send a 489 / Bad Event response ServerTransaction serverTransaction = requestEvent .getServerTransaction(); if (serverTransaction == null) { try { serverTransaction = SipStackSharing. getOrCreateServerTransaction(requestEvent); } catch (TransactionAlreadyExistsException ex) { //let's not scare the user and only log a message logger.error("Failed to create a new server" + "transaction for an incoming request\n" + "(Next message contains the request)" , ex); return; } catch (TransactionUnavailableException ex) { //let's not scare the user and only log a message logger.error("Failed to create a new server" + "transaction for an incoming request\n" + "(Next message contains the request)" , ex); return; } } Response response = null; try { response = this.getMessageFactory().createResponse( Response.BAD_EVENT, request); } catch (ParseException e) { logger.error("failed to create the 489 response", e); return; } try { serverTransaction.sendResponse(response); return; } catch (SipException e) { logger.error("failed to send the response", e); } catch (InvalidArgumentException e) { // should not happen logger.error("invalid argument provided while trying" + " to send the response", e); } } } String method = request.getMethod(); //find the object that is supposed to take care of responses with the //corresponding method List<MethodProcessor> processors = methodProcessors.get(method); //raise this flag if at least one processor handles the request. boolean processedAtLeastOnce = false; if (processors != null) { if (logger.isDebugEnabled()) logger.debug("Found " + processors.size() + " processor(s) for method " + method); for (MethodProcessor processor : processors) { if (processor.processRequest(requestEvent)) { processedAtLeastOnce = true; break; } } } //send an error response if no one processes this if (!processedAtLeastOnce) { ServerTransaction serverTransaction; try { serverTransaction = SipStackSharing.getOrCreateServerTransaction(requestEvent); if (serverTransaction == null) { logger.warn("Could not create a transaction for a " +"non-supported method " + request.getMethod()); return; } TransactionState state = serverTransaction.getState(); if( TransactionState.TRYING.equals(state)) { Response response = this.getMessageFactory().createResponse( Response.NOT_IMPLEMENTED, request); serverTransaction.sendResponse(response); } } catch (Throwable exc) { logger.warn("Could not respond to a non-supported method " + request.getMethod(), exc); } } } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for shutdown/garbage * collection. */ public void shutdown() { if(!isInitialized) { return; } // don't run in Thread cause shutting down may finish before // we were able to unregister new ShutdownThread().run(); } /** * The thread that we use in order to send our unREGISTER request upon * system shut down. */ protected class ShutdownThread implements Runnable { /** * Shutdowns operation sets that need it then calls the * <tt>SipRegistrarConnection.unregister()</tt> method. */ public void run() { if (logger.isTraceEnabled()) logger.trace("Killing the SIP Protocol Provider."); //kill all active calls OperationSetBasicTelephonySipImpl telephony = (OperationSetBasicTelephonySipImpl)getOperationSet( OperationSetBasicTelephony.class); telephony.shutdown(); if(isRegistered()) { try { //create a listener that would notify us when //un-registration has completed. ShutdownUnregistrationBlockListener listener = new ShutdownUnregistrationBlockListener(); addRegistrationStateChangeListener(listener); //do the un-registration unregister(); //leave ourselves time to complete un-registration (may include //2 REGISTER requests in case notification is needed.) listener.waitForEvent(3000L); } catch (OperationFailedException ex) { //we're shutting down so we need to silence the exception here logger.error( "Failed to properly unregister before shutting down. " + getAccountID() , ex); } } headerFactory = null; messageFactory = null; addressFactory = null; sipSecurityManager = null; methodProcessors.clear(); isInitialized = false; } } /** * Initializes and returns an ArrayList with a single ViaHeader * containing a localhost address usable with the specified * s<tt>destination</tt>. This ArrayList may be used when sending * requests to that destination. * <p> * @param intendedDestination The address of the destination that the * request using the via headers will be sent to. * * @return ViaHeader-s list to be used when sending requests. * @throws OperationFailedException code INTERNAL_ERROR if a ParseException * occurs while initializing the array list. * */ public ArrayList<ViaHeader> getLocalViaHeaders(Address intendedDestination) throws OperationFailedException { return getLocalViaHeaders((SipURI)intendedDestination.getURI()); } /** * Initializes and returns an ArrayList with a single ViaHeader * containing a localhost address usable with the specified * s<tt>destination</tt>. This ArrayList may be used when sending * requests to that destination. * <p> * @param intendedDestination The address of the destination that the * request using the via headers will be sent to. * * @return ViaHeader-s list to be used when sending requests. * @throws OperationFailedException code INTERNAL_ERROR if a ParseException * occurs while initializing the array list. * */ public ArrayList<ViaHeader> getLocalViaHeaders(SipURI intendedDestination) throws OperationFailedException { ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>(); ListeningPoint srcListeningPoint = getListeningPoint(intendedDestination.getTransportParam()); try { InetSocketAddress targetAddress = getIntendedDestination(intendedDestination); InetAddress localAddress = SipActivator .getNetworkAddressManagerService().getLocalHost( targetAddress.getAddress()); int localPort = srcListeningPoint.getPort(); String transport = srcListeningPoint.getTransport(); if (ListeningPoint.TCP.equalsIgnoreCase(transport)) //|| ListeningPoint.TLS.equalsIgnoreCase(transport) { InetSocketAddress localSockAddr = sipStackSharing.getLocalAddressForDestination( targetAddress.getAddress(), targetAddress.getPort(), localAddress, transport); localPort = localSockAddr.getPort(); } ViaHeader viaHeader = headerFactory.createViaHeader( localAddress.getHostAddress(), localPort, transport, null ); viaHeaders.add(viaHeader); if (logger.isDebugEnabled()) logger.debug("generated via headers:" + viaHeader); return viaHeaders; } catch (ParseException ex) { logger.error( "A ParseException occurred while creating Via Headers!", ex); throw new OperationFailedException( "A ParseException occurred while creating Via Headers!" ,OperationFailedException.INTERNAL_ERROR ,ex); } catch (InvalidArgumentException ex) { logger.error( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort(), ex); throw new OperationFailedException( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort() ,OperationFailedException.INTERNAL_ERROR ,ex); } catch (java.io.IOException ex) { logger.error( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort(), ex); throw new OperationFailedException( "Unable to create a via header for port " + sipStackSharing.getLP(ListeningPoint.UDP).getPort() ,OperationFailedException.NETWORK_FAILURE ,ex); } } /** * Initializes and returns this provider's default maxForwardsHeader field * using the value specified by MAX_FORWARDS. * * @return an instance of a MaxForwardsHeader that can be used when * sending requests * * @throws OperationFailedException with code INTERNAL_ERROR if MAX_FORWARDS * has an invalid value. */ public MaxForwardsHeader getMaxForwardsHeader() throws OperationFailedException { if (maxForwardsHeader == null) { try { maxForwardsHeader = headerFactory.createMaxForwardsHeader( MAX_FORWARDS); if (logger.isDebugEnabled()) logger.debug("generated max forwards: " + maxForwardsHeader.toString()); } catch (InvalidArgumentException ex) { throw new OperationFailedException( "A problem occurred while creating MaxForwardsHeader" , OperationFailedException.INTERNAL_ERROR , ex); } } return maxForwardsHeader; } /** * Returns a Contact header containing a sip URI based on a localhost * address. * * @param intendedDestination the destination that we plan to be sending * this contact header to. * * @return a Contact header based upon a local inet address. */ public ContactHeader getContactHeader(Address intendedDestination) { return getContactHeader((SipURI)intendedDestination.getURI()); } /** * Returns a Contact header containing a sip URI based on a localhost * address and therefore usable in REGISTER requests only. * * @param intendedDestination the destination that we plan to be sending * this contact header to. * * @return a Contact header based upon a local inet address. */ public ContactHeader getContactHeader(SipURI intendedDestination) { ContactHeader registrationContactHeader = null; ListeningPoint srcListeningPoint = getListeningPoint(intendedDestination); InetSocketAddress targetAddress = getIntendedDestination(intendedDestination); try { //find the address to use with the target InetAddress localAddress = SipActivator .getNetworkAddressManagerService() .getLocalHost(targetAddress.getAddress()); SipURI contactURI = addressFactory.createSipURI( getAccountID().getUserID() , localAddress.getHostAddress() ); String transport = srcListeningPoint.getTransport(); contactURI.setTransportParam(transport); int localPort = srcListeningPoint.getPort(); //if we are using tcp, make sure that we include the port of the //socket that we are actually using and not that of LP if (ListeningPoint.TCP.equalsIgnoreCase(transport)) //|| ListeningPoint.TLS.equalsIgnoreCase(transport)) { InetSocketAddress localSockAddr = sipStackSharing.getLocalAddressForDestination( targetAddress.getAddress(), targetAddress.getPort(), localAddress, transport); localPort = localSockAddr.getPort(); } contactURI.setPort(localPort); // set a custom param to ease incoming requests dispatching in case // we have several registrar accounts with the same username String paramValue = getContactAddressCustomParamValue(); if (paramValue != null) { contactURI.setParameter( SipStackSharing.CONTACT_ADDRESS_CUSTOM_PARAM_NAME, paramValue); } Address contactAddress = addressFactory.createAddress( contactURI ); String ourDisplayName = getOurDisplayName(); if (ourDisplayName != null) { contactAddress.setDisplayName(ourDisplayName); } registrationContactHeader = headerFactory.createContactHeader( contactAddress); if (logger.isDebugEnabled()) logger.debug("generated contactHeader:" + registrationContactHeader); } catch (ParseException ex) { logger.error( "A ParseException occurred while creating From Header!", ex); throw new IllegalArgumentException( "A ParseException occurred while creating From Header!" , ex); } catch (java.io.IOException ex) { logger.error( "A ParseException occurred while creating From Header!", ex); throw new IllegalArgumentException( "A ParseException occurred while creating From Header!" , ex); } return registrationContactHeader; } /** * Returns null for a registraless account, a value for the contact address * custom parameter otherwise. This will help the dispatching of incoming * requests between accounts with the same username. For address-of-record * [email protected], the returned value woud be example_com. * * @return null for a registraless account, a value for the * "registering_acc" contact address parameter otherwise */ public String getContactAddressCustomParamValue() { SipRegistrarConnection src = getRegistrarConnection(); if (src != null && !src.isRegistrarless()) { // if we don't replace the dots in the hostname, we get // "476 No Server Address in Contacts Allowed" // from certain registrars (ippi.fr for instance) String hostValue = ((SipURI) src.getAddressOfRecord().getURI()) .getHost().replace('.', '_'); return hostValue; } return null; } /** * Returns the AddressFactory used to create URLs ans Address objects. * * @return the AddressFactory used to create URLs ans Address objects. */ public AddressFactory getAddressFactory() { return addressFactory; } /** * Returns the HeaderFactory used to create SIP message headers. * * @return the HeaderFactory used to create SIP message headers. */ public HeaderFactory getHeaderFactory() { return headerFactory; } /** * Returns the Message Factory used to create SIP messages. * * @return the Message Factory used to create SIP messages. */ public SipMessageFactory getMessageFactory() { if (messageFactory == null) { messageFactory = new SipMessageFactory(this, new MessageFactoryImpl()); } return messageFactory; } /** * Returns all running instances of ProtocolProviderServiceSipImpl * * @return all running instances of ProtocolProviderServiceSipImpl */ public static Set<ProtocolProviderServiceSipImpl> getAllInstances() { try { Set<ProtocolProviderServiceSipImpl> instances = new HashSet<ProtocolProviderServiceSipImpl>(); BundleContext context = SipActivator.getBundleContext(); ServiceReference[] references = context.getServiceReferences( ProtocolProviderService.class.getName(), null ); for(ServiceReference reference : references) { Object service = context.getService(reference); if(service instanceof ProtocolProviderServiceSipImpl) instances.add((ProtocolProviderServiceSipImpl) service); } return instances; } catch(InvalidSyntaxException ex) { if (logger.isDebugEnabled()) logger.debug("Problem parcing an osgi expression", ex); // should never happen so crash if it ever happens throw new RuntimeException( "getServiceReferences() wasn't supposed to fail!" ); } } /** * Returns the default listening point that we use for communication over * <tt>transport</tt>. * * @param transport the transport that the returned listening point needs * to support. * * @return the default listening point that we use for communication over * <tt>transport</tt> or null if no such transport is supported. */ public ListeningPoint getListeningPoint(String transport) { if(logger.isTraceEnabled()) logger.trace("Query for a " + transport + " listening point"); //override the transport in case we have an outbound proxy. if(getOutboundProxy() != null) { if (logger.isTraceEnabled()) logger.trace("Will use proxy address"); transport = outboundProxyTransport; } if( transport == null || transport.trim().length() == 0 || ( ! transport.trim().equalsIgnoreCase(ListeningPoint.TCP) && ! transport.trim().equalsIgnoreCase(ListeningPoint.UDP) && ! transport.trim().equalsIgnoreCase(ListeningPoint.TLS))) { transport = getDefaultTransport(); } ListeningPoint lp = null; if(transport.equalsIgnoreCase(ListeningPoint.UDP)) { lp = sipStackSharing.getLP(ListeningPoint.UDP); } else if(transport.equalsIgnoreCase(ListeningPoint.TCP)) { lp = sipStackSharing.getLP(ListeningPoint.TCP); } else if(transport.equalsIgnoreCase(ListeningPoint.TLS)) { lp = sipStackSharing.getLP(ListeningPoint.TLS); } if(logger.isTraceEnabled()) { logger.trace("Returning LP " + lp + " for transport [" + transport + "] and "); } return lp; } /** * Returns the default listening point that we should use to contact the * intended destination. * * @param intendedDestination the address that we will be trying to contact * through the listening point we are trying to obtain. * * @return the listening point that we should use to contact the * intended destination. */ public ListeningPoint getListeningPoint(Address intendedDestination) { return getListeningPoint((SipURI)intendedDestination.getURI()); } /** * Returns the default listening point that we should use to contact the * intended destination. * * @param intendedDestination the address that we will be trying to contact * through the listening point we are trying to obtain. * * @return the listening point that we should use to contact the * intended destination. */ public ListeningPoint getListeningPoint(SipURI intendedDestination) { String transport = intendedDestination.getTransportParam(); return getListeningPoint(transport); } /** * Returns the default jain sip provider that we use for communication over * <tt>transport</tt>. * * @param transport the transport that the returned provider needs * to support. * * @return the default jain sip provider that we use for communication over * <tt>transport</tt> or null if no such transport is supported. */ public SipProvider getJainSipProvider(String transport) { return sipStackSharing.getJainSipProvider(transport); } /** * Reurns the currently valid sip security manager that everyone should * use to authenticate SIP Requests. * @return the currently valid instace of a SipSecurityManager that everyone * sould use to authenticate SIP Requests. */ public SipSecurityManager getSipSecurityManager() { return sipSecurityManager; } /** * Initializes the SipRegistrarConnection that this class will be using. * * @param accountID the ID of the account that this registrar is associated * with. * @throws java.lang.IllegalArgumentException if one or more account * properties have invalid values. */ private void initRegistrarConnection(SipAccountID accountID) throws IllegalArgumentException { //First init the registrar address String registrarAddressStr = accountID .getAccountPropertyString(ProtocolProviderFactory.SERVER_ADDRESS); //if there is no registrar address, parse the user_id and extract it //from the domain part of the SIP URI. if (registrarAddressStr == null) { String userID = accountID .getAccountPropertyString(ProtocolProviderFactory.USER_ID); int index = userID.indexOf('@'); if ( index > -1 ) registrarAddressStr = userID.substring( index+1); } //if we still have no registrar address or if the registrar address //string is one of our local host addresses this means the users does //not want to use a registrar connection if(registrarAddressStr == null || registrarAddressStr.trim().length() == 0) { initRegistrarlessConnection(accountID); return; } //from this point on we are certain to have a registrar. InetSocketAddress[] registrarSocketAddresses = null; //registrar transport String registrarTransport = accountID.getAccountPropertyString( ProtocolProviderFactory.PREFERRED_TRANSPORT); if(registrarTransport != null && registrarTransport.length() > 0) { if( ! registrarTransport.equals(ListeningPoint.UDP) && !registrarTransport.equals(ListeningPoint.TCP) && !registrarTransport.equals(ListeningPoint.TLS)) { throw new IllegalArgumentException(registrarTransport + " is not a valid transport protocol. Transport must be " +"left blanc or set to TCP, UDP or TLS."); } } else { registrarTransport = getDefaultTransport(); } //init registrar port int registrarPort = ListeningPoint.PORT_5060; try { // if port is set we must use the explicitly set settings and // skip SRV queries if(accountID.getAccountProperty( ProtocolProviderFactory.SERVER_PORT) != null) { ArrayList<InetSocketAddress> registrarSocketAddressesList = new ArrayList<InetSocketAddress>(); // get only AAAA and A records resolveAddresses( registrarAddressStr, registrarSocketAddressesList, checkPreferIPv6Addresses(), registrarPort ); registrarSocketAddresses = registrarSocketAddressesList .toArray(new InetSocketAddress[0]); } else { ArrayList<InetSocketAddress> registrarSocketAddressesList = new ArrayList<InetSocketAddress>(); ArrayList<String> registrarTransports = new ArrayList<String>(); resolveSipAddress( registrarAddressStr, registrarTransport, registrarSocketAddressesList, registrarTransports, accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_AUTO_CONFIG, false)); registrarTransport = registrarTransports.get(0); registrarSocketAddresses = registrarSocketAddressesList .toArray(new InetSocketAddress[0]); } // We should set here the property to indicate that the server // address is validated. When we load stored accounts we check // this property in order to prevent checking again the server // address. And this is needed because in the case we don't have // network while loading the application we still want to have our // accounts loaded. if(registrarSocketAddresses != null && registrarSocketAddresses.length > 0) accountID.putAccountProperty( ProtocolProviderFactory.SERVER_ADDRESS_VALIDATED, Boolean.toString(true)); } catch (UnknownHostException ex) { if (logger.isDebugEnabled()) logger.debug(registrarAddressStr + " appears to be an either invalid" + " or inaccessible address.", ex); boolean isServerValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.SERVER_ADDRESS_VALIDATED, false); /* * We should check here if the server address was already validated. * When we load stored accounts we want to prevent checking again * the server address. This is needed because in the case we don't * have network while loading the application we still want to have * our accounts loaded. */ if (!isServerValidated) { throw new IllegalArgumentException( registrarAddressStr + " appears to be an either invalid" + " or inaccessible address.", ex); } } // If the registrar address is null we don't need to continue. // If we still have problems with initializing the registrar we are // telling the user. We'll enter here only if the server has been // already validated (this means that the account is already created // and we're trying to login, but we have no internet connection). if(registrarSocketAddresses == null || registrarSocketAddresses.length == 0) { fireRegistrationStateChanged( RegistrationState.UNREGISTERED, RegistrationState.CONNECTION_FAILED, RegistrationStateChangeEvent.REASON_SERVER_NOT_FOUND, "Invalid or inaccessible server address."); return; } // check if user has overridden the registrar port. registrarPort = accountID.getAccountPropertyInt( ProtocolProviderFactory.SERVER_PORT, registrarPort); if (registrarPort > NetworkUtils.MAX_PORT_NUMBER) { throw new IllegalArgumentException(registrarPort + " is larger than " + NetworkUtils.MAX_PORT_NUMBER + " and does not therefore represent a valid port number."); } //init expiration timeout int expires = SipActivator.getConfigurationService().getInt( REGISTRATION_EXPIRATION, SipRegistrarConnection.DEFAULT_REGISTRATION_EXPIRATION); //Initialize our connection with the registrar try { this.sipRegistrarConnection = new SipRegistrarConnection( registrarSocketAddresses , registrarTransport , expires , this); } catch (ParseException ex) { //this really shouldn't happen as we're using InetAddress-es logger.error("Failed to create a registrar connection with " +registrarSocketAddresses[0].getAddress().getHostAddress() , ex); throw new IllegalArgumentException( "Failed to create a registrar connection with " + registrarSocketAddresses[0].getAddress().getHostAddress() + ": " + ex.getMessage()); } } /** * Initializes the SipRegistrarConnection that this class will be using. * * @param accountID the ID of the account that this registrar is associated * with. * @throws java.lang.IllegalArgumentException if one or more account * properties have invalid values. */ private void initRegistrarlessConnection(SipAccountID accountID) throws IllegalArgumentException { //registrar transport String registrarTransport = accountID .getAccountPropertyString(ProtocolProviderFactory.PREFERRED_TRANSPORT); if(registrarTransport != null && registrarTransport.length() > 0) { if( ! registrarTransport.equals(ListeningPoint.UDP) && !registrarTransport.equals(ListeningPoint.TCP) && !registrarTransport.equals(ListeningPoint.TLS)) { throw new IllegalArgumentException(registrarTransport + " is not a valid transport protocol. Transport must be " +"left blanc or set to TCP, UDP or TLS."); } } else { registrarTransport = ListeningPoint.UDP; } //Initialize our connection with the registrar this.sipRegistrarConnection = new SipRegistrarlessConnection(this, registrarTransport); } /** * Returns the SIP address of record (Display Name <[email protected]>) that * this account is created for. The method takes into account whether or * not we are running in Registar or "No Registar" mode and either returns * the AOR we are using to register or an address constructed using the * local address. * * @param intendedDestination the destination that we would be using the * local address to communicate with. * * @return our Address Of Record that we should use in From headers. */ public Address getOurSipAddress(Address intendedDestination) { return getOurSipAddress((SipURI)intendedDestination.getURI()); } /** * Returns the SIP address of record (Display Name <[email protected]>) that * this account is created for. The method takes into account whether or * not we are running in Registar or "No Registar" mode and either returns * the AOR we are using to register or an address constructed using the * local address * * @param intendedDestination the destination that we would be using the * local address to communicate with. * . * @return our Address Of Record that we should use in From headers. */ public Address getOurSipAddress(SipURI intendedDestination) { SipRegistrarConnection src = getRegistrarConnection(); if( src != null && !src.isRegistrarless() ) return src.getAddressOfRecord(); //we are apparently running in "No Registrar" mode so let's create an //address by ourselves. InetSocketAddress destinationAddr = getIntendedDestination(intendedDestination); InetAddress localHost = SipActivator.getNetworkAddressManagerService() .getLocalHost(destinationAddr.getAddress()); String userID = getAccountID().getUserID(); try { SipURI ourSipURI = getAddressFactory() .createSipURI(userID, localHost.getHostAddress()); ListeningPoint lp = getListeningPoint(intendedDestination); ourSipURI.setTransportParam(lp.getTransport()); ourSipURI.setPort(lp.getPort()); Address ourSipAddress = getAddressFactory() .createAddress(getOurDisplayName(), ourSipURI); ourSipAddress.setDisplayName(getOurDisplayName()); return ourSipAddress; } catch (ParseException exc) { if (logger.isTraceEnabled()) logger.trace("Failed to create our SIP AOR address", exc); // this should never happen since we are using InetAddresses // everywhere so parsing could hardly go wrong. throw new IllegalArgumentException( "Failed to create our SIP AOR address" , exc); } } /** * In case we are using an outbound proxy this method returns * a suitable string for use with Router. * The method returns <tt>null</tt> otherwise. * * @return the string of our outbound proxy if we are using one and * <tt>null</tt> otherwise. */ public String getOutboundProxyString() { return this.outboundProxyString; } /** * In case we are using an outbound proxy this method returns its address. * The method returns <tt>null</tt> otherwise. * * @return the address of our outbound proxy if we are using one and * <tt>null</tt> otherwise. */ public InetSocketAddress getOutboundProxy() { return this.outboundProxySocketAddress; } /** * In case we are using an outbound proxy this method returns the transport * we are using to connect to it. The method returns <tt>null</tt> * otherwise. * * @return the transport used to connect to our outbound proxy if we are * using one and <tt>null</tt> otherwise. */ public String getOutboundProxyTransport() { return this.outboundProxyTransport; } /** * Extracts all properties concerning the usage of an outbound proxy for * this account. * @param accountID the account whose outbound proxy we are currently * initializing. * @param ix index of the address to use. */ void initOutboundProxy(SipAccountID accountID, int ix) { //First init the proxy address String proxyAddressStr = accountID .getAccountPropertyString(ProtocolProviderFactory. PROXY_ADDRESS); boolean proxyAddressAndPortEntered = false; if(proxyAddressStr == null || proxyAddressStr.trim().length() == 0) { proxyAddressStr = accountID .getAccountPropertyString(ProtocolProviderFactory. SERVER_ADDRESS); if(proxyAddressStr == null || proxyAddressStr.trim().length() == 0) { /* registrarless account */ return; } } else { if(accountID.getAccountProperty(ProtocolProviderFactory.PROXY_PORT) != null) { proxyAddressAndPortEntered = true; } } InetAddress proxyAddress = null; //init proxy port int proxyPort = ListeningPoint.PORT_5060; //proxy transport String proxyTransport = accountID.getAccountPropertyString( ProtocolProviderFactory.PREFERRED_TRANSPORT); if (proxyTransport != null && proxyTransport.length() > 0) { if (!proxyTransport.equals(ListeningPoint.UDP) && !proxyTransport.equals(ListeningPoint.TCP) && !proxyTransport.equals(ListeningPoint.TLS)) { throw new IllegalArgumentException(proxyTransport + " is not a valid transport protocol. Transport must be " + "left blank or set to TCP, UDP or TLS."); } } else { proxyTransport = getDefaultTransport(); } try { //check if user has overridden proxy port. proxyPort = accountID.getAccountPropertyInt( ProtocolProviderFactory.PROXY_PORT, proxyPort); if (proxyPort > NetworkUtils.MAX_PORT_NUMBER) { throw new IllegalArgumentException(proxyPort + " is larger than " + NetworkUtils.MAX_PORT_NUMBER + " and does not therefore represent a valid port number."); } InetSocketAddress proxySocketAddress = null; if(accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_AUTO_CONFIG, false)) { ArrayList<InetSocketAddress> proxySocketAddressesList = new ArrayList<InetSocketAddress>(); ArrayList<String> proxyTransportsList = new ArrayList<String>(); resolveSipAddress( proxyAddressStr, proxyTransport, proxySocketAddressesList, proxyTransportsList, true); proxyTransport = proxyTransportsList.get(ix); proxySocketAddress = proxySocketAddressesList.get(ix); } else { // according rfc3263 if proxy address and port are // explicitly entered don't make SRV queries if(proxyAddressAndPortEntered) { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); resolveAddresses( proxyAddressStr, addresses, checkPreferIPv6Addresses(), proxyPort); // only set if enough results found if(addresses.size() > ix) proxySocketAddress = addresses.get(ix); } else { ArrayList<InetSocketAddress> proxySocketAddressesList = new ArrayList<InetSocketAddress>(); ArrayList<String> proxyTransportsList = new ArrayList<String>(); resolveSipAddress( proxyAddressStr, proxyTransport, proxySocketAddressesList, proxyTransportsList, false); proxyTransport = proxyTransportsList.get(ix); proxySocketAddress = proxySocketAddressesList.get(ix); } } if(proxySocketAddress == null) throw new UnknownHostException(); proxyAddress = proxySocketAddress.getAddress(); proxyPort = proxySocketAddress.getPort(); if (logger.isTraceEnabled()) logger.trace("Setting proxy address = " + proxyAddressStr); // We should set here the property to indicate that the proxy // address is validated. When we load stored accounts we check // this property in order to prevent checking again the proxy // address. this is needed because in the case we don't have // network while loading the application we still want to have // our accounts loaded. accountID.putAccountProperty( ProtocolProviderFactory.PROXY_ADDRESS_VALIDATED, Boolean.toString(true)); } catch (UnknownHostException ex) { logger.error(proxyAddressStr + " appears to be an either invalid" + " or inaccessible address.", ex); boolean isProxyValidated = accountID.getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_ADDRESS_VALIDATED, false); // We should check here if the proxy address was already validated. // When we load stored accounts we want to prevent checking again the // proxy address. This is needed because in the case we don't have // network while loading the application we still want to have our // accounts loaded. if (!isProxyValidated) { throw new IllegalArgumentException( proxyAddressStr + " appears to be an either invalid or" + " inaccessible address.", ex); } } // Return if no proxy is specified or if the proxyAddress is null. if(proxyAddress == null) { return; } StringBuilder proxyStringBuffer = new StringBuilder(proxyAddress.getHostAddress()); if(proxyAddress instanceof Inet6Address) { proxyStringBuffer.insert(0, '['); proxyStringBuffer.append(']'); } proxyStringBuffer.append(':'); proxyStringBuffer.append(Integer.toString(proxyPort)); proxyStringBuffer.append('/'); proxyStringBuffer.append(proxyTransport); //done parsing. init properties. this.outboundProxyString = proxyStringBuffer.toString(); //store a reference to our sip proxy so that we can use it when //constructing via and contact headers. this.outboundProxySocketAddress = new InetSocketAddress(proxyAddress, proxyPort); this.outboundProxyTransport = proxyTransport; } /** * Registers <tt>methodProcessor</tt> in the <tt>methorProcessors</tt> table * so that it would receives all messages in a transaction initiated by a * <tt>method</tt> request. If any previous processors exist for the same * method, they will be replaced by this one. * * @param method a String representing the SIP method that we're registering * the processor for (e.g. INVITE, REGISTER, or SUBSCRIBE). * @param methodProcessor a <tt>MethodProcessor</tt> implementation that * would handle all messages received within a <tt>method</tt> * transaction. */ public void registerMethodProcessor(String method, MethodProcessor methodProcessor) { List<MethodProcessor> processors = methodProcessors.get(method); if (processors == null) { processors = new LinkedList<MethodProcessor>(); methodProcessors.put(method, processors); } else { /* * Prevent the registering of multiple instances of one and the same * OperationSet class and take only the latest registration into * account. */ Iterator<MethodProcessor> processorIter = processors.iterator(); Class<? extends MethodProcessor> methodProcessorClass = methodProcessor.getClass(); /* * EventPackageSupport and its extenders provide a generic mechanizm * for building support for a specific event package so allow them * to register multiple instances of one and the same class as long * as they are handling different event packages. */ String eventPackage = (methodProcessor instanceof EventPackageSupport) ? ((EventPackageSupport) methodProcessor).getEventPackage() : null; while (processorIter.hasNext()) { MethodProcessor processor = processorIter.next(); if (!processor.getClass().equals(methodProcessorClass)) continue; if ((eventPackage != null) && (processor instanceof EventPackageSupport) && !eventPackage .equals( ((EventPackageSupport) processor) .getEventPackage())) continue; processorIter.remove(); } } processors.add(methodProcessor); } /** * Unregisters <tt>methodProcessor</tt> from the <tt>methorProcessors</tt> * table so that it won't receive further messages in a transaction * initiated by a <tt>method</tt> request. * * @param method the name of the method whose processor we'd like to * unregister. * @param methodProcessor the <tt>MethodProcessor</tt> that we'd like to * unregister. */ public void unregisterMethodProcessor(String method, MethodProcessor methodProcessor) { List<MethodProcessor> processors = methodProcessors.get(method); if ((processors != null) && processors.remove(methodProcessor) && (processors.size() <= 0)) { methodProcessors.remove(method); } } /** * Returns the transport that we should use if we have no clear idea of our * destination's preferred transport. The method would first check if * we are running behind an outbound proxy and if so return its transport. * If no outbound proxy is set, the method would check the contents of the * DEFAULT_TRANSPORT property and return it if not null. Otherwise the * method would return UDP; * * @return The first non null password of the following: * a) the transport we use to communicate with our registrar * b) the transport of our outbound proxy, * c) the transport specified by the DEFAULT_TRANSPORT property, UDP. */ public String getDefaultTransport() { SipRegistrarConnection srConnection = getRegistrarConnection(); if( srConnection != null) { String registrarTransport = srConnection.getTransport(); if( registrarTransport != null && registrarTransport.length() > 0) { return registrarTransport; } } if(outboundProxySocketAddress != null && outboundProxyTransport != null) { return outboundProxyTransport; } else { String userSpecifiedDefaultTransport = SipActivator.getConfigurationService() .getString(DEFAULT_TRANSPORT); if(userSpecifiedDefaultTransport != null) { return userSpecifiedDefaultTransport; } else { String defTransportDefaultValue = SipActivator.getResources() .getSettingsString(DEFAULT_TRANSPORT); if(!StringUtils.isNullOrEmpty(defTransportDefaultValue)) return defTransportDefaultValue; else return ListeningPoint.UDP; } } } /** * Returns the provider that corresponds to the transport returned by * getDefaultTransport(). Equivalent to calling * getJainSipProvider(getDefaultTransport()) * * @return the Jain SipProvider that corresponds to the transport returned * by getDefaultTransport(). */ public SipProvider getDefaultJainSipProvider() { return getJainSipProvider(getDefaultTransport()); } /** * Returns the listening point that corresponds to the transport returned by * getDefaultTransport(). Equivalent to calling * getListeningPoint(getDefaultTransport()) * * @return the Jain SipProvider that corresponds to the transport returned * by getDefaultTransport(). */ public ListeningPoint getDefaultListeningPoint() { return getListeningPoint(getDefaultTransport()); } /** * Returns the display name string that the user has set as a display name * for this account. * * @return the display name string that the user has set as a display name * for this account. */ public String getOurDisplayName() { return ourDisplayName; } /** * Returns a User Agent header that could be used for signing our requests. * * @return a <tt>UserAgentHeader</tt> that could be used for signing our * requests. */ public UserAgentHeader getSipCommUserAgentHeader() { if(userAgentHeader == null) { try { List<String> userAgentTokens = new LinkedList<String>(); Version ver = SipActivator.getVersionService().getCurrentVersion(); userAgentTokens.add(ver.getApplicationName()); userAgentTokens.add(ver.toString()); String osName = System.getProperty("os.name"); userAgentTokens.add(osName); userAgentHeader = this.headerFactory.createUserAgentHeader(userAgentTokens); } catch (ParseException ex) { //shouldn't happen return null; } } return userAgentHeader; } /** * Send an error response with the <tt>errorCode</tt> code using * <tt>serverTransaction</tt> and do not surface exceptions. The method * is useful when we are sending the error response in a stack initiated * operation and don't have the possibility to escalate potential * exceptions, so we can only log them. * * @param serverTransaction the transaction that we'd like to send an error * response in. * @param errorCode the code that the response should have. */ public void sayErrorSilently(ServerTransaction serverTransaction, int errorCode) { try { sayError(serverTransaction, errorCode); } catch (OperationFailedException exc) { if (logger.isDebugEnabled()) logger.debug("Failed to send an error " + errorCode + " response", exc); } } /** * Sends an ACK request in the specified dialog. * * @param clientTransaction the transaction that resulted in the ACK we are * about to send (MUST be an INVITE transaction). * * @throws InvalidArgumentException if there is a problem with the supplied * CSeq ( for example <= 0 ). * @throws SipException if the CSeq does not relate to a previously sent * INVITE or if the Method that created the Dialog is not an INVITE ( for * example SUBSCRIBE) or if we fail to send the INVITE for whatever reason. */ public void sendAck(ClientTransaction clientTransaction) throws SipException, InvalidArgumentException { Request ack = messageFactory.createAck(clientTransaction); clientTransaction.getDialog().sendAck(ack); } /** * Send an error response with the <tt>errorCode</tt> code using * <tt>serverTransaction</tt>. * * @param serverTransaction the transaction that we'd like to send an error * response in. * @param errorCode the code that the response should have. * * @throws OperationFailedException if we failed constructing or sending a * SIP Message. */ public void sayError(ServerTransaction serverTransaction, int errorCode) throws OperationFailedException { Request request = serverTransaction.getRequest(); Response errorResponse = null; try { errorResponse = getMessageFactory().createResponse( errorCode, request); //we used to be adding a To tag here and we shouldn't. 3261 says: //"Dialogs are created through [...] non-failure responses". and //we are using this method for failure responses only. } catch (ParseException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to construct an OK response to an INVITE request", OperationFailedException.INTERNAL_ERROR, ex, logger); } try { serverTransaction.sendResponse(errorResponse); if (logger.isDebugEnabled()) logger.debug("sent response: " + errorResponse); } catch (Exception ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send an OK response to an INVITE request", OperationFailedException.INTERNAL_ERROR, ex, logger); } } /** * Sends a specific <tt>Request</tt> through a given * <tt>SipProvider</tt> as part of the conversation associated with a * specific <tt>Dialog</tt>. * * @param sipProvider the <tt>SipProvider</tt> to send the specified * request through * @param request the <tt>Request</tt> to send through * <tt>sipProvider</tt> * @param dialog the <tt>Dialog</tt> as part of which the specified * <tt>request</tt> is to be sent * * @throws OperationFailedException if creating a transaction or sending * the <tt>request</tt> fails. */ public void sendInDialogRequest(SipProvider sipProvider, Request request, Dialog dialog) throws OperationFailedException { ClientTransaction clientTransaction = null; try { clientTransaction = sipProvider.getNewClientTransaction(request); } catch (TransactionUnavailableException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to create a client transaction for request:\n" + request, OperationFailedException.INTERNAL_ERROR, ex, logger); } try { dialog.sendRequest(clientTransaction); } catch (SipException ex) { ProtocolProviderServiceSipImpl.throwOperationFailedException( "Failed to send request:\n" + request, OperationFailedException.NETWORK_FAILURE, ex, logger); } if (logger.isDebugEnabled()) logger.debug("Sent request:\n" + request); } /** * Returns a List of Strings corresponding to all methods that we have a * processor for. * * @return a List of methods that we support. */ public List<String> getSupportedMethods() { return new ArrayList<String>(methodProcessors.keySet()); } /** * A utility class that allows us to block until we receive a * <tt>RegistrationStateChangeEvent</tt> notifying us of an unregistration. */ private static class ShutdownUnregistrationBlockListener implements RegistrationStateChangeListener { /** * The list where we store <tt>RegistationState</tt>s received while * waiting. */ public List<RegistrationState> collectedNewStates = new LinkedList<RegistrationState>(); /** * The method would simply register all received events so that they * could be available for later inspection by the unit tests. In the * case where a registration event notifying us of a completed * registration is seen, the method would call notifyAll(). * * @param evt ProviderStatusChangeEvent the event describing the * status change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { if (logger.isDebugEnabled()) logger.debug("Received a RegistrationStateChangeEvent: " + evt); collectedNewStates.add(evt.getNewState()); if (evt.getNewState().equals(RegistrationState.UNREGISTERED)) { if (logger.isDebugEnabled()) logger.debug( "We're unregistered and will notify those who wait"); synchronized (this) { notifyAll(); } } } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor milliseconds pass (whichever happens first). * * @param waitFor the number of milliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { if (logger.isTraceEnabled()) logger.trace("Waiting for a " +"RegistrationStateChangeEvent.UNREGISTERED"); synchronized (this) { if (collectedNewStates.contains( RegistrationState.UNREGISTERED)) { if (logger.isTraceEnabled()) logger.trace("Event already received. " + collectedNewStates); return; } try { wait(waitFor); if (collectedNewStates.size() > 0) if (logger.isTraceEnabled()) logger.trace( "Received a RegistrationStateChangeEvent."); else if (logger.isTraceEnabled()) logger.trace( "No RegistrationStateChangeEvent received for " + waitFor + "ms."); } catch (InterruptedException ex) { if (logger.isDebugEnabled()) logger.debug( "Interrupted while waiting for a " +"RegistrationStateChangeEvent" , ex); } } } } /** * Returns the sip protocol icon. * @return the sip protocol icon */ public ProtocolIcon getProtocolIcon() { return protocolIcon; } /** * Returns the current instance of <tt>SipStatusEnum</tt>. * * @return the current instance of <tt>SipStatusEnum</tt>. */ SipStatusEnum getSipStatusEnum() { return sipStatusEnum; } /** * Returns the current instance of <tt>SipRegistrarConnection</tt>. * @return SipRegistrarConnection */ SipRegistrarConnection getRegistrarConnection() { return sipRegistrarConnection; } /** * Parses the the <tt>uriStr</tt> string and returns a JAIN SIP URI. * * @param uriStr a <tt>String</tt> containing the uri to parse. * * @return a URI object corresponding to the <tt>uriStr</tt> string. * @throws ParseException if uriStr is not properly formatted. */ public Address parseAddressString(String uriStr) throws ParseException { uriStr = uriStr.trim(); //we don't know how to handle the "tel:" scheme ... or rather we handle //it same as sip so replace: if(uriStr.toLowerCase().startsWith("tel:")) uriStr = "sip:" + uriStr.substring("tel:".length()); //Handle default domain name (i.e. transform 1234 -> [email protected]) //assuming that if no domain name is specified then it should be the //same as ours. if (uriStr.indexOf('@') == -1) { //if we have a registrar, then we could append its domain name as //default SipRegistrarConnection src = getRegistrarConnection(); if(src != null && !src.isRegistrarless() ) { uriStr = uriStr + "@" + ((SipURI)src.getAddressOfRecord().getURI()).getHost(); } //else this could only be a host ... but this should work as is. } //Let's be uri fault tolerant and add the sip: scheme if there is none. if (!uriStr.toLowerCase().startsWith("sip:")) //no sip scheme { uriStr = "sip:" + uriStr; } Address toAddress = getAddressFactory().createAddress(uriStr); return toAddress; } /** * Tries to resolve <tt>address</tt> into a valid InetSocketAddress using * an <tt>SRV</tt> query where it exists and A/AAAA where it doesn't. * If there is no SRV,A or AAAA records return the socket address created * with the supplied <tt>address</tt>, so we can keep old behaviour. * When letting underling libs and java to resolve the address. * * @param address the address we'd like to resolve. * @param transport the protocol that we'd like to use when accessing * address. * @param resultAddresses the list that will be filled with the result * addresses. An <tt>InetSocketAddress</tt> instances containing the * <tt>SRV</tt> record for <tt>address</tt> if one has been defined and the * A/AAAA record where it hasn't. * @param resultTransports the transports for the <tt>resultAddresses</tt>. * @param resolveProtocol if the protocol should be resolved * @return the transports that is used, when the <tt>transport</tt> is with * value Auto we resolve the address with NAPTR query, if no NAPTR record * we will use the default one. * * @throws UnknownHostException if <tt>address</tt> is not a valid host * address. */ public void resolveSipAddress( String address, String transport, List<InetSocketAddress> resultAddresses, List<String> resultTransports, boolean resolveProtocol) throws UnknownHostException { //we need to resolve the address only if its a hostname. if(NetworkUtils.isValidIPAddress(address)) { InetAddress addressObj = NetworkUtils.getInetAddress(address); //this is an ip address so we need to return default ports since //we can't get them from a DNS. int port = ListeningPoint.PORT_5060; if(transport.equalsIgnoreCase(ListeningPoint.TLS)) port = ListeningPoint.PORT_5061; resultTransports.add(transport); resultAddresses.add(new InetSocketAddress(addressObj, port)); // as its ip address return, no dns is needed. return; } boolean preferIPv6Addresses = checkPreferIPv6Addresses(); // first make NAPTR resolve to get protocol, if needed if(resolveProtocol) { try { String[][] naptrRecords = NetworkUtils.getNAPTRRecords(address); if(naptrRecords != null && naptrRecords.length > 0) { for(String[] rec : naptrRecords) { resolveSRV( rec[2], rec[1], resultAddresses, resultTransports, preferIPv6Addresses, true); } // NAPTR found use only it if(logger.isInfoEnabled()) logger.info("Found NAPRT record and using it:" + resultAddresses); // return only if found something if(resultAddresses.size() > 0 && resultTransports.size() > 0) return; } } catch (ParseException e) { logger.error("Error parsing dns record.", e); } } //try to obtain SRV mappings from the DNS try { resolveSRV( address, transport, resultAddresses, resultTransports, preferIPv6Addresses, false); } catch (ParseException e) { logger.error("Error parsing dns record.", e); } //no SRV means default ports int defaultPort = ListeningPoint.PORT_5060; if(transport.equalsIgnoreCase(ListeningPoint.TLS)) defaultPort = ListeningPoint.PORT_5061; ArrayList<InetSocketAddress> tempResultAddresses = new ArrayList<InetSocketAddress>(); // after checking SRVs, lets add and AAAA and A records resolveAddresses( address, tempResultAddresses, preferIPv6Addresses, defaultPort); for(InetSocketAddress a : tempResultAddresses) { if(!resultAddresses.contains(a)) { resultAddresses.add(a); resultTransports.add(transport); } } // make sure we don't return empty array if(resultAddresses.size() == 0) { resultAddresses.add(new InetSocketAddress(address, defaultPort)); resultTransports.add(transport); // there were no SRV mappings so we only need to A/AAAA resolve the // address. Do this before we instantiate the // resulting InetSocketAddress because its constructor // suppresses UnknownHostException-s and we want to know if // something goes wrong. InetAddress addressObj = InetAddress.getByName(address); } } /** * Resolves the given address. Resolves A and AAAA records and returns * them in <tt>resultAddresses</tt> ordered according * <tt>preferIPv6Addresses</tt> option. * @param address the address to resolve. * @param resultAddresses the List in which we provide the result. * @param preferIPv6Addresses whether ipv6 address should go before ipv4. * @param defaultPort the port to use for the result address. * @throws UnknownHostException its not supposed to be thrown, cause * the address we use is an ip address. */ private void resolveAddresses( String address, List<InetSocketAddress> resultAddresses, boolean preferIPv6Addresses, int defaultPort) throws UnknownHostException { //we need to resolve the address only if its a hostname. if(NetworkUtils.isValidIPAddress(address)) { InetAddress addressObj = NetworkUtils.getInetAddress(address); resultAddresses.add(new InetSocketAddress(addressObj, defaultPort)); // as its ip address return, no dns is needed. return; } InetSocketAddress addressObj4 = null; InetSocketAddress addressObj6 = null; try { addressObj4 = NetworkUtils.getARecord(address, defaultPort); } catch (ParseException ex) { logger.error("Error parsing dns record.", ex); } try { addressObj6 = NetworkUtils.getAAAARecord(address, defaultPort); } catch (ParseException ex) { logger.error("Error parsing dns record.", ex); } if(preferIPv6Addresses) { if(addressObj6 != null && !resultAddresses.contains(addressObj6)) resultAddresses.add(addressObj6); if(addressObj4 != null && !resultAddresses.contains(addressObj4)) resultAddresses.add(addressObj4); } else { if(addressObj4 != null && !resultAddresses.contains(addressObj4)) resultAddresses.add(addressObj4); if(addressObj6 != null && !resultAddresses.contains(addressObj6)) resultAddresses.add(addressObj6); } if(addressObj4 == null && addressObj6 == null) logger.warn("No AAAA and A record found for " + address); } /** * Tries to resolve <tt>address</tt> into a valid InetSocketAddress using * an <tt>SRV</tt> query where it exists and A/AAAA where it doesn't. The * method assumes that the transport that we'll be using when connecting to * address is the one that has been defined as default for this provider. * * @param address the address we'd like to resolve. * * @return an <tt>InetSocketAddress</tt> instance containing the * <tt>SRV</tt> record for <tt>address</tt> if one has been defined and the * A/AAAA record where it hasn't. * * @throws UnknownHostException if <tt>address</tt> is not a valid host * address. */ public InetSocketAddress resolveSipAddress(String address) throws UnknownHostException { ArrayList<InetSocketAddress> socketAddressesList = new ArrayList<InetSocketAddress>(); resolveSipAddress(address, getDefaultTransport(), socketAddressesList, new ArrayList<String>(), getAccountID().getAccountPropertyBoolean( ProtocolProviderFactory.PROXY_AUTO_CONFIG, false)); return socketAddressesList.get(0); } /** * Resolves the SRV records add their corresponding AAAA and A records * in the <tt>resultAddresses</tt> ordered by the preference * <tt>preferIPv6Addresses</tt> and their corresponding <tt>transport</tt> * in the <tt>resultTransports</tt>. * @param address the address to resolve. * @param transport the transport to use * @param resultAddresses the result address after resolve. * @param resultTransports and the addresses transports. * @param preferIPv6Addresses is ipv6 addresses are preferred over ipv4. * @param srvQueryString is the supplied address is of type * _sip(s)._protocol.address, a string ready for srv queries, used * when we have a NAPTR returned records with value <tt>true</tt>. * @throws ParseException exception when parsing dns address */ private void resolveSRV(String address, String transport, List<InetSocketAddress> resultAddresses, List<String> resultTransports, boolean preferIPv6Addresses, boolean srvQueryString) throws ParseException { SRVRecord srvRecords[] = null; if(srvQueryString) { srvRecords = NetworkUtils.getSRVRecords(address); } else { srvRecords = NetworkUtils.getSRVRecords( transport.equalsIgnoreCase(ListeningPoint.TLS) ? "sips" : "sip", transport.equalsIgnoreCase(ListeningPoint.UDP) ? ListeningPoint.UDP : ListeningPoint.TCP, address); } if(srvRecords != null) { ArrayList<InetSocketAddress> tempResultAddresses = new ArrayList<InetSocketAddress>(); for(SRVRecord s : srvRecords) { // add corresponding A and AAAA records // to the host address from SRV records try { // as these are already resolved addresses (the SRV res.) // lets get it without triggering a PTR resolveAddresses( s.getTarget(), tempResultAddresses, preferIPv6Addresses, s.getPort()); } catch(UnknownHostException e) { logger.warn("Address unknown:" + s.getTarget(), e); } /* add and every SRV address itself if not already there if(!tempResultAddresses.contains(s)) tempResultAddresses.add(s); */ if (logger.isTraceEnabled()) logger.trace("Returned SRV " + s); } for(InetSocketAddress a : tempResultAddresses) { if(!resultAddresses.contains(a)) { resultAddresses.add(a); resultTransports.add(transport); } } } } /** * Returns the <tt>InetAddress</tt> that is most likely to be to be used * as a next hop when contacting the specified <tt>destination</tt>. This is * an utility method that is used whenever we have to choose one of our * local addresses to put in the Via, Contact or (in the case of no * registrar accounts) From headers. The method also takes into account * the existence of an outbound proxy and in that case returns its address * as the next hop. * * @param destination the destination that we would contact. * * @return the <tt>InetSocketAddress</tt> that is most likely to be to be * used as a next hop when contacting the specified <tt>destination</tt>. * * @throws IllegalArgumentException if <tt>destination</tt> is not a valid * host/ip/fqdn */ public InetSocketAddress getIntendedDestination(Address destination) throws IllegalArgumentException { return getIntendedDestination((SipURI)destination.getURI()); } /** * Returns the <tt>InetAddress</tt> that is most likely to be to be used * as a next hop when contacting the specified <tt>destination</tt>. This is * an utility method that is used whenever we have to choose one of our * local addresses to put in the Via, Contact or (in the case of no * registrar accounts) From headers. The method also takes into account * the existence of an outbound proxy and in that case returns its address * as the next hop. * * @param destination the destination that we would contact. * * @return the <tt>InetSocketAddress</tt> that is most likely to be to be * used as a next hop when contacting the specified <tt>destination</tt>. * * @throws IllegalArgumentException if <tt>destination</tt> is not a valid * host/ip/fqdn */ public InetSocketAddress getIntendedDestination(SipURI destination) throws IllegalArgumentException { return getIntendedDestination(destination.getHost()); } /** * Returns the <tt>InetAddress</tt> that is most likely to be to be used * as a next hop when contacting the specified <tt>destination</tt>. This is * an utility method that is used whenever we have to choose one of our * local addresses to put in the Via, Contact or (in the case of no * registrar accounts) From headers. The method also takes into account * the existence of an outbound proxy and in that case returns its address * as the next hop. * * @param host the destination that we would contact. * * @return the <tt>InetSocketAddress</tt> that is most likely to be to be * used as a next hop when contacting the specified <tt>destination</tt>. * * @throws IllegalArgumentException if <tt>destination</tt> is not a valid * host/ip/fqdn. */ public InetSocketAddress getIntendedDestination(String host) throws IllegalArgumentException { // Address InetSocketAddress destinationInetAddress = null; //resolveSipAddress() verifies whether our destination is valid //but the destination could only be known to our outbound proxy //if we have one. If this is the case replace the destination //address with that of the proxy.(report by Dan Bogos) InetSocketAddress outboundProxy = getOutboundProxy(); if(outboundProxy != null) { if (logger.isTraceEnabled()) logger.trace("Will use proxy address"); destinationInetAddress = outboundProxy; } else { try { destinationInetAddress = resolveSipAddress(host); } catch (UnknownHostException ex) { throw new IllegalArgumentException( host + " is not a valid internet address.", ex); } } if(logger.isDebugEnabled()) logger.debug("Returning address " + destinationInetAddress + " for destination " + host); return destinationInetAddress; } /** * Stops dispatching SIP messages to a SIP protocol provider service * once it's been unregistered. * * @param event the change event in the registration state of a provider. */ public void registrationStateChanged(RegistrationStateChangeEvent event) { if(event.getNewState() == RegistrationState.UNREGISTERED || event.getNewState() == RegistrationState.CONNECTION_FAILED) { ProtocolProviderServiceSipImpl listener = (ProtocolProviderServiceSipImpl) event.getProvider(); sipStackSharing.removeSipListener(listener); listener.removeRegistrationStateChangeListener(this); } } /** * Logs a specific message and associated <tt>Throwable</tt> cause as an * error using the current <tt>Logger</tt> and then throws a new * <tt>OperationFailedException</tt> with the message, a specific error code * and the cause. * * @param message the message to be logged and then wrapped in a new * <tt>OperationFailedException</tt> * @param errorCode the error code to be assigned to the new * <tt>OperationFailedException</tt> * @param cause the <tt>Throwable</tt> that has caused the necessity to log * an error and have a new <tt>OperationFailedException</tt> thrown * @param logger the logger that we'd like to log the error <tt>message</tt> * and <tt>cause</tt>. * * @throws OperationFailedException the exception that we wanted this method * to throw. */ public static void throwOperationFailedException( String message, int errorCode, Throwable cause, Logger logger) throws OperationFailedException { logger.error(message, cause); if(cause == null) throw new OperationFailedException(message, errorCode); else throw new OperationFailedException(message, errorCode, cause); } /** * Check is property java.net.preferIPv6Addresses has default value * set in the application using our property: * net.java.sip.communicator.impl.protocol.sip.PREFER_IPV6_ADDRESSES * if not set - use setting from the system property. * @return is property java.net.preferIPv6Addresses <code>"true"</code>. */ public static boolean checkPreferIPv6Addresses() { String defaultSetting = SipActivator.getResources().getSettingsString( PREFER_IPV6_ADDRESSES); if(!StringUtils.isNullOrEmpty(defaultSetting)) return Boolean.parseBoolean(defaultSetting); // if there is no default setting return the system wide value. return Boolean.getBoolean("java.net.preferIPv6Addresses"); } /** * Registers early message processor. * @param processor early message processor. */ void addEarlyMessageProcessor(SipMessageProcessor processor) { synchronized (earlyProcessors) { if (!earlyProcessors.contains(processor)) { this.earlyProcessors.add(processor); } } } /** * Removes the early message processor. * @param processor early message processor. */ void removeEarlyMessageProcessor(SipMessageProcessor processor) { synchronized (earlyProcessors) { this.earlyProcessors.remove(processor); } } /** * Early process an incoming message from interested listeners. * @param message the message to process. */ void earlyProcessMessage(EventObject message) { synchronized(earlyProcessors) { for (SipMessageProcessor listener : earlyProcessors) { try { if(message instanceof RequestEvent) listener.processMessage((RequestEvent)message); else if(message instanceof ResponseEvent) listener.processResponse((ResponseEvent)message, null); else if(message instanceof TimeoutEvent) listener.processTimeout((TimeoutEvent)message, null); } catch(Throwable t) { logger.error("Error pre-processing message", t); } } } } }
Fix getting local ports for contact headers when using TLS.
src/net/java/sip/communicator/impl/protocol/sip/ProtocolProviderServiceSipImpl.java
Fix getting local ports for contact headers when using TLS.
<ide><path>rc/net/java/sip/communicator/impl/protocol/sip/ProtocolProviderServiceSipImpl.java <ide> <ide> //if we are using tcp, make sure that we include the port of the <ide> //socket that we are actually using and not that of LP <del> if (ListeningPoint.TCP.equalsIgnoreCase(transport)) <del> //|| ListeningPoint.TLS.equalsIgnoreCase(transport)) <add> if (ListeningPoint.TCP.equalsIgnoreCase(transport) <add> || ListeningPoint.TLS.equalsIgnoreCase(transport)) <ide> { <ide> InetSocketAddress localSockAddr <ide> = sipStackSharing.getLocalAddressForDestination(
Java
agpl-3.0
36c286de5d8b599e5edfb9882e5a659cf2c2a9ab
0
bisq-network/exchange,bitsquare/bitsquare,bisq-network/exchange,bitsquare/bitsquare
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.main.dao.wallet.receive; import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.FxmlView; import bisq.desktop.components.BsqAddressTextField; import bisq.desktop.components.TitledGroupBg; import bisq.desktop.main.dao.wallet.BsqBalanceUtil; import bisq.desktop.util.FormBuilder; import bisq.desktop.util.GUIUtil; import bisq.desktop.util.Layout; import bisq.core.app.BisqEnvironment; import bisq.core.btc.wallet.BsqWalletService; import bisq.core.locale.Res; import bisq.core.util.BsqFormatter; import bisq.common.util.Tuple3; import javax.inject.Inject; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import static bisq.desktop.util.FormBuilder.addLabelBsqAddressTextField; import static bisq.desktop.util.FormBuilder.addTitledGroupBg; @FxmlView public class BsqReceiveView extends ActivatableView<GridPane, Void> { private BsqAddressTextField addressTextField; private final BsqWalletService bsqWalletService; private final BsqFormatter bsqFormatter; private final BsqBalanceUtil bsqBalanceUtil; private int gridRow = 0; /////////////////////////////////////////////////////////////////////////////////////////// // Constructor, lifecycle /////////////////////////////////////////////////////////////////////////////////////////// @Inject private BsqReceiveView(BsqWalletService bsqWalletService, BsqFormatter bsqFormatter, BsqBalanceUtil bsqBalanceUtil) { this.bsqWalletService = bsqWalletService; this.bsqFormatter = bsqFormatter; this.bsqBalanceUtil = bsqBalanceUtil; } @Override public void initialize() { gridRow = bsqBalanceUtil.addGroup(root, gridRow); TitledGroupBg titledGroupBg = addTitledGroupBg(root, ++gridRow, 1, Res.get("dao.wallet.receive.fundYourWallet"), Layout.GROUP_DISTANCE); GridPane.setColumnSpan(titledGroupBg, 3); Tuple3<Label, BsqAddressTextField, VBox> tuple = addLabelBsqAddressTextField(root, gridRow, Res.get("dao.wallet.receive.bsqAddress"), Layout.FIRST_ROW_AND_GROUP_DISTANCE); addressTextField = tuple.second; GridPane.setColumnSpan(tuple.third, 3); if (!BisqEnvironment.isDAOActivatedAndBaseCurrencySupportingBsq()) { FormBuilder.addMultilineLabel(root, ++gridRow, Res.get("dao.wallet.receive.daoInfo")); Button daoInfoButton = FormBuilder.addButton(root, ++gridRow, Res.get("dao.wallet.receive.daoInfo.button"), 10); daoInfoButton.setOnAction(e -> { GUIUtil.openWebPage("https://bisq.network/dao"); }); } } @Override protected void activate() { bsqBalanceUtil.activate(); addressTextField.setAddress(bsqFormatter.getBsqAddressStringFromAddress(bsqWalletService.getUnusedAddress())); } @Override protected void deactivate() { bsqBalanceUtil.deactivate(); } }
desktop/src/main/java/bisq/desktop/main/dao/wallet/receive/BsqReceiveView.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.main.dao.wallet.receive; import bisq.desktop.common.view.ActivatableView; import bisq.desktop.common.view.FxmlView; import bisq.desktop.components.BsqAddressTextField; import bisq.desktop.components.TitledGroupBg; import bisq.desktop.main.dao.wallet.BsqBalanceUtil; import bisq.desktop.util.FormBuilder; import bisq.desktop.util.GUIUtil; import bisq.desktop.util.Layout; import bisq.core.app.BisqEnvironment; import bisq.core.btc.wallet.BsqWalletService; import bisq.core.locale.Res; import bisq.core.util.BsqFormatter; import bisq.common.util.Tuple3; import javax.inject.Inject; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import static bisq.desktop.util.FormBuilder.addLabelBsqAddressTextField; import static bisq.desktop.util.FormBuilder.addTitledGroupBg; @FxmlView public class BsqReceiveView extends ActivatableView<GridPane, Void> { private BsqAddressTextField addressTextField; private final BsqWalletService bsqWalletService; private final BsqFormatter bsqFormatter; private final BsqBalanceUtil bsqBalanceUtil; private int gridRow = 0; /////////////////////////////////////////////////////////////////////////////////////////// // Constructor, lifecycle /////////////////////////////////////////////////////////////////////////////////////////// @Inject private BsqReceiveView(BsqWalletService bsqWalletService, BsqFormatter bsqFormatter, BsqBalanceUtil bsqBalanceUtil) { this.bsqWalletService = bsqWalletService; this.bsqFormatter = bsqFormatter; this.bsqBalanceUtil = bsqBalanceUtil; } @Override public void initialize() { gridRow = bsqBalanceUtil.addGroup(root, gridRow); TitledGroupBg titledGroupBg = addTitledGroupBg(root, ++gridRow, 1, Res.get("dao.wallet.receive.fundYourWallet"), Layout.GROUP_DISTANCE); GridPane.setColumnSpan(titledGroupBg, 3); Tuple3<Label, BsqAddressTextField, VBox> tuple = addLabelBsqAddressTextField(root, gridRow, Res.get("dao.wallet.receive.bsqAddress"), Layout.FIRST_ROW_AND_GROUP_DISTANCE); addressTextField = tuple.second; GridPane.setColumnSpan(tuple.third, 3); if (!BisqEnvironment.isDAOActivatedAndBaseCurrencySupportingBsq()) { FormBuilder.addMultilineLabel(root, ++gridRow, Res.get("dao.wallet.receive.daoInfo")); Button daoInfoButton = FormBuilder.addButton(root, ++gridRow, Res.get("dao.wallet.receive.daoInfo.button")); daoInfoButton.setOnAction(e -> { GUIUtil.openWebPage("https://bisq.network/dao"); }); } } @Override protected void activate() { bsqBalanceUtil.activate(); addressTextField.setAddress(bsqFormatter.getBsqAddressStringFromAddress(bsqWalletService.getUnusedAddress())); } @Override protected void deactivate() { bsqBalanceUtil.deactivate(); } }
Add distance to button
desktop/src/main/java/bisq/desktop/main/dao/wallet/receive/BsqReceiveView.java
Add distance to button
<ide><path>esktop/src/main/java/bisq/desktop/main/dao/wallet/receive/BsqReceiveView.java <ide> <ide> if (!BisqEnvironment.isDAOActivatedAndBaseCurrencySupportingBsq()) { <ide> FormBuilder.addMultilineLabel(root, ++gridRow, Res.get("dao.wallet.receive.daoInfo")); <del> Button daoInfoButton = FormBuilder.addButton(root, ++gridRow, Res.get("dao.wallet.receive.daoInfo.button")); <add> Button daoInfoButton = FormBuilder.addButton(root, ++gridRow, Res.get("dao.wallet.receive.daoInfo.button"), 10); <ide> daoInfoButton.setOnAction(e -> { <ide> GUIUtil.openWebPage("https://bisq.network/dao"); <ide> });
JavaScript
mit
cf614eb3b545c944988106a7dd781e0c60847cd6
0
fajran/kasuari,fajran/kasuari,fajran/kasuari
(function() { var KasuariImage = function(ix, iy, iz, url) { this.ix = ix; this.iy = iy; this.iz = iz; this.scale = Math.pow(2, iz); this.loaded = false; this.url = url; this.img = new Image(); this.onload = undefined; this.id = ix + '-' + iy + '-' + iz; var self = this; this.img.onload = function() { self.loaded = true; if (self.onload != undefined) { self.onload(self); } }; }; KasuariImage.prototype = { init: function() { this.img.src = this.url; }, draw: function(ctx, scale) { if (!this.loaded) { return; } var s = scale * this.scale; var dim = 256 * s; var x = Math.ceil(this.ix * dim); var y = Math.ceil(this.iy * dim); var w = Math.ceil(this.img.width * s); var h = Math.ceil(this.img.height * s); try { ctx.drawImage(this.img, x, y, w, h); } catch (err) { // image is removed when this image is about to be rendered } } }; var RedrawBucket = function(kasuari) { var self = this; this.timer = setInterval(function() { self.redraw(); }, 250); this.items = []; this.kasuari = kasuari; }; RedrawBucket.prototype = { add: function(img) { this.items.push(img); }, redraw: function() { var items = this.items.slice(0); this.items = []; // racing condition possibility var level = this.kasuari.zoomLevel; var len = items.length; var added = false; for (var i=0; i<len; i++) { var img = items[i]; if (img.iz == level) { var key = img.ix+','+img.iy; this.kasuari.images[level][key] = img; added = true; } } if (added) { this.kasuari.redraw(); } }, }; var Kasuari = function(canvas, config) { this.canvas = canvas.get(0); this.cw = canvas.width(); this.ch = canvas.height(); this.canvas.width = this.cw; this.canvas.height = this.ch; this.ctx = this.canvas.getContext('2d'); this.dir = config.imgdir; this.ext = config.ext; this.zoomLevel = config.zoomLevel; this.w = config.w; this.h = config.h; this.scale = Math.pow(0.5, this.zoomLevel); this.tx = 0; this.ty = 0; this.drag = {x: 0, y: 0, dx: 0, dy: 0, enabled: false}; this.zooming = {x: 0, y: 0, scale: 0, dx: 0, dy: 0, dscale: 0, tx: 0, ty: 0, tscale: 0, duration: 250, interval: 20, start: new Date(), enabled: false}; this.clickZoomStep = 2.0; this.wheelZoomStep = 2.0; this.images = []; this.redrawBucket = new RedrawBucket(this); }; Kasuari.prototype = { getURL: function(ix, iy, iz) { //return this.dir + '/img-z' + iz + '.x' + ix + '.y' + iy + this.ext; return this.dir + '/' + iz + '.' + ix + '.' + iy + this.ext; }, start: function() { this.initEventHandlers(); this.updateImages(); }, addImage: function(ix, iy, iz) { var url = this.getURL(ix, iy, iz); var img = new KasuariImage(ix, iy, iz, url); var self = this; img.onload = function(img) { if (self.images[iz] == undefined) { self.images[iz] = {}; } self.redrawBucket.add(img); } return img; }, updateSize: function(w, h) { this.cw = $(this.canvas).width(); this.ch = $(this.canvas).height(); this.canvas.width = this.cw; this.canvas.height = this.ch; this.redraw(); }, redraw: function() { this.ctx.clearRect(0, 0, this.cw, this.ch); this.ctx.save(); this.ctx.translate(this.tx, this.ty); var len = this.images.length; for (var i=len-1; i>=0; i--) { var images = this.images[i]; if (images != undefined) { for (var key in images) { images[key].draw(this.ctx, this.scale); } } } this.ctx.restore(); }, updateZoomLevel: function() { var zoomLevel = Math.floor(Math.log(1/this.scale) / Math.log(2)); if (zoomLevel < 0) { zoomLevel = 0; } this.zoomLevel = zoomLevel; }, getVisibleImages: function(level) { var tx = this.tx / this.scale; var ty = this.ty / this.scale; var cw = this.cw / this.scale; var ch = this.ch / this.scale; var size = 256 * Math.pow(2, level); var x0 = Math.floor(-tx / size) - 1; var y0 = Math.floor(-ty / size) - 1; var x1 = Math.ceil((-tx + cw) / size) + 1; var y1 = Math.ceil((-ty + ch) / size) + 1; var items = {}; var x, y; for (x=x0; x<=x1; x++) { for (y=y0; y<=y1; y++) { var px = x * size; var py = y * size; if ((x < 0) || (y < 0)) { continue; } if ((px > this.w) || (py > this.h)) { continue; } items[x+','+y] = [x, y]; } } return items; }, updateVisibleImages: function(level, add) { var items = this.getVisibleImages(level); if (this.images[level] == undefined) { this.images[level] = {}; } // delete unused image for (var key in this.images[level]) { if (!(key in items)) { delete this.images[level][key]; } } // add new image if ((add == undefined) || add) { var images = this.images[level]; for (var key in items) { var data = items[key]; if (!(data in images)) { this.addImage(data[0], data[1], level).init(); } } } }, updateImages: function() { var len = this.images.length; for (var i=0; i<len; i++) { if (i != this.zoomLevel) { this.updateVisibleImages(i, false); } } this.updateVisibleImages(this.zoomLevel); }, /* Event handlers */ initEventHandlers: function() { var canvas = $(this.canvas); var self = this; canvas.mousedown(function(e) { self._mousedown(e); }); canvas.mousemove(function(e) { self._mousemove(e); }); canvas.mouseup(function(e) { self._mouseup(e); }); canvas.dblclick(function(e) { self._dblclick(e); }); canvas.mousewheel(function(e, d) { self._mousewheel(e, d); }); }, _mousedown: function(e) { this.drag.x = e.clientX; this.drag.y = e.clientY; this.drag.dx = 0; this.drag.dy = 0; this.drag.enabled = true; }, _mouseup: function(e) { this.drag.enabled = false; }, _mousemove: function(e) { if (this.drag.enabled) { var x = e.clientX; var y = e.clientY; this.drag.dx = x - this.drag.x; this.drag.dy = y - this.drag.y; this.drag.x = x; this.drag.y = y; this.tx += this.drag.dx; this.ty += this.drag.dy; // this.updateVisibleImages(this.zoomLevel); this.updateImages(); this.redraw(); }; }, _dblclick: function(e) { var canvas = $(this.canvas); var pos = canvas.offset(); var x = e.pageX - pos.left; var y = e.pageY - pos.top; this.zoom(x, y, this.clickZoomStep); }, _mousewheel: function(e, d) { var pos = $(this.canvas).offset(); var x = e.pageX - pos.left; var y = e.pageY - pos.top; if (d > 0) { this.zoom(x, y, this.wheelZoomStep); } else { this.zoom(x, y, 1/this.wheelZoomStep); } return false; }, /* Navigation */ zoom: function(x, y, scale) { if (this.zooming.enabled) { return; } this.zooming.enabled = true; this.zooming.x = this.tx; this.zooming.y = this.ty; this.zooming.scale = this.scale; this.zooming.tx = Math.floor(x - (x - this.tx) * scale); this.zooming.ty = Math.floor(y - (y - this.ty) * scale); this.zooming.tscale = this.scale * scale; this.zooming.dx = this.zooming.tx - this.zooming.x; this.zooming.dy = this.zooming.ty - this.zooming.y; this.zooming.dscale = this.zooming.tscale - this.zooming.scale; this.zooming.start = new Date(); var self = this; setTimeout(function() { self._zoomStep(); }, this.zooming.interval); }, _zoomStep: function() { var tnow = new Date(); var tdelta = tnow - this.zooming.start; var now = tdelta / this.zooming.duration; this.tx = this.zooming.x + this.zooming.dx * now; this.ty = this.zooming.y + this.zooming.dy * now; this.scale = this.zooming.scale + this.zooming.dscale * now; var a = this.tx; if (now >= 1.0) { this.tx = this.zooming.tx; this.ty = this.zooming.ty; this.scale = this.zooming.tscale; } var b = this.tx; if (now < 1.0) { this.redraw(); var self = this; setTimeout(function() { self._zoomStep(); }, this.zooming.interval); } else { this.zooming.enabled = false; this.updateZoomLevel(); this.updateImages(); this.redraw(); } }, }; this.Kasuari = Kasuari; })();
kasuari.js
(function() { var KasuariImage = function(ix, iy, iz, url) { this.ix = ix; this.iy = iy; this.iz = iz; this.scale = Math.pow(2, iz); this.loaded = false; this.url = url; this.img = new Image(); this.onload = undefined; this.id = ix + '-' + iy + '-' + iz; var self = this; this.img.onload = function() { self.loaded = true; if (self.onload != undefined) { self.onload(self); } }; }; KasuariImage.prototype = { init: function() { this.img.src = this.url; }, draw: function(ctx, scale) { if (!this.loaded) { return; } var s = scale * this.scale; var dim = 256 * s; var x = Math.ceil(this.ix * dim); var y = Math.ceil(this.iy * dim); var w = Math.ceil(this.img.width * s); var h = Math.ceil(this.img.height * s); try { ctx.drawImage(this.img, x, y, w, h); } catch (err) { // image is removed when this image is about to be rendered } } }; var RedrawBucket = function(kasuari) { var self = this; this.timer = setInterval(function() { self.redraw(); }, 250); this.items = []; this.kasuari = kasuari; }; RedrawBucket.prototype = { add: function(img) { this.items.push(img); }, redraw: function() { var items = this.items.slice(0); this.items = []; // racing condition possibility var level = this.kasuari.zoomLevel; var len = items.length; var added = false; for (var i=0; i<len; i++) { var img = items[i]; if (img.iz == level) { var key = img.ix+','+img.iy; this.kasuari.images[level][key] = img; added = true; } } if (added) { this.kasuari.redraw(); } }, }; var Kasuari = function(canvas, config) { this.canvas = canvas.get(0); this.cw = canvas.width(); this.ch = canvas.height(); this.canvas.width = this.cw; this.canvas.height = this.ch; this.ctx = this.canvas.getContext('2d'); this.dir = config.imgdir; this.ext = config.ext; this.zoomLevel = config.zoomLevel; this.w = config.w; this.h = config.h; this.scale = Math.pow(0.5, this.zoomLevel); this.tx = 0; this.ty = 0; this.drag = {x: 0, y: 0, dx: 0, dy: 0, enabled: false}; this.zooming = {x: 0, y: 0, scale: 0, dx: 0, dy: 0, dscale: 0, tx: 0, ty: 0, tscale: 0, duration: 250, interval: 20, start: new Date(), enabled: false}; this.clickZoomStep = 2.0; this.wheelZoomStep = 2.0; this.images = []; this.redrawBucket = new RedrawBucket(this); }; Kasuari.prototype = { getURL: function(ix, iy, iz) { //return this.dir + '/img-z' + iz + '.x' + ix + '.y' + iy + this.ext; return this.dir + '/' + iz + '.' + ix + '.' + iy + this.ext; }, start: function() { this.initEventHandlers(); this.updateImages(); }, addImage: function(ix, iy, iz) { var url = this.getURL(ix, iy, iz); var img = new KasuariImage(ix, iy, iz, url); var self = this; img.onload = function(img) { if (self.images[iz] == undefined) { self.images[iz] = {}; } self.redrawBucket.add(img); } return img; }, redraw: function() { this.ctx.clearRect(0, 0, this.cw, this.ch); this.ctx.save(); this.ctx.translate(this.tx, this.ty); var len = this.images.length; for (var i=len-1; i>=0; i--) { var images = this.images[i]; if (images != undefined) { for (var key in images) { images[key].draw(this.ctx, this.scale); } } } this.ctx.restore(); }, updateZoomLevel: function() { var zoomLevel = Math.floor(Math.log(1/this.scale) / Math.log(2)); if (zoomLevel < 0) { zoomLevel = 0; } this.zoomLevel = zoomLevel; }, getVisibleImages: function(level) { var tx = this.tx / this.scale; var ty = this.ty / this.scale; var cw = this.cw / this.scale; var ch = this.ch / this.scale; var size = 256 * Math.pow(2, level); var x0 = Math.floor(-tx / size) - 1; var y0 = Math.floor(-ty / size) - 1; var x1 = Math.ceil((-tx + cw) / size) + 1; var y1 = Math.ceil((-ty + ch) / size) + 1; var items = {}; var x, y; for (x=x0; x<=x1; x++) { for (y=y0; y<=y1; y++) { var px = x * size; var py = y * size; if ((x < 0) || (y < 0)) { continue; } if ((px > this.w) || (py > this.h)) { continue; } items[x+','+y] = [x, y]; } } return items; }, updateVisibleImages: function(level, add) { var items = this.getVisibleImages(level); if (this.images[level] == undefined) { this.images[level] = {}; } // delete unused image for (var key in this.images[level]) { if (!(key in items)) { delete this.images[level][key]; } } // add new image if ((add == undefined) || add) { var images = this.images[level]; for (var key in items) { var data = items[key]; if (!(data in images)) { this.addImage(data[0], data[1], level).init(); } } } }, updateImages: function() { var len = this.images.length; for (var i=0; i<len; i++) { if (i != this.zoomLevel) { this.updateVisibleImages(i, false); } } this.updateVisibleImages(this.zoomLevel); }, /* Event handlers */ initEventHandlers: function() { var canvas = $(this.canvas); var self = this; canvas.mousedown(function(e) { self._mousedown(e); }); canvas.mousemove(function(e) { self._mousemove(e); }); canvas.mouseup(function(e) { self._mouseup(e); }); canvas.dblclick(function(e) { self._dblclick(e); }); canvas.mousewheel(function(e, d) { self._mousewheel(e, d); }); }, _mousedown: function(e) { this.drag.x = e.clientX; this.drag.y = e.clientY; this.drag.dx = 0; this.drag.dy = 0; this.drag.enabled = true; }, _mouseup: function(e) { this.drag.enabled = false; }, _mousemove: function(e) { if (this.drag.enabled) { var x = e.clientX; var y = e.clientY; this.drag.dx = x - this.drag.x; this.drag.dy = y - this.drag.y; this.drag.x = x; this.drag.y = y; this.tx += this.drag.dx; this.ty += this.drag.dy; // this.updateVisibleImages(this.zoomLevel); this.updateImages(); this.redraw(); }; }, _dblclick: function(e) { var canvas = $(this.canvas); var pos = canvas.offset(); var x = e.pageX - pos.left; var y = e.pageY - pos.top; this.zoom(x, y, this.clickZoomStep); }, _mousewheel: function(e, d) { var pos = $(this.canvas).offset(); var x = e.pageX - pos.left; var y = e.pageY - pos.top; if (d > 0) { this.zoom(x, y, this.wheelZoomStep); } else { this.zoom(x, y, 1/this.wheelZoomStep); } return false; }, /* Navigation */ zoom: function(x, y, scale) { if (this.zooming.enabled) { return; } this.zooming.enabled = true; this.zooming.x = this.tx; this.zooming.y = this.ty; this.zooming.scale = this.scale; this.zooming.tx = Math.floor(x - (x - this.tx) * scale); this.zooming.ty = Math.floor(y - (y - this.ty) * scale); this.zooming.tscale = this.scale * scale; this.zooming.dx = this.zooming.tx - this.zooming.x; this.zooming.dy = this.zooming.ty - this.zooming.y; this.zooming.dscale = this.zooming.tscale - this.zooming.scale; this.zooming.start = new Date(); var self = this; setTimeout(function() { self._zoomStep(); }, this.zooming.interval); }, _zoomStep: function() { var tnow = new Date(); var tdelta = tnow - this.zooming.start; var now = tdelta / this.zooming.duration; this.tx = this.zooming.x + this.zooming.dx * now; this.ty = this.zooming.y + this.zooming.dy * now; this.scale = this.zooming.scale + this.zooming.dscale * now; var a = this.tx; if (now >= 1.0) { this.tx = this.zooming.tx; this.ty = this.zooming.ty; this.scale = this.zooming.tscale; } var b = this.tx; if (now < 1.0) { this.redraw(); var self = this; setTimeout(function() { self._zoomStep(); }, this.zooming.interval); } else { this.zooming.enabled = false; this.updateZoomLevel(); this.updateImages(); this.redraw(); } }, }; this.Kasuari = Kasuari; })();
add updateSize function
kasuari.js
add updateSize function
<ide><path>asuari.js <ide> return img; <ide> }, <ide> <add> updateSize: function(w, h) { <add> this.cw = $(this.canvas).width(); <add> this.ch = $(this.canvas).height(); <add> this.canvas.width = this.cw; <add> this.canvas.height = this.ch; <add> this.redraw(); <add> }, <add> <ide> redraw: function() { <ide> this.ctx.clearRect(0, 0, this.cw, this.ch); <ide>
Java
mit
071370fa393c8342459710e6ba1d8ef9bd4ef9f2
0
WesCook/WateringCans
package ca.wescook.wateringcans.crafting; import ca.wescook.wateringcans.WateringCans; import ca.wescook.wateringcans.fluids.ModFluids; import ca.wescook.wateringcans.items.ItemWateringCan; import ca.wescook.wateringcans.items.ModItems; import mezz.jei.api.BlankModPlugin; import mezz.jei.api.IModRegistry; import mezz.jei.api.ISubtypeRegistry; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.fluids.UniversalBucket; import javax.annotation.Nonnull; import javax.annotation.Nullable; @mezz.jei.api.JEIPlugin public class JEIPlugin extends BlankModPlugin { @Override public void registerItemSubtypes(ISubtypeRegistry subtypeRegistry) { // Register NBT uniquely so JEI distinguishes between each watering can ISubtypeRegistry.ISubtypeInterpreter wateringCanInterpreter = new ISubtypeRegistry.ISubtypeInterpreter() { @Nullable @Override public String getSubtypeInfo(ItemStack itemStack) { if (itemStack.getTagCompound() != null) return itemStack.getTagCompound().getString("material"); return null; } }; subtypeRegistry.registerSubtypeInterpreter(ModItems.itemWateringCan, wateringCanInterpreter); } @Override public void register(@Nonnull IModRegistry registry) { // Add description for growth solution bucket ItemStack growthBucket = UniversalBucket.getFilledBucket(ForgeModContainer.getInstance().universalBucket, ModFluids.fluidGrowthSolution); // Create instance of growth solution bucket registry.addDescription(growthBucket, "jei.wateringcans:growth_bucket"); // Create description page for it // Add description for watering cans for (String material : WateringCans.materials) { ItemStack tempItem = new ItemStack(ModItems.itemWateringCan); // Create ItemStack NBTTagCompound nbtCompound = ItemWateringCan.getDefaultNBT(); // Create compound from NBT defaults nbtCompound.setString("material", material); // Overwrite material tag tempItem.setTagCompound(nbtCompound); // Assign tag to ItemStack registry.addDescription(tempItem, "jei.wateringcans:watering_can_" + material); // Create description page } } }
src/main/java/ca/wescook/wateringcans/crafting/JEIPlugin.java
package ca.wescook.wateringcans.crafting; import ca.wescook.wateringcans.WateringCans; import ca.wescook.wateringcans.fluids.ModFluids; import ca.wescook.wateringcans.items.ItemWateringCan; import ca.wescook.wateringcans.items.ModItems; import mezz.jei.api.BlankModPlugin; import mezz.jei.api.IModRegistry; import mezz.jei.api.ISubtypeRegistry; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.fluids.UniversalBucket; import javax.annotation.Nonnull; import javax.annotation.Nullable; @mezz.jei.api.JEIPlugin public class JEIPlugin extends BlankModPlugin { @Override public void registerItemSubtypes(ISubtypeRegistry subtypeRegistry) { // Register NBT uniquely so JEI distinguishes between each watering can ISubtypeRegistry.ISubtypeInterpreter wateringCanInterpreter = new ISubtypeRegistry.ISubtypeInterpreter() { @Nullable @Override public String getSubtypeInfo(ItemStack itemStack) { if (itemStack.getTagCompound() != null) return itemStack.getTagCompound().getString("material"); return null; } }; subtypeRegistry.registerNbtInterpreter(ModItems.itemWateringCan, wateringCanInterpreter); } @Override public void register(@Nonnull IModRegistry registry) { // Add description for growth solution bucket ItemStack growthBucket = UniversalBucket.getFilledBucket(ForgeModContainer.getInstance().universalBucket, ModFluids.fluidGrowthSolution); // Create instance of growth solution bucket registry.addDescription(growthBucket, "jei.wateringcans:growth_bucket"); // Create description page for it // Add description for watering cans for (String material : WateringCans.materials) { ItemStack tempItem = new ItemStack(ModItems.itemWateringCan); // Create ItemStack NBTTagCompound nbtCompound = ItemWateringCan.getDefaultNBT(); // Create compound from NBT defaults nbtCompound.setString("material", material); // Overwrite material tag tempItem.setTagCompound(nbtCompound); // Assign tag to ItemStack registry.addDescription(tempItem, "jei.wateringcans:watering_can_" + material); // Create description page } } }
Updating JEI deprecated method
src/main/java/ca/wescook/wateringcans/crafting/JEIPlugin.java
Updating JEI deprecated method
<ide><path>rc/main/java/ca/wescook/wateringcans/crafting/JEIPlugin.java <ide> return null; <ide> } <ide> }; <del> subtypeRegistry.registerNbtInterpreter(ModItems.itemWateringCan, wateringCanInterpreter); <add> subtypeRegistry.registerSubtypeInterpreter(ModItems.itemWateringCan, wateringCanInterpreter); <ide> } <ide> <ide> @Override
Java
mit
e989c080bc69307ffdf446f2dca502b15982b77b
0
university-information-system/uis,university-information-system/uis,university-information-system/uis,university-information-system/uis
package at.ac.tuwien.inso.initializer; import at.ac.tuwien.inso.entity.*; import at.ac.tuwien.inso.entity.Role; import at.ac.tuwien.inso.repository.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.*; import org.springframework.context.annotation.*; import java.math.*; import java.util.*; import java.util.stream.*; import static java.util.Arrays.*; @Configuration @Profile("demo") public class DataInitializer { @Autowired CourseRepository courseRepository; @Autowired private UserAccountRepository userAccountRepository; @Autowired private UisUserRepository uisUserRepository; @Autowired private SubjectRepository subjectRepository; @Autowired private SemesterRepository semesterRepository; @Autowired private StudyPlanRepository studyPlanRepository; @Autowired private SubjectForStudyPlanRepository subjectForStudyPlanRepository; private List<Student> students; private List<Lecturer> lecturers; @Bean CommandLineRunner initialize() { return String -> { userAccountRepository.save(new UserAccount("admin", "pass", Role.ADMIN)); createUsers(); //create semesters Semester ss2016 = semesterRepository.save(new Semester("SS2016")); Semester ws2016 = semesterRepository.save(new Semester("WS2016")); //subjects Subject calculus = subjectRepository.save(new Subject("Calculus", new BigDecimal(3.0))); calculus.addLecturers(lecturers.get(3)); Subject sepm = subjectRepository.save(new Subject("SEPM", new BigDecimal(6.0))); sepm.addLecturers(lecturers.get(3)); Subject ase = subjectRepository.save(new Subject("ASE", new BigDecimal(6.0))); ase.addRequiredSubjects(sepm); ase.addLecturers(lecturers.get(3), lecturers.get(4)); subjectRepository.save(ase); subjectRepository.save(sepm); subjectRepository.save(calculus); //courses Course sepmSS2016 = courseRepository.save(new Course(sepm,ss2016)); Course sepmWS2016 = courseRepository.save(new Course(sepm,ws2016)); sepmWS2016.addStudents(students.get(3)); Course aseWS2016 = courseRepository.save(new Course(ase,ws2016)); aseWS2016.addStudents(students.get(0), students.get(1), students.get(2), students.get(3)); Course calculusWS2016 = courseRepository.save(new Course(calculus, ws2016)); calculusWS2016.addStudents(students.get(0), students.get(3)); //study plan StudyPlan studyPlan = studyPlanRepository.save(new StudyPlan("SE",new EctsDistribution(new BigDecimal(90), new BigDecimal(60), new BigDecimal(30)))); SubjectForStudyPlan subjectForStudyPlan1 = subjectForStudyPlanRepository.save(new SubjectForStudyPlan(calculus, false)); SubjectForStudyPlan subjectForStudyPlan2 = subjectForStudyPlanRepository.save(new SubjectForStudyPlan(ase, true)); SubjectForStudyPlan subjectForStudyPlan3 = subjectForStudyPlanRepository.save(new SubjectForStudyPlan(sepm, true)); studyPlan.addSubjects(subjectForStudyPlan1, subjectForStudyPlan2, subjectForStudyPlan3); }; } private void createUsers() { Iterable<UisUser> users = uisUserRepository.save(asList( new Student("Emma Dowd", "[email protected]", new UserAccount("emma", "pass", Role.STUDENT)), new Lecturer("Carol Sanderson", "[email protected]"), new Lecturer("Una Walker", "[email protected]", new UserAccount("lecturer", "pass", Role.LECTURER)), new Student("Caroline Black", "[email protected]", new UserAccount("student", "pass", Role.STUDENT)), new Student("Joan Watson", "[email protected]"), new Lecturer("Connor MacLeod", "[email protected]"), new Student("James Bond", "[email protected]"), new Student("Trevor Bond", "[email protected]"), new Lecturer("Eric Wilkins", "[email protected]", new UserAccount("eric", "pass", Role.LECTURER)), new Lecturer("Benjamin Piper", "[email protected]", new UserAccount("ben", "pass", Role.LECTURER)) )); students = StreamSupport.stream(users.spliterator(), false) .filter(it -> it instanceof Student) .map(it -> (Student) it) .collect(Collectors.toList()); lecturers = StreamSupport.stream(users.spliterator(), false) .filter(it -> it instanceof Lecturer) .map(it -> (Lecturer) it) .collect(Collectors.toList()); } }
src/main/java/at/ac/tuwien/inso/initializer/DataInitializer.java
package at.ac.tuwien.inso.initializer; import at.ac.tuwien.inso.entity.*; import at.ac.tuwien.inso.entity.Role; import at.ac.tuwien.inso.repository.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.*; import org.springframework.context.annotation.*; import java.math.*; import java.util.*; import java.util.stream.*; import static java.util.Arrays.*; @Configuration @Profile("demo") public class DataInitializer { @Autowired CourseRepository courseRepository; @Autowired private UserAccountRepository userAccountRepository; @Autowired private UisUserRepository uisUserRepository; @Autowired private SubjectRepository subjectRepository; @Autowired private SemesterRepository semesterRepository; @Autowired private StudyPlanRepository studyPlanRepository; @Autowired private SubjectForStudyPlanRepository subjectForStudyPlanRepository; private List<Student> students; private List<Lecturer> lecturers; @Bean CommandLineRunner initialize() { return String -> { userAccountRepository.save(new UserAccount("admin", "pass", Role.ADMIN)); createUsers(); //create semesters Semester ss2016 = semesterRepository.save(new Semester("SS2016")); Semester ws2016 = semesterRepository.save(new Semester("WS2016")); //subjects Subject calculus = subjectRepository.save(new Subject("Calculus", new BigDecimal(3.0))); calculus.addLecturers(lecturers.get(2)); Subject sepm = subjectRepository.save(new Subject("SEPM", new BigDecimal(6.0))); sepm.addLecturers(lecturers.get(0)); Subject ase = subjectRepository.save(new Subject("ASE", new BigDecimal(6.0))); ase.addRequiredSubjects(sepm); ase.addLecturers(lecturer1); subjectRepository.save(ase); subjectRepository.save(sepm); subjectRepository.save(calculus); ase.addLecturers(lecturers.get(0), lecturers.get(2)); //courses Course sepmSS2016 = courseRepository.save(new Course(sepm,ss2016)); Course sepmWS2016 = courseRepository.save(new Course(sepm,ws2016)); sepmWS2016.addStudents(students.get(3)); Course aseWS2016 = courseRepository.save(new Course(ase,ws2016)); aseWS2016.addStudents(students.get(0), students.get(1), students.get(2), students.get(3)); Course calculusWS2016 = courseRepository.save(new Course(calculus, ws2016)); calculusWS2016.addStudents(students.get(0), students.get(3)); //study plan StudyPlan studyPlan = studyPlanRepository.save(new StudyPlan("SE",new EctsDistribution(new BigDecimal(90), new BigDecimal(60), new BigDecimal(30)))); SubjectForStudyPlan subjectForStudyPlan1 = subjectForStudyPlanRepository.save(new SubjectForStudyPlan(calculus, false)); SubjectForStudyPlan subjectForStudyPlan2 = subjectForStudyPlanRepository.save(new SubjectForStudyPlan(ase, true)); SubjectForStudyPlan subjectForStudyPlan3 = subjectForStudyPlanRepository.save(new SubjectForStudyPlan(sepm, true)); studyPlan.addSubjects(subjectForStudyPlan1, subjectForStudyPlan2, subjectForStudyPlan3); }; } private void createUsers() { Iterable<UisUser> users = uisUserRepository.save(asList( new Student("Emma Dowd", "[email protected]", new UserAccount("emma", "pass", Role.STUDENT)), new Lecturer("Carol Sanderson", "[email protected]"), new Lecturer("Una Walker", "[email protected]", new UserAccount("lecturer", "pass", Role.LECTURER)), new Student("Caroline Black", "[email protected]", new UserAccount("student", "pass", Role.STUDENT)), new Student("Joan Watson", "[email protected]"), new Lecturer("Connor MacLeod", "[email protected]"), new Student("James Bond", "[email protected]"), new Student("Trevor Bond", "[email protected]"), new Lecturer("Eric Wilkins", "[email protected]", new UserAccount("eric", "pass", Role.LECTURER)), new Lecturer("Benjamin Piper", "[email protected]", new UserAccount("ben", "pass", Role.LECTURER)) )); students = StreamSupport.stream(users.spliterator(), false) .filter(it -> it instanceof Student) .map(it -> (Student) it) .collect(Collectors.toList()); lecturers = StreamSupport.stream(users.spliterator(), false) .filter(it -> it instanceof Lecturer) .map(it -> (Lecturer) it) .collect(Collectors.toList()); } }
adapt new data
src/main/java/at/ac/tuwien/inso/initializer/DataInitializer.java
adapt new data
<ide><path>rc/main/java/at/ac/tuwien/inso/initializer/DataInitializer.java <ide> <ide> //subjects <ide> Subject calculus = subjectRepository.save(new Subject("Calculus", new BigDecimal(3.0))); <del> calculus.addLecturers(lecturers.get(2)); <add> calculus.addLecturers(lecturers.get(3)); <ide> Subject sepm = subjectRepository.save(new Subject("SEPM", new BigDecimal(6.0))); <del> sepm.addLecturers(lecturers.get(0)); <add> sepm.addLecturers(lecturers.get(3)); <ide> Subject ase = subjectRepository.save(new Subject("ASE", new BigDecimal(6.0))); <ide> ase.addRequiredSubjects(sepm); <del> ase.addLecturers(lecturer1); <add> ase.addLecturers(lecturers.get(3), lecturers.get(4)); <ide> subjectRepository.save(ase); <ide> subjectRepository.save(sepm); <ide> subjectRepository.save(calculus); <del> ase.addLecturers(lecturers.get(0), lecturers.get(2)); <ide> <ide> //courses <ide> Course sepmSS2016 = courseRepository.save(new Course(sepm,ss2016));
JavaScript
apache-2.0
7dba8c1117dd550b79483fd27f9f57d8ada421fc
0
bastienmichaux/generator-jhipster-db-helper,bastienmichaux/generator-jhipster-db-helper
const path = require('path'); const fse = require('fs-extra'); const assert = require('yeoman-assert'); const helpers = require('yeoman-test'); const _ = require('lodash'); const dbh = require('../generators/dbh.js'); const DBH_CONSTANTS = require('../generators/dbh-constants'); const expectedAppConfig = { 'generator-jhipster': { baseName: 'sampleMysql', packageName: 'com.mycompany.myapp', packageFolder: 'com/mycompany/myapp', authenticationType: 'session', hibernateCache: 'ehcache', clusteredHttpSession: 'no', websocket: 'no', databaseType: 'sql', devDatabaseType: 'h2Disk', prodDatabaseType: 'mysql', searchEngine: 'no', useSass: false, buildTool: 'maven', frontendBuilder: 'grunt', enableTranslation: true, enableSocialSignIn: false, rememberMeKey: '2bb60a80889aa6e6767e9ccd8714982681152aa5', testFrameworks: [ 'gatling' ] } }; // Dbh unit test describe('Dbh', function () { describe('getColumnIdName', function () { it('works as expected with treacherous input', function () { assert(dbh.getColumnIdName('Authors') === 'authors_id'); assert(dbh.getColumnIdName('AUTHORS') === 'authors_id'); assert(dbh.getColumnIdName('IT_IS_OVER_9000') === 'it_is_over_9000_id'); assert(dbh.getColumnIdName('AuthorTable') === 'author_table_id'); assert(dbh.getColumnIdName('TheAuthor_table') === 'the_author_table_id'); assert(dbh.getColumnIdName('XMLHTTPPosts') === 'xmlhttpposts_id'); assert(dbh.getColumnIdName('CssClassesService') === 'css_classes_service_id'); assert(dbh.getColumnIdName('CSSClassesService') === 'cssclasses_service_id'); }); }); describe('getFilesWithNamingStrategy', function () { it('excludes the Gradle file(s) when given \'maven\' as parameter', function () { // compare sorted arrays (index is irrelevant) const files = dbh.getFilesWithNamingStrategy('maven').sort(); const expectedArray = [ './pom.xml', './src/main/resources/config/application.yml', './src/test/resources/config/application.yml' ].sort(); assert(_.isEqual(files, expectedArray)); }); it('excludes the Maven file(s) when given \'gradle\' as parameter', function () { // compare sorted arrays (index is irrelevant) const files = dbh.getFilesWithNamingStrategy('gradle').sort(); const expectedArray = [ './src/main/resources/config/application.yml', './src/test/resources/config/application.yml', './gradle/liquibase.gradle', ].sort(); assert(_.isEqual(files, expectedArray)); }); it('throws when given an unknown build tool', function () { assert.throws(() => { let foo = dbh.getFilesWithNamingStrategy('foo'); l; }, Error); }); }); describe('getPluralColumnIdName', function () { it('tests THINGS', function () { assert(dbh.getPluralColumnIdName('author') === 'authors_id'); assert(dbh.getPluralColumnIdName('the_Authors_table') === 'the_authors_tables_id'); assert(dbh.getPluralColumnIdName('01234') === '01234s_id'); assert(dbh.getPluralColumnIdName('AUTHORSTABLE') === 'authorstables_id'); assert(dbh.getPluralColumnIdName('AUTHORS_TABLE') === 'authors_tables_id'); assert(dbh.getPluralColumnIdName('_') === '_s_id'); assert(dbh.getPluralColumnIdName('') === '_id'); assert(dbh.getPluralColumnIdName('\rAuthor') === '\rauthors_id'); assert(dbh.getPluralColumnIdName('\tAuthor') === '\tauthors_id'); assert(dbh.getPluralColumnIdName('XMLHTTPAPIService') === 'xmlhttpapiservices_id'); assert(dbh.getPluralColumnIdName('XmlHttpApiService') === 'xml_http_api_services_id'); }); }); describe('hasConstraints', function () { const relationshipsSamples = { oneToOneOwner: [ { relationshipType: 'one-to-one', relationshipName: 'region', otherEntityName: 'region', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'country' } ], mixedWithOneConstraint: [ { relationshipType: 'one-to-one', relationshipName: 'location', otherEntityName: 'location', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'department' }, { relationshipType: 'one-to-many', javadoc: 'A relationship', relationshipName: 'employee', otherEntityName: 'employee', otherEntityRelationshipName: 'department' } ], mixedWithTwoConstraints: [ { relationshipName: 'department', otherEntityName: 'department', relationshipType: 'many-to-one', otherEntityField: 'id' }, { relationshipType: 'one-to-many', relationshipName: 'job', otherEntityName: 'job', otherEntityRelationshipName: 'employee' }, { relationshipType: 'many-to-one', relationshipName: 'manager', otherEntityName: 'employee', otherEntityField: 'id' } ], tripleOneToOneOwner: [ { relationshipType: 'one-to-one', relationshipName: 'job', otherEntityName: 'job', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'jobHistory' }, { relationshipType: 'one-to-one', relationshipName: 'department', otherEntityName: 'department', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'jobHistory' }, { relationshipType: 'one-to-one', relationshipName: 'employee', otherEntityName: 'employee', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'jobHistory' } ], mixedConstraints: [ { relationshipName: 'employee', otherEntityName: 'employee', relationshipType: 'many-to-one', otherEntityField: 'id' }, { relationshipType: 'many-to-many', otherEntityRelationshipName: 'job', relationshipName: 'task', otherEntityName: 'task', otherEntityField: 'title', ownerSide: true } ], Empty: [], manyToManyNotOwner: [ { relationshipType: 'many-to-many', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' } ], oneToOneNotOwner: [ { relationshipType: 'one-to-one', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' } ], mixedNotOwner: [ { relationshipType: 'one-to-one', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' }, { relationshipType: 'many-to-many', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' } ] }; it('returns false with empty relation', function () { assert(dbh.hasConstraints(relationshipsSamples.Empty) === false); }); it('returns false if not owner of the relationship', function () { assert(dbh.hasConstraints(relationshipsSamples.manyToManyNotOwner) === false); assert(dbh.hasConstraints(relationshipsSamples.oneToOneNotOwner) === false); assert(dbh.hasConstraints(relationshipsSamples.mixedNotOwner) === false); }); it('returns true if owner of the relationship', function () { assert(dbh.hasConstraints(relationshipsSamples.oneToOneOwner) === true); assert(dbh.hasConstraints(relationshipsSamples.tripleOneToOneOwner) === true); }); it('returns true if it is owner in at least one relation', function () { assert(dbh.hasConstraints(relationshipsSamples.mixedConstraints) === true); assert(dbh.hasConstraints(relationshipsSamples.mixedWithOneConstraint) === true); assert(dbh.hasConstraints(relationshipsSamples.mixedWithTwoConstraints) === true); }); }); describe('isNotEmptyString', function () { it('works with true strings', function () { assert(dbh.isNotEmptyString('x') === true); assert(dbh.isNotEmptyString(' ') === true); assert(dbh.isNotEmptyString('\r') === true); }); it('fails with wrong input', function () { assert(dbh.isNotEmptyString('') === false); assert(dbh.isNotEmptyString(() => 'foo') === false); }); }); describe('isValidBuildTool', function () { it('works as expected', function () { assert(dbh.isValidBuildTool('maven') === true); assert(dbh.isValidBuildTool('gradle') === true); assert(dbh.isValidBuildTool('Maven') === false); assert(dbh.isValidBuildTool('Gradle') === false); assert(dbh.isValidBuildTool('foo') === false); assert(dbh.isValidBuildTool() === false); }); }); describe('validateColumnName', function () { // messages output by validateColumnName // TODO: 0% maintainability, find something smarter const failMsgWhenSpecialChar = 'Your column name cannot contain special characters'; const failMsgWhenEmpty = 'Your column name cannot be empty'; const failMsgWhenTooLongForOracle = 'Your column name is too long for Oracle, try a shorter name'; it('valid column names return true', function () { assert(dbh.validateColumnName('Book', 'mysql') === true); assert(dbh.validateColumnName('FOO', 'mysql') === true); assert(dbh.validateColumnName('bar', 'mysql') === true); assert(dbh.validateColumnName('_foo2', 'mysql') === true); assert(dbh.validateColumnName('2Foo2Bar', 'mysql') === true); assert(dbh.validateColumnName('06', 'mysql') === true); assert(dbh.validateColumnName('_', 'mysql') === true); assert(dbh.validateColumnName('quiteLongTableName', 'mysql') === true); assert(dbh.validateColumnName('definitelyVeryLongTableName', 'mysql') === true); }); it(`returns '${failMsgWhenSpecialChar}'`, function () { assert(dbh.validateColumnName(' ', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('\r', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('\t', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('Böök', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('book-table', 'mysql') === failMsgWhenSpecialChar); }); it(`returns '${failMsgWhenEmpty}'`, function () { assert(dbh.validateColumnName('', 'mysql') === failMsgWhenEmpty); }); it(`returns '${failMsgWhenTooLongForOracle}'`, function () { assert(dbh.validateColumnName('definitelyVeryLongTableName', 'oracle') === failMsgWhenTooLongForOracle); }); }); describe('validateTableName', function () { // messages output by validateTableName // TODO: 0% maintainability, find something smarter const failMsgWhenSpecialChar = 'The table name cannot contain special characters'; const failMsgWhenEmpty = 'The table name cannot be empty'; const failMsgWhenTooLongForOracle = 'The table name is too long for Oracle, try a shorter name'; const failMsgWhenLongForOracle = 'The table name is long for Oracle, long table names can cause issues when used to create constraint names and join table names'; it('valid table names return true', function () { assert(dbh.validateTableName('Book', 'mysql')); assert(dbh.validateTableName('FOO', 'mysql') === true); assert(dbh.validateTableName('bar', 'mysql') === true); assert(dbh.validateTableName('_foo2', 'mysql') === true); assert(dbh.validateTableName('2Foo2Bar', 'mysql') === true); assert(dbh.validateTableName('06', 'mysql') === true); assert(dbh.validateTableName('_', 'mysql') === true); assert(dbh.validateTableName('quiteLongTableName', 'mysql') === true); assert(dbh.validateTableName('definitelyVeryLongTableName', 'mysql') === true); }); it('returns the correct error message with a name containing a reserved keyword', function () { assert.textEqual(dbh.validateTableName('ASENSITIVE', 'mysql').toString(), '\'ASENSITIVE\' is a mysql reserved keyword.'); }); it('fails with missing parameter', function () { assert.throws(() => dbh.validateTableName('Book'), Error); }); it(`returns '${failMsgWhenSpecialChar}'`, function () { assert(dbh.validateTableName('Böök', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateTableName('book-table', 'mysql') === failMsgWhenSpecialChar); }); it(`returns '${failMsgWhenEmpty}'`, function () { assert(dbh.validateTableName('', 'mysql') === failMsgWhenEmpty); }); it(`returns '${failMsgWhenTooLongForOracle}'`, function () { assert(dbh.validateTableName('definitelyVeryLongTableName', 'oracle') === failMsgWhenTooLongForOracle); }); it(`returns '${failMsgWhenLongForOracle}'`, function () { assert(dbh.validateTableName('quiteLongTableName', 'oracle') === failMsgWhenLongForOracle); }); }); /* describe('', function () { it('', function () { }); }); */ });
test/test-dbh.js
const path = require('path'); const fse = require('fs-extra'); const assert = require('yeoman-assert'); const helpers = require('yeoman-test'); const _ = require('lodash'); const dbh = require('../generators/dbh.js'); const DBH_CONSTANTS = require('../generators/dbh-constants'); const expectedAppConfig = { 'generator-jhipster': { baseName: 'sampleMysql', packageName: 'com.mycompany.myapp', packageFolder: 'com/mycompany/myapp', authenticationType: 'session', hibernateCache: 'ehcache', clusteredHttpSession: 'no', websocket: 'no', databaseType: 'sql', devDatabaseType: 'h2Disk', prodDatabaseType: 'mysql', searchEngine: 'no', useSass: false, buildTool: 'maven', frontendBuilder: 'grunt', enableTranslation: true, enableSocialSignIn: false, rememberMeKey: '2bb60a80889aa6e6767e9ccd8714982681152aa5', testFrameworks: [ 'gatling' ] } }; // Dbh unit test describe('Dbh', function () { describe('getColumnIdName', function () { it('works as expected with treacherous input', function () { assert(dbh.getColumnIdName('Authors') === 'authors_id'); assert(dbh.getColumnIdName('AUTHORS') === 'authors_id'); assert(dbh.getColumnIdName('IT_IS_OVER_9000') === 'it_is_over_9000_id'); assert(dbh.getColumnIdName('AuthorTable') === 'author_table_id'); assert(dbh.getColumnIdName('TheAuthor_table') === 'the_author_table_id'); assert(dbh.getColumnIdName('XMLHTTPPosts') === 'xmlhttpposts_id'); assert(dbh.getColumnIdName('CssClassesService') === 'css_classes_service_id'); assert(dbh.getColumnIdName('CSSClassesService') === 'cssclasses_service_id'); }); }); describe('getFilesWithNamingStrategy', function () { it('excludes the Gradle file(s) when given \'maven\' as parameter', function () { // compare sorted arrays (index is irrelevant) const files = dbh.getFilesWithNamingStrategy('maven').sort(); const expectedArray = [ './pom.xml', './src/main/resources/config/application.yml', './src/test/resources/config/application.yml' ].sort(); assert(_.isEqual(files, expectedArray)); }); it('excludes the Maven file(s) when given \'gradle\' as parameter', function () { // compare sorted arrays (index is irrelevant) const files = dbh.getFilesWithNamingStrategy('gradle').sort(); const expectedArray = [ './src/main/resources/config/application.yml', './src/test/resources/config/application.yml', './gradle/liquibase.gradle', ].sort(); assert(_.isEqual(files, expectedArray)); }); it('throws when given an unknown build tool', function () { assert.throws(() => { let foo = dbh.getFilesWithNamingStrategy('foo'); l; }, Error); }); }); describe('getPluralColumnIdName', function () { it('tests THINGS', function () { assert(dbh.getPluralColumnIdName('author') === 'authors_id'); assert(dbh.getPluralColumnIdName('the_Authors_table') === 'the_authors_tables_id'); assert(dbh.getPluralColumnIdName('01234') === '01234s_id'); assert(dbh.getPluralColumnIdName('AUTHORSTABLE') === 'authorstables_id'); assert(dbh.getPluralColumnIdName('AUTHORS_TABLE') === 'authors_tables_id'); assert(dbh.getPluralColumnIdName('_') === '_s_id'); assert(dbh.getPluralColumnIdName('') === '_id'); assert(dbh.getPluralColumnIdName('\rAuthor') === '\rauthors_id'); assert(dbh.getPluralColumnIdName('\tAuthor') === '\tauthors_id'); assert(dbh.getPluralColumnIdName('XMLHTTPAPIService') === 'xmlhttpapiservices_id'); assert(dbh.getPluralColumnIdName('XmlHttpApiService') === 'xml_http_api_services_id'); }); }); describe('hasConstraints', function () { const relationshipsSamples = { oneToOneOwner: [ { relationshipType: 'one-to-one', relationshipName: 'region', otherEntityName: 'region', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'country' } ], mixedWithOneConstraint: [ { relationshipType: 'one-to-one', relationshipName: 'location', otherEntityName: 'location', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'department' }, { relationshipType: 'one-to-many', javadoc: 'A relationship', relationshipName: 'employee', otherEntityName: 'employee', otherEntityRelationshipName: 'department' } ], mixedWithTwoConstraints: [ { relationshipName: 'department', otherEntityName: 'department', relationshipType: 'many-to-one', otherEntityField: 'id' }, { relationshipType: 'one-to-many', relationshipName: 'job', otherEntityName: 'job', otherEntityRelationshipName: 'employee' }, { relationshipType: 'many-to-one', relationshipName: 'manager', otherEntityName: 'employee', otherEntityField: 'id' } ], tripleOneToOneOwner: [ { relationshipType: 'one-to-one', relationshipName: 'job', otherEntityName: 'job', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'jobHistory' }, { relationshipType: 'one-to-one', relationshipName: 'department', otherEntityName: 'department', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'jobHistory' }, { relationshipType: 'one-to-one', relationshipName: 'employee', otherEntityName: 'employee', otherEntityField: 'id', ownerSide: true, otherEntityRelationshipName: 'jobHistory' } ], mixedConstraints: [ { relationshipName: 'employee', otherEntityName: 'employee', relationshipType: 'many-to-one', otherEntityField: 'id' }, { relationshipType: 'many-to-many', otherEntityRelationshipName: 'job', relationshipName: 'task', otherEntityName: 'task', otherEntityField: 'title', ownerSide: true } ], Empty: [], manyToManyNotOwner: [ { relationshipType: 'many-to-many', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' } ], oneToOneNotOwner: [ { relationshipType: 'one-to-one', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' } ], mixedNotOwner: [ { relationshipType: 'one-to-one', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' }, { relationshipType: 'many-to-many', relationshipName: 'job', otherEntityName: 'job', ownerSide: false, otherEntityRelationshipName: 'task' } ] }; it('returns false with empty relation', function () { assert(dbh.hasConstraints(relationshipsSamples.Empty) === false); }); it('returns false if not owner of the relationship', function () { assert(dbh.hasConstraints(relationshipsSamples.manyToManyNotOwner) === false); assert(dbh.hasConstraints(relationshipsSamples.oneToOneNotOwner) === false); assert(dbh.hasConstraints(relationshipsSamples.mixedNotOwner) === false); }); it('returns true if owner of the relationship', function () { assert(dbh.hasConstraints(relationshipsSamples.oneToOneOwner) === true); assert(dbh.hasConstraints(relationshipsSamples.tripleOneToOneOwner) === true); }); it('returns true if it is owner in at least one relation', function () { assert(dbh.hasConstraints(relationshipsSamples.mixedConstraints) === true); assert(dbh.hasConstraints(relationshipsSamples.mixedWithOneConstraint) === true); assert(dbh.hasConstraints(relationshipsSamples.mixedWithTwoConstraints) === true); }); }); describe('isNotEmptyString', function () { it('works with true strings', function () { assert(dbh.isNotEmptyString('x') === true); assert(dbh.isNotEmptyString(' ') === true); assert(dbh.isNotEmptyString('\r') === true); }); it('fails with wrong input', function () { assert(dbh.isNotEmptyString('') === false); assert(dbh.isNotEmptyString(() => 'foo') === false); }); }); describe('isValidBuildTool', function () { it('works as expected', function () { assert(dbh.isValidBuildTool('maven') === true); assert(dbh.isValidBuildTool('gradle') === true); assert(dbh.isValidBuildTool('Maven') === false); assert(dbh.isValidBuildTool('Gradle') === false); assert(dbh.isValidBuildTool('foo') === false); assert(dbh.isValidBuildTool() === false); }); }); describe('validateColumnName', function () { // messages output by validateColumnName // TODO: 0% maintainability, find something smarter const failMsgWhenSpecialChar = 'Your column name cannot contain special characters'; const failMsgWhenEmpty = 'Your column name cannot be empty'; const failMsgWhenTooLongForOracle = 'Your column name is too long for Oracle, try a shorter name'; it('works as expected', function () { assert(dbh.validateColumnName('Book', 'mysql') === true); assert(dbh.validateColumnName('FOO', 'mysql') === true); assert(dbh.validateColumnName('bar', 'mysql') === true); assert(dbh.validateColumnName('_foo2', 'mysql') === true); assert(dbh.validateColumnName('2Foo2Bar', 'mysql') === true); assert(dbh.validateColumnName('06', 'mysql') === true); assert(dbh.validateColumnName('_', 'mysql') === true); assert(dbh.validateColumnName('quiteLongTableName', 'mysql') === true); assert(dbh.validateColumnName('definitelyVeryLongTableName', 'mysql') === true); }); it(`returns '${failMsgWhenSpecialChar}'`, function () { assert(dbh.validateColumnName(' ', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('\r', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('\t', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('Böök', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateColumnName('book-table', 'mysql') === failMsgWhenSpecialChar); }); it(`returns '${failMsgWhenEmpty}'`, function () { assert(dbh.validateColumnName('', 'mysql') === failMsgWhenEmpty); }); it(`returns '${failMsgWhenTooLongForOracle}'`, function () { assert(dbh.validateColumnName('definitelyVeryLongTableName', 'oracle') === failMsgWhenTooLongForOracle); }); }); describe('validateTableName', function () { // messages output by validateTableName // TODO: 0% maintainability, find something smarter const failMsgWhenSpecialChar = 'The table name cannot contain special characters'; const failMsgWhenEmpty = 'The table name cannot be empty'; const failMsgWhenTooLongForOracle = 'The table name is too long for Oracle, try a shorter name'; const failMsgWhenLongForOracle = 'The table name is long for Oracle, long table names can cause issues when used to create constraint names and join table names'; it('works as expected', function () { assert(dbh.validateTableName('Book', 'mysql') === true); assert(dbh.validateTableName('FOO', 'mysql') === true); assert(dbh.validateTableName('bar', 'mysql') === true); assert(dbh.validateTableName('_foo2', 'mysql') === true); assert(dbh.validateTableName('2Foo2Bar', 'mysql') === true); assert(dbh.validateTableName('06', 'mysql') === true); assert(dbh.validateTableName('_', 'mysql') === true); assert(dbh.validateTableName('quiteLongTableName', 'mysql') === true); assert(dbh.validateTableName('definitelyVeryLongTableName', 'mysql') === true); }); it('fails with missing parameter', function () { assert.throws(() => dbh.validateTableName('Book'), Error); }); it(`returns '${failMsgWhenSpecialChar}'`, function () { assert(dbh.validateTableName('Böök', 'mysql') === failMsgWhenSpecialChar); assert(dbh.validateTableName('book-table', 'mysql') === failMsgWhenSpecialChar); }); it(`returns '${failMsgWhenEmpty}'`, function () { assert(dbh.validateTableName('', 'mysql') === failMsgWhenEmpty); }); it(`returns '${failMsgWhenTooLongForOracle}'`, function () { assert(dbh.validateTableName('definitelyVeryLongTableName', 'oracle') === failMsgWhenTooLongForOracle); }); it(`returns '${failMsgWhenLongForOracle}'`, function () { assert(dbh.validateTableName('quiteLongTableName', 'oracle') === failMsgWhenLongForOracle); }); }); /* describe('', function () { it('', function () { }); }); */ });
add test for reserver keywords with table names
test/test-dbh.js
add test for reserver keywords with table names
<ide><path>est/test-dbh.js <ide> const failMsgWhenEmpty = 'Your column name cannot be empty'; <ide> const failMsgWhenTooLongForOracle = 'Your column name is too long for Oracle, try a shorter name'; <ide> <del> it('works as expected', function () { <add> it('valid column names return true', function () { <ide> assert(dbh.validateColumnName('Book', 'mysql') === true); <ide> assert(dbh.validateColumnName('FOO', 'mysql') === true); <ide> assert(dbh.validateColumnName('bar', 'mysql') === true); <ide> const failMsgWhenTooLongForOracle = 'The table name is too long for Oracle, try a shorter name'; <ide> const failMsgWhenLongForOracle = 'The table name is long for Oracle, long table names can cause issues when used to create constraint names and join table names'; <ide> <del> it('works as expected', function () { <del> assert(dbh.validateTableName('Book', 'mysql') === true); <add> it('valid table names return true', function () { <add> assert(dbh.validateTableName('Book', 'mysql')); <ide> assert(dbh.validateTableName('FOO', 'mysql') === true); <ide> assert(dbh.validateTableName('bar', 'mysql') === true); <ide> assert(dbh.validateTableName('_foo2', 'mysql') === true); <ide> assert(dbh.validateTableName('quiteLongTableName', 'mysql') === true); <ide> assert(dbh.validateTableName('definitelyVeryLongTableName', 'mysql') === true); <ide> }); <add> it('returns the correct error message with a name containing a reserved keyword', function () { <add> assert.textEqual(dbh.validateTableName('ASENSITIVE', 'mysql').toString(), '\'ASENSITIVE\' is a mysql reserved keyword.'); <add> }); <ide> it('fails with missing parameter', function () { <ide> assert.throws(() => dbh.validateTableName('Book'), Error); <ide> });
Java
mit
88081056b3b5e4a9d70200cf0e19fd89490f1a26
0
CS2103AUG2016-W15-C3/main
package seedu.taskell.ui; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import seedu.taskell.model.task.ReadOnlyTask; import seedu.taskell.model.task.Task; public class TaskCard extends UiPart{ private static final String FXML = "TaskListCard.fxml"; private static final String WHITESPACE = " "; @FXML private HBox cardPane; @FXML private Label description; @FXML private Label taskType; @FXML private Label id; @FXML private Label taskDate; @FXML private Label taskPriority; @FXML private Label startTime; @FXML private Label endTime; @FXML private Label tags; private ReadOnlyTask task; private int displayedIndex; public TaskCard(){ } public static TaskCard load(ReadOnlyTask task, int displayedIndex){ TaskCard card = new TaskCard(); card.task = task; card.displayedIndex = displayedIndex; return UiPartLoader.loadUiPart(card); } @FXML public void initialize() { taskType.setText(WHITESPACE); id.setText(displayedIndex + ". "); description.setText(task.getDescription().description); taskPriority.setText(WHITESPACE); tags.setText(task.tagsString()); if (task.getTaskType().equals(Task.FLOATING_TASK)) { taskDate.setText(WHITESPACE); startTime.setText(WHITESPACE); endTime.setText(WHITESPACE); } else if (task.getTaskType().equals(Task.DEADLINE_TASK)) { taskDate.setText(task.getTaskDate().taskDate); startTime.setText(task.getEndTime().taskTime); //To accustomed to display format on UI endTime.setText(WHITESPACE); } else { taskDate.setText(task.getTaskDate().taskDate); startTime.setText(task.getStartTime().taskTime); endTime.setText(task.getEndTime().taskTime); } } public HBox getLayout() { return cardPane; } @Override public void setNode(Node node) { cardPane = (HBox)node; } @Override public String getFxmlPath() { return FXML; } }
src/main/java/seedu/taskell/ui/TaskCard.java
package seedu.taskell.ui; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import seedu.taskell.model.task.ReadOnlyTask; import seedu.taskell.model.task.Task; public class TaskCard extends UiPart{ private static final String FXML = "TaskListCard.fxml"; private static final String WHITESPACE = " "; @FXML private HBox cardPane; @FXML private Label description; @FXML private Label taskType; @FXML private Label id; @FXML private Label taskDate; @FXML private Label taskPriority; @FXML private Label startTime; @FXML private Label endTime; @FXML private Label tags; private ReadOnlyTask task; private int displayedIndex; public TaskCard(){ } public static TaskCard load(ReadOnlyTask task, int displayedIndex){ TaskCard card = new TaskCard(); card.task = task; card.displayedIndex = displayedIndex; return UiPartLoader.loadUiPart(card); } @FXML public void initialize() { taskType.setText(WHITESPACE); id.setText(displayedIndex + ". "); description.setText(task.getDescription().description); taskPriority.setText(task.getTaskPriority().taskPriority); tags.setText(task.tagsString()); if (task.getTaskType().equals(Task.FLOATING_TASK)) { tags.setText(task.tagsString()); } else if (task.getTaskType().equals(Task.DEADLINE_TASK)) { taskDate.setText(task.getTaskDate().taskDate); endTime.setText(task.getEndTime().taskTime); } else { taskDate.setText(task.getTaskDate().taskDate); startTime.setText(task.getStartTime().taskTime); endTime.setText(task.getEndTime().taskTime); } } public HBox getLayout() { return cardPane; } @Override public void setNode(Node node) { cardPane = (HBox)node; } @Override public String getFxmlPath() { return FXML; } }
Update UI display to display according to task types
src/main/java/seedu/taskell/ui/TaskCard.java
Update UI display to display according to task types
<ide><path>rc/main/java/seedu/taskell/ui/TaskCard.java <ide> taskType.setText(WHITESPACE); <ide> id.setText(displayedIndex + ". "); <ide> description.setText(task.getDescription().description); <del> taskPriority.setText(task.getTaskPriority().taskPriority); <add> taskPriority.setText(WHITESPACE); <ide> tags.setText(task.tagsString()); <ide> <ide> if (task.getTaskType().equals(Task.FLOATING_TASK)) { <del> tags.setText(task.tagsString()); <add> taskDate.setText(WHITESPACE); <add> startTime.setText(WHITESPACE); <add> endTime.setText(WHITESPACE); <ide> } else if (task.getTaskType().equals(Task.DEADLINE_TASK)) { <ide> taskDate.setText(task.getTaskDate().taskDate); <del> endTime.setText(task.getEndTime().taskTime); <add> startTime.setText(task.getEndTime().taskTime); //To accustomed to display format on UI <add> endTime.setText(WHITESPACE); <ide> } else { <ide> taskDate.setText(task.getTaskDate().taskDate); <ide> startTime.setText(task.getStartTime().taskTime);
Java
mit
f0bbd114bbeaaea37a2e35ddebb88658a34187c9
0
Ramotion/cardslider-android
package com.ramotion.cardslider.example.simple; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.support.annotation.StyleRes; import android.support.v4.view.ViewCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewTreeObserver; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; import com.ramotion.cardslider.CardSliderLayoutManager; import com.ramotion.cardslider.CardSnapHelper; import java.util.Random; public class MainActivity extends AppCompatActivity { private final int[][] dotCoords = new int[5][2]; private final int[] pics = {R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4, R.drawable.p5}; private final int[] maps = {R.drawable.map_1, R.drawable.map_2, R.drawable.map_3}; private final int[] descriptions = {R.string.text1, R.string.text2, R.string.text3, R.string.text4, R.string.text5}; private final String[] countries = {"FRANCE", "KOREA", "ENGLAND", "CHINA", "GREECE"}; private final String[] places = {"The Louvre", "Gwanghwamun", "Tower Bridge", "Temple of Heaven", "Aegeana Sea"}; private final String[] temperatures = {"8~21°C", "6~19°C", "5~17°C"}; private final String[] times = {"4.11~11.15 7:00~18:00", "3.15~9.15 8:00~16:00", "8.1~12.15 7:00~18:00"}; private final SliderAdapter sliderAdapter = new SliderAdapter(pics, 20, new OnCardClickListener()); private CardSliderLayoutManager layoutManger; private RecyclerView recyclerView; private ImageSwitcher mapSwitcher; private TextSwitcher temperatureSwitcher; private TextSwitcher placeSwitcher; private TextSwitcher clockSwitcher; private TextSwitcher descriptionsSwitcher; private View greenDot; private TextView country1TextView; private TextView country2TextView; private int countryOffset1; private int countryOffset2; private long countryAnimDuration; private int currentPosition; private DecodeBitmapTask decodeMapBitmapTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); initCountryText(); initSwitchers(); initGreenDot(); } private void initRecyclerView() { recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setAdapter(sliderAdapter); recyclerView.setHasFixedSize(true); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { onActiveCardChange(); } } }); layoutManger = (CardSliderLayoutManager) recyclerView.getLayoutManager(); new CardSnapHelper().attachToRecyclerView(recyclerView); } @Override protected void onDestroy() { super.onDestroy(); if (decodeMapBitmapTask != null) { decodeMapBitmapTask.cancel(true); } } private void initSwitchers() { temperatureSwitcher = (TextSwitcher) findViewById(R.id.ts_temperature); temperatureSwitcher.setFactory(new TextViewFactory(R.style.TemperatureTextView, true)); temperatureSwitcher.setCurrentText(temperatures[0]); placeSwitcher = (TextSwitcher) findViewById(R.id.ts_place); placeSwitcher.setFactory(new TextViewFactory(R.style.PlaceTextView, false)); placeSwitcher.setCurrentText(places[0]); clockSwitcher = (TextSwitcher) findViewById(R.id.ts_clock); clockSwitcher.setFactory(new TextViewFactory(R.style.ClockTextView, false)); clockSwitcher.setCurrentText(times[0]); descriptionsSwitcher = (TextSwitcher) findViewById(R.id.ts_description); descriptionsSwitcher.setInAnimation(this, android.R.anim.fade_in); descriptionsSwitcher.setOutAnimation(this, android.R.anim.fade_out); descriptionsSwitcher.setFactory(new TextViewFactory(R.style.DescriptionTextView, false)); descriptionsSwitcher.setCurrentText(getString(descriptions[0])); mapSwitcher = (ImageSwitcher) findViewById(R.id.ts_map); mapSwitcher.setInAnimation(this, android.R.anim.fade_in); mapSwitcher.setOutAnimation(this, android.R.anim.fade_out); mapSwitcher.setFactory(new ImageViewFactory()); mapSwitcher.setImageResource(maps[0]); } private void initCountryText() { countryAnimDuration = getResources().getInteger(R.integer.labels_animation_duration); countryOffset1 = getResources().getDimensionPixelSize(R.dimen.left_offset); countryOffset2 = getResources().getDimensionPixelSize(R.dimen.card_width); country1TextView = (TextView) findViewById(R.id.tv_country_1); country2TextView = (TextView) findViewById(R.id.tv_country_2); country1TextView.setX(countryOffset1); country2TextView.setX(countryOffset2); country1TextView.setText(countries[0]); country2TextView.setAlpha(0f); country1TextView.setTypeface(Typeface.createFromAsset(getAssets(), "open-sans-extrabold.ttf")); country2TextView.setTypeface(Typeface.createFromAsset(getAssets(), "open-sans-extrabold.ttf")); } private void initGreenDot() { mapSwitcher.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mapSwitcher.getViewTreeObserver().removeOnGlobalLayoutListener(this); final int viewLeft = mapSwitcher.getLeft(); final int viewTop = mapSwitcher.getTop() + mapSwitcher.getHeight() / 3; final int border = 100; final int xRange = mapSwitcher.getWidth() - border * 2; final int yRange = (mapSwitcher.getHeight() / 3) * 2 - border * 2; final Random rnd = new Random(); for (int i = 0, cnt = dotCoords.length; i < cnt; i++) { dotCoords[i][0] = viewLeft + border + rnd.nextInt(xRange); dotCoords[i][1] = viewTop + border + rnd.nextInt(yRange); } greenDot = findViewById(R.id.green_dot); greenDot.setX(dotCoords[0][0]); greenDot.setY(dotCoords[0][1]); } }); } private void setCountryText(String text, boolean left2right) { final TextView invisibleText; final TextView visibleText; if (country1TextView.getAlpha() > country2TextView.getAlpha()) { visibleText = country1TextView; invisibleText = country2TextView; } else { visibleText = country2TextView; invisibleText = country1TextView; } final int vOffset; if (left2right) { invisibleText.setX(0); vOffset = countryOffset2; } else { invisibleText.setX(countryOffset2); vOffset = 0; } invisibleText.setText(text); final ObjectAnimator iAlpha = ObjectAnimator.ofFloat(invisibleText, "alpha", 1f); final ObjectAnimator vAlpha = ObjectAnimator.ofFloat(visibleText, "alpha", 0f); final ObjectAnimator iX = ObjectAnimator.ofFloat(invisibleText, "x", countryOffset1); final ObjectAnimator vX = ObjectAnimator.ofFloat(visibleText, "x", vOffset); final AnimatorSet animSet = new AnimatorSet(); animSet.playTogether(iAlpha, vAlpha, iX, vX); animSet.setDuration(countryAnimDuration); animSet.start(); } private void onActiveCardChange() { final int pos = layoutManger.getActiveCardPosition(); if (pos == RecyclerView.NO_POSITION || pos == currentPosition) { return; } onActiveCardChange(pos); } private void onActiveCardChange(int pos) { int animH[] = new int[] {R.anim.slide_in_right, R.anim.slide_out_left}; int animV[] = new int[] {R.anim.slide_in_top, R.anim.slide_out_bottom}; final boolean left2right = pos < currentPosition; if (left2right) { animH[0] = R.anim.slide_in_left; animH[1] = R.anim.slide_out_right; animV[0] = R.anim.slide_in_bottom; animV[1] = R.anim.slide_out_top; } setCountryText(countries[pos % countries.length], left2right); temperatureSwitcher.setInAnimation(MainActivity.this, animH[0]); temperatureSwitcher.setOutAnimation(MainActivity.this, animH[1]); temperatureSwitcher.setText(temperatures[pos % temperatures.length]); placeSwitcher.setInAnimation(MainActivity.this, animV[0]); placeSwitcher.setOutAnimation(MainActivity.this, animV[1]); placeSwitcher.setText(places[pos % places.length]); clockSwitcher.setInAnimation(MainActivity.this, animV[0]); clockSwitcher.setOutAnimation(MainActivity.this, animV[1]); clockSwitcher.setText(times[pos % times.length]); descriptionsSwitcher.setText(getString(descriptions[pos % descriptions.length])); showMap(maps[pos % maps.length]); ViewCompat.animate(greenDot) .translationX(dotCoords[pos % dotCoords.length][0]) .translationY(dotCoords[pos % dotCoords.length][1]) .start(); currentPosition = pos; } private void showMap(@DrawableRes int resId) { if (decodeMapBitmapTask != null) { decodeMapBitmapTask.cancel(true); } decodeMapBitmapTask = new DecodeBitmapTask(getResources(), resId, mapSwitcher.getWidth(), mapSwitcher.getHeight()) { @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); ((ImageView)mapSwitcher.getNextView()).setImageBitmap(bitmap); mapSwitcher.showNext(); } }; decodeMapBitmapTask.execute(); } private class TextViewFactory implements ViewSwitcher.ViewFactory { @StyleRes final int styleId; final boolean center; TextViewFactory(@StyleRes int styleId, boolean center) { this.styleId = styleId; this.center = center; } @SuppressWarnings("deprecation") @Override public View makeView() { final TextView textView = new TextView(MainActivity.this); if (center) { textView.setGravity(Gravity.CENTER); } if (Build.VERSION.SDK_INT < 23) { textView.setTextAppearance(MainActivity.this, styleId); } else { textView.setTextAppearance(styleId); } return textView; } } private class ImageViewFactory implements ViewSwitcher.ViewFactory { @Override public View makeView() { final ImageView imageView = new ImageView(MainActivity.this); imageView.setScaleType(ImageView.ScaleType.FIT_XY); return imageView; } } private class OnCardClickListener implements View.OnClickListener { @Override public void onClick(View view) { final CardSliderLayoutManager lm = (CardSliderLayoutManager) recyclerView.getLayoutManager(); if (lm.isSmoothScrolling()) { return; } final int activeCardPosition = lm.getActiveCardPosition(); if (activeCardPosition == RecyclerView.NO_POSITION) { return; } final int clickedPosition = recyclerView.getChildAdapterPosition(view); if (clickedPosition == activeCardPosition) { final Intent intent = new Intent(MainActivity.this, DetailsActivity.class); intent.putExtra(DetailsActivity.BUNDLE_IMAGE_ID, pics[activeCardPosition % pics.length]); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { startActivity(intent); } else { final CardView cardView = (CardView) view; final View sharedView = cardView.getChildAt(cardView.getChildCount() - 1); final ActivityOptions options = ActivityOptions .makeSceneTransitionAnimation(MainActivity.this, sharedView, "shared"); startActivity(intent, options.toBundle()); } } else if (clickedPosition > activeCardPosition) { recyclerView.smoothScrollToPosition(clickedPosition); onActiveCardChange(clickedPosition); } } } }
card-slider-simple-example/src/main/java/com/ramotion/cardslider/example/simple/MainActivity.java
package com.ramotion.cardslider.example.simple; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.annotation.StyleRes; import android.support.v4.view.ViewCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewTreeObserver; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; import com.ramotion.cardslider.CardSliderLayoutManager; import com.ramotion.cardslider.CardSnapHelper; import java.util.Random; public class MainActivity extends AppCompatActivity { private final int[][] dotCoords = new int[5][2]; private final int[] pics = {R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4, R.drawable.p5}; private final int[] maps = {R.drawable.map_1, R.drawable.map_2, R.drawable.map_3}; private final int[] descriptions = {R.string.text1, R.string.text2, R.string.text3, R.string.text4, R.string.text5}; private final String[] countries = {"FRANCE", "KOREA", "ENGLAND", "CHINA", "GREECE"}; private final String[] places = {"The Louvre", "Gwanghwamun", "Tower Bridge", "Temple of Heaven", "Aegeana Sea"}; private final String[] temperatures = {"8~21°C", "6~19°C", "5~17°C"}; private final String[] times = {"4.11~11.15 7:00~18:00", "3.15~9.15 8:00~16:00", "8.1~12.15 7:00~18:00"}; private final SliderAdapter sliderAdapter = new SliderAdapter(pics, 20, new OnCardClickListener()); private CardSliderLayoutManager layoutManger; private RecyclerView recyclerView; private ImageSwitcher mapSwitcher; private TextSwitcher temperatureSwitcher; private TextSwitcher placeSwitcher; private TextSwitcher clockSwitcher; private TextSwitcher descriptionsSwitcher; private View greenDot; private TextView country1TextView; private TextView country2TextView; private int countryOffset1; private int countryOffset2; private long countryAnimDuration; private int currentPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); initCountryText(); initSwitchers(); initGreenDot(); } private void initRecyclerView() { recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setAdapter(sliderAdapter); recyclerView.setHasFixedSize(true); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { onActiveCardChange(); } } }); layoutManger = (CardSliderLayoutManager) recyclerView.getLayoutManager(); new CardSnapHelper().attachToRecyclerView(recyclerView); } private void initSwitchers() { temperatureSwitcher = (TextSwitcher) findViewById(R.id.ts_temperature); temperatureSwitcher.setFactory(new TextViewFactory(R.style.TemperatureTextView, true)); temperatureSwitcher.setCurrentText(temperatures[0]); placeSwitcher = (TextSwitcher) findViewById(R.id.ts_place); placeSwitcher.setFactory(new TextViewFactory(R.style.PlaceTextView, false)); placeSwitcher.setCurrentText(places[0]); clockSwitcher = (TextSwitcher) findViewById(R.id.ts_clock); clockSwitcher.setFactory(new TextViewFactory(R.style.ClockTextView, false)); clockSwitcher.setCurrentText(times[0]); descriptionsSwitcher = (TextSwitcher) findViewById(R.id.ts_description); descriptionsSwitcher.setInAnimation(this, android.R.anim.fade_in); descriptionsSwitcher.setOutAnimation(this, android.R.anim.fade_out); descriptionsSwitcher.setFactory(new TextViewFactory(R.style.DescriptionTextView, false)); descriptionsSwitcher.setCurrentText(getString(descriptions[0])); mapSwitcher = (ImageSwitcher) findViewById(R.id.ts_map); mapSwitcher.setInAnimation(this, android.R.anim.fade_in); mapSwitcher.setOutAnimation(this, android.R.anim.fade_out); mapSwitcher.setFactory(new ImageViewFactory()); mapSwitcher.setImageResource(maps[0]); } private void initCountryText() { countryAnimDuration = getResources().getInteger(R.integer.labels_animation_duration); countryOffset1 = getResources().getDimensionPixelSize(R.dimen.left_offset); countryOffset2 = getResources().getDimensionPixelSize(R.dimen.card_width); country1TextView = (TextView) findViewById(R.id.tv_country_1); country2TextView = (TextView) findViewById(R.id.tv_country_2); country1TextView.setX(countryOffset1); country2TextView.setX(countryOffset2); country1TextView.setText(countries[0]); country2TextView.setAlpha(0f); country1TextView.setTypeface(Typeface.createFromAsset(getAssets(), "open-sans-extrabold.ttf")); country2TextView.setTypeface(Typeface.createFromAsset(getAssets(), "open-sans-extrabold.ttf")); } private void initGreenDot() { mapSwitcher.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mapSwitcher.getViewTreeObserver().removeOnGlobalLayoutListener(this); final int viewLeft = mapSwitcher.getLeft(); final int viewTop = mapSwitcher.getTop() + mapSwitcher.getHeight() / 3; final int border = 100; final int xRange = mapSwitcher.getWidth() - border * 2; final int yRange = (mapSwitcher.getHeight() / 3) * 2 - border * 2; final Random rnd = new Random(); for (int i = 0, cnt = dotCoords.length; i < cnt; i++) { dotCoords[i][0] = viewLeft + border + rnd.nextInt(xRange); dotCoords[i][1] = viewTop + border + rnd.nextInt(yRange); } greenDot = findViewById(R.id.green_dot); greenDot.setX(dotCoords[0][0]); greenDot.setY(dotCoords[0][1]); } }); } private void setCountryText(String text, boolean left2right) { final TextView invisibleText; final TextView visibleText; if (country1TextView.getAlpha() > country2TextView.getAlpha()) { visibleText = country1TextView; invisibleText = country2TextView; } else { visibleText = country2TextView; invisibleText = country1TextView; } final int vOffset; if (left2right) { invisibleText.setX(0); vOffset = countryOffset2; } else { invisibleText.setX(countryOffset2); vOffset = 0; } invisibleText.setText(text); final ObjectAnimator iAlpha = ObjectAnimator.ofFloat(invisibleText, "alpha", 1f); final ObjectAnimator vAlpha = ObjectAnimator.ofFloat(visibleText, "alpha", 0f); final ObjectAnimator iX = ObjectAnimator.ofFloat(invisibleText, "x", countryOffset1); final ObjectAnimator vX = ObjectAnimator.ofFloat(visibleText, "x", vOffset); final AnimatorSet animSet = new AnimatorSet(); animSet.playTogether(iAlpha, vAlpha, iX, vX); animSet.setDuration(countryAnimDuration); animSet.start(); } private void onActiveCardChange() { final int pos = layoutManger.getActiveCardPosition(); if (pos == RecyclerView.NO_POSITION || pos == currentPosition) { return; } onActiveCardChange(pos); } private void onActiveCardChange(int pos) { int animH[] = new int[] {R.anim.slide_in_right, R.anim.slide_out_left}; int animV[] = new int[] {R.anim.slide_in_top, R.anim.slide_out_bottom}; final boolean left2right = pos < currentPosition; if (left2right) { animH[0] = R.anim.slide_in_left; animH[1] = R.anim.slide_out_right; animV[0] = R.anim.slide_in_bottom; animV[1] = R.anim.slide_out_top; } setCountryText(countries[pos % countries.length], left2right); temperatureSwitcher.setInAnimation(MainActivity.this, animH[0]); temperatureSwitcher.setOutAnimation(MainActivity.this, animH[1]); temperatureSwitcher.setText(temperatures[pos % temperatures.length]); placeSwitcher.setInAnimation(MainActivity.this, animV[0]); placeSwitcher.setOutAnimation(MainActivity.this, animV[1]); placeSwitcher.setText(places[pos % places.length]); clockSwitcher.setInAnimation(MainActivity.this, animV[0]); clockSwitcher.setOutAnimation(MainActivity.this, animV[1]); clockSwitcher.setText(times[pos % times.length]); descriptionsSwitcher.setText(getString(descriptions[pos % descriptions.length])); mapSwitcher.setImageResource(maps[pos % maps.length]); ViewCompat.animate(greenDot) .translationX(dotCoords[pos % dotCoords.length][0]) .translationY(dotCoords[pos % dotCoords.length][1]) .start(); currentPosition = pos; } private class TextViewFactory implements ViewSwitcher.ViewFactory { @StyleRes final int styleId; final boolean center; TextViewFactory(@StyleRes int styleId, boolean center) { this.styleId = styleId; this.center = center; } @SuppressWarnings("deprecation") @Override public View makeView() { final TextView textView = new TextView(MainActivity.this); if (center) { textView.setGravity(Gravity.CENTER); } if (Build.VERSION.SDK_INT < 23) { textView.setTextAppearance(MainActivity.this, styleId); } else { textView.setTextAppearance(styleId); } return textView; } } private class ImageViewFactory implements ViewSwitcher.ViewFactory { @Override public View makeView() { final ImageView imageView = new ImageView(MainActivity.this); imageView.setScaleType(ImageView.ScaleType.FIT_XY); return imageView; } } private class OnCardClickListener implements View.OnClickListener { @Override public void onClick(View view) { final CardSliderLayoutManager lm = (CardSliderLayoutManager) recyclerView.getLayoutManager(); if (lm.isSmoothScrolling()) { return; } final int activeCardPosition = lm.getActiveCardPosition(); if (activeCardPosition == RecyclerView.NO_POSITION) { return; } final int clickedPosition = recyclerView.getChildAdapterPosition(view); if (clickedPosition == activeCardPosition) { final Intent intent = new Intent(MainActivity.this, DetailsActivity.class); intent.putExtra(DetailsActivity.BUNDLE_IMAGE_ID, pics[activeCardPosition % pics.length]); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { startActivity(intent); } else { final CardView cardView = (CardView) view; final View sharedView = cardView.getChildAt(cardView.getChildCount() - 1); final ActivityOptions options = ActivityOptions .makeSceneTransitionAnimation(MainActivity.this, sharedView, "shared"); startActivity(intent, options.toBundle()); } } else if (clickedPosition > activeCardPosition) { recyclerView.smoothScrollToPosition(clickedPosition); onActiveCardChange(clickedPosition); } } } }
Load map bitmap from cache in example
card-slider-simple-example/src/main/java/com/ramotion/cardslider/example/simple/MainActivity.java
Load map bitmap from cache in example
<ide><path>ard-slider-simple-example/src/main/java/com/ramotion/cardslider/example/simple/MainActivity.java <ide> import android.animation.ObjectAnimator; <ide> import android.app.ActivityOptions; <ide> import android.content.Intent; <add>import android.graphics.Bitmap; <ide> import android.graphics.Typeface; <ide> import android.os.Build; <ide> import android.os.Bundle; <add>import android.support.annotation.DrawableRes; <add>import android.support.annotation.IdRes; <ide> import android.support.annotation.StyleRes; <ide> import android.support.v4.view.ViewCompat; <ide> import android.support.v7.app.AppCompatActivity; <ide> private long countryAnimDuration; <ide> private int currentPosition; <ide> <add> private DecodeBitmapTask decodeMapBitmapTask; <add> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <ide> layoutManger = (CardSliderLayoutManager) recyclerView.getLayoutManager(); <ide> <ide> new CardSnapHelper().attachToRecyclerView(recyclerView); <add> } <add> <add> @Override <add> protected void onDestroy() { <add> super.onDestroy(); <add> if (decodeMapBitmapTask != null) { <add> decodeMapBitmapTask.cancel(true); <add> } <ide> } <ide> <ide> private void initSwitchers() { <ide> <ide> descriptionsSwitcher.setText(getString(descriptions[pos % descriptions.length])); <ide> <del> mapSwitcher.setImageResource(maps[pos % maps.length]); <add> showMap(maps[pos % maps.length]); <ide> <ide> ViewCompat.animate(greenDot) <ide> .translationX(dotCoords[pos % dotCoords.length][0]) <ide> .start(); <ide> <ide> currentPosition = pos; <add> } <add> <add> private void showMap(@DrawableRes int resId) { <add> if (decodeMapBitmapTask != null) { <add> decodeMapBitmapTask.cancel(true); <add> } <add> <add> decodeMapBitmapTask = new DecodeBitmapTask(getResources(), resId, mapSwitcher.getWidth(), mapSwitcher.getHeight()) { <add> @Override <add> protected void onPostExecute(Bitmap bitmap) { <add> super.onPostExecute(bitmap); <add> ((ImageView)mapSwitcher.getNextView()).setImageBitmap(bitmap); <add> mapSwitcher.showNext(); <add> } <add> }; <add> <add> decodeMapBitmapTask.execute(); <ide> } <ide> <ide> private class TextViewFactory implements ViewSwitcher.ViewFactory {
JavaScript
mit
b5fbe909226b155900de0df09b34168c4eeed5c0
0
hull/hull-js,hull/hull-js,hull/hull-js
/** * ## Flags review * * Allows an administrator to review all the flags on objects considered as inappropriate * * ### Example * * <div data-hull-widget="admin/flags@hull"></div> * * * ### Template: * * - `main`: Displays the flags' review table if the user is an admin * * ### Datasource: * * - `flags`: The list of flags for the current app * * ### Action: * * - `markReviewed`: Marks a flag as reviewed */ Hull.define({ type: "Hull", templates: ['main'], refreshEvents: ['model.hull.me.change'], datasources: { 'flags': 'flags/' }, onFlagsError: function (err) { return []; }, markReviewed: function () { "use strict"; var filter = this.sandbox.util._.filter; var dfd = this.sandbox.data.deferred(); var path = this.options.id + '/flags'; var myId = this.api.model('me').get('id'); this.api(path).then(function (flags) { var myFlags = filter(flags, function (flag) { return flag.reporter_id === myId; }); dfd.resolve(myFlags.length > 0); }); return dfd; }, actions: { delete: function (evt, ctx) { var self = this; this.api.delete(ctx.data.id).then(function () { self.render(); }); }, unflag: function (evt, ctx) { var self = this; this.api.delete(ctx.data.id + '/flag?all=1').then(function () { self.render(); }); } } });
widgets/admin/flags/main.js
/** * ## Flags review * * Allows an administrator to review all the flags on objects considered as inappropriate * * ### Example * * <div data-hull-widget="admin/flags@hull"></div> * * * ### Template: * * - `main`: Displays the flags' review table if the user is an admin * * ### Datasource: * * - `flags`: The list of flags for the current app * * ### Action: * * - `markReviewed`: Marks a flag as reviewed */ Hull.define({ type: "Hull", templates: ['main'], refreshEvents: ['model.hull.me.change'], datasources: { 'flags': 'flags/' }, onFlagsError: function (err) { return []; }, markReviewed: function () { "use strict"; var filter = this.sandbox.util._.filter; var dfd = this.sandbox.data.deferred(); var path = this.options.id + '/flags'; var myId = this.api.model('me').get('id'); this.api(path).then(function (flags) { var myFlags = filter(flags, function (flag) { return flag.reporter_id === myId; }); dfd.resolve(myFlags.length > 0); }); return dfd; }, beforeRender: function (data) { console.log(data); } });
Deletes and unflags objects
widgets/admin/flags/main.js
Deletes and unflags objects
<ide><path>idgets/admin/flags/main.js <ide> }); <ide> return dfd; <ide> }, <del> beforeRender: function (data) { <del> console.log(data); <add> actions: { <add> delete: function (evt, ctx) { <add> var self = this; <add> this.api.delete(ctx.data.id).then(function () { <add> self.render(); <add> }); <add> }, <add> unflag: function (evt, ctx) { <add> var self = this; <add> this.api.delete(ctx.data.id + '/flag?all=1').then(function () { <add> self.render(); <add> }); <add> } <ide> } <ide> }); <ide>
Java
mit
83fcd717aa062d8b8601b55c4d4db48a05e6e76d
0
LilaQin/mockito,mockito/mockito,GeeChao/mockito,TimvdLippe/mockito,windofthesky/mockito,stefanbirkner/mockito,terebesirobert/mockito,icefoggy/mockito,lukasz-szewc/mockito,lukasz-szewc/mockito,smarkwell/mockito,MuShiiii/mockito,MuShiiii/mockito,JeremybellEU/mockito,huangyingw/mockito,bric3/mockito,geoffschoeman/mockito,rototor/mockito,mohanaraosv/mockito,mbrukman/mockito,bric3/mockito,hansjoachim/mockito,smarkwell/mockito,icefoggy/mockito,alberskib/mockito,JeremybellEU/mockito,diboy2/mockito,hansjoachim/mockito,mbrukman/mockito,Jazzepi/mockito,Jazzepi/mockito,geoffschoeman/mockito,mkordas/mockito,ignaciotcrespo/mockito,Jam71/mockito,mockito/mockito,ignaciotcrespo/mockito,TimvdLippe/mockito,GeeChao/mockito,ze-pequeno/mockito,zorosteven/mockito,stefanbirkner/mockito,alberskib/mockito,diboy2/mockito,mkordas/mockito,zorosteven/mockito,ze-pequeno/mockito,bric3/mockito,mohanaraosv/mockito,rototor/mockito,Ariel-Isaacm/mockito,mockito/mockito,LilaQin/mockito,windofthesky/mockito,Ariel-Isaacm/mockito,Jam71/mockito
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import org.mockito.exceptions.base.MockitoException; /** * <ul> * <li>Allows shorthand mock creation.</li> * <li>Minimizes repetitive mock creation code.</li> * <li>Makes the test class more readable.</li> * </ul> * * <pre> * public class ArticleManagerTest extends SampleBaseTestCase { * * &#064;Mock private ArticleCalculator calculator; * &#064;Mock private ArticleDatabase database; * &#064;Mock private UserProvider userProvider; * * private ArticleManager manager; * * &#064;Before public void setup() { * manager = new ArticleManager(userProvider, database, calculator); * } * } * * public class SampleBaseTestCase { * * &#064;Before public void initMocks() { * MockitoAnnotations.initMocks(this); * } * } * </pre> * * <b><code>MockitoAnnotations.initMocks(this)</code></b> method has to called to initialize annotated mocks. * <p> * In above example, <code>initMocks()</code> is called in &#064;Before (JUnit4) method of test's base class. * You can also put it in your JUnit4 runner (&#064;RunWith). * For JUnit3 <code>initMocks()</code> can go to <code>setup()</code> method of a base class. */ public class MockitoAnnotations { /** * Allows shorthand mock creation, see examples in javadoc for {@link MockitoAnnotations}. */ @Target( { FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Mock {} /** * Initializes objects annotated with &#064;Mock for given testClass. * See examples in javadoc for {@link MockitoAnnotations}. */ public static void initMocks(Object testClass) { if (testClass == null) { throw new MockitoException("testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations"); } Class<?> clazz = testClass.getClass(); while (clazz != Object.class) { scan(testClass, clazz); clazz = clazz.getSuperclass(); } } private static void scan(Object testClass, Class<?> clazz) { Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(Mock.class)) { boolean wasAccessible = f.isAccessible(); f.setAccessible(true); try { f.set(testClass, Mockito.mock(f.getType())); } catch (IllegalAccessException e) { throw new MockitoException("Problems initiating mocks annotated with @Mock", e); } finally { f.setAccessible(wasAccessible); } } } } }
src/org/mockito/MockitoAnnotations.java
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import org.mockito.exceptions.base.MockitoException; /** * <ul> * <li>Allows shorthand mock creation.</li> * <li>Minimizes repetitive mock creation code.</li> * <li>Makes the test class more readable.</li> * </ul> * * <pre> * public class ArticleManagerTest extends SampleBaseTestCase { * * &#064;Mock private ArticleCalculator calculator; * &#064;Mock private ArticleDatabase database; * &#064;Mock private UserProvider userProvider; * * private ArticleManager manager; * * &#064;Before public void setup() { * manager = new ArticleManager(userProvider, database, calculator); * } * } * * public class SampleBaseTestCase { * * &#064;Before public void initMocks() { * MockitoAnnotations.initMocks(this); * } * } * </pre> * * <b><code>MockitoAnnotations.initMocks(this)</code></b> method has to called to initialize annotated mocks. * <p> * In above example, <code>initMocks()</code> is called in &#064;Before (JUnit4) method of test's base class. * You can also put it in your JUnit4 runner (&#064;RunWith). * For JUnit3 <code>initMocks()</code> can go to <code>setup()</code> method of a base class. */ public class MockitoAnnotations { /** * Allows shorthand mock creation, see examples in javadoc for {@link MockitoAnnotations}. */ @Target( { FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Mock {} /** * Initializes objects annotated with &#064;Mock for given testClass. * See examples in javadoc for {@link MockitoAnnotations}. */ public static void initMocks(Object testClass) { if (testClass == null) { throw new MockitoException("testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations"); } Class<?> clazz = testClass.getClass(); while (clazz != Object.class) { scan(testClass, clazz); clazz = clazz.getSuperclass(); } } private static void scan(Object testClass, Class<?> clazz) { Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(Mock.class)) { f.setAccessible(true); try { f.set(testClass, Mockito.mock(f.getType())); } catch (IllegalAccessException e) { throw new MockitoException("Problems initiating mocks annotated with @Mock", e); } } } } }
unsetted accessible flag on field --HG-- extra : convert_revision : svn%3Aaa2aecf3-ea3e-0410-9d70-716747e7c967/trunk%40388
src/org/mockito/MockitoAnnotations.java
unsetted accessible flag on field
<ide><path>rc/org/mockito/MockitoAnnotations.java <ide> Field[] fields = clazz.getDeclaredFields(); <ide> for (Field f : fields) { <ide> if (f.isAnnotationPresent(Mock.class)) { <add> boolean wasAccessible = f.isAccessible(); <ide> f.setAccessible(true); <ide> try { <ide> f.set(testClass, Mockito.mock(f.getType())); <ide> } catch (IllegalAccessException e) { <ide> throw new MockitoException("Problems initiating mocks annotated with @Mock", e); <add> } finally { <add> f.setAccessible(wasAccessible); <ide> } <ide> } <ide> }
JavaScript
apache-2.0
328bf66d7fb61021fa0b8fd93152a256d2a29b1d
0
ibm-cds-labs/nodejs-graph,ukmadlz/gds-wrapper,ibm-cds-labs/gds-wrapper
// Licensed under the Apache License, Version 2.0 (the 'License'); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. 'use strict'; // Necessary libs var request = require('request'); var assert = require('assert'); var _ = require('underscore'); // Global var gds; // Init module.exports = exports = gds = function init(config) { // Validate config assert.equal(typeof config, 'object', 'You must specify the endpoint url when invoking this module'); assert.ok(/^https?:/.test(config.url), 'url is not valid'); // Handle URL Requests function apiCall(opts, callback) { if (!opts) var opts = {} // Debug opts.debug = (config.debug) ? config.debug : ((!opts.debug) ? false : opts.debug); // Force the URL opts.url = config.url + opts.url; // Auth opts.auth = { user: config.username, pass: config.password } // Debug Opts if (opts.debug) console.log(opts); return request(opts, function(error, response, body) { var returnObject = { error: error, response: response, body: body }; if (opts.debug) console.log(returnObject); if (!callback) { return returnObject; } return callback(error, response, body) }) } /* Vertices */ // Create Vertice function createVertices(keyPairs, callback) { var opts = { url: '/vertices', method: 'POST' } return apiCall(opts, callback); } // List Vertices function listVertices(callback) { var opts = { url: '/vertices', method: 'GET' }; return apiCall(opts, callback); } // Vertex by ID function vertexById(id, callback) { var opts = { url: '/vertices/' + id, method: 'GET' } return apiCall(opts, callback); } // Vertex by properties function vertexByProperties(properties, callback) { var opts = { url: '/vertices', method: 'GET', qs: properties } return apiCall(opts, callback); } var vertices = { create: createVertices, list: listVertices, get: vertexById, properties: vertexByProperties }; /* Edges */ // List Edges function listEdges(callback) { var opts = { url: '/edges', method: 'GET', }; return apiCall(opts, callback); } var edges = { list: listEdges, }; /* Gremlin */ // Gremlin Endpoint function gremlinQuery(traversal, callback) { var opts = { url: '/gremlin', method: 'POST', // @TODO: reimplement later // json: true, body: '{"gremlin": ""}', headers: { 'Content-Type': 'application/json' } } // If traveral is string if (_.isArray(traversal)) { // Check first element is g if (traversal[0] != 'g') { traversal.unshift('g'); } opts.body = JSON.stringify({gremlin:traversal.join('.')}); } else { opts.body = JSON.stringify({gremlin:traversal}); } return apiCall(opts, callback); } var gremlin = gremlinQuery; /* Input/Output */ // Bulk Upload - GraphML function uploadGraphMl(graphml, callback) { if (typeof graphml != 'string' && !callback) var callback = graphml; var opts = { url: '/bulkload/graphml', method: 'POST', form: {graphml: graphml} } return apiCall(opts, callback); } // Buld Upload - graphson function uploadGraphSON(graphson, callback) { if (typeof graphson != 'string' && !callback) var callback = graphson; var opts = { url: '/bulkload/graphson', method: 'POST', form: {graphson: graphson} } return apiCall(opts, callback); } // Extract function extractBulk(format, callback) { if (!callback) var callback = format; if (!format) var format = 'json'; var opts = { url: '/extract', method: 'GET', headers: { 'Content-Type': 'application/' + format } } return apiCall(opts, callback); } var io = { bulkload: { graphml: uploadGraphMl, graphson: uploadGraphSON }, extract: extractBulk } // Return object return { vertices: vertices, edges: edges, gremlin: gremlin, io: io, } }
lib/gds.js
// Licensed under the Apache License, Version 2.0 (the 'License'); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. 'use strict'; // Necessary libs var request = require('request'); var assert = require('assert'); var _ = require('underscore'); // Global var gds; // Init module.exports = exports = gds = function init(config) { // Validate config assert.equal(typeof config, 'object', 'You must specify the endpoint url when invoking this module'); assert.ok(/^https?:/.test(config.url), 'url is not valid'); // Handle URL Requests function apiCall(opts, callback) { if (!opts) var opts = {} // Debug opts.debug = (config.debug) ? config.debug : ((!opts.debug) ? false : opts.debug); // Force the URL opts.url = config.url + opts.url; // Auth opts.auth = { user: config.username, pass: config.password } // Debug Opts if (opts.debug) console.log(opts); return request(opts, function(error, response, body) { var returnObject = { error: error, response: response, body: body }; if (opts.debug) console.log(returnObject); if (!callback) { return returnObject; } return callback(error, response, body) }) } /* Vertices */ // Create Vertice function createVertices(keyPairs, callback) { var opts = { url: '/vertices', method: 'POST' } return apiCall(opts, callback); } // List Vertices function listVertices(callback) { var opts = { url: '/vertices', method: 'GET' }; return apiCall(opts, callback); } // Vertex by ID function vertexById(id, callback) { var opts = { url: '/vertices/' + id, method: 'GET' } return apiCall(opts, callback); } // Vertex by properties function vertexByProperties(properties, callback) { var opts = { url: '/vertices', method: 'GET', qs: properties } return apiCall(opts, callback); } var vertices = { create: createVertices, list: listVertices, get: vertexById, properties: vertexByProperties }; /* Gremlin */ // Gremlin Endpoint function gremlinQuery(traversal, callback) { var opts = { url: '/gremlin', method: 'POST', // @TODO: reimplement later // json: true, body: '{"gremlin": ""}', headers: { 'Content-Type': 'application/json' } } // If traveral is string if (_.isArray(traversal)) { // Check first element is g if (traversal[0] != 'g') { traversal.unshift('g'); } opts.body = JSON.stringify({gremlin:traversal.join('.')}); } else { opts.body = JSON.stringify({gremlin:traversal}); } return apiCall(opts, callback); } var gremlin = gremlinQuery; /* Input/Output */ // Bulk Upload - GraphML function uploadGraphMl(graphml, callback) { if (typeof graphml != 'string' && !callback) var callback = graphml; var opts = { url: '/bulkload/graphml', method: 'POST', form: {graphml: graphml} } return apiCall(opts, callback); } // Buld Upload - graphson function uploadGraphSON(graphson, callback) { if (typeof graphson != 'string' && !callback) var callback = graphson; var opts = { url: '/bulkload/graphson', method: 'POST', form: {graphson: graphson} } return apiCall(opts, callback); } // Extract function extractBulk(format, callback) { if (!callback) var callback = format; if (!format) var format = 'json'; var opts = { url: '/extract', method: 'GET', headers: { 'Content-Type': 'application/' + format } } return apiCall(opts, callback); } var io = { bulkload: { graphml: uploadGraphMl, graphson: uploadGraphSON }, extract: extractBulk } // Return object return { vertices: vertices, gremlin: gremlin, io: io } }
List edges
lib/gds.js
List edges
<ide><path>ib/gds.js <ide> }; <ide> <ide> /* <del> Gremlin <add> Edges <ide> */ <add> <add> // List Edges <add> function listEdges(callback) { <add> var opts = { <add> url: '/edges', <add> method: 'GET', <add> }; <add> return apiCall(opts, callback); <add> } <add> <add> var edges = { <add> list: listEdges, <add> }; <add> <add> /* <add> Gremlin <add> */ <ide> <ide> // Gremlin Endpoint <ide> function gremlinQuery(traversal, callback) { <ide> // Return object <ide> return { <ide> vertices: vertices, <add> edges: edges, <ide> gremlin: gremlin, <del> io: io <add> io: io, <ide> } <ide> }
Java
mit
c1d3618aa14a3675807c4078aa89c69a23c23d82
0
raspacorp/maker
/** * Mar 14, 2014 File created by Ramiro.Serrato */ package org.maker_pattern; import java.io.IOException; import java.util.Properties; import org.maker_pattern.animals.Animal; import org.maker_pattern.animals.Cat; import org.maker_pattern.animals.CatFamily; import org.maker_pattern.animals.Dog; import org.maker_pattern.animals.DogFamily; import org.maker_pattern.plants.Ceiba; import org.maker_pattern.plants.Daisy; import org.maker_pattern.plants.Plant; /** * A very basic, light-weight, pragmatic programmatic alternative to DI frameworks * Maker Pattern versions: * 0.1 First version using an external class that included a Map storing the singleton instances and getInstance method, supporting * singleton and prototype beans * 0.2 Redesigned the pattern, now everything is in a single class (enum) and uses kind of factory methods for retrieving instances * This version is also capable of wiring beans inside the same enum and cross enum wiring too, allowing us to separate the beans * by domain or responsibility in different files and wire them if needed * 0.3 Added init, start, shutdown, clear and clearAll life cycle methods * 0.4 Added Properties parameter to getInstance method for supporting initialization properties * 0.5 Removed init method as it was not really useful * @author Ramiro.Serrato * */ public enum LivingBeingMaker { /*** Object configuration, definition, wiring ***/ // Pattern: NAME (isSingleton) { createInstance() { <object creation logic > } } SPARKY_DOG (true) { @Override public Dog createInstance(Properties properties) { Dog sparky = new Dog(); sparky.setName(properties.getProperty("sparky.name")); return sparky; } }, PINKY_DOG (true) { @Override public Dog createInstance(Properties properties) { Dog pinky = new Dog(); pinky.setName(properties.getProperty("pinky.name")); return pinky; } }, SPARKY_FAMILY (true) { // A wired object @Override public DogFamily createInstance(Properties properties) { DogFamily dogFamily = new DogFamily(); dogFamily.setParent1(getDog(SPARKY_DOG)); dogFamily.setParent2(getDog(PINKY_DOG)); return dogFamily; } }, SIAMESE (false) { @Override public Cat createInstance(Properties properties) { return new Cat(); } }, LABRADOR (false) { @Override public Dog createInstance(Properties properties) { return new Dog(); } }, DAISY (false) { @Override public Plant createInstance(Properties properties) { Daisy daisy = new Daisy(); daisy.setKind(properties.getProperty("daisy_kind")); return daisy; } }, CEIBA (false) { @Override public Plant createInstance(Properties properties) { Ceiba ceiba = new Ceiba(); ceiba.setAge(new Integer(properties.getProperty("ceiba_age"))); return ceiba; } }; /** Here define factory methods **/ public static Dog getDog(LivingBeingMaker livingBeingMaker) { return (Dog) livingBeingMaker.getInstance(generalProperties); } public static Cat getCat(LivingBeingMaker livingBeingMaker) { return (Cat) livingBeingMaker.getInstance(generalProperties); } public static DogFamily getDogFamily(LivingBeingMaker livingBeingMaker) { return (DogFamily) livingBeingMaker.getInstance(generalProperties); } public static CatFamily getCatFamily(LivingBeingMaker livingBeingMaker) { return (CatFamily) livingBeingMaker.getInstance(generalProperties); } public static Animal getAnimal(LivingBeingMaker livingBeingMaker) { return (Animal) livingBeingMaker.getInstance(generalProperties); } public static Plant getPlant(LivingBeingMaker livingBeingMaker) { return (Plant) livingBeingMaker.getInstance(generalProperties); } /**** From here and down generic code, change this only if you know what you are doing ****/ static { // here you can define static stuff like properties or xml loaded configuration Properties livingBeingroperties = new Properties(); try { // load plant properties from xml and properties files livingBeingroperties.loadFromXML(LivingBeingMaker.class.getResourceAsStream("resources/plant-config.xml")); livingBeingroperties.load(LivingBeingMaker.class.getResourceAsStream("resources/animal-config.properties")); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } generalProperties = livingBeingroperties; } protected static Properties generalProperties; private LivingBeingMaker(Boolean singleton) { this.singleton = singleton; } private Boolean singleton; private Object instance; public Boolean isSingleton() { return singleton; } /** * This is the method that handles the creation of instances based on the flag singleton it * will create a singleton or a prototype instance * @param properties A Properties object that may contain information needed for the instance creation * @return The instance as an Object */ private Object getInstance(Properties properties) { if (singleton) { if (instance == null) { synchronized (this) { if (instance == null) { instance = this.createInstance(properties); } } } } Object localInstance = (instance == null) ? this.createInstance(properties) : instance; start(localInstance); return localInstance; } /** * Similar to {@link #init()} method, the difference is that the logic here will be executed each time an instance * is created, for prototypes that means every time the getInstance method is called, for singletons only the first * time the getInstance method is called */ protected void start(Object object) { ; } /** * You can put some shutdown logic here, this method can be overriden inside the enum value definition. * Shutdown logic can be: external resources release, clear chache, etc. */ public void shutdown(Object object) { ; } /** * This method will call the {@link #shutdown()} method for all the enums in the maker */ public void shutdownAll() { ; } /** * This method will set the instance to null, useful for reseting singleton instances */ public void clear() { instance = null; } /** * Will call the {@link #clear()} method for all the enums defined in the maker */ public void clearAll() { for (LivingBeingMaker value : LivingBeingMaker.values()) { value.clear(); } } /** * This method contains the logic for creating the instance, it receives a Properties * object as a parameter that my contain initial properties for creating the instances * @param properties a Properties object * @return The created instance as an Object */ public abstract Object createInstance(Properties properties); }
maker-pattern/src/org/maker_pattern/LivingBeingMaker.java
/** * Mar 14, 2014 File created by Ramiro.Serrato */ package org.maker_pattern; import java.io.IOException; import java.util.Properties; import org.maker_pattern.animals.Animal; import org.maker_pattern.animals.Cat; import org.maker_pattern.animals.CatFamily; import org.maker_pattern.animals.Dog; import org.maker_pattern.animals.DogFamily; import org.maker_pattern.plants.Ceiba; import org.maker_pattern.plants.Daisy; import org.maker_pattern.plants.Plant; /** * A very basic, light-weight, pragmatic programmatic alternative to DI frameworks * Maker Pattern versions: * 0.1 First version using an external class that included a Map storing the singleton instances and getInstance method, supporting * singleton and prototype beans * 0.2 Redesigned the pattern, now everything is in a single class (enum) and uses kind of factory methods for retrieving instances * This version is also capable of wiring beans inside the same enum and cross enum wiring too, allowing us to separate the beans * by domain or responsibility in different files and wire them if needed * 0.3 Added init, start, shutdown, clear and clearAll life cycle methods * 0.4 Added Properties parameter to getInstance method for supporting initialization properties * 0.5 Removed init method as it was not really useful * @author Ramiro.Serrato * */ public enum LivingBeingMaker { /*** Object configuration, definition, wiring ***/ // Pattern: NAME (isSingleton) { createInstance() { <object creation logic > } } SPARKY_DOG (true) { @Override public Dog createInstance(Properties properties) { Dog sparky = new Dog(); sparky.setName(properties.getProperty("sparky.name")); return sparky; } }, PINKY_DOG (true) { @Override public Dog createInstance(Properties properties) { Dog pinky = new Dog(); pinky.setName(properties.getProperty("pinky.name")); return pinky; } }, SPARKY_FAMILY (true) { // A wired object @Override public DogFamily createInstance(Properties properties) { DogFamily dogFamily = new DogFamily(); dogFamily.setParent1(getDog(SPARKY_DOG)); dogFamily.setParent2(getDog(PINKY_DOG)); return dogFamily; } }, SIAMESE (false) { @Override public Cat createInstance(Properties properties) { return new Cat(); } }, LABRADOR (false) { @Override public Dog createInstance(Properties properties) { return new Dog(); } }, DAISY (false) { @Override public Plant createInstance(Properties properties) { Daisy daisy = new Daisy(); daisy.setKind(properties.getProperty("daisy_kind")); return daisy; } }, CEIBA (false) { @Override public Plant createInstance(Properties properties) { Ceiba ceiba = new Ceiba(); ceiba.setAge(new Integer(properties.getProperty("ceiba_age"))); return ceiba; } }; /** Here define factory methods **/ public static Dog getDog(LivingBeingMaker livingBeingMaker) { return (Dog) livingBeingMaker.getInstance(generalProperties); } public static Cat getCat(LivingBeingMaker livingBeingMaker) { return (Cat) livingBeingMaker.getInstance(generalProperties); } public static DogFamily getDogFamily(LivingBeingMaker livingBeingMaker) { return (DogFamily) livingBeingMaker.getInstance(generalProperties); } public static CatFamily getCatFamily(LivingBeingMaker livingBeingMaker) { return (CatFamily) livingBeingMaker.getInstance(generalProperties); } public static Animal getAnimal(LivingBeingMaker livingBeingMaker) { return (Animal) livingBeingMaker.getInstance(generalProperties); } public static Plant getPlant(LivingBeingMaker livingBeingMaker) { return (Plant) livingBeingMaker.getInstance(generalProperties); } /**** From here and down generic code, change this only if you know what you are doing ****/ static { // here you can define static stuff like properties or xml loaded configuration Properties livingBeingroperties = new Properties(); try { // load plant properties from xml and properties files livingBeingroperties.loadFromXML(LivingBeingMaker.class.getResourceAsStream("resources/plant-config.xml")); livingBeingroperties.load(LivingBeingMaker.class.getResourceAsStream("resources/animal-config.properties")); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } generalProperties = livingBeingroperties; } protected static Properties generalProperties; private LivingBeingMaker(Boolean singleton) { this.singleton = singleton; } private Boolean singleton; private Object instance; public Boolean isSingleton() { return singleton; } /** * This is the method that handles the creation of instances based on the flag singleton it * will create a singleton or a prototype instance * @param properties A Properties object that may contain information needed for the instance creation * @return The instance as an Object */ private synchronized Object getInstance(Properties properties) { if (singleton) { if (instance == null) { synchronized (this) { if (instance == null) { instance = this.createInstance(properties); } } } } Object localInstance = (instance == null) ? this.createInstance(properties) : instance; start(localInstance); return localInstance; } /** * Similar to {@link #init()} method, the difference is that the logic here will be executed each time an instance * is created, for prototypes that means every time the getInstance method is called, for singletons only the first * time the getInstance method is called */ protected void start(Object object) { ; } /** * You can put some shutdown logic here, this method can be overriden inside the enum value definition. * Shutdown logic can be: external resources release, clear chache, etc. */ public void shutdown(Object object) { ; } /** * This method will call the {@link #shutdown()} method for all the enums in the maker */ public void shutdownAll() { ; } /** * This method will set the instance to null, useful for reseting singleton instances */ public void clear() { instance = null; } /** * Will call the {@link #clear()} method for all the enums defined in the maker */ public void clearAll() { for (LivingBeingMaker value : LivingBeingMaker.values()) { value.clear(); } } /** * This method contains the logic for creating the instance, it receives a Properties * object as a parameter that my contain initial properties for creating the instances * @param properties a Properties object * @return The created instance as an Object */ public abstract Object createInstance(Properties properties); }
Removed synchronized word from the getInstance method definition as it is not necessary now that I am using a synchronized block
maker-pattern/src/org/maker_pattern/LivingBeingMaker.java
Removed synchronized word from the getInstance method definition as it is not necessary now that I am using a synchronized block
<ide><path>aker-pattern/src/org/maker_pattern/LivingBeingMaker.java <ide> * @param properties A Properties object that may contain information needed for the instance creation <ide> * @return The instance as an Object <ide> */ <del> private synchronized Object getInstance(Properties properties) { <add> private Object getInstance(Properties properties) { <ide> if (singleton) { <ide> if (instance == null) { <ide> synchronized (this) {
Java
mit
1a6c79617f866c77f212621136b0d8e2aff3e4f3
0
khanh245/CST-407
package oit.edu.pinpointwaldo.services; import oit.edu.pinpointwaldo.WaldoMapFragment; import android.app.AlertDialog; import android.app.Service; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; public class GPSDataService extends Service implements LocationListener { private LocationManager mManager = null; private String provider = null; private void initialize() { mManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); Location loc = mManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); broadcast(loc); provider = mManager.getBestProvider(new Criteria(), false); mManager.requestLocationUpdates(provider, 1000, 1, this); } private void broadcast(Location loc) { Intent i = new Intent("android.intent.action.MAIN").putExtra(WaldoMapFragment.GPS_LOCATION, loc); this.sendBroadcast(i); this.stopSelf(); Log.d("WALDO_SERVICE", "Service's stopped..."); } // Service Implementation @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if( status != ConnectionResult.SUCCESS) { Log.e("LOCATION_SERVICE", "API NOT AVAILABLE"); stopSelf(); } initialize(); } @Override public void onDestroy() { if (mManager != null) mManager.removeUpdates(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("WALDO_SERVICE", "Service's started..."); initialize(); return START_NOT_STICKY; } // Location Listener Implementation @Override public void onLocationChanged(Location location) { Log.d("WALDO_SERVICE", "Location changed"); broadcast(location); } @Override public void onStatusChanged(final String provider, final int status, final Bundle extras) { } @Override public void onProviderEnabled(String provider) { Toast.makeText(this, provider + " enabled.", Toast.LENGTH_SHORT).show(); } @Override public void onProviderDisabled(String provider) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this) .setTitle("Pinpoint Waldo") .setMessage("GPS is disabled. Please enable it in Settings"); alertDialog.setPositiveButton("Settings", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); } }); alertDialog.setNegativeButton("Cancel", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); } }
PinpointWaldo/src/oit/edu/pinpointwaldo/services/GPSDataService.java
package oit.edu.pinpointwaldo.services; import oit.edu.pinpointwaldo.WaldoMapFragment; import android.app.AlertDialog; import android.app.Service; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; public class GPSDataService extends Service implements LocationListener { private LocationManager mManager = null; private String provider = null; private void initialize() { mManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); Location loc = mManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); broadcast(loc); provider = mManager.getBestProvider(new Criteria(), false); mManager.requestLocationUpdates(provider, 1000, 1, this); } private void broadcast(Location loc) { Intent i = new Intent("android.intent.action.MAIN").putExtra(WaldoMapFragment.GPS_LOCATION, loc); this.sendBroadcast(i); // TODO: Not sure about this this.stopSelf(); Log.d("WALDO_SERVICE", "Service's stopped..."); } // Service Implementation @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if( status != ConnectionResult.SUCCESS) { Log.e("LOCATION_SERVICE", "API NOT AVAILABLE"); stopSelf(); } initialize(); } @Override public void onDestroy() { if (mManager != null) mManager.removeUpdates(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("WALDO_SERVICE", "Service's started..."); initialize(); return START_NOT_STICKY; } // Location Listener Implementation @Override public void onLocationChanged(Location location) { Log.d("WALDO_SERVICE", "Location changed"); broadcast(location); } @Override public void onStatusChanged(final String provider, final int status, final Bundle extras) { } @Override public void onProviderEnabled(String provider) { Toast.makeText(this, provider + " enabled.", Toast.LENGTH_SHORT).show(); } @Override public void onProviderDisabled(String provider) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this) .setTitle("Pinpoint Waldo") .setMessage("GPS is disabled. Please enable it in Settings"); alertDialog.setPositiveButton("Settings", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); } }); alertDialog.setNegativeButton("Cancel", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); } }
removed comment
PinpointWaldo/src/oit/edu/pinpointwaldo/services/GPSDataService.java
removed comment
<ide><path>inpointWaldo/src/oit/edu/pinpointwaldo/services/GPSDataService.java <ide> private void broadcast(Location loc) { <ide> Intent i = new Intent("android.intent.action.MAIN").putExtra(WaldoMapFragment.GPS_LOCATION, loc); <ide> this.sendBroadcast(i); <del> // TODO: Not sure about this <ide> this.stopSelf(); <ide> Log.d("WALDO_SERVICE", "Service's stopped..."); <ide> }
Java
bsd-2-clause
e13bdf24d7b8e12a1faa049e9a4513470f3092c4
0
biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej
// // AWTMouseEventDispatcher.java // /* ImageJ software for multidimensional image processing and analysis. Copyright (c) 2010, ImageJDev.org. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the ImageJDev.org developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package imagej.ui.common.awt; import imagej.data.display.ImageDisplay; import imagej.event.EventService; import imagej.event.ImageJEvent; import imagej.ext.display.EventDispatcher; import imagej.ext.display.event.mouse.MsButtonEvent; import imagej.ext.display.event.mouse.MsClickedEvent; import imagej.ext.display.event.mouse.MsDraggedEvent; import imagej.ext.display.event.mouse.MsEnteredEvent; import imagej.ext.display.event.mouse.MsExitedEvent; import imagej.ext.display.event.mouse.MsMovedEvent; import imagej.ext.display.event.mouse.MsPressedEvent; import imagej.ext.display.event.mouse.MsReleasedEvent; import imagej.ext.display.event.mouse.MsWheelEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; /** * Rebroadcasts AWT events as {@link ImageJEvent}s. * * @author Curtis Rueden * @author Grant Harris */ public class AWTMouseEventDispatcher implements EventDispatcher, MouseListener, MouseMotionListener, MouseWheelListener { private final ImageDisplay display; private final boolean relative; private final EventService eventService; /** * Creates an AWT event dispatcher for the given display, which assumes * viewport mouse coordinates. */ public AWTMouseEventDispatcher(final ImageDisplay display, final EventService eventService) { this(display, eventService, true); } /** * Creates an AWT event dispatcher for the given display, with mouse * coordinates interpreted according to the relative flag. * * @param relative If true, coordinates are relative to the entire image * canvas rather than just the viewport; hence, the pan offset is * already factored in. */ public AWTMouseEventDispatcher(final ImageDisplay display, final EventService eventService, final boolean relative) { this.display = display; this.relative = relative; this.eventService = eventService; } // -- AWTEventDispatcher methods -- /** * Gets whether mouse coordinates are provided relative to the unpanned image * canvas. If true, the coordinates are measured from the top left corner of * the image canvas, regardless of the current pan. Hence, the coordinate * values will equal the pan offset plus the viewport coordinate values. If * false, the coordinates are relative to the canvas's viewport, meaning that * the pan offset is not lumped into the coordinate values. */ public boolean isRelative() { return relative; } // -- MouseListener methods -- @Override public void mouseClicked(final MouseEvent e) { eventService.publish(new MsClickedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } @Override public void mousePressed(final MouseEvent e) { eventService.publish(new MsPressedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } @Override public void mouseReleased(final MouseEvent e) { eventService.publish(new MsReleasedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } // -- MouseMotionListener methods -- @Override public void mouseEntered(final MouseEvent e) { eventService.publish(new MsEnteredEvent(display, getX(e), getY(e))); } @Override public void mouseExited(final MouseEvent e) { eventService.publish(new MsExitedEvent(display, getX(e), getY(e))); } @Override public void mouseDragged(final MouseEvent e) { eventService.publish(new MsDraggedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } @Override public void mouseMoved(final MouseEvent e) { eventService.publish(new MsMovedEvent(display, getX(e), getY(e))); } // -- MouseWheelListener methods -- @Override public void mouseWheelMoved(final MouseWheelEvent e) { eventService.publish(new MsWheelEvent(display, getX(e), getY(e), e.getWheelRotation())); } // -- Helper methods -- private int mouseButton(final MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: return MsButtonEvent.LEFT_BUTTON; case MouseEvent.BUTTON2: return MsButtonEvent.RIGHT_BUTTON; case MouseEvent.BUTTON3: return MsButtonEvent.MIDDLE_BUTTON; default: return -1; } } private int getX(final MouseEvent e) { final int x = e.getX(); if (relative) return x; return x - display.getImageCanvas().getPanOrigin().x; } private int getY(final MouseEvent e) { final int y = e.getY(); if (relative) return y; return y - display.getImageCanvas().getPanOrigin().y; } }
ui/awt-swing/common/src/main/java/imagej/ui/common/awt/AWTMouseEventDispatcher.java
// // AWTMouseEventDispatcher.java // /* ImageJ software for multidimensional image processing and analysis. Copyright (c) 2010, ImageJDev.org. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the ImageJDev.org developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package imagej.ui.common.awt; import imagej.data.display.ImageDisplay; import imagej.event.EventService; import imagej.event.ImageJEvent; import imagej.ext.display.Display; import imagej.ext.display.EventDispatcher; import imagej.ext.display.event.mouse.MsButtonEvent; import imagej.ext.display.event.mouse.MsClickedEvent; import imagej.ext.display.event.mouse.MsDraggedEvent; import imagej.ext.display.event.mouse.MsEnteredEvent; import imagej.ext.display.event.mouse.MsExitedEvent; import imagej.ext.display.event.mouse.MsMovedEvent; import imagej.ext.display.event.mouse.MsPressedEvent; import imagej.ext.display.event.mouse.MsReleasedEvent; import imagej.ext.display.event.mouse.MsWheelEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; /** * Rebroadcasts AWT events as {@link ImageJEvent}s. * * @author Curtis Rueden * @author Grant Harris */ public class AWTMouseEventDispatcher implements EventDispatcher, MouseListener, MouseMotionListener, MouseWheelListener { private final Display<?> display; private final boolean relative; private final EventService eventService; /** * Creates an AWT event dispatcher for the given display, which assumes * viewport mouse coordinates. */ public AWTMouseEventDispatcher(final Display<?> display, final EventService eventService) { this(display, eventService, true); } /** * Creates an AWT event dispatcher for the given display, with mouse * coordinates interpreted according to the relative flag. * * @param relative If true, coordinates are relative to the entire image * canvas rather than just the viewport; hence, the pan offset is * already factored in. */ public AWTMouseEventDispatcher(final Display<?> display, final EventService eventService, final boolean relative) { this.display = display; this.relative = relative; this.eventService = eventService; } // -- AWTEventDispatcher methods -- /** * Gets whether mouse coordinates are provided relative to the unpanned image * canvas. If true, the coordinates are measured from the top left corner of * the image canvas, regardless of the current pan. Hence, the coordinate * values will equal the pan offset plus the viewport coordinate values. If * false, the coordinates are relative to the canvas's viewport, meaning that * the pan offset is not lumped into the coordinate values. */ public boolean isRelative() { return relative; } // -- MouseListener methods -- @Override public void mouseClicked(final MouseEvent e) { eventService.publish(new MsClickedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } @Override public void mousePressed(final MouseEvent e) { eventService.publish(new MsPressedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } @Override public void mouseReleased(final MouseEvent e) { eventService.publish(new MsReleasedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } // -- MouseMotionListener methods -- @Override public void mouseEntered(final MouseEvent e) { eventService.publish(new MsEnteredEvent(display, getX(e), getY(e))); } @Override public void mouseExited(final MouseEvent e) { eventService.publish(new MsExitedEvent(display, getX(e), getY(e))); } @Override public void mouseDragged(final MouseEvent e) { eventService.publish(new MsDraggedEvent(display, getX(e), getY(e), mouseButton(e), e.getClickCount(), e.isPopupTrigger())); } @Override public void mouseMoved(final MouseEvent e) { eventService.publish(new MsMovedEvent(display, getX(e), getY(e))); } // -- MouseWheelListener methods -- @Override public void mouseWheelMoved(final MouseWheelEvent e) { eventService.publish(new MsWheelEvent(display, getX(e), getY(e), e.getWheelRotation())); } // -- Helper methods -- private int mouseButton(final MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: return MsButtonEvent.LEFT_BUTTON; case MouseEvent.BUTTON2: return MsButtonEvent.RIGHT_BUTTON; case MouseEvent.BUTTON3: return MsButtonEvent.MIDDLE_BUTTON; default: return -1; } } private int getX(final MouseEvent e) { final int x = e.getX(); if (relative) return x; if(display instanceof ImageDisplay) { return x - ((ImageDisplay)display).getImageCanvas().getPanOrigin().x;} return x; } private int getY(final MouseEvent e) { final int y = e.getY(); if (relative) return y; if(display instanceof ImageDisplay) { return y - ((ImageDisplay)display).getImageCanvas().getPanOrigin().y; } return y; } }
Went back to ImageDisplay in AWTMouseEventDispatcher This used to be revision r4003.
ui/awt-swing/common/src/main/java/imagej/ui/common/awt/AWTMouseEventDispatcher.java
Went back to ImageDisplay in AWTMouseEventDispatcher
<ide><path>i/awt-swing/common/src/main/java/imagej/ui/common/awt/AWTMouseEventDispatcher.java <ide> import imagej.data.display.ImageDisplay; <ide> import imagej.event.EventService; <ide> import imagej.event.ImageJEvent; <del>import imagej.ext.display.Display; <ide> import imagej.ext.display.EventDispatcher; <ide> import imagej.ext.display.event.mouse.MsButtonEvent; <ide> import imagej.ext.display.event.mouse.MsClickedEvent; <ide> MouseListener, MouseMotionListener, MouseWheelListener <ide> { <ide> <del> private final Display<?> display; <add> private final ImageDisplay display; <ide> private final boolean relative; <ide> private final EventService eventService; <ide> <ide> * Creates an AWT event dispatcher for the given display, which assumes <ide> * viewport mouse coordinates. <ide> */ <del> public AWTMouseEventDispatcher(final Display<?> display, final EventService eventService) { <add> public AWTMouseEventDispatcher(final ImageDisplay display, final EventService eventService) { <ide> this(display, eventService, true); <ide> } <ide> <ide> * canvas rather than just the viewport; hence, the pan offset is <ide> * already factored in. <ide> */ <del> public AWTMouseEventDispatcher(final Display<?> display, final EventService eventService, final boolean relative) { <add> public AWTMouseEventDispatcher(final ImageDisplay display, final EventService eventService, final boolean relative) { <ide> this.display = display; <ide> this.relative = relative; <ide> this.eventService = eventService; <ide> private int getX(final MouseEvent e) { <ide> final int x = e.getX(); <ide> if (relative) return x; <del> if(display instanceof ImageDisplay) { <del> return x - ((ImageDisplay)display).getImageCanvas().getPanOrigin().x;} <del> return x; <add> return x - display.getImageCanvas().getPanOrigin().x; <ide> } <ide> <ide> private int getY(final MouseEvent e) { <ide> final int y = e.getY(); <ide> if (relative) return y; <del> if(display instanceof ImageDisplay) { <del> return y - ((ImageDisplay)display).getImageCanvas().getPanOrigin().y; <del> } <del> return y; <add> return y - display.getImageCanvas().getPanOrigin().y; <ide> } <ide> <ide> }
JavaScript
mit
fd00ce2f703d838dac163a1bbec9e3f423d5bbff
0
vanthome/winston-elasticsearch,jackdbernier/winston-elasticsearch
'use strict'; const util = require('util'); const winston = require('winston'); const moment = require('moment'); const _ = require('lodash'); const elasticsearch = require('elasticsearch'); const defaultTransformer = require('./transformer'); const BulkWriter = require('./bulk_writer'); /** * Constructor */ const Elasticsearch = function Elasticsearch(options) { this.options = options || {}; if (!options.timestamp) { this.options.timestamp = function timestamp() { return new Date().toISOString(); }; } // Enforce context if (!(this instanceof Elasticsearch)) { return new Elasticsearch(options); } // Set defaults const defaults = { level: 'info', index: null, indexPrefix: 'logs', indexSuffixPattern: 'YYYY.MM.DD', messageType: 'log', transformer: defaultTransformer, ensureMappingTemplate: true, flushInterval: 2000, waitForActiveShards: 1, handleExceptions: false, pipeline: null }; _.defaults(options, defaults); winston.Transport.call(this, options); // Use given client or create one if (options.client) { this.client = options.client; } else { const defaultClientOpts = { clientOpts: { log: [ { type: 'console', level: 'error', } ] } }; _.defaults(options, defaultClientOpts); // Create a new ES client // http://localhost:9200 is the default of the client already this.client = new elasticsearch.Client(this.options.clientOpts); } const bulkWriterOptions = { interval: options.flushInterval, waitForActiveShards: options.waitForActiveShards, pipeline: options.pipeline, ensureMappingTemplate: options.ensureMappingTemplate, mappingTemplate: options.mappingTemplate, indexPrefix: options.indexPrefix }; this.bulkWriter = new BulkWriter( this.client, bulkWriterOptions ); this.bulkWriter.start(); return this; }; util.inherits(Elasticsearch, winston.Transport); Elasticsearch.prototype.name = 'elasticsearch'; /** * log() method */ Elasticsearch.prototype.log = function log(level, message, meta, callback) { const logData = { message, level, meta, timestamp: this.options.timestamp() }; const entry = this.options.transformer(logData); this.bulkWriter.append( this.getIndexName(this.options), this.options.messageType, entry ); callback(); // write is deferred, so no room for errors here :) }; Elasticsearch.prototype.getIndexName = function getIndexName(options) { let indexName = options.index; if (indexName === null) { const now = moment(); const dateString = now.format(options.indexSuffixPattern); indexName = options.indexPrefix + '-' + dateString; } return indexName; }; Elasticsearch.prototype.search = function search(q) { const index = this.getIndexName(this.options); const query = { index, q }; return this.client.search(query); }; winston.transports.Elasticsearch = Elasticsearch; module.exports = Elasticsearch;
index.js
'use strict'; const util = require('util'); const winston = require('winston'); const moment = require('moment'); const _ = require('lodash'); const elasticsearch = require('elasticsearch'); const defaultTransformer = require('./transformer'); const BulkWriter = require('./bulk_writer'); /** * Constructor */ const Elasticsearch = function Elasticsearch(options) { this.options = options || {}; if (!options.timestamp) { this.options.timestamp = function timestamp() { return new Date().toISOString(); }; } // Enforce context if (!(this instanceof Elasticsearch)) { return new Elasticsearch(options); } // Set defaults const defaults = { level: 'info', index: null, indexPrefix: 'logs', indexSuffixPattern: 'YYYY.MM.DD', messageType: 'log', transformer: defaultTransformer, ensureMappingTemplate: true, flushInterval: 2000, waitForActiveShards: 1, handleExceptions: false, pipeline: null }; _.defaults(options, defaults); winston.Transport.call(this, options); // Use given client or create one if (options.client) { this.client = options.client; } else { const defaultClientOpts = { clientOpts: { log: [ { type: 'console', level: 'error', } ] } }; _.defaults(options, defaultClientOpts); // Create a new ES client // http://localhost:9200 is the default of the client already this.client = new elasticsearch.Client(this.options.clientOpts); } const bulkWriterOptions = { interval: options.flushInterval, waitForActiveShards: options.waitForActiveShards, pipeline: options.pipeline, ensureMappingTemplate: options.ensureMappingTemplate, }; this.bulkWriter = new BulkWriter( this.client, bulkWriterOptions ); this.bulkWriter.start(); return this; }; util.inherits(Elasticsearch, winston.Transport); Elasticsearch.prototype.name = 'elasticsearch'; /** * log() method */ Elasticsearch.prototype.log = function log(level, message, meta, callback) { const logData = { message, level, meta, timestamp: this.options.timestamp() }; const entry = this.options.transformer(logData); this.bulkWriter.append( this.getIndexName(this.options), this.options.messageType, entry ); callback(); // write is deferred, so no room for errors here :) }; Elasticsearch.prototype.getIndexName = function getIndexName(options) { let indexName = options.index; if (indexName === null) { const now = moment(); const dateString = now.format(options.indexSuffixPattern); indexName = options.indexPrefix + '-' + dateString; } return indexName; }; Elasticsearch.prototype.search = function search(q) { const index = this.getIndexName(this.options); const query = { index, q }; return this.client.search(query); }; winston.transports.Elasticsearch = Elasticsearch; module.exports = Elasticsearch;
pass options, that are using by BulkWriter
index.js
pass options, that are using by BulkWriter
<ide><path>ndex.js <ide> waitForActiveShards: options.waitForActiveShards, <ide> pipeline: options.pipeline, <ide> ensureMappingTemplate: options.ensureMappingTemplate, <add> mappingTemplate: options.mappingTemplate, <add> indexPrefix: options.indexPrefix <ide> }; <ide> <ide> this.bulkWriter = new BulkWriter(
JavaScript
mit
703d5a32760614c30c7b40df08b2609b7c5c4348
0
boomcms/boom-core,boomcms/boom-core,boomcms/boom-core
/** Editable timestamps @class @name chunkTimestamp @extends $.ui.chunk @memberOf $.ui */ $.widget('ui.chunkTimestamp', $.ui.chunk, /** @lends $.ui.chunkTimestamp */ { /** Make the element editable by invokeing boom.editor.edit() on it. */ edit : function(){ var self = this; $.boom.log('Timestamp chunk slot edit'); var data = this.getData(); this.dialog = $.boom.dialog.open({ url: this.options.urlPrefix + '/timestamp/edit/' + $.boom.page.options.id, width: 400, id: self.element[0].id + '-boom-dialog', // cache: true, title: 'Edit date / time', onLoad : function() { if (data.format) { $('#format').val(data.format); } var time; if (data.timestamp) { time = new Date(data.timestamp * 1000); } else { time = new Date(); } $( "#timestamp" ).datepicker('setDate', time); }, destroy: function(){ self.destroy(); }, callback: function(){ var format = $('#format').val(); var stringDate = $('#timestamp').val(); var dateyDate = new Date(stringDate); var timestamp = dateyDate.valueOf() / 1000; self ._insert(format, timestamp) .done( function(){ self.destroy(); }); } }); }, _insert : function(format, timestamp) { var self = this; return $.post(this.options.urlPrefix + '/timestamp/preview/' + $.boom.page.options.id, {slotname : self.options.slot.slotname, format : format, timestamp : timestamp}) .done(function(data) { self._apply(data); }); }, getData: function(){ return { format : this.element.attr('data-boom-format'), timestamp: this.element.attr('data-boom-timestamp') }; } });
media/boom/js/boom.chunk.timestamp.js
/** Editable timestamps @class @name chunkTimestamp @extends $.ui.chunk @memberOf $.ui */ $.widget('ui.chunkTimestamp', $.ui.chunk, /** @lends $.ui.chunkTimestamp */ { /** Make the element editable by invokeing boom.editor.edit() on it. */ edit : function(){ var self = this; $.boom.log('Timestamp chunk slot edit'); var data = this.getData(); this.dialog = $.boom.dialog.open({ url: this.options.urlPrefix + '/timestamp/edit/' + $.boom.page.options.id, width: 400, id: self.element[0].id + '-boom-dialog', // cache: true, title: 'Edit date / time', onLoad : function() { if (data.format) { $('#format').val(data.format); } var time; if (self.options.slot.timestamp) { time = new Date(data.timestamp * 1000); } else { time = new Date(); } $( "#timestamp" ).datepicker('setDate', time); }, destroy: function(){ self.destroy(); }, callback: function(){ var format = $('#format').val(); var stringDate = $('#timestamp').val(); var dateyDate = new Date(stringDate); var timestamp = dateyDate.valueOf() / 1000; self ._insert(format, timestamp) .done( function(){ self.destroy(); }); } }); }, _insert : function(format, timestamp) { var self = this; return $.post(this.options.urlPrefix + '/timestamp/preview/' + $.boom.page.options.id, {slotname : self.options.slot.slotname, format : format, timestamp : timestamp}) .done(function(data) { self._apply(data); }); }, getData: function(){ return { format : this.element.attr('data-boom-format'), timestamp: this.element.attr('data-boom-timestamp') }; } });
bugfix
media/boom/js/boom.chunk.timestamp.js
bugfix
<ide><path>edia/boom/js/boom.chunk.timestamp.js <ide> } <ide> <ide> var time; <del> if (self.options.slot.timestamp) { <add> if (data.timestamp) { <ide> time = new Date(data.timestamp * 1000); <ide> } else { <ide> time = new Date();
Java
apache-2.0
362f599c68bf0f8b0e646f3fe86f27094ace8f4f
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.db; import static org.smoothbuild.SmoothContants.OBJECTS_DIR; import static org.smoothbuild.SmoothContants.TASK_RESULTS_DIR; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.io.fs.SmoothDir; import org.smoothbuild.io.fs.base.FileSystem; import org.smoothbuild.io.fs.base.SubFileSystem; import com.google.inject.AbstractModule; import com.google.inject.Provides; public class DbModule extends AbstractModule { @Override protected void configure() {} @TaskResults @Provides private FileSystem provideTaskResultsFileSystem(@SmoothDir FileSystem fileSystem) { return new SubFileSystem(fileSystem, TASK_RESULTS_DIR); } @TaskResults @Provides public HashedDb provideTaksResultsHashedDb(@TaskResults FileSystem fileSystem) { return new HashedDb(fileSystem); } @Objects @Provides private FileSystem provideObjectsFileSystem(@SmoothDir FileSystem fileSystem) { return new SubFileSystem(fileSystem, OBJECTS_DIR); } @Objects @Provides public HashedDb provideObjectsHashedDb(@Objects FileSystem fileSystem) { return new HashedDb(fileSystem); } }
src/java/org/smoothbuild/db/DbModule.java
package org.smoothbuild.db; import static org.smoothbuild.SmoothContants.OBJECTS_DIR; import static org.smoothbuild.SmoothContants.TASK_RESULTS_DIR; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.io.fs.SmoothDir; import org.smoothbuild.io.fs.base.FileSystem; import org.smoothbuild.io.fs.base.SubFileSystem; import com.google.inject.AbstractModule; import com.google.inject.Provides; public class DbModule extends AbstractModule { @Override protected void configure() {} @TaskResults @Provides public HashedDb provideTaksResultsHashedDb(@SmoothDir FileSystem fileSystem) { FileSystem objectsFileSystem = new SubFileSystem(fileSystem, TASK_RESULTS_DIR); return new HashedDb(objectsFileSystem); } @Objects @Provides public HashedDb provideObjectsHashedDb(@SmoothDir FileSystem fileSystem) { FileSystem objectsFileSystem = new SubFileSystem(fileSystem, OBJECTS_DIR); return new HashedDb(objectsFileSystem); } }
refactored DbModule
src/java/org/smoothbuild/db/DbModule.java
refactored DbModule
<ide><path>rc/java/org/smoothbuild/db/DbModule.java <ide> <ide> @TaskResults <ide> @Provides <del> public HashedDb provideTaksResultsHashedDb(@SmoothDir FileSystem fileSystem) { <del> FileSystem objectsFileSystem = new SubFileSystem(fileSystem, TASK_RESULTS_DIR); <del> return new HashedDb(objectsFileSystem); <add> private FileSystem provideTaskResultsFileSystem(@SmoothDir FileSystem fileSystem) { <add> return new SubFileSystem(fileSystem, TASK_RESULTS_DIR); <add> } <add> <add> @TaskResults <add> @Provides <add> public HashedDb provideTaksResultsHashedDb(@TaskResults FileSystem fileSystem) { <add> return new HashedDb(fileSystem); <ide> } <ide> <ide> @Objects <ide> @Provides <del> public HashedDb provideObjectsHashedDb(@SmoothDir FileSystem fileSystem) { <del> FileSystem objectsFileSystem = new SubFileSystem(fileSystem, OBJECTS_DIR); <del> return new HashedDb(objectsFileSystem); <add> private FileSystem provideObjectsFileSystem(@SmoothDir FileSystem fileSystem) { <add> return new SubFileSystem(fileSystem, OBJECTS_DIR); <add> } <add> <add> @Objects <add> @Provides <add> public HashedDb provideObjectsHashedDb(@Objects FileSystem fileSystem) { <add> return new HashedDb(fileSystem); <ide> } <ide> }
Java
apache-2.0
ceda2873c5b6d272a2537f444dfcfc2d05c08691
0
nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni
/* * Copyright (C) 2007 Google Inc. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yawni.util; //import java.io.Serializable; import com.google.common.collect.UnmodifiableIterator; import java.util.ArrayList; import static com.google.common.collect.ObjectArrays.newArray; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.RandomAccess; /** * This implementation is particularly useful when {@code E} is immutable (e.g., {@code String}, {@code Integer}) * (aka "deeply immutable"). * Strives for performance and memory characteristics of a C99 const array, especially for * small sizes (0-5). "unrolled", "inside out" implementation for small sizes sacrifices * verbosity for space (and probably asks more of the compiler, but who cares). * * Uses cases: * - especially useful when you have millions of short {@code List<T>}s * - ImmutableMultimap * - caches like Yawni uses all the time - impossible to "poison" :) * ? XML parsing / parse tree (read-only JDOM? would be fun to template that anyway if JAXB isn't already far superior) * ? graph / tree data structures * ? ML data structures * * TODO * - make this class package private and move it accordingly ? just an implementation detail for now * - take another crack at Restleton * - run Google Guava test suite on it * - copy Serializable functionality * * <p> Random notes * <ul> * <li> Using {@code Iterator}s is slow compared to {@link LightImmutableList#get(int)} - unnecessary allocation / deallocation. </b> * Unfortunately, the new {@code foreach} syntax is so convenient. * </li> * <li> speed: inefficiencies in most implementations of base {@link Collection} classes ({@link java.util.AbstractCollection}, * {@link java.util.AbstractList}, etc.) in the form of {@link Iterator}-based implementations of key methods * (e.g., {@link #equals}) </li> * </ul> */ // Comparison to Google Collections version // + uses less memory // + much less for many common cases (i.e., sizes (1-5)) // * trades some "extra" code for memory // + doesn't use offset, length impl (or even Object[] ref and instance for some sizes) // * subList impl sorda justifies this // + supports null elements // * this is of dubious value - why did they do this? block errors ? speed up impl ? // * null has a some legit uses // * their equals() and hashCode() are optimized for comparing instances to one another which could be very good // - this impl is only optimized for comparing to RandomAccess List, but still has get() and null-check overhead // but is still a step up from typical Collections implementations // + uses Iterators internally for fewer methods (e.g., contains()) - less transient allocation // - doesn't specialize serialization // * they do this very well ("explicit serialized forms, though readReplace() and writeReplace() are slower) // - doesn't use general utility impls // - Nullable, Iterators, ImmutableCollection, Collections2 // - very clean slick, comprehensive use of covariant return types // // maximally optimized methods // - get(i), isEmpty(), contains(), subList (for small sizes) // // - consider generating code for methods like get(i), subList // // - hopefully compiler won't have problems with deeply nested implementation classes // LightImmutableList → AbstractList → Singleton → Doubleton → ... // // - LightImmutableList should be an interface // - ideally above List, but for compat has to be // below it and therefore we can't remove methods from it // - could be sneaky and duplicate the methods, but this kinda sucks too public abstract class LightImmutableList<E> implements List<E>, RandomAccess { @SuppressWarnings("unchecked") public static <E> LightImmutableList<E> of() { return Nothington.INSTANCE; } public static <E> LightImmutableList<E> of(E e0) { return new Singleton<E>(e0); } public static <E> LightImmutableList<E> of(E e0, E e1) { return new Doubleton<E>(e0, e1); } public static <E> LightImmutableList<E> of(E e0, E e1, E e2) { return new Tripleton<E>(e0, e1, e2); } public static <E> LightImmutableList<E> of(E e0, E e1, E e2, E e3) { return new Quadrupleton<E>(e0, e1, e2, e3); } public static <E> LightImmutableList<E> of(E e0, E e1, E e2, E e3, E e4) { return new Quintupleton<E>(e0, e1, e2, e3, e4); } /** * Selects the most efficient implementation based on the length of {@code all} */ public static <E> LightImmutableList<E> of(E... all) { switch (all.length) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(all[0]); case 2: return LightImmutableList.of(all[0], all[1]); case 3: return LightImmutableList.of(all[0], all[1], all[2]); case 4: return LightImmutableList.of(all[0], all[1], all[2], all[3]); case 5: return LightImmutableList.of(all[0], all[1], all[2], all[3], all[4]); default: if (all.length > 5) { //return new Restleton<E>(all); return new RegularImmutableList<E>(all); } else { // this is impossible throw new IllegalStateException(); } } } public static <E> LightImmutableList<E> copyOf(final Iterable<? extends E> elements) { if (elements instanceof LightImmutableList) { @SuppressWarnings("unchecked") final LightImmutableList<E> elementsAsImmutableList = (LightImmutableList<E>) elements; return elementsAsImmutableList; } else if (elements instanceof Collection) { @SuppressWarnings("unchecked") final Collection<E> elementsAsCollection = (Collection<E>) elements; final int size = elementsAsCollection.size(); if (size == 0) { return LightImmutableList.of(); } @SuppressWarnings("unchecked") final E[] elementsAsArray = (E[]) new Object[size]; final E[] returnedElementsAsArray = elementsAsCollection.toArray(elementsAsArray); assert returnedElementsAsArray == elementsAsArray; return LightImmutableList.of(elementsAsArray); } else { final Collection<E> elementsAsCollection = new ArrayList<E>(); for (final E e : elements) { elementsAsCollection.add(e); } // recursive call return LightImmutableList.copyOf(elementsAsCollection); } } public static <E> LightImmutableList<E> copyOf(final Iterator<? extends E> elements) { if (! elements.hasNext()) { return LightImmutableList.of(); } final E e0 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0); } final E e1 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1); } final E e2 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1, e2); } final E e3 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1, e2, e3); } final E e4 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1, e2, e3, e4); } // give up; copy em' into temp var final Collection<E> elementsAsCollection = new ArrayList<E>(); elementsAsCollection.add(e0); elementsAsCollection.add(e1); elementsAsCollection.add(e2); elementsAsCollection.add(e3); elementsAsCollection.add(e4); do { elementsAsCollection.add(elements.next()); } while (elements.hasNext()); // recursive call return LightImmutableList.copyOf(elementsAsCollection); } private LightImmutableList() {} static boolean eq(Object obj, Object e) { return obj == null ? e == null : obj.equals(e); } // lifted from Google Collections private static Object[] copyIntoArray(Object... items) { final Object[] array = new Object[items.length]; int index = 0; for (final Object element : items) { // if (element == null) { // throw new NullPointerException("at index " + index); // } array[index++] = element; } return array; } /** * Equivalent to {@link Collections#emptyList()} */ static final class Nothington<E> extends AbstractImmutableList<E> { static final Nothington INSTANCE = new Nothington(); static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; private Nothington() { // no reason to make more than 1 of these } @Override public E get(int index) { throw new IndexOutOfBoundsException("Index: " + index); } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object obj) { return false; } @Override public boolean containsAll(Collection<?> needles) { return needles.isEmpty(); } @Override public int indexOf(Object e) { return -1; } @Override public int lastIndexOf(Object e) { return -1; } @Override public Iterator<E> iterator() { return Collections.<E>emptyList().iterator(); } @Override public ListIterator<E> listIterator() { return Collections.<E>emptyList().listIterator(); } @Override public ListIterator<E> listIterator(int index) { return Collections.<E>emptyList().listIterator(index); } @Override public LightImmutableList<E> subList(int fromIndex, int toIndex) { if (fromIndex != 0 || toIndex != 0) { throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is 0"); } return this; } @Override public Object[] toArray() { return EMPTY_OBJECT_ARRAY; } @Override public <T> T[] toArray(T[] a) { if (a.length > 0) { a[0] = null; } return a; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { return obj instanceof List && ((List<?>) obj).isEmpty(); } @Override public String toString() { return "[]"; } private Object readResolve() { return INSTANCE; } } // end class Nothington /** * Equivalent to {@link Collections#singletonList()} */ static class Singleton<E> extends AbstractImmutableList<E> { protected final E e0; Singleton(E e0) { this.e0 = e0; } @Override public E get(int index) { // this impl looks clunky for Singleton, but pays off in Doubleton, ... switch (index) { case 0: return e0; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 1; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl return eq(obj, e0); } @Override public int indexOf(Object e) { // zero allocation vs. AbstractCollection impl return contains(e) ? 0 : -1; } @Override public int lastIndexOf(Object e) { // zero allocation vs. AbstractCollection impl return contains(e) ? 0 : -1; } /* @Override */ @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Singleton static class Doubleton<E> extends Singleton<E> { protected final E e1; Doubleton(E e0, E e1) { super(e0); this.e1 = e1; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 2; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e1); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Doubleton static class Tripleton<E> extends Doubleton<E> { protected final E e2; Tripleton(E e0, E e1, E e2) { super(e0, e1); this.e2 = e2; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; case 2: return e2; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 3; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e2); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e2)) { return 2; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e2)) { return 2; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2,3} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return LightImmutableList.of(e0, e1); case 3: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); case 3: return LightImmutableList.of(e1, e2); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); case 3: return LightImmutableList.of(e2); } case 3: switch (toIndex) { case 3: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Tripleton static class Quadrupleton<E> extends Tripleton<E> { protected final E e3; Quadrupleton(E e0, E e1, E e2, E e3) { super(e0, e1, e2); this.e3 = e3; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; case 2: return e2; case 3: return e3; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 4; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e3); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e2)) { return 2; } else if (eq(obj, e3)) { // TODO redundant null check return 3; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e3)) { return 3; // TODO redundant null check } else if (eq(obj, e2)) { return 2; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2,3,4} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return LightImmutableList.of(e0, e1); case 3: return LightImmutableList.of(e0, e1, e2); case 4: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); case 3: return LightImmutableList.of(e1, e2); case 4: return LightImmutableList.of(e1, e2, e3); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); case 3: return LightImmutableList.of(e2); case 4: return LightImmutableList.of(e2, e3); } case 3: switch (toIndex) { case 3: return LightImmutableList.of(); case 4: return LightImmutableList.of(e3); } case 4: switch (toIndex) { case 4: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Quadrupleton static class Quintupleton<E> extends Quadrupleton<E> { protected final E e4; Quintupleton(E e0, E e1, E e2, E e3, E e4) { super(e0, e1, e2, e3); this.e4 = e4; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; case 2: return e2; case 3: return e3; case 4: return e4; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 5; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e4); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e2)) { return 2; } else if (eq(obj, e3)) { // TODO redundant null check return 3; } else if (eq(obj, e4)) { // TODO redundant null check return 4; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e4)) { return 4; // TODO redundant null check } else if (eq(obj, e3)) { return 3; // TODO redundant null check } else if (eq(obj, e2)) { return 2; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2,3,4,5} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return LightImmutableList.of(e0, e1); case 3: return LightImmutableList.of(e0, e1, e2); case 4: return LightImmutableList.of(e0, e1, e2, e3); case 5: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); case 3: return LightImmutableList.of(e1, e2); case 4: return LightImmutableList.of(e1, e2, e3); case 5: return LightImmutableList.of(e1, e2, e3, e4); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); case 3: return LightImmutableList.of(e2); case 4: return LightImmutableList.of(e2, e3); case 5: return LightImmutableList.of(e2, e3, e4); } case 3: switch (toIndex) { case 3: return LightImmutableList.of(); case 4: return LightImmutableList.of(e3); case 5: return LightImmutableList.of(e3, e4); } case 4: switch (toIndex) { case 4: return LightImmutableList.of(); case 5: return LightImmutableList.of(e4); } case 5: switch (toIndex) { case 5: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Quintupleton /** * <h3> Broken (subList, etc.) impl! Do not use </h3> * Classic {@code ArrayList}-style implementation. * <p> Goal is to minimize memory requirements by avoiding begin/end fields for * common cases. * @param <E> */ @Deprecated static class Restleton<E> extends AbstractImmutableList<E> { private final Object[] items; Restleton(E[] all) { this.items = copyIntoArray(all); } public final int size() { return items.length; } // public boolean contains(Object target) { // for (int i = begin(), n = size(); i < n; i++) { // // TODO redundant null check // if (eq(items[i], target)) { // return true; // } // } // return false; // } @Override public Object[] toArray() { Object[] newArray = new Object[size()]; System.arraycopy(items, 0, newArray, 0, size()); return newArray; } @Override public <T> T[] toArray(T[] other) { if (other.length < size()) { other = newArray(other, size()); } else if (other.length > size()) { other[size()] = null; } System.arraycopy(items, 0, other, 0, size()); return other; } @SuppressWarnings("unchecked") public E get(int index) { try { return (E) items[index]; } catch(ArrayIndexOutOfBoundsException aioobe) { throw new IndexOutOfBoundsException( "Invalid index: " + index + ", list size is " + size()); } } // public int indexOf(Object target) { // for (int i = begin(), n = size(); i < n; i++) { // // TODO redundant null check // if (eq(items[i], target)) { // return i; // } // } // return -1; // } // public int lastIndexOf(Object target) { // for (int i = size() - 1; i >= begin(); i--) { // // TODO redundant null check // if (eq(items[i], target)) { // return i; // } // } // return -1; // } public LightImmutableList<E> subList(int fromIndex, int toIndex) { // - using 2 ints (b, end) and parent reference (Object(8)+4+4+parent(4) = 24 on 32-bit arch // - could optimize with b=0 and end=size() variants :) if (fromIndex < 0 || toIndex > size() || fromIndex > toIndex) { throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } if (fromIndex == toIndex) { return LightImmutableList.of(); } else if (fromIndex == 0 && toIndex == size()) { return this; } else { return new SubList(fromIndex, toIndex); } } /** * Clipped view of its enclosing Restleton with a modified * - begin() * - end() * - size() */ class SubList extends AbstractImmutableList<E> { final int begin; final int end; SubList(int begin, int end) { this.begin = begin; this.end = end; System.out.println("SubList begin(): "+begin()+" end(): "+end()+" size(): "+size()); } @Override int begin() { return begin; } @Override public int end() { return end; } /* @Override */ public int size() { return end - begin; } @Override public Object[] toArray() { throw new UnsupportedOperationException("Not supported yet."); } @Override public <T> T[] toArray(T[] a) { throw new UnsupportedOperationException("Not supported yet."); } public E get(int index) { if (index < 0) { throw new IndexOutOfBoundsException(); } // index needs to be adjusted for s and end // index 0 → begin index += begin; if (index > end) { throw new IndexOutOfBoundsException(); } System.out.println("begin: "+begin+" end: "+end()+" size: "+size()+" index: "+index); return Restleton.this.get(index); } /* @Override */ public LightImmutableList<E> subList(int fromIndex, int toIndex) { // if (fromIndex < 0) { // throw new IndexOutOfBoundsException(); // } // // translate incoming indices // fromIndex += begin; // toIndex += begin; // if (toIndex > end) { // throw new IndexOutOfBoundsException(); // } // return Restleton.this.subList(fromIndex, toIndex); if (fromIndex == toIndex) { return LightImmutableList.of(); } else if (fromIndex == 0 && toIndex == size()) { return this; } else { // translate incoming indices fromIndex += begin; toIndex += begin; //return new SubList(fromIndex, toIndex); return Restleton.this.subList(fromIndex, toIndex); } } } // end class SubList } // end class Restleton /** * Classic {@code ArrayList}-style implementation. Implementation liberally copied * from Google Collections ImmutableList.RegularImmutableList * @param <E> */ private static final class RegularImmutableList<E> extends AbstractImmutableList<E> { private final int offset; private final int size; private final Object[] array; private RegularImmutableList(Object[] array, int offset, int size) { this.offset = offset; this.size = size; this.array = array; } private RegularImmutableList(Object[] array) { this(array, 0, array.length); } public int size() { return size; } @Override public Object[] toArray() { final Object[] newArray = new Object[size()]; System.arraycopy(array, offset, newArray, 0, size); return newArray; } @Override public <T> T[] toArray(T[] other) { if (other.length < size) { other = newArray(other, size); } else if (other.length > size) { other[size] = null; } System.arraycopy(array, offset, other, 0, size); return other; } // The fake cast to E is safe because the creation methods only allow E's @SuppressWarnings("unchecked") public E get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException( "Invalid index: " + index + ", list size is " + size); } return (E) array[index + offset]; } @Override public LightImmutableList<E> subList(int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) { throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size); } return (fromIndex == toIndex) ? LightImmutableList.<E>of() : new RegularImmutableList<E>( array, offset + fromIndex, toIndex - fromIndex); } } // end class RegularImmutableList /** * {@inheritDoc} * Makes covariant subList type inference work. */ public abstract LightImmutableList<E> subList(int fromIndex, int toIndex); static abstract class AbstractImmutableList<E> extends LightImmutableList<E> { // base implementation @Override public boolean contains(Object target) { for (int i = begin(), n = end(); i < n; i++) { // TODO redundant null check if (eq(get(i), target)) { return true; } } return false; } // only Nothington overrides @Override public boolean isEmpty() { return false; } public int indexOf(Object target) { for (int i = begin(), n = end(); i < n; i++) { // TODO redundant null check if (eq(get(i), target)) { return i; } } return -1; } public int lastIndexOf(Object target) { for (int i = end() - 1; i >= begin(); i--) { // TODO redundant null check if (eq(get(i), target)) { return i; } } return -1; } // only Nothington overrides @Override public Iterator<E> iterator() { return new SimpleListIterator(); } // only Nothington overrides @Override public ListIterator<E> listIterator() { return new FullListIterator(begin()); } @Override public ListIterator<E> listIterator(int index) { return new FullListIterator(index); } // only Nothington overrides @Override public boolean containsAll(Collection<?> c) { // TODO consider optimization strategies - c not necessarily a RandomAccess & List, but // we made that assumption for equals() for (final Object target : c) { if (! contains(target)) { return false; } } return true; } /** * @throws UnsupportedOperationException */ @Override public final boolean add(E e) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ public final boolean remove(Object o) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ public final boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ public final boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final E remove(int idx) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final void add(int idx, E e) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final E set(int idx, E e) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final void clear() { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { final Object[] newArray = new Object[size()]; for (int i = begin(), n = end(); i < n; i++) { newArray[i] = get(i); } return newArray; } @Override public <T> T[] toArray(T[] other) { if (other.length < size()) { other = newArray(other, size()); } else if (other.length > size()) { other[size()] = null; } for (int i = begin(), n = end(); i < n; i++) { other[i] = (T) get(i); } return other; } /** * {@inheritDoc} * <p> <i> This implementation is optimized for comparing to {@link RandomAccess} {@link List} </i> </p> */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (! (obj instanceof List)) { return false; } final List<?> that = (List<?>) obj; if (that.size() != this.size()) { return false; } for (int i = begin(), n = this.end(); i < n; i++) { if (! eq(that.get(i), this.get(i))) { return false; } } return true; } @Override public int hashCode() { int result = 1; // optimized for RandomAaccess - zero allocation for (int i = begin(), n = end(); i < n; i++) { final E next = get(i); result = (31 * result) + (next == null ? 0 : next.hashCode()); } return result; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(size() * 16); buffer.append('[').append(get(begin())); for (int i = begin() + 1, n = end(); i < n; i++) { //System.out.println("begin(): "+begin()+" end(): "+end()+" size(): "+size()); final E next = get(i); buffer.append(", "); // there is no way to have an LightImmutableList which contains itself //if (next != this) { buffer.append(next); //} else { // buffer.append("(this LightImmutableList)"); //} } return buffer.append(']').toString(); } // name borrowed from C++ STL int begin() { return 0; } // name borrowed from C++ STL int end() { return size(); } /** * Stating the obvious: this is a non-static class so instances * have implicit {@code AbstractImmutableList.this} reference. */ // Lifted from Apache Harmony class SimpleListIterator extends UnmodifiableIterator<E> { int pos = begin() - 1; @Override public final boolean hasNext() { return pos + 1 < end(); } @Override public E next() { try { final E result = get(pos + 1); pos++; return result; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } } // end class SimpleListIterator /** * Stating the obvious: this is a non-static class so instances * have implicit {@code AbstractImmutableList.this} reference. */ // Lifted from Apache Harmony final class FullListIterator extends SimpleListIterator implements ListIterator<E> { FullListIterator(int begin) { super(); if (begin() <= begin && begin <= end()) { pos = begin - 1; } else { throw new IndexOutOfBoundsException(); } } @Override public E next() { try { final E result = get(pos + 1); ++pos; return result; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } @Override public boolean hasPrevious() { return pos >= begin(); } @Override public int nextIndex() { return pos + 1; } @Override public E previous() { try { final E result = get(pos); pos--; return result; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } @Override public int previousIndex() { return pos; } /** * @throws UnsupportedOperationException */ @Override public void add(E object) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public void set(E object) { throw new UnsupportedOperationException(); } } // end clss FullListIterator } // end class AbstractImmutableList }
api/src/main/java/org/yawni/util/LightImmutableList.java
/* * Copyright (C) 2007 Google Inc. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yawni.util; //import java.io.Serializable; import com.google.common.collect.UnmodifiableIterator; import java.util.ArrayList; import static com.google.common.collect.ObjectArrays.newArray; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.RandomAccess; /** * This implementation is particularly useful when {@code E} is immutable (e.g., {@code String}, {@code Integer}) * (aka "deeply immutable"). * Strives for performance and memory characteristics of a C99 const array, especially for * small sizes (0-5). "unrolled", "inside out" implementation for small sizes sacrifices * verbosity for space (and probably asks more of the compiler, but who cares). * * Uses cases: * - especially useful when you have millions of short {@code List<T>}s * - ImmutableMultimap * - caches like Yawni uses all the time - impossible to "poison" :) * ? XML parsing / parse tree (read-only JDOM? would be fun to template that anyway if JAXB isn't already far superior) * ? graph / tree data structures * ? ML data structures * * TODO * - make this class package private and move it accordingly ? just an implementation detail for now * - take another crack at Restleton * - run Google Collections test suite on it * - copy Serializable functionality * * <p> Random notes * <ul> * <li> Using {@code Iterator}s is slow compared to {@link LightImmutableList#get(int)} - unnecessary allocation / deallocation. </b> * Unfortunately, the new {@code foreach} syntax is so convenient. * </li> * <li> speed: inefficiencies in most implementations of base {@link Collection} classes ({@link java.util.AbstractCollection}, * {@link java.util.AbstractList}, etc.) in the form of {@link Iterator}-based implementations of key methods * (e.g., {@link #equals}) </li> * </ul> */ // Comparison to Google Collections version // + uses less memory // + much less for many common cases (i.e., sizes (1-5)) // * trades some "extra" code for memory // + doesn't use offset, length impl (or even Object[] ref and instance for some sizes) // * subList impl sorda justifies this // + supports null elements // * this is of dubious value - why did they do this? block errors ? speed up impl ? // * null has a some legit uses // * their equals() and hashCode() are optimized for comparing instances to one another which could be very good // - this impl is only optimized for comparing to RandomAccess List, but still has get() and null-check overhead // but is still a step up from typical Collections implementations // + uses Iterators internally for fewer methods (e.g., contains()) - less transient allocation // - doesn't specialize serialization // * they do this very well ("explicit serialized forms, though readReplace() and writeReplace() are slower) // - doesn't use general utility impls // - Nullable, Iterators, ImmutableCollection, Collections2 // - very clean slick, comprehensive use of covariant return types // // maximally optimized methods // - get(i), isEmpty(), contains(), subList (for small sizes) // // - consider generating code for methods like get(i), subList // // - hopefully compiler won't have problems with deeply nested implementation classes // LightImmutableList → AbstractList → Singleton → Doubleton → ... // // - LightImmutableList should be an interface // - ideally above List, but for compat has to be // below it and therefore we can't remove methods from it // - could be sneaky and duplicate the methods, but this kinda sucks too public abstract class LightImmutableList<E> implements List<E>, RandomAccess { @SuppressWarnings("unchecked") public static <E> LightImmutableList<E> of() { return Nothington.INSTANCE; } public static <E> LightImmutableList<E> of(E e0) { return new Singleton<E>(e0); } public static <E> LightImmutableList<E> of(E e0, E e1) { return new Doubleton<E>(e0, e1); } public static <E> LightImmutableList<E> of(E e0, E e1, E e2) { return new Tripleton<E>(e0, e1, e2); } public static <E> LightImmutableList<E> of(E e0, E e1, E e2, E e3) { return new Quadrupleton<E>(e0, e1, e2, e3); } public static <E> LightImmutableList<E> of(E e0, E e1, E e2, E e3, E e4) { return new Quintupleton<E>(e0, e1, e2, e3, e4); } /** * Selects the most efficient implementation based on the length of {@code all} */ public static <E> LightImmutableList<E> of(E... all) { switch (all.length) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(all[0]); case 2: return LightImmutableList.of(all[0], all[1]); case 3: return LightImmutableList.of(all[0], all[1], all[2]); case 4: return LightImmutableList.of(all[0], all[1], all[2], all[3]); case 5: return LightImmutableList.of(all[0], all[1], all[2], all[3], all[4]); default: if (all.length > 5) { //return new Restleton<E>(all); return new RegularImmutableList<E>(all); } else { // this is impossible throw new IllegalStateException(); } } } public static <E> LightImmutableList<E> copyOf(final Iterable<? extends E> elements) { if (elements instanceof LightImmutableList) { @SuppressWarnings("unchecked") final LightImmutableList<E> elementsAsImmutableList = (LightImmutableList<E>) elements; return elementsAsImmutableList; } else if (elements instanceof Collection) { @SuppressWarnings("unchecked") final Collection<E> elementsAsCollection = (Collection<E>) elements; final int size = elementsAsCollection.size(); if (size == 0) { return LightImmutableList.of(); } @SuppressWarnings("unchecked") final E[] elementsAsArray = (E[]) new Object[size]; final E[] returnedElementsAsArray = elementsAsCollection.toArray(elementsAsArray); assert returnedElementsAsArray == elementsAsArray; return LightImmutableList.of(elementsAsArray); } else { final Collection<E> elementsAsCollection = new ArrayList<E>(); for (final E e : elements) { elementsAsCollection.add(e); } // recursive call return LightImmutableList.copyOf(elementsAsCollection); } } public static <E> LightImmutableList<E> copyOf(final Iterator<? extends E> elements) { if (! elements.hasNext()) { return LightImmutableList.of(); } final E e0 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0); } final E e1 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1); } final E e2 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1, e2); } final E e3 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1, e2, e3); } final E e4 = elements.next(); if (! elements.hasNext()) { return LightImmutableList.of(e0, e1, e2, e3, e4); } // give up; copy em' into temp var final Collection<E> elementsAsCollection = new ArrayList<E>(); elementsAsCollection.add(e0); elementsAsCollection.add(e1); elementsAsCollection.add(e2); elementsAsCollection.add(e3); elementsAsCollection.add(e4); do { elementsAsCollection.add(elements.next()); } while (elements.hasNext()); // recursive call return LightImmutableList.copyOf(elementsAsCollection); } private LightImmutableList() {} static boolean eq(Object obj, Object e) { return obj == null ? e == null : obj.equals(e); } // lifted from Google Collections private static Object[] copyIntoArray(Object... items) { final Object[] array = new Object[items.length]; int index = 0; for (final Object element : items) { // if (element == null) { // throw new NullPointerException("at index " + index); // } array[index++] = element; } return array; } /** * Equivalent to {@link Collections#emptyList()} */ static final class Nothington<E> extends AbstractImmutableList<E> { static final Nothington INSTANCE = new Nothington(); static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; private Nothington() { // no reason to make more than 1 of these } @Override public E get(int index) { throw new IndexOutOfBoundsException("Index: " + index); } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object obj) { return false; } @Override public boolean containsAll(Collection<?> needles) { return needles.isEmpty(); } @Override public int indexOf(Object e) { return -1; } @Override public int lastIndexOf(Object e) { return -1; } @Override public Iterator<E> iterator() { return Collections.<E>emptyList().iterator(); } @Override public ListIterator<E> listIterator() { return Collections.<E>emptyList().listIterator(); } @Override public ListIterator<E> listIterator(int index) { return Collections.<E>emptyList().listIterator(index); } @Override public LightImmutableList<E> subList(int fromIndex, int toIndex) { if (fromIndex != 0 || toIndex != 0) { throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is 0"); } return this; } @Override public Object[] toArray() { return EMPTY_OBJECT_ARRAY; } @Override public <T> T[] toArray(T[] a) { if (a.length > 0) { a[0] = null; } return a; } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { return obj instanceof List && ((List<?>) obj).isEmpty(); } @Override public String toString() { return "[]"; } private Object readResolve() { return INSTANCE; } } // end class Nothington /** * Equivalent to {@link Collections#singletonList()} */ static class Singleton<E> extends AbstractImmutableList<E> { protected final E e0; Singleton(E e0) { this.e0 = e0; } @Override public E get(int index) { // this impl looks clunky for Singleton, but pays off in Doubleton, ... switch (index) { case 0: return e0; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 1; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl return eq(obj, e0); } @Override public int indexOf(Object e) { // zero allocation vs. AbstractCollection impl return contains(e) ? 0 : -1; } @Override public int lastIndexOf(Object e) { // zero allocation vs. AbstractCollection impl return contains(e) ? 0 : -1; } /* @Override */ @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Singleton static class Doubleton<E> extends Singleton<E> { protected final E e1; Doubleton(E e0, E e1) { super(e0); this.e1 = e1; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 2; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e1); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Doubleton static class Tripleton<E> extends Doubleton<E> { protected final E e2; Tripleton(E e0, E e1, E e2) { super(e0, e1); this.e2 = e2; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; case 2: return e2; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 3; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e2); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e2)) { return 2; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e2)) { return 2; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2,3} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return LightImmutableList.of(e0, e1); case 3: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); case 3: return LightImmutableList.of(e1, e2); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); case 3: return LightImmutableList.of(e2); } case 3: switch (toIndex) { case 3: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Tripleton static class Quadrupleton<E> extends Tripleton<E> { protected final E e3; Quadrupleton(E e0, E e1, E e2, E e3) { super(e0, e1, e2); this.e3 = e3; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; case 2: return e2; case 3: return e3; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 4; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e3); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e2)) { return 2; } else if (eq(obj, e3)) { // TODO redundant null check return 3; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e3)) { return 3; // TODO redundant null check } else if (eq(obj, e2)) { return 2; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2,3,4} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return LightImmutableList.of(e0, e1); case 3: return LightImmutableList.of(e0, e1, e2); case 4: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); case 3: return LightImmutableList.of(e1, e2); case 4: return LightImmutableList.of(e1, e2, e3); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); case 3: return LightImmutableList.of(e2); case 4: return LightImmutableList.of(e2, e3); } case 3: switch (toIndex) { case 3: return LightImmutableList.of(); case 4: return LightImmutableList.of(e3); } case 4: switch (toIndex) { case 4: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Quadrupleton static class Quintupleton<E> extends Quadrupleton<E> { protected final E e4; Quintupleton(E e0, E e1, E e2, E e3, E e4) { super(e0, e1, e2, e3); this.e4 = e4; } @Override public E get(int index) { switch (index) { case 0: return e0; case 1: return e1; case 2: return e2; case 3: return e3; case 4: return e4; default: throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } } @Override public int size() { return 5; } @Override public boolean contains(Object obj) { // zero allocation vs. AbstractCollection impl // TODO redundant null check (in super.contains() impl) // TODO excessive method overhead ? (using super.contains()) return super.contains(obj) || eq(obj, e4); } @Override public int indexOf(Object obj) { if (eq(obj, e0)) { return 0; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e2)) { return 2; } else if (eq(obj, e3)) { // TODO redundant null check return 3; } else if (eq(obj, e4)) { // TODO redundant null check return 4; } else { return -1; } } @Override public int lastIndexOf(Object obj) { if (eq(obj, e4)) { return 4; // TODO redundant null check } else if (eq(obj, e3)) { return 3; // TODO redundant null check } else if (eq(obj, e2)) { return 2; // TODO redundant null check } else if (eq(obj, e1)) { return 1; // TODO redundant null check } else if (eq(obj, e0)) { return 0; } else { return -1; } } @Override @SuppressWarnings("fallthrough") public LightImmutableList<E> subList(int fromIndex, int toIndex) { // valid indices = {0,1,2,3,4,5} switch (fromIndex) { case 0: switch (toIndex) { case 0: return LightImmutableList.of(); case 1: return LightImmutableList.of(e0); case 2: return LightImmutableList.of(e0, e1); case 3: return LightImmutableList.of(e0, e1, e2); case 4: return LightImmutableList.of(e0, e1, e2, e3); case 5: return this; } case 1: switch (toIndex) { case 1: return LightImmutableList.of(); case 2: return LightImmutableList.of(e1); case 3: return LightImmutableList.of(e1, e2); case 4: return LightImmutableList.of(e1, e2, e3); case 5: return LightImmutableList.of(e1, e2, e3, e4); } case 2: switch (toIndex) { case 2: return LightImmutableList.of(); case 3: return LightImmutableList.of(e2); case 4: return LightImmutableList.of(e2, e3); case 5: return LightImmutableList.of(e2, e3, e4); } case 3: switch (toIndex) { case 3: return LightImmutableList.of(); case 4: return LightImmutableList.of(e3); case 5: return LightImmutableList.of(e3, e4); } case 4: switch (toIndex) { case 4: return LightImmutableList.of(); case 5: return LightImmutableList.of(e4); } case 5: switch (toIndex) { case 5: return LightImmutableList.of(); } } throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } } // end class Quintupleton /** * <h3> Broken (subList, etc.) impl! Do not use </h3> * Classic {@code ArrayList}-style implementation. * <p> Goal is to minimize memory requirements by avoiding begin/end fields for * common cases. * @param <E> */ @Deprecated static class Restleton<E> extends AbstractImmutableList<E> { private final Object[] items; Restleton(E[] all) { this.items = copyIntoArray(all); } public final int size() { return items.length; } // public boolean contains(Object target) { // for (int i = begin(), n = size(); i < n; i++) { // // TODO redundant null check // if (eq(items[i], target)) { // return true; // } // } // return false; // } @Override public Object[] toArray() { Object[] newArray = new Object[size()]; System.arraycopy(items, 0, newArray, 0, size()); return newArray; } @Override public <T> T[] toArray(T[] other) { if (other.length < size()) { other = newArray(other, size()); } else if (other.length > size()) { other[size()] = null; } System.arraycopy(items, 0, other, 0, size()); return other; } @SuppressWarnings("unchecked") public E get(int index) { try { return (E) items[index]; } catch(ArrayIndexOutOfBoundsException aioobe) { throw new IndexOutOfBoundsException( "Invalid index: " + index + ", list size is " + size()); } } // public int indexOf(Object target) { // for (int i = begin(), n = size(); i < n; i++) { // // TODO redundant null check // if (eq(items[i], target)) { // return i; // } // } // return -1; // } // public int lastIndexOf(Object target) { // for (int i = size() - 1; i >= begin(); i--) { // // TODO redundant null check // if (eq(items[i], target)) { // return i; // } // } // return -1; // } public LightImmutableList<E> subList(int fromIndex, int toIndex) { // - using 2 ints (b, end) and parent reference (Object(8)+4+4+parent(4) = 24 on 32-bit arch // - could optimize with b=0 and end=size() variants :) if (fromIndex < 0 || toIndex > size() || fromIndex > toIndex) { throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size()); } if (fromIndex == toIndex) { return LightImmutableList.of(); } else if (fromIndex == 0 && toIndex == size()) { return this; } else { return new SubList(fromIndex, toIndex); } } /** * Clipped view of its enclosing Restleton with a modified * - begin() * - end() * - size() */ class SubList extends AbstractImmutableList<E> { final int begin; final int end; SubList(int begin, int end) { this.begin = begin; this.end = end; System.out.println("SubList begin(): "+begin()+" end(): "+end()+" size(): "+size()); } @Override int begin() { return begin; } @Override public int end() { return end; } /* @Override */ public int size() { return end - begin; } @Override public Object[] toArray() { throw new UnsupportedOperationException("Not supported yet."); } @Override public <T> T[] toArray(T[] a) { throw new UnsupportedOperationException("Not supported yet."); } public E get(int index) { if (index < 0) { throw new IndexOutOfBoundsException(); } // index needs to be adjusted for s and end // index 0 → begin index += begin; if (index > end) { throw new IndexOutOfBoundsException(); } System.out.println("begin: "+begin+" end: "+end()+" size: "+size()+" index: "+index); return Restleton.this.get(index); } /* @Override */ public LightImmutableList<E> subList(int fromIndex, int toIndex) { // if (fromIndex < 0) { // throw new IndexOutOfBoundsException(); // } // // translate incoming indices // fromIndex += begin; // toIndex += begin; // if (toIndex > end) { // throw new IndexOutOfBoundsException(); // } // return Restleton.this.subList(fromIndex, toIndex); if (fromIndex == toIndex) { return LightImmutableList.of(); } else if (fromIndex == 0 && toIndex == size()) { return this; } else { // translate incoming indices fromIndex += begin; toIndex += begin; //return new SubList(fromIndex, toIndex); return Restleton.this.subList(fromIndex, toIndex); } } } // end class SubList } // end class Restleton /** * Classic {@code ArrayList}-style implementation. Implementation liberally copied * from Google Collections ImmutableList.RegularImmutableList * @param <E> */ private static final class RegularImmutableList<E> extends AbstractImmutableList<E> { private final int offset; private final int size; private final Object[] array; private RegularImmutableList(Object[] array, int offset, int size) { this.offset = offset; this.size = size; this.array = array; } private RegularImmutableList(Object[] array) { this(array, 0, array.length); } public int size() { return size; } @Override public Object[] toArray() { final Object[] newArray = new Object[size()]; System.arraycopy(array, offset, newArray, 0, size); return newArray; } @Override public <T> T[] toArray(T[] other) { if (other.length < size) { other = newArray(other, size); } else if (other.length > size) { other[size] = null; } System.arraycopy(array, offset, other, 0, size); return other; } // The fake cast to E is safe because the creation methods only allow E's @SuppressWarnings("unchecked") public E get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException( "Invalid index: " + index + ", list size is " + size); } return (E) array[index + offset]; } @Override public LightImmutableList<E> subList(int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) { throw new IndexOutOfBoundsException("Invalid range: " + fromIndex + ".." + toIndex + ", list size is " + size); } return (fromIndex == toIndex) ? LightImmutableList.<E>of() : new RegularImmutableList<E>( array, offset + fromIndex, toIndex - fromIndex); } } // end class RegularImmutableList /** * {@inheritDoc} * Makes covariant subList type inference work. */ public abstract LightImmutableList<E> subList(int fromIndex, int toIndex); static abstract class AbstractImmutableList<E> extends LightImmutableList<E> { // base implementation @Override public boolean contains(Object target) { for (int i = begin(), n = end(); i < n; i++) { // TODO redundant null check if (eq(get(i), target)) { return true; } } return false; } // only Nothington overrides @Override public boolean isEmpty() { return false; } public int indexOf(Object target) { for (int i = begin(), n = end(); i < n; i++) { // TODO redundant null check if (eq(get(i), target)) { return i; } } return -1; } public int lastIndexOf(Object target) { for (int i = end() - 1; i >= begin(); i--) { // TODO redundant null check if (eq(get(i), target)) { return i; } } return -1; } // only Nothington overrides @Override public Iterator<E> iterator() { return new SimpleListIterator(); } // only Nothington overrides @Override public ListIterator<E> listIterator() { return new FullListIterator(begin()); } @Override public ListIterator<E> listIterator(int index) { return new FullListIterator(index); } // only Nothington overrides @Override public boolean containsAll(Collection<?> c) { // TODO consider optimization strategies - c not necessarily a RandomAccess & List, but // we made that assumption for equals() for (final Object target : c) { if (! contains(target)) { return false; } } return true; } /** * @throws UnsupportedOperationException */ @Override public final boolean add(E e) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ public final boolean remove(Object o) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ public final boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ public final boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final E remove(int idx) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final void add(int idx, E e) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final E set(int idx, E e) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public final void clear() { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { final Object[] newArray = new Object[size()]; for (int i = begin(), n = end(); i < n; i++) { newArray[i] = get(i); } return newArray; } @Override public <T> T[] toArray(T[] other) { if (other.length < size()) { other = newArray(other, size()); } else if (other.length > size()) { other[size()] = null; } for (int i = begin(), n = end(); i < n; i++) { other[i] = (T) get(i); } return other; } /** * {@inheritDoc} * <p> <i> This implementation is optimized for comparing to {@link RandomAccess} {@link List} </i> </p> */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (! (obj instanceof List)) { return false; } final List<?> that = (List<?>) obj; if (that.size() != this.size()) { return false; } for (int i = begin(), n = this.end(); i < n; i++) { if (! eq(that.get(i), this.get(i))) { return false; } } return true; } @Override public int hashCode() { int result = 1; // optimized for RandomAaccess - zero allocation for (int i = begin(), n = end(); i < n; i++) { final E next = get(i); result = (31 * result) + (next == null ? 0 : next.hashCode()); } return result; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(size() * 16); buffer.append('[').append(get(begin())); for (int i = begin() + 1, n = end(); i < n; i++) { //System.out.println("begin(): "+begin()+" end(): "+end()+" size(): "+size()); final E next = get(i); buffer.append(", "); // there is no way to have an LightImmutableList which contains itself //if (next != this) { buffer.append(next); //} else { // buffer.append("(this LightImmutableList)"); //} } return buffer.append(']').toString(); } // name borrowed from C++ STL int begin() { return 0; } // name borrowed from C++ STL int end() { return size(); } /** * Stating the obvious: this is a non-static class so instances * have implicit {@code AbstractImmutableList.this} reference. */ // Lifted from Apache Harmony class SimpleListIterator extends UnmodifiableIterator<E> { int pos = begin() - 1; @Override public final boolean hasNext() { return pos + 1 < end(); } @Override public E next() { try { final E result = get(pos + 1); pos++; return result; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } } // end class SimpleListIterator /** * Stating the obvious: this is a non-static class so instances * have implicit {@code AbstractImmutableList.this} reference. */ // Lifted from Apache Harmony final class FullListIterator extends SimpleListIterator implements ListIterator<E> { FullListIterator(int begin) { super(); if (begin() <= begin && begin <= end()) { pos = begin - 1; } else { throw new IndexOutOfBoundsException(); } } @Override public E next() { try { final E result = get(pos + 1); ++pos; return result; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } @Override public boolean hasPrevious() { return pos >= begin(); } @Override public int nextIndex() { return pos + 1; } @Override public E previous() { try { final E result = get(pos); pos--; return result; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } @Override public int previousIndex() { return pos; } /** * @throws UnsupportedOperationException */ @Override public void add(E object) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public void set(E object) { throw new UnsupportedOperationException(); } } // end clss FullListIterator } // end class AbstractImmutableList }
minor
api/src/main/java/org/yawni/util/LightImmutableList.java
minor
<ide><path>pi/src/main/java/org/yawni/util/LightImmutableList.java <ide> /* <ide> * Copyright (C) 2007 Google Inc. <del> * <add> * <ide> * Licensed to the Apache Software Foundation (ASF) under one or more <ide> * contributor license agreements. See the NOTICE file distributed with <ide> * this work for additional information regarding copyright ownership. <ide> * This implementation is particularly useful when {@code E} is immutable (e.g., {@code String}, {@code Integer}) <ide> * (aka "deeply immutable"). <ide> * Strives for performance and memory characteristics of a C99 const array, especially for <del> * small sizes (0-5). "unrolled", "inside out" implementation for small sizes sacrifices <add> * small sizes (0-5). "unrolled", "inside out" implementation for small sizes sacrifices <ide> * verbosity for space (and probably asks more of the compiler, but who cares). <ide> * <ide> * Uses cases: <ide> * TODO <ide> * - make this class package private and move it accordingly ? just an implementation detail for now <ide> * - take another crack at Restleton <del> * - run Google Collections test suite on it <add> * - run Google Guava test suite on it <ide> * - copy Serializable functionality <ide> * <ide> * <p> Random notes <ide> // <ide> // maximally optimized methods <ide> // - get(i), isEmpty(), contains(), subList (for small sizes) <del>// <add>// <ide> // - consider generating code for methods like get(i), subList <ide> // <ide> // - hopefully compiler won't have problems with deeply nested implementation classes <ide> + ".." + toIndex + ", list size is " + size()); <ide> } <ide> } // end class Singleton <del> <add> <ide> static class Doubleton<E> extends Singleton<E> { <ide> protected final E e1; <ide> Doubleton(E e0, E e1) { <ide> } <ide> } // end class SubList <ide> } // end class Restleton <del> <add> <ide> /** <ide> * Classic {@code ArrayList}-style implementation. Implementation liberally copied <ide> * from Google Collections ImmutableList.RegularImmutableList <ide> public final void clear() { <ide> throw new UnsupportedOperationException(); <ide> } <del> <add> <ide> @Override <ide> public Object[] toArray() { <ide> final Object[] newArray = new Object[size()];
Java
apache-2.0
315179abe22af03927b3dd4ff396fc751903ee09
0
donNewtonAlpha/onos,y-higuchi/onos,kuujo/onos,mengmoya/onos,maheshraju-Huawei/actn,LorenzReinhart/ONOSnew,donNewtonAlpha/onos,sonu283304/onos,LorenzReinhart/ONOSnew,opennetworkinglab/onos,osinstom/onos,gkatsikas/onos,sonu283304/onos,Shashikanth-Huawei/bmp,LorenzReinhart/ONOSnew,osinstom/onos,VinodKumarS-Huawei/ietf96yang,osinstom/onos,gkatsikas/onos,sdnwiselab/onos,oplinkoms/onos,mengmoya/onos,gkatsikas/onos,opennetworkinglab/onos,kuujo/onos,kuujo/onos,y-higuchi/onos,opennetworkinglab/onos,sdnwiselab/onos,VinodKumarS-Huawei/ietf96yang,osinstom/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,lsinfo3/onos,donNewtonAlpha/onos,y-higuchi/onos,mengmoya/onos,kuujo/onos,gkatsikas/onos,gkatsikas/onos,sdnwiselab/onos,VinodKumarS-Huawei/ietf96yang,kuujo/onos,oplinkoms/onos,maheshraju-Huawei/actn,mengmoya/onos,sdnwiselab/onos,opennetworkinglab/onos,oplinkoms/onos,Shashikanth-Huawei/bmp,oplinkoms/onos,maheshraju-Huawei/actn,sdnwiselab/onos,lsinfo3/onos,oplinkoms/onos,Shashikanth-Huawei/bmp,maheshraju-Huawei/actn,donNewtonAlpha/onos,donNewtonAlpha/onos,y-higuchi/onos,kuujo/onos,VinodKumarS-Huawei/ietf96yang,osinstom/onos,maheshraju-Huawei/actn,mengmoya/onos,kuujo/onos,sonu283304/onos,y-higuchi/onos,sonu283304/onos,LorenzReinhart/ONOSnew,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,opennetworkinglab/onos,LorenzReinhart/ONOSnew,lsinfo3/onos,lsinfo3/onos,oplinkoms/onos,oplinkoms/onos,sdnwiselab/onos,gkatsikas/onos
/* * Copyright 2015-2016 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.newresource.impl; import com.google.common.annotations.Beta; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.util.GuavaCollectors; import org.onlab.util.Tools; import org.onosproject.net.newresource.ContinuousResource; import org.onosproject.net.newresource.ContinuousResourceId; import org.onosproject.net.newresource.DiscreteResource; import org.onosproject.net.newresource.DiscreteResourceId; import org.onosproject.net.newresource.ResourceAllocation; import org.onosproject.net.newresource.ResourceConsumer; import org.onosproject.net.newresource.ResourceEvent; import org.onosproject.net.newresource.ResourceId; import org.onosproject.net.newresource.Resource; import org.onosproject.net.newresource.ResourceStore; import org.onosproject.net.newresource.ResourceStoreDelegate; import org.onosproject.net.newresource.Resources; import org.onosproject.store.AbstractStore; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.ConsistentMap; import org.onosproject.store.service.ConsistentMapException; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.StorageService; import org.onosproject.store.service.TransactionContext; import org.onosproject.store.service.TransactionalMap; import org.onosproject.store.service.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.net.newresource.ResourceEvent.Type.*; /** * Implementation of ResourceStore using TransactionalMap. */ @Component(immediate = true) @Service @Beta public class ConsistentResourceStore extends AbstractStore<ResourceEvent, ResourceStoreDelegate> implements ResourceStore { private static final Logger log = LoggerFactory.getLogger(ConsistentResourceStore.class); private static final String DISCRETE_CONSUMER_MAP = "onos-discrete-consumers"; private static final String CONTINUOUS_CONSUMER_MAP = "onos-continuous-consumers"; private static final String CHILD_MAP = "onos-resource-children"; private static final Serializer SERIALIZER = Serializer.using( Arrays.asList(KryoNamespaces.BASIC, KryoNamespaces.API), ContinuousResourceAllocation.class); // TODO: We should provide centralized values for this private static final int MAX_RETRIES = 5; private static final int RETRY_DELAY = 1_000; // millis @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected StorageService service; private ConsistentMap<DiscreteResourceId, ResourceConsumer> discreteConsumers; private ConsistentMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumers; private ConsistentMap<DiscreteResourceId, Set<Resource>> childMap; @Activate public void activate() { discreteConsumers = service.<DiscreteResourceId, ResourceConsumer>consistentMapBuilder() .withName(DISCRETE_CONSUMER_MAP) .withSerializer(SERIALIZER) .build(); continuousConsumers = service.<ContinuousResourceId, ContinuousResourceAllocation>consistentMapBuilder() .withName(CONTINUOUS_CONSUMER_MAP) .withSerializer(SERIALIZER) .build(); childMap = service.<DiscreteResourceId, Set<Resource>>consistentMapBuilder() .withName(CHILD_MAP) .withSerializer(SERIALIZER) .build(); Tools.retryable(() -> childMap.put(Resource.ROOT.id(), new LinkedHashSet<>()), ConsistentMapException.class, MAX_RETRIES, RETRY_DELAY); log.info("Started"); } // Computational complexity: O(1) if the resource is discrete type. // O(n) if the resource is continuous type where n is the number of the existing allocations for the resource @Override public List<ResourceAllocation> getResourceAllocations(ResourceId id) { checkNotNull(id); checkArgument(id instanceof DiscreteResourceId || id instanceof ContinuousResourceId); if (id instanceof DiscreteResourceId) { return getResourceAllocations((DiscreteResourceId) id); } else { return getResourceAllocations((ContinuousResourceId) id); } } // computational complexity: O(1) private List<ResourceAllocation> getResourceAllocations(DiscreteResourceId resource) { Versioned<ResourceConsumer> consumer = discreteConsumers.get(resource); if (consumer == null) { return ImmutableList.of(); } return ImmutableList.of(new ResourceAllocation(Resources.discrete(resource).resource(), consumer.value())); } // computational complexity: O(n) where n is the number of the existing allocations for the resource private List<ResourceAllocation> getResourceAllocations(ContinuousResourceId resource) { Versioned<ContinuousResourceAllocation> allocations = continuousConsumers.get(resource); if (allocations == null) { return ImmutableList.of(); } return allocations.value().allocations().stream() .filter(x -> x.resource().id().equals(resource)) .collect(GuavaCollectors.toImmutableList()); } @Override public boolean register(List<Resource> resources) { checkNotNull(resources); if (log.isTraceEnabled()) { resources.forEach(r -> log.trace("registering {}", r)); } TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap = tx.getTransactionalMap(CHILD_MAP, SERIALIZER); // the order is preserved by LinkedHashMap Map<DiscreteResource, List<Resource>> resourceMap = resources.stream() .filter(x -> x.parent().isPresent()) .collect(Collectors.groupingBy(x -> x.parent().get(), LinkedHashMap::new, Collectors.toList())); for (Map.Entry<DiscreteResource, List<Resource>> entry: resourceMap.entrySet()) { if (!lookup(childTxMap, entry.getKey().id()).isPresent()) { return abortTransaction(tx); } if (!appendValues(childTxMap, entry.getKey().id(), entry.getValue())) { return abortTransaction(tx); } } boolean success = tx.commit(); if (success) { List<ResourceEvent> events = resources.stream() .filter(x -> x.parent().isPresent()) .map(x -> new ResourceEvent(RESOURCE_ADDED, x)) .collect(Collectors.toList()); notifyDelegate(events); } return success; } @Override public boolean unregister(List<ResourceId> ids) { checkNotNull(ids); TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap = tx.getTransactionalMap(CHILD_MAP, SERIALIZER); TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap = tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER); TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap = tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER); // Look up resources by resource IDs List<Resource> resources = ids.stream() .filter(x -> x.parent().isPresent()) .map(x -> { // avoid access to consistent map in the case of discrete resource if (x instanceof DiscreteResourceId) { return Optional.of(Resources.discrete((DiscreteResourceId) x).resource()); } else { return lookup(childTxMap, x); } }) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); // the order is preserved by LinkedHashMap Map<DiscreteResourceId, List<Resource>> resourceMap = resources.stream() .collect(Collectors.groupingBy(x -> x.parent().get().id(), LinkedHashMap::new, Collectors.toList())); // even if one of the resources is allocated to a consumer, // all unregistrations are regarded as failure for (Map.Entry<DiscreteResourceId, List<Resource>> entry: resourceMap.entrySet()) { boolean allocated = entry.getValue().stream().anyMatch(x -> { if (x instanceof DiscreteResource) { return discreteConsumerTxMap.get(((DiscreteResource) x).id()) != null; } else if (x instanceof ContinuousResource) { ContinuousResourceAllocation allocations = continuousConsumerTxMap.get(((ContinuousResource) x).id()); return allocations != null && !allocations.allocations().isEmpty(); } else { return false; } }); if (allocated) { log.warn("Failed to unregister {}: allocation exists", entry.getKey()); return abortTransaction(tx); } if (!removeValues(childTxMap, entry.getKey(), entry.getValue())) { log.warn("Failed to unregister {}: Failed to remove {} values.", entry.getKey(), entry.getValue().size()); log.debug("Failed to unregister {}: Failed to remove values: {}", entry.getKey(), entry.getValue()); return abortTransaction(tx); } } boolean success = tx.commit(); if (success) { List<ResourceEvent> events = resources.stream() .filter(x -> x.parent().isPresent()) .map(x -> new ResourceEvent(RESOURCE_REMOVED, x)) .collect(Collectors.toList()); notifyDelegate(events); } else { log.warn("Failed to unregister {}: Commit failed.", ids); } return success; } @Override public boolean allocate(List<Resource> resources, ResourceConsumer consumer) { checkNotNull(resources); checkNotNull(consumer); TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap = tx.getTransactionalMap(CHILD_MAP, SERIALIZER); TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap = tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER); TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap = tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER); for (Resource resource: resources) { // if the resource is not registered, then abort Optional<Resource> lookedUp = lookup(childTxMap, resource.id()); if (!lookedUp.isPresent()) { return abortTransaction(tx); } if (resource instanceof DiscreteResource) { ResourceConsumer oldValue = discreteConsumerTxMap.put(((DiscreteResource) resource).id(), consumer); if (oldValue != null) { return abortTransaction(tx); } } else if (resource instanceof ContinuousResource) { // Down cast: this must be safe as ContinuousResource is associated with ContinuousResourceId ContinuousResource continuous = (ContinuousResource) lookedUp.get(); ContinuousResourceAllocation allocations = continuousConsumerTxMap.get(continuous.id()); if (!hasEnoughResource(continuous, (ContinuousResource) resource, allocations)) { return abortTransaction(tx); } boolean success = appendValue(continuousConsumerTxMap, continuous, new ResourceAllocation(continuous, consumer)); if (!success) { return abortTransaction(tx); } } } return tx.commit(); } @Override public boolean release(List<ResourceAllocation> allocations) { checkNotNull(allocations); TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap = tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER); TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap = tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER); for (ResourceAllocation allocation : allocations) { Resource resource = allocation.resource(); ResourceConsumer consumer = allocation.consumer(); if (resource instanceof DiscreteResource) { // if this single release fails (because the resource is allocated to another consumer, // the whole release fails if (!discreteConsumerTxMap.remove(((DiscreteResource) resource).id(), consumer)) { return abortTransaction(tx); } } else if (resource instanceof ContinuousResource) { ContinuousResource continuous = (ContinuousResource) resource; ContinuousResourceAllocation continuousAllocation = continuousConsumerTxMap.get(continuous.id()); ImmutableList<ResourceAllocation> newAllocations = continuousAllocation.allocations().stream() .filter(x -> !(x.consumer().equals(consumer) && ((ContinuousResource) x.resource()).value() == continuous.value())) .collect(GuavaCollectors.toImmutableList()); if (!continuousConsumerTxMap.replace(continuous.id(), continuousAllocation, new ContinuousResourceAllocation(continuousAllocation.original(), newAllocations))) { return abortTransaction(tx); } } } return tx.commit(); } // computational complexity: O(1) if the resource is discrete type. // O(n) if the resource is continuous type where n is the number of the children of // the specified resource's parent @Override public boolean isAvailable(Resource resource) { checkNotNull(resource); checkArgument(resource instanceof DiscreteResource || resource instanceof ContinuousResource); if (resource instanceof DiscreteResource) { // check if already consumed return getResourceAllocations(resource.id()).isEmpty(); } else { return isAvailable((ContinuousResource) resource); } } // computational complexity: O(n) where n is the number of existing allocations for the resource private boolean isAvailable(ContinuousResource resource) { // check if it's registered or not. Versioned<Set<Resource>> children = childMap.get(resource.parent().get().id()); if (children == null) { return false; } ContinuousResource registered = children.value().stream() .filter(c -> c.id().equals(resource.id())) .findFirst() .map(c -> (ContinuousResource) c) .get(); if (registered.value() < resource.value()) { // Capacity < requested, can never satisfy return false; } // check if there's enough left Versioned<ContinuousResourceAllocation> allocation = continuousConsumers.get(resource.id()); if (allocation == null) { // no allocation (=no consumer) full registered resources available return true; } return hasEnoughResource(allocation.value().original(), resource, allocation.value()); } // computational complexity: O(n + m) where n is the number of entries in discreteConsumers // and m is the number of allocations for all continuous resources @Override public Collection<Resource> getResources(ResourceConsumer consumer) { checkNotNull(consumer); // NOTE: getting all entries may become performance bottleneck // TODO: revisit for better backend data structure Stream<DiscreteResource> discreteStream = discreteConsumers.entrySet().stream() .filter(x -> x.getValue().value().equals(consumer)) .map(Map.Entry::getKey) .map(x -> Resources.discrete(x).resource()); Stream<ContinuousResource> continuousStream = continuousConsumers.values().stream() .flatMap(x -> x.value().allocations().stream() .map(y -> Maps.immutableEntry(x.value().original(), y))) .filter(x -> x.getValue().consumer().equals(consumer)) .map(x -> x.getKey()); return Stream.concat(discreteStream, continuousStream).collect(Collectors.toList()); } // computational complexity: O(1) @Override public Set<Resource> getChildResources(DiscreteResourceId parent) { checkNotNull(parent); Versioned<Set<Resource>> children = childMap.get(parent); if (children == null) { return ImmutableSet.of(); } return children.value(); } // computational complexity: O(n) where n is the number of the children of the parent @Override public <T> Collection<Resource> getAllocatedResources(DiscreteResourceId parent, Class<T> cls) { checkNotNull(parent); checkNotNull(cls); Versioned<Set<Resource>> children = childMap.get(parent); if (children == null) { return ImmutableList.of(); } Stream<DiscreteResource> discrete = children.value().stream() .filter(x -> x.isTypeOf(cls)) .filter(x -> x instanceof DiscreteResource) .map(x -> ((DiscreteResource) x)) .filter(x -> discreteConsumers.containsKey(x.id())); Stream<ContinuousResource> continuous = children.value().stream() .filter(x -> x.id().equals(parent.child(cls))) .filter(x -> x instanceof ContinuousResource) .map(x -> (ContinuousResource) x) // we don't use cascading simple predicates like follows to reduce accesses to consistent map // .filter(x -> continuousConsumers.containsKey(x.id())) // .filter(x -> continuousConsumers.get(x.id()) != null) // .filter(x -> !continuousConsumers.get(x.id()).value().allocations().isEmpty()); .filter(resource -> { Versioned<ContinuousResourceAllocation> allocation = continuousConsumers.get(resource.id()); if (allocation == null) { return false; } return !allocation.value().allocations().isEmpty(); }); return Stream.concat(discrete, continuous).collect(Collectors.toList()); } /** * Abort the transaction. * * @param tx transaction context * @return always false */ private boolean abortTransaction(TransactionContext tx) { tx.abort(); return false; } // Appends the specified ResourceAllocation to the existing values stored in the map // computational complexity: O(n) where n is the number of the elements in the associated allocation private boolean appendValue(TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> map, ContinuousResource original, ResourceAllocation value) { ContinuousResourceAllocation oldValue = map.putIfAbsent(original.id(), new ContinuousResourceAllocation(original, ImmutableList.of(value))); if (oldValue == null) { return true; } if (oldValue.allocations().contains(value)) { // don't write to map because all values are already stored return true; } ContinuousResourceAllocation newValue = new ContinuousResourceAllocation(original, ImmutableList.<ResourceAllocation>builder() .addAll(oldValue.allocations()) .add(value) .build()); return map.replace(original.id(), oldValue, newValue); } /** * Appends the values to the existing values associated with the specified key. * If the map already has all the given values, appending will not happen. * * @param map map holding multiple values for a key * @param key key specifying values * @param values values to be appended * @return true if the operation succeeds, false otherwise. */ // computational complexity: O(n) where n is the number of the specified value private boolean appendValues(TransactionalMap<DiscreteResourceId, Set<Resource>> map, DiscreteResourceId key, List<Resource> values) { Set<Resource> oldValues = map.putIfAbsent(key, new LinkedHashSet<>(values)); if (oldValues == null) { return true; } Set<ResourceId> oldIds = oldValues.stream() .map(Resource::id) .collect(Collectors.toSet()); // values whose IDs don't match any IDs of oldValues Set<Resource> addedValues = values.stream() .filter(x -> !oldIds.contains(x.id())) .collect(Collectors.toCollection(LinkedHashSet::new)); // no new ID, then no-op if (addedValues.isEmpty()) { // don't write to map because all values are already stored return true; } LinkedHashSet<Resource> newValues = new LinkedHashSet<>(oldValues); newValues.addAll(addedValues); return map.replace(key, oldValues, newValues); } /** * Removes the values from the existing values associated with the specified key. * If the map doesn't contain the given values, removal will not happen. * * @param map map holding multiple values for a key * @param key key specifying values * @param values values to be removed * @return true if the operation succeeds, false otherwise */ // computational complexity: O(n) where n is the number of the specified values private boolean removeValues(TransactionalMap<DiscreteResourceId, Set<Resource>> map, DiscreteResourceId key, List<Resource> values) { Set<Resource> oldValues = map.putIfAbsent(key, new LinkedHashSet<>()); if (oldValues == null) { log.trace("No-Op removing values. key {} did not exist", key); return true; } if (values.stream().allMatch(x -> !oldValues.contains(x))) { // don't write map because none of the values are stored log.trace("No-Op removing values. key {} did not contain {}", key, values); return true; } LinkedHashSet<Resource> newValues = new LinkedHashSet<>(oldValues); newValues.removeAll(values); return map.replace(key, oldValues, newValues); } /** * Returns the resource which has the same key as the specified resource ID * in the set as a value of the map. * * @param childTxMap map storing parent - child relationship of resources * @param id ID of resource to be checked * @return the resource which is regarded as the same as the specified resource */ // Naive implementation, which traverses all elements in the set when continuous resource // computational complexity: O(1) when discrete resource. O(n) when continuous resource // where n is the number of elements in the associated set private Optional<Resource> lookup(TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap, ResourceId id) { if (!id.parent().isPresent()) { return Optional.of(Resource.ROOT); } Set<Resource> values = childTxMap.get(id.parent().get()); if (values == null) { return Optional.empty(); } // short-circuit if discrete resource // check the existence in the set: O(1) operation if (id instanceof DiscreteResourceId) { DiscreteResource discrete = Resources.discrete((DiscreteResourceId) id).resource(); if (values.contains(discrete)) { return Optional.of(discrete); } else { return Optional.empty(); } } // continuous resource case // iterate over the values in the set: O(n) operation return values.stream() .filter(x -> x.id().equals(id)) .findFirst(); } /** * Checks if there is enough resource volume to allocated the requested resource * against the specified resource. * * @param original original resource * @param request requested resource * @param allocation current allocation of the resource * @return true if there is enough resource volume. Otherwise, false. */ // computational complexity: O(n) where n is the number of allocations private boolean hasEnoughResource(ContinuousResource original, ContinuousResource request, ContinuousResourceAllocation allocation) { if (allocation == null) { return request.value() <= original.value(); } double allocated = allocation.allocations().stream() .filter(x -> x.resource() instanceof ContinuousResource) .map(x -> (ContinuousResource) x.resource()) .mapToDouble(ContinuousResource::value) .sum(); double left = original.value() - allocated; return request.value() <= left; } // internal use only private static final class ContinuousResourceAllocation { private final ContinuousResource original; private final ImmutableList<ResourceAllocation> allocations; private ContinuousResourceAllocation(ContinuousResource original, ImmutableList<ResourceAllocation> allocations) { this.original = original; this.allocations = allocations; } private ContinuousResource original() { return original; } private ImmutableList<ResourceAllocation> allocations() { return allocations; } } }
core/store/dist/src/main/java/org/onosproject/store/newresource/impl/ConsistentResourceStore.java
/* * Copyright 2015-2016 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.newresource.impl; import com.google.common.annotations.Beta; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.util.GuavaCollectors; import org.onlab.util.Tools; import org.onosproject.net.newresource.ContinuousResource; import org.onosproject.net.newresource.ContinuousResourceId; import org.onosproject.net.newresource.DiscreteResource; import org.onosproject.net.newresource.DiscreteResourceId; import org.onosproject.net.newresource.ResourceAllocation; import org.onosproject.net.newresource.ResourceConsumer; import org.onosproject.net.newresource.ResourceEvent; import org.onosproject.net.newresource.ResourceId; import org.onosproject.net.newresource.Resource; import org.onosproject.net.newresource.ResourceStore; import org.onosproject.net.newresource.ResourceStoreDelegate; import org.onosproject.net.newresource.Resources; import org.onosproject.store.AbstractStore; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.ConsistentMap; import org.onosproject.store.service.ConsistentMapException; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.StorageService; import org.onosproject.store.service.TransactionContext; import org.onosproject.store.service.TransactionalMap; import org.onosproject.store.service.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.net.newresource.ResourceEvent.Type.*; /** * Implementation of ResourceStore using TransactionalMap. */ @Component(immediate = true) @Service @Beta public class ConsistentResourceStore extends AbstractStore<ResourceEvent, ResourceStoreDelegate> implements ResourceStore { private static final Logger log = LoggerFactory.getLogger(ConsistentResourceStore.class); private static final String DISCRETE_CONSUMER_MAP = "onos-discrete-consumers"; private static final String CONTINUOUS_CONSUMER_MAP = "onos-continuous-consumers"; private static final String CHILD_MAP = "onos-resource-children"; private static final Serializer SERIALIZER = Serializer.using( Arrays.asList(KryoNamespaces.BASIC, KryoNamespaces.API), ContinuousResourceAllocation.class); // TODO: We should provide centralized values for this private static final int MAX_RETRIES = 5; private static final int RETRY_DELAY = 1_000; // millis @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected StorageService service; private ConsistentMap<DiscreteResourceId, ResourceConsumer> discreteConsumers; private ConsistentMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumers; private ConsistentMap<DiscreteResourceId, Set<Resource>> childMap; @Activate public void activate() { discreteConsumers = service.<DiscreteResourceId, ResourceConsumer>consistentMapBuilder() .withName(DISCRETE_CONSUMER_MAP) .withSerializer(SERIALIZER) .build(); continuousConsumers = service.<ContinuousResourceId, ContinuousResourceAllocation>consistentMapBuilder() .withName(CONTINUOUS_CONSUMER_MAP) .withSerializer(SERIALIZER) .build(); childMap = service.<DiscreteResourceId, Set<Resource>>consistentMapBuilder() .withName(CHILD_MAP) .withSerializer(SERIALIZER) .build(); Tools.retryable(() -> childMap.put(Resource.ROOT.id(), new LinkedHashSet<>()), ConsistentMapException.class, MAX_RETRIES, RETRY_DELAY); log.info("Started"); } // Computational complexity: O(1) if the resource is discrete type. // O(n) if the resource is continuous type where n is the number of the existing allocations for the resource @Override public List<ResourceAllocation> getResourceAllocations(ResourceId id) { checkNotNull(id); checkArgument(id instanceof DiscreteResourceId || id instanceof ContinuousResourceId); if (id instanceof DiscreteResourceId) { return getResourceAllocations((DiscreteResourceId) id); } else { return getResourceAllocations((ContinuousResourceId) id); } } // computational complexity: O(1) private List<ResourceAllocation> getResourceAllocations(DiscreteResourceId resource) { Versioned<ResourceConsumer> consumer = discreteConsumers.get(resource); if (consumer == null) { return ImmutableList.of(); } return ImmutableList.of(new ResourceAllocation(Resources.discrete(resource).resource(), consumer.value())); } // computational complexity: O(n) where n is the number of the existing allocations for the resource private List<ResourceAllocation> getResourceAllocations(ContinuousResourceId resource) { Versioned<ContinuousResourceAllocation> allocations = continuousConsumers.get(resource); if (allocations == null) { return ImmutableList.of(); } return allocations.value().allocations().stream() .filter(x -> x.resource().id().equals(resource)) .collect(GuavaCollectors.toImmutableList()); } @Override public boolean register(List<Resource> resources) { checkNotNull(resources); if (log.isTraceEnabled()) { resources.forEach(r -> log.trace("registering {}", r)); } TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap = tx.getTransactionalMap(CHILD_MAP, SERIALIZER); // the order is preserved by LinkedHashMap Map<DiscreteResource, List<Resource>> resourceMap = resources.stream() .filter(x -> x.parent().isPresent()) .collect(Collectors.groupingBy(x -> x.parent().get(), LinkedHashMap::new, Collectors.toList())); for (Map.Entry<DiscreteResource, List<Resource>> entry: resourceMap.entrySet()) { if (!lookup(childTxMap, entry.getKey().id()).isPresent()) { return abortTransaction(tx); } if (!appendValues(childTxMap, entry.getKey().id(), entry.getValue())) { return abortTransaction(tx); } } boolean success = tx.commit(); if (success) { List<ResourceEvent> events = resources.stream() .filter(x -> x.parent().isPresent()) .map(x -> new ResourceEvent(RESOURCE_ADDED, x)) .collect(Collectors.toList()); notifyDelegate(events); } return success; } @Override public boolean unregister(List<ResourceId> ids) { checkNotNull(ids); TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap = tx.getTransactionalMap(CHILD_MAP, SERIALIZER); TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap = tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER); TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap = tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER); // Look up resources by resource IDs List<Resource> resources = ids.stream() .filter(x -> x.parent().isPresent()) .map(x -> { // avoid access to consistent map in the case of discrete resource if (x instanceof DiscreteResourceId) { return Optional.of(Resources.discrete((DiscreteResourceId) x).resource()); } else { return lookup(childTxMap, x); } }) .flatMap(Tools::stream) .collect(Collectors.toList()); // the order is preserved by LinkedHashMap Map<DiscreteResourceId, List<Resource>> resourceMap = resources.stream() .collect(Collectors.groupingBy(x -> x.parent().get().id(), LinkedHashMap::new, Collectors.toList())); // even if one of the resources is allocated to a consumer, // all unregistrations are regarded as failure for (Map.Entry<DiscreteResourceId, List<Resource>> entry: resourceMap.entrySet()) { boolean allocated = entry.getValue().stream().anyMatch(x -> { if (x instanceof DiscreteResource) { return discreteConsumerTxMap.get(((DiscreteResource) x).id()) != null; } else if (x instanceof ContinuousResource) { ContinuousResourceAllocation allocations = continuousConsumerTxMap.get(((ContinuousResource) x).id()); return allocations != null && !allocations.allocations().isEmpty(); } else { return false; } }); if (allocated) { log.warn("Failed to unregister {}: allocation exists", entry.getKey()); return abortTransaction(tx); } if (!removeValues(childTxMap, entry.getKey(), entry.getValue())) { log.warn("Failed to unregister {}: Failed to remove {} values.", entry.getKey(), entry.getValue().size()); log.debug("Failed to unregister {}: Failed to remove values: {}", entry.getKey(), entry.getValue()); return abortTransaction(tx); } } boolean success = tx.commit(); if (success) { List<ResourceEvent> events = resources.stream() .filter(x -> x.parent().isPresent()) .map(x -> new ResourceEvent(RESOURCE_REMOVED, x)) .collect(Collectors.toList()); notifyDelegate(events); } else { log.warn("Failed to unregister {}: Commit failed.", ids); } return success; } @Override public boolean allocate(List<Resource> resources, ResourceConsumer consumer) { checkNotNull(resources); checkNotNull(consumer); TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap = tx.getTransactionalMap(CHILD_MAP, SERIALIZER); TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap = tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER); TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap = tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER); for (Resource resource: resources) { // if the resource is not registered, then abort Optional<Resource> lookedUp = lookup(childTxMap, resource.id()); if (!lookedUp.isPresent()) { return abortTransaction(tx); } if (resource instanceof DiscreteResource) { ResourceConsumer oldValue = discreteConsumerTxMap.put(((DiscreteResource) resource).id(), consumer); if (oldValue != null) { return abortTransaction(tx); } } else if (resource instanceof ContinuousResource) { // Down cast: this must be safe as ContinuousResource is associated with ContinuousResourceId ContinuousResource continuous = (ContinuousResource) lookedUp.get(); ContinuousResourceAllocation allocations = continuousConsumerTxMap.get(continuous.id()); if (!hasEnoughResource(continuous, (ContinuousResource) resource, allocations)) { return abortTransaction(tx); } boolean success = appendValue(continuousConsumerTxMap, continuous, new ResourceAllocation(continuous, consumer)); if (!success) { return abortTransaction(tx); } } } return tx.commit(); } @Override public boolean release(List<ResourceAllocation> allocations) { checkNotNull(allocations); TransactionContext tx = service.transactionContextBuilder().build(); tx.begin(); TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap = tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER); TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap = tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER); for (ResourceAllocation allocation : allocations) { Resource resource = allocation.resource(); ResourceConsumer consumer = allocation.consumer(); if (resource instanceof DiscreteResource) { // if this single release fails (because the resource is allocated to another consumer, // the whole release fails if (!discreteConsumerTxMap.remove(((DiscreteResource) resource).id(), consumer)) { return abortTransaction(tx); } } else if (resource instanceof ContinuousResource) { ContinuousResource continuous = (ContinuousResource) resource; ContinuousResourceAllocation continuousAllocation = continuousConsumerTxMap.get(continuous.id()); ImmutableList<ResourceAllocation> newAllocations = continuousAllocation.allocations().stream() .filter(x -> !(x.consumer().equals(consumer) && ((ContinuousResource) x.resource()).value() == continuous.value())) .collect(GuavaCollectors.toImmutableList()); if (!continuousConsumerTxMap.replace(continuous.id(), continuousAllocation, new ContinuousResourceAllocation(continuousAllocation.original(), newAllocations))) { return abortTransaction(tx); } } } return tx.commit(); } // computational complexity: O(1) if the resource is discrete type. // O(n) if the resource is continuous type where n is the number of the children of // the specified resource's parent @Override public boolean isAvailable(Resource resource) { checkNotNull(resource); checkArgument(resource instanceof DiscreteResource || resource instanceof ContinuousResource); if (resource instanceof DiscreteResource) { // check if already consumed return getResourceAllocations(resource.id()).isEmpty(); } else { return isAvailable((ContinuousResource) resource); } } // computational complexity: O(n) where n is the number of existing allocations for the resource private boolean isAvailable(ContinuousResource resource) { // check if it's registered or not. Versioned<Set<Resource>> children = childMap.get(resource.parent().get().id()); if (children == null) { return false; } ContinuousResource registered = children.value().stream() .filter(c -> c.id().equals(resource.id())) .findFirst() .map(c -> (ContinuousResource) c) .get(); if (registered.value() < resource.value()) { // Capacity < requested, can never satisfy return false; } // check if there's enough left Versioned<ContinuousResourceAllocation> allocation = continuousConsumers.get(resource.id()); if (allocation == null) { // no allocation (=no consumer) full registered resources available return true; } return hasEnoughResource(allocation.value().original(), resource, allocation.value()); } // computational complexity: O(n + m) where n is the number of entries in discreteConsumers // and m is the number of allocations for all continuous resources @Override public Collection<Resource> getResources(ResourceConsumer consumer) { checkNotNull(consumer); // NOTE: getting all entries may become performance bottleneck // TODO: revisit for better backend data structure Stream<DiscreteResource> discreteStream = discreteConsumers.entrySet().stream() .filter(x -> x.getValue().value().equals(consumer)) .map(Map.Entry::getKey) .map(x -> Resources.discrete(x).resource()); Stream<ContinuousResource> continuousStream = continuousConsumers.values().stream() .flatMap(x -> x.value().allocations().stream() .map(y -> Maps.immutableEntry(x.value().original(), y))) .filter(x -> x.getValue().consumer().equals(consumer)) .map(x -> x.getKey()); return Stream.concat(discreteStream, continuousStream).collect(Collectors.toList()); } // computational complexity: O(1) @Override public Set<Resource> getChildResources(DiscreteResourceId parent) { checkNotNull(parent); Versioned<Set<Resource>> children = childMap.get(parent); if (children == null) { return ImmutableSet.of(); } return children.value(); } // computational complexity: O(n) where n is the number of the children of the parent @Override public <T> Collection<Resource> getAllocatedResources(DiscreteResourceId parent, Class<T> cls) { checkNotNull(parent); checkNotNull(cls); Versioned<Set<Resource>> children = childMap.get(parent); if (children == null) { return ImmutableList.of(); } Stream<DiscreteResource> discrete = children.value().stream() .filter(x -> x.isTypeOf(cls)) .filter(x -> x instanceof DiscreteResource) .map(x -> ((DiscreteResource) x)) .filter(x -> discreteConsumers.containsKey(x.id())); Stream<ContinuousResource> continuous = children.value().stream() .filter(x -> x.id().equals(parent.child(cls))) .filter(x -> x instanceof ContinuousResource) .map(x -> (ContinuousResource) x) // we don't use cascading simple predicates like follows to reduce accesses to consistent map // .filter(x -> continuousConsumers.containsKey(x.id())) // .filter(x -> continuousConsumers.get(x.id()) != null) // .filter(x -> !continuousConsumers.get(x.id()).value().allocations().isEmpty()); .filter(resource -> { Versioned<ContinuousResourceAllocation> allocation = continuousConsumers.get(resource.id()); if (allocation == null) { return false; } return !allocation.value().allocations().isEmpty(); }); return Stream.concat(discrete, continuous).collect(Collectors.toList()); } /** * Abort the transaction. * * @param tx transaction context * @return always false */ private boolean abortTransaction(TransactionContext tx) { tx.abort(); return false; } // Appends the specified ResourceAllocation to the existing values stored in the map // computational complexity: O(n) where n is the number of the elements in the associated allocation private boolean appendValue(TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> map, ContinuousResource original, ResourceAllocation value) { ContinuousResourceAllocation oldValue = map.putIfAbsent(original.id(), new ContinuousResourceAllocation(original, ImmutableList.of(value))); if (oldValue == null) { return true; } if (oldValue.allocations().contains(value)) { // don't write to map because all values are already stored return true; } ContinuousResourceAllocation newValue = new ContinuousResourceAllocation(original, ImmutableList.<ResourceAllocation>builder() .addAll(oldValue.allocations()) .add(value) .build()); return map.replace(original.id(), oldValue, newValue); } /** * Appends the values to the existing values associated with the specified key. * If the map already has all the given values, appending will not happen. * * @param map map holding multiple values for a key * @param key key specifying values * @param values values to be appended * @return true if the operation succeeds, false otherwise. */ // computational complexity: O(n) where n is the number of the specified value private boolean appendValues(TransactionalMap<DiscreteResourceId, Set<Resource>> map, DiscreteResourceId key, List<Resource> values) { Set<Resource> oldValues = map.putIfAbsent(key, new LinkedHashSet<>(values)); if (oldValues == null) { return true; } Set<ResourceId> oldIds = oldValues.stream() .map(Resource::id) .collect(Collectors.toSet()); // values whose IDs don't match any IDs of oldValues Set<Resource> addedValues = values.stream() .filter(x -> !oldIds.contains(x.id())) .collect(Collectors.toCollection(LinkedHashSet::new)); // no new ID, then no-op if (addedValues.isEmpty()) { // don't write to map because all values are already stored return true; } LinkedHashSet<Resource> newValues = new LinkedHashSet<>(oldValues); newValues.addAll(addedValues); return map.replace(key, oldValues, newValues); } /** * Removes the values from the existing values associated with the specified key. * If the map doesn't contain the given values, removal will not happen. * * @param map map holding multiple values for a key * @param key key specifying values * @param values values to be removed * @return true if the operation succeeds, false otherwise */ // computational complexity: O(n) where n is the number of the specified values private boolean removeValues(TransactionalMap<DiscreteResourceId, Set<Resource>> map, DiscreteResourceId key, List<Resource> values) { Set<Resource> oldValues = map.putIfAbsent(key, new LinkedHashSet<>()); if (oldValues == null) { log.trace("No-Op removing values. key {} did not exist", key); return true; } if (values.stream().allMatch(x -> !oldValues.contains(x))) { // don't write map because none of the values are stored log.trace("No-Op removing values. key {} did not contain {}", key, values); return true; } LinkedHashSet<Resource> newValues = new LinkedHashSet<>(oldValues); newValues.removeAll(values); return map.replace(key, oldValues, newValues); } /** * Returns the resource which has the same key as the specified resource ID * in the set as a value of the map. * * @param childTxMap map storing parent - child relationship of resources * @param id ID of resource to be checked * @return the resource which is regarded as the same as the specified resource */ // Naive implementation, which traverses all elements in the set when continuous resource // computational complexity: O(1) when discrete resource. O(n) when continuous resource // where n is the number of elements in the associated set private Optional<Resource> lookup(TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap, ResourceId id) { if (!id.parent().isPresent()) { return Optional.of(Resource.ROOT); } Set<Resource> values = childTxMap.get(id.parent().get()); if (values == null) { return Optional.empty(); } // short-circuit if discrete resource // check the existence in the set: O(1) operation if (id instanceof DiscreteResourceId) { DiscreteResource discrete = Resources.discrete((DiscreteResourceId) id).resource(); if (values.contains(discrete)) { return Optional.of(discrete); } else { return Optional.empty(); } } // continuous resource case // iterate over the values in the set: O(n) operation return values.stream() .filter(x -> x.id().equals(id)) .findFirst(); } /** * Checks if there is enough resource volume to allocated the requested resource * against the specified resource. * * @param original original resource * @param request requested resource * @param allocation current allocation of the resource * @return true if there is enough resource volume. Otherwise, false. */ // computational complexity: O(n) where n is the number of allocations private boolean hasEnoughResource(ContinuousResource original, ContinuousResource request, ContinuousResourceAllocation allocation) { if (allocation == null) { return request.value() <= original.value(); } double allocated = allocation.allocations().stream() .filter(x -> x.resource() instanceof ContinuousResource) .map(x -> (ContinuousResource) x.resource()) .mapToDouble(ContinuousResource::value) .sum(); double left = original.value() - allocated; return request.value() <= left; } // internal use only private static final class ContinuousResourceAllocation { private final ContinuousResource original; private final ImmutableList<ResourceAllocation> allocations; private ContinuousResourceAllocation(ContinuousResource original, ImmutableList<ResourceAllocation> allocations) { this.original = original; this.allocations = allocations; } private ContinuousResource original() { return original; } private ImmutableList<ResourceAllocation> allocations() { return allocations; } } }
Workaround for old compiler - Was failing on eclise built-in compiler Change-Id: Ifd76449d0c1054876e447603aa3aff982c3a5e52
core/store/dist/src/main/java/org/onosproject/store/newresource/impl/ConsistentResourceStore.java
Workaround for old compiler
<ide><path>ore/store/dist/src/main/java/org/onosproject/store/newresource/impl/ConsistentResourceStore.java <ide> return lookup(childTxMap, x); <ide> } <ide> }) <del> .flatMap(Tools::stream) <add> .filter(Optional::isPresent) <add> .map(Optional::get) <ide> .collect(Collectors.toList()); <ide> // the order is preserved by LinkedHashMap <ide> Map<DiscreteResourceId, List<Resource>> resourceMap = resources.stream()
Java
apache-2.0
b61c9660762e526ec63d677e06eee4e2bb86bdfe
0
ol-loginov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,xfournet/intellij-community,joewalnes/idea-community,xfournet/intellij-community,fnouama/intellij-community,diorcety/intellij-community,samthor/intellij-community,izonder/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,da1z/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,izonder/intellij-community,kool79/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,orekyuu/intellij-community,slisson/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,da1z/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,semonte/intellij-community,amith01994/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,kool79/intellij-community,kool79/intellij-community,apixandru/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,ibinti/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,FHannes/intellij-community,kdwink/intellij-community,retomerz/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,caot/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,dslomov/intellij-community,ryano144/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,retomerz/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,ol-loginov/intellij-community,allotria/intellij-community,dslomov/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,supersven/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,petteyg/intellij-community,xfournet/intellij-community,fitermay/intellij-community,apixandru/intellij-community,semonte/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,akosyakov/intellij-community,slisson/intellij-community,hurricup/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,Lekanich/intellij-community,holmes/intellij-community,amith01994/intellij-community,izonder/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,adedayo/intellij-community,kdwink/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,adedayo/intellij-community,jagguli/intellij-community,amith01994/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,amith01994/intellij-community,adedayo/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,clumsy/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,izonder/intellij-community,FHannes/intellij-community,dslomov/intellij-community,joewalnes/idea-community,izonder/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,retomerz/intellij-community,vladmm/intellij-community,jexp/idea2,retomerz/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,izonder/intellij-community,fnouama/intellij-community,kool79/intellij-community,retomerz/intellij-community,supersven/intellij-community,kool79/intellij-community,supersven/intellij-community,signed/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ernestp/consulo,mglukhikh/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,kdwink/intellij-community,hurricup/intellij-community,semonte/intellij-community,slisson/intellij-community,dslomov/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ibinti/intellij-community,holmes/intellij-community,orekyuu/intellij-community,samthor/intellij-community,holmes/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,semonte/intellij-community,blademainer/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,holmes/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,hurricup/intellij-community,allotria/intellij-community,xfournet/intellij-community,diorcety/intellij-community,allotria/intellij-community,retomerz/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,caot/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,petteyg/intellij-community,caot/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,caot/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,izonder/intellij-community,suncycheng/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ibinti/intellij-community,clumsy/intellij-community,da1z/intellij-community,FHannes/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,jagguli/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,jexp/idea2,asedunov/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,diorcety/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,signed/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,ernestp/consulo,kool79/intellij-community,ernestp/consulo,xfournet/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,semonte/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,joewalnes/idea-community,vladmm/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,jagguli/intellij-community,izonder/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,caot/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,kool79/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,clumsy/intellij-community,allotria/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,slisson/intellij-community,izonder/intellij-community,vvv1559/intellij-community,caot/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,semonte/intellij-community,wreckJ/intellij-community,signed/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,diorcety/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,kdwink/intellij-community,da1z/intellij-community,holmes/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,petteyg/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,slisson/intellij-community,robovm/robovm-studio,xfournet/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,michaelgallacher/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,diorcety/intellij-community,ibinti/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,semonte/intellij-community,youdonghai/intellij-community,kool79/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,petteyg/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,allotria/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,dslomov/intellij-community,holmes/intellij-community,jexp/idea2,samthor/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,consulo/consulo,blademainer/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,consulo/consulo,slisson/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,nicolargo/intellij-community,samthor/intellij-community,fnouama/intellij-community,jagguli/intellij-community,apixandru/intellij-community,jagguli/intellij-community,ryano144/intellij-community,da1z/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,signed/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,vvv1559/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,kdwink/intellij-community,apixandru/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,blademainer/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,jexp/idea2,blademainer/intellij-community,hurricup/intellij-community,apixandru/intellij-community,signed/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,consulo/consulo,idea4bsd/idea4bsd,orekyuu/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,caot/intellij-community,jexp/idea2,samthor/intellij-community,jagguli/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,apixandru/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,hurricup/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,slisson/intellij-community,fitermay/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,kdwink/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,supersven/intellij-community,clumsy/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,caot/intellij-community,petteyg/intellij-community,clumsy/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,tmpgit/intellij-community,supersven/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,ibinti/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,slisson/intellij-community,diorcety/intellij-community,signed/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,allotria/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,dslomov/intellij-community,jexp/idea2,ahb0327/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,caot/intellij-community,allotria/intellij-community,jexp/idea2,jagguli/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,signed/intellij-community,vladmm/intellij-community,jagguli/intellij-community,vladmm/intellij-community,signed/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,diorcety/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community
/* * Copyright (c) 2004 JetBrains s.r.o. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * Neither the name of JetBrains or IntelliJ IDEA * may be used to endorse or promote products derived from this software * without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. JETBRAINS AND ITS LICENSORS SHALL NOT * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL JETBRAINS OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN * IF JETBRAINS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * */ package com.intellij.ide.projectView.impl.nodes; import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiPackage; import org.jetbrains.annotations.NotNull; import java.util.*; public class PackageViewProjectNode extends AbstractProjectNode { public PackageViewProjectNode(Project project, ViewSettings viewSettings) { super(project, project, viewSettings); } @NotNull public Collection<AbstractTreeNode> getChildren() { if (getSettings().isShowModules()) { final List<Module> allModules = new ArrayList<Module>(Arrays.asList(ModuleManager.getInstance(getProject()).getModules())); for (Iterator<Module> it = allModules.iterator(); it.hasNext();) { final Module module = it.next(); final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(); if (sourceRoots.length == 0) { // do not show modules with no source roots configured it.remove(); } } return modulesAndGroups(allModules.toArray(new Module[allModules.size()])); } else { final List<VirtualFile> sourceRoots = new ArrayList<VirtualFile>(); final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(myProject); sourceRoots.addAll(Arrays.asList(projectRootManager.getContentSourceRoots())); final PsiManager psiManager = PsiManager.getInstance(myProject); final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>(); final Set<PsiPackage> topLevelPackages = new HashSet<PsiPackage>(); for (final VirtualFile root : sourceRoots) { final PsiDirectory directory = psiManager.findDirectory(root); if (directory == null) { continue; } final PsiPackage directoryPackage = directory.getPackage(); if (directoryPackage == null || PackageUtil.isPackageDefault(directoryPackage)) { // add subpackages final PsiDirectory[] subdirectories = directory.getSubdirectories(); for (PsiDirectory subdirectory : subdirectories) { final PsiPackage aPackage = subdirectory.getPackage(); if (aPackage != null && !PackageUtil.isPackageDefault(aPackage)) { topLevelPackages.add(aPackage); } } // add non-dir items children.addAll(PackageUtil.getDirectoryChildren(directory, getSettings(), false)); } else { // this is the case when a source root has pakage prefix assigned topLevelPackages.add(directoryPackage); } } for (final PsiPackage psiPackage : topLevelPackages) { PackageUtil.addPackageAsChild(children, psiPackage, null, getSettings(), false); } if (getSettings().isShowLibraryContents()) { children.add(new PackageViewLibrariesNode(getProject(), null, getSettings())); } return children; } } protected Class<? extends AbstractTreeNode> getModuleNodeClass() { return PackageViewModuleNode.class; } }
source/com/intellij/ide/projectView/impl/nodes/PackageViewProjectNode.java
/* * Copyright (c) 2004 JetBrains s.r.o. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduct the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * Neither the name of JetBrains or IntelliJ IDEA * may be used to endorse or promote products derived from this software * without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. JETBRAINS AND ITS LICENSORS SHALL NOT * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL JETBRAINS OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN * IF JETBRAINS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * */ package com.intellij.ide.projectView.impl.nodes; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiPackage; import com.intellij.psi.PsiDirectory; import java.util.*; import org.jetbrains.annotations.NotNull; public class PackageViewProjectNode extends AbstractProjectNode { public PackageViewProjectNode(Project project, ViewSettings viewSettings) { super(project, project, viewSettings); } @NotNull public Collection<AbstractTreeNode> getChildren() { if (getSettings().isShowModules()) { final List<Module> allModules = new ArrayList<Module>(Arrays.asList(ModuleManager.getInstance(getProject()).getModules())); for (Iterator<Module> it = allModules.iterator(); it.hasNext();) { final Module module = it.next(); final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(); if (sourceRoots.length == 0) { // do not show modules with no source roots configured it.remove(); } } return modulesAndGroups(allModules.toArray(new Module[allModules.size()])); } else { final List<VirtualFile> sourceRoots = new ArrayList<VirtualFile>(); final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(myProject); sourceRoots.addAll(Arrays.asList(projectRootManager.getContentSourceRoots())); final PsiManager psiManager = PsiManager.getInstance(myProject); final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>(); final Set<PsiPackage> topLevelPackages = new HashSet<PsiPackage>(); for (final VirtualFile root : sourceRoots) { final PsiDirectory directory = psiManager.findDirectory(root); if (directory == null) { continue; } final PsiPackage directoryPackage = directory.getPackage(); if (directoryPackage == null || PackageUtil.isPackageDefault(directoryPackage)) { // add subpackages final PsiDirectory[] subdirectories = directory.getSubdirectories(); for (int i = 0; i < subdirectories.length; i++) { final PsiPackage aPackage = subdirectories[i].getPackage(); if (aPackage != null && !PackageUtil.isPackageDefault(aPackage)) { topLevelPackages.add(aPackage); } } // add non-dir items children.addAll(PackageUtil.getDirectoryChildren(directory, getSettings(), false)); } else { // this is the case when a source root has pakage prefix assigned topLevelPackages.add(directoryPackage); } } for (Iterator<PsiPackage> it = topLevelPackages.iterator(); it.hasNext();) { final PsiPackage psiPackage = it.next(); PackageUtil.addPackageAsChild(children, psiPackage, null, getSettings(), false); } if (getSettings().isShowLibraryContents()) { children.add(new PackageViewLibrariesNode(getProject(), null, getSettings())); } return children; } } protected Class<? extends AbstractTreeNode> getModuleNodeClass() { return PackageViewModuleNode.class; } }
cleanup
source/com/intellij/ide/projectView/impl/nodes/PackageViewProjectNode.java
cleanup
<ide><path>ource/com/intellij/ide/projectView/impl/nodes/PackageViewProjectNode.java <ide> */ <ide> package com.intellij.ide.projectView.impl.nodes; <ide> <del>import com.intellij.openapi.project.Project; <del>import com.intellij.openapi.vfs.VirtualFile; <del>import com.intellij.openapi.roots.ProjectRootManager; <del>import com.intellij.openapi.roots.ProjectFileIndex; <del>import com.intellij.openapi.roots.ModuleRootManager; <add>import com.intellij.ide.projectView.ViewSettings; <add>import com.intellij.ide.util.treeView.AbstractTreeNode; <ide> import com.intellij.openapi.module.Module; <ide> import com.intellij.openapi.module.ModuleManager; <del>import com.intellij.ide.projectView.ViewSettings; <del>import com.intellij.ide.util.treeView.AbstractTreeNode; <add>import com.intellij.openapi.project.Project; <add>import com.intellij.openapi.roots.ModuleRootManager; <add>import com.intellij.openapi.roots.ProjectRootManager; <add>import com.intellij.openapi.vfs.VirtualFile; <add>import com.intellij.psi.PsiDirectory; <ide> import com.intellij.psi.PsiManager; <ide> import com.intellij.psi.PsiPackage; <del>import com.intellij.psi.PsiDirectory; <add>import org.jetbrains.annotations.NotNull; <ide> <ide> import java.util.*; <del> <del>import org.jetbrains.annotations.NotNull; <ide> <ide> public class PackageViewProjectNode extends AbstractProjectNode { <ide> public PackageViewProjectNode(Project project, ViewSettings viewSettings) { <ide> if (directoryPackage == null || PackageUtil.isPackageDefault(directoryPackage)) { <ide> // add subpackages <ide> final PsiDirectory[] subdirectories = directory.getSubdirectories(); <del> for (int i = 0; i < subdirectories.length; i++) { <del> final PsiPackage aPackage = subdirectories[i].getPackage(); <add> for (PsiDirectory subdirectory : subdirectories) { <add> final PsiPackage aPackage = subdirectory.getPackage(); <ide> if (aPackage != null && !PackageUtil.isPackageDefault(aPackage)) { <ide> topLevelPackages.add(aPackage); <ide> } <ide> } <ide> } <ide> <del> for (Iterator<PsiPackage> it = topLevelPackages.iterator(); it.hasNext();) { <del> final PsiPackage psiPackage = it.next(); <add> for (final PsiPackage psiPackage : topLevelPackages) { <ide> PackageUtil.addPackageAsChild(children, psiPackage, null, getSettings(), false); <ide> } <ide>
JavaScript
mit
654810447c4be870a2e04d80517b780c15da5f09
0
DemocracyOS/app,DemocracyOS/app
import React, { Component } from 'react' import t from 't-component' import { Link } from 'react-router' import topicStore from 'lib/stores/topic-store/topic-store' import userConnector from 'lib/site/connectors/user' export class Poll extends Component { constructor (props) { super(props) this.state = { showResults: false } } handlePoll = (option) => (e) => { if (!this.props.user.state.fulfilled) return if (this.state.showResults) return topicStore.poll(this.props.topic.id, option) .catch((err) => { console.warn('Error on poll setState', err) }) } componentWillMount () { this.setStateFromProps(this.props) } componentWillReceiveProps (props) { this.setStateFromProps(props) } setStateFromProps (props) { const { topic, user } = props if (topic.closed || !user.state.fulfilled) { return this.setState({ showResults: true }) } const ownVote = this.getOwnVote(props) this.setState((props, state) => ({ showResults: !!ownVote })) } getOwnVote ({ topic, user }) { if (!user.state.fulfilled) return null return topic.action.pollResults.find((r) => { const id = r.author.id || r.author return user.state.value.id === id }) } render () { if (this.props.user.state.pending) return null const { topic, user } = this.props const results = topic.action.pollResults const options = topic.action.pollOptions const votesTotal = results.length const votesCounts = results.reduce((counts, result) => { if (!counts[result.value]) counts[result.value] = 0 counts[result.value]++ return counts }, {}) const votesPercentages = {} options.forEach((opt) => { if (!votesCounts[opt]) votesCounts[opt] = 0 votesPercentages[opt] = 100 / votesTotal * votesCounts[opt] || 0 }) const winnerCount = Math.max(...options.map((opt) => votesCounts[opt])) const ownVote = this.getOwnVote(this.props) return ( <div className='poll-wrapper topic-article-content'> { options.map((opt, i) => ( <Option key={opt} option={opt} results={parseFloat(votesPercentages[opt].toFixed(2))} winner={winnerCount === votesCounts[opt]} voted={opt === (ownVote && ownVote.value)} handlePoll={this.handlePoll(opt)} showResults={this.state.showResults} /> )) } { !user.state.fulfilled && ( <p className='text-mute overlay-vote'> <span className='text'> {t('proposal-options.must-be-signed-in') + '. '} <Link to={{ pathname: '/signin', query: { ref: window.location.pathname } }}> {t('signin.login')} </Link> <span>&nbsp;{t('common.or')}&nbsp;</span> <Link to='/signup'> {t('signin.signup')} </Link>. </span> </p> ) } { user.state.fulfilled && !this.props.canVoteAndComment && ( <p className='text-mute overlay-vote'> <span className='icon-lock' /> <span className='text'> {t('privileges-alert.not-can-vote-and-comment')} </span> </p> ) } </div> ) } } export default userConnector(Poll) const Option = ({ option, handlePoll, results, showResults, winner, voted }) => ( <button className={ 'btn btn-default' + (showResults ? ' show-results' : '') + (winner ? ' winner' : '') } onClick={handlePoll}> {showResults && <span className='poll-results'>{results}%</span> } <span className='poll-option-label'>{ option }</span> {showResults && voted && <span className='icon-check' />} <div className='results-bar' style={{ width: results + '%' }} /> </button> )
lib/site/topic-layout/topic-article/poll/component.js
import React, { Component } from 'react' import t from 't-component' import { Link } from 'react-router' import topicStore from 'lib/stores/topic-store/topic-store' import userConnector from 'lib/site/connectors/user' export class Poll extends Component { constructor (props) { super(props) this.state = { showResults: false } } handlePoll = (option) => (e) => { if (!this.props.user.state.fulfilled) return if (this.state.showResults) return topicStore.poll(this.props.topic.id, option) .catch((err) => { console.warn('Error on poll setState', err) }) } componentWillReceiveProps (props) { if (props.topic.closed) { return this.setState((props, state) => ({ showResults: true })) } const { user } = props const voteIndex = props.topic.action.pollResults .map((r) => r.author.id || r.author) .indexOf(user.state.value.id) if (user.state.fulfilled && voteIndex !== -1) { this.setState((props, state) => ({ showResults: true })) } } render () { if (this.props.user.state.pending) return null const { topic, user } = this.props const results = topic.action.pollResults const options = topic.action.pollOptions const votesTotal = results.length const votesCounts = results.reduce((counts, result) => { if (!counts[result.value]) counts[result.value] = 0 counts[result.value]++ return counts }, {}) const votesPercentages = {} options.forEach((opt) => { if (!votesCounts[opt]) votesCounts[opt] = 0 votesPercentages[opt] = 100 / votesTotal * votesCounts[opt] || 0 }) const winnerCount = Math.max(...options.map((opt) => votesCounts[opt])) const ownVote = user.state.fulfilled && results.find((r) => { return r.author === user.state.value.id }) return ( <div className='poll-wrapper topic-article-content'> { options.map((opt, i) => ( <Option key={opt} option={opt} results={parseFloat(votesPercentages[opt].toFixed(2))} winner={winnerCount === votesCounts[opt]} voted={opt === (ownVote && ownVote.value)} handlePoll={this.handlePoll(opt)} showResults={this.state.showResults} /> )) } { !user.state.fulfilled && ( <p className='text-mute overlay-vote'> <span className='text'> {t('proposal-options.must-be-signed-in') + '. '} <Link to={{ pathname: '/signin', query: { ref: window.location.pathname } }}> {t('signin.login')} </Link> <span>&nbsp;{t('common.or')}&nbsp;</span> <Link to='/signup'> {t('signin.signup')} </Link>. </span> </p> ) } { user.state.fulfilled && !this.props.canVoteAndComment && ( <p className='text-mute overlay-vote'> <span className='icon-lock' /> <span className='text'> {t('privileges-alert.not-can-vote-and-comment')} </span> </p> ) } </div> ) } } export default userConnector(Poll) const Option = ({ option, handlePoll, results, showResults, winner, voted }) => ( <button className={ 'btn btn-default' + (showResults ? ' show-results' : '') + (winner ? ' winner' : '') } onClick={handlePoll}> {showResults && <span className='poll-results'>{results}%</span> } <span className='poll-option-label'>{ option }</span> {showResults && voted && <span className='icon-check' />} <div className='results-bar' style={{ width: results + '%' }} /> </button> )
fix poll ownVote rendering
lib/site/topic-layout/topic-article/poll/component.js
fix poll ownVote rendering
<ide><path>ib/site/topic-layout/topic-article/poll/component.js <ide> }) <ide> } <ide> <add> componentWillMount () { <add> this.setStateFromProps(this.props) <add> } <add> <ide> componentWillReceiveProps (props) { <del> if (props.topic.closed) { <del> return this.setState((props, state) => ({ showResults: true })) <add> this.setStateFromProps(props) <add> } <add> <add> setStateFromProps (props) { <add> const { topic, user } = props <add> <add> if (topic.closed || !user.state.fulfilled) { <add> return this.setState({ showResults: true }) <ide> } <ide> <del> const { user } = props <add> const ownVote = this.getOwnVote(props) <ide> <del> const voteIndex = props.topic.action.pollResults <del> .map((r) => r.author.id || r.author) <del> .indexOf(user.state.value.id) <add> this.setState((props, state) => ({ <add> showResults: !!ownVote <add> })) <add> } <ide> <del> if (user.state.fulfilled && voteIndex !== -1) { <del> this.setState((props, state) => ({ <del> showResults: true <del> })) <del> } <add> getOwnVote ({ topic, user }) { <add> if (!user.state.fulfilled) return null <add> <add> return topic.action.pollResults.find((r) => { <add> const id = r.author.id || r.author <add> return user.state.value.id === id <add> }) <ide> } <ide> <ide> render () { <ide> <ide> const winnerCount = Math.max(...options.map((opt) => votesCounts[opt])) <ide> <del> const ownVote = user.state.fulfilled && results.find((r) => { <del> return r.author === user.state.value.id <del> }) <add> const ownVote = this.getOwnVote(this.props) <ide> <ide> return ( <ide> <div className='poll-wrapper topic-article-content'>
JavaScript
mit
ecc7d72567a3edea5c9e50b3ccbfa520c317b90e
0
DemocracyEarth/sovereign,DemocracyEarth/sovereign,DemocracyEarth/sovereign
import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Meteor } from 'meteor/meteor'; import { getVotes } from '/imports/api/transactions/transaction'; import { timeCompressed } from '/imports/ui/modules/chronos'; import '/imports/ui/templates/widgets/transaction/transaction.html'; import '/imports/ui/templates/widgets/preview/preview.js'; const _verifySubsidy = (id) => { return (Meteor.settings.public.Collective._id === id); }; Template.transaction.onCreated(function () { Template.instance().totalVotes = new ReactiveVar(0); }); Template.transaction.helpers({ sender() { return { _id: this.senderId, imgStyle: () => { if (this.compressed) { return 'float: left; margin-top: 4px;'; } return ''; }, }; }, receiver() { return { _id: this.receiverId, imgStyle: () => { if (this.compressed) { return ' margin-top: 4px; margin-left: 5px; '; } return ''; }, }; }, isSubsidy() { return _verifySubsidy(this.senderId); }, isVote() { return this.isVote; }, value() { let votes; let plus = ''; if (this.isVote) { votes = this.contract.wallet.balance; if (_verifySubsidy(this.senderId)) { plus = '+'; } else if (this.isRevoke) { votes *= -1; } Template.instance().totalVotes.set(votes); } else if (this.editable) { if (Session.get(this.voteId)) { votes = Session.get(this.voteId).allocateQuantity; if (isNaN(votes)) { votes = Session.get(this.voteId).inBallot; } Template.instance().totalVotes.set(votes); } } else { Template.instance().totalVotes.set(getVotes(this.contract._id, this.senderId)); votes = Template.instance().totalVotes.get(); } if (votes === 1 || votes === -1) { return `${plus}${votes} ${TAPi18n.__('vote')}`; } else if (votes > 0 || votes < 0) { return `${plus}${votes} ${TAPi18n.__('votes')}`; } return TAPi18n.__('no-delegated-votes'); }, source() { return TAPi18n.__('delegated-votes'); }, voteStyle() { if (Template.instance().totalVotes.get() !== 0) { if (_verifySubsidy(this.senderId)) { return 'stage stage-vote-totals'; } else if (this.isRevoke) { return 'stage stage-finish-rejected'; } return 'stage stage-finish-approved'; } return 'stage stage-live'; }, ballotOption() { return TAPi18n.__(this.ballot[0].mode); }, emptyVotes() { if (Template.instance().totalVotes.get() === 0 && !this.onCard) { return 'display:none'; } return ''; }, sinceDate() { return `${timeCompressed(this.contract.timestamp)}`; }, noDate() { return this.noDate; }, onCard() { if (this.onCard) { return 'vote-delegation-card'; } return ''; }, isRevoke() { return this.isRevoke; }, hidePost() { return this.hidePost; }, revokeStyle() { if (!this.hidePost) { return 'stage-revoke'; } return ''; }, }); Template.collectivePreview.helpers({ flag() { return Meteor.settings.public.Collective.profile.logo; }, name() { let chars = 30; if (Meteor.Device.isPhone()) { chars = 15; } if (Meteor.settings.public.Collective.name.length > chars) { return `${Meteor.settings.public.Collective.name.substring(0, chars)}...`; } return Meteor.settings.public.Collective.name; }, url() { return '/'; }, });
imports/ui/templates/widgets/transaction/transaction.js
import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Meteor } from 'meteor/meteor'; import { getVotes } from '/imports/api/transactions/transaction'; import { timeCompressed } from '/imports/ui/modules/chronos'; import '/imports/ui/templates/widgets/transaction/transaction.html'; import '/imports/ui/templates/widgets/preview/preview.js'; const _verifySubsidy = (id) => { return (Meteor.settings.public.Collective._id === id); }; Template.transaction.onCreated(function () { Template.instance().totalVotes = new ReactiveVar(0); }); Template.transaction.helpers({ sender() { return { _id: this.senderId, imgStyle: () => { if (this.compressed) { return 'float: left; margin-top: 4px;'; } return ''; }, }; }, receiver() { return { _id: this.receiverId, imgStyle: () => { if (this.compressed) { return ' margin-top: 4px; margin-left: 5px; '; } return ''; }, }; }, isSubsidy() { return _verifySubsidy(this.senderId); }, isVote() { return this.isVote; }, value() { let votes; let plus = ''; if (this.isVote) { votes = this.contract.wallet.balance; if (_verifySubsidy(this.senderId)) { plus = '+'; } else if (this.isRevoke) { votes *= -1; } Template.instance().totalVotes.set(votes); } else if (this.editable) { if (Session.get(this.voteId)) { votes = Session.get(this.voteId).allocateQuantity; if (isNaN(votes)) { votes = Session.get(this.voteId).inBallot; } Template.instance().totalVotes.set(votes); } } else { Template.instance().totalVotes.set(getVotes(this.contract._id, this.senderId)); votes = Template.instance().totalVotes.get(); } if (votes === 1 || votes === -1) { return `${plus}${votes} ${TAPi18n.__('vote')}`; } else if (votes > 0 || votes < 0) { return `${plus}${votes} ${TAPi18n.__('votes')}`; } return TAPi18n.__('no-delegated-votes'); }, source() { return TAPi18n.__('delegated-votes'); }, voteStyle() { if (Template.instance().totalVotes.get() !== 0) { if (_verifySubsidy(this.senderId)) { return 'stage stage-vote-totals'; } else if (this.isRevoke) { return 'stage stage-finish-rejected'; } return 'stage stage-finish-approved'; } return 'stage stage-live'; }, ballotOption() { return TAPi18n.__(this.ballot[0].mode); }, emptyVotes() { if (Template.instance().totalVotes.get() === 0 && !this.onCard) { return 'display:none'; } return ''; }, sinceDate() { return `${timeCompressed(this.contract.timestamp)}`; }, noDate() { return this.noDate; }, onCard() { if (this.onCard) { return 'vote-delegation-card'; } return ''; }, isRevoke() { return this.isRevoke; }, hidePost() { return this.hidePost; }, revokeStyle() { if (!this.hidePost) { return 'stage-revoke'; } return ''; }, }); Template.collectivePreview.helpers({ flag() { return Meteor.settings.public.Collective.profile.logo; }, name() { return Meteor.settings.public.Collective.name; }, url() { return '/'; }, });
shortens collective name
imports/ui/templates/widgets/transaction/transaction.js
shortens collective name
<ide><path>mports/ui/templates/widgets/transaction/transaction.js <ide> return Meteor.settings.public.Collective.profile.logo; <ide> }, <ide> name() { <add> let chars = 30; <add> if (Meteor.Device.isPhone()) { <add> chars = 15; <add> } <add> if (Meteor.settings.public.Collective.name.length > chars) { <add> return `${Meteor.settings.public.Collective.name.substring(0, chars)}...`; <add> } <ide> return Meteor.settings.public.Collective.name; <ide> }, <ide> url() {
Java
apache-2.0
1bc7e18eb54aa4a176401a93f820446a8c21cb3b
0
apache/incubator-freemarker,pradeepmurugesan/incubator-freemarker,pradeepmurugesan/incubator-freemarker,awils18/incubator-freemarker,woonsan/incubator-freemarker,awils18/incubator-freemarker,woonsan/incubator-freemarker,apache/incubator-freemarker
/* * Copyright 2014 Attila Szegedi, Daniel Dekany, Jonathan Revusky * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package freemarker.core; import java.io.IOException; import org.junit.Test; import freemarker.template.TemplateException; import freemarker.test.TemplateTest; public class ListValidationsTest extends TemplateTest { @Test public void testValid() throws IOException, TemplateException { assertOutput("<#list 1..2 as x><#list 3..4>${x}:<#items as x>${x}</#items></#list>;</#list>", "1:34;2:34;"); assertOutput("<#list [] as x>${x}<#else><#list 1..2 as x>${x}<#sep>, </#list></#list>", "1, 2"); assertOutput("<#macro m>[<#nested 3>]</#macro>" + "<#list 1..2 as x>" + "${x}@${x?index}" + "<@m ; x>" + "${x}," + "<#list 4..4 as x>${x}@${x?index}</#list>" + "</@>" + "${x}@${x?index}; " + "</#list>", "1@0[3,4@0]1@0; 2@1[3,4@0]2@1; "); } @Test public void testInvalidItemsParseTime() throws IOException, TemplateException { assertErrorContains("<#items as x>${x}</#items>", "#items", "must be inside", "#list"); assertErrorContains("<#list xs><#macro m><#items as x></#items></#macro></#list>", "#items", "must be inside", "#list"); assertErrorContains("<#list xs><#forEach x in xs><#items as x></#items></#forEach></#list>", "#forEach", "doesn't support", "#items"); assertErrorContains("<#list xs as x><#items as x>${x}</#items></#list>", "#list", "must not have", "#items", "as loopVar"); assertErrorContains("<#list xs><#list xs as x><#items as x>${x}</#items></#list></#list>", "#list", "must not have", "#items", "as loopVar"); assertErrorContains("<#list xs></#list>", "#list", "must have", "#items", "as loopVar"); assertErrorContains("<#forEach x in xs><#items as x></#items></#forEach>", "#forEach", "doesn't support", "#items"); assertErrorContains("<#list xs><#forEach x in xs><#items as x></#items></#forEach></#list>", "#forEach", "doesn't support", "#items"); } @Test public void testInvalidSepParseTime() throws IOException, TemplateException { assertErrorContains("<#sep>, </#sep>", "#sep", "must be inside", "#list", "#foreach"); assertErrorContains("<#sep>, ", "#sep", "must be inside", "#list", "#foreach"); assertErrorContains("<#list xs as x><#else><#sep>, </#list>", "#sep", "must be inside", "#list", "#foreach"); assertErrorContains("<#list xs as x><#macro m><#sep>, </#macro></#list>", "#sep", "must be inside", "#list", "#foreach"); } @Test public void testInvalidItemsRuntime() throws IOException, TemplateException { assertErrorContains("<#list 1..1><#items as x></#items><#items as x></#items></#list>", "#items", "already entered earlier"); assertErrorContains("<#list 1..1><#items as x><#items as y>${x}/${y}</#items></#items></#list>", "#items", "Can't nest #items into each other"); } @Test public void testInvalidLoopVarBuiltinLHO() { assertErrorContains("<#list foos>${foo?index}</#list>", "?index", "foo", "no loop variable"); assertErrorContains("<#list foos as foo></#list>${foo?index}", "?index", "foo" , "no loop variable"); assertErrorContains("<#list foos as foo><#macro m>${foo?index}</#macro></#list>", "?index", "foo" , "no loop variable"); assertErrorContains("<#list foos as foo><#function f>${foo?index}</#function></#list>", "?index", "foo" , "no loop variable"); assertErrorContains("<#list xs as x>${foo?index}</#list>", "?index", "foo" , "no loop variable"); assertErrorContains("<#list foos as foo><@m; foo>${foo?index}</@></#list>", "?index", "foo" , "user defined directive"); assertErrorContains( "<#list foos as foo><@m; foo><@m; foo>${foo?index}</@></@></#list>", "?index", "foo" , "user defined directive"); assertErrorContains( "<#list foos as foo><@m; foo>" + "<#list foos as foo><@m; foo>${foo?index}</@></#list>" + "</@></#list>", "?index", "foo" , "user defined directive"); } }
src/test/java/freemarker/core/ListValidationsTest.java
/* * Copyright 2014 Attila Szegedi, Daniel Dekany, Jonathan Revusky * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package freemarker.core; import java.io.IOException; import org.junit.Test; import freemarker.template.TemplateException; import freemarker.test.TemplateTest; public class ListValidationsTest extends TemplateTest { @Test public void testValid() throws IOException, TemplateException { assertOutput("<#list 1..2 as x><#list 3..4>${x}:<#items as x>${x}</#items></#list>;</#list>", "1:34;2:34;"); assertOutput("<#list [] as x>${x}<#else><#list 1..2 as x>${x}<#sep>, </#list></#list>", "1, 2"); assertOutput("<#macro m>[<#nested 3>]</#macro>" + "<#list 1..2 as x>" + "${x}@${x?index}" + "<@m ; x>" + "${x}," + "<#list 4..4 as x>${x}@${x?index}</#list>" + "</@>" + "${x}@${x?index}; " + "</#list>", "1@0[3,4@0]1@0; 2@1[3,4@0]2@1; "); } @Test public void testInvalidItemsParseTime() throws IOException, TemplateException { assertErrorContains("<#items as x>${x}</#items>", "#items", "must be inside", "#list"); assertErrorContains("<#list xs><#macro m><#items as x></#items></#macro></#list>", "#items", "must be inside", "#list"); assertErrorContains("<#list xs><#forEach x in xs><#items as x></#items></#forEach></#list>", "#forEach", "doesn't support", "#items"); assertErrorContains("<#list xs as x><#items as x>${x}</#items></#list>", "#list", "must not have", "#items", "as loopVar"); assertErrorContains("<#list xs><#list xs as x><#items as x>${x}</#items></#list></#list>", "#list", "must not have", "#items", "as loopVar"); assertErrorContains("<#list xs></#list>", "#list", "must have", "#items", "as loopVar"); assertErrorContains("<#forEach x in xs><#items as x></#items></#forEach>", "#forEach", "doesn't support", "#items"); assertErrorContains("<#list xs><#forEach x in xs><#items as x></#items></#forEach></#list>", "#forEach", "doesn't support", "#items"); } @Test public void testInvalidSepParseTime() throws IOException, TemplateException { assertErrorContains("<#sep>, </#sep>", "#sep", "must be inside", "#list", "#foreach"); assertErrorContains("<#sep>, ", "#sep", "must be inside", "#list", "#foreach"); assertErrorContains("<#list xs as x><#else><#sep>, </#list>", "#sep", "must be inside", "#list", "#foreach"); assertErrorContains("<#list xs as x><#macro m><#sep>, </#macro></#list>", "#sep", "must be inside", "#list", "#foreach"); } @Test public void testInvalidItemsRuntime() throws IOException, TemplateException { assertErrorContains("<#list 1..1><#items as x></#items><#items as x></#items></#list>", "#items", "already entered earlier"); assertErrorContains("<#list 1..1><#items as x><#items as y>${x}/${y}</#items></#items></#list>", "#items", "Can't nest #items into each other"); } @Test public void testInvalidLoopVarBuiltinLHO() { assertErrorContains("<#list foos>${foo?index}</#list>", "?index", "foo", "no loop variable"); assertErrorContains("<#list foos as foo></#list>${foo?index}", "?index", "foo" , "no loop variable"); assertErrorContains("<#list xs as x>${foo?index}</#list>", "?index", "foo" , "no loop variable"); assertErrorContains("<#list foos as foo><@m; foo>${foo?index}</@></#list>", "?index", "foo" , "user defined directive"); assertErrorContains( "<#list foos as foo><@m; foo><@m; foo>${foo?index}</@></@></#list>", "?index", "foo" , "user defined directive"); assertErrorContains( "<#list foos as foo><@m; foo>" + "<#list foos as foo><@m; foo>${foo?index}</@></#list>" + "</@></#list>", "?index", "foo" , "user defined directive"); } }
(Some more loop variable built-in parsing tests.)
src/test/java/freemarker/core/ListValidationsTest.java
(Some more loop variable built-in parsing tests.)
<ide><path>rc/test/java/freemarker/core/ListValidationsTest.java <ide> "?index", "foo", "no loop variable"); <ide> assertErrorContains("<#list foos as foo></#list>${foo?index}", <ide> "?index", "foo" , "no loop variable"); <add> assertErrorContains("<#list foos as foo><#macro m>${foo?index}</#macro></#list>", <add> "?index", "foo" , "no loop variable"); <add> assertErrorContains("<#list foos as foo><#function f>${foo?index}</#function></#list>", <add> "?index", "foo" , "no loop variable"); <ide> assertErrorContains("<#list xs as x>${foo?index}</#list>", <ide> "?index", "foo" , "no loop variable"); <ide> assertErrorContains("<#list foos as foo><@m; foo>${foo?index}</@></#list>",
Java
agpl-3.0
a687c4030813702267107b677349e010b6230b57
0
MarkehMe/FactionsPlus
package markehme.factionsplus; import java.io.IOException; import java.util.Set; import java.util.logging.Logger; import markehme.factionsplus.config.Config; import markehme.factionsplus.extras.LWCBase; import markehme.factionsplus.extras.LWCFunctions; import markehme.factionsplus.extras.Metrics; import markehme.factionsplus.extras.Metrics.Graph; import markehme.factionsplus.listeners.CoreListener; import markehme.factionsplus.listeners.FPConfigLoadedListener; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.event.HandlerList; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import com.massivecraft.factions.Factions; import com.massivecraft.factions.entity.MConf; import com.onarandombox.MultiversePortals.MultiversePortals; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; public class FactionsPlus extends FactionsPlusPlugin { public static FactionsPlus instance; public static Logger log = Logger.getLogger("Minecraft"); Factions factions; public static Permission permission = null; public static boolean isWorldEditEnabled = false; public static boolean isWorldGuardEnabled = false; public static boolean isMultiversePortalsEnabled = false; public final CoreListener corelistener = new CoreListener(); public static WorldEditPlugin worldEditPlugin = null; public static WorldGuardPlugin worldGuardPlugin = null; public static MultiversePortals multiversePortalsPlugin = null; public static String version; public static String FactionsVersion; private static Metrics metrics = null; public static Set<String> ignoredPvPWorlds = null; public static Set<String> noClaimingWorlds = null; public static Set<String> noPowerLossWorlds = null; public static Server server; public static boolean update_avab; public FactionsPlus() { super(); if ( null != instance ) { throw bailOut( "This was not expected, getting new-ed again without getting unloaded first.\n" + "Safest way to reload is to stop and start the server!" ); } instance = this; } @Override public void onEnable() { try { super.onEnable(); ignoredPvPWorlds = MConf.get().worldsIgnorePvP; noClaimingWorlds = MConf.get().worldsNoClaiming; noPowerLossWorlds = MConf.get().worldsNoPowerLoss; version = getDescription().getVersion(); Config.init(); PluginManager pm = this.getServer().getPluginManager(); FactionsVersion = pm.getPlugin( "Factions" ).getDescription().getVersion(); info("Factions v" + FactionsVersion ); pm.registerEvents( new FPConfigLoadedListener(), this ); Config.reload(); pm.registerEvents( this.corelistener, this ); server = getServer(); FactionsPlusCommandManager.setup(); RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration( net.milkbowl.vault.permission.Permission.class ); if ( permissionProvider != null ) { permission = permissionProvider.getProvider(); } if( 1<2 ) { if( pm.isPluginEnabled( "WorldEdit" ) ) { worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin( "WorldEdit" ); isWorldEditEnabled = true; } if( pm.isPluginEnabled( "WorldGuard" ) ) { worldGuardPlugin = ( WorldGuardPlugin ) getServer().getPluginManager().getPlugin( "WorldGuard" ); isWorldGuardEnabled = true; } } if( pm.isPluginEnabled( "Multiverse-Portals" ) ) { Plugin MVc = getServer().getPluginManager().getPlugin( "Multiverse-Portals" ); if (MVc instanceof MultiversePortals) { multiversePortalsPlugin = ( MultiversePortals ) MVc; isMultiversePortalsEnabled = true; } } try { metrics = new Metrics( this ); Graph factionsVersionGraph = metrics.createGraph("Factions Version"); factionsVersionGraph.addPlotter(new Metrics.Plotter(FactionsVersion) { @Override public int getValue() { return 1; } }); metrics.start(); } catch ( IOException e ) { info( "Metrics could not start up: "+e.getMessage() ); } } catch (Throwable t) { FactionsPlus.severe( t ); if ( isEnabled() ) { disableSelf(); } } // try } // onEnable @Override public void onDisable() { Throwable failed = null; // TODO: find a way to chain all thrown exception rather than overwrite all older try { try { if(EssentialsIntegration.isHooked()) { EssentialsIntegration.onDisable(); } } catch ( Throwable t ) { failed = t; severe( t, "Exception on unhooking Essentials" ); } try { Config.deInit(); } catch ( Throwable t ) { failed = t; severe( t, "Exception on disabling Config" ); } // TODO: unhook Factions registered commands on disabling self else they'll still call our code and possibly NPE // since we deinited some of our parts; can add an if for each command and check if we're enabled and make it in a base class try { if ( LWCBase.isLWCPluginPresent() ) { LWCFunctions.unhookLWC(); } } catch ( Throwable t ) { failed = t; severe( t, "Exception on unhooking LWC" ); } update_avab = false; // reset this here try { //FactionsPlusUpdate.ensureNotRunning(); } catch ( Throwable t ) { failed = t; severe( t, "Exception on disabling Updates" ); } try { getServer().getServicesManager().unregisterAll( this ); } catch ( Throwable t ) { failed = t; severe( t, "Exception on unregistering services" ); } try { HandlerList.unregisterAll( FactionsPlus.instance ); } catch ( Throwable t ) { failed = t; severe( t, "Exception on unregistering from HandlerList" ); } try { // This will deInit metrics, but it will be enabled again onEnable. getServer().getScheduler().cancelTasks( this ); } catch ( Throwable t ) { failed = t; severe( t, "Exception when canceling schedule tasks" ); } try { if(Bukkit.getScoreboardManager().getMainScoreboard().getObjective( FactionsPlusScoreboard.objective_name ) != null && (Config._extras._scoreboards.showScoreboardOfFactions._ || Config._extras._scoreboards.showScoreboardOfMap._ )) { Bukkit.getScoreboardManager().getMainScoreboard().getObjective( FactionsPlusScoreboard.objective_name ).unregister(); } } catch( Exception t ) { failed = t; severe( t, "Exception when removing scoreboard" ); } //TODO: investigate why nag author happens ... even though we seem to be shuttind down task correctly //some tasks still remain from both FP and Vault at this point if doing a server `reload` as soon as you see "[FactionsPlus] Ready." // List<BukkitWorker> workers = Bukkit.getScheduler().getActiveWorkers(); // info("Active Workers: "+workers.size()); // // for ( BukkitWorker bukkitWorker : workers ) { // info(" workerOwner: "+bukkitWorker.getOwner()+" taskId="+bukkitWorker.getTaskId() // +", "+bukkitWorker.getThread().getName()); // } if ( null == failed ) { info( "Disabled successfuly." ); } } catch ( Throwable t ) { failed = t; } finally { if ( null != failed ) { info( "Did not disable successfuly! Please check over exceptions." ); } } } // onDisable }
src/markehme/factionsplus/FactionsPlus.java
package markehme.factionsplus; import java.io.IOException; import java.util.Set; import java.util.logging.Logger; import markehme.factionsplus.config.Config; import markehme.factionsplus.extras.LWCBase; import markehme.factionsplus.extras.LWCFunctions; import markehme.factionsplus.extras.Metrics; import markehme.factionsplus.extras.Metrics.Graph; import markehme.factionsplus.listeners.CoreListener; import markehme.factionsplus.listeners.FPConfigLoadedListener; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.event.HandlerList; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import com.massivecraft.factions.Factions; import com.massivecraft.factions.entity.MConf; import com.onarandombox.MultiversePortals.MultiversePortals; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; public class FactionsPlus extends FactionsPlusPlugin { public static FactionsPlus instance; public static Logger log = Logger.getLogger("Minecraft"); Factions factions; public static Permission permission = null; public static boolean isWorldEditEnabled = false; public static boolean isWorldGuardEnabled = false; public static boolean isMultiversePortalsEnabled = false; public final CoreListener corelistener = new CoreListener(); public static WorldEditPlugin worldEditPlugin = null; public static WorldGuardPlugin worldGuardPlugin = null; public static MultiversePortals multiversePortalsPlugin = null; public static String version; public static String FactionsVersion; private static Metrics metrics = null; public static Set<String> ignoredPvPWorlds = null; public static Set<String> noClaimingWorlds = null; public static Set<String> noPowerLossWorlds = null; public static Server server; public static boolean update_avab; public FactionsPlus() { super(); if ( null != instance ) { throw bailOut( "This was not expected, getting new-ed again without getting unloaded first.\n" + "Safest way to reload is to stop and start the server!" ); } instance = this; } @Override public void onEnable() { try { super.onEnable(); ignoredPvPWorlds = MConf.get().worldsIgnorePvP; noClaimingWorlds = MConf.get().worldsNoClaiming; noPowerLossWorlds = MConf.get().worldsNoPowerLoss; version = getDescription().getVersion(); Config.init(); PluginManager pm = this.getServer().getPluginManager(); FactionsVersion = pm.getPlugin( "Factions" ).getDescription().getVersion(); info("Factions v" + FactionsVersion ); pm.registerEvents( new FPConfigLoadedListener(), this ); Config.reload(); pm.registerEvents( this.corelistener, this ); server = getServer(); FactionsPlusCommandManager.setup(); RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration( net.milkbowl.vault.permission.Permission.class ); if ( permissionProvider != null ) { permission = permissionProvider.getProvider(); } if( 1<2 ) { if( pm.isPluginEnabled( "WorldEdit" ) ) { worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin( "WorldEdit" ); isWorldEditEnabled = true; } if( pm.isPluginEnabled( "WorldGuard" ) ) { worldGuardPlugin = ( WorldGuardPlugin ) getServer().getPluginManager().getPlugin( "WorldGuard" ); isWorldGuardEnabled = true; } } if( pm.isPluginEnabled( "Multiverse-Portals" ) ) { Plugin MVc = getServer().getPluginManager().getPlugin( "Multiverse-Portals" ); if (MVc instanceof MultiversePortals) { multiversePortalsPlugin = ( MultiversePortals ) MVc; isMultiversePortalsEnabled = true; } } try { metrics = new Metrics( this ); Graph factionsVersionGraph = metrics.createGraph("Factions Version"); factionsVersionGraph.addPlotter(new Metrics.Plotter(FactionsVersion) { @Override public int getValue() { return 1; } }); metrics.start(); } catch ( IOException e ) { info( "Metrics could not start up: "+e.getMessage() ); } } catch (Throwable t) { FactionsPlus.severe( t ); if ( isEnabled() ) { disableSelf(); } } // try } // onEnable @Override public void onDisable() { Throwable failed = null; // TODO: find a way to chain all thrown exception rather than overwrite all older try { try { EssentialsIntegration.onDisable(); } catch ( Throwable t ) { failed = t; severe( t, "Exception on unhooking Essentials:" ); } try { Config.deInit(); } catch ( Throwable t ) { failed = t; severe( t, "Exception on disabling Config:" ); } // TODO: unhook Factions registered commands on disabling self else they'll still call our code and possibly NPE // since we deinited some of our parts; can add an if for each command and check if we're enabled and make it in a base class try { if ( LWCBase.isLWCPluginPresent() ) { LWCFunctions.unhookLWC(); } } catch ( Throwable t ) { failed = t; severe( t, "Exception on unhooking LWC:" ); } update_avab = false; // reset this here try { FactionsPlusUpdate.ensureNotRunning(); } catch ( Throwable t ) { failed = t; severe( t, "Exception on disabling Updates:" ); } try { getServer().getServicesManager().unregisterAll( this ); } catch ( Throwable t ) { failed = t; severe( t, "Exception on unregistering services:" ); } try { HandlerList.unregisterAll( FactionsPlus.instance ); } catch ( Throwable t ) { failed = t; severe( t, "Exception on unregistering from HandlerList:" ); } try { // This will deInit metrics, but it will be enabled again onEnable. getServer().getScheduler().cancelTasks( this ); } catch ( Throwable t ) { failed = t; severe( t, "Exception when canceling schedule tasks:" ); } try { if(Config._extras._scoreboards.showScoreboardOfFactions._ || Config._extras._scoreboards.showScoreboardOfMap._ ) { Bukkit.getScoreboardManager().getMainScoreboard().getObjective( FactionsPlusScoreboard.objective_name ).unregister(); } } catch( Exception t ) { failed = t; severe( t, "Exception when removing scoreboard:" ); } //TODO: investigate why nag author happens ... even though we seem to be shuttind down task correctly //some tasks still remain from both FP and Vault at this point if doing a server `reload` as soon as you see "[FactionsPlus] Ready." // List<BukkitWorker> workers = Bukkit.getScheduler().getActiveWorkers(); // info("Active Workers: "+workers.size()); // // for ( BukkitWorker bukkitWorker : workers ) { // info(" workerOwner: "+bukkitWorker.getOwner()+" taskId="+bukkitWorker.getTaskId() // +", "+bukkitWorker.getThread().getName()); // } if ( null == failed ) { info( "Disabled successfuly." ); } } catch ( Throwable t ) { failed = t; } finally { if ( null != failed ) { info( "Did not disable successfuly! Please check over exceptions." ); } } } // onDisable }
Sorting scoreboard disable issues, and cleaning up
src/markehme/factionsplus/FactionsPlus.java
Sorting scoreboard disable issues, and cleaning up
<ide><path>rc/markehme/factionsplus/FactionsPlus.java <ide> info( "Metrics could not start up: "+e.getMessage() ); <ide> <ide> } <del> <add> <ide> } catch (Throwable t) { <ide> FactionsPlus.severe( t ); <ide> if ( isEnabled() ) { <ide> <ide> try { <ide> try { <del> EssentialsIntegration.onDisable(); <del> } catch ( Throwable t ) { <del> failed = t; <del> severe( t, "Exception on unhooking Essentials:" ); <add> if(EssentialsIntegration.isHooked()) { <add> EssentialsIntegration.onDisable(); <add> } <add> } catch ( Throwable t ) { <add> failed = t; <add> severe( t, "Exception on unhooking Essentials" ); <ide> } <ide> <ide> try { <ide> Config.deInit(); <ide> } catch ( Throwable t ) { <ide> failed = t; <del> severe( t, "Exception on disabling Config:" ); <add> severe( t, "Exception on disabling Config" ); <ide> } <ide> <ide> // TODO: unhook Factions registered commands on disabling self else they'll still call our code and possibly NPE <ide> } <ide> } catch ( Throwable t ) { <ide> failed = t; <del> severe( t, "Exception on unhooking LWC:" ); <add> severe( t, "Exception on unhooking LWC" ); <ide> } <ide> <ide> update_avab = false; // reset this here <ide> <ide> try { <del> FactionsPlusUpdate.ensureNotRunning(); <del> } catch ( Throwable t ) { <del> failed = t; <del> severe( t, "Exception on disabling Updates:" ); <add> //FactionsPlusUpdate.ensureNotRunning(); <add> } catch ( Throwable t ) { <add> failed = t; <add> severe( t, "Exception on disabling Updates" ); <ide> } <ide> <ide> try { <ide> getServer().getServicesManager().unregisterAll( this ); <ide> } catch ( Throwable t ) { <ide> failed = t; <del> severe( t, "Exception on unregistering services:" ); <add> severe( t, "Exception on unregistering services" ); <ide> } <ide> <ide> try { <ide> HandlerList.unregisterAll( FactionsPlus.instance ); <ide> } catch ( Throwable t ) { <ide> failed = t; <del> severe( t, "Exception on unregistering from HandlerList:" ); <add> severe( t, "Exception on unregistering from HandlerList" ); <ide> } <ide> <ide> try { <ide> getServer().getScheduler().cancelTasks( this ); <ide> } catch ( Throwable t ) { <ide> failed = t; <del> severe( t, "Exception when canceling schedule tasks:" ); <del> } <del> <del> try { <del> if(Config._extras._scoreboards.showScoreboardOfFactions._ || Config._extras._scoreboards.showScoreboardOfMap._ ) { <add> severe( t, "Exception when canceling schedule tasks" ); <add> } <add> <add> try { <add> if(Bukkit.getScoreboardManager().getMainScoreboard().getObjective( FactionsPlusScoreboard.objective_name ) != null && <add> (Config._extras._scoreboards.showScoreboardOfFactions._ || Config._extras._scoreboards.showScoreboardOfMap._ )) { <add> <ide> Bukkit.getScoreboardManager().getMainScoreboard().getObjective( FactionsPlusScoreboard.objective_name ).unregister(); <ide> } <ide> <ide> } catch( Exception t ) { <ide> failed = t; <del> severe( t, "Exception when removing scoreboard:" ); <add> severe( t, "Exception when removing scoreboard" ); <ide> } <ide> <ide> //TODO: investigate why nag author happens ... even though we seem to be shuttind down task correctly
Java
mit
e607bb7ad23db6c05c6350290c67762f654fd0b3
0
aaberg/sql2o,dheerajarora/sql2o,minecrafter/sql2o,trfiladelfo/sql2o,indvd00m/sql2o,xaled/sql2o,mugizico/sql2o
package org.sql2o.data; import org.sql2o.Sql2oException; import org.sql2o.converters.*; import org.sql2o.quirks.Quirks; import java.math.BigDecimal; import java.util.*; import static java.util.Arrays.asList; import static org.sql2o.converters.Convert.throwIfNull; /** * Represents a result set row. */ @SuppressWarnings({"UnusedDeclaration", "RedundantTypeArguments"}) public class Row { private final Object[] values; private final boolean isCaseSensitive; private final Quirks quirks; private final Map<String, Integer> columnNameToIdxMap; public Row(Map<String, Integer> columnNameToIdxMap, boolean isCaseSensitive, Quirks quirks) { this.columnNameToIdxMap = columnNameToIdxMap; this.isCaseSensitive = isCaseSensitive; this.quirks = quirks; // lol. array works better this.values = new Object[columnNameToIdxMap.size()]; } void addValue(int columnIndex, Object value){ values[columnIndex]=value; } public Object getObject(int columnIndex){ return values[columnIndex]; } public Object getObject(String columnName){ Integer index = columnNameToIdxMap.get( isCaseSensitive?columnName :columnName.toLowerCase()); if(index!=null) return getObject(index); throw new Sql2oException(String.format("Column with name '%s' does not exist", columnName)); } @SuppressWarnings("unchecked") public <V> V getObject(int columnIndex, Class clazz){ try{ return (V) throwIfNull(clazz, quirks.converterOf(clazz)).convert(getObject(columnIndex)); } catch (ConverterException ex){ throw new Sql2oException("Error converting value", ex); } } @SuppressWarnings("unchecked") public <V> V getObject(String columnName, Class clazz) { try{ return (V) throwIfNull(clazz, quirks.converterOf(clazz)).convert(getObject(columnName)); } catch (ConverterException ex){ throw new Sql2oException("Error converting value", ex); } } public BigDecimal getBigDecimal(int columnIndex){ return this.<BigDecimal>getObject(columnIndex, BigDecimal.class); } public BigDecimal getBigDecimal(String columnName){ return this.<BigDecimal>getObject(columnName, BigDecimal.class); } public Double getDouble(int columnIndex){ return this.<Double>getObject(columnIndex, Double.class); } public Double getDouble(String columnName){ return this.<Double>getObject(columnName, Double.class); } public Float getFloat(int columnIndex){ return this.<Float>getObject(columnIndex, Float.class); } public Float getFloat(String columnName){ return this.<Float>getObject(columnName, Float.class); } public Long getLong(int columnIndex){ return this.<Long>getObject(columnIndex, Long.class); } public Long getLong(String columnName){ return this.<Long>getObject(columnName, Long.class); } public Integer getInteger(int columnIndex){ return this.<Integer>getObject(columnIndex, Integer.class); } public Integer getInteger(String columnName){ return this.<Integer>getObject(columnName, Integer.class); } public Short getShort(int columnIndex){ return this.<Short>getObject(columnIndex, Short.class); } public Short getShort(String columnName){ return this.<Short>getObject(columnName, Short.class); } public Byte getByte(int columnIndex){ return this.<Byte>getObject(columnIndex, Byte.class); } public Byte getByte(String columnName){ return this.<Byte>getObject(columnName, Byte.class); } public Date getDate(int columnIndex){ return this.<Date>getObject(columnIndex, Date.class); } public Date getDate(String columnName){ return this.<Date>getObject(columnName, Date.class); } public String getString(int columnIndex){ return this.<String>getObject(columnIndex, String.class); } public String getString(String columnName){ return this.<String>getObject(columnName, String.class); } /** * View row as a simple map. */ @SuppressWarnings("NullableProblems") public Map<String, Object> asMap() { final List<Object> listOfValues = asList(values); return new Map<String, Object>() { public int size() { return values.length; } public boolean isEmpty() { return size()==0; } public boolean containsKey(Object key) { return columnNameToIdxMap.containsKey(key); } public boolean containsValue(Object value) { return listOfValues.contains(value); } public Object get(Object key) { return values[columnNameToIdxMap.get(key)]; } public Object put(String key, Object value) { throw new UnsupportedOperationException("Row map is immutable."); } public Object remove(Object key) { throw new UnsupportedOperationException("Row map is immutable."); } public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("Row map is immutable."); } public void clear() { throw new UnsupportedOperationException("Row map is immutable."); } public Set<String> keySet() { return columnNameToIdxMap.keySet(); } public Collection<Object> values() { return listOfValues; } public Set<Entry<String, Object>> entrySet() { throw new UnsupportedOperationException("Row map does not support entrySet."); } }; } }
core/src/main/java/org/sql2o/data/Row.java
package org.sql2o.data; import org.sql2o.Sql2oException; import org.sql2o.converters.*; import org.sql2o.quirks.Quirks; import java.math.BigDecimal; import java.util.*; import static org.sql2o.converters.Convert.throwIfNull; /** * Represents a result set row. */ public class Row { private Map<Integer, Object> values; private boolean isCaseSensitive; private final Quirks quirks; private Map<String, Integer> columnNameToIdxMap; public Row(Map<String, Integer> columnNameToIdxMap, boolean isCaseSensitive, Quirks quirks) { this.columnNameToIdxMap = columnNameToIdxMap; this.isCaseSensitive = isCaseSensitive; this.quirks = quirks; this.values = new HashMap<Integer, Object>(); } void addValue(int columnIndex, Object value){ values.put(columnIndex, value); } public Object getObject(int columnIndex){ return values.get(columnIndex); } public Object getObject(String columnName){ String col = isCaseSensitive ? columnName : columnName.toLowerCase(); Object obj; try{ obj = getObject(columnNameToIdxMap.get(col)); } catch (NullPointerException ex){ throw new Sql2oException(String.format("Column with name '%s' does not exist", columnName), ex); } return obj; } @SuppressWarnings("unchecked") public <V> V getObject(int columnIndex, Class clazz){ try{ return (V) throwIfNull(clazz, quirks.converterOf(clazz)).convert(getObject(columnIndex)); } catch (ConverterException ex){ throw new Sql2oException("Error converting value", ex); } } @SuppressWarnings("unchecked") public <V> V getObject(String columnName, Class clazz) { try{ return (V) throwIfNull(clazz, quirks.converterOf(clazz)).convert(getObject(columnName)); } catch (ConverterException ex){ throw new Sql2oException("Error converting value", ex); } } public BigDecimal getBigDecimal(int columnIndex){ return new BigDecimalConverter().convert(getObject(columnIndex)); } public BigDecimal getBigDecimal(String columnName){ return new BigDecimalConverter().convert(getObject(columnName)); } public Double getDouble(int columnIndex){ return new DoubleConverter(false).convert(getObject(columnIndex)); } public Double getDouble(String columnName){ return new DoubleConverter(false).convert(getObject(columnName)); } public Float getFloat(int columnIndex){ return new FloatConverter(false).convert(getObject(columnIndex)); } public Float getFloat(String columnName){ return new FloatConverter(false).convert(getObject(columnName)); } public Long getLong(int columnIndex){ return new LongConverter(false).convert(getObject(columnIndex)); } public Long getLong(String columnName){ return new LongConverter(false).convert(getObject(columnName)); } public Integer getInteger(int columnIndex){ return new IntegerConverter(false).convert(getObject(columnIndex)); } public Integer getInteger(String columnName){ return new IntegerConverter(false).convert(getObject(columnName)); } public Short getShort(int columnIndex){ return new ShortConverter(false).convert(getObject(columnIndex)); } public Short getShort(String columnName){ return new ShortConverter(false).convert(getObject(columnName)); } public Byte getByte(int columnIndex){ return new ByteConverter(false).convert(getObject(columnIndex)); } public Byte getByte(String columnName){ return new ByteConverter(false).convert(getObject(columnName)); } public Date getDate(int columnIndex){ try { return DateConverter.instance.convert(getObject(columnIndex)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + Date.class.toString()); } } public Date getDate(String columnName){ try { return DateConverter.instance.convert(getObject(columnName)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with name " + columnName + " to " + Date.class.toString()); } } public String getString(int columnIndex){ try { return new StringConverter().convert(getObject(columnIndex)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + String.class.getName()); } } public String getString(String columnName){ try { return new StringConverter().convert(getObject(columnName)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with name " + columnName+ " to " + String.class.getName()); } } /** * View row as a simple map. */ public Map<String, Object> asMap() { return new Map<String, Object>() { public int size() { return values.size(); } public boolean isEmpty() { return values.isEmpty(); } public boolean containsKey(Object key) { return columnNameToIdxMap.containsKey(key); } public boolean containsValue(Object value) { return values.containsValue(value); } public Object get(Object key) { return values.get(columnNameToIdxMap.get(key)); } public Object put(String key, Object value) { throw new UnsupportedOperationException("Row map is immutable."); } public Object remove(Object key) { throw new UnsupportedOperationException("Row map is immutable."); } public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("Row map is immutable."); } public void clear() { throw new UnsupportedOperationException("Row map is immutable."); } public Set<String> keySet() { return columnNameToIdxMap.keySet(); } public Collection<Object> values() { return values.values(); } public Set<Entry<String, Object>> entrySet() { throw new UnsupportedOperationException("Row map does not support entrySet."); } }; } }
tables and rows now use same infrastructure
core/src/main/java/org/sql2o/data/Row.java
tables and rows now use same infrastructure
<ide><path>ore/src/main/java/org/sql2o/data/Row.java <ide> import java.math.BigDecimal; <ide> import java.util.*; <ide> <add>import static java.util.Arrays.asList; <ide> import static org.sql2o.converters.Convert.throwIfNull; <ide> <ide> /** <ide> * Represents a result set row. <ide> */ <add>@SuppressWarnings({"UnusedDeclaration", "RedundantTypeArguments"}) <ide> public class Row { <ide> <del> private Map<Integer, Object> values; <del> <del> private boolean isCaseSensitive; <add> private final Object[] values; <add> private final boolean isCaseSensitive; <ide> private final Quirks quirks; <del> private Map<String, Integer> columnNameToIdxMap; <add> private final Map<String, Integer> columnNameToIdxMap; <ide> <ide> public Row(Map<String, Integer> columnNameToIdxMap, boolean isCaseSensitive, Quirks quirks) { <ide> this.columnNameToIdxMap = columnNameToIdxMap; <ide> this.isCaseSensitive = isCaseSensitive; <ide> this.quirks = quirks; <del> this.values = new HashMap<Integer, Object>(); <add> // lol. array works better <add> this.values = new Object[columnNameToIdxMap.size()]; <ide> } <ide> <ide> void addValue(int columnIndex, Object value){ <del> values.put(columnIndex, value); <add> values[columnIndex]=value; <ide> } <ide> <ide> public Object getObject(int columnIndex){ <del> return values.get(columnIndex); <add> return values[columnIndex]; <ide> } <ide> <ide> public Object getObject(String columnName){ <del> String col = isCaseSensitive ? columnName : columnName.toLowerCase(); <del> <del> Object obj; <del> try{ <del> obj = getObject(columnNameToIdxMap.get(col)); <del> } <del> catch (NullPointerException ex){ <del> throw new Sql2oException(String.format("Column with name '%s' does not exist", columnName), ex); <del> } <del> <del> return obj; <add> Integer index = columnNameToIdxMap.get( <add> isCaseSensitive?columnName <add> :columnName.toLowerCase()); <add> if(index!=null) return getObject(index); <add> throw new Sql2oException(String.format("Column with name '%s' does not exist", columnName)); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <ide> } <ide> <ide> public BigDecimal getBigDecimal(int columnIndex){ <del> return new BigDecimalConverter().convert(getObject(columnIndex)); <add> return this.<BigDecimal>getObject(columnIndex, BigDecimal.class); <ide> } <ide> <ide> public BigDecimal getBigDecimal(String columnName){ <del> return new BigDecimalConverter().convert(getObject(columnName)); <add> return this.<BigDecimal>getObject(columnName, BigDecimal.class); <ide> } <ide> <ide> public Double getDouble(int columnIndex){ <del> return new DoubleConverter(false).convert(getObject(columnIndex)); <add> return this.<Double>getObject(columnIndex, Double.class); <ide> } <ide> <ide> public Double getDouble(String columnName){ <del> return new DoubleConverter(false).convert(getObject(columnName)); <add> return this.<Double>getObject(columnName, Double.class); <ide> } <ide> <ide> public Float getFloat(int columnIndex){ <del> return new FloatConverter(false).convert(getObject(columnIndex)); <add> return this.<Float>getObject(columnIndex, Float.class); <ide> } <ide> <ide> public Float getFloat(String columnName){ <del> return new FloatConverter(false).convert(getObject(columnName)); <add> return this.<Float>getObject(columnName, Float.class); <ide> } <ide> <ide> public Long getLong(int columnIndex){ <del> return new LongConverter(false).convert(getObject(columnIndex)); <add> return this.<Long>getObject(columnIndex, Long.class); <ide> } <ide> <ide> public Long getLong(String columnName){ <del> return new LongConverter(false).convert(getObject(columnName)); <add> return this.<Long>getObject(columnName, Long.class); <ide> } <ide> <ide> public Integer getInteger(int columnIndex){ <del> return new IntegerConverter(false).convert(getObject(columnIndex)); <add> return this.<Integer>getObject(columnIndex, Integer.class); <ide> } <ide> <ide> public Integer getInteger(String columnName){ <del> return new IntegerConverter(false).convert(getObject(columnName)); <add> return this.<Integer>getObject(columnName, Integer.class); <ide> } <ide> <ide> public Short getShort(int columnIndex){ <del> return new ShortConverter(false).convert(getObject(columnIndex)); <add> return this.<Short>getObject(columnIndex, Short.class); <ide> } <ide> <ide> public Short getShort(String columnName){ <del> return new ShortConverter(false).convert(getObject(columnName)); <add> return this.<Short>getObject(columnName, Short.class); <ide> } <ide> <ide> public Byte getByte(int columnIndex){ <del> return new ByteConverter(false).convert(getObject(columnIndex)); <add> return this.<Byte>getObject(columnIndex, Byte.class); <ide> } <ide> <ide> public Byte getByte(String columnName){ <del> return new ByteConverter(false).convert(getObject(columnName)); <add> return this.<Byte>getObject(columnName, Byte.class); <ide> } <ide> <ide> public Date getDate(int columnIndex){ <del> try { <del> return DateConverter.instance.convert(getObject(columnIndex)); <del> } catch (ConverterException e) { <del> throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + Date.class.toString()); <del> } <add> return this.<Date>getObject(columnIndex, Date.class); <ide> } <ide> <ide> public Date getDate(String columnName){ <del> try { <del> return DateConverter.instance.convert(getObject(columnName)); <del> } catch (ConverterException e) { <del> throw new Sql2oException("Could not convert column with name " + columnName + " to " + Date.class.toString()); <del> } <add> return this.<Date>getObject(columnName, Date.class); <ide> } <ide> <ide> public String getString(int columnIndex){ <del> try { <del> return new StringConverter().convert(getObject(columnIndex)); <del> } catch (ConverterException e) { <del> throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + String.class.getName()); <del> } <add> return this.<String>getObject(columnIndex, String.class); <ide> } <ide> <ide> public String getString(String columnName){ <del> try { <del> return new StringConverter().convert(getObject(columnName)); <del> } catch (ConverterException e) { <del> throw new Sql2oException("Could not convert column with name " + columnName+ " to " + String.class.getName()); <del> } <add> return this.<String>getObject(columnName, String.class); <ide> } <ide> <ide> /** <ide> * View row as a simple map. <ide> */ <add> @SuppressWarnings("NullableProblems") <ide> public Map<String, Object> asMap() <del> { <add> { final List<Object> listOfValues = asList(values); <ide> return new Map<String, Object>() { <ide> public int size() { <del> return values.size(); <add> return values.length; <ide> } <ide> <ide> public boolean isEmpty() { <del> return values.isEmpty(); <add> return size()==0; <ide> } <ide> <ide> public boolean containsKey(Object key) { <ide> } <ide> <ide> public boolean containsValue(Object value) { <del> return values.containsValue(value); <add> return listOfValues.contains(value); <ide> } <ide> <ide> public Object get(Object key) { <del> return values.get(columnNameToIdxMap.get(key)); <add> return values[columnNameToIdxMap.get(key)]; <ide> } <ide> <ide> public Object put(String key, Object value) { <ide> } <ide> <ide> public Collection<Object> values() { <del> return values.values(); <add> return listOfValues; <ide> } <ide> <ide> public Set<Entry<String, Object>> entrySet() {
Java
apache-2.0
5be467bc1d6b3379734e2a6f55555c11c0deb53a
0
foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2
/** * @license * Copyright 2018 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.http; import foam.core.ClassInfo; import foam.core.ProxyX; import foam.core.EmptyX; import foam.core.X; import foam.lib.parse.ErrorReportingPStream; import foam.lib.parse.PStream; import foam.lib.parse.Parser; import foam.lib.parse.ParserContext; import foam.lib.parse.ParserContextImpl; import foam.lib.parse.StringPStream; import foam.parse.QueryParser; import foam.mlang.predicate.Predicate; import foam.mlang.predicate.Nary; import foam.mlang.MLang; import foam.nanos.logger.Logger; import foam.nanos.logger.PrefixLogger; import foam.util.SafetyUtil; // // Wrap the common WebAgent use case of QueryParser // to extract and compile the 'q' (mql) URL query. // public class WebAgentQueryParser { protected QueryParser parser_; public WebAgentQueryParser(ClassInfo classInfo) { parser_ = new QueryParser(classInfo); } public Predicate parse(X x, String q) throws IllegalArgumentException { if ( ! SafetyUtil.isEmpty(q) ) { Logger logger = (Logger) x.get("logger"); StringPStream sps = new StringPStream(); PStream ps = sps; ParserContext px = new ParserContextImpl(); sps.setString(q); ps = parser_.parse(ps, px); if ( ps == null ) { String message = getParsingError(x, q); logger.error(this.getClass().getSimpleName(), "failed to parse q", message); throw new IllegalArgumentException("failed to parse [" + q + "]: " + message); } parser_.setX(EmptyX.instance()); Predicate pred = (Predicate) ps.value(); logger.debug(this.getClass().getSimpleName(), "pred", pred.getClass(), pred.toString()); return pred; } return MLang.TRUE; } /** * Gets the result of a failing parsing of a buffer * @param buffer the buffer that failed to be parsed * @return the error message */ protected String getParsingError(X x, String buffer) { PStream ps = new StringPStream(); ParserContext psx = new ParserContextImpl(); ((StringPStream) ps).setString(buffer); psx.set("X", x == null ? new ProxyX() : x); ErrorReportingPStream eps = new ErrorReportingPStream(ps); ps = eps.apply(parser_, psx); return eps.getMessage(); } }
src/foam/nanos/http/WebAgentQueryParser.java
/** * @license * Copyright 2018 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.http; import foam.core.ClassInfo; import foam.core.ProxyX; import foam.core.EmptyX; import foam.core.X; import foam.lib.parse.ErrorReportingPStream; import foam.lib.parse.PStream; import foam.lib.parse.Parser; import foam.lib.parse.ParserContext; import foam.lib.parse.ParserContextImpl; import foam.lib.parse.StringPStream; import foam.parse.QueryParser; import foam.mlang.predicate.Predicate; import foam.mlang.predicate.Nary; import foam.mlang.MLang; import foam.nanos.logger.Logger; import foam.nanos.logger.PrefixLogger; import foam.util.SafetyUtil; // // Wrap the common WebAgent use case of QueryParser // to extract and compile the 'q' (mql) URL query. // public class WebAgentQueryParser { protected QueryParser parser_; public WebAgentQueryParser(ClassInfo classInfo) { parser_ = new QueryParser(classInfo); } public Predicate parse(X x, String q) throws IllegalArgumentException { if ( ! SafetyUtil.isEmpty(q) ) { Logger logger = (Logger) x.get("logger"); logger.debug(this.getClass().getSimpleName(), "q", q); StringPStream sps = new StringPStream(); sps.setString(q); PStream ps = sps; ParserContext px = new ParserContextImpl(); ps = parser_.parse(ps, px); if ( ps == null ) { String message = getParsingError(x, q); logger.error(this.getClass().getSimpleName(), "failed to parse q", message); throw new IllegalArgumentException("failed to parse [" + q + "]: "+message); } parser_.setX(EmptyX.instance()); Predicate pred = (Predicate) ps.value(); logger.debug(this.getClass().getSimpleName(), "pred", pred.getClass(), pred.toString()); return pred; } return MLang.TRUE; } /** * Gets the result of a failing parsing of a buffer * @param buffer the buffer that failed to be parsed * @return the error message */ protected String getParsingError(X x, String buffer) { Parser parser = foam.lib.json.ExprParser.instance(); PStream ps = new StringPStream(); ParserContext psx = new ParserContextImpl(); ((StringPStream) ps).setString(buffer); psx.set("X", x == null ? new ProxyX() : x); ErrorReportingPStream eps = new ErrorReportingPStream(ps); ps = eps.apply(parser, psx); return eps.getMessage(); } }
Fix error reporting in WebAgentQueryParser.
src/foam/nanos/http/WebAgentQueryParser.java
Fix error reporting in WebAgentQueryParser.
<ide><path>rc/foam/nanos/http/WebAgentQueryParser.java <ide> throws IllegalArgumentException { <ide> <ide> if ( ! SafetyUtil.isEmpty(q) ) { <del> Logger logger = (Logger) x.get("logger"); <del> logger.debug(this.getClass().getSimpleName(), "q", q); <del> StringPStream sps = new StringPStream(); <add> Logger logger = (Logger) x.get("logger"); <add> StringPStream sps = new StringPStream(); <add> PStream ps = sps; <add> ParserContext px = new ParserContextImpl(); <add> <ide> sps.setString(q); <del> PStream ps = sps; <del> ParserContext px = new ParserContextImpl(); <ide> ps = parser_.parse(ps, px); <add> <ide> if ( ps == null ) { <ide> String message = getParsingError(x, q); <ide> logger.error(this.getClass().getSimpleName(), "failed to parse q", message); <del> throw new IllegalArgumentException("failed to parse [" + q + "]: "+message); <add> throw new IllegalArgumentException("failed to parse [" + q + "]: " + message); <ide> } <add> <ide> parser_.setX(EmptyX.instance()); <ide> Predicate pred = (Predicate) ps.value(); <ide> logger.debug(this.getClass().getSimpleName(), "pred", pred.getClass(), pred.toString()); <ide> return pred; <ide> } <add> <ide> return MLang.TRUE; <ide> } <ide> <ide> * @return the error message <ide> */ <ide> protected String getParsingError(X x, String buffer) { <del> Parser parser = foam.lib.json.ExprParser.instance(); <del> PStream ps = new StringPStream(); <del> ParserContext psx = new ParserContextImpl(); <add> PStream ps = new StringPStream(); <add> ParserContext psx = new ParserContextImpl(); <ide> <ide> ((StringPStream) ps).setString(buffer); <ide> psx.set("X", x == null ? new ProxyX() : x); <ide> <ide> ErrorReportingPStream eps = new ErrorReportingPStream(ps); <del> ps = eps.apply(parser, psx); <add> ps = eps.apply(parser_, psx); <ide> return eps.getMessage(); <ide> } <ide> }
Java
mit
error: pathspec 'Weather.java' did not match any file(s) known to git
4503bd0936d6b775da44845170127c3b4103cc7c
1
code-for-coffee/AndroidSnippets
public class Weather { public final String DAY_OF_WEEK; public final String MIN_TEMP; public final String MAX_TEMP; public final String HUMIDITY; public final String DESCRIPTION; public final String ICON_URL; private static String convertTimeStampToDay(long timeStamp) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(timeStamp * 1000); TimeZone tz = TimeZone.getDefault(); cal.add(Calendar.MILLISECOND, tz.getOffset(cal.getTimeInMillis())); SimpleDateFormat df = new SimpleDateFormat("EEEE"); return df.format(cal.getTime()); } public Weather(long timeStamp, double minTemp, double maxTemp, double humidity, String description, String iconName) { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(0); this.DAY_OF_WEEK = convertTimeStampToDay(timeStamp); this.MIN_TEMP = nf.format(minTemp) + "\u00B0F"; this.MAX_TEMP = nf.format(maxTemp) + "\u00B0F"; this.HUMIDITY = nf.getPercentInstance().format(humidity / 100.0); this.DESCRIPTION = description; this.ICON_URL = "http://openweathermap.org/img/w/" + iconName + ".png"; } }
Weather.java
weather model for openweathermap.org
Weather.java
weather model for openweathermap.org
<ide><path>eather.java <add>public class Weather { <add> <add> public final String DAY_OF_WEEK; <add> public final String MIN_TEMP; <add> public final String MAX_TEMP; <add> public final String HUMIDITY; <add> public final String DESCRIPTION; <add> public final String ICON_URL; <add> <add> private static String convertTimeStampToDay(long timeStamp) { <add> Calendar cal = Calendar.getInstance(); <add> cal.setTimeInMillis(timeStamp * 1000); <add> TimeZone tz = TimeZone.getDefault(); <add> cal.add(Calendar.MILLISECOND, tz.getOffset(cal.getTimeInMillis())); <add> <add> SimpleDateFormat df = new SimpleDateFormat("EEEE"); <add> return df.format(cal.getTime()); <add> } <add> <add> public Weather(long timeStamp, double minTemp, double maxTemp, double humidity, String description, String iconName) { <add> NumberFormat nf = NumberFormat.getInstance(); <add> nf.setMaximumFractionDigits(0); <add> this.DAY_OF_WEEK = convertTimeStampToDay(timeStamp); <add> this.MIN_TEMP = nf.format(minTemp) + "\u00B0F"; <add> this.MAX_TEMP = nf.format(maxTemp) + "\u00B0F"; <add> this.HUMIDITY = nf.getPercentInstance().format(humidity / 100.0); <add> this.DESCRIPTION = description; <add> this.ICON_URL = "http://openweathermap.org/img/w/" + iconName + ".png"; <add> } <add> <add>}
Java
apache-2.0
3259ddd877a527ecd739e640924078687470ce41
0
thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck
package org.ensembl.healthcheck.eg_gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.Box; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportLine; import org.ensembl.healthcheck.Reporter; import org.ensembl.healthcheck.eg_gui.Constants; import org.ensembl.healthcheck.eg_gui.JPopupTextArea; import org.ensembl.healthcheck.eg_gui.ReportPanel; import org.ensembl.healthcheck.testcase.EnsTestCase; public class GuiReporterTab extends JPanel implements Reporter { final protected TestClassList testList; final protected JScrollPane testListScrollPane; final protected TestClassListModel listModel; final protected ReportPanel reportPanel; final protected TestCaseColoredCellRenderer testCaseCellRenderer; protected boolean userClickedOnList = false; final protected Map<Class<? extends EnsTestCase>,GuiReportPanelData> reportData; public void selectDefaultListItem() { if (!userClickedOnList) { selectLastListItem(); } } /** * Selects the last item in the list and scrolls to that position. */ public void selectLastListItem() { if (listModel.getSize()>0) { int indexOfLastComponentInList =listModel.getSize()-1; testList.setSelectedIndex(indexOfLastComponentInList); testList.ensureIndexIsVisible(indexOfLastComponentInList); } } public GuiReporterTab() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); reportData = new HashMap<Class<? extends EnsTestCase>,GuiReportPanelData>(); testList = new TestClassList(TestClassList.TestClassListToolTipType.CLASS); listModel = new TestClassListModel(); reportPanel = new ReportPanel(); testList.setModel(listModel); testCaseCellRenderer = new TestCaseColoredCellRenderer(); testList.setCellRenderer(testCaseCellRenderer); testList.addMouseListener(new MouseListener() { // We want to know, when as soon as the user clicks somewhere on // the list so we can stop selecting the last item in the list. // @Override public void mouseClicked(MouseEvent arg0) { userClickedOnList = true; } @Override public void mouseEntered (MouseEvent arg0) {} @Override public void mouseExited (MouseEvent arg0) {} @Override public void mousePressed (MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); // Setting the preferred size causes the scrollbars to not be adapted // to the list changing size when items are added later on, so // commented out. // // testList.setPreferredSize( // new Dimension( // Constants.INITIAL_APPLICATION_WINDOW_WIDTH / 3, // Constants.INITIAL_APPLICATION_WINDOW_HEIGHT / 3 * 2 // ) // ); setLayout(new BorderLayout()); testListScrollPane = new JScrollPane(testList); add( new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, testListScrollPane, //new JScrollPane(reportPanel) reportPanel ), BorderLayout.CENTER ); testList.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { if (!arg0.getValueIsAdjusting()) { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } } ); } @Override public void message(final ReportLine reportLine) { final Class<? extends EnsTestCase> currentKey = reportLine.getTestCase().getClass(); if (!reportData.containsKey(currentKey)) { reportData.put(currentKey, new GuiReportPanelData(reportLine)); testCaseCellRenderer.setOutcome(currentKey, null); // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. // SwingUtilities.invokeLater( new Runnable() { @Override public void run() { listModel.addTest(currentKey); // If nothing has been selected, then select // something so the user is not staring at an // empty report. // //if (testList.isSelectionEmpty()) { if (!userClickedOnList) { selectDefaultListItem(); } } } ); } else { reportData.get(currentKey).addReportLine(reportLine); } // If anything was reported as a problem, the outcome is false. // if (reportLine.getLevel()==ReportLine.PROBLEM) { testCaseCellRenderer.setOutcome(currentKey, false); } // If a testcase has been selected, then display the new data in the // GUI so the user can see the new line in real time. // if (!testList.isSelectionEmpty()) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } ); } } @Override public void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) {} @Override public void finishTestCase( final EnsTestCase testCase, final boolean result, DatabaseRegistryEntry dbre ) { // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. // SwingUtilities.invokeLater( new Runnable() { @Override public void run() { testCaseCellRenderer.setOutcome(testCase.getClass(), result); } } ); } } class ReportPanel extends JPanel implements ActionListener, ComponentListener { final protected JTextField testName; final protected JPopupTextArea description; final protected JTextField teamResponsible; final protected JTextField speciesName; final protected JPopupTextArea message; final String copy_selected_text_action = "copy_selected_text_action"; protected Component createVerticalSpacing() { return Box.createVerticalStrut(Constants.DEFAULT_VERTICAL_COMPONENT_SPACING); } public ReportPanel() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); Box singleLineInfo = Box.createVerticalBox(); testName = new JPopupTextField("Name"); description = new JPopupTextArea(3, 0); teamResponsible = new JPopupTextField("Team Responsible"); speciesName = new JPopupTextField("Species Name"); message = new JPopupTextArea (); description.setLineWrap(true); description.setWrapStyleWord(true); GuiTestRunnerFrameComponentBuilder g = null; singleLineInfo.add(g.createLeftJustifiedText("Test class:")); singleLineInfo.add(testName); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Description:")); singleLineInfo.add(description); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Team responsible:")); singleLineInfo.add(teamResponsible); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Species name:")); singleLineInfo.add(speciesName); singleLineInfo.add(createVerticalSpacing()); setLayout(new BorderLayout()); final JPopupMenu popup = new JPopupMenu(); message.add(GuiTestRunnerFrameComponentBuilder.makeMenuItem("Copy selected text", this, copy_selected_text_action)); message.setComponentPopupMenu(popup); Font currentFont = message.getFont(); Font newFont = new Font( "Courier", currentFont.getStyle(), currentFont.getSize() ); message.setFont(newFont); message.setLineWrap(true); message.setWrapStyleWord(true); singleLineInfo.add(g.createLeftJustifiedText("Output from test:")); add(singleLineInfo, BorderLayout.NORTH); add(new JScrollPane(message), BorderLayout.CENTER); // This has to be set to something small otherwise we will get problems when // wrapping this in a JSplitPane: // // http://docs.oracle.com/javase/6/docs/api/javax/swing/JSplitPane.html // // "When the user is resizing the Components the minimum size of the // Components is used to determine the maximum/minimum position the // Components can be set to. If the minimum size of the two // components is greater than the size of the split pane the divider // will not allow you to resize it." // this.setMinimumSize(new Dimension(200,300)); this.addComponentListener(this); } public void setData(GuiReportPanelData reportData) { testName .setText (reportData.getTestName()); description .setText (reportData.getDescription()); speciesName .setText (reportData.getSpeciesName()); teamResponsible .setText (reportData.getTeamResponsible()); message .setText (reportData.getMessage()); } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.paramString().equals(copy_selected_text_action)) { String selection = message.getSelectedText(); StringSelection data = new StringSelection(selection); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(data, data); } } }
src/org/ensembl/healthcheck/eg_gui/GuiReporterTab.java
package org.ensembl.healthcheck.eg_gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Font; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.Box; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportLine; import org.ensembl.healthcheck.Reporter; import org.ensembl.healthcheck.eg_gui.Constants; import org.ensembl.healthcheck.eg_gui.JPopupTextArea; import org.ensembl.healthcheck.eg_gui.ReportPanel; import org.ensembl.healthcheck.testcase.EnsTestCase; public class GuiReporterTab extends JPanel implements Reporter { final protected TestClassList testList; final protected JScrollPane testListScrollPane; final protected TestClassListModel listModel; final protected ReportPanel reportPanel; final protected TestCaseColoredCellRenderer testCaseCellRenderer; protected boolean userClickedOnList = false; final protected Map<Class<? extends EnsTestCase>,GuiReportPanelData> reportData; public void selectDefaultListItem() { if (!userClickedOnList) { selectLastListItem(); } } /** * Selects the last item in the list and scrolls to that position. */ public void selectLastListItem() { if (listModel.getSize()>0) { int indexOfLastComponentInList =listModel.getSize()-1; testList.setSelectedIndex(indexOfLastComponentInList); testList.ensureIndexIsVisible(indexOfLastComponentInList); } } public GuiReporterTab() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); reportData = new HashMap<Class<? extends EnsTestCase>,GuiReportPanelData>(); testList = new TestClassList(TestClassList.TestClassListToolTipType.CLASS); listModel = new TestClassListModel(); reportPanel = new ReportPanel(); testList.setModel(listModel); testCaseCellRenderer = new TestCaseColoredCellRenderer(); testList.setCellRenderer(testCaseCellRenderer); testList.addMouseListener(new MouseListener() { // We want to know, when as soon as the user clicks somewhere on // the list so we can stop selecting the last item in the list. // @Override public void mouseClicked(MouseEvent arg0) { userClickedOnList = true; } @Override public void mouseEntered (MouseEvent arg0) {} @Override public void mouseExited (MouseEvent arg0) {} @Override public void mousePressed (MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); // Setting the preferred size causes the scrollbars to not be adapted // to the list changing size when items are added later on, so // commented out. // // testList.setPreferredSize( // new Dimension( // Constants.INITIAL_APPLICATION_WINDOW_WIDTH / 3, // Constants.INITIAL_APPLICATION_WINDOW_HEIGHT / 3 * 2 // ) // ); setLayout(new BorderLayout()); testListScrollPane = new JScrollPane(testList); add( new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, testListScrollPane, new JScrollPane(reportPanel) ), BorderLayout.CENTER ); testList.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { if (!arg0.getValueIsAdjusting()) { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } } ); } @Override public void message(final ReportLine reportLine) { final Class<? extends EnsTestCase> currentKey = reportLine.getTestCase().getClass(); if (!reportData.containsKey(currentKey)) { reportData.put(currentKey, new GuiReportPanelData(reportLine)); testCaseCellRenderer.setOutcome(currentKey, null); // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. // SwingUtilities.invokeLater( new Runnable() { @Override public void run() { listModel.addTest(currentKey); // If nothing has been selected, then select // something so the user is not staring at an // empty report. // //if (testList.isSelectionEmpty()) { if (!userClickedOnList) { selectDefaultListItem(); } } } ); } else { reportData.get(currentKey).addReportLine(reportLine); } // If anything was reported as a problem, the outcome is false. // if (reportLine.getLevel()==ReportLine.PROBLEM) { testCaseCellRenderer.setOutcome(currentKey, false); } // If a testcase has been selected, then display the new data in the // GUI so the user can see the new line in real time. // if (!testList.isSelectionEmpty()) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { reportPanel.setData( reportData.get( ( (TestClassListItem) listModel.getElementAt(testList.getSelectedIndex()) ).getTestClass() ) ); } } ); } } @Override public void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) {} @Override public void finishTestCase( final EnsTestCase testCase, final boolean result, DatabaseRegistryEntry dbre ) { // This method will be called from a different thread. Therefore // updates to the components must be run through SwingUtilities. // SwingUtilities.invokeLater( new Runnable() { @Override public void run() { testCaseCellRenderer.setOutcome(testCase.getClass(), result); } } ); } } class ReportPanel extends JPanel implements ActionListener { final protected JTextField testName; final protected JPopupTextArea description; final protected JTextField teamResponsible; final protected JTextField speciesName; final protected JPopupTextArea message; final String copy_selected_text_action = "copy_selected_text_action"; protected Component createVerticalSpacing() { return Box.createVerticalStrut(Constants.DEFAULT_VERTICAL_COMPONENT_SPACING); } public ReportPanel() { this.setBorder(GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder); Box singleLineInfo = Box.createVerticalBox(); testName = new JPopupTextField("Name"); description = new JPopupTextArea(3, 0); teamResponsible = new JPopupTextField("Team Responsible"); speciesName = new JPopupTextField("Species Name"); message = new JPopupTextArea (); description.setLineWrap(true); description.setWrapStyleWord(true); GuiTestRunnerFrameComponentBuilder g = null; singleLineInfo.add(g.createLeftJustifiedText("Test class:")); singleLineInfo.add(testName); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Description:")); singleLineInfo.add(description); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Team responsible:")); singleLineInfo.add(teamResponsible); singleLineInfo.add(createVerticalSpacing()); singleLineInfo.add(g.createLeftJustifiedText("Species name:")); singleLineInfo.add(speciesName); singleLineInfo.add(createVerticalSpacing()); setLayout(new BorderLayout()); final JPopupMenu popup = new JPopupMenu(); message.add(GuiTestRunnerFrameComponentBuilder.makeMenuItem("Copy selected text", this, copy_selected_text_action)); message.setComponentPopupMenu(popup); Font currentFont = message.getFont(); Font newFont = new Font( "Courier", currentFont.getStyle(), currentFont.getSize() ); message.setFont(newFont); message.setLineWrap(true); message.setWrapStyleWord(true); singleLineInfo.add(g.createLeftJustifiedText("Output from test:")); add(singleLineInfo, BorderLayout.NORTH); add(new JScrollPane(message), BorderLayout.CENTER); } public void setData(GuiReportPanelData reportData) { testName .setText (reportData.getTestName()); description .setText (reportData.getDescription()); speciesName .setText (reportData.getSpeciesName()); teamResponsible .setText (reportData.getTeamResponsible()); message .setText (reportData.getMessage()); } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.paramString().equals(copy_selected_text_action)) { String selection = message.getSelectedText(); StringSelection data = new StringSelection(selection); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(data, data); } } }
Finally found the reason why the divider in the GuiReportPanel couldn't be moved to the right. Fixed this.
src/org/ensembl/healthcheck/eg_gui/GuiReporterTab.java
Finally found the reason why the divider in the GuiReportPanel couldn't be moved to the right. Fixed this.
<ide><path>rc/org/ensembl/healthcheck/eg_gui/GuiReporterTab.java <ide> <ide> import java.awt.BorderLayout; <ide> import java.awt.Component; <add>import java.awt.Dimension; <ide> import java.awt.Font; <ide> import java.awt.Toolkit; <ide> import java.awt.datatransfer.Clipboard; <ide> import java.awt.datatransfer.StringSelection; <ide> import java.awt.event.ActionEvent; <ide> import java.awt.event.ActionListener; <add>import java.awt.event.ComponentAdapter; <add>import java.awt.event.ComponentEvent; <add>import java.awt.event.ComponentListener; <ide> import java.awt.event.MouseEvent; <ide> import java.awt.event.MouseListener; <ide> import java.util.HashMap; <ide> new JSplitPane( <ide> JSplitPane.HORIZONTAL_SPLIT, <ide> testListScrollPane, <del> new JScrollPane(reportPanel) <add> //new JScrollPane(reportPanel) <add> reportPanel <ide> ), BorderLayout.CENTER <ide> ); <ide> <ide> } <ide> } <ide> <del>class ReportPanel extends JPanel implements ActionListener { <add>class ReportPanel extends JPanel implements ActionListener, ComponentListener { <ide> <ide> final protected JTextField testName; <ide> final protected JPopupTextArea description; <ide> <ide> add(singleLineInfo, BorderLayout.NORTH); <ide> add(new JScrollPane(message), BorderLayout.CENTER); <add> <add> // This has to be set to something small otherwise we will get problems when <add> // wrapping this in a JSplitPane: <add> // <add> // http://docs.oracle.com/javase/6/docs/api/javax/swing/JSplitPane.html <add> // <add> // "When the user is resizing the Components the minimum size of the <add> // Components is used to determine the maximum/minimum position the <add> // Components can be set to. If the minimum size of the two <add> // components is greater than the size of the split pane the divider <add> // will not allow you to resize it." <add> // <add> this.setMinimumSize(new Dimension(200,300)); <add> <add> this.addComponentListener(this); <add> <ide> } <ide> <ide> public void setData(GuiReportPanelData reportData) {
JavaScript
mit
334d9de1a2ccb254cffd059cc850f390d0541359
0
maltempi/extjs-action-column-row-editing
Ext.define('Ext.grid.plugin.RowEditingCustom', { extend: 'Ext.grid.plugin.RowEditing', alias: 'plugin.roweditingCustom', /** * Property * It hides the default action buttons * default: true */ hiddenButtons: true, /** * Property: * It adds a button in a extra action column into grid. * * Accepts: boolean (true show | false hide)| button object (not implemented yet) * Default: true */ saveButton: true, /** * Save button icon class * * Accepts: string * default: 'x-fa fa-check' */ saveButtonIconCls: 'x-fa fa-check', /** * Save button tool tip * * Accepts: string * default: 'Save the edited line' */ saveButtonToolTip: 'Save the edited line', /** * Property: * It adds a button in a extra action column into grid. * * Accepts: boolean (true show | false hide)| button object (not implemented yet) * Default: true */ cancelButton: true, /** * Cancel button icon class * * Accepts: string * default: 'x-fa fa-times' */ cancelButtonIconCls: 'x-fa fa-times', /** * Cancel button tool tip * * Accepts: string * default: 'Cancel' */ cancelButtonToolTip: 'Cancel', /** * Hides a column on edit * * Accepts: string (itemId) * default: null */ columnHiddenOnEdit: null, /** * Sets extra buttons on action column * * Accepts: list of objects * default: empty list */ extraButtons: [], /** * Stores the extra columns to hide and show it on events. */ extraColumns: [], /** * Configure everything */ initEditorConfig: function () { /* * Adds the extra action columns */ this.addExtraColumns(); var me = this, grid = me.grid, view = me.view, headerCt = grid.headerCt, btns = ['saveBtnText', 'cancelBtnText', 'errorsText', 'dirtyText'], b, bLen = btns.length, cfg = { autoCancel: me.autoCancel, autoUpdate: me.autoUpdate, removeUnmodified: me.removeUnmodified, errorSummary: me.errorSummary, formAriaLabel: me.formAriaLabel, formAriaLabelRowBase: me.formAriaLabelRowBase + (grid.hideHeaders ? -1 : 0), fields: headerCt.getGridColumns(), hidden: true, view: view, updateButton: function (valid) { }, editingPlugin: me }, item; /* * Custom configuration. */ if (me.hiddenButtons) { cfg.getFloatingButtons = function () { var me = this, btns = me.floatingButtons; if (!btns && !me.destroying && !me.destroyed) { me.floatingButtons = btns = Ext.create('Ext.container.Container', { hidden: true, setButtonPosition: function () { }, }); } return btns; }; } else { for (b = 0; b < bLen; b++) { item = btns[b]; if (Ext.isDefined(me[item])) { cfg[item] = me[item]; } } } return cfg; }, /** * Cancel edit. Sets the extra columns to false. */ cancelEdit: function () { this.setExtraColumnsVisible(false); this.callSuper(); }, /** * Save edit. Sets the extra columns to false. */ completeEdit: function () { this.setExtraColumnsVisible(false); this.callSuper(); }, /** * Starts editing the specified record, using the specified Column definition to define which field is being edited. * @param {Ext.data.Model} record The Store data record which backs the row to be edited. * @param {Ext.grid.column.Column/Number} [columnHeader] The Column object defining the column field to be focused, or index of the column. * If not specified, it will default to the first visible column. * @return {Boolean} `true` if editing was started, `false` otherwise. */ startEdit: function (record, columnHeader) { var me = this, editor = me.getEditor(), grid = me.grid, context; if (Ext.isEmpty(columnHeader)) { columnHeader = me.grid.getTopLevelVisibleColumnManager().getHeaderAtIndex(0); } if (editor.beforeEdit() !== false) { context = me.getEditingContext(record, columnHeader); if (context && me.beforeEdit(context) !== false && me.fireEvent('beforeedit', me, context) !== false && !context.cancel) { me.context = context; // If editing one side of a lockable grid, cancel any edit on the other side. if (me.lockingPartner) { me.lockingPartner.cancelEdit(); } editor.startEdit(context.record, context.column, context); me.editing = true; this.setExtraColumnsVisible(true); return true; } } return false; }, /** * Hides or shows the extra action columns in the grid. * It is used on startEdit(), cancelEdit() and completeEdit() methods. * @param {*} isVisible */ setExtraColumnsVisible(isVisible) { this.extraColumns.forEach(function (element) { element.setVisible(isVisible); }); }, /** * Add the extra action column */ addExtraColumns() { var me = this, grid = me.grid; /* Defines the cancel button */ if (me.cancelButton) { if (me.cancelButton === true) { me.cancelButton = { iconCls: me.cancelButtonIconCls, xtype: 'button', editor: true, tooltip: me.cancelButtonToolTip, handler: function (grid, rowIndex, colIndex) { me.cancelEdit(); } }; } me.extraButtons.push(me.cancelButton); } /* Defines the saveButton */ if (me.saveButton) { if (me.saveButton === true) { me.saveButton = { iconCls: me.saveButtonIconCls, xtype: 'button', tooltip: me.saveButtonToolTip, handler: function (grid, rowIndex, colIndex) { me.completeEdit(); } }; } me.extraButtons.push(me.saveButton); } /** * Adds the extra columns */ if (me.extraButtons) { for (index in me.extraButtons) { var column = { xtype: 'actioncolumn', width: 30, align: 'center', editor: me.extraButtons[index], menuDisabled: true, sortable: false, border: false, resizable: false, hideable: false, menuDisabled: true }; me.extraColumns.push(grid.headerCt.insert(grid.columns.length, column)); } } } });
ux/RowEditingCustom.js
Ext.define('Ext.grid.plugin.RowEditingCustom', { extend: 'Ext.grid.plugin.RowEditing', alias: 'plugin.roweditingCustom', /** * Property * It hides the default action buttons * default: true */ hiddenButtons: true, /** * Property: * It adds a button in a extra action column into grid. * * Accepts: boolean (true show | false hide)| button object (not implemented yet) * Default: true */ saveButton: true, /** * Property: * It adds a button in a extra action column into grid. * * Accepts: boolean (true show | false hide)| button object (not implemented yet) * Default: true */ cancelButton: true, /** * Hides a column on edit * * Accepts: string (itemId) * default: null */ columnHiddenOnEdit: null, /** * Sets extra buttons on action column * * Accepts: list of objects * default: empty list */ extraButtons: [], /** * Stores the extra columns to hide and show it on events. */ extraColumns: [], /** * Configure everything */ initEditorConfig: function () { /* * Adds the extra action columns */ this.addExtraColumns(); var me = this, grid = me.grid, view = me.view, headerCt = grid.headerCt, btns = ['saveBtnText', 'cancelBtnText', 'errorsText', 'dirtyText'], b, bLen = btns.length, cfg = { autoCancel: me.autoCancel, autoUpdate: me.autoUpdate, removeUnmodified: me.removeUnmodified, errorSummary: me.errorSummary, formAriaLabel: me.formAriaLabel, formAriaLabelRowBase: me.formAriaLabelRowBase + (grid.hideHeaders ? -1 : 0), fields: headerCt.getGridColumns(), hidden: true, view: view, updateButton: function (valid) { }, editingPlugin: me }, item; /* * Custom configuration. */ if (me.hiddenButtons) { cfg.getFloatingButtons = function () { var me = this, btns = me.floatingButtons; if (!btns && !me.destroying && !me.destroyed) { me.floatingButtons = btns = Ext.create('Ext.container.Container', { hidden: true, setButtonPosition: function () { }, }); } return btns; }; } else { for (b = 0; b < bLen; b++) { item = btns[b]; if (Ext.isDefined(me[item])) { cfg[item] = me[item]; } } } return cfg; }, /** * Cancel edit. Sets the extra columns to false. */ cancelEdit: function () { this.setExtraColumnsVisible(false); this.callSuper(); }, /** * Save edit. Sets the extra columns to false. */ completeEdit: function () { this.setExtraColumnsVisible(false); this.callSuper(); }, /** * Starts editing the specified record, using the specified Column definition to define which field is being edited. * @param {Ext.data.Model} record The Store data record which backs the row to be edited. * @param {Ext.grid.column.Column/Number} [columnHeader] The Column object defining the column field to be focused, or index of the column. * If not specified, it will default to the first visible column. * @return {Boolean} `true` if editing was started, `false` otherwise. */ startEdit: function (record, columnHeader) { var me = this, editor = me.getEditor(), grid = me.grid, context; if (Ext.isEmpty(columnHeader)) { columnHeader = me.grid.getTopLevelVisibleColumnManager().getHeaderAtIndex(0); } if (editor.beforeEdit() !== false) { context = me.getEditingContext(record, columnHeader); if (context && me.beforeEdit(context) !== false && me.fireEvent('beforeedit', me, context) !== false && !context.cancel) { me.context = context; // If editing one side of a lockable grid, cancel any edit on the other side. if (me.lockingPartner) { me.lockingPartner.cancelEdit(); } editor.startEdit(context.record, context.column, context); me.editing = true; this.setExtraColumnsVisible(true); return true; } } return false; }, /** * Hides or shows the extra action columns in the grid. * It is used on startEdit(), cancelEdit() and completeEdit() methods. * @param {*} isVisible */ setExtraColumnsVisible(isVisible) { this.extraColumns.forEach(function (element) { element.setVisible(isVisible); }); }, /** * Add the extra action column */ addExtraColumns() { var me = this, grid = me.grid; /* Defines the cancel button */ if (me.cancelButton) { if (me.cancelButton === true) { me.cancelButton = { iconCls: 'x-fa fa-times', xtype: 'button', editor: true, tooltip: 'Cancel', handler: function (grid, rowIndex, colIndex) { me.cancelEdit(); } }; } me.extraButtons.push(me.cancelButton); } /* Defines the saveButton */ if (me.saveButton) { if (me.saveButton === true) { me.saveButton = { iconCls: 'x-fa fa-check', xtype: 'button', tooltip: 'Save the edited line', handler: function (grid, rowIndex, colIndex) { me.completeEdit(); } }; } me.extraButtons.push(me.saveButton); } /** * Adds the extra columns */ if (me.extraButtons) { for (index in me.extraButtons) { var column = { xtype: 'actioncolumn', width: 30, align: 'center', editor: me.extraButtons[index], menuDisabled: true, sortable: false, border: false, resizable: false, hideable: false, menuDisabled: true }; me.extraColumns.push(grid.headerCt.insert(grid.columns.length, column)); } } } });
Adding some customizations
ux/RowEditingCustom.js
Adding some customizations
<ide><path>x/RowEditingCustom.js <ide> saveButton: true, <ide> <ide> /** <add> * Save button icon class <add> * <add> * Accepts: string <add> * default: 'x-fa fa-check' <add> */ <add> saveButtonIconCls: 'x-fa fa-check', <add> <add> /** <add> * Save button tool tip <add> * <add> * Accepts: string <add> * default: 'Save the edited line' <add> */ <add> saveButtonToolTip: 'Save the edited line', <add> <add> /** <ide> * Property: <ide> * It adds a button in a extra action column into grid. <ide> * <ide> * Default: true <ide> */ <ide> cancelButton: true, <add> <add> /** <add> * Cancel button icon class <add> * <add> * Accepts: string <add> * default: 'x-fa fa-times' <add> */ <add> cancelButtonIconCls: 'x-fa fa-times', <add> <add> /** <add> * Cancel button tool tip <add> * <add> * Accepts: string <add> * default: 'Cancel' <add> */ <add> cancelButtonToolTip: 'Cancel', <ide> <ide> /** <ide> * Hides a column on edit <ide> <ide> if (me.cancelButton === true) { <ide> me.cancelButton = { <del> iconCls: 'x-fa fa-times', <add> iconCls: me.cancelButtonIconCls, <ide> xtype: 'button', <ide> editor: true, <del> tooltip: 'Cancel', <add> tooltip: me.cancelButtonToolTip, <ide> handler: function (grid, rowIndex, colIndex) { <ide> me.cancelEdit(); <ide> } <ide> <ide> if (me.saveButton === true) { <ide> me.saveButton = { <del> iconCls: 'x-fa fa-check', <add> iconCls: me.saveButtonIconCls, <ide> xtype: 'button', <del> tooltip: 'Save the edited line', <add> tooltip: me.saveButtonToolTip, <ide> handler: function (grid, rowIndex, colIndex) { <ide> me.completeEdit(); <ide> }
Java
apache-2.0
baaf5c338af65da80a85cd8670faadc10caa2836
0
brandt/GridSphere,brandt/GridSphere
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.event.WindowEvent; import org.gridlab.gridsphere.event.impl.WindowEventImpl; import org.gridlab.gridsphere.layout.event.PortletTitleBarEvent; import org.gridlab.gridsphere.layout.event.PortletTitleBarListener; import org.gridlab.gridsphere.layout.event.impl.PortletTitleBarEventImpl; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portletcontainer.*; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * A <code>PortletTitleBar</code> represents the visual display of the portlet title bar * within a portlet frame and is contained by {@link PortletFrame}. * The title bar contains portlet mode and window state as well as a title. */ public class PortletTitleBar extends BasePortletComponent { private String title = "Portlet Unavailable"; private String portletClass = null; private PortletWindow.State windowState = PortletWindow.State.NORMAL; private List supportedModes = null; private String[] portletModes = null; private Portlet.Mode portletMode = Portlet.Mode.VIEW; private Portlet.Mode previousMode = null; private List listeners = new ArrayList(); private PortletSettings settings; private List allowedWindowStates = null; private String[] windowStates = null; private String errorMessage = ""; private boolean hasError = false; /** * Link is an abstract representation of a hyperlink with an href, image and * alt tags. */ abstract class Link { protected String href = ""; protected String imageSrc = ""; protected String altTag = ""; /** * Returns the image source attribute in the link * * @return the image source attribute in the link */ public String getImageSrc() { return imageSrc; } /** * Sets the href attribute in the link * * @param href the href attribute in the link */ public void setHref(String href) { this.href = href; } /** * Returns the href attribute in the link * * @return the href attribute in the link */ public String getHref() { return href; } /** * Returns the alt tag attribute in the link * * @return the alt tag attribute in the link */ public String getAltTag() { return altTag; } /** * Returns a string containing the image src, href and alt tag attributes * Used primarily for debugging purposes */ public String toString() { StringBuffer sb = new StringBuffer("\n"); sb.append("image src: " + imageSrc + "\n"); sb.append("href: " + href + "\n"); sb.append("alt tag: " + altTag + "\n"); return sb.toString(); } } /** * PortletModeLink is a concrete instance of a Link used for creating * portlet mode hyperlinks */ class PortletModeLink extends Link { public static final String configImage = "images/window_configure.gif"; public static final String editImage = "images/window_edit.gif"; public static final String helpImage = "images/window_help.gif"; public static final String configAlt = "Configure"; public static final String editAlt = "Edit"; public static final String helpAlt = "Help"; /** * Constructs an instance of PortletModeLink with the supplied portlet mode * * @param mode the portlet mode */ public PortletModeLink(String mode) throws IllegalArgumentException { // Set the image src if (mode.equalsIgnoreCase(Portlet.Mode.CONFIGURE.toString())) { imageSrc = configImage; altTag = configAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.EDIT.toString())) { imageSrc = editImage; altTag = editAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.HELP.toString())) { imageSrc = helpImage; altTag = helpAlt; } else { throw new IllegalArgumentException("No matching Portlet.Mode found for received portlet mode: " + mode); } } } /** * PortletStateLink is a concrete instance of a Link used for creating * portlet window state hyperlinks */ class PortletStateLink extends Link { public static final String minimizeImage = "images/window_minimize.gif"; public static final String maximizeImage = "images/window_maximize.gif"; public static final String resizeImage = "images/window_resize.gif"; public static final String minimizeAlt = "Minimize"; public static final String maximizeAlt = "Maximize"; public static final String resizeAlt = "Resize"; /** * Constructs an instance of PortletStateLink with the supplied window state * * @param state the window state */ public PortletStateLink(String state) throws IllegalArgumentException { // Set the image src if (state.equalsIgnoreCase(PortletWindow.State.MINIMIZED.toString())) { imageSrc = minimizeImage; altTag = minimizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.MAXIMIZED.toString())) { imageSrc = maximizeImage; altTag = maximizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { imageSrc = resizeImage; altTag = resizeAlt; } else { throw new IllegalArgumentException("No matching PortletWindow.State found for received window mode: " + state); } } } /** * Constructs an instance of PortletTitleBar */ public PortletTitleBar() { } /** * Sets the portlet class used to render the title bar * * @param portletClass the concrete portlet class */ public void setPortletClass(String portletClass) { this.portletClass = portletClass; } /** * Returns the portlet class used in rendering the title bar * * @return the concrete portlet class */ public String getPortletClass() { return portletClass; } /** * Returns the title of the portlet title bar * * @return the portlet title bar */ public String getTitle() { return title; } /** * Sets the title of the portlet title bar * * @param title the portlet title bar */ public void setTitle(String title) { this.title = title; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string * @see PortletWindow.State */ public void setWindowState(String state) { if (state != null) { try { this.windowState = PortletWindow.State.toState(state); } catch (IllegalArgumentException e) { // do nothing } } } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string * @see PortletWindow.State */ public String getWindowState() { return windowState.toString(); } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string * @see Portlet.Mode */ public void setPortletMode(String mode) { try { this.portletMode = Portlet.Mode.toMode(mode); } catch (IllegalArgumentException e) { // do nothing } } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string * @see Portlet.Mode */ public String getPortletMode() { return portletMode.toString(); } /** * Adds a title bar listener to be notified of title bar events * * @param listener a title bar listener * @see PortletTitleBarEvent */ public void addTitleBarListener(PortletTitleBarListener listener) { listeners.add(listener); } /** * Indicates an error ocurred suring the processing of this title bar * * @return <code>true</code> if an error occured during rendering, * <code>false</code> otherwise */ public boolean hasRenderError() { return hasError; } public String getErrorMessage() { return errorMessage; } /** * Initializes the portlet title bar. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List init(List list) { list = super.init(list); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setPortletClass(portletClass); compId.setComponentID(list.size()); compId.setClassName(this.getClass().getName()); list.add(compId); doConfig(); return list; } /** * Sets configuration information about the supported portlet modes, * allowed window states and title bar obtained from {@link PortletSettings}. * Information is queried from the {@link PortletRegistry} */ protected void doConfig() { PortletRegistry registryManager = PortletRegistry.getInstance(); String appID = registryManager.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = registryManager.getApplicationPortlet(appID); if (appPortlet != null) { ApplicationPortletConfig appConfig = appPortlet.getApplicationPortletConfig(); // get supported modes from application portlet config supportedModes = appConfig.getSupportedModes(); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(portletClass); settings = concPortlet.getPortletSettings(); // get window states from application portlet config allowedWindowStates = appConfig.getAllowedWindowStates(); } } /** * Creates the portlet window state hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of window state hyperlinks */ protected List createWindowLinks(GridSphereEvent event) { PortletURI portletURI; PortletResponse res = event.getPortletResponse(); windowStates = new String[allowedWindowStates.size()]; for (int i = 0; i < allowedWindowStates.size(); i++) { PortletWindow.State state = (PortletWindow.State)allowedWindowStates.get(i); windowStates[i] = state.toString(); } for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // get rid of resized if window state is normal if (windowState == PortletWindow.State.NORMAL) { for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { windowStates[i] = ""; } } } for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // create a URI for each of the window states PortletStateLink stateLink; List stateLinks = new Vector(); for (int i = 0; i < windowStates.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { stateLink = new PortletStateLink(windowStates[i]); portletURI.addParameter(GridSphereProperties.PORTLETWINDOW, windowStates[i]); stateLink.setHref(portletURI.toString()); stateLinks.add(stateLink); } catch (IllegalArgumentException e) { // do nothing } } return stateLinks; } /** * Creates the portlet mode hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of portlet mode hyperlinks */ public List createModeLinks(GridSphereEvent event) { int i; PortletResponse res = event.getPortletResponse(); portletModes = new String[supportedModes.size()]; for (i = 0; i < supportedModes.size(); i++) { Portlet.Mode mode = (Portlet.Mode)supportedModes.get(i); portletModes[i] = mode.toString(); } // subtract current portlet mode for (i = 0; i < portletModes.length; i++) { if (portletModes[i].equalsIgnoreCase(portletMode.toString())) { portletModes[i] = ""; } } // create a URI for each of the portlet modes PortletURI portletURI; PortletModeLink modeLink; List portletLinks = new ArrayList(); for (i = 0; i < portletModes.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { modeLink = new PortletModeLink(portletModes[i]); portletURI.addParameter(GridSphereProperties.PORTLETMODE, portletModes[i]); modeLink.setHref(portletURI.toString()); portletLinks.add(modeLink); } catch (IllegalArgumentException e) { } } return portletLinks; } /** * Performs an action on this portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void actionPerformed(GridSphereEvent event) throws PortletLayoutException, IOException { PortletTitleBarEvent evt = new PortletTitleBarEventImpl(event, COMPONENT_ID); PortletRequest req = event.getPortletRequest(); if (evt.getAction() == PortletTitleBarEvent.Action.WINDOW_MODIFY) { PortletResponse res = event.getPortletResponse(); windowState = evt.getState(); WindowEvent winEvent = null; if (windowState == PortletWindow.State.MAXIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MAXIMIZED); } else if (windowState == PortletWindow.State.MINIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MINIMIZED); } else if (windowState == PortletWindow.State.RESIZING) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_RESTORED); } if (winEvent != null) { try { //userManager.windowEvent(portletClass, winEvent, req, res); PortletInvoker.windowEvent(portletClass, winEvent, req, res); } catch (PortletException e) { hasError = true; errorMessage += "Failed to invoke window event method of portlet: " + portletClass; } } } else if (evt.getAction() == PortletTitleBarEvent.Action.MODE_MODIFY) { previousMode = portletMode; portletMode = evt.getMode(); req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, portletMode); } if (evt != null) fireTitleBarEvent(evt); } /** * Fires a title bar event notification * * @param event a portlet title bar event * @throws PortletLayoutException if a layout error occurs */ protected void fireTitleBarEvent(PortletTitleBarEvent event) throws PortletLayoutException { Iterator it = listeners.iterator(); PortletTitleBarListener l; while (it.hasNext()) { l = (PortletTitleBarListener) it.next(); l.handleTitleBarEvent(event); } } /** * Renders the portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void doRender(GridSphereEvent event) throws PortletLayoutException, IOException { // title bar: configure, edit, help, title, min, max PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); // get the appropriate title for this client Client client = req.getClient(); if (settings == null) { doConfig(); } else { title = settings.getTitle(req.getLocale(), client); } List modeLinks = null, windowLinks = null; User user = req.getUser(); if (user instanceof GuestUser) { } else { if (portletClass != null) { modeLinks = createModeLinks(event); windowLinks = createWindowLinks(event); } } req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, previousMode); PrintWriter out = res.getWriter(); out.println("<tr><td class=\"window-title\">"); out.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>"); // Output portlet mode icons if (modeLinks != null) { Iterator modesIt = modeLinks.iterator(); out.println("<td class=\"window-icon-left\">"); PortletModeLink mode; while (modesIt.hasNext()) { mode = (PortletModeLink) modesIt.next(); out.println("<a href=\"" + mode.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + mode.getImageSrc() + "\" title=\"" + mode.getAltTag() + "\"/></a>"); } out.println("</td>"); } // Invoke doTitle of portlet whose action was perfomed String actionStr = req.getParameter(GridSphereProperties.ACTION); out.println("<td class=\"window-title-name\">"); if (actionStr != null) { try { PortletInvoker.doTitle(portletClass, req, res); out.println(" (" + portletMode.toString() + ") "); } catch (PortletException e) { errorMessage += "Unable to invoke doTitle on active portlet\n"; hasError = true; } } else { out.println(title); } out.println("</td>"); // Output window state icons if (windowLinks != null) { Iterator windowsIt = windowLinks.iterator(); PortletStateLink state; out.println("<td class=\"window-icon-right\">"); while (windowsIt.hasNext()) { state = (PortletStateLink) windowsIt.next(); out.println("<a href=\"" + state.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + state.getImageSrc() + "\" title=\"" + state.getAltTag() + "\"/></a>"); } out.println("</td>"); } out.println("</tr></table>"); out.println("</td></tr>"); } }
src/org/gridlab/gridsphere/layout/PortletTitleBar.java
/* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.event.WindowEvent; import org.gridlab.gridsphere.event.impl.WindowEventImpl; import org.gridlab.gridsphere.layout.event.PortletTitleBarEvent; import org.gridlab.gridsphere.layout.event.PortletTitleBarListener; import org.gridlab.gridsphere.layout.event.impl.PortletTitleBarEventImpl; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portletcontainer.*; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * A <code>PortletTitleBar</code> represents the visual display of the portlet title bar * within a portlet frame and is contained by {@link PortletFrame}. * The title bar contains portlet mode and window state as well as a title. */ public class PortletTitleBar extends BasePortletComponent { private String title = "Portlet Unavailable"; private String portletClass = null; private PortletWindow.State windowState = PortletWindow.State.NORMAL; private List supportedModes = null; private String[] portletModes = null; private Portlet.Mode portletMode = Portlet.Mode.VIEW; private Portlet.Mode previousMode = null; private List listeners = new ArrayList(); private PortletSettings settings; private List allowedWindowStates = null; private String[] windowStates = null; private String errorMessage = ""; private boolean hasError = false; /** * Link is an abstract representation of a hyperlink with an href, image and * alt tags. */ abstract class Link { protected String href = ""; protected String imageSrc = ""; protected String altTag = ""; /** * Returns the image source attribute in the link * * @return the image source attribute in the link */ public String getImageSrc() { return imageSrc; } /** * Sets the href attribute in the link * * @param href the href attribute in the link */ public void setHref(String href) { this.href = href; } /** * Returns the href attribute in the link * * @return the href attribute in the link */ public String getHref() { return href; } /** * Returns the alt tag attribute in the link * * @return the alt tag attribute in the link */ public String getAltTag() { return altTag; } /** * Returns a string containing the image src, href and alt tag attributes * Used primarily for debugging purposes */ public String toString() { StringBuffer sb = new StringBuffer("\n"); sb.append("image src: " + imageSrc + "\n"); sb.append("href: " + href + "\n"); sb.append("alt tag: " + altTag + "\n"); return sb.toString(); } } /** * PortletModeLink is a concrete instance of a Link used for creating * portlet mode hyperlinks */ class PortletModeLink extends Link { public static final String configImage = "images/window_configure.gif"; public static final String editImage = "images/window_edit.gif"; public static final String helpImage = "images/window_help.gif"; public static final String configAlt = "Configure"; public static final String editAlt = "Edit"; public static final String helpAlt = "Help"; /** * Constructs an instance of PortletModeLink with the supplied portlet mode * * @param mode the portlet mode */ public PortletModeLink(String mode) throws IllegalArgumentException { // Set the image src if (mode.equalsIgnoreCase(Portlet.Mode.CONFIGURE.toString())) { imageSrc = configImage; altTag = configAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.EDIT.toString())) { imageSrc = editImage; altTag = editAlt; } else if (mode.equalsIgnoreCase(Portlet.Mode.HELP.toString())) { imageSrc = helpImage; altTag = helpAlt; } else { throw new IllegalArgumentException("No matching Portlet.Mode found for received portlet mode: " + mode); } } } /** * PortletStateLink is a concrete instance of a Link used for creating * portlet window state hyperlinks */ class PortletStateLink extends Link { public static final String minimizeImage = "images/window_minimize.gif"; public static final String maximizeImage = "images/window_maximize.gif"; public static final String resizeImage = "images/window_resize.gif"; public static final String minimizeAlt = "Minimize"; public static final String maximizeAlt = "Maximize"; public static final String resizeAlt = "Resize"; /** * Constructs an instance of PortletStateLink with the supplied window state * * @param state the window state */ public PortletStateLink(String state) throws IllegalArgumentException { // Set the image src if (state.equalsIgnoreCase(PortletWindow.State.MINIMIZED.toString())) { imageSrc = minimizeImage; altTag = minimizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.MAXIMIZED.toString())) { imageSrc = maximizeImage; altTag = maximizeAlt; } else if (state.equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { imageSrc = resizeImage; altTag = resizeAlt; } else { throw new IllegalArgumentException("No matching PortletWindow.State found for received window mode: " + state); } } } /** * Constructs an instance of PortletTitleBar */ public PortletTitleBar() { } /** * Sets the portlet class used to render the title bar * * @param portletClass the concrete portlet class */ public void setPortletClass(String portletClass) { this.portletClass = portletClass; } /** * Returns the portlet class used in rendering the title bar * * @return the concrete portlet class */ public String getPortletClass() { return portletClass; } /** * Returns the title of the portlet title bar * * @return the portlet title bar */ public String getTitle() { return title; } /** * Sets the title of the portlet title bar * * @param title the portlet title bar */ public void setTitle(String title) { this.title = title; } /** * Sets the window state of this title bar * * @param state the portlet window state expressed as a string * @see PortletWindow.State */ public void setWindowState(String state) { if (state != null) { try { this.windowState = PortletWindow.State.toState(state); } catch (IllegalArgumentException e) { // do nothing } } } /** * Returns the window state of this title bar * * @return the portlet window state expressed as a string * @see PortletWindow.State */ public String getWindowState() { return windowState.toString(); } /** * Sets the portlet mode of this title bar * * @param mode the portlet mode expressed as a string * @see Portlet.Mode */ public void setPortletMode(String mode) { try { this.portletMode = Portlet.Mode.toMode(mode); } catch (IllegalArgumentException e) { // do nothing } } /** * Returns the portlet mode of this title bar * * @return the portlet mode expressed as a string * @see Portlet.Mode */ public String getPortletMode() { return portletMode.toString(); } /** * Adds a title bar listener to be notified of title bar events * * @param listener a title bar listener * @see PortletTitleBarEvent */ public void addTitleBarListener(PortletTitleBarListener listener) { listeners.add(listener); } /** * Indicates an error ocurred suring the processing of this title bar * * @return <code>true</code> if an error occured during rendering, * <code>false</code> otherwise */ public boolean hasRenderError() { return hasError; } public String getErrorMessage() { return errorMessage; } /** * Initializes the portlet title bar. Since the components are isolated * after Castor unmarshalls from XML, the ordering is determined by a * passed in List containing the previous portlet components in the tree. * * @param list a list of component identifiers * @return a list of updated component identifiers * @see ComponentIdentifier */ public List init(List list) { list = super.init(list); ComponentIdentifier compId = new ComponentIdentifier(); compId.setPortletComponent(this); compId.setPortletClass(portletClass); compId.setComponentID(list.size()); compId.setClassName(this.getClass().getName()); list.add(compId); doConfig(); return list; } /** * Sets configuration information about the supported portlet modes, * allowed window states and title bar obtained from {@link PortletSettings}. * Information is queried from the {@link PortletRegistry} */ protected void doConfig() { PortletRegistry registryManager = PortletRegistry.getInstance(); String appID = registryManager.getApplicationPortletID(portletClass); ApplicationPortlet appPortlet = registryManager.getApplicationPortlet(appID); if (appPortlet != null) { ApplicationPortletConfig appConfig = appPortlet.getApplicationPortletConfig(); // get supported modes from application portlet config supportedModes = appConfig.getSupportedModes(); ConcretePortlet concPortlet = appPortlet.getConcretePortlet(portletClass); settings = concPortlet.getPortletSettings(); // get window states from application portlet config allowedWindowStates = appConfig.getAllowedWindowStates(); } } /** * Creates the portlet window state hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of window state hyperlinks */ protected List createWindowLinks(GridSphereEvent event) { PortletURI portletURI; PortletResponse res = event.getPortletResponse(); windowStates = new String[allowedWindowStates.size()]; for (int i = 0; i < allowedWindowStates.size(); i++) { PortletWindow.State state = (PortletWindow.State)allowedWindowStates.get(i); windowStates[i] = state.toString(); } for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // get rid of resized if window state is normal if (windowState == PortletWindow.State.NORMAL) { for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(PortletWindow.State.RESIZING.toString())) { windowStates[i] = ""; } } } for (int i = 0; i < windowStates.length; i++) { // remove current state from list if (windowStates[i].equalsIgnoreCase(windowState.toString())) { windowStates[i] = ""; } } // create a URI for each of the window states PortletStateLink stateLink; List stateLinks = new Vector(); for (int i = 0; i < windowStates.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { stateLink = new PortletStateLink(windowStates[i]); portletURI.addParameter(GridSphereProperties.PORTLETWINDOW, windowStates[i]); stateLink.setHref(portletURI.toString()); stateLinks.add(stateLink); } catch (IllegalArgumentException e) { // do nothing } } return stateLinks; } /** * Creates the portlet mode hyperlinks displayed in the title bar * * @param event the gridsphere event * @return a list of portlet mode hyperlinks */ public List createModeLinks(GridSphereEvent event) { int i; PortletResponse res = event.getPortletResponse(); portletModes = new String[supportedModes.size()]; for (int i = 0; i < supportedModes.size(); i++) { Portlet.Mode mode = (Portlet.Mode)supportedModes.get(i); portletModes[i] = mode.toString(); } // subtract current portlet mode for (i = 0; i < portletModes.length; i++) { if (portletModes[i].equalsIgnoreCase(portletMode.toString())) { portletModes[i] = ""; } } // create a URI for each of the portlet modes PortletURI portletURI; PortletModeLink modeLink; List portletLinks = new ArrayList(); for (i = 0; i < portletModes.length; i++) { portletURI = res.createURI(); portletURI.addParameter(GridSphereProperties.COMPONENT_ID, this.componentIDStr); portletURI.addParameter(GridSphereProperties.PORTLETID, portletClass); try { modeLink = new PortletModeLink(portletModes[i]); portletURI.addParameter(GridSphereProperties.PORTLETMODE, portletModes[i]); modeLink.setHref(portletURI.toString()); portletLinks.add(modeLink); } catch (IllegalArgumentException e) { } } return portletLinks; } /** * Performs an action on this portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void actionPerformed(GridSphereEvent event) throws PortletLayoutException, IOException { PortletTitleBarEvent evt = new PortletTitleBarEventImpl(event, COMPONENT_ID); PortletRequest req = event.getPortletRequest(); if (evt.getAction() == PortletTitleBarEvent.Action.WINDOW_MODIFY) { PortletResponse res = event.getPortletResponse(); windowState = evt.getState(); WindowEvent winEvent = null; if (windowState == PortletWindow.State.MAXIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MAXIMIZED); } else if (windowState == PortletWindow.State.MINIMIZED) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_MINIMIZED); } else if (windowState == PortletWindow.State.RESIZING) { winEvent = new WindowEventImpl(req, WindowEvent.WINDOW_RESTORED); } if (winEvent != null) { try { //userManager.windowEvent(portletClass, winEvent, req, res); PortletInvoker.windowEvent(portletClass, winEvent, req, res); } catch (PortletException e) { hasError = true; errorMessage += "Failed to invoke window event method of portlet: " + portletClass; } } } else if (evt.getAction() == PortletTitleBarEvent.Action.MODE_MODIFY) { previousMode = portletMode; portletMode = evt.getMode(); req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, portletMode); } if (evt != null) fireTitleBarEvent(evt); } /** * Fires a title bar event notification * * @param event a portlet title bar event * @throws PortletLayoutException if a layout error occurs */ protected void fireTitleBarEvent(PortletTitleBarEvent event) throws PortletLayoutException { Iterator it = listeners.iterator(); PortletTitleBarListener l; while (it.hasNext()) { l = (PortletTitleBarListener) it.next(); l.handleTitleBarEvent(event); } } /** * Renders the portlet title bar component * * @param event a gridsphere event * @throws PortletLayoutException if a layout error occurs during rendering * @throws IOException if an I/O error occurs during rendering */ public void doRender(GridSphereEvent event) throws PortletLayoutException, IOException { // title bar: configure, edit, help, title, min, max PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); // get the appropriate title for this client Client client = req.getClient(); if (settings == null) { doConfig(); } else { title = settings.getTitle(req.getLocale(), client); } List modeLinks = null, windowLinks = null; User user = req.getUser(); if (user instanceof GuestUser) { } else { if (portletClass != null) { modeLinks = createModeLinks(event); windowLinks = createWindowLinks(event); } } req.setMode(portletMode); req.setAttribute(GridSphereProperties.PREVIOUSMODE, previousMode); PrintWriter out = res.getWriter(); out.println("<tr><td class=\"window-title\">"); out.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr>"); // Output portlet mode icons if (modeLinks != null) { Iterator modesIt = modeLinks.iterator(); out.println("<td class=\"window-icon-left\">"); PortletModeLink mode; while (modesIt.hasNext()) { mode = (PortletModeLink) modesIt.next(); out.println("<a href=\"" + mode.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + mode.getImageSrc() + "\" title=\"" + mode.getAltTag() + "\"/></a>"); } out.println("</td>"); } // Invoke doTitle of portlet whose action was perfomed String actionStr = req.getParameter(GridSphereProperties.ACTION); out.println("<td class=\"window-title-name\">"); if (actionStr != null) { try { PortletInvoker.doTitle(portletClass, req, res); out.println(" (" + portletMode.toString() + ") "); } catch (PortletException e) { errorMessage += "Unable to invoke doTitle on active portlet\n"; hasError = true; } } else { out.println(title); } out.println("</td>"); // Output window state icons if (windowLinks != null) { Iterator windowsIt = windowLinks.iterator(); PortletStateLink state; out.println("<td class=\"window-icon-right\">"); while (windowsIt.hasNext()) { state = (PortletStateLink) windowsIt.next(); out.println("<a href=\"" + state.getHref() + "\"><img border=\"0\" src=\"themes/" + theme + "/" + state.getImageSrc() + "\" title=\"" + state.getAltTag() + "\"/></a>"); } out.println("</td>"); } out.println("</tr></table>"); out.println("</td></tr>"); } }
*** empty log message *** git-svn-id: 616481d960d639df1c769687dde8737486ca2a9a@1171 9c99c85f-4d0c-0410-8460-a9a1c48a3a7f
src/org/gridlab/gridsphere/layout/PortletTitleBar.java
*** empty log message ***
<ide><path>rc/org/gridlab/gridsphere/layout/PortletTitleBar.java <ide> PortletResponse res = event.getPortletResponse(); <ide> <ide> portletModes = new String[supportedModes.size()]; <del> for (int i = 0; i < supportedModes.size(); i++) { <add> for (i = 0; i < supportedModes.size(); i++) { <ide> Portlet.Mode mode = (Portlet.Mode)supportedModes.get(i); <ide> portletModes[i] = mode.toString(); <ide> }
Java
bsd-2-clause
36dca0346dad07d30b1864ae6cd74fdc04d83cd4
0
TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.io.dnd; import imagej.data.Dataset; import imagej.display.Display; import imagej.display.DisplayService; import imagej.io.IOService; import imagej.ui.dnd.AbstractDragAndDropHandler; import imagej.ui.dnd.DragAndDropHandler; import java.io.File; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.io.ImgIOException; import org.scijava.Priority; import org.scijava.log.LogService; import org.scijava.plugin.Plugin; /** * Drag-and-drop handler for image files. * * @author Curtis Rueden * @author Barry DeZonia */ @Plugin(type = DragAndDropHandler.class, priority = Priority.LOW_PRIORITY) public class ImageFileDragAndDropHandler extends AbstractDragAndDropHandler<File> { // -- DragAndDropHandler methods -- @Override public Class<File> getType() { return File.class; } @Override public boolean isCompatible(final File file) { if (file == null) return true; // trivial case // verify that the file is image data final IOService ioService = getContext().getService(IOService.class); if (ioService == null) return false; return ioService.isImageData(file.getAbsolutePath()); } @Override public boolean drop(final File file, final Display<?> display) { check(file, display); if (file == null) return true; // trivial case final IOService ioService = getContext().getService(IOService.class); if (ioService == null) return false; final DisplayService displayService = getContext().getService(DisplayService.class); if (displayService == null) return false; final LogService log = getContext().getService(LogService.class); // load dataset final String filename = file.getAbsolutePath(); final Dataset dataset; try { dataset = ioService.loadDataset(filename); } catch (final ImgIOException exc) { if (log != null) log.error("Error opening file: " + filename, exc); return false; } catch (final IncompatibleTypeException exc) { if (log != null) log.error("Error opening file: " + filename, exc); return false; } // display result displayService.createDisplay(dataset); return true; } }
core/io/src/main/java/imagej/io/dnd/ImageFileDragAndDropHandler.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.io.dnd; import imagej.data.Dataset; import imagej.display.Display; import imagej.display.DisplayService; import imagej.io.IOService; import imagej.ui.dnd.AbstractDragAndDropHandler; import imagej.ui.dnd.DragAndDropHandler; import java.io.File; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.io.ImgIOException; import org.scijava.log.LogService; import org.scijava.plugin.Plugin; /** * Drag-and-drop handler for image files. * * @author Curtis Rueden * @author Barry DeZonia */ @Plugin(type = DragAndDropHandler.class) public class ImageFileDragAndDropHandler extends AbstractDragAndDropHandler<File> { // -- DragAndDropHandler methods -- @Override public Class<File> getType() { return File.class; } @Override public boolean isCompatible(final File file) { if (file == null) return true; // trivial case // verify that the file is image data final IOService ioService = getContext().getService(IOService.class); if (ioService == null) return false; return ioService.isImageData(file.getAbsolutePath()); } @Override public boolean drop(final File file, final Display<?> display) { check(file, display); if (file == null) return true; // trivial case final IOService ioService = getContext().getService(IOService.class); if (ioService == null) return false; final DisplayService displayService = getContext().getService(DisplayService.class); if (displayService == null) return false; final LogService log = getContext().getService(LogService.class); // load dataset final String filename = file.getAbsolutePath(); final Dataset dataset; try { dataset = ioService.loadDataset(filename); } catch (final ImgIOException exc) { if (log != null) log.error("Error opening file: " + filename, exc); return false; } catch (final IncompatibleTypeException exc) { if (log != null) log.error("Error opening file: " + filename, exc); return false; } // display result displayService.createDisplay(dataset); return true; } }
ImageFileDragAndDropHandler: make low priority Otherwise, with the current SNAPSHOT version of SCIFIO, the PGM reader claims it can handle LUT files (and then subsequently barfs when trying to actually read the file), so the LUTFileDragAndDropHandler never gets its chance to shine. Hopefully this will be resolved with the SCIFIO refactoring, but for now, it's safer to make the ImageFileDragAndDropHandler take a back seat to some of the other more conservative drag-and-drop handlers.
core/io/src/main/java/imagej/io/dnd/ImageFileDragAndDropHandler.java
ImageFileDragAndDropHandler: make low priority
<ide><path>ore/io/src/main/java/imagej/io/dnd/ImageFileDragAndDropHandler.java <ide> import net.imglib2.exception.IncompatibleTypeException; <ide> import net.imglib2.io.ImgIOException; <ide> <add>import org.scijava.Priority; <ide> import org.scijava.log.LogService; <ide> import org.scijava.plugin.Plugin; <ide> <ide> * @author Curtis Rueden <ide> * @author Barry DeZonia <ide> */ <del>@Plugin(type = DragAndDropHandler.class) <add>@Plugin(type = DragAndDropHandler.class, priority = Priority.LOW_PRIORITY) <ide> public class ImageFileDragAndDropHandler extends <ide> AbstractDragAndDropHandler<File> <ide> {
Java
mit
30cd42f13dc70dae65ff218f4b9b1ff85e6f9b5d
0
CMPUT301F17T11/CupOfJava
/* HabitEvent * * Version 1.0 * * November 13, 2017 * * Copyright (c) 2017 Cup Of Java. All rights reserved. */ package com.cmput301f17t11.cupofjava.Models; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import io.searchbox.annotations.JestId; /** * Handles all properties of a Habit Event * A habit event includes a date, a name. * It can include option location and photo. * * @version 1.0 */ public class HabitEvent implements Serializable { private String userName; private Habit habit; private String comment; private Date habitEventDate; private String habitTitle; @JestId String id; //for elasticsearch /** TODO: prj5 private Geolocation location; private boolean locationSet = false; private Bitmap photo; public HabitEvent(Habit habit){ this.habitObject = habit; this.habitEventDate = new Date(); } */ /** * Constructor for HabitEvent * * @param comment brief description of habit event */ public HabitEvent(String comment){ this.comment = comment; this.habitEventDate = new Date(); } /** * Constructor for HabitEvent * * @param habit instance of Habit * @param comment brief description of habit event * @see Habit */ public HabitEvent(Habit habit, String comment) { setHabit(habit); setComment(comment); this.habitEventDate = new Date(); this.habit = habit; this.habitTitle = habit.getHabitTitle(); } /** * Constructor for HabitEvent without comment */ public HabitEvent(Habit habit){ this.habitEventDate = new Date(); this.habitTitle = habit.getHabitTitle(); this.comment = ""; this.habit = habit; } //TODO: prj5 constructor for optional comment and optional photograph //TODO: prj5 constructor for optional photograph //TODO: prj5 Constructor for optional location public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } /** * Gets habit reason * * @return habit reason */ public String getHabitReason(){ return this.getHabitReason(); } /** * Gets habit event date * * @return instance of Date */ public Date getHabitEventDate(){ return this.habitEventDate; } /** * Sets habit * * @param habit instance of Habit * @see Habit */ public void setHabit(Habit habit) { this.habit = habit; } /** * Gets habit * * @return instance of Habit * @see Habit */ public Habit getHabit() { return habit; } public void setComment(String comment){ if (comment.length() > 20){ new Exception("Comment longer than 20 chars"); } else { this.comment = comment; } } public String getDateAsString(){ String dateString = new SimpleDateFormat("d MMM yyy") .format(this.habitEventDate); return dateString; } public String getHabitTitle() { return habitTitle; } public String getComment(){ return this.comment; } @Override public String toString(){ //this gets called by array adapter return ("What: " + this.habitTitle + "\n" + "When: " + getDateAsString()); } }
app/src/main/java/com/cmput301f17t11/cupofjava/Models/HabitEvent.java
/* HabitEvent * * Version 1.0 * * November 13, 2017 * * Copyright (c) 2017 Cup Of Java. All rights reserved. */ package com.cmput301f17t11.cupofjava.Models; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import io.searchbox.annotations.JestId; /** * Handles all properties of a Habit Event * A habit event includes a date, a name. * It can include option location and photo. * * @version 1.0 */ public class HabitEvent implements Serializable { private String userName; private Habit habit; private String habitId; private String habitTitle; public String getHabitId() { return habitId; } public String getHabitTitle() { return habitTitle; } public void setHabitId(String habitId) { this.habitId = habitId; } private String comment; private Date habitEventDate; @JestId String id; //for elasticsearch /** TODO: prj5 private Geolocation location; private boolean locationSet = false; private Bitmap photo; public HabitEvent(Habit habit){ this.habitObject = habit; this.habitEventDate = new Date(); } */ /** * Constructor for HabitEvent * * @param comment brief description of habit event */ public HabitEvent(String comment){ this.comment = comment; this.habitEventDate = new Date(); } /** * Constructor for HabitEvent * * @param habit instance of Habit * @param comment brief description of habit event * @see Habit */ public HabitEvent(Habit habit, String comment) { setHabit(habit); setComment(comment); this.habitEventDate = new Date(); this.habit = habit; this.habitTitle = habit.getHabitTitle(); } /** * Constructor for HabitEvent without comment */ public HabitEvent(Habit habit){ this.habitEventDate = new Date(); this.habitTitle = habit.getHabitTitle(); this.comment = ""; this.habit = habit; } //TODO: prj5 constructor for optional comment and optional photograph //TODO: prj5 constructor for optional photograph //TODO: prj5 Constructor for optional location public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } /** * Gets habit reason * * @return habit reason */ public String getHabitReason(){ return this.getHabitReason(); } /** * Gets habit event date * * @return instance of Date */ public Date getHabitEventDate(){ return this.habitEventDate; } /** * Sets habit * * @param habit instance of Habit * @see Habit */ public void setHabit(Habit habit) { this.habit = habit; } /** * Gets habit * * @return instance of Habit * @see Habit */ public Habit getHabit() { return habit; } public void setComment(String comment){ if (comment.length() > 20){ new Exception("Comment longer than 20 chars"); } else { this.comment = comment; } } public String getDateAsString(){ String dateString = new SimpleDateFormat("d MMM yyy") .format(this.habitEventDate); return dateString; } public String getComment(){ return this.comment; } @Override public String toString(){ //this gets called by array adapter return ("What: " + this.habitTitle + "\n" + "When: " + getDateAsString()); } }
minor adjustments
app/src/main/java/com/cmput301f17t11/cupofjava/Models/HabitEvent.java
minor adjustments
<ide><path>pp/src/main/java/com/cmput301f17t11/cupofjava/Models/HabitEvent.java <ide> <ide> private String userName; <ide> private Habit habit; <del> private String habitId; <del> <del> <del> private String habitTitle; <del> <del> public String getHabitId() { <del> return habitId; <del> } <del> <del> public String getHabitTitle() { <del> return habitTitle; <del> } <del> <del> <del> public void setHabitId(String habitId) { <del> this.habitId = habitId; <del> } <del> <ide> private String comment; <ide> private Date habitEventDate; <del> <add> private String habitTitle; <ide> <ide> @JestId <ide> String id; //for elasticsearch <ide> this.userName = userName; <ide> } <ide> <add> <ide> /** <ide> * Gets habit reason <ide> * <ide> return dateString; <ide> } <ide> <add> public String getHabitTitle() { <add> return habitTitle; <add> } <add> <ide> public String getComment(){ <ide> return this.comment; <ide> }
JavaScript
mit
9eb2aaaf8181743481bdce955ab3b5e9bbacac90
0
yungsters/react,facebook/react,yungsters/react,facebook/react,camsong/react,facebook/react,facebook/react,tomocchino/react,facebook/react,facebook/react,yungsters/react,tomocchino/react,tomocchino/react,camsong/react,camsong/react,tomocchino/react,tomocchino/react,tomocchino/react,camsong/react,yungsters/react,yungsters/react,camsong/react,yungsters/react,yungsters/react,tomocchino/react,facebook/react,camsong/react,camsong/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import assign from 'object-assign'; import * as Scheduler from 'scheduler'; import ReactCurrentDispatcher from '../ReactCurrentDispatcher'; import ReactCurrentActQueue from '../ReactCurrentActQueue'; import ReactCurrentOwner from '../ReactCurrentOwner'; import ReactDebugCurrentFrame from '../ReactDebugCurrentFrame'; import ReactCurrentBatchConfig from '../ReactCurrentBatchConfig'; const ReactSharedInternals = { ReactCurrentDispatcher, ReactCurrentOwner, ReactCurrentBatchConfig, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign, // Re-export the schedule API(s) for UMD bundles. // This avoids introducing a dependency on a new UMD global in a minor update, // Since that would be a breaking change (e.g. for all existing CodeSandboxes). // This re-export is only required for UMD bundles; // CJS bundles use the shared NPM package. Scheduler, }; if (__DEV__) { ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; } export default ReactSharedInternals;
packages/react/src/forks/ReactSharedInternals.umd.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import assign from 'object-assign'; import * as Scheduler from 'scheduler'; import ReactCurrentDispatcher from '../ReactCurrentDispatcher'; import ReactCurrentOwner from '../ReactCurrentOwner'; import ReactDebugCurrentFrame from '../ReactDebugCurrentFrame'; import ReactCurrentBatchConfig from '../ReactCurrentBatchConfig'; const ReactSharedInternals = { ReactCurrentDispatcher, ReactCurrentOwner, ReactCurrentBatchConfig, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign, // Re-export the schedule API(s) for UMD bundles. // This avoids introducing a dependency on a new UMD global in a minor update, // Since that would be a breaking change (e.g. for all existing CodeSandboxes). // This re-export is only required for UMD bundles; // CJS bundles use the shared NPM package. Scheduler, }; if (__DEV__) { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; } export default ReactSharedInternals;
Fixed ReactSharedInternals export in UMD bundle (#22117)
packages/react/src/forks/ReactSharedInternals.umd.js
Fixed ReactSharedInternals export in UMD bundle (#22117)
<ide><path>ackages/react/src/forks/ReactSharedInternals.umd.js <ide> import assign from 'object-assign'; <ide> import * as Scheduler from 'scheduler'; <ide> import ReactCurrentDispatcher from '../ReactCurrentDispatcher'; <add>import ReactCurrentActQueue from '../ReactCurrentActQueue'; <ide> import ReactCurrentOwner from '../ReactCurrentOwner'; <ide> import ReactDebugCurrentFrame from '../ReactDebugCurrentFrame'; <ide> import ReactCurrentBatchConfig from '../ReactCurrentBatchConfig'; <ide> }; <ide> <ide> if (__DEV__) { <add> ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; <ide> ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; <ide> } <ide>
Java
apache-2.0
f1481c1dad0ddc1d4075bfa2871a5eab36530449
0
nasrallahmounir/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,trombonehero/Footlights
/* * Copyright 2011 Jonathan Anderson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.footlights.boot; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** Loads classes from a single JAR file. */ class JARLoader { /** * Open a JAR file, from which we will load classes later. * * @param url a URL, no "jar:" prefix (e.g. "file:///home/...", "http://foo.com/...") */ public static JARLoader open(final URL url) throws IOException { if (!url.getProtocol().equals("jar")) throw new MalformedURLException("JAR URL does not start with 'jar:' '" + url + "'"); JarFile jar = new JAROpener().open(url); if (jar.getManifest() == null) throw new SecurityException("The jar file has no manifest (thus, cannot be signed)"); return new JARLoader(jar, url); } public JarFile getJarFile() { return jar; } /** Read a class' bytecode. */ public Bytecode readBytecode(String className) throws ClassNotFoundException, IOException, SecurityException { final String classPath = className.replace('.', '/') + ".class"; for (Enumeration<JarEntry> i = jar.entries() ; i.hasMoreElements() ;) { JarEntry entry = i.nextElement(); if (entry.isDirectory()) continue; if (entry.getName().startsWith("META-INF/")) continue; // read the JAR entry (to make sure it's actually signed) InputStream is = jar.getInputStream(entry); int avail = is.available(); byte[] buffer = new byte[avail]; is.read(buffer); is.close(); if (entry.getName().equals(classPath)) { if (entry.getCodeSigners() == null) throw new SecurityException(entry.toString() + " not signed"); Bytecode bytecode = new Bytecode(); bytecode.raw = buffer; bytecode.source = new CodeSource(url, entry.getCodeSigners()); return bytecode; } } throw new ClassNotFoundException("No class " + className + " in JAR file " + url); } /** Private constructor. */ private JARLoader(JarFile jar, URL url) throws MalformedURLException { this.jar = jar; this.url = url; } /** Opens a {@link JarFile}, or on failure, provides a means to return an {@link Exception}. */ private static class JAROpener implements PrivilegedAction<JarFile> { synchronized JarFile open(URL url) throws IOException { if (url.toExternalForm().startsWith("jar:")) this.url = url; else this.url = new URL("jar:" + url + "!/"); JarFile jar = AccessController.doPrivileged(this); if (jar == null) throw error; else return jar; } @Override public synchronized JarFile run() { try { return ((JarURLConnection) url.openConnection()).getJarFile(); } catch(IOException e) { error = e; return null; } } private URL url; private IOException error; }; /** The {@link JarFile} that we are loading classes from. */ private final JarFile jar; /** Where {@link #jar} came from. */ private final URL url; }
Client/Bootstrap/src/main/java/me/footlights/boot/JARLoader.java
/* * Copyright 2011 Jonathan Anderson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.footlights.boot; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** Loads classes from a single JAR file. */ class JARLoader { /** * Open a JAR file, from which we will load classes later. * * @param url a URL, no "jar:" prefix (e.g. "file:///home/...", "http://foo.com/...") */ public static JARLoader open(final URL url) throws IOException { if (!url.getProtocol().equals("jar")) throw new MalformedURLException("JAR URL does not start with 'jar:' '" + url + "'"); JarFile jar = new JAROpener().open(url); if (jar.getManifest() == null) throw new SecurityException("The jar file has no manifest (thus, cannot be signed)"); return new JARLoader(jar, url); } public JarFile getJarFile() { return jar; } /** Read a class' bytecode. */ public Bytecode readBytecode(String className) throws ClassNotFoundException, IOException { final String classPath = className.replace('.', '/') + ".class"; for (Enumeration<JarEntry> i = jar.entries() ; i.hasMoreElements() ;) { JarEntry entry = i.nextElement(); if (entry.isDirectory()) continue; if (entry.getName().startsWith("META-INF/")) continue; // read the JAR entry (to make sure it's actually signed) InputStream is = jar.getInputStream(entry); int avail = is.available(); byte[] buffer = new byte[avail]; is.read(buffer); is.close(); if (entry.getName().equals(classPath)) { if (entry.getCodeSigners() == null) throw new Error(entry.toString() + " not signed"); Bytecode bytecode = new Bytecode(); bytecode.raw = buffer; bytecode.source = new CodeSource(url, entry.getCodeSigners()); return bytecode; } } throw new ClassNotFoundException("No class " + className + " in JAR file " + url); } /** Private constructor. */ private JARLoader(JarFile jar, URL url) throws MalformedURLException { this.jar = jar; this.url = url; } /** Opens a {@link JarFile}, or on failure, provides a means to return an {@link Exception}. */ private static class JAROpener implements PrivilegedAction<JarFile> { synchronized JarFile open(URL url) throws IOException { if (url.toExternalForm().startsWith("jar:")) this.url = url; else this.url = new URL("jar:" + url + "!/"); JarFile jar = AccessController.doPrivileged(this); if (jar == null) throw error; else return jar; } @Override public synchronized JarFile run() { try { return ((JarURLConnection) url.openConnection()).getJarFile(); } catch(IOException e) { error = e; return null; } } private URL url; private IOException error; }; /** The {@link JarFile} that we are loading classes from. */ private final JarFile jar; /** Where {@link #jar} came from. */ private final URL url; }
Use SecurityException rather than Error. Why not be specific about the kind of problem we've encountered?
Client/Bootstrap/src/main/java/me/footlights/boot/JARLoader.java
Use SecurityException rather than Error.
<ide><path>lient/Bootstrap/src/main/java/me/footlights/boot/JARLoader.java <ide> <ide> /** Read a class' bytecode. */ <ide> public Bytecode readBytecode(String className) <del> throws ClassNotFoundException, IOException <add> throws ClassNotFoundException, IOException, SecurityException <ide> { <ide> final String classPath = className.replace('.', '/') + ".class"; <ide> for (Enumeration<JarEntry> i = jar.entries() ; i.hasMoreElements() ;) <ide> if (entry.getName().equals(classPath)) <ide> { <ide> if (entry.getCodeSigners() == null) <del> throw new Error(entry.toString() + " not signed"); <add> throw new SecurityException(entry.toString() + " not signed"); <ide> <ide> Bytecode bytecode = new Bytecode(); <ide> bytecode.raw = buffer;
Java
apache-2.0
fddf4bd31f1c2425185b9a2a7a8ced6cd3954585
0
youdonghai/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,retomerz/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,allotria/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,xfournet/intellij-community,kdwink/intellij-community,blademainer/intellij-community,adedayo/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,slisson/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,samthor/intellij-community,samthor/intellij-community,slisson/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,signed/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,signed/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,allotria/intellij-community,fnouama/intellij-community,caot/intellij-community,hurricup/intellij-community,izonder/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,kool79/intellij-community,fitermay/intellij-community,caot/intellij-community,blademainer/intellij-community,allotria/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,holmes/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,jagguli/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,jagguli/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,signed/intellij-community,izonder/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,kool79/intellij-community,holmes/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,da1z/intellij-community,asedunov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,samthor/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,caot/intellij-community,signed/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,Distrotech/intellij-community,signed/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,samthor/intellij-community,fitermay/intellij-community,xfournet/intellij-community,signed/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,slisson/intellij-community,adedayo/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,kdwink/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,izonder/intellij-community,hurricup/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,kool79/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,xfournet/intellij-community,samthor/intellij-community,amith01994/intellij-community,dslomov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,xfournet/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,samthor/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,fitermay/intellij-community,samthor/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,petteyg/intellij-community,amith01994/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,wreckJ/intellij-community,caot/intellij-community,youdonghai/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,kdwink/intellij-community,fnouama/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ryano144/intellij-community,da1z/intellij-community,robovm/robovm-studio,blademainer/intellij-community,kool79/intellij-community,dslomov/intellij-community,jagguli/intellij-community,fitermay/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,caot/intellij-community,kool79/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,kool79/intellij-community,vladmm/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,signed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,asedunov/intellij-community,holmes/intellij-community,hurricup/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,diorcety/intellij-community,supersven/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,robovm/robovm-studio,caot/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,kool79/intellij-community,gnuhub/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,caot/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,allotria/intellij-community,petteyg/intellij-community,xfournet/intellij-community,signed/intellij-community,allotria/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,semonte/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,allotria/intellij-community,robovm/robovm-studio,dslomov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,amith01994/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,kdwink/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,supersven/intellij-community,holmes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,fitermay/intellij-community,xfournet/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,ibinti/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,holmes/intellij-community,amith01994/intellij-community,semonte/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,da1z/intellij-community,robovm/robovm-studio,adedayo/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,allotria/intellij-community,vladmm/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,dslomov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,vladmm/intellij-community,kdwink/intellij-community,supersven/intellij-community,retomerz/intellij-community,dslomov/intellij-community,supersven/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,holmes/intellij-community,blademainer/intellij-community,izonder/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,kool79/intellij-community,tmpgit/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,fnouama/intellij-community,supersven/intellij-community,diorcety/intellij-community,jagguli/intellij-community,fitermay/intellij-community,kool79/intellij-community,allotria/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,hurricup/intellij-community,semonte/intellij-community,ryano144/intellij-community,ryano144/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,semonte/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,izonder/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,clumsy/intellij-community,slisson/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,apixandru/intellij-community,holmes/intellij-community,retomerz/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,caot/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ryano144/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,semonte/intellij-community,caot/intellij-community,signed/intellij-community,nicolargo/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community
/* ========================================================================== * Copyright 2006 Mevenide Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================================= */ package org.jetbrains.idea.maven.execution; import com.intellij.execution.ExecutionException; import com.intellij.execution.RunManager; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.impl.EditConfigurationsDialog; import com.intellij.execution.impl.RunManagerImpl; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.util.PathUtil; import com.intellij.util.io.ZipUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM2RtMarker; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM31RtMarker; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM3RtMarker; import org.jetbrains.idea.maven.artifactResolver.common.MavenModuleMap; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenSettings; import org.jetbrains.idea.maven.utils.MavenUtil; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.io.*; import java.util.*; import java.util.zip.ZipOutputStream; /** * @author Ralf Quebbemann */ public class MavenExternalParameters { private static final Logger LOG = Logger.getInstance(MavenExternalParameters.class); public static final String MAVEN_LAUNCHER_CLASS = "org.codehaus.classworlds.Launcher"; @NonNls private static final String MAVEN_OPTS = "MAVEN_OPTS"; @Deprecated // Use createJavaParameters(Project,MavenRunnerParameters, MavenGeneralSettings,MavenRunnerSettings,MavenRunConfiguration) public static JavaParameters createJavaParameters(@Nullable final Project project, @NotNull final MavenRunnerParameters parameters, @Nullable MavenGeneralSettings coreSettings, @Nullable MavenRunnerSettings runnerSettings) throws ExecutionException { return createJavaParameters(project, parameters, coreSettings, runnerSettings, null); } public static JavaParameters createJavaParameters(@Nullable final Project project, @NotNull final MavenRunnerParameters parameters) throws ExecutionException { return createJavaParameters(project, parameters, null, null, null); } /** * * @param project * @param parameters * @param coreSettings * @param runnerSettings * @param runConfiguration used to creation fix if maven home not found * @return * @throws ExecutionException */ public static JavaParameters createJavaParameters(@Nullable final Project project, @NotNull final MavenRunnerParameters parameters, @Nullable MavenGeneralSettings coreSettings, @Nullable MavenRunnerSettings runnerSettings, @Nullable MavenRunConfiguration runConfiguration) throws ExecutionException { final JavaParameters params = new JavaParameters(); ApplicationManager.getApplication().assertReadAccessAllowed(); if (coreSettings == null) { coreSettings = project == null ? new MavenGeneralSettings() : MavenProjectsManager.getInstance(project).getGeneralSettings(); } if (runnerSettings == null) { runnerSettings = project == null ? new MavenRunnerSettings() : MavenRunner.getInstance(project).getState(); } params.setWorkingDirectory(parameters.getWorkingDirFile()); params.setJdk(getJdk(project, runnerSettings, project != null && MavenRunner.getInstance(project).getState() == runnerSettings)); final String mavenHome = resolveMavenHome(coreSettings, project, runConfiguration); params.getProgramParametersList().add("-Didea.version=" + MavenUtil.getIdeaVersionToPassToMavenProcess()); addVMParameters(params.getVMParametersList(), mavenHome, runnerSettings); File confFile = MavenUtil.getMavenConfFile(new File(mavenHome)); if (!confFile.isFile()) { throw new ExecutionException("Configuration file is not exists in maven home: " + confFile.getAbsolutePath()); } if (project != null && parameters.isResolveToWorkspace()) { try { String resolverJar = getArtifactResolverJar(MavenUtil.getMavenVersion(mavenHome)); confFile = patchConfFile(confFile, resolverJar); File modulesPathsFile = dumpModulesPaths(project); params.getVMParametersList().addProperty(MavenModuleMap.PATHS_FILE_PROPERTY, modulesPathsFile.getAbsolutePath()); } catch (IOException e) { LOG.error(e); throw new ExecutionException("Failed to run maven configuration", e); } } params.getVMParametersList().addProperty("classworlds.conf", confFile.getPath()); for (String path : getMavenClasspathEntries(mavenHome)) { params.getClassPath().add(path); } params.setEnv(new HashMap<String, String>(runnerSettings.getEnvironmentProperties())); params.setPassParentEnvs(runnerSettings.isPassParentEnv()); params.setMainClass(MAVEN_LAUNCHER_CLASS); EncodingManager encodingManager = project == null ? EncodingProjectManager.getInstance() : EncodingProjectManager.getInstance(project); params.setCharset(encodingManager.getDefaultCharset()); addMavenParameters(params.getProgramParametersList(), mavenHome, coreSettings, runnerSettings, parameters); return params; } private static File patchConfFile(File conf, String library) throws IOException { File tmpConf = File.createTempFile("idea-", "-mvn.conf"); tmpConf.deleteOnExit(); patchConfFile(conf, tmpConf, library); return tmpConf; } private static void patchConfFile(File originalConf, File dest, String library) throws IOException { Scanner sc = new Scanner(originalConf); try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest))); try { boolean patched = false; while (sc.hasNextLine()) { String line = sc.nextLine(); out.append(line); out.newLine(); if (!patched && "[plexus.core]".equals(line)) { out.append("load ").append(library); out.newLine(); patched = true; } } } finally { out.close(); } } finally { sc.close(); } } private static String getArtifactResolverJar(@Nullable String mavenVersion) throws IOException { boolean isMaven3; Class marker; if (mavenVersion != null && mavenVersion.compareTo("3.1.0") >= 0) { isMaven3 = true; marker = MavenArtifactResolvedM31RtMarker.class; } else if (mavenVersion != null && mavenVersion.compareTo("3.0.0") >= 0) { isMaven3 = true; marker = MavenArtifactResolvedM3RtMarker.class; } else { isMaven3 = false; marker = MavenArtifactResolvedM2RtMarker.class; } File classDirOrJar = new File(PathUtil.getJarPathForClass(marker)); if (!classDirOrJar.isDirectory()) { return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation. } // it's a classes directory, we are in development mode. File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar"); tempFile.deleteOnExit(); ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile)); try { ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null); if (isMaven3) { File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class)); String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/'); ZipUtil.addDirToZipRecursively(zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null); } } finally { zipOutput.close(); } return tempFile.getAbsolutePath(); } private static File dumpModulesPaths(@NotNull Project project) throws IOException { ApplicationManager.getApplication().assertReadAccessAllowed(); Properties res = new Properties(); MavenProjectsManager manager = MavenProjectsManager.getInstance(project); for (Module module : ModuleManager.getInstance(project).getModules()) { if (manager.isMavenizedModule(module)) { MavenProject mavenProject = manager.findProject(module); if (mavenProject != null && !manager.isIgnored(mavenProject)) { res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ":pom" + ':' + mavenProject.getMavenId().getVersion(), mavenProject.getFile().getPath()); res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ":test-jar" + ':' + mavenProject.getMavenId().getVersion(), mavenProject.getTestOutputDirectory()); res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ':' + mavenProject.getPackaging() + ':' + mavenProject.getMavenId().getVersion(), mavenProject.getOutputDirectory()); } } } File file = new File(PathManager.getSystemPath(), "Maven/idea-projects-state-" + project.getLocationHash() + ".properties"); file.getParentFile().mkdirs(); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { res.store(out, null); } finally { out.close(); } return file; } @NotNull private static Sdk getJdk(@Nullable Project project, MavenRunnerSettings runnerSettings, boolean isGlobalRunnerSettings) throws ExecutionException { String name = runnerSettings.getJreName(); if (name.equals(MavenRunnerSettings.USE_INTERNAL_JAVA)) { return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } if (name.equals(MavenRunnerSettings.USE_PROJECT_JDK)) { if (project != null) { Sdk res = ProjectRootManager.getInstance(project).getProjectSdk(); if (res != null) { return res; } } if (project == null) { Sdk recent = ProjectJdkTable.getInstance().findMostRecentSdkOfType(JavaSdk.getInstance()); if (recent != null) return recent; return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } throw new ProjectJdkSettingsOpenerExecutionException("Project JDK is not specified. <a href=''>Configure</a>", project); } if (name.equals(MavenRunnerSettings.USE_JAVA_HOME)) { final String javaHome = System.getenv("JAVA_HOME"); if (StringUtil.isEmptyOrSpaces(javaHome)) { throw new ExecutionException(RunnerBundle.message("maven.java.home.undefined")); } final Sdk jdk = JavaSdk.getInstance().createJdk("", javaHome); if (jdk == null) { throw new ExecutionException(RunnerBundle.message("maven.java.home.invalid", javaHome)); } return jdk; } for (Sdk projectJdk : ProjectJdkTable.getInstance().getAllJdks()) { if (projectJdk.getName().equals(name)) { return projectJdk; } } if (isGlobalRunnerSettings) { throw new ExecutionException(RunnerBundle.message("maven.java.not.found.default.config", name)); } else { throw new ExecutionException(RunnerBundle.message("maven.java.not.found", name)); } } public static void addVMParameters(ParametersList parametersList, String mavenHome, MavenRunnerSettings runnerSettings) { parametersList.addParametersString(System.getenv(MAVEN_OPTS)); parametersList.addParametersString(runnerSettings.getVmOptions()); parametersList.addProperty("maven.home", mavenHome); } private static void addMavenParameters(ParametersList parametersList, String mavenHome, MavenGeneralSettings coreSettings, MavenRunnerSettings runnerSettings, MavenRunnerParameters parameters) { encodeCoreAndRunnerSettings(coreSettings, mavenHome, parametersList); if (runnerSettings.isSkipTests()) { parametersList.addProperty("skipTests", "true"); } for (Map.Entry<String, String> entry : runnerSettings.getMavenProperties().entrySet()) { if (entry.getKey().length() > 0) { parametersList.addProperty(entry.getKey(), entry.getValue()); } } for (String goal : parameters.getGoals()) { parametersList.add(goal); } addOption(parametersList, "P", encodeProfiles(parameters.getProfilesMap())); } private static void addOption(ParametersList cmdList, @NonNls String key, @NonNls String value) { if (!StringUtil.isEmptyOrSpaces(value)) { cmdList.add("-" + key); cmdList.add(value); } } public static String resolveMavenHome(@NotNull MavenGeneralSettings coreSettings) throws ExecutionException { return resolveMavenHome(coreSettings, null, null); } /** * * @param coreSettings * @param project used to creation fix if maven home not found * @param runConfiguration used to creation fix if maven home not found * @return * @throws ExecutionException */ public static String resolveMavenHome(@NotNull MavenGeneralSettings coreSettings, @Nullable Project project, @Nullable MavenRunConfiguration runConfiguration) throws ExecutionException { final File file = MavenUtil.resolveMavenHomeDirectory(coreSettings.getMavenHome()); if (file == null) { throw createExecutionException(RunnerBundle.message("external.maven.home.no.default"), RunnerBundle.message("external.maven.home.no.default.with.fix"), coreSettings, project, runConfiguration); } if (!file.exists()) { throw createExecutionException(RunnerBundle.message("external.maven.home.does.not.exist", file.getPath()), RunnerBundle.message("external.maven.home.does.not.exist.with.fix", file.getPath()), coreSettings, project, runConfiguration); } if (!MavenUtil.isValidMavenHome(file)) { throw createExecutionException(RunnerBundle.message("external.maven.home.invalid", file.getPath()), RunnerBundle.message("external.maven.home.invalid.with.fix", file.getPath()), coreSettings, project, runConfiguration); } try { return file.getCanonicalPath(); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } } private static ExecutionException createExecutionException(String text, String textWithFix, @NotNull MavenGeneralSettings coreSettings, @Nullable Project project, @Nullable MavenRunConfiguration runConfiguration) { Project notNullProject = project; if (notNullProject == null) { if (runConfiguration == null) return new ExecutionException(text); notNullProject = runConfiguration.getProject(); if (notNullProject == null) return new ExecutionException(text); } if (coreSettings == MavenProjectsManager.getInstance(notNullProject).getGeneralSettings()) { return new ProjectSettingsOpenerExecutionException(textWithFix, notNullProject); } if (runConfiguration != null) { Project runCfgProject = runConfiguration.getProject(); if (runCfgProject != null) { if (((RunManagerImpl)RunManager.getInstance(runCfgProject)).getSettings(runConfiguration) != null) { return new RunConfigurationOpenerExecutionException(textWithFix, runConfiguration); } } } return new ExecutionException(text); } @SuppressWarnings({"HardCodedStringLiteral"}) private static List<String> getMavenClasspathEntries(final String mavenHome) { File mavenHomeBootAsFile = new File(new File(mavenHome, "core"), "boot"); // if the dir "core/boot" does not exist we are using a Maven version > 2.0.5 // in this case the classpath must be constructed from the dir "boot" if (!mavenHomeBootAsFile.exists()) { mavenHomeBootAsFile = new File(mavenHome, "boot"); } List<String> classpathEntries = new ArrayList<String>(); File[] files = mavenHomeBootAsFile.listFiles(); if (files != null) { for (File file : files) { if (file.getName().contains("classworlds")) { classpathEntries.add(file.getAbsolutePath()); } } } return classpathEntries; } private static void encodeCoreAndRunnerSettings(MavenGeneralSettings coreSettings, String mavenHome, ParametersList cmdList) { if (coreSettings.isWorkOffline()) { cmdList.add("--offline"); } boolean atLeastMaven3 = MavenUtil.isMaven3(mavenHome); if (!atLeastMaven3) { addIfNotEmpty(cmdList, coreSettings.getPluginUpdatePolicy().getCommandLineOption()); if (!coreSettings.isUsePluginRegistry()) { cmdList.add("--no-plugin-registry"); } } if (coreSettings.getOutputLevel() == MavenExecutionOptions.LoggingLevel.DEBUG) { cmdList.add("--debug"); } if (coreSettings.isNonRecursive()) { cmdList.add("--non-recursive"); } if (coreSettings.isPrintErrorStackTraces()) { cmdList.add("--errors"); } if (coreSettings.isAlwaysUpdateSnapshots()) { cmdList.add("--update-snapshots"); } if (StringUtil.isNotEmpty(coreSettings.getThreads())) { cmdList.add("-T", coreSettings.getThreads()); } addIfNotEmpty(cmdList, coreSettings.getFailureBehavior().getCommandLineOption()); addIfNotEmpty(cmdList, coreSettings.getChecksumPolicy().getCommandLineOption()); addOption(cmdList, "s", coreSettings.getUserSettingsFile()); if (!StringUtil.isEmptyOrSpaces(coreSettings.getLocalRepository())) { cmdList.addProperty("maven.repo.local", coreSettings.getLocalRepository()); } } private static void addIfNotEmpty(ParametersList parametersList, @Nullable String value) { if (!StringUtil.isEmptyOrSpaces(value)) { parametersList.add(value); } } private static String encodeProfiles(Map<String, Boolean> profiles) { StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry<String, Boolean> entry : profiles.entrySet()) { if (stringBuilder.length() != 0) { stringBuilder.append(","); } if (!entry.getValue()) { stringBuilder.append("!"); } stringBuilder.append(entry.getKey()); } return stringBuilder.toString(); } private static class ProjectSettingsOpenerExecutionException extends ExecutionExceptionWithHyperlink { private final Project myProject; public ProjectSettingsOpenerExecutionException(final String s, Project project) { super(s); myProject = project; } @Override protected void hyperlinkClicked() { ShowSettingsUtil.getInstance().showSettingsDialog(myProject, MavenSettings.DISPLAY_NAME); } } private static class ProjectJdkSettingsOpenerExecutionException extends ExecutionExceptionWithHyperlink { private final Project myProject; public ProjectJdkSettingsOpenerExecutionException(final String s, Project project) { super(s); myProject = project; } @Override protected void hyperlinkClicked() { ProjectSettingsService.getInstance(myProject).openProjectSettings(); } } private static class RunConfigurationOpenerExecutionException extends ExecutionExceptionWithHyperlink { private final MavenRunConfiguration myRunConfiguration; public RunConfigurationOpenerExecutionException(final String s, MavenRunConfiguration runConfiguration) { super(s); myRunConfiguration = runConfiguration; } @Override protected void hyperlinkClicked() { Project project = myRunConfiguration.getProject(); EditConfigurationsDialog dialog = new EditConfigurationsDialog(project); dialog.show(); } } private static abstract class ExecutionExceptionWithHyperlink extends ExecutionException implements HyperlinkListener, NotificationListener { public ExecutionExceptionWithHyperlink(String s) { super(s); } protected abstract void hyperlinkClicked(); @Override public final void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { hyperlinkClicked(); } } @Override public final void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { hyperlinkUpdate(event); } } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java
/* ========================================================================== * Copyright 2006 Mevenide Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================================= */ package org.jetbrains.idea.maven.execution; import com.intellij.execution.ExecutionException; import com.intellij.execution.RunManager; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.impl.EditConfigurationsDialog; import com.intellij.execution.impl.RunManagerImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.util.PathUtil; import com.intellij.util.io.ZipUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM2RtMarker; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM31RtMarker; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM3RtMarker; import org.jetbrains.idea.maven.artifactResolver.common.MavenModuleMap; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenSettings; import org.jetbrains.idea.maven.utils.MavenUtil; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.io.*; import java.util.*; import java.util.zip.ZipOutputStream; /** * @author Ralf Quebbemann */ public class MavenExternalParameters { private static final Logger LOG = Logger.getInstance(MavenExternalParameters.class); public static final String MAVEN_LAUNCHER_CLASS = "org.codehaus.classworlds.Launcher"; @NonNls private static final String MAVEN_OPTS = "MAVEN_OPTS"; @Deprecated // Use createJavaParameters(Project,MavenRunnerParameters, MavenGeneralSettings,MavenRunnerSettings,MavenRunConfiguration) public static JavaParameters createJavaParameters(@Nullable final Project project, @NotNull final MavenRunnerParameters parameters, @Nullable MavenGeneralSettings coreSettings, @Nullable MavenRunnerSettings runnerSettings) throws ExecutionException { return createJavaParameters(project, parameters, coreSettings, runnerSettings, null); } public static JavaParameters createJavaParameters(@Nullable final Project project, @NotNull final MavenRunnerParameters parameters) throws ExecutionException { return createJavaParameters(project, parameters, null, null, null); } /** * * @param project * @param parameters * @param coreSettings * @param runnerSettings * @param runConfiguration used to creation fix if maven home not found * @return * @throws ExecutionException */ public static JavaParameters createJavaParameters(@Nullable final Project project, @NotNull final MavenRunnerParameters parameters, @Nullable MavenGeneralSettings coreSettings, @Nullable MavenRunnerSettings runnerSettings, @Nullable MavenRunConfiguration runConfiguration) throws ExecutionException { final JavaParameters params = new JavaParameters(); ApplicationManager.getApplication().assertReadAccessAllowed(); if (coreSettings == null) { coreSettings = project == null ? new MavenGeneralSettings() : MavenProjectsManager.getInstance(project).getGeneralSettings(); } if (runnerSettings == null) { runnerSettings = project == null ? new MavenRunnerSettings() : MavenRunner.getInstance(project).getState(); } params.setWorkingDirectory(parameters.getWorkingDirFile()); params.setJdk(getJdk(project, runnerSettings, project != null && MavenRunner.getInstance(project).getState() == runnerSettings)); final String mavenHome = resolveMavenHome(coreSettings, project, runConfiguration); params.getProgramParametersList().add("-Didea.version=" + MavenUtil.getIdeaVersionToPassToMavenProcess()); addVMParameters(params.getVMParametersList(), mavenHome, runnerSettings); File confFile = MavenUtil.getMavenConfFile(new File(mavenHome)); if (!confFile.isFile()) { throw new ExecutionException("Configuration file is not exists in maven home: " + confFile.getAbsolutePath()); } if (project != null && parameters.isResolveToWorkspace()) { try { String resolverJar = getArtifactResolverJar(MavenUtil.getMavenVersion(mavenHome)); confFile = patchConfFile(confFile, resolverJar); File modulesPathsFile = dumpModulesPaths(project); params.getVMParametersList().addProperty(MavenModuleMap.PATHS_FILE_PROPERTY, modulesPathsFile.getAbsolutePath()); } catch (IOException e) { LOG.error(e); throw new ExecutionException("Failed to run maven configuration", e); } } params.getVMParametersList().addProperty("classworlds.conf", confFile.getPath()); for (String path : getMavenClasspathEntries(mavenHome)) { params.getClassPath().add(path); } params.setEnv(new HashMap<String, String>(runnerSettings.getEnvironmentProperties())); params.setPassParentEnvs(runnerSettings.isPassParentEnv()); params.setMainClass(MAVEN_LAUNCHER_CLASS); EncodingManager encodingManager = project == null ? EncodingProjectManager.getInstance() : EncodingProjectManager.getInstance(project); params.setCharset(encodingManager.getDefaultCharset()); addMavenParameters(params.getProgramParametersList(), mavenHome, coreSettings, runnerSettings, parameters); return params; } private static File patchConfFile(File conf, String library) throws IOException { File tmpConf = File.createTempFile("idea-", "-mvn.conf"); tmpConf.deleteOnExit(); patchConfFile(conf, tmpConf, library); return tmpConf; } private static void patchConfFile(File originalConf, File dest, String library) throws IOException { Scanner sc = new Scanner(originalConf); try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest))); try { boolean patched = false; while (sc.hasNextLine()) { String line = sc.nextLine(); out.append(line); out.newLine(); if (!patched && "[plexus.core]".equals(line)) { out.append("load ").append(library); out.newLine(); patched = true; } } } finally { out.close(); } } finally { sc.close(); } } private static String getArtifactResolverJar(@Nullable String mavenVersion) throws IOException { boolean isMaven3; Class marker; if (mavenVersion != null && mavenVersion.compareTo("3.1.0") >= 0) { isMaven3 = true; marker = MavenArtifactResolvedM31RtMarker.class; } else if (mavenVersion != null && mavenVersion.compareTo("3.0.0") >= 0) { isMaven3 = true; marker = MavenArtifactResolvedM3RtMarker.class; } else { isMaven3 = false; marker = MavenArtifactResolvedM2RtMarker.class; } File classDirOrJar = new File(PathUtil.getJarPathForClass(marker)); if (!classDirOrJar.isDirectory()) { return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation. } // it's a classes directory, we are in development mode. File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar"); tempFile.deleteOnExit(); ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile)); try { ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null); if (isMaven3) { File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class)); String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/'); ZipUtil.addDirToZipRecursively(zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null); } } finally { zipOutput.close(); } return tempFile.getAbsolutePath(); } private static File dumpModulesPaths(@NotNull Project project) throws IOException { ApplicationManager.getApplication().assertReadAccessAllowed(); Properties res = new Properties(); MavenProjectsManager manager = MavenProjectsManager.getInstance(project); for (Module module : ModuleManager.getInstance(project).getModules()) { if (manager.isMavenizedModule(module)) { MavenProject mavenProject = manager.findProject(module); if (mavenProject != null && !manager.isIgnored(mavenProject)) { res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ":pom" + ':' + mavenProject.getMavenId().getVersion(), mavenProject.getFile().getPath()); res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ":test-jar" + ':' + mavenProject.getMavenId().getVersion(), mavenProject.getTestOutputDirectory()); res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ':' + mavenProject.getPackaging() + ':' + mavenProject.getMavenId().getVersion(), mavenProject.getOutputDirectory()); } } } File file = new File(PathManager.getSystemPath(), "Maven/idea-projects-state-" + project.getLocationHash() + ".properties"); file.getParentFile().mkdirs(); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { res.store(out, null); } finally { out.close(); } return file; } @NotNull private static Sdk getJdk(@Nullable Project project, MavenRunnerSettings runnerSettings, boolean isGlobalRunnerSettings) throws ExecutionException { String name = runnerSettings.getJreName(); if (name.equals(MavenRunnerSettings.USE_INTERNAL_JAVA)) { return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } if (name.equals(MavenRunnerSettings.USE_PROJECT_JDK)) { if (project != null) { Sdk res = ProjectRootManager.getInstance(project).getProjectSdk(); if (res != null) { return res; } } if (project == null) { Sdk recent = ProjectJdkTable.getInstance().findMostRecentSdkOfType(JavaSdk.getInstance()); if (recent != null) return recent; return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } throw new ProjectJdkSettingsOpenerExecutionException("Project JDK is not specified. <a href='#'>Configure</a>", project); } if (name.equals(MavenRunnerSettings.USE_JAVA_HOME)) { final String javaHome = System.getenv("JAVA_HOME"); if (StringUtil.isEmptyOrSpaces(javaHome)) { throw new ExecutionException(RunnerBundle.message("maven.java.home.undefined")); } final Sdk jdk = JavaSdk.getInstance().createJdk("", javaHome); if (jdk == null) { throw new ExecutionException(RunnerBundle.message("maven.java.home.invalid", javaHome)); } return jdk; } for (Sdk projectJdk : ProjectJdkTable.getInstance().getAllJdks()) { if (projectJdk.getName().equals(name)) { return projectJdk; } } if (isGlobalRunnerSettings) { throw new ExecutionException(RunnerBundle.message("maven.java.not.found.default.config", name)); } else { throw new ExecutionException(RunnerBundle.message("maven.java.not.found", name)); } } public static void addVMParameters(ParametersList parametersList, String mavenHome, MavenRunnerSettings runnerSettings) { parametersList.addParametersString(System.getenv(MAVEN_OPTS)); parametersList.addParametersString(runnerSettings.getVmOptions()); parametersList.addProperty("maven.home", mavenHome); } private static void addMavenParameters(ParametersList parametersList, String mavenHome, MavenGeneralSettings coreSettings, MavenRunnerSettings runnerSettings, MavenRunnerParameters parameters) { encodeCoreAndRunnerSettings(coreSettings, mavenHome, parametersList); if (runnerSettings.isSkipTests()) { parametersList.addProperty("skipTests", "true"); } for (Map.Entry<String, String> entry : runnerSettings.getMavenProperties().entrySet()) { if (entry.getKey().length() > 0) { parametersList.addProperty(entry.getKey(), entry.getValue()); } } for (String goal : parameters.getGoals()) { parametersList.add(goal); } addOption(parametersList, "P", encodeProfiles(parameters.getProfilesMap())); } private static void addOption(ParametersList cmdList, @NonNls String key, @NonNls String value) { if (!StringUtil.isEmptyOrSpaces(value)) { cmdList.add("-" + key); cmdList.add(value); } } public static String resolveMavenHome(@NotNull MavenGeneralSettings coreSettings) throws ExecutionException { return resolveMavenHome(coreSettings, null, null); } /** * * @param coreSettings * @param project used to creation fix if maven home not found * @param runConfiguration used to creation fix if maven home not found * @return * @throws ExecutionException */ public static String resolveMavenHome(@NotNull MavenGeneralSettings coreSettings, @Nullable Project project, @Nullable MavenRunConfiguration runConfiguration) throws ExecutionException { final File file = MavenUtil.resolveMavenHomeDirectory(coreSettings.getMavenHome()); if (file == null) { throw createExecutionException(RunnerBundle.message("external.maven.home.no.default"), RunnerBundle.message("external.maven.home.no.default.with.fix"), coreSettings, project, runConfiguration); } if (!file.exists()) { throw createExecutionException(RunnerBundle.message("external.maven.home.does.not.exist", file.getPath()), RunnerBundle.message("external.maven.home.does.not.exist.with.fix", file.getPath()), coreSettings, project, runConfiguration); } if (!MavenUtil.isValidMavenHome(file)) { throw createExecutionException(RunnerBundle.message("external.maven.home.invalid", file.getPath()), RunnerBundle.message("external.maven.home.invalid.with.fix", file.getPath()), coreSettings, project, runConfiguration); } try { return file.getCanonicalPath(); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } } private static ExecutionException createExecutionException(String text, String textWithFix, @NotNull MavenGeneralSettings coreSettings, @Nullable Project project, @Nullable MavenRunConfiguration runConfiguration) { Project notNullProject = project; if (notNullProject == null) { if (runConfiguration == null) return new ExecutionException(text); notNullProject = runConfiguration.getProject(); if (notNullProject == null) return new ExecutionException(text); } if (coreSettings == MavenProjectsManager.getInstance(notNullProject).getGeneralSettings()) { return new ProjectSettingsOpenerExecutionException(textWithFix, notNullProject); } if (runConfiguration != null) { Project runCfgProject = runConfiguration.getProject(); if (runCfgProject != null) { if (((RunManagerImpl)RunManager.getInstance(runCfgProject)).getSettings(runConfiguration) != null) { return new RunConfigurationOpenerExecutionException(textWithFix, runConfiguration); } } } return new ExecutionException(text); } @SuppressWarnings({"HardCodedStringLiteral"}) private static List<String> getMavenClasspathEntries(final String mavenHome) { File mavenHomeBootAsFile = new File(new File(mavenHome, "core"), "boot"); // if the dir "core/boot" does not exist we are using a Maven version > 2.0.5 // in this case the classpath must be constructed from the dir "boot" if (!mavenHomeBootAsFile.exists()) { mavenHomeBootAsFile = new File(mavenHome, "boot"); } List<String> classpathEntries = new ArrayList<String>(); File[] files = mavenHomeBootAsFile.listFiles(); if (files != null) { for (File file : files) { if (file.getName().contains("classworlds")) { classpathEntries.add(file.getAbsolutePath()); } } } return classpathEntries; } private static void encodeCoreAndRunnerSettings(MavenGeneralSettings coreSettings, String mavenHome, ParametersList cmdList) { if (coreSettings.isWorkOffline()) { cmdList.add("--offline"); } boolean atLeastMaven3 = MavenUtil.isMaven3(mavenHome); if (!atLeastMaven3) { addIfNotEmpty(cmdList, coreSettings.getPluginUpdatePolicy().getCommandLineOption()); if (!coreSettings.isUsePluginRegistry()) { cmdList.add("--no-plugin-registry"); } } if (coreSettings.getOutputLevel() == MavenExecutionOptions.LoggingLevel.DEBUG) { cmdList.add("--debug"); } if (coreSettings.isNonRecursive()) { cmdList.add("--non-recursive"); } if (coreSettings.isPrintErrorStackTraces()) { cmdList.add("--errors"); } if (coreSettings.isAlwaysUpdateSnapshots()) { cmdList.add("--update-snapshots"); } if (StringUtil.isNotEmpty(coreSettings.getThreads())) { cmdList.add("-T", coreSettings.getThreads()); } addIfNotEmpty(cmdList, coreSettings.getFailureBehavior().getCommandLineOption()); addIfNotEmpty(cmdList, coreSettings.getChecksumPolicy().getCommandLineOption()); addOption(cmdList, "s", coreSettings.getUserSettingsFile()); if (!StringUtil.isEmptyOrSpaces(coreSettings.getLocalRepository())) { cmdList.addProperty("maven.repo.local", coreSettings.getLocalRepository()); } } private static void addIfNotEmpty(ParametersList parametersList, @Nullable String value) { if (!StringUtil.isEmptyOrSpaces(value)) { parametersList.add(value); } } private static String encodeProfiles(Map<String, Boolean> profiles) { StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry<String, Boolean> entry : profiles.entrySet()) { if (stringBuilder.length() != 0) { stringBuilder.append(","); } if (!entry.getValue()) { stringBuilder.append("!"); } stringBuilder.append(entry.getKey()); } return stringBuilder.toString(); } private static class ProjectSettingsOpenerExecutionException extends ExecutionException implements HyperlinkListener { private final Project myProject; public ProjectSettingsOpenerExecutionException(final String s, Project project) { super(s); myProject = project; } @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; ShowSettingsUtil.getInstance().showSettingsDialog(myProject, MavenSettings.DISPLAY_NAME); } } private static class ProjectJdkSettingsOpenerExecutionException extends ExecutionException implements HyperlinkListener { private final Project myProject; public ProjectJdkSettingsOpenerExecutionException(final String s, Project project) { super(s); myProject = project; } @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; ProjectSettingsService.getInstance(myProject).openProjectSettings(); } } private static class RunConfigurationOpenerExecutionException extends ExecutionException implements HyperlinkListener { private final MavenRunConfiguration myRunConfiguration; public RunConfigurationOpenerExecutionException(final String s, MavenRunConfiguration runConfiguration) { super(s); myRunConfiguration = runConfiguration; } @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; Project project = myRunConfiguration.getProject(); //RunManagerImpl runManager = (RunManagerImpl)RunManager.getInstance(project); //RunnerAndConfigurationSettings settings = runManager.getSettings(myRunConfiguration); //if (settings == null) { // return; //} // //runManager.setSelectedConfiguration(settings); EditConfigurationsDialog dialog = new EditConfigurationsDialog(project); dialog.show(); } } }
IDEA-123851 Link in Event Log seems to be not working correctly
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java
IDEA-123851 Link in Event Log seems to be not working correctly
<ide><path>lugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java <ide> import com.intellij.execution.configurations.ParametersList; <ide> import com.intellij.execution.impl.EditConfigurationsDialog; <ide> import com.intellij.execution.impl.RunManagerImpl; <add>import com.intellij.notification.Notification; <add>import com.intellij.notification.NotificationListener; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.application.PathManager; <ide> import com.intellij.openapi.diagnostic.Logger; <ide> return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); <ide> } <ide> <del> throw new ProjectJdkSettingsOpenerExecutionException("Project JDK is not specified. <a href='#'>Configure</a>", project); <add> throw new ProjectJdkSettingsOpenerExecutionException("Project JDK is not specified. <a href=''>Configure</a>", project); <ide> } <ide> <ide> if (name.equals(MavenRunnerSettings.USE_JAVA_HOME)) { <ide> return stringBuilder.toString(); <ide> } <ide> <del> private static class ProjectSettingsOpenerExecutionException extends ExecutionException implements HyperlinkListener { <add> private static class ProjectSettingsOpenerExecutionException extends ExecutionExceptionWithHyperlink { <ide> <ide> private final Project myProject; <ide> <ide> } <ide> <ide> @Override <del> public void hyperlinkUpdate(HyperlinkEvent e) { <del> if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; <del> <add> protected void hyperlinkClicked() { <ide> ShowSettingsUtil.getInstance().showSettingsDialog(myProject, MavenSettings.DISPLAY_NAME); <ide> } <ide> } <ide> <del> private static class ProjectJdkSettingsOpenerExecutionException extends ExecutionException implements HyperlinkListener { <add> private static class ProjectJdkSettingsOpenerExecutionException extends ExecutionExceptionWithHyperlink { <ide> <ide> private final Project myProject; <ide> <ide> } <ide> <ide> @Override <del> public void hyperlinkUpdate(HyperlinkEvent e) { <del> if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; <del> <add> protected void hyperlinkClicked() { <ide> ProjectSettingsService.getInstance(myProject).openProjectSettings(); <ide> } <ide> } <ide> <del> private static class RunConfigurationOpenerExecutionException extends ExecutionException implements HyperlinkListener { <add> private static class RunConfigurationOpenerExecutionException extends ExecutionExceptionWithHyperlink { <ide> <ide> private final MavenRunConfiguration myRunConfiguration; <ide> <ide> } <ide> <ide> @Override <del> public void hyperlinkUpdate(HyperlinkEvent e) { <del> if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; <del> <add> protected void hyperlinkClicked() { <ide> Project project = myRunConfiguration.getProject(); <del> //RunManagerImpl runManager = (RunManagerImpl)RunManager.getInstance(project); <del> //RunnerAndConfigurationSettings settings = runManager.getSettings(myRunConfiguration); <del> //if (settings == null) { <del> // return; <del> //} <del> // <del> //runManager.setSelectedConfiguration(settings); <del> <ide> EditConfigurationsDialog dialog = new EditConfigurationsDialog(project); <ide> dialog.show(); <ide> } <ide> } <add> <add> private static abstract class ExecutionExceptionWithHyperlink extends ExecutionException implements HyperlinkListener, NotificationListener { <add> <add> public ExecutionExceptionWithHyperlink(String s) { <add> super(s); <add> } <add> <add> protected abstract void hyperlinkClicked(); <add> <add> @Override <add> public final void hyperlinkUpdate(HyperlinkEvent e) { <add> if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { <add> hyperlinkClicked(); <add> } <add> } <add> <add> @Override <add> public final void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { <add> hyperlinkUpdate(event); <add> } <add> } <ide> }
Java
apache-2.0
de4b218bf4130111109d2b273e29df89ed69fd90
0
sdinot/hipparchus,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,sdinot/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,Hipparchus-Math/hipparchus
/* * Licensed to the Hipparchus project under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Hipparchus project licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hipparchus.analysis.interpolation; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import org.hipparchus.exception.LocalizedCoreFormats; import org.hipparchus.exception.MathIllegalArgumentException; import org.hipparchus.util.FastMath; import org.hipparchus.util.MathArrays; /** * Helper for finding interpolation nodes along one axis of grid data. * <p> * This class is intended to be used for interpolating inside grids. * It works on any sorted data without duplication and size at least * {@code n} where {@code n} is the number of points required for * interpolation (i.e. 2 for linear interpolation, 3 for quadratic...) * <p> * </p> * The method uses linear interpolation to select the nodes indices. * It should be O(1) for sufficiently regular data, therefore much faster * than bisection. It also features caching, which improves speed when * interpolating several points in raw in the close locations, i.e. when * successive calls have a high probability to return the same interpolation * nodes. This occurs for example when scanning with small steps a loose * grid. The method also works on non-regular grids, but may be slower in * this case. * </p> * <p> * This class is thread-safe. * </p> * @since 1.4 */ public class GridAxis implements Serializable { /** Serializable UID. */ private static final long serialVersionUID = 20180926L; /** All the coordinates of the interpolation points, sorted in increasing order. */ private final double[] grid; /** Number of points required for interpolation. */ private int n; /** Cached value of last x index. */ private final AtomicInteger cache; /** Simple constructor. * @param grid coordinates of the interpolation points, sorted in increasing order * @param n number of points required for interpolation, i.e. 2 for linear, 3 * for quadratic... * @exception MathIllegalArgumentException if grid size is smaller than {@code n} * or if the grid is not sorted in strict increasing order */ public GridAxis(final double[] grid, final int n) throws MathIllegalArgumentException { // safety checks if (grid.length < n) { throw new MathIllegalArgumentException(LocalizedCoreFormats.INSUFFICIENT_DIMENSION, grid.length, n); } MathArrays.checkOrder(grid); this.grid = grid.clone(); this.n = n; this.cache = new AtomicInteger(0); } /** Get the number of points of the grid. * @return number of points of the grid */ public int size() { return grid.length; } /** Get the number of points required for interpolation. * @return number of points required for interpolation */ public int getN() { return n; } /** Get the interpolation node at specified index. * @param index node index * @return coordinate of the node at specified index */ public double node(final int index) { return grid[index]; } /** Get the index of the first interpolation node for some coordinate along the grid. * <p> * The index return is the one for the lowest interpolation node suitable for * {@code t}. This means that if {@code i} is returned the nodes to use for * interpolation at coordinate {@code t} are at indices {@code i}, {@code i+1}, * ..., {@code i+n-1}, where {@code n} is the number of points required for * interpolation passed at construction. * </p> * <p> * The index is selected in order to have the subset of nodes from {@code i} to * {@code i+n-1} as balanced as possible around {@code t}: * </p> * <ul> * <li> * if {@code t} is inside the grid and sufficiently far from the endpoints * <ul> * <li> * if {@code n} is even, the returned nodes will be perfectly balanced: * there will be {@code n/2} nodes smaller than {@code t} and {@code n/2} * nodes larger than {@code t} * </li> * <li> * if {@code n} is odd, the returned nodes will be slightly unbalanced by * one point: there will be {@code (n+1)/2} nodes smaller than {@code t} * and {@code (n-1)/2} nodes larger than {@code t} * </li> * </ul> * </li> * <li> * if {@code t} is inside the grid and close to endpoints, the returned nodes * will be unbalanced: there will be less nodes on the endpoints side and * more nodes on the interior side * </li> * <li> * if {@code t} is outside of the grid, the returned nodes will completely * off balance: all nodes will be on the same side with respect to {@code t} * </li> * </ul> * <p> * It is <em>not</em> an error to call this method with {@code t} outside of the grid, * it simply implies that the interpolation will become an extrapolation and accuracy * will decrease as {@code t} goes farther from the grid points. This is intended so * interpolation does not fail near the end of the grid. * </p> * @param t coordinate of the point to interpolate * @return index {@code i} such {@link #node(int) node(i)}, {@link #node(int) node(i+1)}, * ... {@link #node(int) node(i+n-1)} can be used for interpolating a value at * coordinate {@code t} * @since 1.4 */ public int interpolationIndex(final double t) { final int middleOffset = (n - 1) / 2; int iInf = middleOffset; int iSup = grid.length - (n - 1) + middleOffset; // first try to simply reuse the cached index, // for faster return in a common case final int cached = cache.get(); final int middle = cached + middleOffset; final double aMid0 = grid[middle]; final double aMid1 = grid[middle + 1]; if (t < aMid0) { if (middle == iInf) { // we are in the unbalanced low area return cached; } } else if (t < aMid1) { // we are in the balanced middle area return cached; } else { if (middle == iSup - 1) { // we are in the unbalanced high area return cached; } } // we need to find a new index double aInf = grid[iInf]; double aSup = grid[iSup]; while (iSup - iInf > 1) { final int iInterp = (int) ((iInf * (aSup - t) + iSup * (t - aInf)) / (aSup - aInf)); final int iMed = FastMath.max(iInf + 1, FastMath.min(iInterp, iSup - 1)); if (t < grid[iMed]) { // keeps looking in the lower part of the grid iSup = iMed; aSup = grid[iSup]; } else { // keeps looking in the upper part of the grid iInf = iMed; aInf = grid[iInf]; } } final int newCached = iInf - middleOffset; cache.compareAndSet(cached, newCached); return newCached; } }
hipparchus-core/src/main/java/org/hipparchus/analysis/interpolation/GridAxis.java
/* * Licensed to the Hipparchus project under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Hipparchus project licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hipparchus.analysis.interpolation; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import org.hipparchus.exception.LocalizedCoreFormats; import org.hipparchus.exception.MathIllegalArgumentException; import org.hipparchus.util.FastMath; import org.hipparchus.util.MathArrays; /** * Helper for finding interpolation nodes along one axis of grid data. * <p> * This class is intended to be used for interpolating inside grids. * It works on any sorted data without duplication and size at least * {@code n} where {@code n} is the number of points required for * interpolation (i.e. 2 for linear interpolation, 3 for quadratic...) * <p> * </p> * The method uses linear interpolation to select the nodes indices. * It should be O(1) for sufficiently regular data, therefore much faster * than bisection. It also features caching, which improves speed when * interpolating several points in raw in the close locations, i.e. when * successive calls have a high probability to return the same interpolation * nodes. This occurs for example when scanning with small steps a loose * grid. The method also works on non-regular grids, but may be slower in * this case. * </p> * <p> * This class is thread-safe. * </p> * @since 1.4 */ public class GridAxis implements Serializable { /** Serializable UID. */ private static final long serialVersionUID = 20180926L; /** All the coordinates of the interpolation points, sorted in increasing order. */ private final double[] grid; /** Number of points required for interpolation. */ private int n; /** Cached value of last x index. */ private final AtomicInteger cache; /** Simple constructor. * @param grid coordinates of the interpolation points, sorted in increasing order * @param n number of points required for interpolation, i.e. 2 for linear, 3 * for quadratic... * @exception MathIllegalArgumentException if grid size is smaller than {@code n} * or if the grid is not sorted in strict increasing order */ public GridAxis(final double[] grid, final int n) throws MathIllegalArgumentException { // safety checks if (grid.length < n) { throw new MathIllegalArgumentException(LocalizedCoreFormats.INSUFFICIENT_DIMENSION, grid.length, n); } MathArrays.checkOrder(grid); this.grid = grid.clone(); this.n = n; this.cache = new AtomicInteger(0); } /** Get the number of points of the grid. * @return number of points of the grid */ public int size() { return grid.length; } /** Get the number of points required for interpolation. * @return number of points required for interpolation */ public int getN() { return n; } /** Get the interpolation node at specified index. * @param index node index * @return coordinate of the node at specified index */ public double node(final int index) { return grid[index]; } /** Get the index of the first interpolation node for some coordinate along the grid. * <p> * The index return is the one for the lowest interpolation node suitable for * {@code t}. This means that if {@code i} is returned the nodes to use for * interpolation at coordinate {@code t} are at indices {@code i}, {@code i+1}, * ..., {@code i+n-1}, where {@code n} is the number of points required for * interpolation passed at construction. * </p> * <p> * The index is selected in order to have the subset of nodes from {@code i} to * {@code i+n-1} as balanced as possible around {@code t}: * </p> * <ul> * <li> * if {@code t} is inside the grid and sufficiently far from the endpoints * <ul> * <li> * if {@code n} is even, the returned nodes will be perfectly balanced: * there will be {@code n/2} nodes smaller than {@code t} and {@code n/2} * nodes larger than {@code t} * </li> * <li> * if {@code n} is odd, the returned nodes will be slightly unbalanced by * one point: there will be {@code (n+1)/2} nodes smaller than {@code t} * and {@code (n-1)/2} nodes larger than {@code t} * </li> * </ul> * </li> * <li> * if {@code t} is inside the grid and close to endpoints, the returned nodes * will be unbalanced: there will be less nodes on the endpoints side and * more nodes on the interior side * </li> * <li> * if {@code t} is outside of the grid, the returned nodes will completely * off balance: all nodes will be on the same side with respect to {@code t} * </li> * </ul> * <p> * It is <em>not</em> an error to call this method with {@code t} outside of the grid, * it simply implies that the interpolation will become an extrapolation and accuracy * will decrease as {@code t} goes farther from the grid points. This is intended so * interpolation does not fail near the end of the grid. * </p> * @param t coordinate of the point to interpolate * @return index {@code i} such {@link #node(int) node(i)}, {@link #node(int) node(i+1)}, * ... {@link #node(int) node(i+n-1)} can be used for interpolating a value at * coordinate {@code t} * @since 1.4 */ public int interpolationIndex(final double t) { final int middleOffset = (n - 1) / 2; int iInf = middleOffset; int iSup = grid.length - (n - 1) + middleOffset; // first try to simply reuse the cached index, // for faster return in a common case final int cached = cache.get(); final int middle = cached + middleOffset; final double aMid0 = grid[middle]; final double aMid1 = grid[middle + 1]; if (t < aMid0) { // we are in the unbalanced low area if (middle == iInf) { return cached; } } else if (t < aMid1) { // we are in the balanced middle area return cached; } else { // we are in the unbalanced high area if (middle == iSup - 1) { return cached; } } // we need to find a new index double aInf = grid[iInf]; double aSup = grid[iSup]; while (iSup - iInf > 1) { final int iInterp = (int) ((iInf * (aSup - t) + iSup * (t - aInf)) / (aSup - aInf)); final int iMed = FastMath.max(iInf + 1, FastMath.min(iInterp, iSup - 1)); if (t < grid[iMed]) { // keeps looking in the lower part of the grid iSup = iMed; aSup = grid[iSup]; } else { // keeps looking in the upper part of the grid iInf = iMed; aInf = grid[iInf]; } } final int newCached = iInf - middleOffset; cache.compareAndSet(cached, newCached); return newCached; } }
Fixed comments.
hipparchus-core/src/main/java/org/hipparchus/analysis/interpolation/GridAxis.java
Fixed comments.
<ide><path>ipparchus-core/src/main/java/org/hipparchus/analysis/interpolation/GridAxis.java <ide> final double aMid0 = grid[middle]; <ide> final double aMid1 = grid[middle + 1]; <ide> if (t < aMid0) { <del> // we are in the unbalanced low area <ide> if (middle == iInf) { <add> // we are in the unbalanced low area <ide> return cached; <ide> } <ide> } else if (t < aMid1) { <ide> // we are in the balanced middle area <ide> return cached; <ide> } else { <del> // we are in the unbalanced high area <ide> if (middle == iSup - 1) { <add> // we are in the unbalanced high area <ide> return cached; <ide> } <ide> }
Java
apache-2.0
337cc29de15f4d6aa51e04ca121956a9052a7b18
0
dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia
package org.wikipedia.search; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.wikipedia.Constants.InvokeSource; import org.wikipedia.WikipediaApp; import org.wikipedia.activity.SingleFragmentActivity; import org.wikipedia.analytics.IntentFunnel; import static org.wikipedia.Constants.INTENT_EXTRA_INVOKE_SOURCE; import static org.wikipedia.Constants.InvokeSource.WIDGET; public class SearchActivity extends SingleFragmentActivity<SearchFragment> { static final String QUERY_EXTRA = "query"; public static Intent newIntent(@NonNull Context context, InvokeSource source, @Nullable String query) { if (source == WIDGET) { new IntentFunnel(WikipediaApp.getInstance()).logSearchWidgetTap(); } return new Intent(context, SearchActivity.class) .putExtra(INTENT_EXTRA_INVOKE_SOURCE, source) .putExtra(QUERY_EXTRA, query); } @Override public SearchFragment createFragment() { return SearchFragment.newInstance((InvokeSource) getIntent().getSerializableExtra(INTENT_EXTRA_INVOKE_SOURCE), getIntent().getStringExtra(QUERY_EXTRA)); } }
app/src/main/java/org/wikipedia/search/SearchActivity.java
package org.wikipedia.search; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.wikipedia.Constants.InvokeSource; import org.wikipedia.WikipediaApp; import org.wikipedia.activity.SingleFragmentActivity; import org.wikipedia.analytics.IntentFunnel; import static org.wikipedia.Constants.INTENT_EXTRA_INVOKE_SOURCE; import static org.wikipedia.Constants.InvokeSource.WIDGET; public class SearchActivity extends SingleFragmentActivity<SearchFragment> { static final String QUERY_EXTRA = "query"; public static Intent newIntent(@NonNull Context context, InvokeSource source, @Nullable String query) { if (source == WIDGET) { new IntentFunnel(WikipediaApp.getInstance()).logSearchWidgetTap(); } // We use the ordinal() for passing the INVOKE_SOURCE into the intent because this intent // could be used as part of an App Shortcut, and unfortunately app shortcuts do not allow // Serializable objects in their intents. return new Intent(context, SearchActivity.class) .putExtra(INTENT_EXTRA_INVOKE_SOURCE, source.ordinal()) .putExtra(QUERY_EXTRA, query); } @Override public SearchFragment createFragment() { return SearchFragment.newInstance(InvokeSource.values()[getIntent().getIntExtra(INTENT_EXTRA_INVOKE_SOURCE, InvokeSource.TOOLBAR.ordinal())], getIntent().getStringExtra(QUERY_EXTRA)); } }
Undo ordinal conversion, since this is now a static shortcut. Change-Id: Ia5275052e4dbeef4c9379e8ba103c08a095e9075
app/src/main/java/org/wikipedia/search/SearchActivity.java
Undo ordinal conversion, since this is now a static shortcut.
<ide><path>pp/src/main/java/org/wikipedia/search/SearchActivity.java <ide> new IntentFunnel(WikipediaApp.getInstance()).logSearchWidgetTap(); <ide> } <ide> <del> // We use the ordinal() for passing the INVOKE_SOURCE into the intent because this intent <del> // could be used as part of an App Shortcut, and unfortunately app shortcuts do not allow <del> // Serializable objects in their intents. <ide> return new Intent(context, SearchActivity.class) <del> .putExtra(INTENT_EXTRA_INVOKE_SOURCE, source.ordinal()) <add> .putExtra(INTENT_EXTRA_INVOKE_SOURCE, source) <ide> .putExtra(QUERY_EXTRA, query); <ide> } <ide> <ide> @Override <ide> public SearchFragment createFragment() { <del> return SearchFragment.newInstance(InvokeSource.values()[getIntent().getIntExtra(INTENT_EXTRA_INVOKE_SOURCE, InvokeSource.TOOLBAR.ordinal())], <add> return SearchFragment.newInstance((InvokeSource) getIntent().getSerializableExtra(INTENT_EXTRA_INVOKE_SOURCE), <ide> getIntent().getStringExtra(QUERY_EXTRA)); <ide> } <ide> }
Java
apache-2.0
c7c03f2816355138ada8e26cbe7d7fee9d0e059e
0
antag99/artemis-odb,DaanVanYperen/artemis-odb,gjroelofs/artemis-odb,gjroelofs/artemis-odb,gjroelofs/artemis-odb,Namek/artemis-odb,snorrees/artemis-odb,snorrees/artemis-odb,antag99/artemis-odb
package com.artemis; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.BitSet; import java.util.UUID; import com.artemis.utils.Bag; /** * EntityManager. * * @author Arni Arent */ public class EntityManager extends Manager { /** Contains all entities in the manager. */ private final Bag<Entity> entities; /** Stores the bits of all currently disabled entities IDs. */ private final BitSet disabled; /** Amount of currently active (added to the world) entities. */ private int active; /** Amount of entities ever added to the manager. */ private long added; /** Amount of entites ever created by the manager. */ private long created; /** Amount of entities ever deleted from the manager. */ private long deleted; private RecyclingEntityFactory recyclingEntityFactory; /** * Creates a new EntityManager Instance. */ public EntityManager() { entities = new Bag<Entity>(); disabled = new BitSet(); } @Override protected void initialize() { recyclingEntityFactory = new RecyclingEntityFactory(world); } /** * Create a new entity. * <p> * New entities will recieve a free ID from a global pool, ensuring * every entity has a unique ID. Deleted entities free their ID for new * entities. * </p> * * @return a new entity */ protected Entity createEntityInstance() { Entity e = recyclingEntityFactory.obtain(); created++; return e; } /** * Create a new entity. * <p> * New entities will receive a free ID from a global pool, ensuring * every entity has a unique ID. Deleted entities free their ID for new * entities. * </p> * * @param uuid * the UUID to give to the entity * * @return a new entity */ protected Entity createEntityInstance(UUID uuid) { Entity e = createEntityInstance(); e.setUuid(uuid); return e; } /** * Adds the entity to this manager. * <p> * Called by the world when an entity is added. * </p> * * @param e * the entity to add */ @Override public void added(Entity e) { active++; added++; entities.set(e.getId(), e); } /** * Sets the entity (re)enabled in the manager. * * @param e * the entity to (re)enable */ @Override public void enabled(Entity e) { disabled.clear(e.getId()); } /** * Sets the entity as disabled in the manager. * * @param e * the entity to disable */ @Override public void disabled(Entity e) { disabled.set(e.getId()); } /** * Removes the entity from the manager, freeing it's id for new entities. * * @param e * the entity to remove */ @Override public void deleted(Entity e) { entities.set(e.getId(), null); disabled.clear(e.getId()); recyclingEntityFactory.free(e); active--; deleted++; } /** * Check if this entity is active. * <p> * Active means the entity is being actively processed. * </p> * * @param entityId * the entities id * * @return true if active, false if not */ public boolean isActive(int entityId) { return entities.get(entityId) != null; } /** * Check if the specified entityId is enabled. * * @param entityId * the entities id * * @return true if the entity is enabled, false if it is disabled */ public boolean isEnabled(int entityId) { return !disabled.get(entityId); } /** * Get a entity with this id. * * @param entityId * the entities id * * @return the entity */ protected Entity getEntity(int entityId) { return entities.get(entityId); } /** * Get how many entities are active in this world. * * @return how many entities are currently active */ public int getActiveEntityCount() { return active; } /** * Get how many entities have been created in the world since start. * <p> * Note: A created entity may not have been added to the world, thus * created count is always equal or larger than added count. * </p> * * @return how many entities have been created since start */ public long getTotalCreated() { return created; } /** * Get how many entities have been added to the world since start. * * @return how many entities have been added */ public long getTotalAdded() { return added; } /** * Get how many entities have been deleted from the world since start. * * @return how many entities have been deleted since start */ public long getTotalDeleted() { return deleted; } private static final class RecyclingEntityFactory { private final Bag<Entity> recycled; private int nextId; private Constructor<Entity> constructor; private Object[] args; RecyclingEntityFactory(World world) { recycled = new Bag<Entity>(); args = new Object[]{world, 0}; try { constructor = Entity.class.getDeclaredConstructor(World.class, int.class); constructor.setAccessible(true); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } void free(Entity e) { e.reset(); recycled.add(e); } Entity obtain() { if (recycled.isEmpty()) { try { args[1] = nextId++; return constructor.newInstance(args); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } else { return recycled.removeLast(); } } } }
src/main/java/com/artemis/EntityManager.java
package com.artemis; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.BitSet; import java.util.UUID; import com.artemis.utils.Bag; /** * EntityManager. * * @author Arni Arent */ public class EntityManager extends Manager { /** Contains all entities in the manager. */ private final Bag<Entity> entities; /** Stores the bits of all currently disabled entities IDs. */ private final BitSet disabled; /** Amount of currently active (added to the world) entities. */ private int active; /** Amount of entities ever added to the manager. */ private long added; /** Amount of entites ever created by the manager. */ private long created; /** Amount of entities ever deleted from the manager. */ private long deleted; private RecyclingEntityFactory recyclingEntityFactory; /** * Creates a new EntityManager Instance. */ public EntityManager() { entities = new Bag<Entity>(); disabled = new BitSet(); } @Override protected void initialize() { recyclingEntityFactory = new RecyclingEntityFactory(world); } /** * Create a new entity. * <p> * New entities will recieve a free ID from a global pool, ensuring * every entity has a unique ID. Deleted entities free their ID for new * entities. * </p> * * @return a new entity */ protected Entity createEntityInstance() { Entity e = recyclingEntityFactory.obtain(); created++; return e; } /** * Create a new entity. * <p> * New entities will receive a free ID from a global pool, ensuring * every entity has a unique ID. Deleted entities free their ID for new * entities. * </p> * * @param uuid * the UUID to give to the entity * * @return a new entity */ protected Entity createEntityInstance(UUID uuid) { Entity e = createEntityInstance(); e.setUuid(uuid); return e; } /** * Adds the entity to this manager. * <p> * Called by the world when an entity is added. * </p> * * @param e * the entity to add */ @Override public void added(Entity e) { active++; added++; entities.set(e.getId(), e); } /** * Sets the entity (re)enabled in the manager. * * @param e * the entity to (re)enable */ @Override public void enabled(Entity e) { disabled.clear(e.getId()); } /** * Sets the entity as disabled in the manager. * * @param e * the entity to disable */ @Override public void disabled(Entity e) { disabled.set(e.getId()); } /** * Removes the entity from the manager, freeing it's id for new entities. * * @param e * the entity to remove */ @Override public void deleted(Entity e) { entities.set(e.getId(), null); disabled.clear(e.getId()); recyclingEntityFactory.free(e); active--; deleted++; } /** * Check if this entity is active. * <p> * Active means the entity is being actively processed. * </p> * * @param entityId * the entities id * * @return true if active, false if not */ public boolean isActive(int entityId) { return entities.get(entityId) != null; } /** * Check if the specified entityId is enabled. * * @param entityId * the entities id * * @return true if the entity is enabled, false if it is disabled */ public boolean isEnabled(int entityId) { return !disabled.get(entityId); } /** * Get a entity with this id. * * @param entityId * the entities id * * @return the entity */ protected Entity getEntity(int entityId) { return entities.get(entityId); } /** * Get how many entities are active in this world. * * @return how many entities are currently active */ public int getActiveEntityCount() { return active; } /** * Get how many entities have been created in the world since start. * <p> * Note: A created entity may not have been added to the world, thus * created count is always equal or larger than added count. * </p> * * @return how many entities have been created since start */ public long getTotalCreated() { return created; } /** * Get how many entities have been added to the world since start. * * @return how many entities have been added */ public long getTotalAdded() { return added; } /** * Get how many entities have been deleted from the world since start. * * @return how many entities have been deleted since start */ public long getTotalDeleted() { return deleted; } private static final class RecyclingEntityFactory { private final Bag<Entity> recycled; private int nextId; private Constructor<Entity> constructor; private Object[] args; RecyclingEntityFactory(World world) { recycled = new Bag<Entity>(); args = new Object[]{world, 0}; try { constructor = Entity.class.getDeclaredConstructor(World.class, int.class); constructor.setAccessible(true); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } void free(Entity e) { recycled.add(e); } Entity obtain() { if (recycled.isEmpty()) { try { args[1] = nextId++; return constructor.newInstance(args); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } else { return recycled.removeLast(); } } } }
reset entity when inserting into the pool
src/main/java/com/artemis/EntityManager.java
reset entity when inserting into the pool
<ide><path>rc/main/java/com/artemis/EntityManager.java <ide> } <ide> <ide> void free(Entity e) { <add> e.reset(); <ide> recycled.add(e); <ide> } <ide>
Java
bsd-3-clause
a068dcbaced1233ec872d77c655b0985297ccc89
0
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
package org.hisp.dhis.android.core.program; import android.content.ContentValues; import android.database.MatrixCursor; import android.support.test.runner.AndroidJUnit4; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.hisp.dhis.android.core.program.ProgramContract.Columns; import org.junit.Test; import org.junit.runner.RunWith; import java.text.ParseException; import java.util.Date; import static com.google.common.truth.Truth.assertThat; @RunWith(AndroidJUnit4.class) public class ProgramModelIntegrationTest { //BaseIdentifiableModel attributes: private static final long ID = 11L; private static final String UID = "test_uid"; private static final String CODE = "test_code"; private static final String NAME = "test_name"; private static final String DISPLAY_NAME = "test_display_name"; // timestamp private static final String DATE = "2014-03-20T13:37:00.007"; //BaseNameableModel attributes: private static final String SHORT_NAME = "test_program"; private static final String DISPLAY_SHORT_NAME = "test_prog"; private static final String DESCRIPTION = "A test program for the integration tests."; private static final String DISPLAY_DESCRIPTION = "A test program for the integration tests."; //ProgramModel attributes: private static final Integer VERSION = 1; private static final Integer ONLY_ENROLL_ONCE = 1; private static final String ENROLLMENT_DATE_LABEL = "enrollment date"; private static final Integer DISPLAY_INCIDENT_DATE = 1; private static final String INCIDENT_DATE_LABEL = "incident date label"; private static final Integer REGISTRATION = 1; private static final Integer SELECT_ENROLLMENT_DATES_IN_FUTURE = 1; private static final Integer DATA_ENTRY_METHOD = 1; private static final Integer IGNORE_OVERDUE_EVENTS = 0; private static final Integer RELATIONSHIP_FROM_A = 1; private static final Integer SELECT_INCIDENT_DATES_IN_FUTURE = 1; private static final Integer CAPTURE_COORDINATES = 1; private static final Integer USE_FIRST_STAGE_DURING_REGISTRATION = 1; private static final Integer DISPLAY_FRONT_PAGE_LIST = 1; private static final ProgramType PROGRAM_TYPE = ProgramType.WITH_REGISTRATION; private static final String RELATIONSHIP_TYPE = "relationshipUid"; private static final String RELATIONSHIP_TEXT = "test relationship"; private static final String RELATED_PROGRAM = "ProgramUid"; /** * A method to create ContentValues for a Program. * To be used by other tests. * * @param id * @param uid * @return */ public static ContentValues create(long id, String uid) { ContentValues program = new ContentValues(); program.put(Columns.ID, id); program.put(Columns.UID, uid); program.put(Columns.CODE, CODE); program.put(Columns.NAME, NAME); program.put(Columns.DISPLAY_NAME, DISPLAY_NAME); program.put(Columns.CREATED, DATE); program.put(Columns.LAST_UPDATED, DATE); program.put(Columns.SHORT_NAME, SHORT_NAME); program.put(Columns.DISPLAY_SHORT_NAME, DISPLAY_SHORT_NAME); program.put(Columns.DESCRIPTION, DESCRIPTION); program.put(Columns.DISPLAY_DESCRIPTION, DISPLAY_DESCRIPTION); program.put(Columns.VERSION, VERSION); program.put(Columns.ONLY_ENROLL_ONCE, ONLY_ENROLL_ONCE); program.put(Columns.ENROLLMENT_DATE_LABEL, ENROLLMENT_DATE_LABEL); program.put(Columns.DISPLAY_INCIDENT_DATE, DISPLAY_INCIDENT_DATE); program.put(Columns.INCIDENT_DATE_LABEL, INCIDENT_DATE_LABEL); program.put(Columns.REGISTRATION, REGISTRATION); program.put(Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE, SELECT_ENROLLMENT_DATES_IN_FUTURE); program.put(Columns.DATA_ENTRY_METHOD, DATA_ENTRY_METHOD); program.put(Columns.IGNORE_OVERDUE_EVENTS, IGNORE_OVERDUE_EVENTS); program.put(Columns.RELATIONSHIP_FROM_A, RELATIONSHIP_FROM_A); program.put(Columns.SELECT_INCIDENT_DATES_IN_FUTURE, SELECT_INCIDENT_DATES_IN_FUTURE); program.put(Columns.CAPTURE_COORDINATES, CAPTURE_COORDINATES); program.put(Columns.USE_FIRST_STAGE_DURING_REGISTRATION, USE_FIRST_STAGE_DURING_REGISTRATION); program.put(Columns.DISPLAY_FRONT_PAGE_LIST, DISPLAY_FRONT_PAGE_LIST); program.put(Columns.PROGRAM_TYPE, PROGRAM_TYPE.name()); program.put(Columns.RELATIONSHIP_TYPE, RELATIONSHIP_TYPE); program.put(Columns.RELATIONSHIP_TEXT, RELATIONSHIP_TEXT); program.put(Columns.RELATED_PROGRAM, RELATED_PROGRAM); return program; } @Test public void create_shouldConvertToModel() throws ParseException { MatrixCursor matrixCursor = new MatrixCursor(new String[]{ Columns.ID, Columns.UID, Columns.CODE, Columns.NAME, Columns.DISPLAY_NAME, Columns.CREATED, Columns.LAST_UPDATED, Columns.SHORT_NAME, Columns.DISPLAY_SHORT_NAME, Columns.DESCRIPTION, Columns.DISPLAY_DESCRIPTION, Columns.VERSION, Columns.ONLY_ENROLL_ONCE, Columns.ENROLLMENT_DATE_LABEL, Columns.DISPLAY_INCIDENT_DATE, Columns.INCIDENT_DATE_LABEL, Columns.REGISTRATION, Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE, Columns.DATA_ENTRY_METHOD, Columns.IGNORE_OVERDUE_EVENTS, Columns.RELATIONSHIP_FROM_A, Columns.SELECT_INCIDENT_DATES_IN_FUTURE, Columns.CAPTURE_COORDINATES, Columns.USE_FIRST_STAGE_DURING_REGISTRATION, Columns.DISPLAY_FRONT_PAGE_LIST, Columns.PROGRAM_TYPE, Columns.RELATIONSHIP_TYPE, Columns.RELATIONSHIP_TEXT, Columns.RELATED_PROGRAM }); matrixCursor.addRow(new Object[]{ ID, UID, CODE, NAME, DISPLAY_NAME, DATE, DATE, SHORT_NAME, DISPLAY_SHORT_NAME, DESCRIPTION, DISPLAY_DESCRIPTION, VERSION, ONLY_ENROLL_ONCE, ENROLLMENT_DATE_LABEL, DISPLAY_INCIDENT_DATE, INCIDENT_DATE_LABEL, REGISTRATION, SELECT_ENROLLMENT_DATES_IN_FUTURE, DATA_ENTRY_METHOD, IGNORE_OVERDUE_EVENTS, RELATIONSHIP_FROM_A, SELECT_INCIDENT_DATES_IN_FUTURE, CAPTURE_COORDINATES, USE_FIRST_STAGE_DURING_REGISTRATION, DISPLAY_FRONT_PAGE_LIST, PROGRAM_TYPE, RELATIONSHIP_TYPE, RELATIONSHIP_TEXT, RELATED_PROGRAM }); // move cursor to first item before reading matrixCursor.moveToFirst(); Date timeStamp = BaseIdentifiableObject.DATE_FORMAT.parse(DATE); ProgramModel program = ProgramModel.create(matrixCursor); assertThat(program.id()).isEqualTo(ID); assertThat(program.uid()).isEqualTo(UID); assertThat(program.code()).isEqualTo(CODE); assertThat(program.name()).isEqualTo(NAME); assertThat(program.displayName()).isEqualTo(DISPLAY_NAME); assertThat(program.created()).isEqualTo(timeStamp); assertThat(program.lastUpdated()).isEqualTo(timeStamp); assertThat(program.shortName()).isEqualTo(SHORT_NAME); assertThat(program.displayShortName()).isEqualTo(DISPLAY_SHORT_NAME); assertThat(program.description()).isEqualTo(DESCRIPTION); assertThat(program.displayDescription()).isEqualTo(DISPLAY_DESCRIPTION); assertThat(program.version()).isEqualTo(VERSION); assertThat(program.onlyEnrollOnce()).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(program.enrollmentDateLabel()).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(program.displayIncidentDate()).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(program.incidentDateLabel()).isEqualTo(INCIDENT_DATE_LABEL); assertThat(program.registration()).isEqualTo(toBoolean(REGISTRATION)); assertThat(program.selectEnrollmentDatesInFuture()).isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(program.dataEntryMethod()).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(program.ignoreOverdueEvents()).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(program.relationshipFromA()).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(program.selectIncidentDatesInFuture()).isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(program.captureCoordinates()).isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(program.useFirstStageDuringRegistration()).isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(program.displayFrontPageList()).isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(program.programType()).isEqualTo(PROGRAM_TYPE); assertThat(program.relationshipType()).isEqualTo(RELATIONSHIP_TYPE); assertThat(program.relationshipText()).isEqualTo(RELATIONSHIP_TEXT); assertThat(program.relatedProgram()).isEqualTo(RELATED_PROGRAM); } @Test public void toContentValues_shouldConvertToContentValues() throws ParseException { Date timeStamp = BaseIdentifiableObject.DATE_FORMAT.parse(DATE); ProgramModel program = ProgramModel.builder() .id(ID) .uid(UID) .code(CODE) .name(NAME) .displayName(DISPLAY_NAME) .created(timeStamp) .lastUpdated(timeStamp) .shortName(SHORT_NAME) .displayShortName(DISPLAY_SHORT_NAME) .description(DESCRIPTION) .displayDescription(DISPLAY_DESCRIPTION) .version(VERSION) .onlyEnrollOnce(toBoolean(ONLY_ENROLL_ONCE)) .enrollmentDateLabel(ENROLLMENT_DATE_LABEL) .displayIncidentDate(toBoolean(DISPLAY_INCIDENT_DATE)) .registration(toBoolean(REGISTRATION)) .selectEnrollmentDatesInFuture(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)) .dataEntryMethod(toBoolean(DATA_ENTRY_METHOD)) .ignoreOverdueEvents(toBoolean(IGNORE_OVERDUE_EVENTS)) .relationshipFromA(toBoolean(RELATIONSHIP_FROM_A)) .selectIncidentDatesInFuture(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)) .captureCoordinates(toBoolean(CAPTURE_COORDINATES)) .useFirstStageDuringRegistration(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)) .displayFrontPageList(toBoolean(DISPLAY_FRONT_PAGE_LIST)) .programType(PROGRAM_TYPE) .relationshipType(RELATIONSHIP_TYPE) .relationshipText(RELATIONSHIP_TEXT) .relatedProgram(RELATED_PROGRAM) .build(); ContentValues contentValues = program.toContentValues(); assertThat(contentValues.getAsLong(Columns.ID)).isEqualTo(ID); assertThat(contentValues.getAsString(Columns.UID)).isEqualTo(UID); assertThat(contentValues.getAsString(Columns.NAME)).isEqualTo(NAME); assertThat(contentValues.getAsString(Columns.DISPLAY_NAME)).isEqualTo(DISPLAY_NAME); assertThat(contentValues.getAsString(Columns.CREATED)).isEqualTo(DATE); assertThat(contentValues.getAsString(Columns.LAST_UPDATED)).isEqualTo(DATE); assertThat(contentValues.getAsString(Columns.SHORT_NAME)).isEqualTo(SHORT_NAME); assertThat(contentValues.getAsString(Columns.DISPLAY_SHORT_NAME)).isEqualTo(DISPLAY_SHORT_NAME); assertThat(contentValues.getAsString(Columns.DESCRIPTION)).isEqualTo(DESCRIPTION); assertThat(contentValues.getAsString(Columns.DISPLAY_DESCRIPTION)).isEqualTo(DISPLAY_DESCRIPTION); assertThat(contentValues.getAsInteger(Columns.VERSION)).isEqualTo(VERSION); assertThat(contentValues.getAsBoolean(Columns.ONLY_ENROLL_ONCE)).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(contentValues.getAsString(Columns.ENROLLMENT_DATE_LABEL)).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(contentValues.getAsBoolean(Columns.DISPLAY_INCIDENT_DATE)).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(contentValues.getAsBoolean(Columns.REGISTRATION)).isEqualTo(toBoolean(REGISTRATION)); assertThat(contentValues.getAsBoolean(Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE)).isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean(Columns.DATA_ENTRY_METHOD)).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(contentValues.getAsBoolean(Columns.IGNORE_OVERDUE_EVENTS)).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(contentValues.getAsBoolean(Columns.RELATIONSHIP_FROM_A)).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(contentValues.getAsBoolean(Columns.SELECT_INCIDENT_DATES_IN_FUTURE)).isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean(Columns.CAPTURE_COORDINATES)).isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(contentValues.getAsBoolean(Columns.USE_FIRST_STAGE_DURING_REGISTRATION)).isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(contentValues.getAsBoolean(Columns.DISPLAY_FRONT_PAGE_LIST)).isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(contentValues.getAsString(Columns.PROGRAM_TYPE)).isEqualTo(PROGRAM_TYPE.toString()); assertThat(contentValues.getAsString(Columns.RELATIONSHIP_TYPE)).isEqualTo(RELATIONSHIP_TYPE); assertThat(contentValues.getAsString(Columns.RELATIONSHIP_TEXT)).isEqualTo(RELATIONSHIP_TEXT); assertThat(contentValues.getAsString(Columns.RELATED_PROGRAM)).isEqualTo(RELATED_PROGRAM); } /* A helper method to convert an integer to Boolean. 0 -> false, != 0 -> true*/ private Boolean toBoolean(Integer i) { return i != 0; } }
core/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramModelIntegrationTest.java
package org.hisp.dhis.android.core.program; import android.content.ContentValues; import android.database.MatrixCursor; import android.support.test.runner.AndroidJUnit4; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.hisp.dhis.android.core.program.ProgramContract.Columns; import org.junit.Test; import org.junit.runner.RunWith; import java.text.ParseException; import java.util.Date; import static com.google.common.truth.Truth.assertThat; @RunWith(AndroidJUnit4.class) public class ProgramModelIntegrationTest { //BaseIdentifiableModel attributes: private static final long ID = 11L; private static final String UID = "test_uid"; private static final String CODE = "test_code"; private static final String NAME = "test_name"; private static final String DISPLAY_NAME = "test_display_name"; // timestamp private static final String DATE = "2014-03-20T13:37:00.007"; //BaseNameableModel attributes: private static final String SHORT_NAME = "test_program"; private static final String DISPLAY_SHORT_NAME = "test_prog"; private static final String DESCRIPTION = "A test program for the integration tests."; private static final String DISPLAY_DESCRIPTION = "A test program for the integration tests."; //ProgramModel attributes: private static final Integer VERSION = 1; private static final Integer ONLY_ENROLL_ONCE = 1; private static final String ENROLLMENT_DATE_LABEL = "enrollment date"; private static final Integer DISPLAY_INCIDENT_DATE = 1; private static final String INCIDENT_DATE_LABEL = "incident date label"; private static final Integer REGISTRATION = 1; private static final Integer SELECT_ENROLLMENT_DATES_IN_FUTURE = 1; private static final Integer DATA_ENTRY_METHOD = 1; private static final Integer IGNORE_OVERDUE_EVENTS = 0; private static final Integer RELATIONSHIP_FROM_A = 1; private static final Integer SELECT_INCIDENT_DATES_IN_FUTURE = 1; private static final Integer CAPTURE_COORDINATES = 1; private static final Integer USE_FIRST_STAGE_DURING_REGISTRATION = 1; private static final Integer DISPLAY_FRONT_PAGE_LIST = 1; //TODO : TEST custom Types: private static final ProgramType PROGRAM_TYPE = ProgramType.WITH_REGISTRATION; private static final String RELATIONSHIP_TYPE = "relationshipUid"; private static final String RELATIONSHIP_TEXT = "test relationship"; private static final String RELATED_PROGRAM = "ProgramUid"; @Test public void create_shouldConvertToModel() throws ParseException { MatrixCursor matrixCursor = new MatrixCursor(new String[]{ Columns.ID, Columns.UID, Columns.CODE, Columns.NAME, Columns.DISPLAY_NAME, Columns.CREATED, Columns.LAST_UPDATED, Columns.SHORT_NAME, Columns.DISPLAY_SHORT_NAME, Columns.DESCRIPTION, Columns.DISPLAY_DESCRIPTION, Columns.VERSION, Columns.ONLY_ENROLL_ONCE, Columns.ENROLLMENT_DATE_LABEL, Columns.DISPLAY_INCIDENT_DATE, Columns.INCIDENT_DATE_LABEL, Columns.REGISTRATION, Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE, Columns.DATA_ENTRY_METHOD, Columns.IGNORE_OVERDUE_EVENTS, Columns.RELATIONSHIP_FROM_A, Columns.SELECT_INCIDENT_DATES_IN_FUTURE, Columns.CAPTURE_COORDINATES, Columns.USE_FIRST_STAGE_DURING_REGISTRATION, Columns.DISPLAY_FRONT_PAGE_LIST, Columns.PROGRAM_TYPE, Columns.RELATIONSHIP_TYPE, Columns.RELATIONSHIP_TEXT, Columns.RELATED_PROGRAM }); matrixCursor.addRow(new Object[]{ ID, UID, CODE, NAME, DISPLAY_NAME, DATE, DATE, SHORT_NAME, DISPLAY_SHORT_NAME, DESCRIPTION, DISPLAY_DESCRIPTION, VERSION, ONLY_ENROLL_ONCE, ENROLLMENT_DATE_LABEL, DISPLAY_INCIDENT_DATE, INCIDENT_DATE_LABEL, REGISTRATION, SELECT_ENROLLMENT_DATES_IN_FUTURE, DATA_ENTRY_METHOD, IGNORE_OVERDUE_EVENTS, RELATIONSHIP_FROM_A, SELECT_INCIDENT_DATES_IN_FUTURE, CAPTURE_COORDINATES, USE_FIRST_STAGE_DURING_REGISTRATION, DISPLAY_FRONT_PAGE_LIST, PROGRAM_TYPE, RELATIONSHIP_TYPE, RELATIONSHIP_TEXT, RELATED_PROGRAM }); // move cursor to first item before reading matrixCursor.moveToFirst(); Date timeStamp = BaseIdentifiableObject.DATE_FORMAT.parse(DATE); ProgramModel program = ProgramModel.create(matrixCursor); assertThat(program.id()).isEqualTo(ID); assertThat(program.uid()).isEqualTo(UID); assertThat(program.code()).isEqualTo(CODE); assertThat(program.name()).isEqualTo(NAME); assertThat(program.displayName()).isEqualTo(DISPLAY_NAME); assertThat(program.created()).isEqualTo(timeStamp); assertThat(program.lastUpdated()).isEqualTo(timeStamp); assertThat(program.shortName()).isEqualTo(SHORT_NAME); assertThat(program.displayShortName()).isEqualTo(DISPLAY_SHORT_NAME); assertThat(program.description()).isEqualTo(DESCRIPTION); assertThat(program.displayDescription()).isEqualTo(DISPLAY_DESCRIPTION); assertThat(program.version()).isEqualTo(VERSION); assertThat(program.onlyEnrollOnce()).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(program.enrollmentDateLabel()).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(program.displayIncidentDate()).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(program.incidentDateLabel()).isEqualTo(INCIDENT_DATE_LABEL); assertThat(program.registration()).isEqualTo(toBoolean(REGISTRATION)); assertThat(program.selectEnrollmentDatesInFuture()).isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(program.dataEntryMethod()).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(program.ignoreOverdueEvents()).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(program.relationshipFromA()).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(program.selectIncidentDatesInFuture()).isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(program.captureCoordinates()).isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(program.useFirstStageDuringRegistration()).isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(program.displayFrontPageList()).isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(program.programType()).isEqualTo(PROGRAM_TYPE); assertThat(program.relationshipType()).isEqualTo(RELATIONSHIP_TYPE); assertThat(program.relationshipText()).isEqualTo(RELATIONSHIP_TEXT); assertThat(program.relatedProgram()).isEqualTo(RELATED_PROGRAM); } @Test public void toContentValues_shouldConvertToContentValues() throws ParseException { Date timeStamp = BaseIdentifiableObject.DATE_FORMAT.parse(DATE); ProgramModel program = ProgramModel.builder() .id(ID) .uid(UID) .code(CODE) .name(NAME) .displayName(DISPLAY_NAME) .created(timeStamp) .lastUpdated(timeStamp) .shortName(SHORT_NAME) .displayShortName(DISPLAY_SHORT_NAME) .description(DESCRIPTION) .displayDescription(DISPLAY_DESCRIPTION) .version(VERSION) .onlyEnrollOnce(toBoolean(ONLY_ENROLL_ONCE)) .enrollmentDateLabel(ENROLLMENT_DATE_LABEL) .displayIncidentDate(toBoolean(DISPLAY_INCIDENT_DATE)) .registration(toBoolean(REGISTRATION)) .selectEnrollmentDatesInFuture(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)) .dataEntryMethod(toBoolean(DATA_ENTRY_METHOD)) .ignoreOverdueEvents(toBoolean(IGNORE_OVERDUE_EVENTS)) .relationshipFromA(toBoolean(RELATIONSHIP_FROM_A)) .selectIncidentDatesInFuture(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)) .captureCoordinates(toBoolean(CAPTURE_COORDINATES)) .useFirstStageDuringRegistration(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)) .displayFrontPageList(toBoolean(DISPLAY_FRONT_PAGE_LIST)) .programType(PROGRAM_TYPE) .relationshipType(RELATIONSHIP_TYPE) .relationshipText(RELATIONSHIP_TEXT) .relatedProgram(RELATED_PROGRAM) .build(); ContentValues contentValues = program.toContentValues(); assertThat(contentValues.getAsLong(Columns.ID)).isEqualTo(ID); assertThat(contentValues.getAsString(Columns.UID)).isEqualTo(UID); assertThat(contentValues.getAsString(Columns.NAME)).isEqualTo(NAME); assertThat(contentValues.getAsString(Columns.DISPLAY_NAME)).isEqualTo(DISPLAY_NAME); assertThat(contentValues.getAsString(Columns.CREATED)).isEqualTo(DATE); assertThat(contentValues.getAsString(Columns.LAST_UPDATED)).isEqualTo(DATE); assertThat(contentValues.getAsString(Columns.SHORT_NAME)).isEqualTo(SHORT_NAME); assertThat(contentValues.getAsString(Columns.DISPLAY_SHORT_NAME)).isEqualTo(DISPLAY_SHORT_NAME); assertThat(contentValues.getAsString(Columns.DESCRIPTION)).isEqualTo(DESCRIPTION); assertThat(contentValues.getAsString(Columns.DISPLAY_DESCRIPTION)).isEqualTo(DISPLAY_DESCRIPTION); assertThat(contentValues.getAsInteger(Columns.VERSION)).isEqualTo(VERSION); assertThat(contentValues.getAsBoolean(Columns.ONLY_ENROLL_ONCE)).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(contentValues.getAsString(Columns.ENROLLMENT_DATE_LABEL)).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(contentValues.getAsBoolean(Columns.DISPLAY_INCIDENT_DATE)).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(contentValues.getAsBoolean(Columns.REGISTRATION)).isEqualTo(toBoolean(REGISTRATION)); assertThat(contentValues.getAsBoolean(Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE)).isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean(Columns.DATA_ENTRY_METHOD)).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(contentValues.getAsBoolean(Columns.IGNORE_OVERDUE_EVENTS)).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(contentValues.getAsBoolean(Columns.RELATIONSHIP_FROM_A)).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(contentValues.getAsBoolean(Columns.SELECT_INCIDENT_DATES_IN_FUTURE)).isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean(Columns.CAPTURE_COORDINATES)).isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(contentValues.getAsBoolean(Columns.USE_FIRST_STAGE_DURING_REGISTRATION)).isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(contentValues.getAsBoolean(Columns.DISPLAY_FRONT_PAGE_LIST)).isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(contentValues.getAsString(Columns.PROGRAM_TYPE)).isEqualTo(PROGRAM_TYPE.toString()); assertThat(contentValues.getAsString(Columns.RELATIONSHIP_TYPE)).isEqualTo(RELATIONSHIP_TYPE); assertThat(contentValues.getAsString(Columns.RELATIONSHIP_TEXT)).isEqualTo(RELATIONSHIP_TEXT); assertThat(contentValues.getAsString(Columns.RELATED_PROGRAM)).isEqualTo(RELATED_PROGRAM); } /* A helper method to convert an integer to Boolean. 0 -> false, != 0 -> true*/ private Boolean toBoolean(Integer i) { return i != 0; } }
Added create Program method in ProgramModelintegrationTest.
core/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramModelIntegrationTest.java
Added create Program method in ProgramModelintegrationTest.
<ide><path>ore/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramModelIntegrationTest.java <ide> private static final Integer USE_FIRST_STAGE_DURING_REGISTRATION = 1; <ide> private static final Integer DISPLAY_FRONT_PAGE_LIST = 1; <ide> <del> //TODO : TEST custom Types: <ide> private static final ProgramType PROGRAM_TYPE = ProgramType.WITH_REGISTRATION; <ide> private static final String RELATIONSHIP_TYPE = "relationshipUid"; <ide> private static final String RELATIONSHIP_TEXT = "test relationship"; <ide> private static final String RELATED_PROGRAM = "ProgramUid"; <add> <add> /** <add> * A method to create ContentValues for a Program. <add> * To be used by other tests. <add> * <add> * @param id <add> * @param uid <add> * @return <add> */ <add> public static ContentValues create(long id, String uid) { <add> ContentValues program = new ContentValues(); <add> program.put(Columns.ID, id); <add> program.put(Columns.UID, uid); <add> program.put(Columns.CODE, CODE); <add> program.put(Columns.NAME, NAME); <add> program.put(Columns.DISPLAY_NAME, DISPLAY_NAME); <add> program.put(Columns.CREATED, DATE); <add> program.put(Columns.LAST_UPDATED, DATE); <add> program.put(Columns.SHORT_NAME, SHORT_NAME); <add> program.put(Columns.DISPLAY_SHORT_NAME, DISPLAY_SHORT_NAME); <add> program.put(Columns.DESCRIPTION, DESCRIPTION); <add> program.put(Columns.DISPLAY_DESCRIPTION, DISPLAY_DESCRIPTION); <add> program.put(Columns.VERSION, VERSION); <add> program.put(Columns.ONLY_ENROLL_ONCE, ONLY_ENROLL_ONCE); <add> program.put(Columns.ENROLLMENT_DATE_LABEL, ENROLLMENT_DATE_LABEL); <add> program.put(Columns.DISPLAY_INCIDENT_DATE, DISPLAY_INCIDENT_DATE); <add> program.put(Columns.INCIDENT_DATE_LABEL, INCIDENT_DATE_LABEL); <add> program.put(Columns.REGISTRATION, REGISTRATION); <add> program.put(Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE, SELECT_ENROLLMENT_DATES_IN_FUTURE); <add> program.put(Columns.DATA_ENTRY_METHOD, DATA_ENTRY_METHOD); <add> program.put(Columns.IGNORE_OVERDUE_EVENTS, IGNORE_OVERDUE_EVENTS); <add> program.put(Columns.RELATIONSHIP_FROM_A, RELATIONSHIP_FROM_A); <add> program.put(Columns.SELECT_INCIDENT_DATES_IN_FUTURE, SELECT_INCIDENT_DATES_IN_FUTURE); <add> program.put(Columns.CAPTURE_COORDINATES, CAPTURE_COORDINATES); <add> program.put(Columns.USE_FIRST_STAGE_DURING_REGISTRATION, USE_FIRST_STAGE_DURING_REGISTRATION); <add> program.put(Columns.DISPLAY_FRONT_PAGE_LIST, DISPLAY_FRONT_PAGE_LIST); <add> program.put(Columns.PROGRAM_TYPE, PROGRAM_TYPE.name()); <add> program.put(Columns.RELATIONSHIP_TYPE, RELATIONSHIP_TYPE); <add> program.put(Columns.RELATIONSHIP_TEXT, RELATIONSHIP_TEXT); <add> program.put(Columns.RELATED_PROGRAM, RELATED_PROGRAM); <add> <add> return program; <add> } <ide> <ide> @Test <ide> public void create_shouldConvertToModel() throws ParseException {
JavaScript
mit
12a82aecd4b72faac0774709a0b2c721be3d7621
0
Hydrock/pomodoro,Hydrock/pomodoro
import * as constants from '@src/constants.js' import * as Cookies from "js-cookie"; let period = Cookies.get('timerPeriod'); if (!period) { Cookies.set('timerPeriod', 25); period = 25; } let breakTime = Cookies.get('timerBreak'); if (!breakTime) { Cookies.set('timerBreak', 5); breakTime = 5; } let startState = { timerTime: 0, timerState: 'pause', // working, pause // It determines whether the countdown is in progress or not mode: constants.TIMER_MODE_POMODORO, //pomodoro, break // timer mode timerActivated: false, // Started timer or not period: period, // minutes breakTime: breakTime, // minutes timeStart: Date.now(), timeEnd: 0, timeDifference: 0 } export default function timer(state = startState, action) { switch (action.type) { case constants.SET_TIMER_SETTINGS: state = Object.assign({}, state, action.payload); return state; default: return state } }
src/reducers/timer.js
import * as constants from '@src/constants.js' let startState = { timerTime: 0, timerState: 'pause', // working, pause // It determines whether the countdown is in progress or not mode: constants.TIMER_MODE_POMODORO, //pomodoro, break // timer mode timerActivated: false, // Started timer or not period: 0.2, // minutes breakTime: 0.1, // minutes timeStart: Date.now(), timeEnd: 0, timeDifference: 0 } export default function timer(state = startState, action) { switch (action.type) { case constants.SET_TIMER_SETTINGS: state = Object.assign({}, state, action.payload); return state; default: return state } }
add timer period and break perid cookies
src/reducers/timer.js
add timer period and break perid cookies
<ide><path>rc/reducers/timer.js <ide> import * as constants from '@src/constants.js' <add>import * as Cookies from "js-cookie"; <add> <add>let period = Cookies.get('timerPeriod'); <add>if (!period) { <add> Cookies.set('timerPeriod', 25); <add> period = 25; <add>} <add> <add>let breakTime = Cookies.get('timerBreak'); <add>if (!breakTime) { <add> Cookies.set('timerBreak', 5); <add> breakTime = 5; <add>} <ide> <ide> let startState = { <ide> timerTime: 0, <ide> timerState: 'pause', // working, pause // It determines whether the countdown is in progress or not <ide> mode: constants.TIMER_MODE_POMODORO, //pomodoro, break // timer mode <ide> timerActivated: false, // Started timer or not <del> period: 0.2, // minutes <del> breakTime: 0.1, // minutes <add> period: period, // minutes <add> breakTime: breakTime, // minutes <ide> timeStart: Date.now(), <ide> timeEnd: 0, <ide> timeDifference: 0
Java
mit
d459990764651938ade16a2d19f316bf0dff18d0
0
fenfir/mtg-familiar,fenfir/mtg-familiar,fenfir/mtg-familiar
/** Copyright 2011 Adam Feinstein This file is part of MTG Familiar. MTG Familiar is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MTG Familiar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MTG Familiar. If not, see <http://www.gnu.org/licenses/>. */ package com.gelakinetic.mtgfam.helpers.database; import android.app.SearchManager; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources.NotFoundException; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteQueryBuilder; import android.preference.PreferenceManager; import android.provider.BaseColumns; import com.gelakinetic.mtgfam.R; import com.gelakinetic.mtgfam.helpers.MtgCard; import com.gelakinetic.mtgfam.helpers.MtgSet; import com.gelakinetic.mtgfam.helpers.WishlistHelpers.CompressedWishlistInfo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.zip.GZIPInputStream; /** * Simple Cards database access helper class. Defines the basic CRUD operations * and gives the ability to list all Cards as well as retrieve or modify a * specific Card. */ public class CardDbAdapter { public static final int STAR = -1000; public static final int ONE_PLUS_STAR = -1001; public static final int TWO_PLUS_STAR = -1002; public static final int SEVEN_MINUS_STAR = -1003; public static final int STAR_SQUARED = -1004; public static final int NO_ONE_CARES = -1005; public static final int MOST_RECENT_PRINTING = 0; public static final int FIRST_PRINTING = 1; public static final int ALL_PRINTINGS = 2; public static final String DATABASE_NAME = "data"; public static final String DATABASE_TABLE_CARDS = "cards"; public static final String DATABASE_TABLE_SETS = "sets"; private static final String DATABASE_TABLE_FORMATS = "formats"; private static final String DATABASE_TABLE_LEGAL_SETS = "legal_sets"; private static final String DATABASE_TABLE_BANNED_CARDS = "banned_cards"; private static final String DATABASE_TABLE_RULES = "rules"; private static final String DATABASE_TABLE_GLOSSARY = "glossary"; public static final int DATABASE_VERSION = 49; public static final String KEY_ID = "_id"; public static final String KEY_NAME = SearchManager.SUGGEST_COLUMN_TEXT_1; // "name"; public static final String KEY_SET = "expansion"; public static final String KEY_TYPE = "type"; public static final String KEY_ABILITY = "cardtext"; public static final String KEY_COLOR = "color"; public static final String KEY_MANACOST = "manacost"; public static final String KEY_CMC = "cmc"; public static final String KEY_POWER = "power"; public static final String KEY_TOUGHNESS = "toughness"; public static final String KEY_RARITY = "rarity"; public static final String KEY_LOYALTY = "loyalty"; public static final String KEY_FLAVOR = "flavor"; public static final String KEY_ARTIST = "artist"; public static final String KEY_NUMBER = "number"; public static final String KEY_MULTIVERSEID = "multiverseID"; private static final String KEY_RULINGS = "rulings"; public static final String KEY_CODE = "code"; private static final String KEY_CODE_MTGI = "code_mtgi"; public static final String KEY_NAME_TCGPLAYER = "name_tcgplayer"; private static final String KEY_DATE = "date"; public static final String KEY_FORMAT = "format"; public static final String KEY_LEGALITY = "legality"; public static final String KEY_CATEGORY = "category"; public static final String KEY_SUBCATEGORY = "subcategory"; public static final String KEY_ENTRY = "entry"; public static final String KEY_RULE_TEXT = "rule_text"; private static final String KEY_POSITION = "position"; public static final String KEY_TERM = "term"; public static final String KEY_DEFINITION = "definition"; public static final String KEY_BANNED_LIST = "banned_list"; public static final String KEY_LEGAL_SETS = "legal_sets"; public static final String[] allData = {DATABASE_TABLE_CARDS + "." + KEY_ID, DATABASE_TABLE_CARDS + "." + KEY_NAME, DATABASE_TABLE_CARDS + "." + KEY_SET, DATABASE_TABLE_CARDS + "." + KEY_NUMBER, DATABASE_TABLE_CARDS + "." + KEY_TYPE, DATABASE_TABLE_CARDS + "." + KEY_MANACOST, DATABASE_TABLE_CARDS + "." + KEY_ABILITY, DATABASE_TABLE_CARDS + "." + KEY_POWER, DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS, DATABASE_TABLE_CARDS + "." + KEY_LOYALTY, DATABASE_TABLE_CARDS + "." + KEY_RARITY, DATABASE_TABLE_CARDS + "." + KEY_FLAVOR, DATABASE_TABLE_CARDS + "." + KEY_CMC, DATABASE_TABLE_CARDS + "." + KEY_COLOR }; public static final String DATABASE_CREATE_CARDS = "create table " + DATABASE_TABLE_CARDS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_SET + " text not null, " + KEY_TYPE + " text not null, " + KEY_RARITY + " integer, " + KEY_MANACOST + " text, " + KEY_CMC + " integer not null, " + KEY_POWER + " real, " + KEY_TOUGHNESS + " real, " + KEY_LOYALTY + " integer, " + KEY_ABILITY + " text, " + KEY_FLAVOR + " text, " + KEY_ARTIST + " text, " + KEY_NUMBER + " text, " + KEY_MULTIVERSEID + " integer not null, " + KEY_COLOR + " text not null, " + KEY_RULINGS + " text);"; public static final String DATABASE_CREATE_SETS = "create table " + DATABASE_TABLE_SETS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_CODE + " text not null unique, " + KEY_CODE_MTGI + " text not null, " + KEY_NAME_TCGPLAYER + " text, " + KEY_DATE + " integer);"; private static final String DATABASE_CREATE_FORMATS = "create table " + DATABASE_TABLE_FORMATS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null);"; private static final String DATABASE_CREATE_LEGAL_SETS = "create table " + DATABASE_TABLE_LEGAL_SETS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_SET + " text not null, " + KEY_FORMAT + " text not null);"; private static final String DATABASE_CREATE_BANNED_CARDS = "create table " + DATABASE_TABLE_BANNED_CARDS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_LEGALITY + " integer not null, " + KEY_FORMAT + " text not null);"; private static final String DATABASE_CREATE_RULES = "create table " + DATABASE_TABLE_RULES + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_CATEGORY + " integer not null, " + KEY_SUBCATEGORY + " integer not null, " + KEY_ENTRY + " text null, " + KEY_RULE_TEXT + " text not null, " + KEY_POSITION + " integer null);"; private static final String DATABASE_CREATE_GLOSSARY = "create table " + DATABASE_TABLE_GLOSSARY + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_TERM + " text not null, " + KEY_DEFINITION + " text not null);"; private static final String EXCLUDE_TOKEN = "!"; private static final int EXCLUDE_TOKEN_START = 1; public static final int LEGAL = 0; public static final int BANNED = 1; public static final int RESTRICTED = 2; // use a hash map for performance private static final HashMap<String, String> mColumnMap = buildColumnMap(); private static final String DB_NAME = "data"; public static final int NOPE = 0; public static final int TRANSFORM = 1; public static final int FUSE = 2; public static final int SPLIT = 3; /** * @param sqLiteDatabase * @throws FamiliarDbException */ public static void dropCreateDB(SQLiteDatabase sqLiteDatabase) throws FamiliarDbException { try { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_CARDS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SETS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_FORMATS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_LEGAL_SETS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_BANNED_CARDS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_RULES); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_GLOSSARY); sqLiteDatabase.execSQL(DATABASE_CREATE_CARDS); sqLiteDatabase.execSQL(DATABASE_CREATE_SETS); sqLiteDatabase.execSQL(DATABASE_CREATE_FORMATS); sqLiteDatabase.execSQL(DATABASE_CREATE_LEGAL_SETS); sqLiteDatabase.execSQL(DATABASE_CREATE_BANNED_CARDS); sqLiteDatabase.execSQL(DATABASE_CREATE_RULES); sqLiteDatabase.execSQL(DATABASE_CREATE_GLOSSARY); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param c * @param mDb * @return */ public static void createCard(MtgCard c, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, c.name); initialValues.put(KEY_SET, c.set); initialValues.put(KEY_TYPE, c.type); initialValues.put(KEY_RARITY, (int) c.rarity); initialValues.put(KEY_MANACOST, c.manaCost); initialValues.put(KEY_CMC, c.cmc); initialValues.put(KEY_POWER, c.power); initialValues.put(KEY_TOUGHNESS, c.toughness); initialValues.put(KEY_LOYALTY, c.loyalty); initialValues.put(KEY_ABILITY, c.ability); initialValues.put(KEY_FLAVOR, c.flavor); initialValues.put(KEY_ARTIST, c.artist); initialValues.put(KEY_NUMBER, c.number); initialValues.put(KEY_COLOR, c.color); initialValues.put(KEY_MULTIVERSEID, c.multiverseId); mDb.insert(DATABASE_TABLE_CARDS, null, initialValues); } /** * @param set * @param mDb * @return */ public static void createSet(MtgSet set, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_CODE, set.code); initialValues.put(KEY_NAME, set.name); initialValues.put(KEY_CODE_MTGI, set.codeMagicCards); initialValues.put(KEY_DATE, set.date); mDb.insert(DATABASE_TABLE_SETS, null, initialValues); } /** * @param name * @param code * @param mDb * @return */ public static void addTcgName(String name, String code, SQLiteDatabase mDb) { ContentValues args = new ContentValues(); args.put(KEY_NAME_TCGPLAYER, name); mDb.update(DATABASE_TABLE_SETS, args, KEY_CODE + " = '" + code + "'", null); } /** * @param sqLiteDatabase * @return * @throws FamiliarDbException */ public static Cursor fetchAllSets(SQLiteDatabase sqLiteDatabase) throws FamiliarDbException { Cursor c; try { c = sqLiteDatabase.query(DATABASE_TABLE_SETS, new String[]{KEY_ID, KEY_NAME, KEY_CODE, KEY_CODE_MTGI}, null, null, null, null, KEY_DATE + " DESC"); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } catch (NullPointerException e) { throw new FamiliarDbException(e); } return c; } /** * @param code * @param mDb * @return * @throws FamiliarDbException */ public static boolean doesSetExist(String code, SQLiteDatabase mDb) throws FamiliarDbException { String statement = "(" + KEY_CODE + " = '" + code + "')"; Cursor c; int count; try { c = mDb.query(true, DATABASE_TABLE_SETS, new String[]{KEY_ID}, statement, null, null, null, KEY_NAME, null); count = c.getCount(); c.close(); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return count > 0; } /** * @param code * @param mDb * @return * @throws FamiliarDbException */ public static String getCodeMtgi(String code, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; try { c = mDb.query(DATABASE_TABLE_SETS, new String[]{KEY_CODE_MTGI}, KEY_CODE + "=\"" + code + "\"", null, null, null, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } c.moveToFirst(); String returnVal = c.getString(c.getColumnIndex(KEY_CODE_MTGI)); c.close(); return returnVal; } /** * @param id * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchCard(long id, SQLiteDatabase mDb) throws FamiliarDbException { String columns[] = new String[]{KEY_ID, KEY_NAME, KEY_SET, KEY_TYPE, KEY_RARITY, KEY_MANACOST, KEY_CMC, KEY_POWER, KEY_TOUGHNESS, KEY_LOYALTY, KEY_ABILITY, KEY_FLAVOR, KEY_ARTIST, KEY_NUMBER, KEY_COLOR, KEY_MULTIVERSEID}; Cursor c; try { c = mDb.query(true, DATABASE_TABLE_CARDS, columns, KEY_ID + "=" + id, null, null, null, KEY_NAME, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param name * @param fields * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchCardByName(String name, String[] fields, SQLiteDatabase mDb) throws FamiliarDbException { // replace lowercase ae with Ae name = name.replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); String sql = "SELECT "; boolean first = true; for (String field : fields) { if (first) { first = false; } else { sql += ", "; } sql += field; } sql += " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(name) + " GROUP BY " + DATABASE_TABLE_SETS + "." + KEY_CODE + " ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC"; Cursor c; try { c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param mCompressedWishlist * @param mDb * @throws FamiliarDbException */ public static void fillExtraWishlistData(ArrayList<CompressedWishlistInfo> mCompressedWishlist, SQLiteDatabase mDb) throws FamiliarDbException { String sql = "SELECT "; boolean first = true; for (String field : CardDbAdapter.allData) { if (first) { first = false; } else { sql += ", "; } sql += field; } sql += " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE ("; first = true; boolean doSql = false; for (CompressedWishlistInfo cwi : mCompressedWishlist) { if (cwi.mCard.type == null || cwi.mCard.type.equals("")) { doSql = true; if (first) { first = false; } else { sql += " OR "; } if (cwi.mCard.setCode != null && !cwi.mCard.setCode.equals("")) { sql += "(" + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(cwi.mCard.name) + " AND " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = '" + cwi.mCard.setCode + "')"; } else { sql += "(" + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(cwi.mCard.name) + ")"; } } } if (!doSql) { return; } sql += ")"; /* ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC */ Cursor cursor; try { cursor = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (cursor != null) { cursor.moveToFirst(); } else { return; } while (!cursor.isAfterLast()) { /* Do stuff */ String name = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_NAME)); for (CompressedWishlistInfo cwi : mCompressedWishlist) { if (name != null && name.equals(cwi.mCard.name)) { cwi.mCard.type = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_TYPE)); cwi.mCard.rarity = (char) cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_RARITY)); cwi.mCard.manaCost = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_MANACOST)); cwi.mCard.power = cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_POWER)); cwi.mCard.toughness = cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_TOUGHNESS)); cwi.mCard.loyalty = cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_LOYALTY)); cwi.mCard.ability = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_ABILITY)); cwi.mCard.flavor = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_FLAVOR)); cwi.mCard.number = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_NUMBER)); cwi.mCard.cmc = cursor.getInt((cursor.getColumnIndex(CardDbAdapter.KEY_CMC))); cwi.mCard.color = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_COLOR)); } } /* NEXT! */ cursor.moveToNext(); } /* Use the cursor to populate stuff */ cursor.close(); } /** * @param name * @param setCode * @param fields * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchCardByNameAndSet(String name, String setCode, String[] fields, SQLiteDatabase mDb) throws FamiliarDbException { // replace lowercase ae with Ae name = name.replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); String sql = "SELECT "; boolean first = true; for (String field : fields) { if (first) { first = false; } else { sql += ", "; } sql += field; } sql += " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(name) + " AND " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = '" + setCode + "' ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC"; Cursor c; try { c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param name * @param mDb * @return * @throws FamiliarDbException */ public static long fetchIdByName(String name, SQLiteDatabase mDb) throws FamiliarDbException { // replace lowercase ae with Ae name = name.replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); String sql = "SELECT " + DATABASE_TABLE_CARDS + "." + KEY_ID + ", " + DATABASE_TABLE_CARDS + "." + KEY_SET + ", " + DATABASE_TABLE_SETS + "." + KEY_DATE + " FROM (" + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_CARDS + "." + KEY_SET + "=" + DATABASE_TABLE_SETS + "." + KEY_CODE + ")" + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(name) + " ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC"; Cursor c; try { c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); long id = c.getLong(c .getColumnIndex(CardDbAdapter.KEY_ID)); c.close(); return id; } return -1; } /** * @param cardname * @param cardtext * @param cardtype * @param color * @param colorlogic * @param sets * @param pow_choice * @param pow_logic * @param tou_choice * @param tou_logic * @param cmc * @param cmcLogic * @param format * @param rarity * @param flavor * @param artist * @param type_logic * @param text_logic * @param set_logic * @param backface * @param returnTypes * @param consolidate * @param mDb * @return * @throws FamiliarDbException */ public static Cursor Search(String cardname, String cardtext, String cardtype, String color, int colorlogic, String sets, float pow_choice, String pow_logic, float tou_choice, String tou_logic, int cmc, String cmcLogic, String format, String rarity, String flavor, String artist, int type_logic, int text_logic, int set_logic, boolean backface, String[] returnTypes, boolean consolidate, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; if (cardname != null) cardname = cardname.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]).trim(); if (cardtext != null) cardtext = cardtext.replace("'", "''").trim(); if (cardtype != null) cardtype = cardtype.replace("'", "''").trim(); if (flavor != null) flavor = flavor.replace("'", "''").trim(); if (artist != null) artist = artist.replace("'", "''").trim(); String statement = " WHERE 1=1"; if (cardname != null) { String[] nameParts = cardname.split(" "); for (String s : nameParts) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '%" + s + "%' OR " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '%" + s.toLowerCase().replace("ae", String.valueOf(Character.toChars(0xC6)[0])) + "%')"; } } /*************************************************************************************/ /** * Reuben's version Differences: Original code is verbose only, but mine * allows for matching exact text, all words, or just any one word. */ if (cardtext != null) { String[] cardTextParts = cardtext.split(" "); // Separate each // individual /** * The following switch statement tests to see which text search * logic was chosen by the user. If they chose the first option (0), * then look for cards with text that includes all words, but not * necessarily the exact phrase. The second option (1) finds cards * that have 1 or more of the chosen words in their text. The third * option (2) searches for the exact phrase as entered by the user. * The 'default' option is impossible via the way the code is * written, but I believe it's also mandatory to include it in case * someone else is perhaps fussing with the code and breaks it. The * if statement at the end is theoretically unnecessary, because * once we've entered the current if statement, there is no way to * NOT change the statement variable. However, you never really know * who's going to break open your code and fuss around with it, so * it's always good to leave some small safety measures. */ switch (text_logic) { case 0: for (String s : cardTextParts) { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " NOT LIKE '%" + s.substring(EXCLUDE_TOKEN_START) + "%')"; else statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + s + "%')"; } break; case 1: boolean firstRun = true; for (String s : cardTextParts) { if (firstRun) { firstRun = false; if (s.contains(EXCLUDE_TOKEN)) statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " NOT LIKE '%" + s.substring(EXCLUDE_TOKEN_START) + "%')"; else statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + s + "%')"; } else { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " NOT LIKE '%" + s.substring(EXCLUDE_TOKEN_START) + "%')"; else statement += " OR (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + s + "%')"; } } statement += ")"; break; case 2: statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + cardtext + "%')"; break; default: break; } } /** End Reuben's version */ /** * Reuben's version Differences: Original version only allowed for * including all types, not any of the types or excluding the given * types. */ String supertypes = null; String subtypes = null; if (cardtype != null && !cardtype.equals("-")) { boolean containsSupertype = true; if (cardtype.substring(0, 2).equals("- ")) { containsSupertype = false; } String[] split = cardtype.split(" - "); if (split.length >= 2) { supertypes = split[0].replace(" -", ""); subtypes = split[1].replace(" -", ""); } else if (containsSupertype) { supertypes = cardtype.replace(" -", ""); } else { subtypes = cardtype.replace("- ", ""); } } if (supertypes != null) { String[] supertypesParts = supertypes.split(" "); // Separate each // individual switch (type_logic) { case 0: for (String s : supertypesParts) { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } break; case 1: boolean firstRun = true; for (String s : supertypesParts) { if (firstRun) { firstRun = false; if (s.contains(EXCLUDE_TOKEN)) statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } else if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " OR (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } statement += ")"; break; case 2: for (String s : supertypesParts) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s + "%')"; } break; default: break; } } if (subtypes != null) { String[] subtypesParts = subtypes.split(" "); // Separate each // individual switch (type_logic) { case 0: for (String s : subtypesParts) { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } break; case 1: boolean firstRun = true; for (String s : subtypesParts) { if (firstRun) { firstRun = false; if (s.contains(EXCLUDE_TOKEN)) statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } else if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " OR (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } statement += ")"; break; case 2: for (String s : subtypesParts) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s + "%')"; } break; default: break; } } /** End Reuben's version */ /*************************************************************************************/ if (flavor != null) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_FLAVOR + " LIKE '%" + flavor + "%')"; } if (artist != null) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ARTIST + " LIKE '%" + artist + "%')"; } /*************************************************************************************/ /** * Code below added/modified by Reuben. Differences: Original version * only had 'Any' and 'All' options and lacked 'Exclusive' and 'Exact' * matching. In addition, original programming only provided exclusive * results. */ if (!(color.equals("wubrgl") || (color.equals("WUBRGL") && colorlogic == 0))) { boolean firstPrint = true; // Can't contain these colors /** * ...if the chosen color logic was exactly (2) or none (3) of the * selected colors */ if (colorlogic > 1) // if colorlogic is 2 or 3 it will be greater // than 1 { statement += " AND (("; for (byte b : color.getBytes()) { char ch = (char) b; if (ch > 'a') { if (firstPrint) firstPrint = false; else statement += " AND "; if (ch == 'l' || ch == 'L') statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " NOT GLOB '[CLA]'"; else statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " NOT LIKE '%" + Character.toUpperCase(ch) + "%'"; } } statement += ") AND ("; } firstPrint = true; // Might contain these colors if (colorlogic < 2) statement += " AND ("; for (byte b : color.getBytes()) { char ch = (char) b; if (ch < 'a') { if (firstPrint) firstPrint = false; else { if (colorlogic == 1 || colorlogic == 3) statement += " AND "; else statement += " OR "; } if (ch == 'l' || ch == 'L') statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " GLOB '[CLA]'"; else statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " LIKE '%" + ch + "%'"; } } if (colorlogic > 1) statement += "))"; else statement += ")"; } /** End of addition */ /*************************************************************************************/ if (sets != null) { statement += " AND ("; boolean first = true; for (String s : sets.split("-")) { if (first) { first = false; } else { statement += " OR "; } statement += DATABASE_TABLE_CARDS + "." + KEY_SET + " = '" + s + "'"; } statement += ")"; } if (pow_choice != NO_ONE_CARES) { statement += " AND ("; if (pow_choice > STAR) { statement += DATABASE_TABLE_CARDS + "." + KEY_POWER + " " + pow_logic + " " + pow_choice; if (pow_logic.equals("<")) { statement += " AND " + DATABASE_TABLE_CARDS + "." + KEY_POWER + " > " + STAR; } } else if (pow_logic.equals("=")) { statement += DATABASE_TABLE_CARDS + "." + KEY_POWER + " " + pow_logic + " " + pow_choice; } statement += ")"; } if (tou_choice != NO_ONE_CARES) { statement += " AND ("; if (tou_choice > STAR) { statement += DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS + " " + tou_logic + " " + tou_choice; if (tou_logic.equals("<")) { statement += " AND " + DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS + " > " + STAR; } } else if (tou_logic.equals("=")) { statement += DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS + " " + tou_logic + " " + tou_choice; } statement += ")"; } if (cmc != -1) { statement += " AND ("; statement += DATABASE_TABLE_CARDS + "." + KEY_CMC + " " + cmcLogic + " " + cmc + ")"; } if (rarity != null) { statement += " AND ("; boolean firstPrint = true; for (int i = 0; i < rarity.length(); i++) { if (firstPrint) { firstPrint = false; } else { statement += " OR "; } statement += DATABASE_TABLE_CARDS + "." + KEY_RARITY + " = " + (int) rarity.toUpperCase().charAt(i) + ""; } statement += ")"; } String tbl = DATABASE_TABLE_CARDS; if (format != null) { /* Check if the format is eternal or not, by the number of legal sets */ String numLegalSetsSql = "SELECT * FROM " + DATABASE_TABLE_LEGAL_SETS + " WHERE " + KEY_FORMAT + " = \"" + format + "\""; Cursor numLegalSetCursor = mDb.rawQuery(numLegalSetsSql, null); /* If the format is not eternal, filter by set */ if (numLegalSetCursor.getCount() > 0) { tbl = "(" + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_LEGAL_SETS + " ON " + DATABASE_TABLE_CARDS + "." + KEY_SET + "=" + DATABASE_TABLE_LEGAL_SETS + "." + KEY_SET + " AND " + DATABASE_TABLE_LEGAL_SETS + "." + KEY_FORMAT + "='" + format + "')"; } else { /* Otherwise filter silver bordered cards, giant cards */ statement += " AND NOT " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = 'UNH'" + " AND NOT " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = 'UG'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Plane %'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Conspiracy%'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%Scheme%'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Vanguard%'"; } statement += " AND NOT EXISTS (SELECT * FROM " + DATABASE_TABLE_BANNED_CARDS + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DATABASE_TABLE_BANNED_CARDS + "." + KEY_NAME + " AND " + DATABASE_TABLE_BANNED_CARDS + "." + KEY_FORMAT + " = '" + format + "' AND " + DATABASE_TABLE_BANNED_CARDS + "." + KEY_LEGALITY + " = " + BANNED + ")"; } if (!backface) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_NUMBER + " NOT LIKE '%b%')"; } if (set_logic != MOST_RECENT_PRINTING && set_logic != ALL_PRINTINGS) { statement = " JOIN (SELECT iT" + DATABASE_TABLE_CARDS + "." + KEY_NAME + ", MIN(" + DATABASE_TABLE_SETS + "." + KEY_DATE + ") AS " + KEY_DATE + " FROM " + DATABASE_TABLE_CARDS + " AS iT" + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON iT" + DATABASE_TABLE_CARDS + "." + KEY_SET + " = " + DATABASE_TABLE_SETS + "." + KEY_CODE + " GROUP BY iT" + DATABASE_TABLE_CARDS + "." + KEY_NAME + ") AS FirstPrints" + " ON " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = FirstPrints." + KEY_NAME + statement; if (set_logic == FIRST_PRINTING) statement = " AND " + DATABASE_TABLE_SETS + "." + KEY_DATE + " = FirstPrints." + KEY_DATE + statement; else statement = " AND " + DATABASE_TABLE_SETS + "." + KEY_DATE + " <> FirstPrints." + KEY_DATE + statement; } if (statement.equals(" WHERE 1=1")) { // If the statement is just this, it means we added nothing return null; } try { String sel = null; for (String s : returnTypes) { if (sel == null) { sel = DATABASE_TABLE_CARDS + "." + s + " AS " + s; } else { sel += ", " + DATABASE_TABLE_CARDS + "." + s + " AS " + s; } } sel += ", " + DATABASE_TABLE_SETS + "." + KEY_DATE; String sql = "SELECT * FROM (SELECT " + sel + " FROM " + tbl + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = " + DATABASE_TABLE_SETS + "." + KEY_CODE + statement; if (consolidate) { sql += " ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + ") GROUP BY " + KEY_NAME + " ORDER BY " + KEY_NAME + " COLLATE UNICODE"; } else { sql += " ORDER BY " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " COLLATE UNICODE" + ", " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC)"; } c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param set * @param number * @param mDb * @return * @throws FamiliarDbException */ public static int getTransform(String set, String number, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String statement = "(" + KEY_NUMBER + " = '" + number + "') AND (" + KEY_SET + " = '" + set + "')"; try { c = mDb.query(true, DATABASE_TABLE_CARDS, new String[]{KEY_ID}, statement, null, null, null, KEY_ID, null); c.moveToFirst(); int ID = c.getInt(c.getColumnIndex(KEY_ID)); c.close(); return ID; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } catch (CursorIndexOutOfBoundsException e) { return -1; /* The other half doesn't exist... */ } } /** * @param set * @param number * @param mDb * @return * @throws FamiliarDbException */ public static String getTransformName(String set, String number, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String name; String statement = "(" + KEY_NUMBER + " = '" + number + "') AND (" + KEY_SET + " = '" + set + "')"; try { c = mDb.query(true, DATABASE_TABLE_CARDS, new String[]{KEY_NAME}, statement, null, null, null, KEY_NAME, null); c.moveToFirst(); name = c.getString(c.getColumnIndex(KEY_NAME)); c.close(); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return name; } /** * @param mDb * @throws FamiliarDbException */ public static void createLegalTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL(DATABASE_CREATE_FORMATS); mDb.execSQL(DATABASE_CREATE_LEGAL_SETS); mDb.execSQL(DATABASE_CREATE_BANNED_CARDS); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @throws FamiliarDbException */ public static void dropLegalTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_FORMATS); mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_LEGAL_SETS); mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_BANNED_CARDS); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param name * @param mDb * @return */ public static void createFormat(String name, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name); mDb.insert(DATABASE_TABLE_FORMATS, null, initialValues); } /** * @param set * @param format * @param mDb * @return */ public static void addLegalSet(String set, String format, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_SET, set); initialValues.put(KEY_FORMAT, format); mDb.insert(DATABASE_TABLE_LEGAL_SETS, null, initialValues); } /** * @param card * @param format * @param status * @param mDb * @return */ public static void addLegalCard(String card, String format, int status, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, card); initialValues.put(KEY_LEGALITY, status); initialValues.put(KEY_FORMAT, format); mDb.insert(DATABASE_TABLE_BANNED_CARDS, null, initialValues); } /** * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchAllFormats(SQLiteDatabase mDb) throws FamiliarDbException { try { return mDb.query(DATABASE_TABLE_FORMATS, new String[]{KEY_ID, KEY_NAME,}, null, null, null, null, KEY_NAME); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mCardName * @param format * @param mDb * @return * @throws FamiliarDbException */ public static int checkLegality(String mCardName, String format, SQLiteDatabase mDb) throws FamiliarDbException { mCardName = mCardName.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); format = format.replace("'", "''"); // Just to be safe; remember Bobby // Tables try { // The new way (single query per type, should be much faster) - Alex String sql = "SELECT COALESCE(CASE (SELECT " + KEY_SET + " FROM " + DATABASE_TABLE_CARDS + " WHERE " + KEY_NAME + " = '" + mCardName + "') WHEN 'UG' THEN 1 WHEN 'UNH' THEN 1 WHEN 'ARS' THEN 1 WHEN 'PCP' THEN 1 " + "WHEN 'PP2' THEN 1 ELSE NULL END, " + "CASE (SELECT 1 FROM " + DATABASE_TABLE_CARDS + " c INNER JOIN " + DATABASE_TABLE_LEGAL_SETS + " ls ON ls." + KEY_SET + " = c." + KEY_SET + " WHERE ls." + KEY_FORMAT + " = '" + format + "' AND c." + KEY_NAME + " = '" + mCardName + "') WHEN 1 THEN NULL ELSE CASE WHEN '" + format + "' = 'Legacy' " + "THEN NULL WHEN '" + format + "' = 'Vintage' THEN NULL WHEN '" + format + "' = 'Commander' THEN NULL ELSE 1 END END, (SELECT " + KEY_LEGALITY + " from " + DATABASE_TABLE_BANNED_CARDS + " WHERE " + KEY_NAME + " = '" + mCardName + "' AND " + KEY_FORMAT + " = '" + format + "'), 0) AS " + KEY_LEGALITY; Cursor c = mDb.rawQuery(sql, null); c.moveToFirst(); int legality = c.getInt(c.getColumnIndex(KEY_LEGALITY)); c.close(); return legality; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param setCode * @param mDb * @return * @throws FamiliarDbException */ public static String getTcgName(String setCode, SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT " + KEY_NAME_TCGPLAYER + " FROM " + DATABASE_TABLE_SETS + " WHERE " + KEY_CODE + " = '" + setCode.replace("'", "''") + "';"; Cursor c = mDb.rawQuery(sql, null); c.moveToFirst(); /* Some users had this cursor come up empty. I couldn't replicate. This is safe */ if (c.getCount() == 0) { c.close(); return ""; } String tcgName = c.getString(c.getColumnIndex(KEY_NAME_TCGPLAYER)); c.close(); return tcgName; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param setName * @param mDb * @return * @throws FamiliarDbException */ private static boolean isModernLegalSet(String setName, SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT " + KEY_SET + " FROM " + DATABASE_TABLE_LEGAL_SETS + " WHERE " + KEY_SET + " = '" + setName.replace("'", "''") + "';"; Cursor c = mDb.rawQuery(sql, null); boolean isModernLegal = (c.getCount() >= 1); c.close(); return isModernLegal; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param category * @param subcategory * @param mDb * @return * @throws FamiliarDbException */ public static Cursor getRules(int category, int subcategory, SQLiteDatabase mDb) throws FamiliarDbException { try { if (category == -1) { // No category specified; return the main categories String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_SUBCATEGORY + " = -1"; return mDb.rawQuery(sql, null); } else if (subcategory == -1) { // No subcategory specified; return the subcategories under the given category String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " > -1 AND " + KEY_ENTRY + " IS NULL"; return mDb.rawQuery(sql, null); } else { // Both specified; return the rules under the given subcategory String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory) + " AND " + KEY_ENTRY + " IS NOT NULL"; return mDb.rawQuery(sql, null); } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param keyword * @param category * @param subcategory * @param mDb * @return * @throws FamiliarDbException */ public static Cursor getRulesByKeyword(String keyword, int category, int subcategory, SQLiteDatabase mDb) throws FamiliarDbException { try { // Don't let them pass in an empty string; it'll return ALL the // rules if (keyword != null && !keyword.trim().equals("")) { keyword = "'%" + keyword.replace("'", "''") + "%'"; if (category == -1) { // No category; we're searching from the main page, so no // restrictions String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_RULE_TEXT + " LIKE " + keyword + " AND " + KEY_ENTRY + " IS NOT NULL"; return mDb.rawQuery(sql, null); } else if (subcategory == -1) { // No subcategory; we're searching from a category page, so // restrict // within that String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_RULE_TEXT + " LIKE " + keyword + " AND " + KEY_ENTRY + " IS NOT NULL AND " + KEY_CATEGORY + " = " + String.valueOf(category); return mDb.rawQuery(sql, null); } else { // We're searching within a subcategory, so restrict within // that String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_RULE_TEXT + " LIKE " + keyword + " AND " + KEY_ENTRY + " IS NOT NULL AND " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory); return mDb.rawQuery(sql, null); } } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return null; } /** * @param category * @param subcategory * @param entry * @param mDb * @return * @throws FamiliarDbException */ public static int getRulePosition(int category, int subcategory, String entry, SQLiteDatabase mDb) throws FamiliarDbException { try { if (entry != null) { String sql = "SELECT " + KEY_POSITION + " FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory) + " AND " + KEY_ENTRY + " = '" + entry.replace("'", "''") + "'"; Cursor c = mDb.rawQuery(sql, null); if (c != null) { c.moveToFirst(); int result = c.getInt(c.getColumnIndex(KEY_POSITION)); c.close(); return result; } } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return 0; } /** * @param category * @param subcategory * @param mDb * @return * @throws FamiliarDbException */ public static String getCategoryName(int category, int subcategory, SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT " + KEY_RULE_TEXT + " FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory) + " AND " + KEY_ENTRY + " IS NULL"; Cursor c = mDb.rawQuery(sql, null); if (c != null) { c.moveToFirst(); String result = c.getString(c.getColumnIndex(KEY_RULE_TEXT)); c.close(); return result; } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return ""; } /** * @param mDb * @return * @throws FamiliarDbException */ public static Cursor getGlossaryTerms(SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT * FROM " + DATABASE_TABLE_GLOSSARY; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @param format * @return * @throws FamiliarDbException */ public static Cursor getBannedCards(SQLiteDatabase mDb, String format) throws FamiliarDbException { try { String sql = "SELECT " + KEY_LEGALITY + ", GROUP_CONCAT(" + KEY_NAME + ", '<br>') AS " + KEY_BANNED_LIST + " FROM " + DATABASE_TABLE_BANNED_CARDS + " WHERE " + KEY_FORMAT + " = '" + format + "'" + " GROUP BY " + KEY_LEGALITY; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @param format * @return * @throws FamiliarDbException */ public static Cursor getLegalSets(SQLiteDatabase mDb, String format) throws FamiliarDbException { try { String sql = "SELECT GROUP_CONCAT(" + DATABASE_TABLE_SETS +"."+KEY_NAME + ", '<br>') AS " + KEY_LEGAL_SETS + " FROM (" + DATABASE_TABLE_LEGAL_SETS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_LEGAL_SETS +"."+KEY_SET+" = "+DATABASE_TABLE_SETS+"."+KEY_CODE + ")" + " WHERE " + DATABASE_TABLE_LEGAL_SETS + "." + KEY_FORMAT + " = '" + format + "'"; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @throws FamiliarDbException */ public static void dropRulesTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_RULES); mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_GLOSSARY); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @throws FamiliarDbException */ public static void createRulesTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL(DATABASE_CREATE_RULES); mDb.execSQL(DATABASE_CREATE_GLOSSARY); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param category * @param subcategory * @param entry * @param text * @param position * @param mDb * @throws FamiliarDbException */ public static void insertRule(int category, int subcategory, String entry, String text, int position, SQLiteDatabase mDb) throws FamiliarDbException { if (entry == null) { entry = "NULL"; } else { entry = "'" + entry.replace("'", "''") + "'"; } text = "'" + text.replace("'", "''") + "'"; String positionStr; if (position < 0) { positionStr = "NULL"; } else { positionStr = String.valueOf(position); } String sql = "INSERT INTO " + DATABASE_TABLE_RULES + " (" + KEY_CATEGORY + ", " + KEY_SUBCATEGORY + ", " + KEY_ENTRY + ", " + KEY_RULE_TEXT + ", " + KEY_POSITION + ") VALUES (" + String.valueOf(category) + ", " + String.valueOf(subcategory) + ", " + entry + ", " + text + ", " + positionStr + ");"; try { mDb.execSQL(sql); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param term * @param definition * @param mDb * @throws FamiliarDbException */ public static void insertGlossaryTerm(String term, String definition, SQLiteDatabase mDb) throws FamiliarDbException { term = "'" + term.replace("'", "''") + "'"; definition = "'" + definition.replace("'", "''") + "'"; String sql = "INSERT INTO " + DATABASE_TABLE_GLOSSARY + " (" + KEY_TERM + ", " + KEY_DEFINITION + ") VALUES (" + term + ", " + definition + ");"; try { mDb.execSQL(sql); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * Builds a map for all columns that may be requested, which will be given * to the SQLiteQueryBuilder. This is a good way to define aliases for * column names, but must include all columns, even if the value is the key. * This allows the ContentProvider to request columns w/o the need to know * real column names and create the alias itself. * * @return */ private static HashMap<String, String> buildColumnMap() { HashMap<String, String> map = new HashMap<String, String>(); map.put(KEY_NAME, KEY_NAME); map.put(BaseColumns._ID, "rowid AS " + BaseColumns._ID); map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); return map; } /** * @param selection The selection clause * @param selectionArgs Selection arguments for "?" components in the selection * @param columns The columns to return * @param mDb * @return A Cursor over all rows matching the query * @throws FamiliarDbException */ private static Cursor query(String selection, String[] selectionArgs, String[] columns, SQLiteDatabase mDb) throws FamiliarDbException { /* * The SQLiteBuilder provides a map for all possible columns requested * to actual columns in the database, creating a simple column alias * mechanism by which the ContentProvider does not need to know the real * column names */ SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables(DATABASE_TABLE_CARDS); builder.setProjectionMap(mColumnMap); Cursor cursor; try { cursor = builder.query(mDb, columns, selection, selectionArgs, KEY_NAME, null, KEY_NAME); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (cursor != null && !cursor.moveToFirst()) { cursor.close(); return null; } return cursor; } /** * Returns a Cursor positioned at the word specified by rowId * * @param rowId id of word to retrieve * @param columns The columns to include, if null then all are included * @param mDb * @return Cursor positioned to matching word, or null if not found. * @throws FamiliarDbException */ public static Cursor getCardByRowId(String rowId, String[] columns, SQLiteDatabase mDb) throws FamiliarDbException { String selection = "rowid = ?"; String[] selectionArgs = new String[]{rowId}; return query(selection, selectionArgs, columns, mDb); /* * This builds a query that looks like: SELECT <columns> FROM <table> * WHERE rowid = <rowId> */ } /** * Returns a Cursor over all words that match the given query * * @param query The string to search for * @param mDb * @return Cursor over all words that match, or null if none found. * @throws FamiliarDbException */ public static Cursor getCardsByNamePrefix(String query, SQLiteDatabase mDb) throws FamiliarDbException { try { query = query.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]).trim(); String convert = query.toLowerCase().replace("ae", String.valueOf(Character.toChars(0xC6)[0])); if (query.length() < 2) { return null; } String sql = "SELECT * FROM (" + "SELECT " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " AS " + KEY_NAME + ", " + DATABASE_TABLE_CARDS + "." + KEY_ID + " AS " + KEY_ID + ", " + DATABASE_TABLE_CARDS + "." + KEY_ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID + " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '" + query + "%'" + " OR " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '" + convert + "%'" + " ORDER BY " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " COLLATE UNICODE, " + DATABASE_TABLE_SETS + "." + KEY_DATE + " ASC " + ") GROUP BY " + KEY_NAME; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param ctx * @return */ public static boolean isDbOutOfDate(Context ctx) { SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(ctx); String dbPath = ctx.getFilesDir().getPath(); dbPath = dbPath.substring(0, dbPath.lastIndexOf("/")) + "/databases"; File f = new File(dbPath, DB_NAME); int dbVersion = preferences.getInt("databaseVersion", -1); return (!f.exists() || f.length() < 1048576 || dbVersion < CardDbAdapter.DATABASE_VERSION); } /** * @param ctx */ public static void copyDB(Context ctx) { SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(ctx); SharedPreferences.Editor editor = preferences.edit(); try { String dbPath = ctx.getFilesDir().getPath(); dbPath = dbPath.substring(0, dbPath.lastIndexOf("/")) + "/databases"; File folder = new File(dbPath); if (!folder.exists()) { folder.mkdir(); } File dbFile = new File(folder, DB_NAME); if (dbFile.exists()) { dbFile.delete(); editor.putString("lastUpdate", ""); editor.putInt("databaseVersion", -1); editor.apply(); } if (!dbFile.exists()) { GZIPInputStream gis = new GZIPInputStream(ctx.getResources().openRawResource(R.raw.datagz)); FileOutputStream fos = new FileOutputStream(dbFile); byte[] buffer = new byte[1024]; int length; while ((length = gis.read(buffer)) > 0) { fos.write(buffer, 0, length); } editor.putInt("databaseVersion", CardDbAdapter.DATABASE_VERSION); editor.apply(); // Close the streams fos.flush(); fos.close(); gis.close(); } } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * @param name * @param mSetCode * @param mDb @return * @throws FamiliarDbException */ public static int getSplitMultiverseID(String name, String setCode, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String statement = "SELECT " + KEY_MULTIVERSEID + " from " + DATABASE_TABLE_CARDS + " WHERE " + KEY_NAME + " = '" + name + "' AND " + KEY_SET + " = '" + setCode + "'"; try { c = mDb.rawQuery(statement, null); if (c.getCount() > 0) { c.moveToFirst(); int retVal = c.getInt(c.getColumnIndex(KEY_MULTIVERSEID)); c.close(); return retVal; } else { c.close(); return -1; } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param multiverseId * @param mDb * @return * @throws FamiliarDbException */ public static String getSplitName(int multiverseId, boolean ascending, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String statement = "SELECT " + KEY_NAME + ", " + KEY_NUMBER + " from " + DATABASE_TABLE_CARDS + " WHERE " + KEY_MULTIVERSEID + " = " + multiverseId + " ORDER BY " + KEY_NUMBER; if (ascending) { statement += " ASC"; } else { statement += " DESC"; } try { c = mDb.rawQuery(statement, null); if (c.getCount() == 2) { c.moveToFirst(); String retVal = c.getString(c .getColumnIndex(KEY_NAME)); retVal += " // "; c.moveToNext(); retVal += c.getString(c.getColumnIndex(KEY_NAME)); c.close(); return retVal; } else { c.close(); return null; } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param s * @return */ public static String removeAccentMarks(String s) { return s.replace(Character.toChars(0xC0)[0] + "", "A") .replace(Character.toChars(0xC1)[0] + "", "A") .replace(Character.toChars(0xC2)[0] + "", "A") .replace(Character.toChars(0xC3)[0] + "", "A") .replace(Character.toChars(0xC4)[0] + "", "A") .replace(Character.toChars(0xC5)[0] + "", "A") .replace(Character.toChars(0xC6)[0] + "", "Ae") .replace(Character.toChars(0xC7)[0] + "", "C") .replace(Character.toChars(0xC8)[0] + "", "E") .replace(Character.toChars(0xC9)[0] + "", "E") .replace(Character.toChars(0xCA)[0] + "", "E") .replace(Character.toChars(0xCB)[0] + "", "E") .replace(Character.toChars(0xCC)[0] + "", "I") .replace(Character.toChars(0xCD)[0] + "", "I") .replace(Character.toChars(0xCE)[0] + "", "I") .replace(Character.toChars(0xCF)[0] + "", "I") .replace(Character.toChars(0xD0)[0] + "", "D") .replace(Character.toChars(0xD1)[0] + "", "N") .replace(Character.toChars(0xD2)[0] + "", "O") .replace(Character.toChars(0xD3)[0] + "", "O") .replace(Character.toChars(0xD4)[0] + "", "O") .replace(Character.toChars(0xD5)[0] + "", "O") .replace(Character.toChars(0xD6)[0] + "", "O") .replace(Character.toChars(0xD7)[0] + "", "x") .replace(Character.toChars(0xD8)[0] + "", "O") .replace(Character.toChars(0xD9)[0] + "", "U") .replace(Character.toChars(0xDA)[0] + "", "U") .replace(Character.toChars(0xDB)[0] + "", "U") .replace(Character.toChars(0xDC)[0] + "", "U") .replace(Character.toChars(0xDD)[0] + "", "Y") .replace(Character.toChars(0xE0)[0] + "", "a") .replace(Character.toChars(0xE1)[0] + "", "a") .replace(Character.toChars(0xE2)[0] + "", "a") .replace(Character.toChars(0xE3)[0] + "", "a") .replace(Character.toChars(0xE4)[0] + "", "a") .replace(Character.toChars(0xE5)[0] + "", "a") .replace(Character.toChars(0xE6)[0] + "", "ae") .replace(Character.toChars(0xE7)[0] + "", "c") .replace(Character.toChars(0xE8)[0] + "", "e") .replace(Character.toChars(0xE9)[0] + "", "e") .replace(Character.toChars(0xEA)[0] + "", "e") .replace(Character.toChars(0xEB)[0] + "", "e") .replace(Character.toChars(0xEC)[0] + "", "i") .replace(Character.toChars(0xED)[0] + "", "i") .replace(Character.toChars(0xEE)[0] + "", "i") .replace(Character.toChars(0xEF)[0] + "", "i") .replace(Character.toChars(0xF1)[0] + "", "n") .replace(Character.toChars(0xF2)[0] + "", "o") .replace(Character.toChars(0xF3)[0] + "", "o") .replace(Character.toChars(0xF4)[0] + "", "o") .replace(Character.toChars(0xF5)[0] + "", "o") .replace(Character.toChars(0xF6)[0] + "", "o") .replace(Character.toChars(0xF8)[0] + "", "o") .replace(Character.toChars(0xF9)[0] + "", "u") .replace(Character.toChars(0xFA)[0] + "", "u") .replace(Character.toChars(0xFB)[0] + "", "u") .replace(Character.toChars(0xFC)[0] + "", "u") .replace(Character.toChars(0xFD)[0] + "", "y") .replace(Character.toChars(0xFF)[0] + "", "y"); } /** * @param number * @param setCode * @return */ public static int isMultiCard(String number, String setCode) { if (number.contains("a") || number.contains("b")) { if (setCode.compareTo("ISD") == 0 || setCode.compareTo("DKA") == 0) { return TRANSFORM; } else if (setCode.compareTo("DGM") == 0) { return FUSE; } else { return SPLIT; } } return NOPE; } /** * @param setCode * @param mDb * @return * @throws FamiliarDbException */ public static boolean canBeFoil(String setCode, SQLiteDatabase mDb) throws FamiliarDbException { String[] extraSets = {"UNH", "UL", "UD", "MM", "NE", "PY", "IN", "PS", "7E", "AP", "OD", "TO", "JU", "ON", "LE", "SC", "CNS", "CNSC"}; ArrayList<String> nonModernLegalSets = new ArrayList<String>(Arrays.asList(extraSets)); for (String value : nonModernLegalSets) { if (value.equals(setCode)) { return true; } } return isModernLegalSet(setCode, mDb); } }
MTGFamiliar/src/main/java/com/gelakinetic/mtgfam/helpers/database/CardDbAdapter.java
/** Copyright 2011 Adam Feinstein This file is part of MTG Familiar. MTG Familiar is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MTG Familiar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MTG Familiar. If not, see <http://www.gnu.org/licenses/>. */ package com.gelakinetic.mtgfam.helpers.database; import android.app.SearchManager; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources.NotFoundException; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteQueryBuilder; import android.preference.PreferenceManager; import android.provider.BaseColumns; import com.gelakinetic.mtgfam.R; import com.gelakinetic.mtgfam.helpers.MtgCard; import com.gelakinetic.mtgfam.helpers.MtgSet; import com.gelakinetic.mtgfam.helpers.WishlistHelpers.CompressedWishlistInfo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.zip.GZIPInputStream; /** * Simple Cards database access helper class. Defines the basic CRUD operations * and gives the ability to list all Cards as well as retrieve or modify a * specific Card. */ public class CardDbAdapter { public static final int STAR = -1000; public static final int ONE_PLUS_STAR = -1001; public static final int TWO_PLUS_STAR = -1002; public static final int SEVEN_MINUS_STAR = -1003; public static final int STAR_SQUARED = -1004; public static final int NO_ONE_CARES = -1005; public static final int MOST_RECENT_PRINTING = 0; public static final int FIRST_PRINTING = 1; public static final int ALL_PRINTINGS = 2; public static final String DATABASE_NAME = "data"; public static final String DATABASE_TABLE_CARDS = "cards"; public static final String DATABASE_TABLE_SETS = "sets"; private static final String DATABASE_TABLE_FORMATS = "formats"; private static final String DATABASE_TABLE_LEGAL_SETS = "legal_sets"; private static final String DATABASE_TABLE_BANNED_CARDS = "banned_cards"; private static final String DATABASE_TABLE_RULES = "rules"; private static final String DATABASE_TABLE_GLOSSARY = "glossary"; public static final int DATABASE_VERSION = 49; public static final String KEY_ID = "_id"; public static final String KEY_NAME = SearchManager.SUGGEST_COLUMN_TEXT_1; // "name"; public static final String KEY_SET = "expansion"; public static final String KEY_TYPE = "type"; public static final String KEY_ABILITY = "cardtext"; public static final String KEY_COLOR = "color"; public static final String KEY_MANACOST = "manacost"; public static final String KEY_CMC = "cmc"; public static final String KEY_POWER = "power"; public static final String KEY_TOUGHNESS = "toughness"; public static final String KEY_RARITY = "rarity"; public static final String KEY_LOYALTY = "loyalty"; public static final String KEY_FLAVOR = "flavor"; public static final String KEY_ARTIST = "artist"; public static final String KEY_NUMBER = "number"; public static final String KEY_MULTIVERSEID = "multiverseID"; private static final String KEY_RULINGS = "rulings"; public static final String KEY_CODE = "code"; private static final String KEY_CODE_MTGI = "code_mtgi"; public static final String KEY_NAME_TCGPLAYER = "name_tcgplayer"; private static final String KEY_DATE = "date"; public static final String KEY_FORMAT = "format"; public static final String KEY_LEGALITY = "legality"; public static final String KEY_CATEGORY = "category"; public static final String KEY_SUBCATEGORY = "subcategory"; public static final String KEY_ENTRY = "entry"; public static final String KEY_RULE_TEXT = "rule_text"; private static final String KEY_POSITION = "position"; public static final String KEY_TERM = "term"; public static final String KEY_DEFINITION = "definition"; public static final String KEY_BANNED_LIST = "banned_list"; public static final String KEY_LEGAL_SETS = "legal_sets"; public static final String[] allData = {DATABASE_TABLE_CARDS + "." + KEY_ID, DATABASE_TABLE_CARDS + "." + KEY_NAME, DATABASE_TABLE_CARDS + "." + KEY_SET, DATABASE_TABLE_CARDS + "." + KEY_NUMBER, DATABASE_TABLE_CARDS + "." + KEY_TYPE, DATABASE_TABLE_CARDS + "." + KEY_MANACOST, DATABASE_TABLE_CARDS + "." + KEY_ABILITY, DATABASE_TABLE_CARDS + "." + KEY_POWER, DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS, DATABASE_TABLE_CARDS + "." + KEY_LOYALTY, DATABASE_TABLE_CARDS + "." + KEY_RARITY, DATABASE_TABLE_CARDS + "." + KEY_FLAVOR, DATABASE_TABLE_CARDS + "." + KEY_CMC, DATABASE_TABLE_CARDS + "." + KEY_COLOR }; public static final String DATABASE_CREATE_CARDS = "create table " + DATABASE_TABLE_CARDS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_SET + " text not null, " + KEY_TYPE + " text not null, " + KEY_RARITY + " integer, " + KEY_MANACOST + " text, " + KEY_CMC + " integer not null, " + KEY_POWER + " real, " + KEY_TOUGHNESS + " real, " + KEY_LOYALTY + " integer, " + KEY_ABILITY + " text, " + KEY_FLAVOR + " text, " + KEY_ARTIST + " text, " + KEY_NUMBER + " text, " + KEY_MULTIVERSEID + " integer not null, " + KEY_COLOR + " text not null, " + KEY_RULINGS + " text);"; public static final String DATABASE_CREATE_SETS = "create table " + DATABASE_TABLE_SETS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_CODE + " text not null unique, " + KEY_CODE_MTGI + " text not null, " + KEY_NAME_TCGPLAYER + " text, " + KEY_DATE + " integer);"; private static final String DATABASE_CREATE_FORMATS = "create table " + DATABASE_TABLE_FORMATS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null);"; private static final String DATABASE_CREATE_LEGAL_SETS = "create table " + DATABASE_TABLE_LEGAL_SETS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_SET + " text not null, " + KEY_FORMAT + " text not null);"; private static final String DATABASE_CREATE_BANNED_CARDS = "create table " + DATABASE_TABLE_BANNED_CARDS + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_LEGALITY + " integer not null, " + KEY_FORMAT + " text not null);"; private static final String DATABASE_CREATE_RULES = "create table " + DATABASE_TABLE_RULES + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_CATEGORY + " integer not null, " + KEY_SUBCATEGORY + " integer not null, " + KEY_ENTRY + " text null, " + KEY_RULE_TEXT + " text not null, " + KEY_POSITION + " integer null);"; private static final String DATABASE_CREATE_GLOSSARY = "create table " + DATABASE_TABLE_GLOSSARY + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_TERM + " text not null, " + KEY_DEFINITION + " text not null);"; private static final String EXCLUDE_TOKEN = "!"; private static final int EXCLUDE_TOKEN_START = 1; public static final int LEGAL = 0; public static final int BANNED = 1; public static final int RESTRICTED = 2; // use a hash map for performance private static final HashMap<String, String> mColumnMap = buildColumnMap(); private static final String DB_NAME = "data"; public static final int NOPE = 0; public static final int TRANSFORM = 1; public static final int FUSE = 2; public static final int SPLIT = 3; /** * @param sqLiteDatabase * @throws FamiliarDbException */ public static void dropCreateDB(SQLiteDatabase sqLiteDatabase) throws FamiliarDbException { try { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_CARDS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SETS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_FORMATS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_LEGAL_SETS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_BANNED_CARDS); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_RULES); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_GLOSSARY); sqLiteDatabase.execSQL(DATABASE_CREATE_CARDS); sqLiteDatabase.execSQL(DATABASE_CREATE_SETS); sqLiteDatabase.execSQL(DATABASE_CREATE_FORMATS); sqLiteDatabase.execSQL(DATABASE_CREATE_LEGAL_SETS); sqLiteDatabase.execSQL(DATABASE_CREATE_BANNED_CARDS); sqLiteDatabase.execSQL(DATABASE_CREATE_RULES); sqLiteDatabase.execSQL(DATABASE_CREATE_GLOSSARY); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param c * @param mDb * @return */ public static void createCard(MtgCard c, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, c.name); initialValues.put(KEY_SET, c.set); initialValues.put(KEY_TYPE, c.type); initialValues.put(KEY_RARITY, (int) c.rarity); initialValues.put(KEY_MANACOST, c.manaCost); initialValues.put(KEY_CMC, c.cmc); initialValues.put(KEY_POWER, c.power); initialValues.put(KEY_TOUGHNESS, c.toughness); initialValues.put(KEY_LOYALTY, c.loyalty); initialValues.put(KEY_ABILITY, c.ability); initialValues.put(KEY_FLAVOR, c.flavor); initialValues.put(KEY_ARTIST, c.artist); initialValues.put(KEY_NUMBER, c.number); initialValues.put(KEY_COLOR, c.color); initialValues.put(KEY_MULTIVERSEID, c.multiverseId); mDb.insert(DATABASE_TABLE_CARDS, null, initialValues); } /** * @param set * @param mDb * @return */ public static void createSet(MtgSet set, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_CODE, set.code); initialValues.put(KEY_NAME, set.name); initialValues.put(KEY_CODE_MTGI, set.codeMagicCards); initialValues.put(KEY_DATE, set.date); mDb.insert(DATABASE_TABLE_SETS, null, initialValues); } /** * @param name * @param code * @param mDb * @return */ public static void addTcgName(String name, String code, SQLiteDatabase mDb) { ContentValues args = new ContentValues(); args.put(KEY_NAME_TCGPLAYER, name); mDb.update(DATABASE_TABLE_SETS, args, KEY_CODE + " = '" + code + "'", null); } /** * @param sqLiteDatabase * @return * @throws FamiliarDbException */ public static Cursor fetchAllSets(SQLiteDatabase sqLiteDatabase) throws FamiliarDbException { Cursor c; try { c = sqLiteDatabase.query(DATABASE_TABLE_SETS, new String[]{KEY_ID, KEY_NAME, KEY_CODE, KEY_CODE_MTGI}, null, null, null, null, KEY_DATE + " DESC"); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } catch (NullPointerException e) { throw new FamiliarDbException(e); } return c; } /** * @param code * @param mDb * @return * @throws FamiliarDbException */ public static boolean doesSetExist(String code, SQLiteDatabase mDb) throws FamiliarDbException { String statement = "(" + KEY_CODE + " = '" + code + "')"; Cursor c; int count; try { c = mDb.query(true, DATABASE_TABLE_SETS, new String[]{KEY_ID}, statement, null, null, null, KEY_NAME, null); count = c.getCount(); c.close(); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return count > 0; } /** * @param code * @param mDb * @return * @throws FamiliarDbException */ public static String getCodeMtgi(String code, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; try { c = mDb.query(DATABASE_TABLE_SETS, new String[]{KEY_CODE_MTGI}, KEY_CODE + "=\"" + code + "\"", null, null, null, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } c.moveToFirst(); String returnVal = c.getString(c.getColumnIndex(KEY_CODE_MTGI)); c.close(); return returnVal; } /** * @param id * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchCard(long id, SQLiteDatabase mDb) throws FamiliarDbException { String columns[] = new String[]{KEY_ID, KEY_NAME, KEY_SET, KEY_TYPE, KEY_RARITY, KEY_MANACOST, KEY_CMC, KEY_POWER, KEY_TOUGHNESS, KEY_LOYALTY, KEY_ABILITY, KEY_FLAVOR, KEY_ARTIST, KEY_NUMBER, KEY_COLOR, KEY_MULTIVERSEID}; Cursor c; try { c = mDb.query(true, DATABASE_TABLE_CARDS, columns, KEY_ID + "=" + id, null, null, null, KEY_NAME, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param name * @param fields * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchCardByName(String name, String[] fields, SQLiteDatabase mDb) throws FamiliarDbException { // replace lowercase ae with Ae name = name.replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); String sql = "SELECT "; boolean first = true; for (String field : fields) { if (first) { first = false; } else { sql += ", "; } sql += field; } sql += " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(name) + " GROUP BY " + DATABASE_TABLE_SETS + "." + KEY_CODE + " ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC"; Cursor c; try { c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param mCompressedWishlist * @param mDb * @throws FamiliarDbException */ public static void fillExtraWishlistData(ArrayList<CompressedWishlistInfo> mCompressedWishlist, SQLiteDatabase mDb) throws FamiliarDbException { String sql = "SELECT "; boolean first = true; for (String field : CardDbAdapter.allData) { if (first) { first = false; } else { sql += ", "; } sql += field; } sql += " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE ("; first = true; boolean doSql = false; for (CompressedWishlistInfo cwi : mCompressedWishlist) { if (cwi.mCard.type == null || cwi.mCard.type.equals("")) { doSql = true; if (first) { first = false; } else { sql += " OR "; } if (cwi.mCard.setCode != null && !cwi.mCard.setCode.equals("")) { sql += "(" + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(cwi.mCard.name) + " AND " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = '" + cwi.mCard.setCode + "')"; } else { sql += "(" + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(cwi.mCard.name) + ")"; } } } if (!doSql) { return; } sql += ")"; /* ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC */ Cursor cursor; try { cursor = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (cursor != null) { cursor.moveToFirst(); } else { return; } while (!cursor.isAfterLast()) { /* Do stuff */ String name = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_NAME)); for (CompressedWishlistInfo cwi : mCompressedWishlist) { if (name != null && name.equals(cwi.mCard.name)) { cwi.mCard.type = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_TYPE)); cwi.mCard.rarity = (char) cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_RARITY)); cwi.mCard.manaCost = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_MANACOST)); cwi.mCard.power = cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_POWER)); cwi.mCard.toughness = cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_TOUGHNESS)); cwi.mCard.loyalty = cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_LOYALTY)); cwi.mCard.ability = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_ABILITY)); cwi.mCard.flavor = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_FLAVOR)); cwi.mCard.number = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_NUMBER)); cwi.mCard.cmc = cursor.getInt((cursor.getColumnIndex(CardDbAdapter.KEY_CMC))); cwi.mCard.color = cursor.getString(cursor.getColumnIndex(CardDbAdapter.KEY_COLOR)); } } /* NEXT! */ cursor.moveToNext(); } /* Use the cursor to populate stuff */ cursor.close(); } /** * @param name * @param setCode * @param fields * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchCardByNameAndSet(String name, String setCode, String[] fields, SQLiteDatabase mDb) throws FamiliarDbException { // replace lowercase ae with Ae name = name.replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); String sql = "SELECT "; boolean first = true; for (String field : fields) { if (first) { first = false; } else { sql += ", "; } sql += field; } sql += " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(name) + " AND " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = '" + setCode + "' ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC"; Cursor c; try { c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param name * @param mDb * @return * @throws FamiliarDbException */ public static long fetchIdByName(String name, SQLiteDatabase mDb) throws FamiliarDbException { // replace lowercase ae with Ae name = name.replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); String sql = "SELECT " + DATABASE_TABLE_CARDS + "." + KEY_ID + ", " + DATABASE_TABLE_CARDS + "." + KEY_SET + ", " + DATABASE_TABLE_SETS + "." + KEY_DATE + " FROM (" + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_CARDS + "." + KEY_SET + "=" + DATABASE_TABLE_SETS + "." + KEY_CODE + ")" + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DatabaseUtils.sqlEscapeString(name) + " ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC"; Cursor c; try { c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); long id = c.getLong(c .getColumnIndex(CardDbAdapter.KEY_ID)); c.close(); return id; } return -1; } /** * @param cardname * @param cardtext * @param cardtype * @param color * @param colorlogic * @param sets * @param pow_choice * @param pow_logic * @param tou_choice * @param tou_logic * @param cmc * @param cmcLogic * @param format * @param rarity * @param flavor * @param artist * @param type_logic * @param text_logic * @param set_logic * @param backface * @param returnTypes * @param consolidate * @param mDb * @return * @throws FamiliarDbException */ public static Cursor Search(String cardname, String cardtext, String cardtype, String color, int colorlogic, String sets, float pow_choice, String pow_logic, float tou_choice, String tou_logic, int cmc, String cmcLogic, String format, String rarity, String flavor, String artist, int type_logic, int text_logic, int set_logic, boolean backface, String[] returnTypes, boolean consolidate, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; if (cardname != null) cardname = cardname.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]).trim(); if (cardtext != null) cardtext = cardtext.replace("'", "''").trim(); if (cardtype != null) cardtype = cardtype.replace("'", "''").trim(); if (flavor != null) flavor = flavor.replace("'", "''").trim(); if (artist != null) artist = artist.replace("'", "''").trim(); String statement = " WHERE 1=1"; if (cardname != null) { String[] nameParts = cardname.split(" "); for (String s : nameParts) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '%" + s + "%' OR " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '%" + s.toLowerCase().replace("ae", String.valueOf(Character.toChars(0xC6)[0])) + "%')"; } } /*************************************************************************************/ /** * Reuben's version Differences: Original code is verbose only, but mine * allows for matching exact text, all words, or just any one word. */ if (cardtext != null) { String[] cardTextParts = cardtext.split(" "); // Separate each // individual /** * The following switch statement tests to see which text search * logic was chosen by the user. If they chose the first option (0), * then look for cards with text that includes all words, but not * necessarily the exact phrase. The second option (1) finds cards * that have 1 or more of the chosen words in their text. The third * option (2) searches for the exact phrase as entered by the user. * The 'default' option is impossible via the way the code is * written, but I believe it's also mandatory to include it in case * someone else is perhaps fussing with the code and breaks it. The * if statement at the end is theoretically unnecessary, because * once we've entered the current if statement, there is no way to * NOT change the statement variable. However, you never really know * who's going to break open your code and fuss around with it, so * it's always good to leave some small safety measures. */ switch (text_logic) { case 0: for (String s : cardTextParts) { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " NOT LIKE '%" + s.substring(EXCLUDE_TOKEN_START) + "%')"; else statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + s + "%')"; } break; case 1: boolean firstRun = true; for (String s : cardTextParts) { if (firstRun) { firstRun = false; if (s.contains(EXCLUDE_TOKEN)) statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " NOT LIKE '%" + s.substring(EXCLUDE_TOKEN_START) + "%')"; else statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + s + "%')"; } else { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " NOT LIKE '%" + s.substring(EXCLUDE_TOKEN_START) + "%')"; else statement += " OR (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + s + "%')"; } } statement += ")"; break; case 2: statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ABILITY + " LIKE '%" + cardtext + "%')"; break; default: break; } } /** End Reuben's version */ /** * Reuben's version Differences: Original version only allowed for * including all types, not any of the types or excluding the given * types. */ String supertypes = null; String subtypes = null; if (cardtype != null && !cardtype.equals("-")) { boolean containsSupertype = true; if (cardtype.substring(0, 2).equals("- ")) { containsSupertype = false; } String[] split = cardtype.split(" - "); if (split.length >= 2) { supertypes = split[0].replace(" -", ""); subtypes = split[1].replace(" -", ""); } else if (containsSupertype) { supertypes = cardtype.replace(" -", ""); } else { subtypes = cardtype.replace("- ", ""); } } if (supertypes != null) { String[] supertypesParts = supertypes.split(" "); // Separate each // individual switch (type_logic) { case 0: for (String s : supertypesParts) { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } break; case 1: boolean firstRun = true; for (String s : supertypesParts) { if (firstRun) { firstRun = false; if (s.contains(EXCLUDE_TOKEN)) statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } else if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " OR (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } statement += ")"; break; case 2: for (String s : supertypesParts) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s + "%')"; } break; default: break; } } if (subtypes != null) { String[] subtypesParts = subtypes.split(" "); // Separate each // individual switch (type_logic) { case 0: for (String s : subtypesParts) { if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } break; case 1: boolean firstRun = true; for (String s : subtypesParts) { if (firstRun) { firstRun = false; if (s.contains(EXCLUDE_TOKEN)) statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " AND ((" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } else if (s.contains(EXCLUDE_TOKEN)) statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s.substring(1) + "%')"; else statement += " OR (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " LIKE '%" + s + "%')"; } statement += ")"; break; case 2: for (String s : subtypesParts) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%" + s + "%')"; } break; default: break; } } /** End Reuben's version */ /*************************************************************************************/ if (flavor != null) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_FLAVOR + " LIKE '%" + flavor + "%')"; } if (artist != null) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_ARTIST + " LIKE '%" + artist + "%')"; } /*************************************************************************************/ /** * Code below added/modified by Reuben. Differences: Original version * only had 'Any' and 'All' options and lacked 'Exclusive' and 'Exact' * matching. In addition, original programming only provided exclusive * results. */ if (!(color.equals("wubrgl") || (color.equals("WUBRGL") && colorlogic == 0))) { boolean firstPrint = true; // Can't contain these colors /** * ...if the chosen color logic was exactly (2) or none (3) of the * selected colors */ if (colorlogic > 1) // if colorlogic is 2 or 3 it will be greater // than 1 { statement += " AND (("; for (byte b : color.getBytes()) { char ch = (char) b; if (ch > 'a') { if (firstPrint) firstPrint = false; else statement += " AND "; if (ch == 'l' || ch == 'L') statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " NOT GLOB '[CLA]'"; else statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " NOT LIKE '%" + Character.toUpperCase(ch) + "%'"; } } statement += ") AND ("; } firstPrint = true; // Might contain these colors if (colorlogic < 2) statement += " AND ("; for (byte b : color.getBytes()) { char ch = (char) b; if (ch < 'a') { if (firstPrint) firstPrint = false; else { if (colorlogic == 1 || colorlogic == 3) statement += " AND "; else statement += " OR "; } if (ch == 'l' || ch == 'L') statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " GLOB '[CLA]'"; else statement += DATABASE_TABLE_CARDS + "." + KEY_COLOR + " LIKE '%" + ch + "%'"; } } if (colorlogic > 1) statement += "))"; else statement += ")"; } /** End of addition */ /*************************************************************************************/ if (sets != null) { statement += " AND ("; boolean first = true; for (String s : sets.split("-")) { if (first) { first = false; } else { statement += " OR "; } statement += DATABASE_TABLE_CARDS + "." + KEY_SET + " = '" + s + "'"; } statement += ")"; } if (pow_choice != NO_ONE_CARES) { statement += " AND ("; if (pow_choice > STAR) { statement += DATABASE_TABLE_CARDS + "." + KEY_POWER + " " + pow_logic + " " + pow_choice; if (pow_logic.equals("<")) { statement += " AND " + DATABASE_TABLE_CARDS + "." + KEY_POWER + " > " + STAR; } } else if (pow_logic.equals("=")) { statement += DATABASE_TABLE_CARDS + "." + KEY_POWER + " " + pow_logic + " " + pow_choice; } statement += ")"; } if (tou_choice != NO_ONE_CARES) { statement += " AND ("; if (tou_choice > STAR) { statement += DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS + " " + tou_logic + " " + tou_choice; if (tou_logic.equals("<")) { statement += " AND " + DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS + " > " + STAR; } } else if (tou_logic.equals("=")) { statement += DATABASE_TABLE_CARDS + "." + KEY_TOUGHNESS + " " + tou_logic + " " + tou_choice; } statement += ")"; } if (cmc != -1) { statement += " AND ("; statement += DATABASE_TABLE_CARDS + "." + KEY_CMC + " " + cmcLogic + " " + cmc + ")"; } if (rarity != null) { statement += " AND ("; boolean firstPrint = true; for (int i = 0; i < rarity.length(); i++) { if (firstPrint) { firstPrint = false; } else { statement += " OR "; } statement += DATABASE_TABLE_CARDS + "." + KEY_RARITY + " = " + (int) rarity.toUpperCase().charAt(i) + ""; } statement += ")"; } String tbl = DATABASE_TABLE_CARDS; if (format != null) { /* Check if the format is eternal or not, by the number of legal sets */ String numLegalSetsSql = "SELECT * FROM " + DATABASE_TABLE_LEGAL_SETS + " WHERE " + KEY_FORMAT + " = \"" + format + "\""; Cursor numLegalSetCursor = mDb.rawQuery(numLegalSetsSql, null); /* If the format is not eternal, filter by set */ if (numLegalSetCursor.getCount() > 0) { tbl = "(" + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_LEGAL_SETS + " ON " + DATABASE_TABLE_CARDS + "." + KEY_SET + "=" + DATABASE_TABLE_LEGAL_SETS + "." + KEY_SET + " AND " + DATABASE_TABLE_LEGAL_SETS + "." + KEY_FORMAT + "='" + format + "')"; } else { /* Otherwise filter silver bordered cards, giant cards */ statement += " AND NOT " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = 'UNH'" + " AND NOT " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = 'UG'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Plane %'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Conspiracy%'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Scheme%'" + " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Vanguard%'"; } statement += " AND NOT EXISTS (SELECT * FROM " + DATABASE_TABLE_BANNED_CARDS + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = " + DATABASE_TABLE_BANNED_CARDS + "." + KEY_NAME + " AND " + DATABASE_TABLE_BANNED_CARDS + "." + KEY_FORMAT + " = '" + format + "' AND " + DATABASE_TABLE_BANNED_CARDS + "." + KEY_LEGALITY + " = " + BANNED + ")"; } if (!backface) { statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_NUMBER + " NOT LIKE '%b%')"; } if (set_logic != MOST_RECENT_PRINTING && set_logic != ALL_PRINTINGS) { statement = " JOIN (SELECT iT" + DATABASE_TABLE_CARDS + "." + KEY_NAME + ", MIN(" + DATABASE_TABLE_SETS + "." + KEY_DATE + ") AS " + KEY_DATE + " FROM " + DATABASE_TABLE_CARDS + " AS iT" + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON iT" + DATABASE_TABLE_CARDS + "." + KEY_SET + " = " + DATABASE_TABLE_SETS + "." + KEY_CODE + " GROUP BY iT" + DATABASE_TABLE_CARDS + "." + KEY_NAME + ") AS FirstPrints" + " ON " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " = FirstPrints." + KEY_NAME + statement; if (set_logic == FIRST_PRINTING) statement = " AND " + DATABASE_TABLE_SETS + "." + KEY_DATE + " = FirstPrints." + KEY_DATE + statement; else statement = " AND " + DATABASE_TABLE_SETS + "." + KEY_DATE + " <> FirstPrints." + KEY_DATE + statement; } if (statement.equals(" WHERE 1=1")) { // If the statement is just this, it means we added nothing return null; } try { String sel = null; for (String s : returnTypes) { if (sel == null) { sel = DATABASE_TABLE_CARDS + "." + s + " AS " + s; } else { sel += ", " + DATABASE_TABLE_CARDS + "." + s + " AS " + s; } } sel += ", " + DATABASE_TABLE_SETS + "." + KEY_DATE; String sql = "SELECT * FROM (SELECT " + sel + " FROM " + tbl + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = " + DATABASE_TABLE_SETS + "." + KEY_CODE + statement; if (consolidate) { sql += " ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + ") GROUP BY " + KEY_NAME + " ORDER BY " + KEY_NAME + " COLLATE UNICODE"; } else { sql += " ORDER BY " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " COLLATE UNICODE" + ", " + DATABASE_TABLE_SETS + "." + KEY_DATE + " DESC)"; } c = mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (c != null) { c.moveToFirst(); } return c; } /** * @param set * @param number * @param mDb * @return * @throws FamiliarDbException */ public static int getTransform(String set, String number, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String statement = "(" + KEY_NUMBER + " = '" + number + "') AND (" + KEY_SET + " = '" + set + "')"; try { c = mDb.query(true, DATABASE_TABLE_CARDS, new String[]{KEY_ID}, statement, null, null, null, KEY_ID, null); c.moveToFirst(); int ID = c.getInt(c.getColumnIndex(KEY_ID)); c.close(); return ID; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } catch (CursorIndexOutOfBoundsException e) { return -1; /* The other half doesn't exist... */ } } /** * @param set * @param number * @param mDb * @return * @throws FamiliarDbException */ public static String getTransformName(String set, String number, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String name; String statement = "(" + KEY_NUMBER + " = '" + number + "') AND (" + KEY_SET + " = '" + set + "')"; try { c = mDb.query(true, DATABASE_TABLE_CARDS, new String[]{KEY_NAME}, statement, null, null, null, KEY_NAME, null); c.moveToFirst(); name = c.getString(c.getColumnIndex(KEY_NAME)); c.close(); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return name; } /** * @param mDb * @throws FamiliarDbException */ public static void createLegalTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL(DATABASE_CREATE_FORMATS); mDb.execSQL(DATABASE_CREATE_LEGAL_SETS); mDb.execSQL(DATABASE_CREATE_BANNED_CARDS); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @throws FamiliarDbException */ public static void dropLegalTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_FORMATS); mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_LEGAL_SETS); mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_BANNED_CARDS); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param name * @param mDb * @return */ public static void createFormat(String name, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name); mDb.insert(DATABASE_TABLE_FORMATS, null, initialValues); } /** * @param set * @param format * @param mDb * @return */ public static void addLegalSet(String set, String format, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_SET, set); initialValues.put(KEY_FORMAT, format); mDb.insert(DATABASE_TABLE_LEGAL_SETS, null, initialValues); } /** * @param card * @param format * @param status * @param mDb * @return */ public static void addLegalCard(String card, String format, int status, SQLiteDatabase mDb) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, card); initialValues.put(KEY_LEGALITY, status); initialValues.put(KEY_FORMAT, format); mDb.insert(DATABASE_TABLE_BANNED_CARDS, null, initialValues); } /** * @param mDb * @return * @throws FamiliarDbException */ public static Cursor fetchAllFormats(SQLiteDatabase mDb) throws FamiliarDbException { try { return mDb.query(DATABASE_TABLE_FORMATS, new String[]{KEY_ID, KEY_NAME,}, null, null, null, null, KEY_NAME); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mCardName * @param format * @param mDb * @return * @throws FamiliarDbException */ public static int checkLegality(String mCardName, String format, SQLiteDatabase mDb) throws FamiliarDbException { mCardName = mCardName.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]); format = format.replace("'", "''"); // Just to be safe; remember Bobby // Tables try { // The new way (single query per type, should be much faster) - Alex String sql = "SELECT COALESCE(CASE (SELECT " + KEY_SET + " FROM " + DATABASE_TABLE_CARDS + " WHERE " + KEY_NAME + " = '" + mCardName + "') WHEN 'UG' THEN 1 WHEN 'UNH' THEN 1 WHEN 'ARS' THEN 1 WHEN 'PCP' THEN 1 " + "WHEN 'PP2' THEN 1 ELSE NULL END, " + "CASE (SELECT 1 FROM " + DATABASE_TABLE_CARDS + " c INNER JOIN " + DATABASE_TABLE_LEGAL_SETS + " ls ON ls." + KEY_SET + " = c." + KEY_SET + " WHERE ls." + KEY_FORMAT + " = '" + format + "' AND c." + KEY_NAME + " = '" + mCardName + "') WHEN 1 THEN NULL ELSE CASE WHEN '" + format + "' = 'Legacy' " + "THEN NULL WHEN '" + format + "' = 'Vintage' THEN NULL WHEN '" + format + "' = 'Commander' THEN NULL ELSE 1 END END, (SELECT " + KEY_LEGALITY + " from " + DATABASE_TABLE_BANNED_CARDS + " WHERE " + KEY_NAME + " = '" + mCardName + "' AND " + KEY_FORMAT + " = '" + format + "'), 0) AS " + KEY_LEGALITY; Cursor c = mDb.rawQuery(sql, null); c.moveToFirst(); int legality = c.getInt(c.getColumnIndex(KEY_LEGALITY)); c.close(); return legality; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param setCode * @param mDb * @return * @throws FamiliarDbException */ public static String getTcgName(String setCode, SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT " + KEY_NAME_TCGPLAYER + " FROM " + DATABASE_TABLE_SETS + " WHERE " + KEY_CODE + " = '" + setCode.replace("'", "''") + "';"; Cursor c = mDb.rawQuery(sql, null); c.moveToFirst(); /* Some users had this cursor come up empty. I couldn't replicate. This is safe */ if (c.getCount() == 0) { c.close(); return ""; } String tcgName = c.getString(c.getColumnIndex(KEY_NAME_TCGPLAYER)); c.close(); return tcgName; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param setName * @param mDb * @return * @throws FamiliarDbException */ private static boolean isModernLegalSet(String setName, SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT " + KEY_SET + " FROM " + DATABASE_TABLE_LEGAL_SETS + " WHERE " + KEY_SET + " = '" + setName.replace("'", "''") + "';"; Cursor c = mDb.rawQuery(sql, null); boolean isModernLegal = (c.getCount() >= 1); c.close(); return isModernLegal; } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param category * @param subcategory * @param mDb * @return * @throws FamiliarDbException */ public static Cursor getRules(int category, int subcategory, SQLiteDatabase mDb) throws FamiliarDbException { try { if (category == -1) { // No category specified; return the main categories String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_SUBCATEGORY + " = -1"; return mDb.rawQuery(sql, null); } else if (subcategory == -1) { // No subcategory specified; return the subcategories under the given category String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " > -1 AND " + KEY_ENTRY + " IS NULL"; return mDb.rawQuery(sql, null); } else { // Both specified; return the rules under the given subcategory String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory) + " AND " + KEY_ENTRY + " IS NOT NULL"; return mDb.rawQuery(sql, null); } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param keyword * @param category * @param subcategory * @param mDb * @return * @throws FamiliarDbException */ public static Cursor getRulesByKeyword(String keyword, int category, int subcategory, SQLiteDatabase mDb) throws FamiliarDbException { try { // Don't let them pass in an empty string; it'll return ALL the // rules if (keyword != null && !keyword.trim().equals("")) { keyword = "'%" + keyword.replace("'", "''") + "%'"; if (category == -1) { // No category; we're searching from the main page, so no // restrictions String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_RULE_TEXT + " LIKE " + keyword + " AND " + KEY_ENTRY + " IS NOT NULL"; return mDb.rawQuery(sql, null); } else if (subcategory == -1) { // No subcategory; we're searching from a category page, so // restrict // within that String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_RULE_TEXT + " LIKE " + keyword + " AND " + KEY_ENTRY + " IS NOT NULL AND " + KEY_CATEGORY + " = " + String.valueOf(category); return mDb.rawQuery(sql, null); } else { // We're searching within a subcategory, so restrict within // that String sql = "SELECT * FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_RULE_TEXT + " LIKE " + keyword + " AND " + KEY_ENTRY + " IS NOT NULL AND " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory); return mDb.rawQuery(sql, null); } } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return null; } /** * @param category * @param subcategory * @param entry * @param mDb * @return * @throws FamiliarDbException */ public static int getRulePosition(int category, int subcategory, String entry, SQLiteDatabase mDb) throws FamiliarDbException { try { if (entry != null) { String sql = "SELECT " + KEY_POSITION + " FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory) + " AND " + KEY_ENTRY + " = '" + entry.replace("'", "''") + "'"; Cursor c = mDb.rawQuery(sql, null); if (c != null) { c.moveToFirst(); int result = c.getInt(c.getColumnIndex(KEY_POSITION)); c.close(); return result; } } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return 0; } /** * @param category * @param subcategory * @param mDb * @return * @throws FamiliarDbException */ public static String getCategoryName(int category, int subcategory, SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT " + KEY_RULE_TEXT + " FROM " + DATABASE_TABLE_RULES + " WHERE " + KEY_CATEGORY + " = " + String.valueOf(category) + " AND " + KEY_SUBCATEGORY + " = " + String.valueOf(subcategory) + " AND " + KEY_ENTRY + " IS NULL"; Cursor c = mDb.rawQuery(sql, null); if (c != null) { c.moveToFirst(); String result = c.getString(c.getColumnIndex(KEY_RULE_TEXT)); c.close(); return result; } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } return ""; } /** * @param mDb * @return * @throws FamiliarDbException */ public static Cursor getGlossaryTerms(SQLiteDatabase mDb) throws FamiliarDbException { try { String sql = "SELECT * FROM " + DATABASE_TABLE_GLOSSARY; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @param format * @return * @throws FamiliarDbException */ public static Cursor getBannedCards(SQLiteDatabase mDb, String format) throws FamiliarDbException { try { String sql = "SELECT " + KEY_LEGALITY + ", GROUP_CONCAT(" + KEY_NAME + ", '<br>') AS " + KEY_BANNED_LIST + " FROM " + DATABASE_TABLE_BANNED_CARDS + " WHERE " + KEY_FORMAT + " = '" + format + "'" + " GROUP BY " + KEY_LEGALITY; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @param format * @return * @throws FamiliarDbException */ public static Cursor getLegalSets(SQLiteDatabase mDb, String format) throws FamiliarDbException { try { String sql = "SELECT GROUP_CONCAT(" + DATABASE_TABLE_SETS +"."+KEY_NAME + ", '<br>') AS " + KEY_LEGAL_SETS + " FROM (" + DATABASE_TABLE_LEGAL_SETS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_LEGAL_SETS +"."+KEY_SET+" = "+DATABASE_TABLE_SETS+"."+KEY_CODE + ")" + " WHERE " + DATABASE_TABLE_LEGAL_SETS + "." + KEY_FORMAT + " = '" + format + "'"; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @throws FamiliarDbException */ public static void dropRulesTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_RULES); mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_GLOSSARY); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param mDb * @throws FamiliarDbException */ public static void createRulesTables(SQLiteDatabase mDb) throws FamiliarDbException { try { mDb.execSQL(DATABASE_CREATE_RULES); mDb.execSQL(DATABASE_CREATE_GLOSSARY); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param category * @param subcategory * @param entry * @param text * @param position * @param mDb * @throws FamiliarDbException */ public static void insertRule(int category, int subcategory, String entry, String text, int position, SQLiteDatabase mDb) throws FamiliarDbException { if (entry == null) { entry = "NULL"; } else { entry = "'" + entry.replace("'", "''") + "'"; } text = "'" + text.replace("'", "''") + "'"; String positionStr; if (position < 0) { positionStr = "NULL"; } else { positionStr = String.valueOf(position); } String sql = "INSERT INTO " + DATABASE_TABLE_RULES + " (" + KEY_CATEGORY + ", " + KEY_SUBCATEGORY + ", " + KEY_ENTRY + ", " + KEY_RULE_TEXT + ", " + KEY_POSITION + ") VALUES (" + String.valueOf(category) + ", " + String.valueOf(subcategory) + ", " + entry + ", " + text + ", " + positionStr + ");"; try { mDb.execSQL(sql); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * @param term * @param definition * @param mDb * @throws FamiliarDbException */ public static void insertGlossaryTerm(String term, String definition, SQLiteDatabase mDb) throws FamiliarDbException { term = "'" + term.replace("'", "''") + "'"; definition = "'" + definition.replace("'", "''") + "'"; String sql = "INSERT INTO " + DATABASE_TABLE_GLOSSARY + " (" + KEY_TERM + ", " + KEY_DEFINITION + ") VALUES (" + term + ", " + definition + ");"; try { mDb.execSQL(sql); } catch (SQLiteException e) { throw new FamiliarDbException(e); } } /** * Builds a map for all columns that may be requested, which will be given * to the SQLiteQueryBuilder. This is a good way to define aliases for * column names, but must include all columns, even if the value is the key. * This allows the ContentProvider to request columns w/o the need to know * real column names and create the alias itself. * * @return */ private static HashMap<String, String> buildColumnMap() { HashMap<String, String> map = new HashMap<String, String>(); map.put(KEY_NAME, KEY_NAME); map.put(BaseColumns._ID, "rowid AS " + BaseColumns._ID); map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); return map; } /** * @param selection The selection clause * @param selectionArgs Selection arguments for "?" components in the selection * @param columns The columns to return * @param mDb * @return A Cursor over all rows matching the query * @throws FamiliarDbException */ private static Cursor query(String selection, String[] selectionArgs, String[] columns, SQLiteDatabase mDb) throws FamiliarDbException { /* * The SQLiteBuilder provides a map for all possible columns requested * to actual columns in the database, creating a simple column alias * mechanism by which the ContentProvider does not need to know the real * column names */ SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables(DATABASE_TABLE_CARDS); builder.setProjectionMap(mColumnMap); Cursor cursor; try { cursor = builder.query(mDb, columns, selection, selectionArgs, KEY_NAME, null, KEY_NAME); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } if (cursor != null && !cursor.moveToFirst()) { cursor.close(); return null; } return cursor; } /** * Returns a Cursor positioned at the word specified by rowId * * @param rowId id of word to retrieve * @param columns The columns to include, if null then all are included * @param mDb * @return Cursor positioned to matching word, or null if not found. * @throws FamiliarDbException */ public static Cursor getCardByRowId(String rowId, String[] columns, SQLiteDatabase mDb) throws FamiliarDbException { String selection = "rowid = ?"; String[] selectionArgs = new String[]{rowId}; return query(selection, selectionArgs, columns, mDb); /* * This builds a query that looks like: SELECT <columns> FROM <table> * WHERE rowid = <rowId> */ } /** * Returns a Cursor over all words that match the given query * * @param query The string to search for * @param mDb * @return Cursor over all words that match, or null if none found. * @throws FamiliarDbException */ public static Cursor getCardsByNamePrefix(String query, SQLiteDatabase mDb) throws FamiliarDbException { try { query = query.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]).trim(); String convert = query.toLowerCase().replace("ae", String.valueOf(Character.toChars(0xC6)[0])); if (query.length() < 2) { return null; } String sql = "SELECT * FROM (" + "SELECT " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " AS " + KEY_NAME + ", " + DATABASE_TABLE_CARDS + "." + KEY_ID + " AS " + KEY_ID + ", " + DATABASE_TABLE_CARDS + "." + KEY_ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID + " FROM " + DATABASE_TABLE_CARDS + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = " + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '" + query + "%'" + " OR " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '" + convert + "%'" + " ORDER BY " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " COLLATE UNICODE, " + DATABASE_TABLE_SETS + "." + KEY_DATE + " ASC " + ") GROUP BY " + KEY_NAME; return mDb.rawQuery(sql, null); } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param ctx * @return */ public static boolean isDbOutOfDate(Context ctx) { SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(ctx); String dbPath = ctx.getFilesDir().getPath(); dbPath = dbPath.substring(0, dbPath.lastIndexOf("/")) + "/databases"; File f = new File(dbPath, DB_NAME); int dbVersion = preferences.getInt("databaseVersion", -1); return (!f.exists() || f.length() < 1048576 || dbVersion < CardDbAdapter.DATABASE_VERSION); } /** * @param ctx */ public static void copyDB(Context ctx) { SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(ctx); SharedPreferences.Editor editor = preferences.edit(); try { String dbPath = ctx.getFilesDir().getPath(); dbPath = dbPath.substring(0, dbPath.lastIndexOf("/")) + "/databases"; File folder = new File(dbPath); if (!folder.exists()) { folder.mkdir(); } File dbFile = new File(folder, DB_NAME); if (dbFile.exists()) { dbFile.delete(); editor.putString("lastUpdate", ""); editor.putInt("databaseVersion", -1); editor.apply(); } if (!dbFile.exists()) { GZIPInputStream gis = new GZIPInputStream(ctx.getResources().openRawResource(R.raw.datagz)); FileOutputStream fos = new FileOutputStream(dbFile); byte[] buffer = new byte[1024]; int length; while ((length = gis.read(buffer)) > 0) { fos.write(buffer, 0, length); } editor.putInt("databaseVersion", CardDbAdapter.DATABASE_VERSION); editor.apply(); // Close the streams fos.flush(); fos.close(); gis.close(); } } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * @param name * @param mSetCode * @param mDb @return * @throws FamiliarDbException */ public static int getSplitMultiverseID(String name, String setCode, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String statement = "SELECT " + KEY_MULTIVERSEID + " from " + DATABASE_TABLE_CARDS + " WHERE " + KEY_NAME + " = '" + name + "' AND " + KEY_SET + " = '" + setCode + "'"; try { c = mDb.rawQuery(statement, null); if (c.getCount() > 0) { c.moveToFirst(); int retVal = c.getInt(c.getColumnIndex(KEY_MULTIVERSEID)); c.close(); return retVal; } else { c.close(); return -1; } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param multiverseId * @param mDb * @return * @throws FamiliarDbException */ public static String getSplitName(int multiverseId, boolean ascending, SQLiteDatabase mDb) throws FamiliarDbException { Cursor c; String statement = "SELECT " + KEY_NAME + ", " + KEY_NUMBER + " from " + DATABASE_TABLE_CARDS + " WHERE " + KEY_MULTIVERSEID + " = " + multiverseId + " ORDER BY " + KEY_NUMBER; if (ascending) { statement += " ASC"; } else { statement += " DESC"; } try { c = mDb.rawQuery(statement, null); if (c.getCount() == 2) { c.moveToFirst(); String retVal = c.getString(c .getColumnIndex(KEY_NAME)); retVal += " // "; c.moveToNext(); retVal += c.getString(c.getColumnIndex(KEY_NAME)); c.close(); return retVal; } else { c.close(); return null; } } catch (SQLiteException e) { throw new FamiliarDbException(e); } catch (IllegalStateException e) { throw new FamiliarDbException(e); } } /** * @param s * @return */ public static String removeAccentMarks(String s) { return s.replace(Character.toChars(0xC0)[0] + "", "A") .replace(Character.toChars(0xC1)[0] + "", "A") .replace(Character.toChars(0xC2)[0] + "", "A") .replace(Character.toChars(0xC3)[0] + "", "A") .replace(Character.toChars(0xC4)[0] + "", "A") .replace(Character.toChars(0xC5)[0] + "", "A") .replace(Character.toChars(0xC6)[0] + "", "Ae") .replace(Character.toChars(0xC7)[0] + "", "C") .replace(Character.toChars(0xC8)[0] + "", "E") .replace(Character.toChars(0xC9)[0] + "", "E") .replace(Character.toChars(0xCA)[0] + "", "E") .replace(Character.toChars(0xCB)[0] + "", "E") .replace(Character.toChars(0xCC)[0] + "", "I") .replace(Character.toChars(0xCD)[0] + "", "I") .replace(Character.toChars(0xCE)[0] + "", "I") .replace(Character.toChars(0xCF)[0] + "", "I") .replace(Character.toChars(0xD0)[0] + "", "D") .replace(Character.toChars(0xD1)[0] + "", "N") .replace(Character.toChars(0xD2)[0] + "", "O") .replace(Character.toChars(0xD3)[0] + "", "O") .replace(Character.toChars(0xD4)[0] + "", "O") .replace(Character.toChars(0xD5)[0] + "", "O") .replace(Character.toChars(0xD6)[0] + "", "O") .replace(Character.toChars(0xD7)[0] + "", "x") .replace(Character.toChars(0xD8)[0] + "", "O") .replace(Character.toChars(0xD9)[0] + "", "U") .replace(Character.toChars(0xDA)[0] + "", "U") .replace(Character.toChars(0xDB)[0] + "", "U") .replace(Character.toChars(0xDC)[0] + "", "U") .replace(Character.toChars(0xDD)[0] + "", "Y") .replace(Character.toChars(0xE0)[0] + "", "a") .replace(Character.toChars(0xE1)[0] + "", "a") .replace(Character.toChars(0xE2)[0] + "", "a") .replace(Character.toChars(0xE3)[0] + "", "a") .replace(Character.toChars(0xE4)[0] + "", "a") .replace(Character.toChars(0xE5)[0] + "", "a") .replace(Character.toChars(0xE6)[0] + "", "ae") .replace(Character.toChars(0xE7)[0] + "", "c") .replace(Character.toChars(0xE8)[0] + "", "e") .replace(Character.toChars(0xE9)[0] + "", "e") .replace(Character.toChars(0xEA)[0] + "", "e") .replace(Character.toChars(0xEB)[0] + "", "e") .replace(Character.toChars(0xEC)[0] + "", "i") .replace(Character.toChars(0xED)[0] + "", "i") .replace(Character.toChars(0xEE)[0] + "", "i") .replace(Character.toChars(0xEF)[0] + "", "i") .replace(Character.toChars(0xF1)[0] + "", "n") .replace(Character.toChars(0xF2)[0] + "", "o") .replace(Character.toChars(0xF3)[0] + "", "o") .replace(Character.toChars(0xF4)[0] + "", "o") .replace(Character.toChars(0xF5)[0] + "", "o") .replace(Character.toChars(0xF6)[0] + "", "o") .replace(Character.toChars(0xF8)[0] + "", "o") .replace(Character.toChars(0xF9)[0] + "", "u") .replace(Character.toChars(0xFA)[0] + "", "u") .replace(Character.toChars(0xFB)[0] + "", "u") .replace(Character.toChars(0xFC)[0] + "", "u") .replace(Character.toChars(0xFD)[0] + "", "y") .replace(Character.toChars(0xFF)[0] + "", "y"); } /** * @param number * @param setCode * @return */ public static int isMultiCard(String number, String setCode) { if (number.contains("a") || number.contains("b")) { if (setCode.compareTo("ISD") == 0 || setCode.compareTo("DKA") == 0) { return TRANSFORM; } else if (setCode.compareTo("DGM") == 0) { return FUSE; } else { return SPLIT; } } return NOPE; } /** * @param setCode * @param mDb * @return * @throws FamiliarDbException */ public static boolean canBeFoil(String setCode, SQLiteDatabase mDb) throws FamiliarDbException { String[] extraSets = {"UNH", "UL", "UD", "MM", "NE", "PY", "IN", "PS", "7E", "AP", "OD", "TO", "JU", "ON", "LE", "SC", "CNS", "CNSC"}; ArrayList<String> nonModernLegalSets = new ArrayList<String>(Arrays.asList(extraSets)); for (String value : nonModernLegalSets) { if (value.equals(setCode)) { return true; } } return isModernLegalSet(setCode, mDb); } }
Fixed bug that allows for scheme cards to appear in vintage and legacy Card Search results.
MTGFamiliar/src/main/java/com/gelakinetic/mtgfam/helpers/database/CardDbAdapter.java
Fixed bug that allows for scheme cards to appear in vintage and legacy Card Search results.
<ide><path>TGFamiliar/src/main/java/com/gelakinetic/mtgfam/helpers/database/CardDbAdapter.java <ide> " AND NOT " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = 'UG'" + <ide> " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Plane %'" + <ide> " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Conspiracy%'" + <del> " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Scheme%'" + <add> " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE '%Scheme%'" + <ide> " AND " + DATABASE_TABLE_CARDS + "." + KEY_TYPE + " NOT LIKE 'Vanguard%'"; <ide> } <ide> statement += " AND NOT EXISTS (SELECT * FROM "
Java
apache-2.0
fbd76c73aef35b198c6beae89fc8ba0d7b9f29b3
0
wso2-extensions/identity-inbound-auth-oauth,chirankavinda123/identity-inbound-auth-oauth,darshanasbg/identity-inbound-auth-oauth,IsuraD/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth,darshanasbg/identity-inbound-auth-oauth,chirankavinda123/identity-inbound-auth-oauth,IsuraD/identity-inbound-auth-oauth
/* * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth.endpoint.user.impl; import org.apache.commons.lang.StringUtils; import org.apache.oltu.oauth2.common.error.OAuthError; import org.wso2.carbon.identity.oauth.user.UserInfoEndpointException; import org.wso2.carbon.identity.oauth.user.UserInfoRequestValidator; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Scanner; /** * Validates the schema and authorization header according to the specification * * @see http://openid.net/specs/openid-connect-basic-1_0-22.html#anchor6 */ public class UserInforRequestDefaultValidator implements UserInfoRequestValidator { private static String CONTENT_TYPE_HEADER_VALUE = "application/x-www-form-urlencoded"; private static String US_ASCII = "US-ASCII"; @Override public String validateRequest(HttpServletRequest request) throws UserInfoEndpointException { String authzHeaders = request.getHeader(HttpHeaders.AUTHORIZATION); if (authzHeaders == null) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Authorization header missing"); } String[] authzHeaderInfo = ((String) authzHeaders).trim().split(" "); if (!"Bearer".equals(authzHeaderInfo[0])) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Bearer token missing"); } return authzHeaderInfo[1]; } @Override public String validateRequestBody(HttpServletRequest request) throws UserInfoEndpointException { String contentTypeHeaders = request.getHeader(HttpHeaders.CONTENT_TYPE); //to validate the Content_Type header if (StringUtils.isEmpty(contentTypeHeaders)) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Content-Type header missing"); } if ((CONTENT_TYPE_HEADER_VALUE).equals(contentTypeHeaders.trim())) { StringBuilder stringBuilder = new StringBuilder(); Scanner scanner = null; try { scanner = new Scanner(request.getInputStream()); } catch (IOException e) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "can not read the request body"); } while (scanner.hasNextLine()) { stringBuilder.append(scanner.nextLine()); } String[] arrAccessToken = new String[2]; String requestBody = stringBuilder.toString(); String[] arrAccessTokenNew ; //to check whether the entity-body consist entirely of ASCII [USASCII] characters if (!isPureAscii(requestBody)) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Body contains non ASCII characters"); } if (requestBody.contains("access_token=")) { arrAccessToken = requestBody.trim().split("="); if(arrAccessToken[1].contains("&")){ arrAccessTokenNew = arrAccessToken[1].split("&", 1); return arrAccessTokenNew[0]; } } return arrAccessToken[1]; } else { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Content-Type header is wrong"); } } public static boolean isPureAscii(String requestBody) { byte bytearray[] = requestBody.getBytes(); CharsetDecoder charsetDecoder = Charset.forName(US_ASCII).newDecoder(); try { CharBuffer charBuffer = charsetDecoder.decode(ByteBuffer.wrap(bytearray)); charBuffer.toString(); } catch (CharacterCodingException e) { return false; } return true; } }
components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInforRequestDefaultValidator.java
/* * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth.endpoint.user.impl; import org.apache.commons.lang.StringUtils; import org.apache.oltu.oauth2.common.error.OAuthError; import org.wso2.carbon.identity.oauth.user.UserInfoEndpointException; import org.wso2.carbon.identity.oauth.user.UserInfoRequestValidator; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Scanner; /** * Validates the schema and authorization header according to the specification * * @see http://openid.net/specs/openid-connect-basic-1_0-22.html#anchor6 */ public class UserInforRequestDefaultValidator implements UserInfoRequestValidator { private static String CONTENT_TYPE_HEADER_VALUE = "application/x-www-form-urlencoded"; private static String US_ASCII = "US-ASCII"; @Override public String validateRequest(HttpServletRequest request) throws UserInfoEndpointException { String authzHeaders = request.getHeader(HttpHeaders.AUTHORIZATION); if (authzHeaders == null) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Authorization header missing"); } String[] authzHeaderInfo = ((String) authzHeaders).trim().split(" "); if (!"Bearer".equals(authzHeaderInfo[0])) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Bearer token missing"); } return authzHeaderInfo[1]; } @Override public String validateRequestBody(HttpServletRequest request) throws UserInfoEndpointException { String contentTypeHeaders = request.getHeader(HttpHeaders.CONTENT_TYPE); //to validate the Content_Type header if (StringUtils.isEmpty(contentTypeHeaders)) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Content-Type header missing"); } if ((CONTENT_TYPE_HEADER_VALUE).equals(contentTypeHeaders.trim())) { StringBuilder stringBuilder = new StringBuilder(); Scanner scanner = null; try { scanner = new Scanner(request.getInputStream()); } catch (IOException e) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "can not read the request body"); } while (scanner.hasNextLine()) { stringBuilder.append(scanner.nextLine()); } String[] arrAccessToken = new String[2]; String requestBody = stringBuilder.toString(); //to check whether the entity-body consist entirely of ASCII [USASCII] characters if (!isPureAscii(requestBody)) { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Body contains non ASCII characters"); } if (requestBody.contains("access_token=")) { arrAccessToken = requestBody.trim().split("="); } return arrAccessToken[1]; } else { throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Content-Type header is wrong"); } } public static boolean isPureAscii(String requestBody) { byte bytearray[] = requestBody.getBytes(); CharsetDecoder charsetDecoder = Charset.forName(US_ASCII).newDecoder(); try { CharBuffer charBuffer = charsetDecoder.decode(ByteBuffer.wrap(bytearray)); charBuffer.toString(); } catch (CharacterCodingException e) { return false; } return true; } }
Validate the post body for other request parameters
components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInforRequestDefaultValidator.java
Validate the post body for other request parameters
<ide><path>omponents/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/user/impl/UserInforRequestDefaultValidator.java <ide> } <ide> String[] arrAccessToken = new String[2]; <ide> String requestBody = stringBuilder.toString(); <add> String[] arrAccessTokenNew ; <ide> //to check whether the entity-body consist entirely of ASCII [USASCII] characters <ide> if (!isPureAscii(requestBody)) { <ide> throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, <ide> } <ide> if (requestBody.contains("access_token=")) { <ide> arrAccessToken = requestBody.trim().split("="); <add> if(arrAccessToken[1].contains("&")){ <add> arrAccessTokenNew = arrAccessToken[1].split("&", 1); <add> return arrAccessTokenNew[0]; <add> } <ide> } <ide> return arrAccessToken[1]; <ide> } else {
JavaScript
agpl-3.0
e2e3c4c649d2a8b55afa187b0e703e9d6ffa2edb
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
99715dc8-2e64-11e5-9284-b827eb9e62be
helloWorld.js
996be1e0-2e64-11e5-9284-b827eb9e62be
99715dc8-2e64-11e5-9284-b827eb9e62be
helloWorld.js
99715dc8-2e64-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>996be1e0-2e64-11e5-9284-b827eb9e62be <add>99715dc8-2e64-11e5-9284-b827eb9e62be
Java
mit
f4390de550af7f46eebfc363709c1815377fe328
0
DAC-2014-Equipe-3/sujet-2
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.dac2014equipe3.sujet2.model.entity; import com.dac2014equipe3.sujet2.vo.RewardVo; import java.io.Serializable; import java.util.List; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Jummartinezro */ @Entity @Table(name = "Reward", catalog = "sujet2", schema = "") @NamedQueries({ @NamedQuery(name = "Reward.findAll", query = "SELECT r FROM Reward r"), @NamedQuery(name = "Reward.findByRewardId", query = "SELECT r FROM Reward r WHERE r.rewardId = :rewardId"), @NamedQuery(name = "Reward.findByRewardName", query = "SELECT r FROM Reward r WHERE r.rewardName = :rewardName"), @NamedQuery(name = "Reward.findByRewardDescription", query = "SELECT r FROM Reward r WHERE r.rewardDescription = :rewardDescription"), @NamedQuery(name = "Reward.findByRewardMinPrice", query = "SELECT r FROM Reward r WHERE r.rewardMinPrice = :rewardMinPrice")}) public class Reward implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Basic(optional = false) @Column(name = "rewardId") private Integer rewardId; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "rewardName") private String rewardName; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "rewardDescription") private String rewardDescription; @Size(max = 45) @Column(name = "rewardMinPrice") private String rewardMinPrice; @OneToMany(cascade = CascadeType.ALL, mappedBy = "reward") private List<MemberbacksProject> memberbacksProjectList; @JoinColumn(name = "Project_projectId", referencedColumnName = "projectId") @ManyToOne(optional = false) private Project project; public Reward() { } public Reward(Integer rewardId) { this.rewardId = rewardId; } public Reward(Integer rewardId, String rewardName, String rewardDescription, String rewardMinPrice, Project project) { this.rewardId = rewardId; this.rewardName = rewardName; this.rewardDescription = rewardDescription; this.rewardMinPrice = rewardMinPrice; this.project = project; } public Reward(RewardVo rewardVo) { this.rewardId = rewardVo.getRewardId(); this.rewardName = rewardVo.getRewardName(); this.rewardDescription = rewardVo.getRewardDescription(); this.rewardMinPrice = rewardVo.getRewardMinPrice(); this.project = rewardVo.getProject(); } public Integer getRewardId() { return rewardId; } public void setRewardId(Integer rewardId) { this.rewardId = rewardId; } public String getRewardName() { return rewardName; } public void setRewardName(String rewardName) { this.rewardName = rewardName; } public String getRewardDescription() { return rewardDescription; } public void setRewardDescription(String rewardDescription) { this.rewardDescription = rewardDescription; } public String getRewardMinPrice() { return rewardMinPrice; } public void setRewardMinPrice(String rewardMinPrice) { this.rewardMinPrice = rewardMinPrice; } public List<MemberbacksProject> getMemberbacksProjectList() { return memberbacksProjectList; } public void setMemberbacksProjectList(List<MemberbacksProject> memberbacksProjectList) { this.memberbacksProjectList = memberbacksProjectList; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } @Override public int hashCode() { int hash = 0; hash += (rewardId != null ? rewardId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Reward)) { return false; } Reward other = (Reward) object; if ((this.rewardId == null && other.rewardId != null) || (this.rewardId != null && !this.rewardId.equals(other.rewardId))) { return false; } return true; } @Override public String toString() { return "com.dac2014equipe3.sujet2.model.entity.Reward[ rewardId=" + rewardId + " ]"; } }
sujet2/src/main/java/com/dac2014equipe3/sujet2/model/entity/Reward.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.dac2014equipe3.sujet2.model.entity; import com.dac2014equipe3.sujet2.vo.RewardVo; import java.io.Serializable; import java.util.List; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Jummartinezro */ @Entity @Table(name = "Reward", catalog = "sujet2", schema = "") @NamedQueries({ @NamedQuery(name = "Reward.findAll", query = "SELECT r FROM Reward r"), @NamedQuery(name = "Reward.findByRewardId", query = "SELECT r FROM Reward r WHERE r.rewardId = :rewardId"), @NamedQuery(name = "Reward.findByRewardName", query = "SELECT r FROM Reward r WHERE r.rewardName = :rewardName"), @NamedQuery(name = "Reward.findByRewardDescription", query = "SELECT r FROM Reward r WHERE r.rewardDescription = :rewardDescription"), @NamedQuery(name = "Reward.findByRewardMinPrice", query = "SELECT r FROM Reward r WHERE r.rewardMinPrice = :rewardMinPrice")}) public class Reward implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Basic(optional = false) @Column(name = "rewardId") private Integer rewardId; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "rewardName") private String rewardName; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "rewardDescription") private String rewardDescription; @Size(max = 45) @Column(name = "rewardMinPrice") private String rewardMinPrice; @OneToMany(cascade = CascadeType.ALL, mappedBy = "reward") private List<MemberbacksProject> memberbacksProjectList; @JoinColumn(name = "Project_projectId", referencedColumnName = "projectId", insertable = false, updatable = false) @ManyToOne(optional = false) private Project project; public Reward() { } public Reward(Integer rewardId) { this.rewardId = rewardId; } public Reward(Integer rewardId, String rewardName, String rewardDescription, String rewardMinPrice, Project project) { this.rewardId = rewardId; this.rewardName = rewardName; this.rewardDescription = rewardDescription; this.rewardMinPrice = rewardMinPrice; this.project = project; } public Reward(RewardVo rewardVo) { this.rewardId = rewardVo.getRewardId(); this.rewardName = rewardVo.getRewardName(); this.rewardDescription = rewardVo.getRewardDescription(); this.rewardMinPrice = rewardVo.getRewardMinPrice(); this.project = rewardVo.getProject(); } public Integer getRewardId() { return rewardId; } public void setRewardId(Integer rewardId) { this.rewardId = rewardId; } public String getRewardName() { return rewardName; } public void setRewardName(String rewardName) { this.rewardName = rewardName; } public String getRewardDescription() { return rewardDescription; } public void setRewardDescription(String rewardDescription) { this.rewardDescription = rewardDescription; } public String getRewardMinPrice() { return rewardMinPrice; } public void setRewardMinPrice(String rewardMinPrice) { this.rewardMinPrice = rewardMinPrice; } public List<MemberbacksProject> getMemberbacksProjectList() { return memberbacksProjectList; } public void setMemberbacksProjectList(List<MemberbacksProject> memberbacksProjectList) { this.memberbacksProjectList = memberbacksProjectList; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } @Override public int hashCode() { int hash = 0; hash += (rewardId != null ? rewardId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Reward)) { return false; } Reward other = (Reward) object; if ((this.rewardId == null && other.rewardId != null) || (this.rewardId != null && !this.rewardId.equals(other.rewardId))) { return false; } return true; } @Override public String toString() { return "com.dac2014equipe3.sujet2.model.entity.Reward[ rewardId=" + rewardId + " ]"; } }
Correction reward entity
sujet2/src/main/java/com/dac2014equipe3/sujet2/model/entity/Reward.java
Correction reward entity
<ide><path>ujet2/src/main/java/com/dac2014equipe3/sujet2/model/entity/Reward.java <ide> private String rewardMinPrice; <ide> @OneToMany(cascade = CascadeType.ALL, mappedBy = "reward") <ide> private List<MemberbacksProject> memberbacksProjectList; <del> @JoinColumn(name = "Project_projectId", referencedColumnName = "projectId", insertable = false, updatable = false) <add> @JoinColumn(name = "Project_projectId", referencedColumnName = "projectId") <ide> @ManyToOne(optional = false) <ide> private Project project; <ide>
Java
apache-2.0
d6fcfce39d9cf233118fb282a55b97a34a679d9c
0
alex-bl/ivyDEextension,alex-bl/ivyDEextension,apache/ant-ivyde,apache/ant-ivyde
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivyde.eclipse.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; public class RetrieveComposite extends Composite { public static final String TOOLTIP_RETRIEVE_PATTERN = "Exemple: lib/[conf]/[artifact].[ext]\n" + "To copy artifacts in folder named lib without revision by folder" + " named like configurations"; public static final String TOOLTIP_RETRIEVE_CONFS = "Comma separated list of configuration to retrieve\n" +"Exemple: '*' or 'compile,test'"; public static final String TOOLTIP_RETRIEVE_TYPES = "Comma separated list of types to retrieve\n" +"Exemple: '*' or 'jar,source'"; private Button doRetrieveButton; private Text retrievePatternText; private Button retrieveSyncButton; private Text confsText; private Text typesText; public RetrieveComposite(Composite parent, int style) { super(parent, style); GridLayout layout = new GridLayout(2, false); layout.marginHeight = 0; layout.marginWidth = 0; setLayout(layout); doRetrieveButton = new Button(this, SWT.CHECK); doRetrieveButton.setText("Do retrieve after resolve"); doRetrieveButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, 2, 1)); Label label = new Label(this, SWT.NONE); label.setText("Retrieve pattern:"); retrievePatternText = new Text(this, SWT.SINGLE | SWT.BORDER); retrievePatternText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); retrievePatternText.setEnabled(doRetrieveButton.getSelection()); retrievePatternText.setToolTipText(TOOLTIP_RETRIEVE_PATTERN); retrieveSyncButton = new Button(this, SWT.CHECK); retrieveSyncButton.setText("Delete old retrieved artifacts"); retrieveSyncButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, 2, 1)); retrieveSyncButton.setEnabled(doRetrieveButton.getSelection()); label = new Label(this, SWT.NONE); label.setText("Configurations:"); confsText = new Text(this, SWT.SINGLE | SWT.BORDER); confsText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); confsText.setEnabled(doRetrieveButton.getSelection()); confsText.setToolTipText(TOOLTIP_RETRIEVE_CONFS); label = new Label(this, SWT.NONE); label.setText("Types:"); typesText = new Text(this, SWT.SINGLE | SWT.BORDER); typesText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); typesText.setEnabled(doRetrieveButton.getSelection()); typesText.setToolTipText(TOOLTIP_RETRIEVE_TYPES); doRetrieveButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { retrievePatternText.setEnabled(doRetrieveButton.getSelection()); retrieveSyncButton.setEnabled(doRetrieveButton.getSelection()); confsText.setEnabled(doRetrieveButton.getSelection()); typesText.setEnabled(doRetrieveButton.getSelection()); } }); } public boolean isRetrieveEnabled() { return doRetrieveButton.getSelection(); } public boolean isSyncEnabled() { return retrieveSyncButton.getSelection(); } public String getRetrievePattern() { return retrievePatternText.getText(); } public String getRetrieveConfs() { return confsText.getText(); } public String getRetrieveTypes() { return typesText.getText(); } public void init(boolean doRetrieve, String retrievePattern, String confs, String types, boolean retrieveSync) { doRetrieveButton.setSelection(doRetrieve); retrievePatternText.setText(retrievePattern); retrieveSyncButton.setSelection(retrieveSync); confsText.setText(confs); typesText.setText(types); } public void setEnabled(boolean enabled) { super.setEnabled(enabled); doRetrieveButton.setEnabled(enabled); retrievePatternText.setEnabled(enabled && doRetrieveButton.getSelection()); retrieveSyncButton.setEnabled(enabled && doRetrieveButton.getSelection()); confsText.setEnabled(enabled && doRetrieveButton.getSelection()); typesText.setEnabled(enabled && doRetrieveButton.getSelection()); } }
org.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/ui/RetrieveComposite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivyde.eclipse.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; public class RetrieveComposite extends Composite { public static final String TOOLTIP_RETRIEVE_PATTERN = "Example: lib/[conf]/[artifact].[ext]\n" + "To copy artifacts in folder named lib without revision by folder" + " named like configurations"; public static final String TOOLTIP_RETRIEVE_CONFS = "Comma separated list of configuration to retrieve\n" +"Exemple: '*' or 'compile,test'"; public static final String TOOLTIP_RETRIEVE_TYPES = "Comma separated list of types to retrieve\n" +"Exemple: '*' or 'jar,source'"; private Button doRetrieveButton; private Text retrievePatternText; private Button retrieveSyncButton; private Text confsText; private Text typesText; public RetrieveComposite(Composite parent, int style) { super(parent, style); GridLayout layout = new GridLayout(2, false); layout.marginHeight = 0; layout.marginWidth = 0; setLayout(layout); doRetrieveButton = new Button(this, SWT.CHECK); doRetrieveButton.setText("Do retrieve after resolve"); doRetrieveButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, 2, 1)); Label label = new Label(this, SWT.NONE); label.setText("Retrieve pattern:"); retrievePatternText = new Text(this, SWT.SINGLE | SWT.BORDER); retrievePatternText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); retrievePatternText.setEnabled(doRetrieveButton.getSelection()); retrievePatternText.setToolTipText(TOOLTIP_RETRIEVE_PATTERN); retrieveSyncButton = new Button(this, SWT.CHECK); retrieveSyncButton.setText("Delete old retrieved artifacts"); retrieveSyncButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, 2, 1)); retrieveSyncButton.setEnabled(doRetrieveButton.getSelection()); label = new Label(this, SWT.NONE); label.setText("Configurations:"); confsText = new Text(this, SWT.SINGLE | SWT.BORDER); confsText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); confsText.setEnabled(doRetrieveButton.getSelection()); confsText.setToolTipText(TOOLTIP_RETRIEVE_CONFS); label = new Label(this, SWT.NONE); label.setText("Types:"); typesText = new Text(this, SWT.SINGLE | SWT.BORDER); typesText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); typesText.setEnabled(doRetrieveButton.getSelection()); typesText.setToolTipText(TOOLTIP_RETRIEVE_TYPES); doRetrieveButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { retrievePatternText.setEnabled(doRetrieveButton.getSelection()); retrieveSyncButton.setEnabled(doRetrieveButton.getSelection()); confsText.setEnabled(doRetrieveButton.getSelection()); typesText.setEnabled(doRetrieveButton.getSelection()); } }); } public boolean isRetrieveEnabled() { return doRetrieveButton.getSelection(); } public boolean isSyncEnabled() { return retrieveSyncButton.getSelection(); } public String getRetrievePattern() { return retrievePatternText.getText(); } public String getRetrieveConfs() { return confsText.getText(); } public String getRetrieveTypes() { return typesText.getText(); } public void init(boolean doRetrieve, String retrievePattern, String confs, String types, boolean retrieveSync) { doRetrieveButton.setSelection(doRetrieve); retrievePatternText.setText(retrievePattern); retrieveSyncButton.setSelection(retrieveSync); confsText.setText(confs); typesText.setText(types); } public void setEnabled(boolean enabled) { super.setEnabled(enabled); doRetrieveButton.setEnabled(enabled); retrievePatternText.setEnabled(enabled && doRetrieveButton.getSelection()); retrieveSyncButton.setEnabled(enabled && doRetrieveButton.getSelection()); confsText.setEnabled(enabled && doRetrieveButton.getSelection()); typesText.setEnabled(enabled && doRetrieveButton.getSelection()); } }
Use english more than the french spell (thanks to Paul Newport to have spotted it) git-svn-id: 804c0f3032317a396a1b8894d1ed8cc0b56e9f1c@724692 13f79535-47bb-0310-9956-ffa450edef68
org.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/ui/RetrieveComposite.java
Use english more than the french spell (thanks to Paul Newport to have spotted it)
<ide><path>rg.apache.ivyde.eclipse/src/java/org/apache/ivyde/eclipse/ui/RetrieveComposite.java <ide> <ide> public class RetrieveComposite extends Composite { <ide> <del> public static final String TOOLTIP_RETRIEVE_PATTERN = "Example: lib/[conf]/[artifact].[ext]\n" <add> public static final String TOOLTIP_RETRIEVE_PATTERN = "Exemple: lib/[conf]/[artifact].[ext]\n" <ide> + "To copy artifacts in folder named lib without revision by folder" <ide> + " named like configurations"; <ide>
Java
agpl-3.0
d6871b8a57458004ede94635fbe3830cf1626250
0
PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver
package nl.mpi.kinnate.ui.menu; import java.io.File; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.export.ExportToR; import nl.mpi.kinnate.transcoder.DiagramTranscoder; import nl.mpi.kinnate.ui.ImportSamplesFileMenu; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.window.AbstractDiagramManager; /** * Document : FileMenu * Created on : Dec 1, 2011, 4:04:06 PM * Author : Peter Withers */ public class FileMenu extends javax.swing.JMenu { private javax.swing.JMenuItem importGedcomUrl; private javax.swing.JMenuItem importGedcomFile; private javax.swing.JMenuItem importCsvFile; private javax.swing.JMenuItem closeTabMenuItem; private javax.swing.JMenuItem entityUploadMenuItem; private javax.swing.JMenuItem exitApplication; private javax.swing.JMenuItem exportToR; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JPopupMenu.Separator jSeparator4; private javax.swing.JPopupMenu.Separator jSeparator5; private javax.swing.JMenuItem newDiagramMenuItem; private javax.swing.JMenuItem openDiagram; private RecentFileMenu recentFileMenu; private javax.swing.JMenuItem saveAsDefaultMenuItem; private javax.swing.JMenuItem saveDiagram; private javax.swing.JMenuItem saveDiagramAs; private javax.swing.JMenuItem savePdfMenuItem; AbstractDiagramManager diagramWindowManager; public FileMenu(AbstractDiagramManager diagramWindowManager) { this.diagramWindowManager = diagramWindowManager; importGedcomUrl = new javax.swing.JMenuItem(); importGedcomFile = new javax.swing.JMenuItem(); importCsvFile = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); newDiagramMenuItem = new javax.swing.JMenuItem(); jMenu3 = new DocumentNewMenu(diagramWindowManager); openDiagram = new javax.swing.JMenuItem(); recentFileMenu = new RecentFileMenu(diagramWindowManager); jMenu1 = new SamplesFileMenu(diagramWindowManager); jMenu2 = new ImportSamplesFileMenu(diagramWindowManager); jSeparator2 = new javax.swing.JPopupMenu.Separator(); entityUploadMenuItem = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); saveDiagram = new javax.swing.JMenuItem(); saveDiagramAs = new javax.swing.JMenuItem(); savePdfMenuItem = new javax.swing.JMenuItem(); exportToR = new javax.swing.JMenuItem(); closeTabMenuItem = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); saveAsDefaultMenuItem = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JPopupMenu.Separator(); exitApplication = new javax.swing.JMenuItem(); // todo: Ticket #1297 add an import gedcom and csv menu item this.setText("File"); this.addMenuListener(new javax.swing.event.MenuListener() { public void menuSelected(javax.swing.event.MenuEvent evt) { fileMenuMenuSelected(evt); } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuCanceled(javax.swing.event.MenuEvent evt) { } }); this.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fileMenuActionPerformed(evt); } }); importGedcomUrl.setText("Import Gedcom Samples (from internet)"); importGedcomUrl.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importGedcomUrlActionPerformed(evt); } }); this.add(importGedcomFile); importGedcomFile.setText("Import Gedcom File"); importGedcomFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importGedcomFileActionPerformed(evt); } }); this.add(importGedcomFile); importCsvFile.setText("Import CSV File"); importCsvFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importCsvFileActionPerformed(evt); } }); this.add(importCsvFile); this.add(jSeparator1); newDiagramMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); newDiagramMenuItem.setText("New (default diagram)"); newDiagramMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newDiagramMenuItemActionPerformed(evt); } }); this.add(newDiagramMenuItem); jMenu3.setText("New Diagram of Type"); this.add(jMenu3); openDiagram.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); openDiagram.setText("Open"); openDiagram.setActionCommand("open"); openDiagram.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openDiagramActionPerformed(evt); } }); this.add(openDiagram); this.add(recentFileMenu); jMenu1.setText("Open Sample Diagram"); this.add(jMenu1); jMenu2.setText("Import Sample Data"); this.add(jMenu2); this.add(jSeparator2); entityUploadMenuItem.setText("Entity Upload"); entityUploadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { entityUploadMenuItemActionPerformed(evt); } }); this.add(entityUploadMenuItem); this.add(jSeparator4); saveDiagram.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); saveDiagram.setText("Save"); saveDiagram.setActionCommand("save"); saveDiagram.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveDiagramActionPerformed(evt); } }); this.add(saveDiagram); saveDiagramAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveDiagramAs.setText("Save As"); saveDiagramAs.setActionCommand("saveas"); saveDiagramAs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveDiagramAsActionPerformed(evt); } }); this.add(saveDiagramAs); savePdfMenuItem.setText("Export as PDF"); savePdfMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { savePdfMenuItemActionPerformed(evt); } }); this.add(savePdfMenuItem); exportToR.setText("Export to R / SPSS"); exportToR.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportToRActionPerformed(evt); } }); this.add(exportToR); closeTabMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK)); closeTabMenuItem.setText("Close"); closeTabMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeTabMenuItemActionPerformed(evt); } }); this.add(closeTabMenuItem); this.add(jSeparator3); saveAsDefaultMenuItem.setText("Save as Default Diagram"); saveAsDefaultMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveAsDefaultMenuItemActionPerformed(evt); } }); this.add(saveAsDefaultMenuItem); this.add(jSeparator5); exitApplication.setText("Exit"); exitApplication.setActionCommand("exit"); exitApplication.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitApplicationActionPerformed(evt); } }); this.add(exitApplication); } private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) { } private void openDiagramActionPerformed(java.awt.event.ActionEvent evt) { final File[] selectedFilesArray = ArbilWindowManager.getSingleInstance().showFileSelectBox("Open Kin Diagram", false, true, false); if (selectedFilesArray != null) { for (File selectedFile : selectedFilesArray) { diagramWindowManager.openDiagram(selectedFile.getName(), selectedFile.toURI(), true); } } } private void saveDiagramActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(); } private void saveDiagramAsActionPerformed(java.awt.event.ActionEvent evt) { // todo: update the file select to limit to svg and test that a file has been selected // todo: move this into the arbil window manager and get the last used directory // todo: make sure the file has the svg suffix JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new FileFilter() { @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } return (file.getName().toLowerCase().endsWith(".svg")); } @Override public String getDescription() { return "Scalable Vector Graphics (SVG)"; } }); int returnVal = fc.showSaveDialog(this); // make sure the file path ends in .svg lowercase if (returnVal == JFileChooser.APPROVE_OPTION) { File svgFile = fc.getSelectedFile(); if (!svgFile.getName().toLowerCase().endsWith(".svg")) { svgFile = new File(svgFile.getParentFile(), svgFile.getName() + ".svg"); } int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(svgFile); recentFileMenu.addRecentFile(svgFile); diagramWindowManager.setDiagramTitle(tabIndex, svgFile.getName()); } else { // todo: warn user that no file selected and so cannot save } // File selectedFile[] = LinorgWindowManager.getSingleInstance().showFileSelectBox("Save Kin Diagram", false, false, false); // if (selectedFile != null && selectedFile.length > 0) { // int tabIndex = Integer.valueOf(evt.getActionCommand()); // SavePanel savePanel = getSavePanel(tabIndex); // savePanel.saveToFile(selectedFile[0]); // jTabbedPane1.setTitleAt(tabIndex, selectedFile[0].getName()); // } else { // // todo: warn user that no file selected and so cannot save // } } private void exitApplicationActionPerformed(java.awt.event.ActionEvent evt) { // check that things are saved and ask user if not if (diagramWindowManager.offerUserToSaveAll()) { System.exit(0); } } private void fileMenuMenuSelected(javax.swing.event.MenuEvent evt) { // set the save, save as and close text to include the tab to which the action will occur int selectedIndex = diagramWindowManager.getSavePanelIndex(); SavePanel savePanel = null; if (selectedIndex > -1) { String currentTabText = diagramWindowManager.getSavePanelTitle(selectedIndex); savePanel = diagramWindowManager.getSavePanel(selectedIndex); saveDiagramAs.setText("Save As (" + currentTabText + ")"); saveDiagramAs.setActionCommand(Integer.toString(selectedIndex)); saveDiagram.setText("Save (" + currentTabText + ")"); saveDiagram.setActionCommand(Integer.toString(selectedIndex)); closeTabMenuItem.setText("Close (" + currentTabText + ")"); closeTabMenuItem.setActionCommand(Integer.toString(selectedIndex)); saveAsDefaultMenuItem.setText("Set Default Diagram as (" + currentTabText + ")"); saveAsDefaultMenuItem.setActionCommand(Integer.toString(selectedIndex)); } if (savePanel != null) { saveDiagram.setEnabled(savePanel.hasSaveFileName() && savePanel.requiresSave()); saveDiagramAs.setEnabled(true); exportToR.setEnabled(true); closeTabMenuItem.setEnabled(true); saveAsDefaultMenuItem.setEnabled(true); savePdfMenuItem.setEnabled(true); } else { saveDiagramAs.setEnabled(false); saveDiagram.setEnabled(false); exportToR.setEnabled(false); closeTabMenuItem.setEnabled(false); saveAsDefaultMenuItem.setEnabled(false); savePdfMenuItem.setEnabled(false); } } private void closeTabMenuItemActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); String diagramTitle = diagramWindowManager.getSavePanelTitle(tabIndex); boolean userCanceled = diagramWindowManager.offerUserToSave(savePanel, diagramTitle); if (!userCanceled) { diagramWindowManager.closeSavePanel(tabIndex); } } private void newDiagramMenuItemActionPerformed(java.awt.event.ActionEvent evt) { diagramWindowManager.newDiagram(); } private void importGedcomFileActionPerformed(java.awt.event.ActionEvent evt) { } private void importCsvFileActionPerformed(java.awt.event.ActionEvent evt) { } private void importGedcomUrlActionPerformed(java.awt.event.ActionEvent evt) { // todo: Ticket #1297 either remove this or change it so it does not open so many tabs / windows String[] importList = new String[]{"http://gedcomlibrary.com/gedcoms.html", "http://GedcomLibrary.com/gedcoms/gl120365.ged", // Tammy Carter Inman "http://GedcomLibrary.com/gedcoms/gl120366.ged", // Luis Lemonnier "http://GedcomLibrary.com/gedcoms/gl120367.ged", // Cheryl Marion Follansbee // New England Genealogical Detective "http://GedcomLibrary.com/gedcoms/gl120368.ged", // Phil Willaims "http://GedcomLibrary.com/gedcoms/gl120369.ged", // Francisco Casta�eda "http://GedcomLibrary.com/gedcoms/gl120370.ged", // Kim Carter "http://GedcomLibrary.com/gedcoms/gl120371.ged", // Maria Perusia "http://GedcomLibrary.com/gedcoms/gl120372.ged", // R. J. Bosman "http://GedcomLibrary.com/gedcoms/liverpool.ged", // William Robinette "http://GedcomLibrary.com/gedcoms/misc2a.ged", // William Robinette "http://GedcomLibrary.com/gedcoms/myline.ged", // William Robinette // also look into http://gedcomlibrary.com/list.html for sample files "http://gedcomlibrary.com/gedcoms/gl120368.ged", // "http://GedcomLibrary.com/gedcoms/gl120367.ged", // "http://GedcomLibrary.com/gedcoms/liverpool.ged", // "http://GedcomLibrary.com/gedcoms/misc2a.ged", // "http://GedcomLibrary.com/gedcoms/gl120372.ged"}; for (String importUrlString : importList) { diagramWindowManager.openImportPanel(importUrlString); } } private void savePdfMenuItemActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: // todo: implement pdf export new DiagramTranscoder().saveAsPdf(diagramWindowManager.getCurrentSavePanel()); new DiagramTranscoder().saveAsJpg(diagramWindowManager.getCurrentSavePanel()); } private void exportToRActionPerformed(java.awt.event.ActionEvent evt) { // public KinTermSavePanel getKinTermPanel() { // Object selectedComponent = jTabbedPane1.getComponentAt(jTabbedPane1.getSelectedIndex()); // KinTermSavePanel kinTermSavePanel = null; SavePanel currentSavePanel = diagramWindowManager.getCurrentSavePanel(); if (currentSavePanel instanceof KinTermSavePanel) { new ExportToR().doExport(this, (KinTermSavePanel) currentSavePanel); } } private void entityUploadMenuItemActionPerformed(java.awt.event.ActionEvent evt) { diagramWindowManager.openEntityUploadPanel(); } private void saveAsDefaultMenuItemActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(KinDiagramPanel.getDefaultDiagramFile()); } }
desktop/src/main/java/nl/mpi/kinnate/ui/menu/FileMenu.java
package nl.mpi.kinnate.ui.menu; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.export.ExportToR; import nl.mpi.kinnate.transcoder.DiagramTranscoder; import nl.mpi.kinnate.ui.ImportSamplesFileMenu; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.window.AbstractDiagramManager; /** * Document : FileMenu * Created on : Dec 1, 2011, 4:04:06 PM * Author : Peter Withers */ public class FileMenu extends javax.swing.JMenu { private javax.swing.JMenuItem ImportGedcomUrl; private javax.swing.JMenuItem closeTabMenuItem; private javax.swing.JMenuItem entityUploadMenuItem; private javax.swing.JMenuItem exitApplication; private javax.swing.JMenuItem exportToR; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JPopupMenu.Separator jSeparator4; private javax.swing.JPopupMenu.Separator jSeparator5; private javax.swing.JMenuItem newDiagramMenuItem; private javax.swing.JMenuItem openDiagram; private RecentFileMenu recentFileMenu; private javax.swing.JMenuItem saveAsDefaultMenuItem; private javax.swing.JMenuItem saveDiagram; private javax.swing.JMenuItem saveDiagramAs; private javax.swing.JMenuItem savePdfMenuItem; AbstractDiagramManager diagramWindowManager; public FileMenu(AbstractDiagramManager diagramWindowManager) { this.diagramWindowManager = diagramWindowManager; ImportGedcomUrl = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); newDiagramMenuItem = new javax.swing.JMenuItem(); jMenu3 = new DocumentNewMenu(diagramWindowManager); openDiagram = new javax.swing.JMenuItem(); recentFileMenu = new RecentFileMenu(diagramWindowManager); jMenu1 = new SamplesFileMenu(diagramWindowManager); jMenu2 = new ImportSamplesFileMenu(diagramWindowManager); jSeparator2 = new javax.swing.JPopupMenu.Separator(); entityUploadMenuItem = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); saveDiagram = new javax.swing.JMenuItem(); saveDiagramAs = new javax.swing.JMenuItem(); savePdfMenuItem = new javax.swing.JMenuItem(); exportToR = new javax.swing.JMenuItem(); closeTabMenuItem = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); saveAsDefaultMenuItem = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JPopupMenu.Separator(); exitApplication = new javax.swing.JMenuItem(); // todo: Ticket #1297 add an import gedcom and csv menu item this.setText("File"); this.addMenuListener(new javax.swing.event.MenuListener() { public void menuSelected(javax.swing.event.MenuEvent evt) { fileMenuMenuSelected(evt); } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuCanceled(javax.swing.event.MenuEvent evt) { } }); this.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fileMenuActionPerformed(evt); } }); ImportGedcomUrl.setText("Import Gedcom Samples (from internet)"); ImportGedcomUrl.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ImportGedcomUrlActionPerformed(evt); } }); this.add(ImportGedcomUrl); this.add(jSeparator1); newDiagramMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); newDiagramMenuItem.setText("New (default diagram)"); newDiagramMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newDiagramMenuItemActionPerformed(evt); } }); this.add(newDiagramMenuItem); jMenu3.setText("New Diagram of Type"); this.add(jMenu3); openDiagram.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); openDiagram.setText("Open"); openDiagram.setActionCommand("open"); openDiagram.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openDiagramActionPerformed(evt); } }); this.add(openDiagram); this.add(recentFileMenu); jMenu1.setText("Open Sample Diagram"); this.add(jMenu1); jMenu2.setText("Import Sample Data"); this.add(jMenu2); this.add(jSeparator2); entityUploadMenuItem.setText("Entity Upload"); entityUploadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { entityUploadMenuItemActionPerformed(evt); } }); this.add(entityUploadMenuItem); this.add(jSeparator4); saveDiagram.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); saveDiagram.setText("Save"); saveDiagram.setActionCommand("save"); saveDiagram.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveDiagramActionPerformed(evt); } }); this.add(saveDiagram); saveDiagramAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveDiagramAs.setText("Save As"); saveDiagramAs.setActionCommand("saveas"); saveDiagramAs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveDiagramAsActionPerformed(evt); } }); this.add(saveDiagramAs); savePdfMenuItem.setText("Export as PDF"); savePdfMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { savePdfMenuItemActionPerformed(evt); } }); this.add(savePdfMenuItem); exportToR.setText("Export to R / SPSS"); exportToR.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportToRActionPerformed(evt); } }); this.add(exportToR); closeTabMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK)); closeTabMenuItem.setText("Close"); closeTabMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeTabMenuItemActionPerformed(evt); } }); this.add(closeTabMenuItem); this.add(jSeparator3); saveAsDefaultMenuItem.setText("Save as Default Diagram"); saveAsDefaultMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveAsDefaultMenuItemActionPerformed(evt); } }); this.add(saveAsDefaultMenuItem); this.add(jSeparator5); exitApplication.setText("Exit"); exitApplication.setActionCommand("exit"); exitApplication.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitApplicationActionPerformed(evt); } }); this.add(exitApplication); } private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) { } private void openDiagramActionPerformed(java.awt.event.ActionEvent evt) { final File[] selectedFilesArray = ArbilWindowManager.getSingleInstance().showFileSelectBox("Open Kin Diagram", false, true, false); if (selectedFilesArray != null) { for (File selectedFile : selectedFilesArray) { diagramWindowManager.openDiagram(selectedFile.getName(), selectedFile.toURI(), true); } } } private void saveDiagramActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(); } private void saveDiagramAsActionPerformed(java.awt.event.ActionEvent evt) { // todo: update the file select to limit to svg and test that a file has been selected // todo: move this into the arbil window manager and get the last used directory // todo: make sure the file has the svg suffix JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new FileFilter() { @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } return (file.getName().toLowerCase().endsWith(".svg")); } @Override public String getDescription() { return "Scalable Vector Graphics (SVG)"; } }); int returnVal = fc.showSaveDialog(this); // make sure the file path ends in .svg lowercase if (returnVal == JFileChooser.APPROVE_OPTION) { File svgFile = fc.getSelectedFile(); if (!svgFile.getName().toLowerCase().endsWith(".svg")) { svgFile = new File(svgFile.getParentFile(), svgFile.getName() + ".svg"); } int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(svgFile); recentFileMenu.addRecentFile(svgFile); diagramWindowManager.setDiagramTitle(tabIndex, svgFile.getName()); } else { // todo: warn user that no file selected and so cannot save } // File selectedFile[] = LinorgWindowManager.getSingleInstance().showFileSelectBox("Save Kin Diagram", false, false, false); // if (selectedFile != null && selectedFile.length > 0) { // int tabIndex = Integer.valueOf(evt.getActionCommand()); // SavePanel savePanel = getSavePanel(tabIndex); // savePanel.saveToFile(selectedFile[0]); // jTabbedPane1.setTitleAt(tabIndex, selectedFile[0].getName()); // } else { // // todo: warn user that no file selected and so cannot save // } } private void exitApplicationActionPerformed(java.awt.event.ActionEvent evt) { // check that things are saved and ask user if not if (diagramWindowManager.offerUserToSaveAll()) { System.exit(0); } } private void fileMenuMenuSelected(javax.swing.event.MenuEvent evt) { // set the save, save as and close text to include the tab to which the action will occur int selectedIndex = diagramWindowManager.getSavePanelIndex(); SavePanel savePanel = null; if (selectedIndex > -1) { String currentTabText = diagramWindowManager.getSavePanelTitle(selectedIndex); savePanel = diagramWindowManager.getSavePanel(selectedIndex); saveDiagramAs.setText("Save As (" + currentTabText + ")"); saveDiagramAs.setActionCommand(Integer.toString(selectedIndex)); saveDiagram.setText("Save (" + currentTabText + ")"); saveDiagram.setActionCommand(Integer.toString(selectedIndex)); closeTabMenuItem.setText("Close (" + currentTabText + ")"); closeTabMenuItem.setActionCommand(Integer.toString(selectedIndex)); saveAsDefaultMenuItem.setText("Set Default Diagram as (" + currentTabText + ")"); saveAsDefaultMenuItem.setActionCommand(Integer.toString(selectedIndex)); } if (savePanel != null) { saveDiagram.setEnabled(savePanel.hasSaveFileName() && savePanel.requiresSave()); saveDiagramAs.setEnabled(true); exportToR.setEnabled(true); closeTabMenuItem.setEnabled(true); saveAsDefaultMenuItem.setEnabled(true); savePdfMenuItem.setEnabled(true); } else { saveDiagramAs.setEnabled(false); saveDiagram.setEnabled(false); exportToR.setEnabled(false); closeTabMenuItem.setEnabled(false); saveAsDefaultMenuItem.setEnabled(false); savePdfMenuItem.setEnabled(false); } } private void closeTabMenuItemActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); String diagramTitle = diagramWindowManager.getSavePanelTitle(tabIndex); boolean userCanceled = diagramWindowManager.offerUserToSave(savePanel, diagramTitle); if (!userCanceled) { diagramWindowManager.closeSavePanel(tabIndex); } } private void newDiagramMenuItemActionPerformed(java.awt.event.ActionEvent evt) { diagramWindowManager.newDiagram(); } private void ImportGedcomUrlActionPerformed(java.awt.event.ActionEvent evt) { // todo: Ticket #1297 either remove this or change it so it does not open so many tabs / windows String[] importList = new String[]{"http://gedcomlibrary.com/gedcoms.html", "http://GedcomLibrary.com/gedcoms/gl120365.ged", // Tammy Carter Inman "http://GedcomLibrary.com/gedcoms/gl120366.ged", // Luis Lemonnier "http://GedcomLibrary.com/gedcoms/gl120367.ged", // Cheryl Marion Follansbee // New England Genealogical Detective "http://GedcomLibrary.com/gedcoms/gl120368.ged", // Phil Willaims "http://GedcomLibrary.com/gedcoms/gl120369.ged", // Francisco Casta�eda "http://GedcomLibrary.com/gedcoms/gl120370.ged", // Kim Carter "http://GedcomLibrary.com/gedcoms/gl120371.ged", // Maria Perusia "http://GedcomLibrary.com/gedcoms/gl120372.ged", // R. J. Bosman "http://GedcomLibrary.com/gedcoms/liverpool.ged", // William Robinette "http://GedcomLibrary.com/gedcoms/misc2a.ged", // William Robinette "http://GedcomLibrary.com/gedcoms/myline.ged", // William Robinette // also look into http://gedcomlibrary.com/list.html for sample files "http://gedcomlibrary.com/gedcoms/gl120368.ged", // "http://GedcomLibrary.com/gedcoms/gl120367.ged", // "http://GedcomLibrary.com/gedcoms/liverpool.ged", // "http://GedcomLibrary.com/gedcoms/misc2a.ged", // "http://GedcomLibrary.com/gedcoms/gl120372.ged"}; for (String importUrlString : importList) { diagramWindowManager.openImportPanel(importUrlString); } } private void savePdfMenuItemActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: // todo: implement pdf export new DiagramTranscoder().saveAsPdf(diagramWindowManager.getCurrentSavePanel()); new DiagramTranscoder().saveAsJpg(diagramWindowManager.getCurrentSavePanel()); } private void exportToRActionPerformed(java.awt.event.ActionEvent evt) { // public KinTermSavePanel getKinTermPanel() { // Object selectedComponent = jTabbedPane1.getComponentAt(jTabbedPane1.getSelectedIndex()); // KinTermSavePanel kinTermSavePanel = null; SavePanel currentSavePanel = diagramWindowManager.getCurrentSavePanel(); if (currentSavePanel instanceof KinTermSavePanel) { new ExportToR().doExport(this, (KinTermSavePanel) currentSavePanel); } } private void entityUploadMenuItemActionPerformed(java.awt.event.ActionEvent evt) { diagramWindowManager.openEntityUploadPanel(); } private void saveAsDefaultMenuItemActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(KinDiagramPanel.getDefaultDiagramFile()); } }
Added import of csv and gedcom via a file select action.
desktop/src/main/java/nl/mpi/kinnate/ui/menu/FileMenu.java
Added import of csv and gedcom via a file select action.
<ide><path>esktop/src/main/java/nl/mpi/kinnate/ui/menu/FileMenu.java <ide> <ide> import java.io.File; <ide> import javax.swing.JFileChooser; <del>import javax.swing.JOptionPane; <ide> import javax.swing.filechooser.FileFilter; <ide> import nl.mpi.arbil.ui.ArbilWindowManager; <ide> import nl.mpi.kinnate.KinTermSavePanel; <ide> */ <ide> public class FileMenu extends javax.swing.JMenu { <ide> <del> private javax.swing.JMenuItem ImportGedcomUrl; <add> private javax.swing.JMenuItem importGedcomUrl; <add> private javax.swing.JMenuItem importGedcomFile; <add> private javax.swing.JMenuItem importCsvFile; <ide> private javax.swing.JMenuItem closeTabMenuItem; <ide> private javax.swing.JMenuItem entityUploadMenuItem; <ide> private javax.swing.JMenuItem exitApplication; <ide> <ide> public FileMenu(AbstractDiagramManager diagramWindowManager) { <ide> this.diagramWindowManager = diagramWindowManager; <del> ImportGedcomUrl = new javax.swing.JMenuItem(); <add> importGedcomUrl = new javax.swing.JMenuItem(); <add> importGedcomFile = new javax.swing.JMenuItem(); <add> importCsvFile = new javax.swing.JMenuItem(); <ide> jSeparator1 = new javax.swing.JPopupMenu.Separator(); <ide> newDiagramMenuItem = new javax.swing.JMenuItem(); <ide> jMenu3 = new DocumentNewMenu(diagramWindowManager); <ide> } <ide> }); <ide> <del> ImportGedcomUrl.setText("Import Gedcom Samples (from internet)"); <del> ImportGedcomUrl.addActionListener(new java.awt.event.ActionListener() { <del> <del> public void actionPerformed(java.awt.event.ActionEvent evt) { <del> ImportGedcomUrlActionPerformed(evt); <del> } <del> }); <del> this.add(ImportGedcomUrl); <add> importGedcomUrl.setText("Import Gedcom Samples (from internet)"); <add> importGedcomUrl.addActionListener(new java.awt.event.ActionListener() { <add> <add> public void actionPerformed(java.awt.event.ActionEvent evt) { <add> importGedcomUrlActionPerformed(evt); <add> } <add> }); <add> this.add(importGedcomFile); <add> <add> importGedcomFile.setText("Import Gedcom File"); <add> importGedcomFile.addActionListener(new java.awt.event.ActionListener() { <add> <add> public void actionPerformed(java.awt.event.ActionEvent evt) { <add> importGedcomFileActionPerformed(evt); <add> } <add> }); <add> this.add(importGedcomFile); <add> <add> importCsvFile.setText("Import CSV File"); <add> importCsvFile.addActionListener(new java.awt.event.ActionListener() { <add> <add> public void actionPerformed(java.awt.event.ActionEvent evt) { <add> importCsvFileActionPerformed(evt); <add> } <add> }); <add> this.add(importCsvFile); <add> <ide> this.add(jSeparator1); <ide> <ide> newDiagramMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); <ide> diagramWindowManager.newDiagram(); <ide> } <ide> <del> private void ImportGedcomUrlActionPerformed(java.awt.event.ActionEvent evt) { <add> private void importGedcomFileActionPerformed(java.awt.event.ActionEvent evt) { <add> } <add> <add> private void importCsvFileActionPerformed(java.awt.event.ActionEvent evt) { <add> } <add> <add> private void importGedcomUrlActionPerformed(java.awt.event.ActionEvent evt) { <ide> // todo: Ticket #1297 either remove this or change it so it does not open so many tabs / windows <ide> String[] importList = new String[]{"http://gedcomlibrary.com/gedcoms.html", <ide> "http://GedcomLibrary.com/gedcoms/gl120365.ged", // Tammy Carter Inman
Java
lgpl-2.1
916781aa3179e889adf5a3c2ea76dfeff9ec8870
0
mbenz89/soot,cfallin/soot,plast-lab/soot,xph906/SootNew,xph906/SootNew,anddann/soot,cfallin/soot,mbenz89/soot,anddann/soot,mbenz89/soot,cfallin/soot,plast-lab/soot,xph906/SootNew,mbenz89/soot,anddann/soot,xph906/SootNew,anddann/soot,plast-lab/soot,cfallin/soot
package soot.jimple.toolkits.thread.transaction; import java.util.*; import soot.*; import soot.util.Chain; import soot.jimple.*; import soot.jimple.toolkits.callgraph.CallGraph; import soot.toolkits.scalar.*; public class TransactionBodyTransformer extends BodyTransformer { private static TransactionBodyTransformer instance = new TransactionBodyTransformer(); private TransactionBodyTransformer() {} public static TransactionBodyTransformer v() { return instance; } // private FlowSet fs; // private int maxLockObjs; // private boolean[] useGlobalLock; // public void setDetails(FlowSet fs, int maxLockObjs, boolean[] useGlobalLock) // { // this.fs = fs; // this.maxLockObjs = maxLockObjs; // this.useGlobalLock = useGlobalLock; // } public static boolean[] addedGlobalLockObj = null; private static boolean addedGlobalLockDefs = false; private static int throwableNum = 0; // doesn't matter if not reinitialized to 0 protected void internalTransform(Body b, String phase, Map opts) { throw new RuntimeException("Not Supported"); } protected void internalTransform(Body b, FlowSet fs, List groups) { // JimpleBody j = (JimpleBody) b; SootMethod thisMethod = b.getMethod(); PatchingChain units = b.getUnits(); Iterator unitIt = units.iterator(); Unit firstUnit = (Unit) j.getFirstNonIdentityStmt(); Unit lastUnit = (Unit) units.getLast(); // Objects of synchronization, plus book keeping Local[] lockObj = new Local[groups.size()]; boolean[] addedLocalLockObj = new boolean[groups.size()]; SootField[] globalLockObj = new SootField[groups.size()]; for(int i = 1; i < groups.size(); i++) { lockObj[i] = Jimple.v().newLocal("lockObj" + i, RefType.v("java.lang.Object")); addedLocalLockObj[i] = false; globalLockObj[i] = null; } // Make sure a main routine exists. We will insert some code into it. // if (!Scene.v().getMainClass().declaresMethod("void main(java.lang.String[])")) // throw new RuntimeException("couldn't find main() in mainClass"); // Add all global lock objects to the main class if not yet added. // Get references to them if they do already exist. for(int i = 1; i < groups.size(); i++) { TransactionGroup tnGroup = (TransactionGroup) groups.get(i); // if( useGlobalLock[i - 1] ) if( !tnGroup.useDynamicLock && !tnGroup.useLocksets ) { if( !addedGlobalLockObj[i] ) { // Add globalLockObj field if possible... // Avoid name collision... if it's already there, then just use it! try { globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i); // field already exists } catch(RuntimeException re) { // field does not yet exist (or, as a pre-existing error, there is more than one field by this name) globalLockObj[i] = new SootField("globalLockObj" + i, RefType.v("java.lang.Object"), Modifier.STATIC | Modifier.PUBLIC); Scene.v().getMainClass().addField(globalLockObj[i]); } addedGlobalLockObj[i] = true; } else { globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i); } } } // If the current method is the clinit method of the main class, for each global lock object, // add a local lock object and assign it a new object. Copy the new // local lock object into the global lock object for use by other fns. if(!addedGlobalLockDefs)// thisMethod.getSubSignature().equals("void <clinit>()") && thisMethod.getDeclaringClass() == Scene.v().getMainClass()) { // Either get or add the <clinit> method to the main class SootClass mainClass = Scene.v().getMainClass(); SootMethod clinitMethod = null; JimpleBody clinitBody = null; Stmt firstStmt = null; boolean addingNewClinit = !mainClass.declaresMethod("void <clinit>()"); if(addingNewClinit) { clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); clinitBody = Jimple.v().newBody(clinitMethod); clinitMethod.setActiveBody(clinitBody); mainClass.addMethod(clinitMethod); } else { clinitMethod = mainClass.getMethod("void <clinit>()"); clinitBody = (JimpleBody) clinitMethod.getActiveBody(); firstStmt = clinitBody.getFirstNonIdentityStmt(); } PatchingChain clinitUnits = clinitBody.getUnits(); for(int i = 1; i < groups.size(); i++) { TransactionGroup tnGroup = (TransactionGroup) groups.get(i); // if( useGlobalLock[i - 1] ) if( !tnGroup.useDynamicLock && !tnGroup.useLocksets ) { // add local lock obj // addedLocalLockObj[i] = true; clinitBody.getLocals().add(lockObj[i]); // TODO: add name conflict avoidance code // assign new object to lock obj Stmt newStmt = Jimple.v().newAssignStmt(lockObj[i], Jimple.v().newNewExpr(RefType.v("java.lang.Object"))); if(addingNewClinit) clinitUnits.add(newStmt); else clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt); // initialize new object SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object"); RefType type = RefType.v(objectClass); SootMethod initMethod = objectClass.getMethod("void <init>()"); Stmt initStmt = Jimple.v().newInvokeStmt( Jimple.v().newSpecialInvokeExpr(lockObj[i], initMethod.makeRef(), Collections.EMPTY_LIST)); if(addingNewClinit) clinitUnits.add(initStmt); else clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt); // copy new object to global static lock object (for use by other fns) Stmt assignStmt = Jimple.v().newAssignStmt( Jimple.v().newStaticFieldRef(globalLockObj[i].makeRef()), lockObj[i]); if(addingNewClinit) clinitUnits.add(assignStmt); else clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt); } } if(addingNewClinit) clinitUnits.add(Jimple.v().newReturnVoidStmt()); addedGlobalLockDefs = true; } int tempNum = 1; // Iterate through all of the transactions in the current method Iterator fsIt = fs.iterator(); while(fsIt.hasNext()) { Transaction tn = ((TransactionFlowPair) fsIt.next()).tn; if(tn.setNumber == -1) continue; // this tn should be deleted... for now just skip it! Local clo = null; // depends on type of locking LockRegion clr = null; // current lock region int lockNum = 0; boolean moreLocks = true; while(moreLocks) { // If this method does not yet have a reference to the lock object // needed for this transaction, then create one. if( tn.group.useDynamicLock ) { if(!addedLocalLockObj[tn.setNumber]) { b.getLocals().add(lockObj[tn.setNumber]); addedLocalLockObj[tn.setNumber] = true; } if(tn.lockObject instanceof Ref) { Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], tn.lockObject); if(tn.wholeMethod) units.insertBeforeNoRedirect(assignLocalLockStmt, (Stmt) firstUnit); else units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); clo = lockObj[tn.setNumber]; } else if(tn.lockObject instanceof Local) clo = (Local) tn.lockObject; else throw new RuntimeException("Unknown type of lock (" + tn.lockObject + "): expected Ref or Local"); clr = tn; moreLocks = false; } else if( tn.group.useLocksets ) { Value lock = getLockFor((EquivalentValue) tn.lockset.get(lockNum)); // adds local vars and global objects if needed if( lock instanceof FieldRef ) { // add a local variable for this lock Local lockLocal = Jimple.v().newLocal("locksetObj" + tempNum, RefType.v("java.lang.Object")); tempNum++; b.getLocals().add(lockLocal); // make it refer to the right lock object Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockLocal, lock); if(tn.entermonitor != null) units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); else units.insertBeforeNoRedirect(assignLocalLockStmt, (Stmt) tn.beginning); // use it as the lock clo = lockLocal; } else if( lock instanceof Local ) clo = (Local) lock; else throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local"); if(lockNum + 1 >= tn.lockset.size()) moreLocks = false; else moreLocks = true; if( lockNum > 0 ) { LockRegion nlr = new LockRegion(); nlr.beginning = clr.beginning; for(Iterator earlyEndsIt = clr.earlyEnds.iterator(); earlyEndsIt.hasNext(); ) { Pair earlyEnd = (Pair) earlyEndsIt.next(); // <early end, early exitmonitor> Stmt earlyExitmonitor = (Stmt) earlyEnd.getO2(); nlr.earlyEnds.add(new Pair(earlyExitmonitor, null)); // <early exitmonitor, null> } if(clr.end != null) { Stmt endExitmonitor = (Stmt) clr.end.getO2(); nlr.after = endExitmonitor; } clr = nlr; } else clr = tn; } else // global lock { if(!addedLocalLockObj[tn.setNumber]) b.getLocals().add(lockObj[tn.setNumber]); addedLocalLockObj[tn.setNumber] = true; Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], Jimple.v().newStaticFieldRef(globalLockObj[tn.setNumber].makeRef())); if(tn.wholeMethod) units.insertBeforeNoRedirect(assignLocalLockStmt, firstUnit); else units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); clo = lockObj[tn.setNumber]; clr = tn; moreLocks = false; } // Add synchronization code // For transactions from synchronized methods, use synchronizeSingleEntrySingleExitBlock() // to add all necessary code (including ugly exception handling) // For transactions from synchronized blocks, simply replace the // monitorenter/monitorexit statements with new ones if(true) { // Remove old prep stmt if( clr.prepStmt != null ) { units.remove(clr.prepStmt); } // Reuse old entermonitor or insert new one, and insert prep Stmt newEntermonitor = Jimple.v().newEnterMonitorStmt(clo); if( clr.entermonitor != null ) { units.insertBefore(newEntermonitor, clr.entermonitor); // redirectTraps(b, clr.entermonitor, newEntermonitor); // EXPERIMENTAL units.remove(clr.entermonitor); clr.entermonitor = newEntermonitor; // units.insertBefore(newEntermonitor, newPrep); // clr.prepStmt = newPrep; } else { units.insertBeforeNoRedirect(newEntermonitor, clr.beginning); clr.entermonitor = newEntermonitor; // units.insertBefore(newEntermonitor, newPrep); // clr.prepStmt = newPrep; } // For each early end, reuse or insert exitmonitor stmt List newEarlyEnds = new ArrayList(); for(Iterator earlyEndsIt = clr.earlyEnds.iterator(); earlyEndsIt.hasNext(); ) { Pair end = (Pair) earlyEndsIt.next(); Stmt earlyEnd = (Stmt) end.getO1(); Stmt exitmonitor = (Stmt) end.getO2(); Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo); if( exitmonitor != null ) { units.insertBefore(newExitmonitor, exitmonitor); // redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL units.remove(exitmonitor); newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor)); } else { units.insertBefore(newExitmonitor, earlyEnd); newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor)); } } clr.earlyEnds = newEarlyEnds; // If fallthrough end, reuse or insert goto and exit if( clr.after != null ) { Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo); if( clr.end != null ) { Stmt exitmonitor = (Stmt) clr.end.getO2(); units.insertBefore(newExitmonitor, exitmonitor); // redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL units.remove(exitmonitor); clr.end = new Pair(clr.end.getO1(), newExitmonitor); } else { units.insertBefore(newExitmonitor, clr.after); // steal jumps to end, send them to monitorexit Stmt newGotoStmt = Jimple.v().newGotoStmt(clr.after); units.insertBeforeNoRedirect(newGotoStmt, clr.after); clr.end = new Pair(newGotoStmt, newExitmonitor); } } // If exceptional end, reuse it, else insert it and traps Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo); if( clr.exceptionalEnd != null ) { Stmt exitmonitor = (Stmt) clr.exceptionalEnd.getO2(); units.insertBefore(newExitmonitor, exitmonitor); // redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL units.remove(exitmonitor); clr.exceptionalEnd = new Pair(clr.end.getO1(), newExitmonitor); } else { // insert after the last end Stmt lastEnd = null; if( clr.end != null ) { lastEnd = (Stmt) clr.end.getO1(); } else { for(Iterator earlyEndsIt = clr.earlyEnds.iterator(); earlyEndsIt.hasNext(); ) { Pair earlyEnd = (Pair) earlyEndsIt.next(); Stmt end = (Stmt) earlyEnd.getO1(); if( lastEnd == null || units.follows(end, lastEnd) ) lastEnd = end; } } if(lastEnd == null) throw new RuntimeException("Lock Region has no ends! Where should we put the exception handling???"); // Add throwable Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable")); b.getLocals().add(throwableLocal); // Add stmts Stmt newCatch = Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef()); units.insertAfter(newCatch, lastEnd); units.insertAfter(newExitmonitor, newCatch); Stmt newThrow = Jimple.v().newThrowStmt(throwableLocal); units.insertAfter(newThrow, newExitmonitor); // Add traps SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable"); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, clr.beginning, lastEnd, newCatch)); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, newExitmonitor, newThrow, newCatch)); clr.exceptionalEnd = new Pair(newThrow, newExitmonitor); } } /* else if(tn.wholeMethod) { thisMethod.setModifiers( thisMethod.getModifiers() & ~ (Modifier.SYNCHRONIZED) ); // remove synchronized modifier for this method synchronizeSingleEntrySingleExitBlock(b, (Stmt) firstUnit, (Stmt) lastUnit, (Local) clo); } else if(lockNum > 0) { // don't have all the info to do this right yet // synchronizeSingleEntrySingleExitBlock(b, (Stmt) tnbodystart, (Stmt) tnbodyend, (Local) clo); } else { if(tn.entermonitor == null) G.v().out.println("ERROR: Transaction has no beginning statement: " + tn.method.toString()); // Deal with entermonitor Stmt newBegin = Jimple.v().newEnterMonitorStmt(clo); units.insertBefore(newBegin, tn.entermonitor); redirectTraps(b, tn.entermonitor, newBegin); units.remove(tn.entermonitor); // Deal with exitmonitors // early Iterator endsIt = tn.earlyEnds.iterator(); while(endsIt.hasNext()) { Pair end = (Pair) endsIt.next(); Stmt sEnd = (Stmt) end.getO2(); Stmt newEnd = Jimple.v().newExitMonitorStmt(clo); units.insertBefore(newEnd, sEnd); redirectTraps(b, sEnd, newEnd); units.remove(sEnd); } // exceptional Stmt sEnd = (Stmt) tn.exceptionalEnd.getO2(); Stmt newEnd = Jimple.v().newExitMonitorStmt(clo); units.insertBefore(newEnd, sEnd); redirectTraps(b, sEnd, newEnd); units.remove(sEnd); // fallthrough sEnd = (Stmt) tn.end.getO2(); newEnd = Jimple.v().newExitMonitorStmt(clo); units.insertBefore(newEnd, sEnd); redirectTraps(b, sEnd, newEnd); units.remove(sEnd); } */ // Replace calls to notify() with calls to notifyAll() // Replace base object with appropriate lockobj lockNum++; } // deal with waits and notifys { Iterator notifysIt = tn.notifys.iterator(); while(notifysIt.hasNext()) { Stmt sNotify = (Stmt) notifysIt.next(); Stmt newNotify = Jimple.v().newInvokeStmt( Jimple.v().newVirtualInvokeExpr( (Local) clo, sNotify.getInvokeExpr().getMethodRef().declaringClass().getMethod("void notifyAll()").makeRef(), Collections.EMPTY_LIST)); units.insertBefore(newNotify, sNotify); redirectTraps(b, sNotify, newNotify); units.remove(sNotify); } // Replace base object of calls to wait with appropriate lockobj Iterator waitsIt = tn.waits.iterator(); while(waitsIt.hasNext()) { Stmt sWait = (Stmt) waitsIt.next(); ((InstanceInvokeExpr) sWait.getInvokeExpr()).setBase(clo); // WHAT IF THIS IS THE WRONG LOCK IN A PAIR OF NESTED LOCKS??? // Stmt newWait = // Jimple.v().newInvokeStmt( // Jimple.v().newVirtualInvokeExpr( // (Local) clo, // sWait.getInvokeExpr().getMethodRef().declaringClass().getMethod("void wait()").makeRef(), // Collections.EMPTY_LIST)); // units.insertBefore(newWait, sWait); // redirectTraps(b, sWait, newWait); // units.remove(sWait); } } } } static int lockNumber = 0; Map lockEqValToLock = new HashMap(); public Value getLockFor(EquivalentValue lockEqVal) { Value lock = lockEqVal.getValue(); if( lock instanceof InstanceFieldRef ) return lock; if( lock instanceof Local ) return lock; if( lock instanceof StaticFieldRef ) { if( lockEqValToLock.containsKey(lockEqVal) ) return (Value) lockEqValToLock.get(lockEqVal); StaticFieldRef sfrLock = (StaticFieldRef) lock; SootClass lockClass = sfrLock.getField().getDeclaringClass(); SootMethod clinitMethod = null; JimpleBody clinitBody = null; Stmt firstStmt = null; boolean addingNewClinit = !lockClass.declaresMethod("void <clinit>()"); if(addingNewClinit) { clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); clinitBody = Jimple.v().newBody(clinitMethod); clinitMethod.setActiveBody(clinitBody); lockClass.addMethod(clinitMethod); } else { clinitMethod = lockClass.getMethod("void <clinit>()"); clinitBody = (JimpleBody) clinitMethod.getActiveBody(); firstStmt = clinitBody.getFirstNonIdentityStmt(); } PatchingChain clinitUnits = clinitBody.getUnits(); Local lockLocal = Jimple.v().newLocal("objectLockLocal" + lockNumber, RefType.v("java.lang.Object")); // lockNumber is increased below clinitBody.getLocals().add(lockLocal); // TODO: add name conflict avoidance code // assign new object to lock obj Stmt newStmt = Jimple.v().newAssignStmt(lockLocal, Jimple.v().newNewExpr(RefType.v("java.lang.Object"))); if(addingNewClinit) clinitUnits.add(newStmt); else clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt); // initialize new object SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object"); RefType type = RefType.v(objectClass); SootMethod initMethod = objectClass.getMethod("void <init>()"); Stmt initStmt = Jimple.v().newInvokeStmt( Jimple.v().newSpecialInvokeExpr(lockLocal, initMethod.makeRef(), Collections.EMPTY_LIST)); if(addingNewClinit) clinitUnits.add(initStmt); else clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt); // copy new object to global static lock object (for use by other fns) SootField actualLockObject = new SootField("objectLockGlobal" + lockNumber, RefType.v("java.lang.Object"), Modifier.STATIC | Modifier.PUBLIC); lockNumber++; lockClass.addField(actualLockObject); StaticFieldRef actualLockSfr = Jimple.v().newStaticFieldRef(actualLockObject.makeRef()); Stmt assignStmt = Jimple.v().newAssignStmt(actualLockSfr, lockLocal); if(addingNewClinit) clinitUnits.add(assignStmt); else clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt); if(addingNewClinit) clinitUnits.add(Jimple.v().newReturnVoidStmt()); lockEqValToLock.put(lockEqVal, actualLockSfr); return actualLockSfr; } throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local"); } /* public void synchronizeSingleEntrySingleExitBlock(Body b, Stmt start, Stmt end, Local lockObj) { PatchingChain units = b.getUnits(); // <existing local defs> // add a throwable to local vars Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable")); b.getLocals().add(throwableLocal); // <existing identity refs> // add entermonitor statement and label0 // Unit label0Unit = start; Unit labelEnterMonitorStmt = Jimple.v().newEnterMonitorStmt(lockObj); units.insertBeforeNoRedirect(labelEnterMonitorStmt, start); // steal jumps to start, send them to monitorenter // <existing code body> check for return statements List returnUnits = new ArrayList(); if(start != end) { Iterator bodyIt = units.iterator(start, end); while(bodyIt.hasNext()) { Stmt bodyStmt = (Stmt) bodyIt.next(); if(bodyIt.hasNext()) // ignore the end unit { if( bodyStmt instanceof ReturnStmt || bodyStmt instanceof ReturnVoidStmt) { returnUnits.add(bodyStmt); } } } } // add normal flow and labels Unit labelExitMonitorStmt = (Unit) Jimple.v().newExitMonitorStmt(lockObj); units.insertBefore(labelExitMonitorStmt, end); // steal jumps to end, send them to monitorexit // end = (Stmt) units.getSuccOf(end); Unit label1Unit = (Unit) Jimple.v().newGotoStmt(end); units.insertBeforeNoRedirect(label1Unit, end); // end = (Stmt) units.getSuccOf(end); // add exceptional flow and labels Unit label2Unit = (Unit) Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef()); units.insertBeforeNoRedirect(label2Unit, end); // end = (Stmt) units.getSuccOf(end); Unit label3Unit = (Unit) Jimple.v().newExitMonitorStmt(lockObj); units.insertBeforeNoRedirect(label3Unit, end); // end = (Stmt) units.getSuccOf(end); Unit label4Unit = (Unit) Jimple.v().newThrowStmt(throwableLocal); units.insertBeforeNoRedirect(label4Unit, end); // end = (Stmt) units.getSuccOf(end); // <existing end statement> Iterator returnIt = returnUnits.iterator(); while(returnIt.hasNext()) { Stmt bodyStmt = (Stmt) returnIt.next(); units.insertBefore(Jimple.v().newExitMonitorStmt(lockObj), bodyStmt); // TODO: WHAT IF IT'S IN A NESTED TRANSACTION??? // Stmt placeholder = Jimple.v().newNopStmt(); // units.insertAfter(Jimple.v().newNopStmt(), label4Unit); // bodyStmt.redirectJumpsToThisTo(placeholder); // units.insertBefore(Jimple.v().newGotoStmt(placeholder), bodyStmt); // units.remove(bodyStmt); // units.swapWith(placeholder, bodyStmt); // units.swapWith } // add exception routing table Unit label0Unit = (Unit) units.getSuccOf(labelEnterMonitorStmt); SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable"); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label0Unit, label1Unit, label2Unit)); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label3Unit, label4Unit, label2Unit)); } */ public void redirectTraps(Body b, Unit oldUnit, Unit newUnit) { Chain traps = b.getTraps(); Iterator trapsIt = traps.iterator(); while(trapsIt.hasNext()) { AbstractTrap trap = (AbstractTrap) trapsIt.next(); if(trap.getHandlerUnit() == oldUnit) trap.setHandlerUnit(newUnit); if(trap.getBeginUnit() == oldUnit) trap.setBeginUnit(newUnit); if(trap.getEndUnit() == oldUnit) trap.setEndUnit(newUnit); } } }
src/soot/jimple/toolkits/thread/transaction/TransactionBodyTransformer.java
package soot.jimple.toolkits.thread.transaction; import java.util.*; import soot.*; import soot.util.Chain; import soot.jimple.*; import soot.jimple.toolkits.callgraph.CallGraph; import soot.toolkits.scalar.*; public class TransactionBodyTransformer extends BodyTransformer { private static TransactionBodyTransformer instance = new TransactionBodyTransformer(); private TransactionBodyTransformer() {} public static TransactionBodyTransformer v() { return instance; } // private FlowSet fs; // private int maxLockObjs; // private boolean[] useGlobalLock; // public void setDetails(FlowSet fs, int maxLockObjs, boolean[] useGlobalLock) // { // this.fs = fs; // this.maxLockObjs = maxLockObjs; // this.useGlobalLock = useGlobalLock; // } public static boolean[] addedGlobalLockObj = null; private static boolean addedGlobalLockDefs = false; private static int throwableNum = 0; // doesn't matter if not reinitialized to 0 protected void internalTransform(Body b, String phase, Map opts) { throw new RuntimeException("Not Supported"); } protected void internalTransform(Body b, FlowSet fs, List groups) { // JimpleBody j = (JimpleBody) b; SootMethod thisMethod = b.getMethod(); PatchingChain units = b.getUnits(); Iterator unitIt = units.iterator(); Unit firstUnit = (Unit) j.getFirstNonIdentityStmt(); Unit lastUnit = (Unit) units.getLast(); // Objects of synchronization, plus book keeping Local[] lockObj = new Local[groups.size()]; boolean[] addedLocalLockObj = new boolean[groups.size()]; SootField[] globalLockObj = new SootField[groups.size()]; for(int i = 1; i < groups.size(); i++) { lockObj[i] = Jimple.v().newLocal("lockObj" + i, RefType.v("java.lang.Object")); addedLocalLockObj[i] = false; globalLockObj[i] = null; } // Make sure a main routine exists. We will insert some code into it. // if (!Scene.v().getMainClass().declaresMethod("void main(java.lang.String[])")) // throw new RuntimeException("couldn't find main() in mainClass"); // Add all global lock objects to the main class if not yet added. // Get references to them if they do already exist. for(int i = 1; i < groups.size(); i++) { TransactionGroup tnGroup = (TransactionGroup) groups.get(i); // if( useGlobalLock[i - 1] ) if( !tnGroup.useDynamicLock && !tnGroup.useLocksets ) { if( !addedGlobalLockObj[i] ) { // Add globalLockObj field if possible... // Avoid name collision... if it's already there, then just use it! try { globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i); // field already exists } catch(RuntimeException re) { // field does not yet exist (or, as a pre-existing error, there is more than one field by this name) globalLockObj[i] = new SootField("globalLockObj" + i, RefType.v("java.lang.Object"), Modifier.STATIC | Modifier.PUBLIC); Scene.v().getMainClass().addField(globalLockObj[i]); } addedGlobalLockObj[i] = true; } else { globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i); } } } // If the current method is the clinit method of the main class, for each global lock object, // add a local lock object and assign it a new object. Copy the new // local lock object into the global lock object for use by other fns. if(!addedGlobalLockDefs)// thisMethod.getSubSignature().equals("void <clinit>()") && thisMethod.getDeclaringClass() == Scene.v().getMainClass()) { // Either get or add the <clinit> method to the main class SootClass mainClass = Scene.v().getMainClass(); SootMethod clinitMethod = null; JimpleBody clinitBody = null; Stmt firstStmt = null; boolean addingNewClinit = !mainClass.declaresMethod("void <clinit>()"); if(addingNewClinit) { clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); clinitBody = Jimple.v().newBody(clinitMethod); clinitMethod.setActiveBody(clinitBody); mainClass.addMethod(clinitMethod); } else { clinitMethod = mainClass.getMethod("void <clinit>()"); clinitBody = (JimpleBody) clinitMethod.getActiveBody(); firstStmt = clinitBody.getFirstNonIdentityStmt(); } PatchingChain clinitUnits = clinitBody.getUnits(); for(int i = 1; i < groups.size(); i++) { TransactionGroup tnGroup = (TransactionGroup) groups.get(i); // if( useGlobalLock[i - 1] ) if( !tnGroup.useDynamicLock && !tnGroup.useLocksets ) { // add local lock obj // addedLocalLockObj[i] = true; clinitBody.getLocals().add(lockObj[i]); // TODO: add name conflict avoidance code // assign new object to lock obj Stmt newStmt = Jimple.v().newAssignStmt(lockObj[i], Jimple.v().newNewExpr(RefType.v("java.lang.Object"))); if(addingNewClinit) clinitUnits.add(newStmt); else clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt); // initialize new object SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object"); RefType type = RefType.v(objectClass); SootMethod initMethod = objectClass.getMethod("void <init>()"); Stmt initStmt = Jimple.v().newInvokeStmt( Jimple.v().newSpecialInvokeExpr(lockObj[i], initMethod.makeRef(), Collections.EMPTY_LIST)); if(addingNewClinit) clinitUnits.add(initStmt); else clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt); // copy new object to global static lock object (for use by other fns) Stmt assignStmt = Jimple.v().newAssignStmt( Jimple.v().newStaticFieldRef(globalLockObj[i].makeRef()), lockObj[i]); if(addingNewClinit) clinitUnits.add(assignStmt); else clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt); } } if(addingNewClinit) clinitUnits.add(Jimple.v().newReturnVoidStmt()); addedGlobalLockDefs = true; } int tempNum = 1; // Iterate through all of the transactions in the current method Iterator fsIt = fs.iterator(); while(fsIt.hasNext()) { Transaction tn = ((TransactionFlowPair) fsIt.next()).tn; if(tn.setNumber == -1) continue; // this tn should be deleted... for now just skip it! Local clo = null; // depends on type of locking LockRegion clr = null; // current lock region int lockNum = 0; boolean moreLocks = true; while(moreLocks) { // If this method does not yet have a reference to the lock object // needed for this transaction, then create one. if( tn.group.useDynamicLock ) { if(!addedLocalLockObj[tn.setNumber]) { b.getLocals().add(lockObj[tn.setNumber]); addedLocalLockObj[tn.setNumber] = true; } if(tn.lockObject instanceof Ref) { Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], tn.lockObject); if(tn.wholeMethod) units.insertBeforeNoRedirect(assignLocalLockStmt, (Stmt) firstUnit); else units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); clo = lockObj[tn.setNumber]; } else if(tn.lockObject instanceof Local) clo = (Local) tn.lockObject; else throw new RuntimeException("Unknown type of lock (" + tn.lockObject + "): expected Ref or Local"); clr = tn; moreLocks = false; } else if( tn.group.useLocksets ) { Value lock = (Value) tn.lockset.get(lockNum); if( lock instanceof EquivalentValue ) // unwrap equivalent value lock = ((EquivalentValue)lock).getValue(); if(!addedLocalLockObj[tn.setNumber]) { b.getLocals().add(lockObj[tn.setNumber]); addedLocalLockObj[tn.setNumber] = true; } if(lock instanceof InstanceFieldRef) { Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], lock); if(tn.entermonitor != null) units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); else units.insertBeforeNoRedirect(assignLocalLockStmt, (Stmt) tn.beginning); clo = lockObj[tn.setNumber]; } else if(lock instanceof StaticFieldRef) { StaticFieldRef sfrLock = (StaticFieldRef) lock; SootField sfrField = sfrLock.getField(); SootClass sfrClass = sfrField.getDeclaringClass(); // add a static lock object to that class // use it here Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], lock); if(tn.entermonitor != null) units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); else units.insertBeforeNoRedirect(assignLocalLockStmt, (Stmt) tn.beginning); clo = lockObj[tn.setNumber]; } else if(lock instanceof Local) clo = (Local) lock; else throw new RuntimeException("Unknown type of lock (" + lock + "): expected Ref or Local"); if(lockNum + 1 >= tn.lockset.size()) moreLocks = false; else moreLocks = true; if( lockNum > 0 ) { LockRegion nlr = new LockRegion(); nlr.beginning = clr.beginning; for(Iterator earlyEndsIt = clr.earlyEnds.iterator(); earlyEndsIt.hasNext(); ) { Pair earlyEnd = (Pair) earlyEndsIt.next(); // <early end, early exitmonitor> Stmt earlyExitmonitor = (Stmt) earlyEnd.getO2(); nlr.earlyEnds.add(new Pair(earlyExitmonitor, null)); // <early exitmonitor, null> } if(clr.end != null) { Stmt endExitmonitor = (Stmt) clr.end.getO2(); nlr.after = endExitmonitor; } clr = nlr; } else clr = tn; } else // global lock { if(!addedLocalLockObj[tn.setNumber]) b.getLocals().add(lockObj[tn.setNumber]); addedLocalLockObj[tn.setNumber] = true; Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], Jimple.v().newStaticFieldRef(globalLockObj[tn.setNumber].makeRef())); if(tn.wholeMethod) units.insertBeforeNoRedirect(assignLocalLockStmt, firstUnit); else units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); clo = lockObj[tn.setNumber]; clr = tn; moreLocks = false; } // Add synchronization code // For transactions from synchronized methods, use synchronizeSingleEntrySingleExitBlock() // to add all necessary code (including ugly exception handling) // For transactions from synchronized blocks, simply replace the // monitorenter/monitorexit statements with new ones if(true) { // Remove old prep stmt if( clr.prepStmt != null ) { units.remove(clr.prepStmt); } // Reuse old entermonitor or insert new one, and insert prep Stmt newEntermonitor = Jimple.v().newEnterMonitorStmt(clo); if( clr.entermonitor != null ) { units.insertBefore(newEntermonitor, clr.entermonitor); // redirectTraps(b, clr.entermonitor, newEntermonitor); // EXPERIMENTAL units.remove(clr.entermonitor); clr.entermonitor = newEntermonitor; // units.insertBefore(newEntermonitor, newPrep); // clr.prepStmt = newPrep; } else { units.insertBeforeNoRedirect(newEntermonitor, clr.beginning); clr.entermonitor = newEntermonitor; // units.insertBefore(newEntermonitor, newPrep); // clr.prepStmt = newPrep; } // For each early end, reuse or insert exitmonitor stmt List newEarlyEnds = new ArrayList(); for(Iterator earlyEndsIt = clr.earlyEnds.iterator(); earlyEndsIt.hasNext(); ) { Pair end = (Pair) earlyEndsIt.next(); Stmt earlyEnd = (Stmt) end.getO1(); Stmt exitmonitor = (Stmt) end.getO2(); Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo); if( exitmonitor != null ) { units.insertBefore(newExitmonitor, exitmonitor); // redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL units.remove(exitmonitor); newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor)); } else { units.insertBefore(newExitmonitor, earlyEnd); newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor)); } } clr.earlyEnds = newEarlyEnds; // If fallthrough end, reuse or insert goto and exit if( clr.after != null ) { Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo); if( clr.end != null ) { Stmt exitmonitor = (Stmt) clr.end.getO2(); units.insertBefore(newExitmonitor, exitmonitor); // redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL units.remove(exitmonitor); clr.end = new Pair(clr.end.getO1(), newExitmonitor); } else { units.insertBefore(newExitmonitor, clr.after); // steal jumps to end, send them to monitorexit Stmt newGotoStmt = Jimple.v().newGotoStmt(clr.after); units.insertBeforeNoRedirect(newGotoStmt, clr.after); clr.end = new Pair(newGotoStmt, newExitmonitor); } } // If exceptional end, reuse it, else insert it and traps Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo); if( clr.exceptionalEnd != null ) { Stmt exitmonitor = (Stmt) clr.exceptionalEnd.getO2(); units.insertBefore(newExitmonitor, exitmonitor); // redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL units.remove(exitmonitor); clr.exceptionalEnd = new Pair(clr.end.getO1(), newExitmonitor); } else { // insert after the last end Stmt lastEnd = null; if( clr.end != null ) { lastEnd = (Stmt) clr.end.getO1(); } else { for(Iterator earlyEndsIt = clr.earlyEnds.iterator(); earlyEndsIt.hasNext(); ) { Pair earlyEnd = (Pair) earlyEndsIt.next(); Stmt end = (Stmt) earlyEnd.getO1(); if( lastEnd == null || units.follows(end, lastEnd) ) lastEnd = end; } } if(lastEnd == null) throw new RuntimeException("Lock Region has no ends! Where should we put the exception handling???"); // Add throwable Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable")); b.getLocals().add(throwableLocal); // Add stmts Stmt newCatch = Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef()); units.insertAfter(newCatch, lastEnd); units.insertAfter(newExitmonitor, newCatch); Stmt newThrow = Jimple.v().newThrowStmt(throwableLocal); units.insertAfter(newThrow, newExitmonitor); // Add traps SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable"); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, clr.beginning, lastEnd, newCatch)); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, newExitmonitor, newThrow, newCatch)); clr.exceptionalEnd = new Pair(newThrow, newExitmonitor); } } /* else if(tn.wholeMethod) { thisMethod.setModifiers( thisMethod.getModifiers() & ~ (Modifier.SYNCHRONIZED) ); // remove synchronized modifier for this method synchronizeSingleEntrySingleExitBlock(b, (Stmt) firstUnit, (Stmt) lastUnit, (Local) clo); } else if(lockNum > 0) { // don't have all the info to do this right yet // synchronizeSingleEntrySingleExitBlock(b, (Stmt) tnbodystart, (Stmt) tnbodyend, (Local) clo); } else { if(tn.entermonitor == null) G.v().out.println("ERROR: Transaction has no beginning statement: " + tn.method.toString()); // Deal with entermonitor Stmt newBegin = Jimple.v().newEnterMonitorStmt(clo); units.insertBefore(newBegin, tn.entermonitor); redirectTraps(b, tn.entermonitor, newBegin); units.remove(tn.entermonitor); // Deal with exitmonitors // early Iterator endsIt = tn.earlyEnds.iterator(); while(endsIt.hasNext()) { Pair end = (Pair) endsIt.next(); Stmt sEnd = (Stmt) end.getO2(); Stmt newEnd = Jimple.v().newExitMonitorStmt(clo); units.insertBefore(newEnd, sEnd); redirectTraps(b, sEnd, newEnd); units.remove(sEnd); } // exceptional Stmt sEnd = (Stmt) tn.exceptionalEnd.getO2(); Stmt newEnd = Jimple.v().newExitMonitorStmt(clo); units.insertBefore(newEnd, sEnd); redirectTraps(b, sEnd, newEnd); units.remove(sEnd); // fallthrough sEnd = (Stmt) tn.end.getO2(); newEnd = Jimple.v().newExitMonitorStmt(clo); units.insertBefore(newEnd, sEnd); redirectTraps(b, sEnd, newEnd); units.remove(sEnd); } */ // Replace calls to notify() with calls to notifyAll() // Replace base object with appropriate lockobj lockNum++; } // deal with waits and notifys { Iterator notifysIt = tn.notifys.iterator(); while(notifysIt.hasNext()) { Stmt sNotify = (Stmt) notifysIt.next(); Stmt newNotify = Jimple.v().newInvokeStmt( Jimple.v().newVirtualInvokeExpr( (Local) clo, sNotify.getInvokeExpr().getMethodRef().declaringClass().getMethod("void notifyAll()").makeRef(), Collections.EMPTY_LIST)); units.insertBefore(newNotify, sNotify); redirectTraps(b, sNotify, newNotify); units.remove(sNotify); } // Replace base object of calls to wait with appropriate lockobj Iterator waitsIt = tn.waits.iterator(); while(waitsIt.hasNext()) { Stmt sWait = (Stmt) waitsIt.next(); ((InstanceInvokeExpr) sWait.getInvokeExpr()).setBase(clo); // WHAT IF THIS IS THE WRONG LOCK IN A PAIR OF NESTED LOCKS??? // Stmt newWait = // Jimple.v().newInvokeStmt( // Jimple.v().newVirtualInvokeExpr( // (Local) clo, // sWait.getInvokeExpr().getMethodRef().declaringClass().getMethod("void wait()").makeRef(), // Collections.EMPTY_LIST)); // units.insertBefore(newWait, sWait); // redirectTraps(b, sWait, newWait); // units.remove(sWait); } } } } public void synchronizeSingleEntrySingleExitBlock(Body b, Stmt start, Stmt end, Local lockObj) { PatchingChain units = b.getUnits(); // <existing local defs> // add a throwable to local vars Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable")); b.getLocals().add(throwableLocal); // <existing identity refs> // add entermonitor statement and label0 // Unit label0Unit = start; Unit labelEnterMonitorStmt = Jimple.v().newEnterMonitorStmt(lockObj); units.insertBeforeNoRedirect(labelEnterMonitorStmt, start); // steal jumps to start, send them to monitorenter // <existing code body> check for return statements List returnUnits = new ArrayList(); if(start != end) { Iterator bodyIt = units.iterator(start, end); while(bodyIt.hasNext()) { Stmt bodyStmt = (Stmt) bodyIt.next(); if(bodyIt.hasNext()) // ignore the end unit { if( bodyStmt instanceof ReturnStmt || bodyStmt instanceof ReturnVoidStmt) { returnUnits.add(bodyStmt); } } } } // add normal flow and labels Unit labelExitMonitorStmt = (Unit) Jimple.v().newExitMonitorStmt(lockObj); units.insertBefore(labelExitMonitorStmt, end); // steal jumps to end, send them to monitorexit // end = (Stmt) units.getSuccOf(end); Unit label1Unit = (Unit) Jimple.v().newGotoStmt(end); units.insertBeforeNoRedirect(label1Unit, end); // end = (Stmt) units.getSuccOf(end); // add exceptional flow and labels Unit label2Unit = (Unit) Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef()); units.insertBeforeNoRedirect(label2Unit, end); // end = (Stmt) units.getSuccOf(end); Unit label3Unit = (Unit) Jimple.v().newExitMonitorStmt(lockObj); units.insertBeforeNoRedirect(label3Unit, end); // end = (Stmt) units.getSuccOf(end); Unit label4Unit = (Unit) Jimple.v().newThrowStmt(throwableLocal); units.insertBeforeNoRedirect(label4Unit, end); // end = (Stmt) units.getSuccOf(end); // <existing end statement> Iterator returnIt = returnUnits.iterator(); while(returnIt.hasNext()) { Stmt bodyStmt = (Stmt) returnIt.next(); units.insertBefore(Jimple.v().newExitMonitorStmt(lockObj), bodyStmt); // TODO: WHAT IF IT'S IN A NESTED TRANSACTION??? // Stmt placeholder = Jimple.v().newNopStmt(); // units.insertAfter(Jimple.v().newNopStmt(), label4Unit); // bodyStmt.redirectJumpsToThisTo(placeholder); // units.insertBefore(Jimple.v().newGotoStmt(placeholder), bodyStmt); // units.remove(bodyStmt); // units.swapWith(placeholder, bodyStmt); // units.swapWith } // add exception routing table Unit label0Unit = (Unit) units.getSuccOf(labelEnterMonitorStmt); SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable"); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label0Unit, label1Unit, label2Unit)); b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label3Unit, label4Unit, label2Unit)); } public void redirectTraps(Body b, Unit oldUnit, Unit newUnit) { Chain traps = b.getTraps(); Iterator trapsIt = traps.iterator(); while(trapsIt.hasNext()) { AbstractTrap trap = (AbstractTrap) trapsIt.next(); if(trap.getHandlerUnit() == oldUnit) trap.setHandlerUnit(newUnit); if(trap.getBeginUnit() == oldUnit) trap.setBeginUnit(newUnit); if(trap.getEndUnit() == oldUnit) trap.setEndUnit(newUnit); } } }
Transactional Transformer: Improvements to lock insertion.
src/soot/jimple/toolkits/thread/transaction/TransactionBodyTransformer.java
Transactional Transformer: Improvements to lock insertion.
<ide><path>rc/soot/jimple/toolkits/thread/transaction/TransactionBodyTransformer.java <ide> } <ide> else if( tn.group.useLocksets ) <ide> { <del> Value lock = (Value) tn.lockset.get(lockNum); <add> Value lock = getLockFor((EquivalentValue) tn.lockset.get(lockNum)); // adds local vars and global objects if needed <add> if( lock instanceof FieldRef ) <add> { <add> // add a local variable for this lock <add> Local lockLocal = Jimple.v().newLocal("locksetObj" + tempNum, RefType.v("java.lang.Object")); <add> tempNum++; <add> b.getLocals().add(lockLocal); <ide> <del> if( lock instanceof EquivalentValue ) // unwrap equivalent value <del> lock = ((EquivalentValue)lock).getValue(); <del> <del> if(!addedLocalLockObj[tn.setNumber]) <del> { <del> b.getLocals().add(lockObj[tn.setNumber]); <del> addedLocalLockObj[tn.setNumber] = true; <del> } <del> if(lock instanceof InstanceFieldRef) <del> { <del> Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], lock); <add> // make it refer to the right lock object <add> Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockLocal, lock); <ide> if(tn.entermonitor != null) <ide> units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); <ide> else <ide> units.insertBeforeNoRedirect(assignLocalLockStmt, (Stmt) tn.beginning); <del> clo = lockObj[tn.setNumber]; <del> } <del> else if(lock instanceof StaticFieldRef) <del> { <del> StaticFieldRef sfrLock = (StaticFieldRef) lock; <del> SootField sfrField = sfrLock.getField(); <del> SootClass sfrClass = sfrField.getDeclaringClass(); <del> <del> // add a static lock object to that class <del> // use it here <del> <del> Stmt assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], lock); <del> if(tn.entermonitor != null) <del> units.insertBefore(assignLocalLockStmt, (Stmt) tn.entermonitor); <del> else <del> units.insertBeforeNoRedirect(assignLocalLockStmt, (Stmt) tn.beginning); <del> clo = lockObj[tn.setNumber]; <del> } <del> else if(lock instanceof Local) <add> <add> // use it as the lock <add> clo = lockLocal; <add> } <add> else if( lock instanceof Local ) <ide> clo = (Local) lock; <ide> else <del> throw new RuntimeException("Unknown type of lock (" + lock + "): expected Ref or Local"); <add> throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local"); <ide> <ide> if(lockNum + 1 >= tn.lockset.size()) <ide> moreLocks = false; <ide> } <ide> } <ide> <add> static int lockNumber = 0; <add> Map lockEqValToLock = new HashMap(); <add> public Value getLockFor(EquivalentValue lockEqVal) <add> { <add> Value lock = lockEqVal.getValue(); <add> <add> if( lock instanceof InstanceFieldRef ) <add> return lock; <add> <add> if( lock instanceof Local ) <add> return lock; <add> <add> if( lock instanceof StaticFieldRef ) <add> { <add> if( lockEqValToLock.containsKey(lockEqVal) ) <add> return (Value) lockEqValToLock.get(lockEqVal); <add> <add> StaticFieldRef sfrLock = (StaticFieldRef) lock; <add> SootClass lockClass = sfrLock.getField().getDeclaringClass(); <add> SootMethod clinitMethod = null; <add> JimpleBody clinitBody = null; <add> Stmt firstStmt = null; <add> boolean addingNewClinit = !lockClass.declaresMethod("void <clinit>()"); <add> if(addingNewClinit) <add> { <add> clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); <add> clinitBody = Jimple.v().newBody(clinitMethod); <add> clinitMethod.setActiveBody(clinitBody); <add> lockClass.addMethod(clinitMethod); <add> } <add> else <add> { <add> clinitMethod = lockClass.getMethod("void <clinit>()"); <add> clinitBody = (JimpleBody) clinitMethod.getActiveBody(); <add> firstStmt = clinitBody.getFirstNonIdentityStmt(); <add> } <add> PatchingChain clinitUnits = clinitBody.getUnits(); <add> <add> Local lockLocal = Jimple.v().newLocal("objectLockLocal" + lockNumber, RefType.v("java.lang.Object")); <add> // lockNumber is increased below <add> clinitBody.getLocals().add(lockLocal); // TODO: add name conflict avoidance code <add> <add> // assign new object to lock obj <add> Stmt newStmt = Jimple.v().newAssignStmt(lockLocal, Jimple.v().newNewExpr(RefType.v("java.lang.Object"))); <add> if(addingNewClinit) <add> clinitUnits.add(newStmt); <add> else <add> clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt); <add> <add> // initialize new object <add> SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object"); <add> RefType type = RefType.v(objectClass); <add> SootMethod initMethod = objectClass.getMethod("void <init>()"); <add> Stmt initStmt = Jimple.v().newInvokeStmt( <add> Jimple.v().newSpecialInvokeExpr(lockLocal, <add> initMethod.makeRef(), Collections.EMPTY_LIST)); <add> if(addingNewClinit) <add> clinitUnits.add(initStmt); <add> else <add> clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt); <add> <add> // copy new object to global static lock object (for use by other fns) <add> SootField actualLockObject = new SootField("objectLockGlobal" + lockNumber, RefType.v("java.lang.Object"), Modifier.STATIC | Modifier.PUBLIC); <add> lockNumber++; <add> lockClass.addField(actualLockObject); <add> <add> StaticFieldRef actualLockSfr = Jimple.v().newStaticFieldRef(actualLockObject.makeRef()); <add> Stmt assignStmt = Jimple.v().newAssignStmt(actualLockSfr, lockLocal); <add> if(addingNewClinit) <add> clinitUnits.add(assignStmt); <add> else <add> clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt); <add> <add> if(addingNewClinit) <add> clinitUnits.add(Jimple.v().newReturnVoidStmt()); <add> <add> lockEqValToLock.put(lockEqVal, actualLockSfr); <add> return actualLockSfr; <add> } <add> <add> throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local"); <add> } <add> <add>/* <ide> public void synchronizeSingleEntrySingleExitBlock(Body b, Stmt start, Stmt end, Local lockObj) <ide> { <ide> PatchingChain units = b.getUnits(); <ide> b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label3Unit, label4Unit, label2Unit)); <ide> <ide> } <del> <add>*/ <add> <ide> public void redirectTraps(Body b, Unit oldUnit, Unit newUnit) <ide> { <ide> Chain traps = b.getTraps(); <ide> trap.setEndUnit(newUnit); <ide> } <ide> } <add> <ide> }
Java
apache-2.0
6b57699c6ef92a085b41bdda75b06aea6e5c3c4e
0
johnnywale/compass,johnnywale/compass,johnnywale/compass,kimchy/compass,kimchy/compass
/* * Copyright 2004-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.compass.gps.device.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import org.compass.core.Compass; import org.compass.core.CompassDetachedHits; import org.compass.core.CompassTemplate; import org.compass.core.Resource; import org.compass.core.config.CompassConfiguration; import org.compass.core.config.CompassEnvironment; import org.compass.gps.device.jdbc.mapping.DataColumnToPropertyMapping; import org.compass.gps.device.jdbc.mapping.TableToResourceMapping; import org.compass.gps.device.jdbc.mapping.VersionColumnMapping; import org.compass.gps.device.jdbc.snapshot.FSJdbcSnapshotPersister; import org.compass.gps.impl.SingleCompassGps; /** * * @author kimchy * */ public class TableJdbcGpsDeviceTests extends AbstractJdbcGpsDeviceTests { protected Compass compass; protected CompassTemplate compassTemplate; private ResultSetJdbcGpsDevice gpsDevice; private SingleCompassGps gps; protected void tearDown() throws Exception { if (gps != null) gps.stop(); if (compass != null) { compass.close(); } super.tearDown(); } protected void setUpDefinedExactMapping() throws Exception { // set up the database mappings, since they are used both to generate // the resource mappings and configure the jdbc gps device TableToResourceMapping parentMapping = new TableToResourceMapping("PARENT", "parent"); parentMapping.setIndexUnMappedColumns(false); parentMapping.addDataMapping(new DataColumnToPropertyMapping("first_name", "first_name")); TableToResourceMapping childMapping = new TableToResourceMapping("CHILD", "child"); childMapping.addDataMapping(new DataColumnToPropertyMapping("first_name", "first_name")); childMapping.setIndexUnMappedColumns(false); CompassConfiguration conf = new CompassConfiguration().setSetting(CompassEnvironment.CONNECTION, "target/test-index"); conf.addMappingResolver(new ResultSetResourceMappingResolver(parentMapping, dataSource)); conf.addMappingResolver(new ResultSetResourceMappingResolver(childMapping, dataSource)); conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true); compass = conf.buildCompass(); compass.getSearchEngineIndexManager().deleteIndex(); compass.getSearchEngineIndexManager().verifyIndex(); compassTemplate = new CompassTemplate(compass); gpsDevice = new ResultSetJdbcGpsDevice(); gpsDevice.setDataSource(dataSource); gpsDevice.setName("tableJdbcDevice"); gpsDevice.addMapping(parentMapping); gpsDevice.addMapping(childMapping); gps = new SingleCompassGps(compass); gps.addGpsDevice(gpsDevice); gps.start(); } public void testDefinedExactMapping() throws Exception { setUpDefinedExactMapping(); gps.index(); Resource r = compassTemplate.getResource("parent", "1"); assertNotNull(r); assertNotNull(r.getProperty("ID")); assertNotNull(r.getProperty("first_name")); assertNull(r.getProperty("FIRST_NAME")); assertNull(r.getProperty("LAST_NAME")); CompassDetachedHits hits = compassTemplate.findWithDetach("parent"); assertEquals(4, hits.getLength()); hits = compassTemplate.findWithDetach("child"); assertEquals(6, hits.getLength()); } protected void setUpAutomaticMapping() throws Exception { // set up the database mappings, since they are used both to generate // the resource mappings and configure the jdbc gps device TableToResourceMapping parentMapping = new TableToResourceMapping("PARENT", "parent"); parentMapping.addVersionMapping(new VersionColumnMapping("version")); parentMapping.setIndexUnMappedColumns(true); TableToResourceMapping childMapping = new TableToResourceMapping("CHILD", "child"); childMapping.addVersionMapping(new VersionColumnMapping("version")); childMapping.setIndexUnMappedColumns(true); CompassConfiguration conf = new CompassConfiguration().setSetting(CompassEnvironment.CONNECTION, "target/testindex"); conf.addMappingResolver(new ResultSetResourceMappingResolver(parentMapping, dataSource)); conf.addMappingResolver(new ResultSetResourceMappingResolver(childMapping, dataSource)); conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true); compass = conf.buildCompass(); compass.getSearchEngineIndexManager().deleteIndex(); compass.getSearchEngineIndexManager().verifyIndex(); compassTemplate = new CompassTemplate(compass); gpsDevice = new ResultSetJdbcGpsDevice(); gpsDevice.setSnapshotPersister(new FSJdbcSnapshotPersister("target/testindex/snapshot")); gpsDevice.setDataSource(dataSource); gpsDevice.setName("tableJdbcDevice"); gpsDevice.addMapping(parentMapping); gpsDevice.addMapping(childMapping); gps = new SingleCompassGps(compass); gps.addGpsDevice(gpsDevice); gps.start(); } public void testAutomaticMappingAndFSPersister() throws Exception { setUpAutomaticMapping(); gps.index(); Resource r = compassTemplate.getResource("parent", "1"); assertNotNull(r); assertNotNull(r.getProperty("ID")); assertNotNull(r.getProperty("FIRST_NAME")); assertNotNull(r.getProperty("LAST_NAME")); CompassDetachedHits hits = compassTemplate.findWithDetach("parent"); assertEquals(4, hits.getLength()); hits = compassTemplate.findWithDetach("child"); assertEquals(6, hits.getLength()); } public void testAutomaticMappingWithMirroringAndFSPersister() throws Exception { setUpAutomaticMapping(); gpsDevice.setMirrorDataChanges(true); gps.index(); Resource r = compassTemplate.getResource("parent", "1"); assertNotNull(r); assertNotNull(r.getProperty("ID")); assertNotNull(r.getProperty("FIRST_NAME")); assertNotNull(r.getProperty("LAST_NAME")); CompassDetachedHits hits = compassTemplate.findWithDetach("parent"); assertEquals(4, hits.getLength()); hits = compassTemplate.findWithDetach("child"); assertEquals(6, hits.getLength()); // test that create works Connection con = JdbcUtils.getConnection(dataSource); PreparedStatement ps = con .prepareStatement("INSERT INTO parent VALUES (999, 'parent first 999', 'last 999', 1);"); ps.execute(); ps.close(); con.commit(); con.close(); r = compassTemplate.getResource("parent", "999"); assertNull(r); gpsDevice.performMirroring(); compassTemplate.loadResource("parent", "999"); gps.stop(); gps.start(); // test that update works con = JdbcUtils.getConnection(dataSource); ps = con.prepareStatement("update parent set first_name = 'new first name', version = 2 where id = 1"); ps.execute(); ps.close(); con.commit(); con.close(); gpsDevice.performMirroring(); r = compassTemplate.loadResource("parent", "1"); assertEquals("new first name", r.getValue("FIRST_NAME")); // test that delete works con = JdbcUtils.getConnection(dataSource); ps = con.prepareStatement("delete from parent where id = 999"); ps.execute(); ps.close(); con.commit(); con.close(); gpsDevice.performMirroring(); r = compassTemplate.getResource("parent", "999"); assertNull(r); } }
src/main/test/org/compass/gps/device/jdbc/TableJdbcGpsDeviceTests.java
/* * Copyright 2004-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.compass.gps.device.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import org.compass.core.Compass; import org.compass.core.CompassDetachedHits; import org.compass.core.CompassTemplate; import org.compass.core.Resource; import org.compass.core.config.CompassConfiguration; import org.compass.core.config.CompassEnvironment; import org.compass.core.util.FileHandlerMonitor; import org.compass.gps.device.jdbc.mapping.DataColumnToPropertyMapping; import org.compass.gps.device.jdbc.mapping.TableToResourceMapping; import org.compass.gps.device.jdbc.mapping.VersionColumnMapping; import org.compass.gps.device.jdbc.snapshot.FSJdbcSnapshotPersister; import org.compass.gps.impl.SingleCompassGps; /** * * @author kimchy * */ public class TableJdbcGpsDeviceTests extends AbstractJdbcGpsDeviceTests { protected Compass compass; private FileHandlerMonitor fileHandlerMonitor; protected CompassTemplate compassTemplate; private ResultSetJdbcGpsDevice gpsDevice; private SingleCompassGps gps; protected void tearDown() throws Exception { if (gps != null) gps.stop(); if (compass != null) { compass.close(); if (fileHandlerMonitor != null) { fileHandlerMonitor.verifyNoHandlers(); } } super.tearDown(); } protected void setUpDefinedExactMapping() throws Exception { // set up the database mappings, since they are used both to generate // the resource mappings and configure the jdbc gps device TableToResourceMapping parentMapping = new TableToResourceMapping("PARENT", "parent"); parentMapping.setIndexUnMappedColumns(false); parentMapping.addDataMapping(new DataColumnToPropertyMapping("first_name", "first_name")); TableToResourceMapping childMapping = new TableToResourceMapping("CHILD", "child"); childMapping.addDataMapping(new DataColumnToPropertyMapping("first_name", "first_name")); childMapping.setIndexUnMappedColumns(false); CompassConfiguration conf = new CompassConfiguration().setSetting(CompassEnvironment.CONNECTION, "target/test-index"); conf.addMappingResolver(new ResultSetResourceMappingResolver(parentMapping, dataSource)); conf.addMappingResolver(new ResultSetResourceMappingResolver(childMapping, dataSource)); conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true); compass = conf.buildCompass(); fileHandlerMonitor = FileHandlerMonitor.getFileHandlerMonitor(compass); fileHandlerMonitor.verifyNoHandlers(); compass.getSearchEngineIndexManager().deleteIndex(); compass.getSearchEngineIndexManager().verifyIndex(); compassTemplate = new CompassTemplate(compass); gpsDevice = new ResultSetJdbcGpsDevice(); gpsDevice.setDataSource(dataSource); gpsDevice.setName("tableJdbcDevice"); gpsDevice.addMapping(parentMapping); gpsDevice.addMapping(childMapping); gps = new SingleCompassGps(compass); gps.addGpsDevice(gpsDevice); gps.start(); } public void testDefinedExactMapping() throws Exception { setUpDefinedExactMapping(); gps.index(); Resource r = compassTemplate.getResource("parent", "1"); assertNotNull(r); assertNotNull(r.getProperty("ID")); assertNotNull(r.getProperty("first_name")); assertNull(r.getProperty("FIRST_NAME")); assertNull(r.getProperty("LAST_NAME")); CompassDetachedHits hits = compassTemplate.findWithDetach("parent"); assertEquals(4, hits.getLength()); hits = compassTemplate.findWithDetach("child"); assertEquals(6, hits.getLength()); } protected void setUpAutomaticMapping() throws Exception { // set up the database mappings, since they are used both to generate // the resource mappings and configure the jdbc gps device TableToResourceMapping parentMapping = new TableToResourceMapping("PARENT", "parent"); parentMapping.addVersionMapping(new VersionColumnMapping("version")); parentMapping.setIndexUnMappedColumns(true); TableToResourceMapping childMapping = new TableToResourceMapping("CHILD", "child"); childMapping.addVersionMapping(new VersionColumnMapping("version")); childMapping.setIndexUnMappedColumns(true); CompassConfiguration conf = new CompassConfiguration().setSetting(CompassEnvironment.CONNECTION, "target/testindex"); conf.addMappingResolver(new ResultSetResourceMappingResolver(parentMapping, dataSource)); conf.addMappingResolver(new ResultSetResourceMappingResolver(childMapping, dataSource)); conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true); compass = conf.buildCompass(); fileHandlerMonitor = FileHandlerMonitor.getFileHandlerMonitor(compass); fileHandlerMonitor.verifyNoHandlers(); compass.getSearchEngineIndexManager().deleteIndex(); compass.getSearchEngineIndexManager().verifyIndex(); compassTemplate = new CompassTemplate(compass); gpsDevice = new ResultSetJdbcGpsDevice(); gpsDevice.setSnapshotPersister(new FSJdbcSnapshotPersister("target/testindex/snapshot")); gpsDevice.setDataSource(dataSource); gpsDevice.setName("tableJdbcDevice"); gpsDevice.addMapping(parentMapping); gpsDevice.addMapping(childMapping); gps = new SingleCompassGps(compass); gps.addGpsDevice(gpsDevice); gps.start(); } public void testAutomaticMappingAndFSPersister() throws Exception { setUpAutomaticMapping(); gps.index(); Resource r = compassTemplate.getResource("parent", "1"); assertNotNull(r); assertNotNull(r.getProperty("ID")); assertNotNull(r.getProperty("FIRST_NAME")); assertNotNull(r.getProperty("LAST_NAME")); CompassDetachedHits hits = compassTemplate.findWithDetach("parent"); assertEquals(4, hits.getLength()); hits = compassTemplate.findWithDetach("child"); assertEquals(6, hits.getLength()); } public void testAutomaticMappingWithMirroringAndFSPersister() throws Exception { setUpAutomaticMapping(); // don't check file handles, since there will be a snapshot for it fileHandlerMonitor = null; gpsDevice.setMirrorDataChanges(true); gps.index(); Resource r = compassTemplate.getResource("parent", "1"); assertNotNull(r); assertNotNull(r.getProperty("ID")); assertNotNull(r.getProperty("FIRST_NAME")); assertNotNull(r.getProperty("LAST_NAME")); CompassDetachedHits hits = compassTemplate.findWithDetach("parent"); assertEquals(4, hits.getLength()); hits = compassTemplate.findWithDetach("child"); assertEquals(6, hits.getLength()); // test that create works Connection con = JdbcUtils.getConnection(dataSource); PreparedStatement ps = con .prepareStatement("INSERT INTO parent VALUES (999, 'parent first 999', 'last 999', 1);"); ps.execute(); ps.close(); con.commit(); con.close(); r = compassTemplate.getResource("parent", "999"); assertNull(r); gpsDevice.performMirroring(); compassTemplate.loadResource("parent", "999"); gps.stop(); gps.start(); // test that update works con = JdbcUtils.getConnection(dataSource); ps = con.prepareStatement("update parent set first_name = 'new first name', version = 2 where id = 1"); ps.execute(); ps.close(); con.commit(); con.close(); gpsDevice.performMirroring(); r = compassTemplate.loadResource("parent", "1"); assertEquals("new first name", r.getValue("FIRST_NAME")); // test that delete works con = JdbcUtils.getConnection(dataSource); ps = con.prepareStatement("delete from parent where id = 999"); ps.execute(); ps.close(); con.commit(); con.close(); gpsDevice.performMirroring(); r = compassTemplate.getResource("parent", "999"); assertNull(r); } }
fix test
src/main/test/org/compass/gps/device/jdbc/TableJdbcGpsDeviceTests.java
fix test
<ide><path>rc/main/test/org/compass/gps/device/jdbc/TableJdbcGpsDeviceTests.java <ide> import org.compass.core.Resource; <ide> import org.compass.core.config.CompassConfiguration; <ide> import org.compass.core.config.CompassEnvironment; <del>import org.compass.core.util.FileHandlerMonitor; <ide> import org.compass.gps.device.jdbc.mapping.DataColumnToPropertyMapping; <ide> import org.compass.gps.device.jdbc.mapping.TableToResourceMapping; <ide> import org.compass.gps.device.jdbc.mapping.VersionColumnMapping; <ide> <ide> protected Compass compass; <ide> <del> private FileHandlerMonitor fileHandlerMonitor; <del> <ide> protected CompassTemplate compassTemplate; <ide> <ide> private ResultSetJdbcGpsDevice gpsDevice; <ide> if (gps != null) gps.stop(); <ide> if (compass != null) { <ide> compass.close(); <del> if (fileHandlerMonitor != null) { <del> fileHandlerMonitor.verifyNoHandlers(); <del> } <ide> } <ide> super.tearDown(); <ide> } <ide> conf.addMappingResolver(new ResultSetResourceMappingResolver(childMapping, dataSource)); <ide> conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true); <ide> compass = conf.buildCompass(); <del> <del> fileHandlerMonitor = FileHandlerMonitor.getFileHandlerMonitor(compass); <del> fileHandlerMonitor.verifyNoHandlers(); <ide> <ide> compass.getSearchEngineIndexManager().deleteIndex(); <ide> compass.getSearchEngineIndexManager().verifyIndex(); <ide> conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true); <ide> compass = conf.buildCompass(); <ide> <del> fileHandlerMonitor = FileHandlerMonitor.getFileHandlerMonitor(compass); <del> fileHandlerMonitor.verifyNoHandlers(); <del> <ide> compass.getSearchEngineIndexManager().deleteIndex(); <ide> compass.getSearchEngineIndexManager().verifyIndex(); <ide> <ide> <ide> public void testAutomaticMappingWithMirroringAndFSPersister() throws Exception { <ide> setUpAutomaticMapping(); <del> // don't check file handles, since there will be a snapshot for it <del> fileHandlerMonitor = null; <ide> gpsDevice.setMirrorDataChanges(true); <ide> gps.index(); <ide> Resource r = compassTemplate.getResource("parent", "1");
Java
apache-2.0
c80041463e55c786b2116524ade355d9830d84ff
0
sonatype/sisu-guice,sonatype/sisu-guice
/** * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.servlet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Injector; import com.google.inject.Provider; import java.io.IOException; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * Central routing/dispatch class handles lifecycle of managed filters, and delegates to the servlet * pipeline. * * @author [email protected] (Dhanji R. Prasanna) */ public abstract class AbstractFilterPipeline implements FilterPipeline { protected abstract boolean hasFiltersMapped(); protected abstract FilterDefinition[] filterDefinitions(); protected final AbstractServletPipeline servletPipeline; protected final Provider<ServletContext> servletContext; //Unfortunately, we need the injector itself in order to create filters + servlets private final Injector injector; //Guards a DCL, so needs to be volatile private volatile boolean initialized = false; protected AbstractFilterPipeline(Injector injector, AbstractServletPipeline servletPipeline, Provider<ServletContext> servletContext) { this.injector = injector; this.servletPipeline = servletPipeline; this.servletContext = servletContext; } public synchronized void initPipeline(ServletContext servletContext) throws ServletException { //double-checked lock, prevents duplicate initialization if (initialized) return; // Used to prevent duplicate initialization. Set<Filter> initializedSoFar = Sets.newSetFromMap(Maps.<Filter, Boolean>newIdentityHashMap()); for (FilterDefinition filterDefinition : filterDefinitions()) { filterDefinition.init(servletContext, injector, initializedSoFar); } //next, initialize servlets... servletPipeline.init(servletContext, injector); //everything was ok... initialized = true; } public void dispatch(ServletRequest request, ServletResponse response, FilterChain proceedingFilterChain) throws IOException, ServletException { //lazy init of filter pipeline (OK by the servlet specification). This is needed //in order for us not to force users to create a GuiceServletContextListener subclass. if (!initialized) { initPipeline(servletContext.get()); } //obtain the servlet pipeline to dispatch against new FilterChainInvocation(filterDefinitions(), servletPipeline, proceedingFilterChain) .doFilter(withDispatcher(request, servletPipeline), response); } /** * Used to create an proxy that dispatches either to the guice-servlet pipeline or the regular * pipeline based on uri-path match. This proxy also provides minimal forwarding support. * * We cannot forward from a web.xml Servlet/JSP to a guice-servlet (because the filter pipeline * is not called again). However, we can wrap requests with our own dispatcher to forward the * *other* way. web.xml Servlets/JSPs can forward to themselves as per normal. * * This is not a problem cuz we intend for people to migrate from web.xml to guice-servlet, * incrementally, but not the other way around (which, we should actively discourage). */ @SuppressWarnings({ "JavaDoc", "deprecation" }) private static ServletRequest withDispatcher(ServletRequest servletRequest, final AbstractServletPipeline servletPipeline) { // don't wrap the request if there are no servlets mapped. This prevents us from inserting our // wrapper unless it's actually going to be used. This is necessary for compatibility for apps // that downcast their HttpServletRequests to a concrete implementation. if (!servletPipeline.hasServletsMapped()) { return servletRequest; } HttpServletRequest request = (HttpServletRequest) servletRequest; //noinspection OverlyComplexAnonymousInnerClass return new HttpServletRequestWrapper(request) { @Override public RequestDispatcher getRequestDispatcher(String path) { final RequestDispatcher dispatcher = servletPipeline.getRequestDispatcher(path); return (null != dispatcher) ? dispatcher : super.getRequestDispatcher(path); } }; } public void destroyPipeline() { //destroy servlets first servletPipeline.destroy(); //go down chain and destroy all our filters Set<Filter> destroyedSoFar = Sets.newSetFromMap(Maps.<Filter, Boolean>newIdentityHashMap()); for (FilterDefinition filterDefinition : filterDefinitions()) { filterDefinition.destroy(destroyedSoFar); } } }
extensions/servlet/src/com/google/inject/servlet/AbstractFilterPipeline.java
/** * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.servlet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Injector; import com.google.inject.Provider; import java.io.IOException; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * Central routing/dispatch class handles lifecycle of managed filters, and delegates to the servlet * pipeline. * * @author [email protected] (Dhanji R. Prasanna) */ public abstract class AbstractFilterPipeline implements FilterPipeline{ protected abstract boolean hasFiltersMapped(); protected abstract FilterDefinition[] filterDefinitions(); private final AbstractServletPipeline servletPipeline; private final Provider<ServletContext> servletContext; //Unfortunately, we need the injector itself in order to create filters + servlets private final Injector injector; //Guards a DCL, so needs to be volatile private volatile boolean initialized = false; protected AbstractFilterPipeline(Injector injector, AbstractServletPipeline servletPipeline, Provider<ServletContext> servletContext) { this.injector = injector; this.servletPipeline = servletPipeline; this.servletContext = servletContext; } public synchronized void initPipeline(ServletContext servletContext) throws ServletException { //double-checked lock, prevents duplicate initialization if (initialized) return; // Used to prevent duplicate initialization. Set<Filter> initializedSoFar = Sets.newSetFromMap(Maps.<Filter, Boolean>newIdentityHashMap()); for (FilterDefinition filterDefinition : filterDefinitions()) { filterDefinition.init(servletContext, injector, initializedSoFar); } //next, initialize servlets... servletPipeline.init(servletContext, injector); //everything was ok... initialized = true; } public void dispatch(ServletRequest request, ServletResponse response, FilterChain proceedingFilterChain) throws IOException, ServletException { //lazy init of filter pipeline (OK by the servlet specification). This is needed //in order for us not to force users to create a GuiceServletContextListener subclass. if (!initialized) { initPipeline(servletContext.get()); } //obtain the servlet pipeline to dispatch against new FilterChainInvocation(filterDefinitions(), servletPipeline, proceedingFilterChain) .doFilter(withDispatcher(request, servletPipeline), response); } /** * Used to create an proxy that dispatches either to the guice-servlet pipeline or the regular * pipeline based on uri-path match. This proxy also provides minimal forwarding support. * * We cannot forward from a web.xml Servlet/JSP to a guice-servlet (because the filter pipeline * is not called again). However, we can wrap requests with our own dispatcher to forward the * *other* way. web.xml Servlets/JSPs can forward to themselves as per normal. * * This is not a problem cuz we intend for people to migrate from web.xml to guice-servlet, * incrementally, but not the other way around (which, we should actively discourage). */ @SuppressWarnings({ "JavaDoc", "deprecation" }) private static ServletRequest withDispatcher(ServletRequest servletRequest, final AbstractServletPipeline servletPipeline) { // don't wrap the request if there are no servlets mapped. This prevents us from inserting our // wrapper unless it's actually going to be used. This is necessary for compatibility for apps // that downcast their HttpServletRequests to a concrete implementation. if (!servletPipeline.hasServletsMapped()) { return servletRequest; } HttpServletRequest request = (HttpServletRequest) servletRequest; //noinspection OverlyComplexAnonymousInnerClass return new HttpServletRequestWrapper(request) { @Override public RequestDispatcher getRequestDispatcher(String path) { final RequestDispatcher dispatcher = servletPipeline.getRequestDispatcher(path); return (null != dispatcher) ? dispatcher : super.getRequestDispatcher(path); } }; } public void destroyPipeline() { //destroy servlets first servletPipeline.destroy(); //go down chain and destroy all our filters Set<Filter> destroyedSoFar = Sets.newSetFromMap(Maps.<Filter, Boolean>newIdentityHashMap()); for (FilterDefinition filterDefinition : filterDefinitions()) { filterDefinition.destroy(destroyedSoFar); } } }
Experiment with making guice-servlet more adaptable
extensions/servlet/src/com/google/inject/servlet/AbstractFilterPipeline.java
Experiment with making guice-servlet more adaptable
<ide><path>xtensions/servlet/src/com/google/inject/servlet/AbstractFilterPipeline.java <ide> * <ide> * @author [email protected] (Dhanji R. Prasanna) <ide> */ <del>public abstract class AbstractFilterPipeline implements FilterPipeline{ <add>public abstract class AbstractFilterPipeline implements FilterPipeline { <ide> <ide> protected abstract boolean hasFiltersMapped(); <ide> <ide> protected abstract FilterDefinition[] filterDefinitions(); <ide> <del> private final AbstractServletPipeline servletPipeline; <del> private final Provider<ServletContext> servletContext; <add> protected final AbstractServletPipeline servletPipeline; <add> protected final Provider<ServletContext> servletContext; <ide> <ide> //Unfortunately, we need the injector itself in order to create filters + servlets <ide> private final Injector injector;
Java
apache-2.0
32da3290259b504ab032b2c9ee526e4921908985
0
sktoo/timetabling-system-,UniTime/unitime,rafati/unitime,sktoo/timetabling-system-,zuzanamullerova/unitime,UniTime/unitime,nikeshmhr/unitime,maciej-zygmunt/unitime,nikeshmhr/unitime,zuzanamullerova/unitime,maciej-zygmunt/unitime,nikeshmhr/unitime,maciej-zygmunt/unitime,zuzanamullerova/unitime,rafati/unitime,sktoo/timetabling-system-,rafati/unitime,UniTime/unitime
/* * UniTime 3.1 (University Course Timetabling & Student Sectioning Application) * Copyright (C) 2008, UniTime.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.unitime.timetable.model; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.unitime.timetable.model.base.BaseEvent; import org.unitime.timetable.model.dao.EventDAO; public class Event extends BaseEvent { private static final long serialVersionUID = 1L; /*[CONSTRUCTOR MARKER BEGIN]*/ public Event () { super(); } /** * Constructor for primary key */ public Event (java.lang.Long uniqueId) { super(uniqueId); } /** * Constructor for required fields */ public Event ( java.lang.Long uniqueId, org.unitime.timetable.model.EventType eventType, java.lang.Integer minCapacity, java.lang.Integer maxCapacity) { super ( uniqueId, eventType, minCapacity, maxCapacity); } /*[CONSTRUCTOR MARKER END]*/ public static List findEventsOfSubjectArea(org.hibernate.Session hibSession, Long subjectAreaId, Integer eventType) { return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.course.subjectArea.uniqueId=:subjectAreaId and e.eventType.uniqueId=:eventType") .setLong("subjectAreaId", subjectAreaId) .setInteger("examType", eventType) .setCacheable(true) .list(); } public static List findEventsOfSubjectArea(Long subjectAreaId, Integer eventType) { return (findEventsOfSubjectArea((new EventDAO().getSession()), subjectAreaId, eventType)); } public static List findExamsOfCourseOffering(org.hibernate.Session hibSession, Long courseOfferingId, Integer eventType) { return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.course.uniqueId=:courseOfferingId and e.eventType.uniqueId=:eventType") .setLong("courseOfferingId", courseOfferingId) .setInteger("eventType", eventType) .setCacheable(true) .list(); } public static List findExamsOfCourseOffering(Long courseOfferingId, Integer eventType) { return (findExamsOfCourseOffering((new EventDAO().getSession()),courseOfferingId, eventType)); } public static List findEventsOfCourse(org.hibernate.Session hibSession, Long subjectAreaId, String courseNbr, Integer eventType) { if (courseNbr==null || courseNbr.trim().length()==0) return findEventsOfSubjectArea(subjectAreaId, eventType); return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.course.subjectArea.uniqueId=:subjectAreaId and e.eventType.uniqueId=:eventType and "+ (courseNbr.indexOf('*')>=0?"r.course.courseNbr like :courseNbr":"r.course.courseNbr=:courseNbr")) .setLong("subjectAreaId", subjectAreaId) .setString("courseNbr", courseNbr.trim().replaceAll("\\*", "%")) .setInteger("eventType", eventType) .setCacheable(true) .list(); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, Long ownerId, Integer ownerType) { return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.ownerId=:ownerId and r.ownerType=:ownerType and e.eventType.uniqueId=:eventType") .setLong("ownerId", ownerId) .setInteger("ownerType", ownerType) .setLong("eventType", eventType) .setCacheable(true) .list(); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, Long ownerId, Integer ownerType) { return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, ownerId, ownerType)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, CourseOffering courseOffering){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, courseOffering.getUniqueId(), ExamOwner.sOwnerTypeCourse)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, CourseOffering courseOffering){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, courseOffering)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, InstructionalOffering instructionalOffering){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, instructionalOffering.getUniqueId(), ExamOwner.sOwnerTypeOffering)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, InstructionalOffering instructionalOffering){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, instructionalOffering)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, InstrOfferingConfig instrOffrConfig){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, instrOffrConfig.getUniqueId(), ExamOwner.sOwnerTypeConfig)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, InstrOfferingConfig instrOffrConfig){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, instrOffrConfig)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, Class_ clazz){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, clazz.getUniqueId(), ExamOwner.sOwnerTypeClass)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, Class_ clazz){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, clazz)); } public static List findEventsOfCourse(Long subjectAreaId, String courseNbr, Integer eventType) { if (courseNbr==null || courseNbr.trim().length()==0) return findEventsOfSubjectArea(subjectAreaId, eventType); return (findEventsOfCourse((new EventDAO().getSession()), subjectAreaId, courseNbr, eventType)); } public Set<Object> getStudents() { HashSet<Object> students = new HashSet<Object>(); for (Iterator<?> i=getRelatedCourses().iterator();i.hasNext();) students.addAll(((RelatedCourseInfo)i.next()).getStudents()); return students; } public int countStudents() { int nrStudents = 0; for (Iterator i=getRelatedCourses().iterator();i.hasNext();) nrStudents += ((RelatedCourseInfo)i.next()).countStudents(); return nrStudents; } public static void deleteFromEvents(org.hibernate.Session hibSession, Integer ownerType, Long ownerId) { for (Iterator i=hibSession.createQuery("select r from Event e inner join e.relatedCourses r where "+ "r.ownerType=:ownerType and r.ownerId=:ownerId") .setInteger("ownerType", ownerType) .setLong("ownerId", ownerId).iterate();i.hasNext();) { RelatedCourseInfo relatedCourse = (RelatedCourseInfo)i.next(); Event event = relatedCourse.getEvent(); event.getRelatedCourses().remove(relatedCourse); relatedCourse.setOwnerId(null); relatedCourse.setCourse(null); hibSession.delete(relatedCourse); if (event.getRelatedCourses().isEmpty()) { hibSession.delete(event); } else { hibSession.saveOrUpdate(event); } } } public static void deleteFromEvents(org.hibernate.Session hibSession, Class_ clazz) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeClass, clazz.getUniqueId()); } public static void deleteFromEvents(org.hibernate.Session hibSession, InstrOfferingConfig config) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeConfig, config.getUniqueId()); } public static void deleteFromEvents(org.hibernate.Session hibSession, InstructionalOffering offering) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeOffering, offering.getUniqueId()); } public static void deleteFromEvents(org.hibernate.Session hibSession, CourseOffering course) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeCourse, course.getUniqueId()); } public String toString() { return (this.getEventName()); } // methods for eventDetail and eventList pages public int compareTo (Event e) { return getUniqueId().compareTo(e.getUniqueId()); } public static List findAll() { return new EventDAO().getSession().createQuery( "select e from Event e" ) .setCacheable(true) .list(); } }
JavaSource/org/unitime/timetable/model/Event.java
/* * UniTime 3.1 (University Course Timetabling & Student Sectioning Application) * Copyright (C) 2008, UniTime.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.unitime.timetable.model; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.unitime.timetable.model.base.BaseEvent; import org.unitime.timetable.model.dao.EventDAO; import org.unitime.timetable.util.Constants; public class Event extends BaseEvent { private static final long serialVersionUID = 1L; /*[CONSTRUCTOR MARKER BEGIN]*/ public Event () { super(); } /** * Constructor for primary key */ public Event (java.lang.Long uniqueId) { super(uniqueId); } /** * Constructor for required fields */ public Event ( java.lang.Long uniqueId, org.unitime.timetable.model.EventType eventType, java.lang.Integer minCapacity, java.lang.Integer maxCapacity) { super ( uniqueId, eventType, minCapacity, maxCapacity); } /*[CONSTRUCTOR MARKER END]*/ public static List findEventsOfSubjectArea(org.hibernate.Session hibSession, Long subjectAreaId, Integer eventType) { return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.course.subjectArea.uniqueId=:subjectAreaId and e.eventType.uniqueId=:eventType") .setLong("subjectAreaId", subjectAreaId) .setInteger("examType", eventType) .setCacheable(true) .list(); } public static List findEventsOfSubjectArea(Long subjectAreaId, Integer eventType) { return (findEventsOfSubjectArea((new EventDAO().getSession()), subjectAreaId, eventType)); } public static List findExamsOfCourseOffering(org.hibernate.Session hibSession, Long courseOfferingId, Integer eventType) { return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.course.uniqueId=:courseOfferingId and e.eventType.uniqueId=:eventType") .setLong("courseOfferingId", courseOfferingId) .setInteger("eventType", eventType) .setCacheable(true) .list(); } public static List findExamsOfCourseOffering(Long courseOfferingId, Integer eventType) { return (findExamsOfCourseOffering((new EventDAO().getSession()),courseOfferingId, eventType)); } public static List findEventsOfCourse(org.hibernate.Session hibSession, Long subjectAreaId, String courseNbr, Integer eventType) { if (courseNbr==null || courseNbr.trim().length()==0) return findEventsOfSubjectArea(subjectAreaId, eventType); return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.course.subjectArea.uniqueId=:subjectAreaId and e.eventType.uniqueId=:eventType and "+ (courseNbr.indexOf('*')>=0?"r.course.courseNbr like :courseNbr":"r.course.courseNbr=:courseNbr")) .setLong("subjectAreaId", subjectAreaId) .setString("courseNbr", courseNbr.trim().replaceAll("\\*", "%")) .setInteger("eventType", eventType) .setCacheable(true) .list(); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, Long ownerId, Integer ownerType) { return hibSession.createQuery( "select distinct e from Event e inner join e.relatedCourses r where " + "r.ownerId=:ownerId and r.ownerType=:ownerType and e.eventType.uniqueId=:eventType") .setLong("ownerId", ownerId) .setInteger("ownerType", ownerType) .setLong("eventType", eventType) .setCacheable(true) .list(); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, Long ownerId, Integer ownerType) { return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, ownerId, ownerType)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, CourseOffering courseOffering){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, courseOffering.getUniqueId(), ExamOwner.sOwnerTypeCourse)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, CourseOffering courseOffering){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, courseOffering)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, InstructionalOffering instructionalOffering){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, instructionalOffering.getUniqueId(), ExamOwner.sOwnerTypeOffering)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, InstructionalOffering instructionalOffering){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, instructionalOffering)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, InstrOfferingConfig instrOffrConfig){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, instrOffrConfig.getUniqueId(), ExamOwner.sOwnerTypeConfig)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, InstrOfferingConfig instrOffrConfig){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, instrOffrConfig)); } public static List findCourseRelatedEventsOfTypeOwnedBy(org.hibernate.Session hibSession, Long eventType, Class_ clazz){ return(findCourseRelatedEventsOfTypeOwnedBy(hibSession, eventType, clazz.getUniqueId(), ExamOwner.sOwnerTypeClass)); } public static List findCourseRelatedEventsOfTypeOwnedBy(Long eventType, Class_ clazz){ return(findCourseRelatedEventsOfTypeOwnedBy((new EventDAO().getSession()), eventType, clazz)); } public static List findEventsOfCourse(Long subjectAreaId, String courseNbr, Integer eventType) { if (courseNbr==null || courseNbr.trim().length()==0) return findEventsOfSubjectArea(subjectAreaId, eventType); return (findEventsOfCourse((new EventDAO().getSession()), subjectAreaId, courseNbr, eventType)); } public Set<Object> getStudents() { HashSet<Object> students = new HashSet<Object>(); for (Iterator<?> i=getRelatedCourses().iterator();i.hasNext();) students.addAll(((RelatedCourseInfo)i.next()).getStudents()); return students; } public int countStudents() { int nrStudents = 0; for (Iterator i=getRelatedCourses().iterator();i.hasNext();) nrStudents += ((RelatedCourseInfo)i.next()).countStudents(); return nrStudents; } public static void deleteFromEvents(org.hibernate.Session hibSession, Integer ownerType, Long ownerId) { for (Iterator i=hibSession.createQuery("select r from Event e inner join e.relatedCourses r where "+ "r.ownerType=:ownerType and r.ownerId=:ownerId") .setInteger("ownerType", ownerType) .setLong("ownerId", ownerId).iterate();i.hasNext();) { RelatedCourseInfo relatedCourse = (RelatedCourseInfo)i.next(); Event event = relatedCourse.getEvent(); event.getRelatedCourses().remove(relatedCourse); relatedCourse.setOwnerId(null); relatedCourse.setCourse(null); hibSession.delete(relatedCourse); if (event.getRelatedCourses().isEmpty()) { hibSession.delete(event); } else { hibSession.saveOrUpdate(event); } } } public static void deleteFromEvents(org.hibernate.Session hibSession, Class_ clazz) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeClass, clazz.getUniqueId()); } public static void deleteFromEvents(org.hibernate.Session hibSession, InstrOfferingConfig config) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeConfig, config.getUniqueId()); } public static void deleteFromEvents(org.hibernate.Session hibSession, InstructionalOffering offering) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeOffering, offering.getUniqueId()); } public static void deleteFromEvents(org.hibernate.Session hibSession, CourseOffering course) { deleteFromEvents(hibSession, ExamOwner.sOwnerTypeCourse, course.getUniqueId()); } public String toString() { return (this.getEventName()); } }
Added methods compareTo (not yet used) and findAll (currently used in Events)
JavaSource/org/unitime/timetable/model/Event.java
Added methods compareTo (not yet used) and findAll (currently used in Events)
<ide><path>avaSource/org/unitime/timetable/model/Event.java <ide> <ide> import org.unitime.timetable.model.base.BaseEvent; <ide> import org.unitime.timetable.model.dao.EventDAO; <del>import org.unitime.timetable.util.Constants; <del> <ide> <ide> <ide> public class Event extends BaseEvent { <ide> return (this.getEventName()); <ide> } <ide> <add>// methods for eventDetail and eventList pages <add> public int compareTo (Event e) { <add> return getUniqueId().compareTo(e.getUniqueId()); <add> } <add> <add> public static List findAll() { <add> return new EventDAO().getSession().createQuery( <add> "select e from Event e" <add> ) <add> .setCacheable(true) <add> .list(); <add> } <add> <add> <ide> }
Java
lgpl-2.1
867d428d019c4d14dd972e9e85fc39fff226d685
0
godbyk/vrjuggler-upstream-old,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ package org.vrjuggler.jccl.editors; import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import org.vrjuggler.jccl.config.*; import org.vrjuggler.jccl.config.undo.ConfigElementNameEdit; /** * Simple factory-like helper class that centralizes the creation of the * data flavors that are needed for copy/paste and drag-and-drop support. */ class DataFlavorFactory { static DataFlavor makeConfigElementFlavor() { return new DataFlavor(ConfigElement.class, "VR Juggler Config Element"); } } /** * Wraps a ConfigElement to allow us to transfer it from on context to another * either using copy/past or drag and drop methods. */ class ConfigElementSelection implements ClipboardOwner , Transferable { /** * Constructor that takes the given ConfigElement and creates a Transferable * wrapper around it to allow us to move the ConfigElement from one context * to another. */ public ConfigElementSelection(ConfigElement elm) { mConfigElement = elm; } /** * Return the ConfigElement that we are transfering. */ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (flavor.getRepresentationClass().equals(ConfigElement.class)) { return mConfigElement; } else { throw new UnsupportedFlavorException(flavor); } } /** * Return an array of valid DataFlavors that we can use to pass * ConfigElements from one context to another context. */ public DataFlavor[] getTransferDataFlavors() { return flavors; } /** * Check if the given DataFlavor is a valid flavor for transfering * ConfigElements from one context to another. */ public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.getRepresentationClass().equals(ConfigElement.class); } /** * Informs the ConfigContextEditor that it has lost the clipboard. */ public void lostOwnership(Clipboard clip, Transferable obj) { ; } /** ConfigElement that we are transfering. */ private ConfigElement mConfigElement = null; /** Array of valid DataFlavors for transfering a ConfigElement. */ private DataFlavor[] flavors = { DataFlavorFactory.makeConfigElementFlavor() }; } /** * Returns a component used to edit the name of the ConfigElement in the JTree. */ class ElementNameEditor implements TreeCellEditor { /** * Constructor that takes a reference to the JTree that we will be editing. * This is required so that we can determine if the selected node is * editable. */ public ElementNameEditor(JTree tree) { mTree = tree; } /** * Returns a component that will be used to edit the name of the * ConfigElement. */ public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { // Get a reference to the selected TreeNode. DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; if(!(node.getUserObject() instanceof ConfigElement)) { throw new IllegalArgumentException("Error: " + "The selected node contains an object with type:" + node.getUserObject().getClass()); } // Get a reference to the selected ConfigElement. mElement = (ConfigElement)node.getUserObject(); mTextField = new JTextField(mElement.getName()); mTree = tree; // Specify what should happen when done editing. mTextField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Force the focus to be lost. //mTextField.transferFocusUpCycle(); // Force the focus to be transfered to the next component. //mTextField.transferFocus(); // This is no longer needed since the above line will force a // focusLostEvent. But I have choosen to leave this line here in // case it might become useful later. //stopCellEditing(); mTree.clearSelection(); } }); mTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { stopCellEditing(); } }); return mTextField; } public Object getCellEditorValue() { return mElement; } public boolean isCellEditable(EventObject evt) { TreePath current_selection = mTree.getSelectionPath(); if (current_selection != null) { DefaultMutableTreeNode current_node = (DefaultMutableTreeNode) (current_selection.getLastPathComponent()); if (current_node != null) { if(current_node.getUserObject() instanceof ConfigElement) { return true; } } } return false; } public boolean shouldSelectCell(EventObject evt) { return true; } public boolean stopCellEditing() { // Detect when the user does not actually change the name. if (mTextField.getText().equals(mElement.getName())) { return false; } ConfigContext ctx = ((ConfigContextModel)mTree.getModel()).getContext(); if (ctx.containsElementNamed(mTextField.getText())) { JOptionPane.showMessageDialog(null, "A ConfigElement named \"" + mTextField.getText() + "\" already exists.", "Invalid Name", JOptionPane.ERROR_MESSAGE); return false; } ConfigElementNameEdit new_edit = new ConfigElementNameEdit(mElement, mElement.getName(), mTextField.getText()); mElement.setName(mTextField.getText()); ctx.postEdit(new_edit); return true; } public void cancelCellEditing() { ; } public void addCellEditorListener(CellEditorListener l) { ; } public void removeCellEditorListener(CellEditorListener l) { ; } private JTree mTree = null; private JTextField mTextField = null; private ConfigElement mElement = null; } /** * A JTree that allows us to transfer ConfigElements to/from other ElementTrees * in other contexts. */ class ElementTree extends JTree implements DragGestureListener , DragSourceListener , DropTargetListener , ActionListener { JPopupMenu mPopup; Clipboard clipboard = getToolkit().getSystemClipboard(); /** * Create a JTree that supports the dragging and dropping of ConfigElements. */ public ElementTree() { super(); // Allow the user to change the name of a leaf node(an element) setEditable(true); // setCellEditor(new DefaultTreeCellEditor(this, // new DefaultTreeCellRenderer())); setCellEditor(new DefaultTreeCellEditor(this, new DefaultTreeCellRenderer(), new ElementNameEditor(this))); DragSource dragSource = DragSource.getDefaultDragSource(); // Create a new drop target. We do not need to keep a reference to this // since internally it associates itself with the componenets that it // needs. new DropTarget( this, // Component to associate with. DnDConstants.ACTION_COPY_OR_MOVE, // Default acceptable actions. this // Drop target listener. ); // Create a DragGestureRecognizer to watch for drags. Once again we do // not need to keep the reference that is returned from this method. dragSource.createDefaultDragGestureRecognizer( this, // component where drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this // drag gesture recognizer ); // Load the icons for the popup menu. ClassLoader loader = getClass().getClassLoader(); ImageIcon cut_icon = null; ImageIcon copy_icon = null; ImageIcon paste_icon = null; ImageIcon remove_icon = null; try { String img_root = "org/vrjuggler/jccl/editors/images"; cut_icon = new ImageIcon(loader.getResource(img_root + "/Cut16.gif")); copy_icon = new ImageIcon(loader.getResource(img_root + "/Copy16.gif")); paste_icon = new ImageIcon(loader.getResource(img_root + "/Paste16.gif")); remove_icon = new ImageIcon(loader.getResource(img_root + "/Delete16.gif")); } catch(Exception ex) { ex.printStackTrace(); } // Set up the pop up menu mPopup = new JPopupMenu(); mDeleteMenuItem = new JMenuItem("Delete", remove_icon); mDeleteMenuItem.addActionListener(this); mDeleteMenuItem.setActionCommand("delete"); mDeleteMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0) ); mPopup.add(mDeleteMenuItem); mRenameMenuItem = new JMenuItem("Rename"); mRenameMenuItem.addActionListener(this); mRenameMenuItem.setActionCommand("rename"); mPopup.add(mRenameMenuItem); mPopup.addSeparator(); int shortcut_mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); mCutMenuItem = new JMenuItem("Cut", cut_icon); mCutMenuItem.addActionListener(this); mCutMenuItem.setActionCommand("cut"); mCutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, shortcut_mask)); mPopup.add(mCutMenuItem); mCopyMenuItem = new JMenuItem("Copy", copy_icon); mCopyMenuItem.addActionListener(this); mCopyMenuItem.setActionCommand("copy"); mCopyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, shortcut_mask)); mPopup.add(mCopyMenuItem); mPasteMenuItem = new JMenuItem("Paste", paste_icon); mPasteMenuItem.addActionListener(this); mPasteMenuItem.setActionCommand("paste"); mPasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, shortcut_mask)); mPopup.add(mPasteMenuItem); mPopup.setOpaque(true); mPopup.setLightWeightPopupEnabled(true); // Add mouse listener to get the popup menu events. addMouseListener( new MouseAdapter() { // NOTE: XWindows and Windows sense popup trigger events at // different times. On windows it occurs when the mouse is // released, while on XWindows is occurs when the mouse // button is pressed. // Check for a popup trigger on Windows. public void mouseReleased( MouseEvent e ) { // Get the currently selected ConfigElement. TreePath path = getLeadSelectionPath(); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object temp = node.getUserObject(); if (temp instanceof ConfigElement) { mDeleteMenuItem.setEnabled(true); mRenameMenuItem.setEnabled(true); mCutMenuItem.setEnabled(true); mCopyMenuItem.setEnabled(true); mPasteMenuItem.setEnabled(true); // Ensure that the ConfigElement is writable. if ( ((ConfigElement)temp).isReadOnly() ) { mDeleteMenuItem.setEnabled(false); mRenameMenuItem.setEnabled(false); mCutMenuItem.setEnabled(false); mPasteMenuItem.setEnabled(false); } if ( e.isPopupTrigger()) { mPopup.show((JComponent) e.getSource(), e.getX(), e.getY()); } } } } // Check for a popup trigger on XWindows. public void mousePressed(MouseEvent e) { mouseReleased(e); } }); // Add key listener to catch the shortcuts for cut/copy/paste/delete addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { int shortcut_mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if(e.getKeyCode() == KeyEvent.VK_C && e.getModifiers() == shortcut_mask) { System.out.println("We have a copy."); actionPerformed(new ActionEvent(this, 0, "copy")); } if(e.getKeyCode() == KeyEvent.VK_V && e.getModifiers() == shortcut_mask) { System.out.println("We have a paste."); actionPerformed(new ActionEvent(this, 0, "paste")); } if(e.getKeyCode() == KeyEvent.VK_X && e.getModifiers() == shortcut_mask) { System.out.println("We have a cut."); actionPerformed(new ActionEvent(this, 0, "cut")); } if(e.getKeyCode() == KeyEvent.VK_DELETE && e.getModifiers() == 0) { System.out.println("We have a delete."); actionPerformed(new ActionEvent(this, 0, "delete")); } } } ); } public void setContextEditable(boolean val) { mContextEditable = val; } /** * Catch all events for the pop-up menu events. */ public void actionPerformed(ActionEvent ae) { // Get the currently selected ConfigElement. TreePath path = this.getLeadSelectionPath(); // Ensure that we have a valid selection path. if (null == path) { return; } DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object temp = node.getUserObject(); // Make sure that we have a ConfigElement selected. if ( (temp instanceof ConfigElement) ) { ConfigElement elm = (ConfigElement)temp; // If the user selected the copy action. if( ae.getActionCommand().equals("copy") ) { // Place ConfigElement in the system clipboard. ConfigElementSelection selection = new ConfigElementSelection(elm); // TODO: Change owner of clipboard. clipboard.setContents(selection, selection); } if ( !elm.isReadOnly() ) // Ensure that the ConfigElement is writable. { // If the user selcted the remove menu item. if( ae.getActionCommand().equals("delete") ) { TreeModel model = this.getModel(); // Remove the ConfigElement from the context. if( model instanceof ConfigContextModel ) { Object[] nodes = getLeadSelectionPath().getPath(); DefaultMutableTreeNode cur_node; // The last node in the path is the config element that the // user wants to remove. We do not have to test the type // before the cast because the user interface only allows // removal of ConfigElement objects. cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 1]; ConfigElement elt_to_remove = (ConfigElement) cur_node.getUserObject(); // Now, we need to see if the parent of the selected config // element is a PropertyDefinition object. cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 2]; Object obj = cur_node.getUserObject(); ConfigContext context = ((ConfigContextModel) model).getContext(); // If the parent of the config element to remove is a // PropertyDefinition object, then the user wants to remove // an embedded element. This must be done by editing the // appropriate property in the config element containing the // one to be removed. if ( obj instanceof PropertyDefinition ) { PropertyDefinition prop_def = (PropertyDefinition) obj; cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 3]; ConfigElement owner = (ConfigElement) cur_node.getUserObject(); owner.removeProperty(prop_def.getToken(), elt_to_remove, context); } // If the parent of the config element to remove is not a // PropertyDefinition object, then we have a "top-level" // config element. We have to remove it using the Config // Broker. else { ConfigBroker broker = new ConfigBrokerProxy(); boolean removed = broker.remove(context, elt_to_remove); if ( ! removed ) { Container parent = SwingUtilities.getAncestorOfClass(Container.class, this); JOptionPane.showMessageDialog( parent, "Failed to remove config element '" + elt_to_remove.getName() + "'", "Config Element Removal Failed", JOptionPane.ERROR_MESSAGE ); } } } } // Start editing the currently selected ConfigElement if we want // to rename it. if(ae.getActionCommand().equals("rename")) { // Get the currently selected ConfigElement. startEditingAtPath(path); } // If the user selects the cut operation we should first copy it // into the clipboard and then delete it from the active context. if(ae.getActionCommand().equals("cut")) { ActionEvent evt; evt = new ActionEvent(this, -1, "copy"); actionPerformed(evt); evt = new ActionEvent(this, -1, "delete"); actionPerformed(evt); } } } // If the user selected the paste action. if(ae.getActionCommand().equals("paste") && mContextEditable) { try { // Get the context model for this JTree. TreeModel model = this.getModel(); ConfigContextModel config_model = (ConfigContextModel)model; // Get the ConfigElement to paste out of the clipboard. DataFlavor my_flavor = DataFlavorFactory.makeConfigElementFlavor(); Transferable tr = clipboard.getContents(this); // If this JTree has a valid JTreeModel and the incoming paste // supports the DataFlavor that we are trying to use. if ( model instanceof ConfigContextModel && tr.isDataFlavorSupported(my_flavor) ) { // Get the ConfigElement that we are transfering and make a deep // copy of it. ConfigElement old_elm = (ConfigElement) tr.getTransferData(my_flavor); ConfigElement new_elm = new ConfigElement(old_elm); // Make sure that we have a meaningful unique name. ConfigContext ctx = config_model.getContext(); String base_name = new_elm.getName(); int num = 1; while(ctx.containsElement(new_elm)) { String new_name = base_name + "Copy" + Integer.toString(num); new_elm.setName(new_name); ++num; } // Make sure that we are not trying to add an element to // ourselves. ConfigBroker broker = new ConfigBrokerProxy(); // Make sure this add goes through successfully if (!broker.add(config_model.getContext(), new_elm)) { throw new Exception("Could not paste ConfigElement into " + "context."); } System.out.println("Paste completed..."); } } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } } /** * When the user attempts to drag an object out of the JTree we need to * prepare the associated transfer object. */ public void dragGestureRecognized(DragGestureEvent e) { if(e.getDragAction() == DnDConstants.ACTION_COPY) { System.out.println("Copy..."); } else if(e.getDragAction() == DnDConstants.ACTION_MOVE) { System.out.println("Move..."); } else { System.out.println("Something else: " + e.getDragAction()); } // Get the selected node the JTree. TreePath path = getLeadSelectionPath(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); // Get the object associated with it, and if it is a ConfigElement // prepare it to be transfered. Object temp = node.getUserObject(); if(null != temp && temp instanceof ConfigElement) { // Start the dragging action with the given icon, transferable object // and listener to listen for the dropEnd event that will only occur // in the case of a successful drag and drop. e.startDrag(DragSource.DefaultCopyDrop, // cursor new ConfigElementSelection((ConfigElement)temp), // transferable this); // drag source listener } } /** * Take appropriate actions after a drop has ended. */ public void dragDropEnd(DragSourceDropEvent e) { if(e.getDropAction() == DnDConstants.ACTION_COPY) { System.out.println("Copy has occured..."); } else if(e.getDropAction() == DnDConstants.ACTION_MOVE) { System.out.println("Move has occured..."); } else { System.out.println("Something else: " + e.getDropAction() + " has occured."); } // If the drag was successful and it was not a copy action, then default // to a move action and remove the ConfigElement from our context. if(e.getDropSuccess() && (e.getDropAction() != DnDConstants.ACTION_COPY)) { TreeModel model = this.getModel(); if(model instanceof ConfigContextModel) { DataFlavor my_flavor = DataFlavorFactory.makeConfigElementFlavor(); try { // Get the ConfigElement that we are trying to transfer. // NOTE: We could get the selected ConfigElement from the JTree, // but this might be more error prone than getting it this way. ConfigElement elm = (ConfigElement) e.getDragSourceContext().getTransferable().getTransferData(my_flavor); ConfigContextModel config_model = (ConfigContextModel)model; ConfigBroker broker = new ConfigBrokerProxy(); // Make sure this add goes through successfully if (!broker.remove(config_model.getContext(), elm)) { throw new Exception("Failed to remove ConfigElement from " + "context after a copy action."); } } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } } } public void dragEnter(DragSourceDragEvent e) { ; } public void dragExit(DragSourceEvent e) { ; } public void dragOver(DragSourceDragEvent e) { ; } public void dropActionChanged(DragSourceDragEvent e) { ; } /** * Attept to handle the dropping of a ConfigElement into this JTree. */ public void drop(DropTargetDropEvent e) { if(e.getDropAction() == DnDConstants.ACTION_COPY) { System.out.println("Dropping a Copy..."); } else if(e.getDropAction() == DnDConstants.ACTION_MOVE) { System.out.println("Dropping a Move..."); } else { System.out.println("Dropping Something else: " + e.getDropAction()); } try { TreeModel model = this.getModel(); ConfigContextModel config_model = (ConfigContextModel)model; DataFlavor my_flavor = DataFlavorFactory.makeConfigElementFlavor(); Transferable tr = e.getTransferable(); // If this JTree has a valid JTreeModel and the incoming drop supports // the DataFlavor that we are trying to use. if ( model instanceof ConfigContextModel && e.isDataFlavorSupported(my_flavor) ) { // Get the ConfigElement that we are transfering. ConfigElement elm = (ConfigElement)tr.getTransferData(my_flavor); // Make sure that we are not trying to add an element to ourselves. ConfigBroker broker = new ConfigBrokerProxy(); java.util.List data_sources = config_model.getContext().getResources(); for(Iterator itr = data_sources.iterator() ; itr.hasNext() ; ) { java.util.List elm_list = broker.getElementsIn((String)itr.next()); if(elm_list.contains(elm)) { System.out.println("You can not drag an Element into a " + "context in which it already exists."); e.rejectDrop(); return; } } // Accept whatever action was sent to us. e.acceptDrop(e.getDropAction()); // Make sure this add goes through successfully if (!broker.add(config_model.getContext(), elm)) { e.rejectDrop(); throw new Exception("Could not add dropped ConfigElement " + "into context."); } System.out.println("Drop completed..."); e.dropComplete(true); } else { e.rejectDrop(); } } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } public void dragEnter(DropTargetDragEvent e) { ; } public void dragExit(DropTargetEvent e) { ; } public void dragOver(DropTargetDragEvent e) { ; } public void dropActionChanged(DropTargetDragEvent e) { ; } private JMenuItem mDeleteMenuItem = null; private JMenuItem mRenameMenuItem = null; private JMenuItem mCutMenuItem = null; private JMenuItem mCopyMenuItem = null; private JMenuItem mPasteMenuItem = null; private boolean mContextEditable = false; }
modules/jackal/editors/org/vrjuggler/jccl/editors/ElementTree.java
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ package org.vrjuggler.jccl.editors; import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import org.vrjuggler.jccl.config.*; import org.vrjuggler.jccl.config.undo.ConfigElementNameEdit; /** * Simple factory-like helper class that centralizes the creation of the * data flavors that are needed for copy/paste and drag-and-drop support. */ class DataFlavorFactory { static DataFlavor makeConfigElementFlavor() { return new DataFlavor(ConfigElement.class, "VR Juggler Config Element"); } } /** * Wraps a ConfigElement to allow us to transfer it from on context to another * either using copy/past or drag and drop methods. */ class ConfigElementSelection implements ClipboardOwner , Transferable { /** * Constructor that takes the given ConfigElement and creates a Transferable * wrapper around it to allow us to move the ConfigElement from one context * to another. */ public ConfigElementSelection(ConfigElement elm) { mConfigElement = elm; } /** * Return the ConfigElement that we are transfering. */ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (flavor.getRepresentationClass().equals(ConfigElement.class)) { return mConfigElement; } else { throw new UnsupportedFlavorException(flavor); } } /** * Return an array of valid DataFlavors that we can use to pass * ConfigElements from one context to another context. */ public DataFlavor[] getTransferDataFlavors() { return flavors; } /** * Check if the given DataFlavor is a valid flavor for transfering * ConfigElements from one context to another. */ public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.getRepresentationClass().equals(ConfigElement.class); } /** * Informs the ConfigContextEditor that it has lost the clipboard. */ public void lostOwnership(Clipboard clip, Transferable obj) { ; } /** ConfigElement that we are transfering. */ private ConfigElement mConfigElement = null; /** Array of valid DataFlavors for transfering a ConfigElement. */ private DataFlavor[] flavors = { DataFlavorFactory.makeConfigElementFlavor() }; } /** * Returns a component used to edit the name of the ConfigElement in the JTree. */ class ElementNameEditor implements TreeCellEditor { /** * Constructor that takes a reference to the JTree that we will be editing. * This is required so that we can determine if the selected node is * editable. */ public ElementNameEditor(JTree tree) { mTree = tree; } /** * Returns a component that will be used to edit the name of the * ConfigElement. */ public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { // Get a reference to the selected TreeNode. DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; if(!(node.getUserObject() instanceof ConfigElement)) { throw new IllegalArgumentException("Error: " + "The selected node contains an object with type:" + node.getUserObject().getClass()); } // Get a reference to the selected ConfigElement. mElement = (ConfigElement)node.getUserObject(); mTextField = new JTextField(mElement.getName()); mTree = tree; // Specify what should happen when done editing. mTextField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Force the focus to be lost. //mTextField.transferFocusUpCycle(); // Force the focus to be transfered to the next component. //mTextField.transferFocus(); // This is no longer needed since the above line will force a // focusLostEvent. But I have choosen to leave this line here in // case it might become useful later. //stopCellEditing(); mTree.clearSelection(); } }); mTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { stopCellEditing(); } }); return mTextField; } public Object getCellEditorValue() { return mElement; } public boolean isCellEditable(EventObject evt) { TreePath current_selection = mTree.getSelectionPath(); if (current_selection != null) { DefaultMutableTreeNode current_node = (DefaultMutableTreeNode) (current_selection.getLastPathComponent()); if (current_node != null) { if(current_node.getUserObject() instanceof ConfigElement) { return true; } } } return false; } public boolean shouldSelectCell(EventObject evt) { return true; } public boolean stopCellEditing() { // Detect when the user does not actually change the name. if (mTextField.getText().equals(mElement.getName())) { return false; } ConfigContext ctx = ((ConfigContextModel)mTree.getModel()).getContext(); if (ctx.containsElementNamed(mTextField.getText())) { JOptionPane.showMessageDialog(null, "A ConfigElement named \"" + mTextField.getText() + "\" already exists.", "Invalid Name", JOptionPane.ERROR_MESSAGE); return false; } ConfigElementNameEdit new_edit = new ConfigElementNameEdit(mElement, mElement.getName(), mTextField.getText()); mElement.setName(mTextField.getText()); ctx.postEdit(new_edit); return true; } public void cancelCellEditing() { ; } public void addCellEditorListener(CellEditorListener l) { ; } public void removeCellEditorListener(CellEditorListener l) { ; } private JTree mTree = null; private JTextField mTextField = null; private ConfigElement mElement = null; } /** * A JTree that allows us to transfer ConfigElements to/from other ElementTrees * in other contexts. */ class ElementTree extends JTree implements DragGestureListener , DragSourceListener , DropTargetListener , ActionListener { JPopupMenu mPopup; Clipboard clipboard = getToolkit().getSystemClipboard(); /** * Create a JTree that supports the dragging and dropping of ConfigElements. */ public ElementTree() { super(); // Allow the user to change the name of a leaf node(an element) setEditable(true); // setCellEditor(new DefaultTreeCellEditor(this, // new DefaultTreeCellRenderer())); setCellEditor(new DefaultTreeCellEditor(this, new DefaultTreeCellRenderer(), new ElementNameEditor(this))); DragSource dragSource = DragSource.getDefaultDragSource(); // Create a new drop target. We do not need to keep a reference to this // since internally it associates itself with the componenets that it // needs. new DropTarget( this, // Component to associate with. DnDConstants.ACTION_COPY_OR_MOVE, // Default acceptable actions. this // Drop target listener. ); // Create a DragGestureRecognizer to watch for drags. Once again we do // not need to keep the reference that is returned from this method. dragSource.createDefaultDragGestureRecognizer( this, // component where drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this // drag gesture recognizer ); // Load the icons for the popup menu. ClassLoader loader = getClass().getClassLoader(); ImageIcon cut_icon = null; ImageIcon copy_icon = null; ImageIcon paste_icon = null; ImageIcon remove_icon = null; try { String img_root = "org/vrjuggler/jccl/editors/images"; cut_icon = new ImageIcon(loader.getResource(img_root + "/Cut16.gif")); copy_icon = new ImageIcon(loader.getResource(img_root + "/Copy16.gif")); paste_icon = new ImageIcon(loader.getResource(img_root + "/Paste16.gif")); remove_icon = new ImageIcon(loader.getResource(img_root + "/Delete16.gif")); } catch(Exception ex) { ex.printStackTrace(); } // Set up the pop up menu mPopup = new JPopupMenu(); mDeleteMenuItem = new JMenuItem("Delete", remove_icon); mDeleteMenuItem.addActionListener(this); mDeleteMenuItem.setActionCommand("delete"); mDeleteMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0) ); mPopup.add(mDeleteMenuItem); mRenameMenuItem = new JMenuItem("Rename"); mRenameMenuItem.addActionListener(this); mRenameMenuItem.setActionCommand("rename"); mPopup.add(mRenameMenuItem); mPopup.addSeparator(); int shortcut_mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); mCutMenuItem = new JMenuItem("Cut", cut_icon); mCutMenuItem.addActionListener(this); mCutMenuItem.setActionCommand("cut"); mCutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, shortcut_mask)); mPopup.add(mCutMenuItem); mCopyMenuItem = new JMenuItem("Copy", copy_icon); mCopyMenuItem.addActionListener(this); mCopyMenuItem.setActionCommand("copy"); mCopyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, shortcut_mask)); mPopup.add(mCopyMenuItem); mPasteMenuItem = new JMenuItem("Paste", paste_icon); mPasteMenuItem.addActionListener(this); mPasteMenuItem.setActionCommand("paste"); mPasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, shortcut_mask)); mPopup.add(mPasteMenuItem); mPopup.setOpaque(true); mPopup.setLightWeightPopupEnabled(true); // Add mouse listener to get the popup menu events. addMouseListener( new MouseAdapter() { // NOTE: XWindows and Windows sense popup trigger events at // different times. On windows it occurs when the mouse is // released, while on XWindows is occurs when the mouse // button is pressed. // Check for a popup trigger on Windows. public void mouseReleased( MouseEvent e ) { // Get the currently selected ConfigElement. TreePath path = getLeadSelectionPath(); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object temp = node.getUserObject(); if (temp instanceof ConfigElement) { mDeleteMenuItem.setEnabled(true); mRenameMenuItem.setEnabled(true); mCutMenuItem.setEnabled(true); mCopyMenuItem.setEnabled(true); mPasteMenuItem.setEnabled(true); // Ensure that the ConfigElement is writable. if ( ((ConfigElement)temp).isReadOnly() ) { mDeleteMenuItem.setEnabled(false); mRenameMenuItem.setEnabled(false); mCutMenuItem.setEnabled(false); mPasteMenuItem.setEnabled(false); } if ( e.isPopupTrigger()) { mPopup.show((JComponent) e.getSource(), e.getX(), e.getY()); } } } } // Check for a popup trigger on XWindows. public void mousePressed(MouseEvent e) { mouseReleased(e); } }); // Add key listener to catch the shortcuts for cut/copy/paste/delete addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { int shortcut_mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if(e.getKeyCode() == KeyEvent.VK_C && e.getModifiers() == shortcut_mask) { System.out.println("We have a copy."); actionPerformed(new ActionEvent(this, 0, "copy")); } if(e.getKeyCode() == KeyEvent.VK_V && e.getModifiers() == shortcut_mask) { System.out.println("We have a paste."); actionPerformed(new ActionEvent(this, 0, "paste")); } if(e.getKeyCode() == KeyEvent.VK_X && e.getModifiers() == shortcut_mask) { System.out.println("We have a cut."); actionPerformed(new ActionEvent(this, 0, "cut")); } if(e.getKeyCode() == KeyEvent.VK_DELETE && e.getModifiers() == 0) { System.out.println("We have a delete."); actionPerformed(new ActionEvent(this, 0, "delete")); } } } ); } public void setContextEditable(boolean val) { mContextEditable = val; } /** * Catch all events for the pop-up menu events. */ public void actionPerformed(ActionEvent ae) { // Get the currently selected ConfigElement. TreePath path = this.getLeadSelectionPath(); // Ensure that we have a valid selection path. if (null == path) { return; } DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); Object temp = node.getUserObject(); // Make sure that we have a ConfigElement selected. if ( (temp instanceof ConfigElement) ) { ConfigElement elm = (ConfigElement)temp; // If the user selected the copy action. if( ae.getActionCommand().equals("copy") ) { // Place ConfigElement in the system clipboard. ConfigElementSelection selection = new ConfigElementSelection(elm); // TODO: Change owner of clipboard. clipboard.setContents(selection, selection); } if ( !elm.isReadOnly() ) // Ensure that the ConfigElement is writable. { // If the user selcted the remove menu item. if( ae.getActionCommand().equals("delete") ) { TreeModel model = this.getModel(); // Remove the ConfigElement from the context. if( model instanceof ConfigContextModel ) { Object[] nodes = getLeadSelectionPath().getPath(); DefaultMutableTreeNode cur_node; cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 1]; ConfigElement elt_to_remove = (ConfigElement) cur_node.getUserObject(); // We need to see if the parent of the selected config // element is a PropertyDefinition object. cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 2]; Object obj = cur_node.getUserObject(); ConfigContext context = ((ConfigContextModel) model).getContext(); // If the parent of the config element to remove is a // PropertyDefinition object, then the user wants to remove // an embedded element. This must be done by editing the // appropriate property in the config element containing the // one to be removed. if ( obj instanceof PropertyDefinition ) { PropertyDefinition prop_def = (PropertyDefinition) obj; cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 3]; ConfigElement owner = (ConfigElement) cur_node.getUserObject(); owner.removeProperty(prop_def.getToken(), elt_to_remove, context); } // If the parent of the config element to remove is not a // PropertyDefinition object, then we have a "top-level" // config element. We have to remove it using the Config // Broker. else { ConfigBroker broker = new ConfigBrokerProxy(); boolean removed = broker.remove(context, elt_to_remove); if ( ! removed ) { Container parent = SwingUtilities.getAncestorOfClass(Container.class, this); JOptionPane.showMessageDialog( parent, "Failed to remove config element '" + elt_to_remove.getName() + "'", "Config Element Removal Failed", JOptionPane.ERROR_MESSAGE ); } } } } // Start editing the currently selected ConfigElement if we want // to rename it. if(ae.getActionCommand().equals("rename")) { // Get the currently selected ConfigElement. startEditingAtPath(path); } // If the user selects the cut operation we should first copy it // into the clipboard and then delete it from the active context. if(ae.getActionCommand().equals("cut")) { ActionEvent evt; evt = new ActionEvent(this, -1, "copy"); actionPerformed(evt); evt = new ActionEvent(this, -1, "delete"); actionPerformed(evt); } } } // If the user selected the paste action. if(ae.getActionCommand().equals("paste") && mContextEditable) { try { // Get the context model for this JTree. TreeModel model = this.getModel(); ConfigContextModel config_model = (ConfigContextModel)model; // Get the ConfigElement to paste out of the clipboard. DataFlavor my_flavor = DataFlavorFactory.makeConfigElementFlavor(); Transferable tr = clipboard.getContents(this); // If this JTree has a valid JTreeModel and the incoming paste // supports the DataFlavor that we are trying to use. if ( model instanceof ConfigContextModel && tr.isDataFlavorSupported(my_flavor) ) { // Get the ConfigElement that we are transfering and make a deep // copy of it. ConfigElement old_elm = (ConfigElement) tr.getTransferData(my_flavor); ConfigElement new_elm = new ConfigElement(old_elm); // Make sure that we have a meaningful unique name. ConfigContext ctx = config_model.getContext(); String base_name = new_elm.getName(); int num = 1; while(ctx.containsElement(new_elm)) { String new_name = base_name + "Copy" + Integer.toString(num); new_elm.setName(new_name); ++num; } // Make sure that we are not trying to add an element to // ourselves. ConfigBroker broker = new ConfigBrokerProxy(); // Make sure this add goes through successfully if (!broker.add(config_model.getContext(), new_elm)) { throw new Exception("Could not paste ConfigElement into " + "context."); } System.out.println("Paste completed..."); } } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } } /** * When the user attempts to drag an object out of the JTree we need to * prepare the associated transfer object. */ public void dragGestureRecognized(DragGestureEvent e) { if(e.getDragAction() == DnDConstants.ACTION_COPY) { System.out.println("Copy..."); } else if(e.getDragAction() == DnDConstants.ACTION_MOVE) { System.out.println("Move..."); } else { System.out.println("Something else: " + e.getDragAction()); } // Get the selected node the JTree. TreePath path = getLeadSelectionPath(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); // Get the object associated with it, and if it is a ConfigElement // prepare it to be transfered. Object temp = node.getUserObject(); if(null != temp && temp instanceof ConfigElement) { // Start the dragging action with the given icon, transferable object // and listener to listen for the dropEnd event that will only occur // in the case of a successful drag and drop. e.startDrag(DragSource.DefaultCopyDrop, // cursor new ConfigElementSelection((ConfigElement)temp), // transferable this); // drag source listener } } /** * Take appropriate actions after a drop has ended. */ public void dragDropEnd(DragSourceDropEvent e) { if(e.getDropAction() == DnDConstants.ACTION_COPY) { System.out.println("Copy has occured..."); } else if(e.getDropAction() == DnDConstants.ACTION_MOVE) { System.out.println("Move has occured..."); } else { System.out.println("Something else: " + e.getDropAction() + " has occured."); } // If the drag was successful and it was not a copy action, then default // to a move action and remove the ConfigElement from our context. if(e.getDropSuccess() && (e.getDropAction() != DnDConstants.ACTION_COPY)) { TreeModel model = this.getModel(); if(model instanceof ConfigContextModel) { DataFlavor my_flavor = DataFlavorFactory.makeConfigElementFlavor(); try { // Get the ConfigElement that we are trying to transfer. // NOTE: We could get the selected ConfigElement from the JTree, // but this might be more error prone than getting it this way. ConfigElement elm = (ConfigElement) e.getDragSourceContext().getTransferable().getTransferData(my_flavor); ConfigContextModel config_model = (ConfigContextModel)model; ConfigBroker broker = new ConfigBrokerProxy(); // Make sure this add goes through successfully if (!broker.remove(config_model.getContext(), elm)) { throw new Exception("Failed to remove ConfigElement from " + "context after a copy action."); } } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } } } public void dragEnter(DragSourceDragEvent e) { ; } public void dragExit(DragSourceEvent e) { ; } public void dragOver(DragSourceDragEvent e) { ; } public void dropActionChanged(DragSourceDragEvent e) { ; } /** * Attept to handle the dropping of a ConfigElement into this JTree. */ public void drop(DropTargetDropEvent e) { if(e.getDropAction() == DnDConstants.ACTION_COPY) { System.out.println("Dropping a Copy..."); } else if(e.getDropAction() == DnDConstants.ACTION_MOVE) { System.out.println("Dropping a Move..."); } else { System.out.println("Dropping Something else: " + e.getDropAction()); } try { TreeModel model = this.getModel(); ConfigContextModel config_model = (ConfigContextModel)model; DataFlavor my_flavor = DataFlavorFactory.makeConfigElementFlavor(); Transferable tr = e.getTransferable(); // If this JTree has a valid JTreeModel and the incoming drop supports // the DataFlavor that we are trying to use. if ( model instanceof ConfigContextModel && e.isDataFlavorSupported(my_flavor) ) { // Get the ConfigElement that we are transfering. ConfigElement elm = (ConfigElement)tr.getTransferData(my_flavor); // Make sure that we are not trying to add an element to ourselves. ConfigBroker broker = new ConfigBrokerProxy(); java.util.List data_sources = config_model.getContext().getResources(); for(Iterator itr = data_sources.iterator() ; itr.hasNext() ; ) { java.util.List elm_list = broker.getElementsIn((String)itr.next()); if(elm_list.contains(elm)) { System.out.println("You can not drag an Element into a " + "context in which it already exists."); e.rejectDrop(); return; } } // Accept whatever action was sent to us. e.acceptDrop(e.getDropAction()); // Make sure this add goes through successfully if (!broker.add(config_model.getContext(), elm)) { e.rejectDrop(); throw new Exception("Could not add dropped ConfigElement " + "into context."); } System.out.println("Drop completed..."); e.dropComplete(true); } else { e.rejectDrop(); } } catch(Exception ex) { System.out.println(ex); ex.printStackTrace(); } } public void dragEnter(DropTargetDragEvent e) { ; } public void dragExit(DropTargetEvent e) { ; } public void dragOver(DropTargetDragEvent e) { ; } public void dropActionChanged(DropTargetDragEvent e) { ; } private JMenuItem mDeleteMenuItem = null; private JMenuItem mRenameMenuItem = null; private JMenuItem mCutMenuItem = null; private JMenuItem mCopyMenuItem = null; private JMenuItem mPasteMenuItem = null; private boolean mContextEditable = false; }
Copied comments in from ConfigContextEditor.removeAction(). git-svn-id: 769d22dfa2d22aad706b9a451492fb87c0735f19@16794 08b38cba-cd3b-11de-854e-f91c5b6e4272
modules/jackal/editors/org/vrjuggler/jccl/editors/ElementTree.java
Copied comments in from ConfigContextEditor.removeAction().
<ide><path>odules/jackal/editors/org/vrjuggler/jccl/editors/ElementTree.java <ide> <ide> DefaultMutableTreeNode cur_node; <ide> <add> // The last node in the path is the config element that the <add> // user wants to remove. We do not have to test the type <add> // before the cast because the user interface only allows <add> // removal of ConfigElement objects. <ide> cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 1]; <ide> ConfigElement elt_to_remove = <ide> (ConfigElement) cur_node.getUserObject(); <ide> <del> // We need to see if the parent of the selected config <add> // Now, we need to see if the parent of the selected config <ide> // element is a PropertyDefinition object. <ide> cur_node = (DefaultMutableTreeNode) nodes[nodes.length - 2]; <ide> Object obj = cur_node.getUserObject();
Java
apache-2.0
6721e5363066371adbf17f133850efd06c996804
0
JBYoshi/BlockDodge
package jbyoshi.blockdodge.core; import java.awt.*; import java.awt.event.*; public final class PlayerDodgeShape extends DodgeShape implements KeyListener { private static final Color COLOR = Color.WHITE; private static final int SIZE = 32; private boolean up, down, left, right; public PlayerDodgeShape(BlockDodge game) { super(game, 0, 0, SIZE, SIZE, COLOR); } @Override public void move() { double move = left != right && up != down ? 0.5 : 1; if (left && getX() >= move) { setX(getX() - move); } if (right && getX() < game.getWidth() - getWidth() - move) { setX(getX() + move); } if (up && getY() >= move) { setY(getY() - move); } if (down && getY() < game.getHeight() - getHeight() - move) { setY(getY() + move); } } void reset() { setX(game.getWidth() / 2 - getWidth() / 2); setY(game.getHeight() / 2 - getHeight() / 2); } @Override void onRemoved() { game.stop(); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: up = true; break; case KeyEvent.VK_DOWN: down = true; break; case KeyEvent.VK_LEFT: left = true; break; case KeyEvent.VK_RIGHT: right = true; break; } } @Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: up = false; break; case KeyEvent.VK_DOWN: down = false; break; case KeyEvent.VK_LEFT: left = false; break; case KeyEvent.VK_RIGHT: right = false; break; } } }
src/main/java/jbyoshi/blockdodge/core/PlayerDodgeShape.java
package jbyoshi.blockdodge.core; import java.awt.*; import java.awt.event.*; public final class PlayerDodgeShape extends DodgeShape implements KeyListener { private static final Color COLOR = Color.WHITE; private static final int SIZE = 32; private boolean up, down, left, right; public PlayerDodgeShape(BlockDodge game) { super(game, 0, 0, SIZE, SIZE, COLOR); } @Override public void move() { if (left && getX() > 0) { setX(getX() - 1); } if (right && getX() < game.getWidth() - getWidth() - 1) { setX(getX() + 1); } if (up && getY() > 0) { setY(getY() - 1); } if (down && getY() < game.getHeight() - getHeight() - 1) { setY(getY() + 1); } } void reset() { setX(game.getWidth() / 2 - getWidth() / 2); setY(game.getHeight() / 2 - getHeight() / 2); } @Override void onRemoved() { game.stop(); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: up = true; break; case KeyEvent.VK_DOWN: down = true; break; case KeyEvent.VK_LEFT: left = true; break; case KeyEvent.VK_RIGHT: right = true; break; } } @Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: up = false; break; case KeyEvent.VK_DOWN: down = false; break; case KeyEvent.VK_LEFT: left = false; break; case KeyEvent.VK_RIGHT: right = false; break; } } }
Slow the per-axis motion down if they're moving on both axes.
src/main/java/jbyoshi/blockdodge/core/PlayerDodgeShape.java
Slow the per-axis motion down if they're moving on both axes.
<ide><path>rc/main/java/jbyoshi/blockdodge/core/PlayerDodgeShape.java <ide> <ide> @Override <ide> public void move() { <del> if (left && getX() > 0) { <del> setX(getX() - 1); <add> double move = left != right && up != down ? 0.5 : 1; <add> if (left && getX() >= move) { <add> setX(getX() - move); <ide> } <del> if (right && getX() < game.getWidth() - getWidth() - 1) { <del> setX(getX() + 1); <add> if (right && getX() < game.getWidth() - getWidth() - move) { <add> setX(getX() + move); <ide> } <del> if (up && getY() > 0) { <del> setY(getY() - 1); <add> if (up && getY() >= move) { <add> setY(getY() - move); <ide> } <del> if (down && getY() < game.getHeight() - getHeight() - 1) { <del> setY(getY() + 1); <add> if (down && getY() < game.getHeight() - getHeight() - move) { <add> setY(getY() + move); <ide> } <ide> } <ide>
JavaScript
mpl-2.0
2dfc173e1c3326b79540731bccf227aff90a7a56
0
djmitche/taskcluster-hooks
var base = require('taskcluster-base'); var debug = require('debug')('hooks:data'); var assert = require('assert'); var Promise = require('promise'); var taskcluster = require('taskcluster-client'); var _ = require('lodash'); /** Entity for tracking hooks and associated state **/ var Hook = base.Entity.configure({ version: 1, partitionKey: base.Entity.keys.StringKey('groupId'), rowKey: base.Entity.keys.StringKey('hookId'), properties: { groupId: base.Entity.types.String, hookId: base.Entity.types.String, metadata: base.Entity.types.JSON, // task template task: base.Entity.types.JSON, // pulse bindings bindings: base.Entity.types.JSON, // timings for the task (in fromNow format, e.g., "1 day") deadline: base.Entity.types.String, expires: base.Entity.types.String, // schedule for this task schedule: base.Entity.types.JSON, // access token used to trigger this task via webhook accessToken: base.Entity.types.SlugId, // the taskId that will be used next time this hook is scheduled; // this allows scheduling to be idempotent nextTaskId: base.Entity.types.SlugId, // next date at which this task is scheduled to run nextScheduledDate: base.Entity.types.Date, } }); /** Return promise for hook definition */ Hook.prototype.definition = function() { return Promise.resolve({ hookId: this.hookId, groupId: this.groupId, metadata: _.cloneDeep(this.metadata), task: _.cloneDeep(this.task), bindings: _.cloneDeep(this.bindings), schedule: _.cloneDeep(this.schedule), deadline: this.deadline, expires: this.expires }); }; Hook.prototype.taskPayload = function() { let payload = _.cloneDeep(this.task); payload.created = new Date().toJSON(); payload.deadline = taskcluster.fromNow(this.deadline).toJSON(); if (this.expires) { payload.expires = taskcluster.fromNow(this.expires).toJSON(); } return Promise.resolve(payload); } // export Hook exports.Hook = Hook;
hooks/data.js
var base = require('taskcluster-base'); var debug = require('debug')('hooks:data'); var assert = require('assert'); var Promise = require('promise'); var taskcluster = require('taskcluster-client'); var _ = require('lodash'); /** Entity for tracking hooks and associated state **/ var Hook = base.Entity.configure({ version: 1, partitionKey: base.Entity.keys.StringKey('groupId'), rowKey: base.Entity.keys.StringKey('hookId'), properties: { groupId: base.Entity.types.String, hookId: base.Entity.types.String, metadata: base.Entity.types.JSON, task: base.Entity.types.JSON, bindings: base.Entity.types.JSON, deadline: base.Entity.types.String, expires: base.Entity.types.String, schedule: base.Entity.types.JSON, accessToken: base.Entity.types.SlugId, nextTaskId: base.Entity.types.SlugId, nextScheduledDate: base.Entity.types.Date, } }); /** Return promise for hook definition */ Hook.prototype.definition = function() { return Promise.resolve({ hookId: this.hookId, groupId: this.groupId, metadata: _.cloneDeep(this.metadata), task: _.cloneDeep(this.task), bindings: _.cloneDeep(this.bindings), schedule: _.cloneDeep(this.schedule), deadline: this.deadline, expires: this.expires }); }; Hook.prototype.taskPayload = function() { let payload = _.cloneDeep(this.task); payload.created = new Date().toJSON(); payload.deadline = taskcluster.fromNow(this.deadline).toJSON(); if (this.expires) { payload.expires = taskcluster.fromNow(this.expires).toJSON(); } return Promise.resolve(payload); } // export Hook exports.Hook = Hook;
comments
hooks/data.js
comments
<ide><path>ooks/data.js <ide> groupId: base.Entity.types.String, <ide> hookId: base.Entity.types.String, <ide> metadata: base.Entity.types.JSON, <add> // task template <ide> task: base.Entity.types.JSON, <add> // pulse bindings <ide> bindings: base.Entity.types.JSON, <add> // timings for the task (in fromNow format, e.g., "1 day") <ide> deadline: base.Entity.types.String, <ide> expires: base.Entity.types.String, <add> // schedule for this task <ide> schedule: base.Entity.types.JSON, <add> // access token used to trigger this task via webhook <ide> accessToken: base.Entity.types.SlugId, <add> // the taskId that will be used next time this hook is scheduled; <add> // this allows scheduling to be idempotent <ide> nextTaskId: base.Entity.types.SlugId, <add> // next date at which this task is scheduled to run <ide> nextScheduledDate: base.Entity.types.Date, <ide> } <ide> });
Java
mit
44756af19c0358ae142f14a6bf474e8b2a13f803
0
wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav,wellenvogel/avnav
package de.wellenvogel.avnav.appapi; import android.content.SharedPreferences; import android.location.Location; import android.net.Uri; import android.view.View; import android.webkit.MimeTypeMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import de.wellenvogel.avnav.charts.ChartHandler; import de.wellenvogel.avnav.main.Constants; import de.wellenvogel.avnav.main.MainActivity; import de.wellenvogel.avnav.main.R; import de.wellenvogel.avnav.settings.AudioEditTextPreference; import de.wellenvogel.avnav.util.AvnLog; import de.wellenvogel.avnav.util.AvnUtil; import de.wellenvogel.avnav.worker.Alarm; import de.wellenvogel.avnav.worker.GpsDataProvider; import de.wellenvogel.avnav.worker.GpsService; import de.wellenvogel.avnav.worker.RouteHandler; /** * Created by andreas on 22.11.15. */ public class RequestHandler { //we have to use a valid http url instead of a file url for loading our page //otherwise we crash the renderer process with ol6 and chrome 86 in debug builds /* E/chromium: [ERROR:render_process_host_impl.cc(5148)] Terminating render process for bad Mojo message: Received bad user message: Non committable URL passed to BlobURLStore::Register E/chromium: [ERROR:bad_message.cc(26)] Terminating renderer for bad IPC message, reason 123 E/DecorView: mWindow.mActivityCurrentConfig is null E/chromium: [ERROR:aw_browser_terminator.cc(123)] Renderer process (9537) crash detected (code -1). E/chromium: [ERROR:aw_browser_terminator.cc(89)] Render process (9537) kill (OOM or update) wasn't handed by all associated webviews, killing application. */ public static final String INTERNAL_URL_PREFIX ="http://assets"; public static final String ROOT_PATH="/viewer"; protected static final String NAVURL="viewer/avnav_navi.php"; private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); MainActivity activity; private SharedPreferences preferences; private MimeTypeMap mime = MimeTypeMap.getSingleton(); private final Object handlerMonitor =new Object(); private Thread chartHandler=null; private boolean chartHandlerRunning=false; private final Object chartHandlerMonitor=new Object(); private ChartHandler gemfHandler; private LayoutHandler layoutHandler; private AddonHandler addonHandler; //file types from the js side public static String TYPE_ROUTE="route"; public static String TYPE_LAYOUT="layout"; public static String TYPE_CHART="chart"; public static String TYPE_TRACK="track"; public static String TYPE_USER="user"; public static String TYPE_IMAGE="images"; public static String TYPE_OVERLAY="overlay"; public static String TYPE_ADDON="addon"; public static class KeyValue<VT>{ String key; public VT value; public KeyValue(String key, VT v){ this.key=key; this.value=v; } } public static class TypeItemMap<VT> extends HashMap<String, KeyValue<VT>>{ public TypeItemMap(KeyValue<VT>...list){ for (KeyValue<VT> i : list){ put(i.key,i); } } } public static TypeItemMap<Integer> typeHeadings=new TypeItemMap<Integer>( new KeyValue<Integer>(TYPE_ROUTE, R.string.uploadRoute), new KeyValue<Integer>(TYPE_CHART,R.string.uploadChart), new KeyValue<Integer>(TYPE_IMAGE,R.string.uploadImage), new KeyValue<Integer>(TYPE_USER,R.string.uploadUser), new KeyValue<Integer>(TYPE_LAYOUT,R.string.uploadLayout), new KeyValue<Integer>(TYPE_OVERLAY,R.string.uploadOverlay), new KeyValue<Integer>(TYPE_TRACK,R.string.uploadTrack) ); //directories below workdir public static TypeItemMap<File> typeDirs=new TypeItemMap<File>( new KeyValue<File>(TYPE_ROUTE,new File("routes")), new KeyValue<File>(TYPE_CHART,new File("charts")), new KeyValue<File>(TYPE_TRACK,new File("tracks")), new KeyValue<File>(TYPE_LAYOUT,new File("layout")), new KeyValue<File>(TYPE_USER,new File(new File("user"),"viewer")), new KeyValue<File>(TYPE_IMAGE,new File(new File("user"),"images")), new KeyValue<File>(TYPE_OVERLAY,new File("overlays")) ); public static class ServerInfo{ public InetSocketAddress address; public boolean listenAny=false; public String lastError=null; } static interface LazyHandlerAccess{ INavRequestHandler getHandler(); } private HashMap<String,LazyHandlerAccess> handlerMap=new HashMap<>(); public static JSONObject getReturn(KeyValue ...data) throws JSONException { JSONObject rt=new JSONObject(); Object error=null; for (KeyValue kv : data){ if ("error".equals(kv.key)) error=kv.value; else rt.put(kv.key,kv.value); } rt.put("status",error == null?"OK":error); return rt; } public static JSONObject getReturn(ArrayList<KeyValue> data) throws JSONException { JSONObject rt=new JSONObject(); Object error=null; for (KeyValue kv : data){ if ("error".equals(kv.key)) error=kv.value; else rt.put(kv.key,kv.value); } rt.put("status",error == null?"OK":error); return rt; } public static JSONObject getErrorReturn(String error,KeyValue ...data) throws JSONException { JSONObject rt=new JSONObject(); rt.put("status",error == null?"OK":error); for (KeyValue kv : data){ if (!"error".equals(kv.key)) rt.put(kv.key,kv.value); } return rt; } public File getWorkDirFromType(String type) throws Exception { KeyValue<File>subDir=typeDirs.get(type); if (subDir == null) throw new Exception("invalid type "+type); return new File(getWorkDir(),subDir.value.getPath()); } public RequestHandler(MainActivity activity){ this.activity=activity; this.gemfHandler =new ChartHandler(activity,this); this.gemfHandler.updateChartList(); this.addonHandler= new AddonHandler(activity,this); startHandler(); layoutHandler=new LayoutHandler(activity,"viewer/layout", new File(getWorkDir(),typeDirs.get(TYPE_LAYOUT).value.getPath())); handlerMap.put(TYPE_LAYOUT, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return layoutHandler; } }); handlerMap.put(TYPE_ROUTE, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return getRouteHandler(); } }); handlerMap.put(TYPE_TRACK, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return getTrackWriter(); } }); handlerMap.put(TYPE_CHART, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return gemfHandler; } }); try{ final DirectoryRequestHandler userHandler=new UserDirectoryRequestHandler(this, addonHandler); handlerMap.put(TYPE_USER, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return userHandler; } }); }catch (Exception e){ AvnLog.e("unable to create user handler",e); } try { final DirectoryRequestHandler imageHandler=new DirectoryRequestHandler(TYPE_IMAGE, getWorkDirFromType(TYPE_IMAGE), "user/images",null); handlerMap.put(TYPE_IMAGE, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return imageHandler; } }); }catch(Exception e){ AvnLog.e("unable to create images handler",e); } try { final DirectoryRequestHandler overlayHandler=new DirectoryRequestHandler(TYPE_OVERLAY, getWorkDirFromType(TYPE_OVERLAY), "user/overlays",null); handlerMap.put(TYPE_OVERLAY, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return overlayHandler; } }); }catch(Exception e){ AvnLog.e("unable to create images handler",e); } handlerMap.put(TYPE_ADDON, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return addonHandler; } }); } private INavRequestHandler getTrackWriter() { GpsService gps=getGpsService(); if (gps == null) return null; return gps.getTrackWriter(); } INavRequestHandler getHandler(String type){ if (type == null) return null; LazyHandlerAccess access=handlerMap.get(type); if (access == null) return null; return access.getHandler(); } void startHandler(){ synchronized (handlerMonitor) { if (chartHandler == null) { chartHandlerRunning=true; chartHandler = new Thread(new Runnable() { @Override public void run() { AvnLog.i("RequestHandler: chartHandler thread is starting"); while (chartHandlerRunning) { gemfHandler.updateChartList(); try { synchronized (chartHandlerMonitor){ chartHandlerMonitor.wait(5000); } } catch (InterruptedException e) { break; } } AvnLog.i("RequestHandler: chartHandler thread is stopping"); } }); chartHandler.setDaemon(true); chartHandler.start(); } } } RouteHandler getRouteHandler(){ GpsService service=getGpsService(); if (service == null) return null; return service.getRouteHandler(); } protected File getWorkDir(){ return AvnUtil.getWorkDir(getSharedPreferences(),activity); } GpsService getGpsService(){ return activity.getGpsService(); } public synchronized SharedPreferences getSharedPreferences(){ if (preferences != null) return preferences; preferences=AvnUtil.getSharedPreferences(activity); return preferences; } public static String mimeType(String fname){ HashMap<String,String> ownMimeMap=new HashMap<String, String>(); ownMimeMap.put("js", "text/javascript"); String ext=fname.replaceAll(".*\\.", ""); String mimeType=MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); if (mimeType == null) { mimeType=ownMimeMap.get(ext); } return mimeType; } /** * used for the internal requests from our WebView * @param view * @param url undecoded url * @return * @throws Exception */ public ExtendedWebResourceResponse handleRequest(View view, String url) throws Exception { Uri uri=null; try { uri = Uri.parse(url); }catch (Exception e){ return null; } String path=uri.getPath(); if (path == null) return null; if (url.startsWith(INTERNAL_URL_PREFIX)){ try { if (path.startsWith("/")) path=path.substring(1); if (path.startsWith(NAVURL)){ return handleNavRequest(uri,null); } ExtendedWebResourceResponse rt=tryDirectRequest(uri); if (rt != null) return rt; InputStream is=activity.getAssets().open(path); return new ExtendedWebResourceResponse(-1,mimeType(path),"",is); } catch (Throwable e) { e.printStackTrace(); throw new Exception("error processing "+url+": "+e.getLocalizedMessage()); } } else { AvnLog.d("AvNav", "external request " + url); return null; } } public ExtendedWebResourceResponse tryDirectRequest(Uri uri) throws Exception { String path=uri.getPath(); if (path == null) return null; if (path.startsWith("/")) path=path.substring(1); INavRequestHandler handler=getPrefixHandler(path); if (handler != null){ return handler.handleDirectRequest(uri,this ); } return null; } public String getStartPage(){ InputStream input; String htmlPage=null; try { input = activity.getAssets().open("viewer/avnav_viewer.html"); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); // byte buffer into a string htmlPage = new String(buffer); } catch (IOException e) { e.printStackTrace(); } return htmlPage; } JSONObject handleUploadRequest(Uri uri,PostVars postData) throws Exception{ String dtype = uri.getQueryParameter("type"); if (dtype == null ) throw new IOException("missing parameter type for upload"); String overwrite=uri.getQueryParameter("overwrite"); String name=uri.getQueryParameter("name"); INavRequestHandler handler=getHandler(dtype); if (handler != null){ boolean success=handler.handleUpload(postData,name,overwrite != null && overwrite.equals("true")); JSONObject rt=new JSONObject(); if (success) { rt.put("status", "OK"); } else{ rt.put("status", "already exists"); } return rt; } return null; } ExtendedWebResourceResponse handleNavRequest(Uri uri, PostVars postData) throws Exception{ return handleNavRequest(uri,postData,null); } ExtendedWebResourceResponse handleNavRequest(Uri uri, PostVars postData,ServerInfo serverInfo) throws Exception { if (uri.getPath() == null) return null; String remain=uri.getPath(); if (remain.startsWith("/")) remain=remain.substring(1); if (remain != null) { remain=remain.substring(Math.min(remain.length(),NAVURL.length()+1)); } String type=uri.getQueryParameter("request"); if (type == null) type="gps"; Object fout=null; InputStream is=null; int len=0; boolean handled=false; try{ if (type.equals("gps")){ handled=true; JSONObject navLocation=null; if (getGpsService() != null) { navLocation=getGpsService().getGpsData(); if (navLocation == null) { navLocation = new JSONObject(); } } fout=navLocation; } if (type.equals("nmeaStatus")){ handled=true; JSONObject o=new JSONObject(); if (getGpsService() != null) { JSONObject status = getGpsService().getNmeaStatus(); o.put("data", status); o.put("status", "OK"); } else{ o.put("status","no gps service"); } fout=o; } if (type.equals("track")){ handled=true; if (getGpsService() != null) { String intervals = uri.getQueryParameter("interval"); String maxnums = uri.getQueryParameter("maxnum"); long interval = 60000; if (intervals != null) { try { interval = 1000*Long.parseLong(intervals); } catch (NumberFormatException i) { } } int maxnum = 60; if (maxnums != null) { try { maxnum = Integer.parseInt(maxnums); } catch (NumberFormatException i) { } } ArrayList<Location> track=getGpsService().getTrack(maxnum, interval); //the returned track is inverse order, i.e. the newest entry comes first JSONArray arr=new JSONArray(); for (int i=track.size()-1;i>=0;i--){ Location l=track.get(i); JSONObject e=new JSONObject(); e.put("ts",l.getTime()/1000.0); e.put("time",dateFormat.format(new Date(l.getTime()))); e.put("lon",l.getLongitude()); e.put("lat",l.getLatitude()); arr.put(e); } fout=arr; } } if (type.equals("ais")) { handled=true; String slat=uri.getQueryParameter("lat"); String slon=uri.getQueryParameter("lon"); String sdistance=uri.getQueryParameter("distance"); double lat=0,lon=0,distance=0; try{ if (slat != null) lat=Double.parseDouble(slat); if (slon != null) lon=Double.parseDouble(slon); if (sdistance != null)distance=Double.parseDouble(sdistance); }catch (Exception e){} if (getGpsService() !=null){ fout=getGpsService().getAisData(lat, lon, distance); } } if (type.equals("route")){ if (getGpsService() != null && getRouteHandler() != null) { JSONObject o=getRouteHandler().handleApiRequest(uri,postData, null); if (o != null){ handled=true; fout=o; } } } if (type.equals("listdir") || type.equals("list")){ String dirtype=uri.getQueryParameter("type"); INavRequestHandler handler=getHandler(dirtype); if (handler != null){ handled=true; fout=getReturn(new KeyValue<JSONArray>("items",handler.handleList(uri, serverInfo))); } } if (type.equals("download")){ boolean setAttachment=true; String dltype=uri.getQueryParameter("type"); String name=uri.getQueryParameter("name"); String noattach=uri.getQueryParameter("noattach"); if (noattach != null && noattach.equals("true")) setAttachment=false; ExtendedWebResourceResponse resp=null; INavRequestHandler handler=getHandler(dltype); if (handler != null){ handled=true; try { resp = handler.handleDownload(name, uri); }catch (Exception e){ AvnLog.e("error in download request "+uri.getPath(),e); } } if (!handled && dltype != null && dltype.equals("alarm") && name != null) { AudioEditTextPreference.AudioInfo info=AudioEditTextPreference.getAudioInfoForAlarmName(name,activity); if (info != null){ AudioEditTextPreference.AudioStream stream=AudioEditTextPreference.getAlarmAudioStream(info,activity); if (stream == null){ AvnLog.e("unable to get audio stream for "+info.uri.toString()); } else { resp = new ExtendedWebResourceResponse((int) stream.len, "audio/mpeg", "", stream.stream); } } else{ AvnLog.e("unable to get audio info for "+name); } } if (resp == null) { byte[] o = ("file " + ((name != null) ? name : "<null>") + " not found").getBytes(); resp = new ExtendedWebResourceResponse(o.length, "application/octet-stream", "", new ByteArrayInputStream(o)); } if (setAttachment) { String value="attachment"; if (remain != null && ! remain.isEmpty()) value+="; filename=\""+remain+"\""; resp.setHeader("Content-Disposition", value); } resp.setHeader("Content-Type",resp.getMimeType()); return resp; } if (type.equals("delete")) { JSONObject o=new JSONObject(); String dtype = uri.getQueryParameter("type"); String name = uri.getQueryParameter("name"); INavRequestHandler handler=getHandler(dtype); if (handler != null){ handled=true; try { boolean deleteOk = handler.handleDelete(name, uri); if (!"chart".equals(dtype)) { INavRequestHandler chartHandler = getHandler("chart"); if (chartHandler != null) { try { ((ChartHandler) chartHandler).deleteFromOverlays(dtype, name); } catch (Exception e){ AvnLog.e("exception when trying to delete from overlays",e); } } } if (deleteOk) { o.put("status", "OK"); } else { o.put("status", "unable to delete"); } }catch (Exception e){ o.put("status","error deleting "+name+": "+e.getLocalizedMessage()); } } fout=o; } if (type.equals("status")){ handled=true; JSONObject o=new JSONObject(); JSONArray items=new JSONArray(); if (getGpsService() != null) { //internal GPS JSONObject gps = new JSONObject(); gps.put("name", "GPS"); gps.put("info", getGpsService().getStatus()); items.put(gps); JSONObject tw=new JSONObject(); tw.put("name","TrackWriter"); tw.put("info",getGpsService().getTrackStatus()); items.put(tw); } if (serverInfo != null){ //we are queried from the WebServer - just return all network interfaces JSONObject http=new JSONObject(); http.put("name","AVNHttpServer"); http.put("configname","AVNHttpServer"); //this is the part the GUI looks for JSONArray status=new JSONArray(); JSONObject serverStatus=new JSONObject(); serverStatus.put("info","listening on "+serverInfo.address.toString()); serverStatus.put("name","HttpServer"); serverStatus.put("status", GpsDataProvider.STATUS_NMEA); status.put(serverStatus); JSONObject info=new JSONObject(); info.put("items",status); http.put("info",info); JSONObject props=new JSONObject(); JSONArray addr=new JSONArray(); if (serverInfo.listenAny) { try { Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces(); while (intfs.hasMoreElements()) { NetworkInterface intf = intfs.nextElement(); Enumeration<InetAddress> ifaddresses = intf.getInetAddresses(); while (ifaddresses.hasMoreElements()) { InetAddress ifaddress = ifaddresses.nextElement(); if (ifaddress.getHostAddress().contains(":")) continue; //skip IPV6 for now String ifurl = ifaddress.getHostAddress() + ":" + serverInfo.address.getPort(); addr.put(ifurl); } } } catch (SocketException e1) { } } else{ addr.put(serverInfo.address.getAddress().getHostAddress()+":"+serverInfo.address.getPort()); } props.put("addresses",addr); http.put("properties",props); items.put(http); } o.put("handler",items); fout=o; } if (type.equals("alarm")){ handled=true; JSONObject o=null; String status=uri.getQueryParameter("status"); if (status != null && ! status.isEmpty()){ JSONObject rt=new JSONObject(); if (getGpsService() != null) { if (status.matches(".*all.*")) { rt = getGpsService().getAlarStatusJson(); } else { Map<String, Alarm> alarmStatus = getGpsService().getAlarmStatus(); String[] queryAlarms = status.split(","); for (String alarm : queryAlarms) { Alarm ao = alarmStatus.get(alarm); if (ao != null) { rt.put(alarm, ao.toJson()); } } } } o=new JSONObject(); o.put("status","OK"); o.put("data",rt); } String stop=uri.getQueryParameter("stop"); if (stop != null && ! stop.isEmpty()){ getGpsService().resetAlarm(stop); o=new JSONObject(); o.put("status","OK"); } if (o == null){ o=new JSONObject(); o.put("status","error"); o.put("info","unknown alarm command"); } fout=o; } if (type.equals("upload")){ fout=handleUploadRequest(uri,postData); if (fout != null) handled=true; } if (type.equals("capabilities")){ //see keys.jsx in viewer - gui.capabilities handled=true; JSONObject o=new JSONObject(); o.put("addons",true); o.put("uploadCharts",true); o.put("plugins",false); o.put("uploadRoute",true); o.put("uploadLayout",true); o.put("canConnect",true); o.put("uploadUser",true); o.put("uploadImages",true); o.put("uploadOverlays",true); o.put("uploadTracks",true); fout=getReturn(new KeyValue<JSONObject>("data",o)); } if (type.equals("api")){ try { String apiType = AvnUtil.getMandatoryParameter(uri, "type"); RequestHandler.LazyHandlerAccess handler = handlerMap.get(apiType); if (handler == null || handler.getHandler() == null ) throw new Exception("no handler for api request "+apiType); JSONObject resp=handler.getHandler().handleApiRequest(uri,postData, serverInfo); if (resp == null){ fout=getErrorReturn("api request returned null"); } else{ fout=resp; } }catch (Throwable t){ fout=getErrorReturn("exception: "+t.getLocalizedMessage()); } } if (!handled){ AvnLog.d(Constants.LOGPRFX,"unhandled nav request "+type); } String outstring=""; if (fout != null) outstring=fout.toString(); byte o[]=outstring.getBytes("UTF-8"); len=o.length; is = new ByteArrayInputStream(o); } catch (JSONException jse) { jse.printStackTrace(); is=new ByteArrayInputStream(new byte[]{}); len=0; } return new ExtendedWebResourceResponse(len,"application/json","UTF-8",is); } public INavRequestHandler getPrefixHandler(String url){ if (url == null) return null; for (LazyHandlerAccess handler : handlerMap.values()){ if (handler.getHandler() == null || handler.getHandler().getPrefix() == null) continue; if (url.startsWith(handler.getHandler().getPrefix())) return handler.getHandler(); } return null; } public Collection<INavRequestHandler> getHandlers(){ ArrayList<INavRequestHandler> rt=new ArrayList<INavRequestHandler>(); for (LazyHandlerAccess handler : handlerMap.values()){ if (handler.getHandler() == null ) continue; rt.add(handler.getHandler()); } return rt; } public void stop(){ synchronized (handlerMonitor) { if (chartHandler != null){ chartHandlerRunning=false; synchronized (chartHandlerMonitor){ chartHandlerMonitor.notifyAll(); } chartHandler.interrupt(); try { chartHandler.join(1000); } catch (InterruptedException e) { } chartHandler=null; } } } }
android/src/main/java/de/wellenvogel/avnav/appapi/RequestHandler.java
package de.wellenvogel.avnav.appapi; import android.content.SharedPreferences; import android.location.Location; import android.net.Uri; import android.view.View; import android.webkit.MimeTypeMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import de.wellenvogel.avnav.charts.ChartHandler; import de.wellenvogel.avnav.main.Constants; import de.wellenvogel.avnav.main.MainActivity; import de.wellenvogel.avnav.main.R; import de.wellenvogel.avnav.settings.AudioEditTextPreference; import de.wellenvogel.avnav.util.AvnLog; import de.wellenvogel.avnav.util.AvnUtil; import de.wellenvogel.avnav.worker.Alarm; import de.wellenvogel.avnav.worker.GpsDataProvider; import de.wellenvogel.avnav.worker.GpsService; import de.wellenvogel.avnav.worker.RouteHandler; /** * Created by andreas on 22.11.15. */ public class RequestHandler { //we have to use a valid http url instead of a file url for loading our page //otherwise we crash the renderer process with ol6 and chrome 86 in debug builds /* E/chromium: [ERROR:render_process_host_impl.cc(5148)] Terminating render process for bad Mojo message: Received bad user message: Non committable URL passed to BlobURLStore::Register E/chromium: [ERROR:bad_message.cc(26)] Terminating renderer for bad IPC message, reason 123 E/DecorView: mWindow.mActivityCurrentConfig is null E/chromium: [ERROR:aw_browser_terminator.cc(123)] Renderer process (9537) crash detected (code -1). E/chromium: [ERROR:aw_browser_terminator.cc(89)] Render process (9537) kill (OOM or update) wasn't handed by all associated webviews, killing application. */ public static final String INTERNAL_URL_PREFIX ="http://assets"; public static final String ROOT_PATH="/viewer"; protected static final String NAVURL="viewer/avnav_navi.php"; private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); MainActivity activity; private SharedPreferences preferences; private MimeTypeMap mime = MimeTypeMap.getSingleton(); private final Object handlerMonitor =new Object(); private Thread chartHandler=null; private boolean chartHandlerRunning=false; private final Object chartHandlerMonitor=new Object(); private ChartHandler gemfHandler; private LayoutHandler layoutHandler; private AddonHandler addonHandler; //file types from the js side public static String TYPE_ROUTE="route"; public static String TYPE_LAYOUT="layout"; public static String TYPE_CHART="chart"; public static String TYPE_TRACK="track"; public static String TYPE_USER="user"; public static String TYPE_IMAGE="images"; public static String TYPE_OVERLAY="overlay"; public static String TYPE_ADDON="addon"; public static class KeyValue<VT>{ String key; public VT value; public KeyValue(String key, VT v){ this.key=key; this.value=v; } } public static class TypeItemMap<VT> extends HashMap<String, KeyValue<VT>>{ public TypeItemMap(KeyValue<VT>...list){ for (KeyValue<VT> i : list){ put(i.key,i); } } } public static TypeItemMap<Integer> typeHeadings=new TypeItemMap<Integer>( new KeyValue<Integer>(TYPE_ROUTE, R.string.uploadRoute), new KeyValue<Integer>(TYPE_CHART,R.string.uploadChart), new KeyValue<Integer>(TYPE_IMAGE,R.string.uploadImage), new KeyValue<Integer>(TYPE_USER,R.string.uploadUser), new KeyValue<Integer>(TYPE_LAYOUT,R.string.uploadLayout), new KeyValue<Integer>(TYPE_OVERLAY,R.string.uploadOverlay), new KeyValue<Integer>(TYPE_TRACK,R.string.uploadTrack) ); //directories below workdir public static TypeItemMap<File> typeDirs=new TypeItemMap<File>( new KeyValue<File>(TYPE_ROUTE,new File("routes")), new KeyValue<File>(TYPE_CHART,new File("charts")), new KeyValue<File>(TYPE_TRACK,new File("tracks")), new KeyValue<File>(TYPE_LAYOUT,new File("layout")), new KeyValue<File>(TYPE_USER,new File(new File("user"),"viewer")), new KeyValue<File>(TYPE_IMAGE,new File(new File("user"),"images")), new KeyValue<File>(TYPE_OVERLAY,new File(new File("user"),"overlays")) ); public static class ServerInfo{ public InetSocketAddress address; public boolean listenAny=false; public String lastError=null; } static interface LazyHandlerAccess{ INavRequestHandler getHandler(); } private HashMap<String,LazyHandlerAccess> handlerMap=new HashMap<>(); public static JSONObject getReturn(KeyValue ...data) throws JSONException { JSONObject rt=new JSONObject(); Object error=null; for (KeyValue kv : data){ if ("error".equals(kv.key)) error=kv.value; else rt.put(kv.key,kv.value); } rt.put("status",error == null?"OK":error); return rt; } public static JSONObject getReturn(ArrayList<KeyValue> data) throws JSONException { JSONObject rt=new JSONObject(); Object error=null; for (KeyValue kv : data){ if ("error".equals(kv.key)) error=kv.value; else rt.put(kv.key,kv.value); } rt.put("status",error == null?"OK":error); return rt; } public static JSONObject getErrorReturn(String error,KeyValue ...data) throws JSONException { JSONObject rt=new JSONObject(); rt.put("status",error == null?"OK":error); for (KeyValue kv : data){ if (!"error".equals(kv.key)) rt.put(kv.key,kv.value); } return rt; } public File getWorkDirFromType(String type) throws Exception { KeyValue<File>subDir=typeDirs.get(type); if (subDir == null) throw new Exception("invalid type "+type); return new File(getWorkDir(),subDir.value.getPath()); } public RequestHandler(MainActivity activity){ this.activity=activity; this.gemfHandler =new ChartHandler(activity,this); this.gemfHandler.updateChartList(); this.addonHandler= new AddonHandler(activity,this); startHandler(); layoutHandler=new LayoutHandler(activity,"viewer/layout", new File(getWorkDir(),typeDirs.get(TYPE_LAYOUT).value.getPath())); handlerMap.put(TYPE_LAYOUT, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return layoutHandler; } }); handlerMap.put(TYPE_ROUTE, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return getRouteHandler(); } }); handlerMap.put(TYPE_TRACK, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return getTrackWriter(); } }); handlerMap.put(TYPE_CHART, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return gemfHandler; } }); try{ final DirectoryRequestHandler userHandler=new UserDirectoryRequestHandler(this, addonHandler); handlerMap.put(TYPE_USER, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return userHandler; } }); }catch (Exception e){ AvnLog.e("unable to create user handler",e); } try { final DirectoryRequestHandler imageHandler=new DirectoryRequestHandler(TYPE_IMAGE, getWorkDirFromType(TYPE_IMAGE), "user/images",null); handlerMap.put(TYPE_IMAGE, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return imageHandler; } }); }catch(Exception e){ AvnLog.e("unable to create images handler",e); } try { final DirectoryRequestHandler overlayHandler=new DirectoryRequestHandler(TYPE_OVERLAY, getWorkDirFromType(TYPE_OVERLAY), "user/overlays",null); handlerMap.put(TYPE_OVERLAY, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return overlayHandler; } }); }catch(Exception e){ AvnLog.e("unable to create images handler",e); } handlerMap.put(TYPE_ADDON, new LazyHandlerAccess() { @Override public INavRequestHandler getHandler() { return addonHandler; } }); } private INavRequestHandler getTrackWriter() { GpsService gps=getGpsService(); if (gps == null) return null; return gps.getTrackWriter(); } INavRequestHandler getHandler(String type){ if (type == null) return null; LazyHandlerAccess access=handlerMap.get(type); if (access == null) return null; return access.getHandler(); } void startHandler(){ synchronized (handlerMonitor) { if (chartHandler == null) { chartHandlerRunning=true; chartHandler = new Thread(new Runnable() { @Override public void run() { AvnLog.i("RequestHandler: chartHandler thread is starting"); while (chartHandlerRunning) { gemfHandler.updateChartList(); try { synchronized (chartHandlerMonitor){ chartHandlerMonitor.wait(5000); } } catch (InterruptedException e) { break; } } AvnLog.i("RequestHandler: chartHandler thread is stopping"); } }); chartHandler.setDaemon(true); chartHandler.start(); } } } RouteHandler getRouteHandler(){ GpsService service=getGpsService(); if (service == null) return null; return service.getRouteHandler(); } protected File getWorkDir(){ return AvnUtil.getWorkDir(getSharedPreferences(),activity); } GpsService getGpsService(){ return activity.getGpsService(); } public synchronized SharedPreferences getSharedPreferences(){ if (preferences != null) return preferences; preferences=AvnUtil.getSharedPreferences(activity); return preferences; } public static String mimeType(String fname){ HashMap<String,String> ownMimeMap=new HashMap<String, String>(); ownMimeMap.put("js", "text/javascript"); String ext=fname.replaceAll(".*\\.", ""); String mimeType=MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); if (mimeType == null) { mimeType=ownMimeMap.get(ext); } return mimeType; } /** * used for the internal requests from our WebView * @param view * @param url undecoded url * @return * @throws Exception */ public ExtendedWebResourceResponse handleRequest(View view, String url) throws Exception { Uri uri=null; try { uri = Uri.parse(url); }catch (Exception e){ return null; } String path=uri.getPath(); if (path == null) return null; if (url.startsWith(INTERNAL_URL_PREFIX)){ try { if (path.startsWith("/")) path=path.substring(1); if (path.startsWith(NAVURL)){ return handleNavRequest(uri,null); } ExtendedWebResourceResponse rt=tryDirectRequest(uri); if (rt != null) return rt; InputStream is=activity.getAssets().open(path); return new ExtendedWebResourceResponse(-1,mimeType(path),"",is); } catch (Throwable e) { e.printStackTrace(); throw new Exception("error processing "+url+": "+e.getLocalizedMessage()); } } else { AvnLog.d("AvNav", "external request " + url); return null; } } public ExtendedWebResourceResponse tryDirectRequest(Uri uri) throws Exception { String path=uri.getPath(); if (path == null) return null; if (path.startsWith("/")) path=path.substring(1); INavRequestHandler handler=getPrefixHandler(path); if (handler != null){ return handler.handleDirectRequest(uri,this ); } return null; } public String getStartPage(){ InputStream input; String htmlPage=null; try { input = activity.getAssets().open("viewer/avnav_viewer.html"); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); // byte buffer into a string htmlPage = new String(buffer); } catch (IOException e) { e.printStackTrace(); } return htmlPage; } JSONObject handleUploadRequest(Uri uri,PostVars postData) throws Exception{ String dtype = uri.getQueryParameter("type"); if (dtype == null ) throw new IOException("missing parameter type for upload"); String overwrite=uri.getQueryParameter("overwrite"); String name=uri.getQueryParameter("name"); INavRequestHandler handler=getHandler(dtype); if (handler != null){ boolean success=handler.handleUpload(postData,name,overwrite != null && overwrite.equals("true")); JSONObject rt=new JSONObject(); if (success) { rt.put("status", "OK"); } else{ rt.put("status", "already exists"); } return rt; } return null; } ExtendedWebResourceResponse handleNavRequest(Uri uri, PostVars postData) throws Exception{ return handleNavRequest(uri,postData,null); } ExtendedWebResourceResponse handleNavRequest(Uri uri, PostVars postData,ServerInfo serverInfo) throws Exception { if (uri.getPath() == null) return null; String remain=uri.getPath(); if (remain.startsWith("/")) remain=remain.substring(1); if (remain != null) { remain=remain.substring(Math.min(remain.length(),NAVURL.length()+1)); } String type=uri.getQueryParameter("request"); if (type == null) type="gps"; Object fout=null; InputStream is=null; int len=0; boolean handled=false; try{ if (type.equals("gps")){ handled=true; JSONObject navLocation=null; if (getGpsService() != null) { navLocation=getGpsService().getGpsData(); if (navLocation == null) { navLocation = new JSONObject(); } } fout=navLocation; } if (type.equals("nmeaStatus")){ handled=true; JSONObject o=new JSONObject(); if (getGpsService() != null) { JSONObject status = getGpsService().getNmeaStatus(); o.put("data", status); o.put("status", "OK"); } else{ o.put("status","no gps service"); } fout=o; } if (type.equals("track")){ handled=true; if (getGpsService() != null) { String intervals = uri.getQueryParameter("interval"); String maxnums = uri.getQueryParameter("maxnum"); long interval = 60000; if (intervals != null) { try { interval = 1000*Long.parseLong(intervals); } catch (NumberFormatException i) { } } int maxnum = 60; if (maxnums != null) { try { maxnum = Integer.parseInt(maxnums); } catch (NumberFormatException i) { } } ArrayList<Location> track=getGpsService().getTrack(maxnum, interval); //the returned track is inverse order, i.e. the newest entry comes first JSONArray arr=new JSONArray(); for (int i=track.size()-1;i>=0;i--){ Location l=track.get(i); JSONObject e=new JSONObject(); e.put("ts",l.getTime()/1000.0); e.put("time",dateFormat.format(new Date(l.getTime()))); e.put("lon",l.getLongitude()); e.put("lat",l.getLatitude()); arr.put(e); } fout=arr; } } if (type.equals("ais")) { handled=true; String slat=uri.getQueryParameter("lat"); String slon=uri.getQueryParameter("lon"); String sdistance=uri.getQueryParameter("distance"); double lat=0,lon=0,distance=0; try{ if (slat != null) lat=Double.parseDouble(slat); if (slon != null) lon=Double.parseDouble(slon); if (sdistance != null)distance=Double.parseDouble(sdistance); }catch (Exception e){} if (getGpsService() !=null){ fout=getGpsService().getAisData(lat, lon, distance); } } if (type.equals("route")){ if (getGpsService() != null && getRouteHandler() != null) { JSONObject o=getRouteHandler().handleApiRequest(uri,postData, null); if (o != null){ handled=true; fout=o; } } } if (type.equals("listdir") || type.equals("list")){ String dirtype=uri.getQueryParameter("type"); INavRequestHandler handler=getHandler(dirtype); if (handler != null){ handled=true; fout=getReturn(new KeyValue<JSONArray>("items",handler.handleList(uri, serverInfo))); } } if (type.equals("download")){ boolean setAttachment=true; String dltype=uri.getQueryParameter("type"); String name=uri.getQueryParameter("name"); String noattach=uri.getQueryParameter("noattach"); if (noattach != null && noattach.equals("true")) setAttachment=false; ExtendedWebResourceResponse resp=null; INavRequestHandler handler=getHandler(dltype); if (handler != null){ handled=true; try { resp = handler.handleDownload(name, uri); }catch (Exception e){ AvnLog.e("error in download request "+uri.getPath(),e); } } if (!handled && dltype != null && dltype.equals("alarm") && name != null) { AudioEditTextPreference.AudioInfo info=AudioEditTextPreference.getAudioInfoForAlarmName(name,activity); if (info != null){ AudioEditTextPreference.AudioStream stream=AudioEditTextPreference.getAlarmAudioStream(info,activity); if (stream == null){ AvnLog.e("unable to get audio stream for "+info.uri.toString()); } else { resp = new ExtendedWebResourceResponse((int) stream.len, "audio/mpeg", "", stream.stream); } } else{ AvnLog.e("unable to get audio info for "+name); } } if (resp == null) { byte[] o = ("file " + ((name != null) ? name : "<null>") + " not found").getBytes(); resp = new ExtendedWebResourceResponse(o.length, "application/octet-stream", "", new ByteArrayInputStream(o)); } if (setAttachment) { String value="attachment"; if (remain != null && ! remain.isEmpty()) value+="; filename=\""+remain+"\""; resp.setHeader("Content-Disposition", value); } resp.setHeader("Content-Type",resp.getMimeType()); return resp; } if (type.equals("delete")) { JSONObject o=new JSONObject(); String dtype = uri.getQueryParameter("type"); String name = uri.getQueryParameter("name"); INavRequestHandler handler=getHandler(dtype); if (handler != null){ handled=true; try { boolean deleteOk = handler.handleDelete(name, uri); if (!"chart".equals(dtype)) { INavRequestHandler chartHandler = getHandler("chart"); if (chartHandler != null) { try { ((ChartHandler) chartHandler).deleteFromOverlays(dtype, name); } catch (Exception e){ AvnLog.e("exception when trying to delete from overlays",e); } } } if (deleteOk) { o.put("status", "OK"); } else { o.put("status", "unable to delete"); } }catch (Exception e){ o.put("status","error deleting "+name+": "+e.getLocalizedMessage()); } } fout=o; } if (type.equals("status")){ handled=true; JSONObject o=new JSONObject(); JSONArray items=new JSONArray(); if (getGpsService() != null) { //internal GPS JSONObject gps = new JSONObject(); gps.put("name", "GPS"); gps.put("info", getGpsService().getStatus()); items.put(gps); JSONObject tw=new JSONObject(); tw.put("name","TrackWriter"); tw.put("info",getGpsService().getTrackStatus()); items.put(tw); } if (serverInfo != null){ //we are queried from the WebServer - just return all network interfaces JSONObject http=new JSONObject(); http.put("name","AVNHttpServer"); http.put("configname","AVNHttpServer"); //this is the part the GUI looks for JSONArray status=new JSONArray(); JSONObject serverStatus=new JSONObject(); serverStatus.put("info","listening on "+serverInfo.address.toString()); serverStatus.put("name","HttpServer"); serverStatus.put("status", GpsDataProvider.STATUS_NMEA); status.put(serverStatus); JSONObject info=new JSONObject(); info.put("items",status); http.put("info",info); JSONObject props=new JSONObject(); JSONArray addr=new JSONArray(); if (serverInfo.listenAny) { try { Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces(); while (intfs.hasMoreElements()) { NetworkInterface intf = intfs.nextElement(); Enumeration<InetAddress> ifaddresses = intf.getInetAddresses(); while (ifaddresses.hasMoreElements()) { InetAddress ifaddress = ifaddresses.nextElement(); if (ifaddress.getHostAddress().contains(":")) continue; //skip IPV6 for now String ifurl = ifaddress.getHostAddress() + ":" + serverInfo.address.getPort(); addr.put(ifurl); } } } catch (SocketException e1) { } } else{ addr.put(serverInfo.address.getAddress().getHostAddress()+":"+serverInfo.address.getPort()); } props.put("addresses",addr); http.put("properties",props); items.put(http); } o.put("handler",items); fout=o; } if (type.equals("alarm")){ handled=true; JSONObject o=null; String status=uri.getQueryParameter("status"); if (status != null && ! status.isEmpty()){ JSONObject rt=new JSONObject(); if (getGpsService() != null) { if (status.matches(".*all.*")) { rt = getGpsService().getAlarStatusJson(); } else { Map<String, Alarm> alarmStatus = getGpsService().getAlarmStatus(); String[] queryAlarms = status.split(","); for (String alarm : queryAlarms) { Alarm ao = alarmStatus.get(alarm); if (ao != null) { rt.put(alarm, ao.toJson()); } } } } o=new JSONObject(); o.put("status","OK"); o.put("data",rt); } String stop=uri.getQueryParameter("stop"); if (stop != null && ! stop.isEmpty()){ getGpsService().resetAlarm(stop); o=new JSONObject(); o.put("status","OK"); } if (o == null){ o=new JSONObject(); o.put("status","error"); o.put("info","unknown alarm command"); } fout=o; } if (type.equals("upload")){ fout=handleUploadRequest(uri,postData); if (fout != null) handled=true; } if (type.equals("capabilities")){ //see keys.jsx in viewer - gui.capabilities handled=true; JSONObject o=new JSONObject(); o.put("addons",true); o.put("uploadCharts",true); o.put("plugins",false); o.put("uploadRoute",true); o.put("uploadLayout",true); o.put("canConnect",true); o.put("uploadUser",true); o.put("uploadImages",true); o.put("uploadOverlays",true); o.put("uploadTracks",true); fout=getReturn(new KeyValue<JSONObject>("data",o)); } if (type.equals("api")){ try { String apiType = AvnUtil.getMandatoryParameter(uri, "type"); RequestHandler.LazyHandlerAccess handler = handlerMap.get(apiType); if (handler == null || handler.getHandler() == null ) throw new Exception("no handler for api request "+apiType); JSONObject resp=handler.getHandler().handleApiRequest(uri,postData, serverInfo); if (resp == null){ fout=getErrorReturn("api request returned null"); } else{ fout=resp; } }catch (Throwable t){ fout=getErrorReturn("exception: "+t.getLocalizedMessage()); } } if (!handled){ AvnLog.d(Constants.LOGPRFX,"unhandled nav request "+type); } String outstring=""; if (fout != null) outstring=fout.toString(); byte o[]=outstring.getBytes("UTF-8"); len=o.length; is = new ByteArrayInputStream(o); } catch (JSONException jse) { jse.printStackTrace(); is=new ByteArrayInputStream(new byte[]{}); len=0; } return new ExtendedWebResourceResponse(len,"application/json","UTF-8",is); } public INavRequestHandler getPrefixHandler(String url){ if (url == null) return null; for (LazyHandlerAccess handler : handlerMap.values()){ if (handler.getHandler() == null || handler.getHandler().getPrefix() == null) continue; if (url.startsWith(handler.getHandler().getPrefix())) return handler.getHandler(); } return null; } public Collection<INavRequestHandler> getHandlers(){ ArrayList<INavRequestHandler> rt=new ArrayList<INavRequestHandler>(); for (LazyHandlerAccess handler : handlerMap.values()){ if (handler.getHandler() == null ) continue; rt.add(handler.getHandler()); } return rt; } public void stop(){ synchronized (handlerMonitor) { if (chartHandler != null){ chartHandlerRunning=false; synchronized (chartHandlerMonitor){ chartHandlerMonitor.notifyAll(); } chartHandler.interrupt(); try { chartHandler.join(1000); } catch (InterruptedException e) { } chartHandler=null; } } } }
relocate overlay dir on android
android/src/main/java/de/wellenvogel/avnav/appapi/RequestHandler.java
relocate overlay dir on android
<ide><path>ndroid/src/main/java/de/wellenvogel/avnav/appapi/RequestHandler.java <ide> new KeyValue<File>(TYPE_LAYOUT,new File("layout")), <ide> new KeyValue<File>(TYPE_USER,new File(new File("user"),"viewer")), <ide> new KeyValue<File>(TYPE_IMAGE,new File(new File("user"),"images")), <del> new KeyValue<File>(TYPE_OVERLAY,new File(new File("user"),"overlays")) <add> new KeyValue<File>(TYPE_OVERLAY,new File("overlays")) <ide> <ide> ); <ide>
Java
apache-2.0
153ec5b9ee2416c7d52c388dc9163f1fc13f2da3
0
eayun/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine
package org.ovirt.engine.core.common.action; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.validation.Valid; import org.ovirt.engine.core.common.businessentities.network.Bond; import org.ovirt.engine.core.common.businessentities.network.NetworkAttachment; import org.ovirt.engine.core.common.businessentities.network.NicLabel; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.validation.annotation.ConfiguredRange; import org.ovirt.engine.core.compat.Guid; public class HostSetupNetworksParameters extends VdsActionParameters { private static final long serialVersionUID = 6819278948636850828L; /* * This field cannot be validated via bean validation due to validation conflict: {@link NetworkAttachment} in this * class is present as new entity and entity to be updated, both requiring different conflicting validations. So * {@link NetworkAttachment} will be validated manually in {@link org.ovirt.engine.core.bll.CommandBase#canDoAction} */ private List<NetworkAttachment> networkAttachments; private Set<Guid> removedNetworkAttachments; private List<Bond> bonds; private Set<Guid> removedBonds; private Set<String> removedUnmanagedNetworks; @Valid private Set<NicLabel> labels; private Set<String> removedLabels; private boolean rollbackOnFailure = true; @ConfiguredRange(min = 1, maxConfigValue = ConfigValues.NetworkConnectivityCheckTimeoutInSeconds, message = "VALIDATION.CONNECTIVITY.TIMEOUT.INVALID") private Integer conectivityTimeout; HostSetupNetworksParameters() { } public HostSetupNetworksParameters(Guid hostId) { super(hostId); setNetworkAttachments(new ArrayList<NetworkAttachment>()); setRemovedNetworkAttachments(new HashSet<Guid>()); setBonds(new ArrayList<Bond>()); setRemovedBonds(new HashSet<Guid>()); setRemovedUnmanagedNetworks(new HashSet<String>()); setLabels(new HashSet<NicLabel>()); setRemovedLabels(new HashSet<String>()); } public boolean rollbackOnFailure() { return rollbackOnFailure; } public void setRollbackOnFailure(boolean rollbackOnFailure) { this.rollbackOnFailure = rollbackOnFailure; } public Integer getConectivityTimeout() { return conectivityTimeout; } public void setConectivityTimeout(Integer conectivityTimeout) { this.conectivityTimeout = conectivityTimeout; } public List<NetworkAttachment> getNetworkAttachments() { return networkAttachments; } public void setNetworkAttachments(List<NetworkAttachment> networkAttachments) { this.networkAttachments = networkAttachments; } public Set<Guid> getRemovedNetworkAttachments() { return removedNetworkAttachments; } public void setRemovedNetworkAttachments(Set<Guid> removedNetworkAttachments) { this.removedNetworkAttachments = removedNetworkAttachments; } public List<Bond> getBonds() { return bonds; } public void setBonds(List<Bond> bonds) { this.bonds = bonds; } public Set<Guid> getRemovedBonds() { return removedBonds; } public void setRemovedBonds(Set<Guid> removedBonds) { this.removedBonds = removedBonds; } public Set<String> getRemovedUnmanagedNetworks() { return removedUnmanagedNetworks; } public void setRemovedUnmanagedNetworks(Set<String> removedUnmanagedNetworks) { this.removedUnmanagedNetworks = removedUnmanagedNetworks; } public void setLabels(Set<NicLabel> labels) { this.labels = labels; } public Set<NicLabel> getLabels() { return labels; } public void setRemovedLabels(Set<String> removedLabels) { this.removedLabels = removedLabels; } public Set<String> getRemovedLabels() { return removedLabels; } }
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/action/HostSetupNetworksParameters.java
package org.ovirt.engine.core.common.action; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.ovirt.engine.core.common.businessentities.network.Bond; import org.ovirt.engine.core.common.businessentities.network.NetworkAttachment; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.validation.annotation.ConfiguredRange; import org.ovirt.engine.core.compat.Guid; public class HostSetupNetworksParameters extends VdsActionParameters { private static final long serialVersionUID = 6819278948636850828L; /*This field cannot be validated via bean validation due to validation conflict: {@link NetworkAttachment} in this class is present as new entity and entity to be updated, both requiring different conflicting validations. So {@link NetworkAttachment} will be validated manually in {@link org.ovirt.engine.core.bll.CommandBase#canDoAction}*/ private List<NetworkAttachment> networkAttachments; private Set<Guid> removedNetworkAttachments; private List<Bond> bonds; private Set<Guid> removedBonds; private Set<String> removedUnmanagedNetworks; private boolean rollbackOnFailure = true; @ConfiguredRange(min = 1, maxConfigValue = ConfigValues.NetworkConnectivityCheckTimeoutInSeconds, message = "VALIDATION.CONNECTIVITY.TIMEOUT.INVALID") private Integer conectivityTimeout; HostSetupNetworksParameters() { } public HostSetupNetworksParameters(Guid hostId) { super(hostId); setNetworkAttachments(new ArrayList<NetworkAttachment>()); setRemovedNetworkAttachments(new HashSet<Guid>()); setBonds(new ArrayList<Bond>()); setRemovedBonds(new HashSet<Guid>()); setRemovedUnmanagedNetworks(new HashSet<String>()); } public boolean rollbackOnFailure() { return rollbackOnFailure; } public void setRollbackOnFailure(boolean rollbackOnFailure) { this.rollbackOnFailure = rollbackOnFailure; } public Integer getConectivityTimeout() { return conectivityTimeout; } public void setConectivityTimeout(Integer conectivityTimeout) { this.conectivityTimeout = conectivityTimeout; } public List<NetworkAttachment> getNetworkAttachments() { return networkAttachments; } public void setNetworkAttachments(List<NetworkAttachment> networkAttachments) { this.networkAttachments = networkAttachments; } public Set<Guid> getRemovedNetworkAttachments() { return removedNetworkAttachments; } public void setRemovedNetworkAttachments(Set<Guid> removedNetworkAttachments) { this.removedNetworkAttachments = removedNetworkAttachments; } public List<Bond> getBonds() { return bonds; } public void setBonds(List<Bond> bonds) { this.bonds = bonds; } public Set<Guid> getRemovedBonds() { return removedBonds; } public void setRemovedBonds(Set<Guid> removedBonds) { this.removedBonds = removedBonds; } public Set<String> getRemovedUnmanagedNetworks() { return removedUnmanagedNetworks; } public void setRemovedUnmanagedNetworks(Set<String> removedUnmanagedNetworks) { this.removedUnmanagedNetworks = removedUnmanagedNetworks; } }
engine: Adding labels and removdLabels to HostSetupNetworksParameters Change-Id: I6477ad6cab342b2fd0ed40de53509bd31f789356 Signed-off-by: Alona Kaplan <[email protected]>
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/action/HostSetupNetworksParameters.java
engine: Adding labels and removdLabels to HostSetupNetworksParameters
<ide><path>ackend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/action/HostSetupNetworksParameters.java <ide> import java.util.List; <ide> import java.util.Set; <ide> <add>import javax.validation.Valid; <add> <ide> import org.ovirt.engine.core.common.businessentities.network.Bond; <ide> import org.ovirt.engine.core.common.businessentities.network.NetworkAttachment; <add>import org.ovirt.engine.core.common.businessentities.network.NicLabel; <ide> import org.ovirt.engine.core.common.config.ConfigValues; <ide> import org.ovirt.engine.core.common.validation.annotation.ConfiguredRange; <ide> import org.ovirt.engine.core.compat.Guid; <del> <ide> <ide> public class HostSetupNetworksParameters extends VdsActionParameters { <ide> <ide> private static final long serialVersionUID = 6819278948636850828L; <ide> <del> /*This field cannot be validated via bean validation due to validation conflict: <del> {@link NetworkAttachment} in this class is present as new entity and entity to be updated, both requiring different <del> conflicting validations. So {@link NetworkAttachment} will be validated manually in <del> {@link org.ovirt.engine.core.bll.CommandBase#canDoAction}*/ <add> /* <add> * This field cannot be validated via bean validation due to validation conflict: {@link NetworkAttachment} in this <add> * class is present as new entity and entity to be updated, both requiring different conflicting validations. So <add> * {@link NetworkAttachment} will be validated manually in {@link org.ovirt.engine.core.bll.CommandBase#canDoAction} <add> */ <ide> private List<NetworkAttachment> networkAttachments; <ide> <ide> private Set<Guid> removedNetworkAttachments; <ide> private Set<Guid> removedBonds; <ide> <ide> private Set<String> removedUnmanagedNetworks; <add> <add> @Valid <add> private Set<NicLabel> labels; <add> <add> private Set<String> removedLabels; <ide> <ide> private boolean rollbackOnFailure = true; <ide> <ide> setBonds(new ArrayList<Bond>()); <ide> setRemovedBonds(new HashSet<Guid>()); <ide> setRemovedUnmanagedNetworks(new HashSet<String>()); <add> setLabels(new HashSet<NicLabel>()); <add> setRemovedLabels(new HashSet<String>()); <ide> } <ide> <ide> public boolean rollbackOnFailure() { <ide> public void setRemovedUnmanagedNetworks(Set<String> removedUnmanagedNetworks) { <ide> this.removedUnmanagedNetworks = removedUnmanagedNetworks; <ide> } <add> <add> public void setLabels(Set<NicLabel> labels) { <add> this.labels = labels; <add> } <add> <add> public Set<NicLabel> getLabels() { <add> return labels; <add> } <add> <add> public void setRemovedLabels(Set<String> removedLabels) { <add> this.removedLabels = removedLabels; <add> } <add> <add> public Set<String> getRemovedLabels() { <add> return removedLabels; <add> } <ide> } <del>
Java
apache-2.0
36726b1fc9292a610a9ac83dcc14d194714db5fc
0
Wick3r/WikiN-G-ER
package data.control; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Properties; import javax.xml.parsers.*; import org.xml.sax.*; import org.w3c.dom.*; import java.io.*; import edu.stanford.nlp.ie.AbstractSequenceClassifier; import edu.stanford.nlp.ie.crf.CRFClassifier; public class StanfordNER { // _________________________________Variables______________________________________ private AbstractSequenceClassifier<?> classifier; private String serializedClassifier; //private EntityFilter filter; // _________________________________Constructors___________________________________ /** * Constructor which handles an commited Classifier Filename * @param clfFilename */ public StanfordNER(String clfFilename) { serializedClassifier = clfFilename; classifier = CRFClassifier.getClassifierNoExceptions(serializedClassifier); } // _______________________________Methods_________________________________________ /** * OFFLINE-PART: extracts the Entities from the Output of the Crawler-Component * @param crawlerOutput */ /** public City extractEntities(CrawlerOutput crawlerOutput) { StringBuffer buffer = new StringBuffer(); buffer.append(crawlerOutput.getContent()); ArrayList<Entity> entities = extractEntities(buffer); City cityWithEntities = new City(entities, crawlerOutput.getName(), crawlerOutput.getLongitude(), crawlerOutput.getLatitude()); return cityWithEntities; }*/ /** * ONLINE-PART: extracts all Entities using the Stanford NER and sends them to CWS Component * @param textDoc * @return ArrayList<Entity> * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public ArrayList<String> extractEntities(StringBuffer textDoc) throws IOException, ParserConfigurationException, SAXException{ ArrayList<String> entities = new ArrayList<String>(); String text = textDoc.toString(); String resultInXml = classifier.classifyToString(text, "xml", false); StringBuffer buffer = new StringBuffer("<root>"); buffer.append(resultInXml); buffer.append("</root>"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(buffer.toString())); Document doc = db.parse(is); NodeList nodes = doc.getElementsByTagName("wi"); for (int i = 0; i < nodes.getLength(); i++){ Element element = (Element) nodes.item(i); if(!element.getAttribute("entity").equals("O")){ entities.add(element.getAttribute("entity") + ";" + element.getTextContent()); } } /* entities = new ArrayList<String>(); String category, name, oldName, oldCategory; int categoryEnd; // System.out.println(resultInXml); //kann man mit ausgeben, TESTZWECK! String[] temp = resultInXml.split("</wi>"); String[] temp2 = temp[0].split("="); categoryEnd = temp2[2].indexOf(">"); oldCategory = temp2[2].substring(1, categoryEnd - 1); oldName = temp2[2].substring(categoryEnd + 1, temp2[2].length()); for (int i = 1; i < temp.length - 1; i++){ temp2 = temp[i].split("="); categoryEnd = temp2[2].indexOf(">"); category = temp2[2].substring(1, categoryEnd - 1); name = temp2[2].substring(categoryEnd + 1, temp2[2].length()); if ( category.equals(oldCategory) && !category.equals("O")){ oldName += " " + name; } else if(!category.equals("O")){ oldName += " " + name; } else if(!oldCategory.equals("O")){ Entity e = new Entity(oldName.trim(), oldCategory.trim()); entities.add(e); oldName = ""; } oldCategory = category; }*/ return entities; } /** * returns the actual serialized Classifier * @return serializedClassifier */ public String getSerializedClassifier() { return serializedClassifier; } /** * sets the current serializedClassifier * @param serializedClassifier */ public void setSerializedClassifier(String serializedClassifier) { this.serializedClassifier = serializedClassifier; } /** * returns the current CRFClassifier * @return CRFClassifier<?> */ public CRFClassifier<?> getClassifier(){ return (CRFClassifier<?>) classifier; } }
Wikinger/src/data/control/StanfordNER.java
package data.control; import java.io.IOException; import java.util.ArrayList; import javax.swing.text.Document; import javax.xml.bind.JAXBException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.xpath.XPathExpressionException; import edu.stanford.nlp.ie.AbstractSequenceClassifier; import edu.stanford.nlp.ie.crf.CRFClassifier; public class StanfordNER { // _________________________________Variables______________________________________ private AbstractSequenceClassifier<?> classifier; private String serializedClassifier; //private EntityFilter filter; // _________________________________Constructors___________________________________ /** * Constructor which handles an commited Classifier Filename * @param clfFilename */ public StanfordNER(String clfFilename) { serializedClassifier = clfFilename; classifier = CRFClassifier.getClassifierNoExceptions(serializedClassifier); } // _______________________________Methods_________________________________________ /** * OFFLINE-PART: extracts the Entities from the Output of the Crawler-Component * @param crawlerOutput */ /** public City extractEntities(CrawlerOutput crawlerOutput) { StringBuffer buffer = new StringBuffer(); buffer.append(crawlerOutput.getContent()); ArrayList<Entity> entities = extractEntities(buffer); City cityWithEntities = new City(entities, crawlerOutput.getName(), crawlerOutput.getLongitude(), crawlerOutput.getLatitude()); return cityWithEntities; }*/ /** * ONLINE-PART: extracts all Entities using the Stanford NER and sends them to CWS Component * @param textDoc * @return ArrayList<Entity> * @throws JAXBException * @throws ParserConfigurationException * @throws IOException * @throws SAXException * @throws XPathExpressionException */ public String extractEntities(StringBuffer textDoc) throws JAXBException{ ArrayList<String> entities; String text = textDoc.toString(); String resultInXml = classifier.classifyToString(text, "xml", false); StringBuffer buffer = new StringBuffer("<root>"); buffer.append(resultInXml); buffer.append("</root>"); System.out.println(buffer); /* entities = new ArrayList<String>(); String category, name, oldName, oldCategory; int categoryEnd; // System.out.println(resultInXml); //kann man mit ausgeben, TESTZWECK! String[] temp = resultInXml.split("</wi>"); String[] temp2 = temp[0].split("="); categoryEnd = temp2[2].indexOf(">"); oldCategory = temp2[2].substring(1, categoryEnd - 1); oldName = temp2[2].substring(categoryEnd + 1, temp2[2].length()); for (int i = 1; i < temp.length - 1; i++){ temp2 = temp[i].split("="); categoryEnd = temp2[2].indexOf(">"); category = temp2[2].substring(1, categoryEnd - 1); name = temp2[2].substring(categoryEnd + 1, temp2[2].length()); if ( category.equals(oldCategory) && !category.equals("O")){ oldName += " " + name; } else if(!category.equals("O")){ oldName += " " + name; } else if(!oldCategory.equals("O")){ Entity e = new Entity(oldName.trim(), oldCategory.trim()); entities.add(e); oldName = ""; } oldCategory = category; }*/ return resultInXml; } /** * returns the actual serialized Classifier * @return serializedClassifier */ public String getSerializedClassifier() { return serializedClassifier; } /** * sets the current serializedClassifier * @param serializedClassifier */ public void setSerializedClassifier(String serializedClassifier) { this.serializedClassifier = serializedClassifier; } /** * returns the current CRFClassifier * @return CRFClassifier<?> */ public CRFClassifier<?> getClassifier(){ return (CRFClassifier<?>) classifier; } }
Xml Parsen geht
Wikinger/src/data/control/StanfordNER.java
Xml Parsen geht
<ide><path>ikinger/src/data/control/StanfordNER.java <ide> package data.control; <ide> <ide> import java.io.IOException; <add>import java.io.StringReader; <ide> import java.util.ArrayList; <add>import java.util.Properties; <ide> <del>import javax.swing.text.Document; <del>import javax.xml.bind.JAXBException; <del>import javax.xml.parsers.DocumentBuilderFactory; <del>import javax.xml.parsers.ParserConfigurationException; <del>import javax.xml.parsers.SAXParser; <del>import javax.xml.xpath.XPathExpressionException; <add>import javax.xml.parsers.*; <add> <add>import org.xml.sax.*; <add>import org.w3c.dom.*; <add> <add>import java.io.*; <ide> <ide> import edu.stanford.nlp.ie.AbstractSequenceClassifier; <ide> import edu.stanford.nlp.ie.crf.CRFClassifier; <ide> * ONLINE-PART: extracts all Entities using the Stanford NER and sends them to CWS Component <ide> * @param textDoc <ide> * @return ArrayList<Entity> <del> * @throws JAXBException <ide> * @throws ParserConfigurationException <ide> * @throws IOException <del> * @throws SAXException <del> * @throws XPathExpressionException <add> * @throws SAXException <ide> */ <del> public String extractEntities(StringBuffer textDoc) throws JAXBException{ <add> public ArrayList<String> extractEntities(StringBuffer textDoc) throws IOException, ParserConfigurationException, SAXException{ <ide> <del> ArrayList<String> entities; <add> ArrayList<String> entities = new ArrayList<String>(); <ide> String text = textDoc.toString(); <ide> String resultInXml = classifier.classifyToString(text, "xml", false); <ide> StringBuffer buffer = new StringBuffer("<root>"); <ide> buffer.append(resultInXml); <ide> buffer.append("</root>"); <del> System.out.println(buffer); <ide> <add> DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); <add> DocumentBuilder db = dbf.newDocumentBuilder(); <add> InputSource is = new InputSource(); <add> is.setCharacterStream(new StringReader(buffer.toString())); <add> <add> Document doc = db.parse(is); <add> NodeList nodes = doc.getElementsByTagName("wi"); <add> <add> for (int i = 0; i < nodes.getLength(); i++){ <add> Element element = (Element) nodes.item(i); <add> <add> if(!element.getAttribute("entity").equals("O")){ <add> entities.add(element.getAttribute("entity") + ";" + element.getTextContent()); <add> } <add> <add> } <ide> <ide> /* <ide> entities = new ArrayList<String>(); <ide> oldCategory = category; <ide> <ide> }*/ <del> return resultInXml; <add> return entities; <ide> } <ide> <ide> /**