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
211e8e5d50b2fbfcec02e5265fe007917e18b746
0
brettwooldridge/HikariCP,polpot78/HikariCP,nitincchauhan/HikariCP,ams2990/HikariCP,udayshnk/HikariCP,brettwooldridge/HikariCP
/* * Copyright (C) 2013, 2014 Brett Wooldridge * * 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.zaxxer.hikari; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import com.zaxxer.hikari.metrics.MetricsTrackerFactory; import com.zaxxer.hikari.util.PropertyElf; import static com.zaxxer.hikari.util.UtilityElf.getNullIfEmpty; public class HikariConfig implements HikariConfigMXBean { private static final Logger LOGGER = LoggerFactory.getLogger(HikariConfig.class); private static final long CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(30); private static final long VALIDATION_TIMEOUT = TimeUnit.SECONDS.toMillis(5); private static final long IDLE_TIMEOUT = TimeUnit.MINUTES.toMillis(10); private static final long MAX_LIFETIME = TimeUnit.MINUTES.toMillis(30); private static final AtomicInteger POOL_NUMBER = new AtomicInteger(); private static boolean unitTest; // Properties changeable at runtime through the MBean // private volatile long connectionTimeout; private volatile long validationTimeout; private volatile long idleTimeout; private volatile long leakDetectionThreshold; private volatile long maxLifetime; private volatile int maxPoolSize; private volatile int minIdle; // Properties NOT changeable at runtime // private String catalog; private String connectionInitSql; private String connectionTestQuery; private String dataSourceClassName; private String dataSourceJndiName; private String driverClassName; private String jdbcUrl; private String password; private String poolName; private String transactionIsolationName; private String username; private boolean isAutoCommit; private boolean isReadOnly; private boolean isInitializationFailFast; private boolean isIsolateInternalQueries; private boolean isRegisterMbeans; private boolean isAllowPoolSuspension; private DataSource dataSource; private Properties dataSourceProperties; private ThreadFactory threadFactory; private ScheduledThreadPoolExecutor scheduledExecutor; private MetricsTrackerFactory metricsTrackerFactory; private Object metricRegistry; private Object healthCheckRegistry; private Properties healthCheckProperties; /** * Default constructor */ public HikariConfig() { dataSourceProperties = new Properties(); healthCheckProperties = new Properties(); connectionTimeout = CONNECTION_TIMEOUT; validationTimeout = VALIDATION_TIMEOUT; idleTimeout = IDLE_TIMEOUT; isAutoCommit = true; isInitializationFailFast = true; minIdle = -1; maxPoolSize = 10; maxLifetime = MAX_LIFETIME; String systemProp = System.getProperty("hikaricp.configurationFile"); if ( systemProp != null) { loadProperties(systemProp); } } /** * Construct a HikariConfig from the specified properties object. * * @param properties the name of the property file */ public HikariConfig(Properties properties) { this(); PropertyElf.setTargetFromProperties(this, properties); } /** * Construct a HikariConfig from the specified property file name. <code>propertyFileName</code> * will first be treated as a path in the file-system, and if that fails the * Class.getResourceAsStream(propertyFileName) will be tried. * * @param propertyFileName the name of the property file */ public HikariConfig(String propertyFileName) { this(); loadProperties(propertyFileName); } /** * Get the default catalog name to be set on connections. * * @return the default catalog name */ public String getCatalog() { return catalog; } /** * Set the default catalog name to be set on connections. * * @param catalog the catalog name, or null */ public void setCatalog(String catalog) { this.catalog = catalog; } /** * Get the SQL query to be executed to test the validity of connections. * * @return the SQL query string, or null */ public String getConnectionTestQuery() { return connectionTestQuery; } /** * Set the SQL query to be executed to test the validity of connections. Using * the JDBC4 <code>Connection.isValid()</code> method to test connection validity can * be more efficient on some databases and is recommended. See * {@link HikariConfig#setJdbc4ConnectionTest(boolean)}. * * @param connectionTestQuery a SQL query string */ public void setConnectionTestQuery(String connectionTestQuery) { this.connectionTestQuery = connectionTestQuery; } /** * Get the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. * * @return the SQL to execute on new connections, or null */ public String getConnectionInitSql() { return connectionInitSql; } /** * Set the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. If this query fails, it will be * treated as a failed connection attempt. * * @param connectionInitSql the SQL to execute on new connections */ public void setConnectionInitSql(String connectionInitSql) { this.connectionInitSql = connectionInitSql; } /** {@inheritDoc} */ @Override public long getConnectionTimeout() { return connectionTimeout; } /** {@inheritDoc} */ @Override public void setConnectionTimeout(long connectionTimeoutMs) { if (connectionTimeoutMs == 0) { this.connectionTimeout = Integer.MAX_VALUE; } else if (connectionTimeoutMs < 1000) { throw new IllegalArgumentException("connectionTimeout cannot be less than 1000ms"); } else { this.connectionTimeout = connectionTimeoutMs; } if (validationTimeout > connectionTimeoutMs) { this.validationTimeout = connectionTimeoutMs; } } /** {@inheritDoc} */ @Override public long getValidationTimeout() { return validationTimeout; } /** {@inheritDoc} */ @Override public void setValidationTimeout(long validationTimeoutMs) { if (validationTimeoutMs < 1000) { throw new IllegalArgumentException("validationTimeout cannot be less than 1000ms"); } else { this.validationTimeout = validationTimeoutMs; } if (validationTimeout > connectionTimeout) { this.validationTimeout = connectionTimeout; } } /** * Get the {@link DataSource} that has been explicitly specified to be wrapped by the * pool. * * @return the {@link DataSource} instance, or null */ public DataSource getDataSource() { return dataSource; } /** * Set a {@link DataSource} for the pool to explicitly wrap. This setter is not * available through property file based initialization. * * @param dataSource a specific {@link DataSource} to be wrapped by the pool */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public String getDataSourceClassName() { return dataSourceClassName; } public void setDataSourceClassName(String className) { this.dataSourceClassName = className; } public void addDataSourceProperty(String propertyName, Object value) { dataSourceProperties.put(propertyName, value); } public String getDataSourceJNDI() { return this.dataSourceJndiName; } public void setDataSourceJNDI(String jndiDataSource) { this.dataSourceJndiName = jndiDataSource; } public Properties getDataSourceProperties() { return dataSourceProperties; } public void setDataSourceProperties(Properties dsProperties) { dataSourceProperties.putAll(dsProperties); } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { try { Class<?> driverClass = this.getClass().getClassLoader().loadClass(driverClassName); driverClass.newInstance(); this.driverClassName = driverClassName; } catch (Exception e) { throw new RuntimeException("Could not load class of driverClassName " + driverClassName, e); } } /** {@inheritDoc} */ @Override public long getIdleTimeout() { return idleTimeout; } /** {@inheritDoc} */ @Override public void setIdleTimeout(long idleTimeoutMs) { if (idleTimeoutMs < 0) { throw new IllegalArgumentException("idleTimeout cannot be negative"); } this.idleTimeout = idleTimeoutMs; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } /** * Get the default auto-commit behavior of connections in the pool. * * @return the default auto-commit behavior of connections */ public boolean isAutoCommit() { return isAutoCommit; } /** * Set the default auto-commit behavior of connections in the pool. * * @param isAutoCommit the desired auto-commit default for connections */ public void setAutoCommit(boolean isAutoCommit) { this.isAutoCommit = isAutoCommit; } /** * Get the pool suspension behavior (allowed or disallowed). * * @return the pool suspension behavior */ public boolean isAllowPoolSuspension() { return isAllowPoolSuspension; } /** * Set whether or not pool suspension is allowed. There is a performance * impact when pool suspension is enabled. Unless you need it (for a * redundancy system for example) do not enable it. * * @param isAllowPoolSuspension the desired pool suspension allowance */ public void setAllowPoolSuspension(boolean isAllowPoolSuspension) { this.isAllowPoolSuspension = isAllowPoolSuspension; } /** * Get whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @return whether or not initialization should fail on error immediately */ public boolean isInitializationFailFast() { return isInitializationFailFast; } /** * Set whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @param failFast true if the pool should fail if the minimum connections cannot be created */ public void setInitializationFailFast(boolean failFast) { isInitializationFailFast = failFast; } public boolean isIsolateInternalQueries() { return isIsolateInternalQueries; } public void setIsolateInternalQueries(boolean isolate) { this.isIsolateInternalQueries = isolate; } @Deprecated public boolean isJdbc4ConnectionTest() { return false; } @Deprecated public void setJdbc4ConnectionTest(boolean useIsValid) { LOGGER.warn("The jdbcConnectionTest property is now deprecated, see the documentation for connectionTestQuery"); } public MetricsTrackerFactory getMetricsTrackerFactory() { return metricsTrackerFactory; } public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) { if (metricRegistry != null) { throw new IllegalStateException("cannot use setMetricsTrackerFactory() and setMetricRegistry() together"); } this.metricsTrackerFactory = metricsTrackerFactory; } /** * Get the Codahale MetricRegistry, could be null. * * @return the codahale MetricRegistry instance */ public Object getMetricRegistry() { return metricRegistry; } /** * Set a Codahale MetricRegistry to use for HikariCP. * * @param metricRegistry the Codahale MetricRegistry to set */ public void setMetricRegistry(Object metricRegistry) { if (metricsTrackerFactory != null) { throw new IllegalStateException("cannot use setMetricRegistry() and setMetricsTrackerFactory() together"); } if (metricRegistry != null) { if (metricRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); metricRegistry = (MetricRegistry) initCtx.lookup((String) metricRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(metricRegistry instanceof MetricRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.MetricRegistry"); } } this.metricRegistry = metricRegistry; } /** * Get the Codahale HealthCheckRegistry, could be null. * * @return the Codahale HealthCheckRegistry instance */ public Object getHealthCheckRegistry() { return healthCheckRegistry; } /** * Set a Codahale HealthCheckRegistry to use for HikariCP. * * @param healthCheckRegistry the Codahale HealthCheckRegistry to set */ public void setHealthCheckRegistry(Object healthCheckRegistry) { if (healthCheckRegistry != null) { if (healthCheckRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); healthCheckRegistry = (HealthCheckRegistry) initCtx.lookup((String) healthCheckRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(healthCheckRegistry instanceof HealthCheckRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.health.HealthCheckRegistry"); } } this.healthCheckRegistry = healthCheckRegistry; } public Properties getHealthCheckProperties() { return healthCheckProperties; } public void setHealthCheckProperties(Properties healthCheckProperties) { this.healthCheckProperties.putAll(healthCheckProperties); } public void addHealthCheckProperty(String key, String value) { healthCheckProperties.setProperty(key, value); } public boolean isReadOnly() { return isReadOnly; } public void setReadOnly(boolean readOnly) { this.isReadOnly = readOnly; } public boolean isRegisterMbeans() { return isRegisterMbeans; } public void setRegisterMbeans(boolean register) { this.isRegisterMbeans = register; } /** {@inheritDoc} */ @Override public long getLeakDetectionThreshold() { return leakDetectionThreshold; } /** {@inheritDoc} */ @Override public void setLeakDetectionThreshold(long leakDetectionThresholdMs) { this.leakDetectionThreshold = leakDetectionThresholdMs; } /** {@inheritDoc} */ @Override public long getMaxLifetime() { return maxLifetime; } /** {@inheritDoc} */ @Override public void setMaxLifetime(long maxLifetimeMs) { this.maxLifetime = maxLifetimeMs; } /** {@inheritDoc} */ @Override public int getMaximumPoolSize() { return maxPoolSize; } /** {@inheritDoc} */ @Override public void setMaximumPoolSize(int maxPoolSize) { if (maxPoolSize < 1) { throw new IllegalArgumentException("maxPoolSize cannot be less than 1"); } this.maxPoolSize = maxPoolSize; } /** {@inheritDoc} */ @Override public int getMinimumIdle() { return minIdle; } /** {@inheritDoc} */ @Override public void setMinimumIdle(int minIdle) { if (minIdle < 0) { throw new IllegalArgumentException("minimumIdle cannot be negative"); } this.minIdle = minIdle; } /** * Get the default password to use for DataSource.getConnection(username, password) calls. * @return the password */ public String getPassword() { return password; } /** * Set the default password to use for DataSource.getConnection(username, password) calls. * @param password the password */ public void setPassword(String password) { this.password = password; } /** {@inheritDoc} */ @Override public String getPoolName() { return poolName; } /** * Set the name of the connection pool. This is primarily used for the MBean * to uniquely identify the pool configuration. * * @param poolName the name of the connection pool to use */ public void setPoolName(String poolName) { this.poolName = poolName; } /** * Get the ScheduledExecutorService used for housekeeping. * * @return the executor */ public ScheduledThreadPoolExecutor getScheduledExecutorService() { return scheduledExecutor; } /** * Set the ScheduledExecutorService used for housekeeping. * * @param executor the ScheduledExecutorService */ public void setScheduledExecutorService(ScheduledThreadPoolExecutor executor) { this.scheduledExecutor = executor; } public String getTransactionIsolation() { return transactionIsolationName; } /** * Set the default transaction isolation level. The specified value is the * constant name from the <code>Connection</code> class, eg. * <code>TRANSACTION_REPEATABLE_READ</code>. * * @param isolationLevel the name of the isolation level */ public void setTransactionIsolation(String isolationLevel) { this.transactionIsolationName = isolationLevel; } /** * Get the default username used for DataSource.getConnection(username, password) calls. * * @return the username */ public String getUsername() { return username; } /** * Set the default username used for DataSource.getConnection(username, password) calls. * * @param username the username */ public void setUsername(String username) { this.username = username; } /** * Get the thread factory used to create threads. * * @return the thread factory (may be null, in which case the default thread factory is used) */ public ThreadFactory getThreadFactory() { return threadFactory; } /** * Set the thread factory to be used to create threads. * * @param threadFactory the thread factory (setting to null causes the default thread factory to be used) */ public void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; } public void validate() { validateNumerics(); // treat empty property as null catalog = getNullIfEmpty(catalog); connectionInitSql = getNullIfEmpty(connectionInitSql); connectionTestQuery = getNullIfEmpty(connectionTestQuery); transactionIsolationName = getNullIfEmpty(transactionIsolationName); dataSourceClassName = getNullIfEmpty(dataSourceClassName); dataSourceJndiName = getNullIfEmpty(dataSourceJndiName); driverClassName = getNullIfEmpty(driverClassName); jdbcUrl = getNullIfEmpty(jdbcUrl); if (poolName == null) { poolName = "HikariPool-" + POOL_NUMBER.getAndIncrement(); } if (poolName.contains(":") && isRegisterMbeans) { throw new IllegalArgumentException("poolName cannot contain ':' when used with JMX"); } // Check Data Source Options if (dataSource != null) { if (dataSourceClassName != null) { LOGGER.warn("using dataSource and ignoring dataSourceClassName"); } } else if (dataSourceClassName != null) { if (driverClassName != null) { LOGGER.error("cannot use driverClassName and dataSourceClassName together"); throw new IllegalArgumentException("cannot use driverClassName and dataSourceClassName together"); } else if (jdbcUrl != null) { LOGGER.warn("using dataSourceClassName and ignoring jdbcUrl"); } } else if (jdbcUrl != null) { } else if (driverClassName != null) { LOGGER.error("jdbcUrl is required with driverClassName"); throw new IllegalArgumentException("jdbcUrl is required with driverClassName"); } else { LOGGER.error("{} - dataSource or dataSourceClassName or jdbcUrl is required.", poolName); throw new IllegalArgumentException("dataSource or dataSourceClassName or jdbcUrl is required."); } if (isIsolateInternalQueries) { // set it false if not required isIsolateInternalQueries = connectionInitSql != null || connectionTestQuery != null; } if (LOGGER.isDebugEnabled() || unitTest) { logConfiguration(); } } private void validateNumerics() { if (maxLifetime < 0) { LOGGER.error("maxLifetime cannot be negative."); throw new IllegalArgumentException("maxLifetime cannot be negative."); } else if (maxLifetime > 0 && maxLifetime < TimeUnit.SECONDS.toMillis(30)) { LOGGER.warn("maxLifetime is less than 30000ms, setting to default {}ms.", MAX_LIFETIME); maxLifetime = MAX_LIFETIME; } if (idleTimeout != 0 && idleTimeout < TimeUnit.SECONDS.toMillis(10)) { LOGGER.warn("idleTimeout is less than 10000ms, setting to default {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (idleTimeout + TimeUnit.SECONDS.toMillis(1) > maxLifetime && maxLifetime > 0) { LOGGER.warn("idleTimeout is close to or greater than maxLifetime, disabling it."); maxLifetime = idleTimeout; idleTimeout = 0; } if (maxLifetime == 0 && idleTimeout == 0) { LOGGER.warn("setting idleTimeout to {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(2) && !unitTest) { LOGGER.warn("leakDetectionThreshold is less than 2000ms, setting to minimum 2000ms."); leakDetectionThreshold = 2000L; } if (connectionTimeout != Integer.MAX_VALUE) { if (validationTimeout > connectionTimeout) { LOGGER.warn("validationTimeout should be less than connectionTimeout, setting validationTimeout to connectionTimeout"); validationTimeout = connectionTimeout; } if (maxLifetime > 0 && connectionTimeout > maxLifetime) { LOGGER.warn("connectionTimeout should be less than maxLifetime, setting maxLifetime to connectionTimeout"); maxLifetime = connectionTimeout; } } if (minIdle < 0) { minIdle = maxPoolSize; } else if (minIdle > maxPoolSize) { LOGGER.warn("minIdle should be less than maxPoolSize, setting maxPoolSize to minIdle"); maxPoolSize = minIdle; } } private void logConfiguration() { LOGGER.debug("{} - configuration:", poolName); final Set<String> propertyNames = new TreeSet<>(PropertyElf.getPropertyNames(HikariConfig.class)); for (String prop : propertyNames) { try { Object value = PropertyElf.getProperty(prop, this); if ("dataSourceProperties".equals(prop)) { Properties dsProps = PropertyElf.copyProperties(dataSourceProperties); dsProps.setProperty("password", "<masked>"); value = dsProps; } if (prop.contains("password")) { value = "<masked>"; } else { value = (value instanceof String) ? "\"" + value + "\"" : value; } LOGGER.debug((prop + "................................................").substring(0, 32) + value); } catch (Exception e) { continue; } } } protected void loadProperties(String propertyFileName) { final File propFile = new File(propertyFileName); try (final InputStream is = propFile.isFile() ? new FileInputStream(propFile) : this.getClass().getResourceAsStream(propertyFileName)) { if (is != null) { Properties props = new Properties(); props.load(is); PropertyElf.setTargetFromProperties(this, props); } else { throw new IllegalArgumentException("Property file " + propertyFileName + " was not found."); } } catch (IOException io) { throw new RuntimeException("Error loading properties file", io); } } public void copyState(HikariConfig other) { for (Field field : HikariConfig.class.getDeclaredFields()) { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); try { field.set(other, field.get(this)); } catch (Exception e) { throw new RuntimeException("Exception copying HikariConfig state: " + e.getMessage(), e); } } } } }
src/main/java/com/zaxxer/hikari/HikariConfig.java
/* * Copyright (C) 2013, 2014 Brett Wooldridge * * 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.zaxxer.hikari; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import com.zaxxer.hikari.metrics.MetricsTrackerFactory; import com.zaxxer.hikari.util.PropertyElf; import static com.zaxxer.hikari.util.UtilityElf.getNullIfEmpty; public class HikariConfig implements HikariConfigMXBean { private static final Logger LOGGER = LoggerFactory.getLogger(HikariConfig.class); private static final long CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(30); private static final long VALIDATION_TIMEOUT = TimeUnit.SECONDS.toMillis(5); private static final long IDLE_TIMEOUT = TimeUnit.MINUTES.toMillis(10); private static final long MAX_LIFETIME = TimeUnit.MINUTES.toMillis(30); private static final AtomicInteger POOL_NUMBER = new AtomicInteger(); private static boolean unitTest; // Properties changeable at runtime through the MBean // private volatile long connectionTimeout; private volatile long validationTimeout; private volatile long idleTimeout; private volatile long leakDetectionThreshold; private volatile long maxLifetime; private volatile int maxPoolSize; private volatile int minIdle; // Properties NOT changeable at runtime // private String catalog; private String connectionInitSql; private String connectionTestQuery; private String dataSourceClassName; private String dataSourceJndiName; private String driverClassName; private String jdbcUrl; private String password; private String poolName; private String transactionIsolationName; private String username; private boolean isAutoCommit; private boolean isReadOnly; private boolean isInitializationFailFast; private boolean isIsolateInternalQueries; private boolean isRegisterMbeans; private boolean isAllowPoolSuspension; private DataSource dataSource; private Properties dataSourceProperties; private ThreadFactory threadFactory; private ScheduledThreadPoolExecutor scheduledExecutor; private MetricsTrackerFactory metricsTrackerFactory; private Object metricRegistry; private Object healthCheckRegistry; private Properties healthCheckProperties; /** * Default constructor */ public HikariConfig() { dataSourceProperties = new Properties(); healthCheckProperties = new Properties(); connectionTimeout = CONNECTION_TIMEOUT; validationTimeout = VALIDATION_TIMEOUT; idleTimeout = IDLE_TIMEOUT; isAutoCommit = true; isInitializationFailFast = true; minIdle = -1; maxPoolSize = 10; maxLifetime = MAX_LIFETIME; String systemProp = System.getProperty("hikaricp.configurationFile"); if ( systemProp != null) { loadProperties(systemProp); } } /** * Construct a HikariConfig from the specified properties object. * * @param properties the name of the property file */ public HikariConfig(Properties properties) { this(); PropertyElf.setTargetFromProperties(this, properties); } /** * Construct a HikariConfig from the specified property file name. <code>propertyFileName</code> * will first be treated as a path in the file-system, and if that fails the * Class.getResourceAsStream(propertyFileName) will be tried. * * @param propertyFileName the name of the property file */ public HikariConfig(String propertyFileName) { this(); loadProperties(propertyFileName); } /** * Get the default catalog name to be set on connections. * * @return the default catalog name */ public String getCatalog() { return catalog; } /** * Set the default catalog name to be set on connections. * * @param catalog the catalog name, or null */ public void setCatalog(String catalog) { this.catalog = catalog; } /** * Get the SQL query to be executed to test the validity of connections. * * @return the SQL query string, or null */ public String getConnectionTestQuery() { return connectionTestQuery; } /** * Set the SQL query to be executed to test the validity of connections. Using * the JDBC4 <code>Connection.isValid()</code> method to test connection validity can * be more efficient on some databases and is recommended. See * {@link HikariConfig#setJdbc4ConnectionTest(boolean)}. * * @param connectionTestQuery a SQL query string */ public void setConnectionTestQuery(String connectionTestQuery) { this.connectionTestQuery = connectionTestQuery; } /** * Get the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. * * @return the SQL to execute on new connections, or null */ public String getConnectionInitSql() { return connectionInitSql; } /** * Set the SQL string that will be executed on all new connections when they are * created, before they are added to the pool. If this query fails, it will be * treated as a failed connection attempt. * * @param connectionInitSql the SQL to execute on new connections */ public void setConnectionInitSql(String connectionInitSql) { this.connectionInitSql = connectionInitSql; } /** {@inheritDoc} */ @Override public long getConnectionTimeout() { return connectionTimeout; } /** {@inheritDoc} */ @Override public void setConnectionTimeout(long connectionTimeoutMs) { if (connectionTimeoutMs == 0) { this.connectionTimeout = Integer.MAX_VALUE; } else if (connectionTimeoutMs < 1000) { throw new IllegalArgumentException("connectionTimeout cannot be less than 1000ms"); } else { this.connectionTimeout = connectionTimeoutMs; } if (validationTimeout > connectionTimeoutMs) { this.validationTimeout = connectionTimeoutMs; } } /** {@inheritDoc} */ @Override public long getValidationTimeout() { return validationTimeout; } /** {@inheritDoc} */ @Override public void setValidationTimeout(long validationTimeoutMs) { if (validationTimeoutMs < 1000) { throw new IllegalArgumentException("validationTimeout cannot be less than 1000ms"); } else { this.validationTimeout = validationTimeoutMs; } if (validationTimeout > connectionTimeout) { this.validationTimeout = connectionTimeout; } } /** * Get the {@link DataSource} that has been explicitly specified to be wrapped by the * pool. * * @return the {@link DataSource} instance, or null */ public DataSource getDataSource() { return dataSource; } /** * Set a {@link DataSource} for the pool to explicitly wrap. This setter is not * available through property file based initialization. * * @param dataSource a specific {@link DataSource} to be wrapped by the pool */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public String getDataSourceClassName() { return dataSourceClassName; } public void setDataSourceClassName(String className) { this.dataSourceClassName = className; } public void addDataSourceProperty(String propertyName, Object value) { dataSourceProperties.put(propertyName, value); } public String getDataSourceJNDI() { return this.dataSourceJndiName; } public void setDataSourceJNDI(String jndiDataSource) { this.dataSourceJndiName = jndiDataSource; } public Properties getDataSourceProperties() { return dataSourceProperties; } public void setDataSourceProperties(Properties dsProperties) { dataSourceProperties.putAll(dsProperties); } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { try { Class<?> driverClass = this.getClass().getClassLoader().loadClass(driverClassName); driverClass.newInstance(); this.driverClassName = driverClassName; } catch (Exception e) { throw new RuntimeException("Could not load class of driverClassName " + driverClassName, e); } } /** {@inheritDoc} */ @Override public long getIdleTimeout() { return idleTimeout; } /** {@inheritDoc} */ @Override public void setIdleTimeout(long idleTimeoutMs) { if (idleTimeoutMs < 0) { throw new IllegalArgumentException("idleTimeout cannot be negative"); } this.idleTimeout = idleTimeoutMs; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } /** * Get the default auto-commit behavior of connections in the pool. * * @return the default auto-commit behavior of connections */ public boolean isAutoCommit() { return isAutoCommit; } /** * Set the default auto-commit behavior of connections in the pool. * * @param isAutoCommit the desired auto-commit default for connections */ public void setAutoCommit(boolean isAutoCommit) { this.isAutoCommit = isAutoCommit; } /** * Get the pool suspension behavior (allowed or disallowed). * * @return the pool suspension behavior */ public boolean isAllowPoolSuspension() { return isAllowPoolSuspension; } /** * Set whether or not pool suspension is allowed. There is a performance * impact when pool suspension is enabled. Unless you need it (for a * redundancy system for example) do not enable it. * * @param isAllowPoolSuspension the desired pool suspension allowance */ public void setAllowPoolSuspension(boolean isAllowPoolSuspension) { this.isAllowPoolSuspension = isAllowPoolSuspension; } /** * Get whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @return whether or not initialization should fail on error immediately */ public boolean isInitializationFailFast() { return isInitializationFailFast; } /** * Set whether or not the construction of the pool should throw an exception * if the minimum number of connections cannot be created. * * @param failFast true if the pool should fail if the minimum connections cannot be created */ public void setInitializationFailFast(boolean failFast) { isInitializationFailFast = failFast; } public boolean isIsolateInternalQueries() { return isIsolateInternalQueries; } public void setIsolateInternalQueries(boolean isolate) { this.isIsolateInternalQueries = isolate; } @Deprecated public boolean isJdbc4ConnectionTest() { return false; } @Deprecated public void setJdbc4ConnectionTest(boolean useIsValid) { LOGGER.warn("The jdbcConnectionTest property is now deprecated, see the documentation for connectionTestQuery"); } public MetricsTrackerFactory getMetricsTrackerFactory() { return metricsTrackerFactory; } public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) { if (metricRegistry != null) { throw new IllegalStateException("cannot use setMetricsTrackerFactory() and setMetricRegistry() together"); } this.metricsTrackerFactory = metricsTrackerFactory; } /** * Get the Codahale MetricRegistry, could be null. * * @return the codahale MetricRegistry instance */ public Object getMetricRegistry() { return metricRegistry; } /** * Set a Codahale MetricRegistry to use for HikariCP. * * @param metricRegistry the Codahale MetricRegistry to set */ public void setMetricRegistry(Object metricRegistry) { if (metricsTrackerFactory != null) { throw new IllegalStateException("cannot use setMetricRegistry() and setMetricsTrackerFactory() together"); } if (metricRegistry != null) { if (metricRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); metricRegistry = (MetricRegistry) initCtx.lookup((String) metricRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(metricRegistry instanceof MetricRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.MetricRegistry"); } } this.metricRegistry = metricRegistry; } /** * Get the Codahale HealthCheckRegistry, could be null. * * @return the Codahale HealthCheckRegistry instance */ public Object getHealthCheckRegistry() { return healthCheckRegistry; } /** * Set a Codahale HealthCheckRegistry to use for HikariCP. * * @param healthCheckRegistry the Codahale HealthCheckRegistry to set */ public void setHealthCheckRegistry(Object healthCheckRegistry) { if (healthCheckRegistry != null) { if (healthCheckRegistry instanceof String) { try { InitialContext initCtx = new InitialContext(); healthCheckRegistry = (HealthCheckRegistry) initCtx.lookup((String) healthCheckRegistry); } catch (NamingException e) { throw new IllegalArgumentException(e); } } if (!(healthCheckRegistry instanceof HealthCheckRegistry)) { throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.health.HealthCheckRegistry"); } } this.healthCheckRegistry = healthCheckRegistry; } public Properties getHealthCheckProperties() { return healthCheckProperties; } public void setHealthCheckProperties(Properties healthCheckProperties) { this.healthCheckProperties.putAll(healthCheckProperties); } public void addHealthCheckProperty(String key, String value) { healthCheckProperties.setProperty(key, value); } public boolean isReadOnly() { return isReadOnly; } public void setReadOnly(boolean readOnly) { this.isReadOnly = readOnly; } public boolean isRegisterMbeans() { return isRegisterMbeans; } public void setRegisterMbeans(boolean register) { this.isRegisterMbeans = register; } /** {@inheritDoc} */ @Override public long getLeakDetectionThreshold() { return leakDetectionThreshold; } /** {@inheritDoc} */ @Override public void setLeakDetectionThreshold(long leakDetectionThresholdMs) { this.leakDetectionThreshold = leakDetectionThresholdMs; } /** {@inheritDoc} */ @Override public long getMaxLifetime() { return maxLifetime; } /** {@inheritDoc} */ @Override public void setMaxLifetime(long maxLifetimeMs) { this.maxLifetime = maxLifetimeMs; } /** {@inheritDoc} */ @Override public int getMaximumPoolSize() { return maxPoolSize; } /** {@inheritDoc} */ @Override public void setMaximumPoolSize(int maxPoolSize) { if (maxPoolSize < 1) { throw new IllegalArgumentException("maxPoolSize cannot be less than 1"); } this.maxPoolSize = maxPoolSize; } /** {@inheritDoc} */ @Override public int getMinimumIdle() { return minIdle; } /** {@inheritDoc} */ @Override public void setMinimumIdle(int minIdle) { if (minIdle < 0) { throw new IllegalArgumentException("minimumIdle cannot be negative"); } this.minIdle = minIdle; } /** * Get the default password to use for DataSource.getConnection(username, password) calls. * @return the password */ public String getPassword() { return password; } /** * Set the default password to use for DataSource.getConnection(username, password) calls. * @param password the password */ public void setPassword(String password) { this.password = password; } /** {@inheritDoc} */ @Override public String getPoolName() { return poolName; } /** * Set the name of the connection pool. This is primarily used for the MBean * to uniquely identify the pool configuration. * * @param poolName the name of the connection pool to use */ public void setPoolName(String poolName) { this.poolName = poolName; } /** * Get the ScheduledExecutorService used for housekeeping. * * @return the executor */ public ScheduledThreadPoolExecutor getScheduledExecutorService() { return scheduledExecutor; } /** * Set the ScheduledExecutorService used for housekeeping. * * @param executor the ScheduledExecutorService */ public void setScheduledExecutorService(ScheduledThreadPoolExecutor executor) { this.scheduledExecutor = executor; } public String getTransactionIsolation() { return transactionIsolationName; } /** * Set the default transaction isolation level. The specified value is the * constant name from the <code>Connection</code> class, eg. * <code>TRANSACTION_REPEATABLE_READ</code>. * * @param isolationLevel the name of the isolation level */ public void setTransactionIsolation(String isolationLevel) { this.transactionIsolationName = isolationLevel; } /** * Get the default username used for DataSource.getConnection(username, password) calls. * * @return the username */ public String getUsername() { return username; } /** * Set the default username used for DataSource.getConnection(username, password) calls. * * @param username the username */ public void setUsername(String username) { this.username = username; } /** * Get the thread factory used to create threads. * * @return the thread factory (may be null, in which case the default thread factory is used) */ public ThreadFactory getThreadFactory() { return threadFactory; } /** * Set the thread factory to be used to create threads. * * @param threadFactory the thread factory (setting to null causes the default thread factory to be used) */ public void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; } public void validate() { validateNumerics(); // treat empty property as null catalog = getNullIfEmpty(catalog); connectionInitSql = getNullIfEmpty(connectionInitSql); connectionTestQuery = getNullIfEmpty(connectionTestQuery); transactionIsolationName = getNullIfEmpty(transactionIsolationName); dataSourceClassName = getNullIfEmpty(dataSourceClassName); dataSourceJndiName = getNullIfEmpty(dataSourceJndiName); driverClassName = getNullIfEmpty(driverClassName); jdbcUrl = getNullIfEmpty(jdbcUrl); if (poolName == null) { poolName = "HikariPool-" + POOL_NUMBER.getAndIncrement(); } if (poolName.contains(":") && isRegisterMbeans) { throw new IllegalArgumentException("poolName cannot contain ':' when used with JMX"); } // Check Data Source Options if (dataSource != null) { if (dataSourceClassName != null) { LOGGER.warn("using dataSource and ignoring dataSourceClassName"); } } else if (dataSourceClassName != null) { if (driverClassName != null) { LOGGER.error("cannot use driverClassName and dataSourceClassName together"); throw new IllegalArgumentException("cannot use driverClassName and dataSourceClassName together"); } else if (jdbcUrl != null) { LOGGER.warn("using dataSourceClassName and ignoring jdbcUrl"); } } else if (jdbcUrl != null) { } else if (driverClassName != null) { LOGGER.error("jdbcUrl is required with driverClassName"); throw new IllegalArgumentException("jdbcUrl is required with driverClassName"); } else { LOGGER.error("{} - dataSource or dataSourceClassName or jdbcUrl is required.", poolName); throw new IllegalArgumentException("dataSource or dataSourceClassName or jdbcUrl is required."); } if (isIsolateInternalQueries) { // set it false if not required isIsolateInternalQueries = connectionInitSql != null || connectionTestQuery != null; } if (LOGGER.isDebugEnabled() || unitTest) { logConfiguration(); } } private void validateNumerics() { if (maxLifetime < 0) { LOGGER.error("maxLifetime cannot be negative."); throw new IllegalArgumentException("maxLifetime cannot be negative."); } else if (maxLifetime > 0 && maxLifetime < TimeUnit.SECONDS.toMillis(30)) { LOGGER.warn("maxLifetime is less than 30000ms, setting to default {}ms.", MAX_LIFETIME); maxLifetime = MAX_LIFETIME; } if (idleTimeout != 0 && idleTimeout < TimeUnit.SECONDS.toMillis(10)) { LOGGER.warn("idleTimeout is less than 10000ms, setting to default {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (idleTimeout + TimeUnit.SECONDS.toMillis(1) > maxLifetime && maxLifetime > 0) { LOGGER.warn("idleTimeout is close to or greater than maxLifetime, disabling it."); maxLifetime = idleTimeout; idleTimeout = 0; } if (maxLifetime == 0 && idleTimeout == 0) { LOGGER.warn("setting idleTimeout to {}ms.", IDLE_TIMEOUT); idleTimeout = IDLE_TIMEOUT; } if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(2) && !unitTest) { LOGGER.warn("leakDetectionThreshold is less than 2000ms, setting to minimum 2000ms."); leakDetectionThreshold = 2000L; } if (connectionTimeout != Integer.MAX_VALUE) { if (validationTimeout > connectionTimeout) { LOGGER.warn("validationTimeout should be less than connectionTimeout, setting validationTimeout to connectionTimeout"); validationTimeout = connectionTimeout; } if (maxLifetime > 0 && connectionTimeout > maxLifetime) { LOGGER.warn("connectionTimeout should be less than maxLifetime, setting maxLifetime to connectionTimeout"); maxLifetime = connectionTimeout; } } if (minIdle < 0) { minIdle = maxPoolSize; } else if (minIdle > maxPoolSize) { LOGGER.warn("minIdle should be less than maxPoolSize, setting maxPoolSize to minIdle"); maxPoolSize = minIdle; } } private void logConfiguration() { LOGGER.debug("{} - configuration:", poolName); final Set<String> propertyNames = new TreeSet<>(PropertyElf.getPropertyNames(HikariConfig.class)); for (String prop : propertyNames) { try { Object value = PropertyElf.getProperty(prop, this); if ("dataSourceProperties".equals(prop)) { Properties dsProps = PropertyElf.copyProperties(dataSourceProperties); dsProps.setProperty("password", "<masked>"); value = dsProps; } value = (prop.contains("password") ? "<masked>" : value); value = (value instanceof String) ? "\"" + value + "\"" : value; LOGGER.debug((prop + "................................................").substring(0, 32) + value); } catch (Exception e) { continue; } } } protected void loadProperties(String propertyFileName) { final File propFile = new File(propertyFileName); try (final InputStream is = propFile.isFile() ? new FileInputStream(propFile) : this.getClass().getResourceAsStream(propertyFileName)) { if (is != null) { Properties props = new Properties(); props.load(is); PropertyElf.setTargetFromProperties(this, props); } else { throw new IllegalArgumentException("Property file " + propertyFileName + " was not found."); } } catch (IOException io) { throw new RuntimeException("Error loading properties file", io); } } public void copyState(HikariConfig other) { for (Field field : HikariConfig.class.getDeclaredFields()) { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); try { field.set(other, field.get(this)); } catch (Exception e) { throw new RuntimeException("Exception copying HikariConfig state: " + e.getMessage(), e); } } } } }
special treatment for password
src/main/java/com/zaxxer/hikari/HikariConfig.java
special treatment for password
<ide><path>rc/main/java/com/zaxxer/hikari/HikariConfig.java <ide> dsProps.setProperty("password", "<masked>"); <ide> value = dsProps; <ide> } <del> value = (prop.contains("password") ? "<masked>" : value); <del> value = (value instanceof String) ? "\"" + value + "\"" : value; <add> if (prop.contains("password")) { <add> value = "<masked>"; <add> } <add> else { <add> value = (value instanceof String) ? "\"" + value + "\"" : value; <add> } <ide> LOGGER.debug((prop + "................................................").substring(0, 32) + value); <ide> } <ide> catch (Exception e) {
Java
lgpl-2.1
c2df3bb103e826dc7aba57d314ffa01ba07e430c
0
hal/core,hal/core,hal/core,hal/core,hal/core
/* * JBoss, Home of Professional Open Source * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.shared.homepage; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.Place; import com.gwtplatform.mvp.client.proxy.Proxy; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.ProductConfig; import org.jboss.as.console.client.core.*; import java.util.LinkedList; import java.util.List; import static org.jboss.as.console.client.ProductConfig.Profile.COMMUNITY; import static org.jboss.as.console.client.ProductConfig.Profile.PRODUCT; /** * @author Harald Pehl */ public class HomepagePresenter extends Presenter<HomepagePresenter.MyView, HomepagePresenter.MyProxy> { @NoGatekeeper @ProxyCodeSplit @NameToken(NameTokens.HomepagePresenter) public interface MyProxy extends Proxy<HomepagePresenter>, Place {} public interface MyView extends View { void addInfoBoxes(List<InfoBox> infoBoxes); void addContentBoxes(List<ContentBox> contentBoxes); void addSidebarSections(List<SidebarSection> sidebarSections); } public static final Object SECTION_INFO_SLOT = new Object(); public static final Object CONTENT_BOX_SLOT = new Object(); public static final Object SIDEBAR_SLOT = new Object(); private final List<InfoBox> infoBoxes; private final List<ContentBox> contentBoxes; private final List<SidebarSection> sidebarSections; private final Header header; @Inject public HomepagePresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final BootstrapContext bootstrapContext, final ProductConfig productConfig, Header header) { super(eventBus, view, proxy, MainLayoutPresenter.TYPE_MainContent); this.infoBoxes = setupInfoBoxes(bootstrapContext.isStandalone()); this.contentBoxes = setupContentBoxes(bootstrapContext.isStandalone()); this.sidebarSections = setupSidebarSection(productConfig.getProfile()); this.header = header; } private List<InfoBox> setupInfoBoxes(final boolean standalone) { List<InfoBox> infoBoxes = new LinkedList<InfoBox>(); if (standalone) { infoBoxes.add(new InfoBox(NameTokens.DeploymentBrowserPresenter, Console.CONSTANTS.common_label_deployments(), Console.CONSTANTS.section_deployment_intro())); infoBoxes.add(new InfoBox(NameTokens.ServerProfile, Console.CONSTANTS.common_label_configuration(), Console.CONSTANTS.section_configuration_intro())); infoBoxes.add(new InfoBox(NameTokens.StandaloneRuntimePresenter, "Runtime", Console.CONSTANTS.section_runtime_intro())); } else { infoBoxes.add(new InfoBox(NameTokens.DeploymentsPresenter, Console.CONSTANTS.common_label_deployments(), Console.CONSTANTS.section_deployment_intro())); infoBoxes.add(new InfoBox(NameTokens.ProfileMgmtPresenter, Console.CONSTANTS.common_label_configuration(), Console.CONSTANTS.section_configuration_intro())); infoBoxes.add(new InfoBox(NameTokens.DomainRuntimePresenter, "Runtime", Console.CONSTANTS.section_runtime_intro())); } infoBoxes.add(new InfoBox(NameTokens.AdministrationPresenter, "Administration", Console.CONSTANTS.section_administration_intro())); return infoBoxes; } private List<ContentBox> setupContentBoxes(final boolean standalone) { List<ContentBox> contentBoxes = new LinkedList<ContentBox>(); if (standalone) { contentBoxes.add(new ContentBox("NewDeployment", Console.CONSTANTS.content_box_new_deployment_title(), Console.MESSAGES.content_box_new_deployment_body_standalone(), Console.CONSTANTS.content_box_new_deployment_link(), NameTokens.DeploymentBrowserPresenter)); contentBoxes.add(new ContentBox("Datasources", Console.CONSTANTS.content_box_create_datasource_title(), Console.MESSAGES.content_box_create_datasource_body_standalone(), "Datasources", NameTokens.DataSourcePresenter)); contentBoxes.add(new ContentBox("ApplyPath", Console.CONSTANTS.content_box_apply_patch_title(), Console.MESSAGES.content_box_apply_patch_body_standalone(), "Patch Management", NameTokens.PatchingPresenter)); } else { contentBoxes.add(new ContentBox("NewDeployment", Console.CONSTANTS.content_box_new_deployment_title(), Console.MESSAGES.content_box_new_deployment_body_domain(), Console.CONSTANTS.content_box_new_deployment_link(), NameTokens.DeploymentsPresenter)); contentBoxes.add(new ContentBox("Datasources", Console.CONSTANTS.content_box_create_datasource_title(), Console.MESSAGES.content_box_create_datasource_body_domain(), "Datasources", NameTokens.DataSourcePresenter)); contentBoxes.add(new ContentBox("Topology", Console.CONSTANTS.content_box_topology_title(), Console.MESSAGES.content_box_topology_body(), Console.CONSTANTS.content_box_topology_link(), NameTokens.Topology)); contentBoxes.add(new ContentBox("CreateServerGroup", Console.CONSTANTS.content_box_create_server_group_title(), Console.MESSAGES.content_box_create_server_group_body(), Console.CONSTANTS.content_box_create_server_group_link(), NameTokens.ServerGroupPresenter)); contentBoxes.add(new ContentBox("ApplyPath", Console.CONSTANTS.content_box_apply_patch_title(), Console.MESSAGES.content_box_apply_patch_body_domain(), "Patch Management", NameTokens.PatchingPresenter)); } contentBoxes.add(new ContentBox("Administration", Console.CONSTANTS.content_box_role_assignment_title(), Console.MESSAGES.content_box_role_assignment_body(), Console.CONSTANTS.content_box_role_assignment_link(), NameTokens.RoleAssignmentPresenter)); return contentBoxes; } private List<SidebarSection> setupSidebarSection(ProductConfig.Profile profile) { List<SidebarSection> sections = new LinkedList<SidebarSection>(); if (profile == COMMUNITY) { SidebarSection general = new SidebarSection(Console.CONSTANTS.sidebar_general_resources()); general.addLink("http://wildfly.org/", Console.CONSTANTS.sidebar_wilfdfly_home_text()); general.addLink("https://docs.jboss.org/author/display/WFLY8/Documentation", Console.CONSTANTS.sidebar_wilfdfly_documentation_text()); general.addLink("https://docs.jboss.org/author/display/WFLY8/Admin+Guide", Console.CONSTANTS.sidebar_admin_guide_text()); general.addLink("http://wildscribe.github.io/index.html", Console.CONSTANTS.sidebar_model_reference_text()); general.addLink("https://issues.jboss.org/browse/WFLY", Console.CONSTANTS.sidebar_wildfly_issues_text()); general.addLink("http://wildfly.org/news/", Console.CONSTANTS.sidebar_latest_news()); sections.add(general); SidebarSection help = new SidebarSection(Console.CONSTANTS.sidebar_get_help()); help.addLink("http://www.jboss.org/jdf/", Console.CONSTANTS.sidebar_tutorials_text()); help.addLink("https://community.jboss.org/en/wildfly?view=discussions", Console.CONSTANTS.sidebar_user_forums_text()); help.addLink("irc://freenode.org/#wildfly", Console.CONSTANTS.sidebar_irc_text()); help.addLink("https://lists.jboss.org/mailman/listinfo/wildfly-dev", Console.CONSTANTS.sidebar_developers_mailing_list_text()); sections.add(help); } else if (profile == PRODUCT) { SidebarSection general = new SidebarSection(Console.CONSTANTS.sidebar_general_resources()); general.addLink(Console.CONSTANTS.sidebar_eap_documentation_link(), Console.CONSTANTS.sidebar_eap_documentation_text()); general.addLink(Console.CONSTANTS.sidebar_learn_more_eap_link(), Console.CONSTANTS.sidebar_learn_more_eap_text()); general.addLink(Console.CONSTANTS.sidebar_trouble_ticket_link(), Console.CONSTANTS.sidebar_trouble_ticket_text()); general.addLink(Console.CONSTANTS.sidebar_training_link(), Console.CONSTANTS.sidebar_training_text()); sections.add(general); SidebarSection developer = new SidebarSection(Console.CONSTANTS.sidebar_developer_resources()); developer.addLink(Console.CONSTANTS.sidebar_tutorials_link(), Console.CONSTANTS.sidebar_tutorials_text()); developer.addLink(Console.CONSTANTS.sidebar_eap_community_link(), Console.CONSTANTS.sidebar_eap_community_text()); sections.add(developer); SidebarSection operational = new SidebarSection(Console.CONSTANTS.sidebar_operational_resources()); operational.addLink(Console.CONSTANTS.sidebar_eap_configurations_link(), Console.CONSTANTS.sidebar_eap_configurations_text()); operational.addLink(Console.CONSTANTS.sidebar_knowledgebase_link(), Console.CONSTANTS.sidebar_knowledgebase_text()); operational .addLink(Console.CONSTANTS.sidebar_consulting_link(), Console.CONSTANTS.sidebar_consulting_text()); sections.add(operational); } return sections; } @Override protected void onBind() { super.onBind(); getView().addInfoBoxes(infoBoxes); getView().addContentBoxes(contentBoxes); getView().addSidebarSections(sidebarSections); } @Override protected void onReset() { super.onReset(); header.highlight(NameTokens.HomepagePresenter); } }
gui/src/main/java/org/jboss/as/console/client/shared/homepage/HomepagePresenter.java
/* * JBoss, Home of Professional Open Source * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.shared.homepage; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.Place; import com.gwtplatform.mvp.client.proxy.Proxy; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.ProductConfig; import org.jboss.as.console.client.core.*; import java.util.LinkedList; import java.util.List; import static org.jboss.as.console.client.ProductConfig.Profile.COMMUNITY; import static org.jboss.as.console.client.ProductConfig.Profile.PRODUCT; /** * @author Harald Pehl */ public class HomepagePresenter extends Presenter<HomepagePresenter.MyView, HomepagePresenter.MyProxy> { @NoGatekeeper @ProxyCodeSplit @NameToken(NameTokens.HomepagePresenter) public interface MyProxy extends Proxy<HomepagePresenter>, Place {} public interface MyView extends View { void addInfoBoxes(List<InfoBox> infoBoxes); void addContentBoxes(List<ContentBox> contentBoxes); void addSidebarSections(List<SidebarSection> sidebarSections); } public static final Object SECTION_INFO_SLOT = new Object(); public static final Object CONTENT_BOX_SLOT = new Object(); public static final Object SIDEBAR_SLOT = new Object(); private final List<InfoBox> infoBoxes; private final List<ContentBox> contentBoxes; private final List<SidebarSection> sidebarSections; private final Header header; @Inject public HomepagePresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final BootstrapContext bootstrapContext, final ProductConfig productConfig, Header header) { super(eventBus, view, proxy, MainLayoutPresenter.TYPE_MainContent); this.infoBoxes = setupInfoBoxes(bootstrapContext.isStandalone()); this.contentBoxes = setupContentBoxes(bootstrapContext.isStandalone()); this.sidebarSections = setupSidebarSection(productConfig.getProfile()); this.header = header; } private List<InfoBox> setupInfoBoxes(final boolean standalone) { List<InfoBox> infoBoxes = new LinkedList<InfoBox>(); if (standalone) { infoBoxes.add(new InfoBox(NameTokens.DeploymentBrowserPresenter, Console.CONSTANTS.common_label_deployments(), Console.CONSTANTS.section_deployment_intro())); infoBoxes.add(new InfoBox(NameTokens.ServerProfile, Console.CONSTANTS.common_label_configuration(), Console.CONSTANTS.section_configuration_intro())); infoBoxes.add(new InfoBox(NameTokens.StandaloneRuntimePresenter, "Runtime", Console.CONSTANTS.section_runtime_intro())); } else { infoBoxes.add(new InfoBox(NameTokens.DeploymentsPresenter, Console.CONSTANTS.common_label_deployments(), Console.CONSTANTS.section_deployment_intro())); infoBoxes.add(new InfoBox(NameTokens.ProfileMgmtPresenter, Console.CONSTANTS.common_label_configuration(), Console.CONSTANTS.section_configuration_intro())); infoBoxes.add(new InfoBox(NameTokens.HostMgmtPresenter, "Domain", Console.CONSTANTS.section_domain_intro())); infoBoxes.add(new InfoBox(NameTokens.DomainRuntimePresenter, "Runtime", Console.CONSTANTS.section_runtime_intro())); } infoBoxes.add(new InfoBox(NameTokens.AdministrationPresenter, "Administration", Console.CONSTANTS.section_administration_intro())); return infoBoxes; } private List<ContentBox> setupContentBoxes(final boolean standalone) { List<ContentBox> contentBoxes = new LinkedList<ContentBox>(); if (standalone) { contentBoxes.add(new ContentBox("NewDeployment", Console.CONSTANTS.content_box_new_deployment_title(), Console.MESSAGES.content_box_new_deployment_body_standalone(), Console.CONSTANTS.content_box_new_deployment_link(), NameTokens.DeploymentBrowserPresenter)); contentBoxes.add(new ContentBox("Datasources", Console.CONSTANTS.content_box_create_datasource_title(), Console.MESSAGES.content_box_create_datasource_body_standalone(), "Datasources", NameTokens.DataSourcePresenter)); contentBoxes.add(new ContentBox("ApplyPath", Console.CONSTANTS.content_box_apply_patch_title(), Console.MESSAGES.content_box_apply_patch_body_standalone(), "Patch Management", NameTokens.PatchingPresenter)); } else { contentBoxes.add(new ContentBox("NewDeployment", Console.CONSTANTS.content_box_new_deployment_title(), Console.MESSAGES.content_box_new_deployment_body_domain(), Console.CONSTANTS.content_box_new_deployment_link(), NameTokens.DeploymentsPresenter)); contentBoxes.add(new ContentBox("Datasources", Console.CONSTANTS.content_box_create_datasource_title(), Console.MESSAGES.content_box_create_datasource_body_domain(), "Datasources", NameTokens.DataSourcePresenter)); contentBoxes.add(new ContentBox("Topology", Console.CONSTANTS.content_box_topology_title(), Console.MESSAGES.content_box_topology_body(), Console.CONSTANTS.content_box_topology_link(), NameTokens.Topology)); contentBoxes.add(new ContentBox("CreateServerGroup", Console.CONSTANTS.content_box_create_server_group_title(), Console.MESSAGES.content_box_create_server_group_body(), Console.CONSTANTS.content_box_create_server_group_link(), NameTokens.ServerGroupPresenter)); contentBoxes.add(new ContentBox("ApplyPath", Console.CONSTANTS.content_box_apply_patch_title(), Console.MESSAGES.content_box_apply_patch_body_domain(), "Patch Management", NameTokens.PatchingPresenter)); } contentBoxes.add(new ContentBox("Administration", Console.CONSTANTS.content_box_role_assignment_title(), Console.MESSAGES.content_box_role_assignment_body(), Console.CONSTANTS.content_box_role_assignment_link(), NameTokens.RoleAssignmentPresenter)); return contentBoxes; } private List<SidebarSection> setupSidebarSection(ProductConfig.Profile profile) { List<SidebarSection> sections = new LinkedList<SidebarSection>(); if (profile == COMMUNITY) { SidebarSection general = new SidebarSection(Console.CONSTANTS.sidebar_general_resources()); general.addLink("http://wildfly.org/", Console.CONSTANTS.sidebar_wilfdfly_home_text()); general.addLink("https://docs.jboss.org/author/display/WFLY8/Documentation", Console.CONSTANTS.sidebar_wilfdfly_documentation_text()); general.addLink("https://docs.jboss.org/author/display/WFLY8/Admin+Guide", Console.CONSTANTS.sidebar_admin_guide_text()); general.addLink("http://wildscribe.github.io/index.html", Console.CONSTANTS.sidebar_model_reference_text()); general.addLink("https://issues.jboss.org/browse/WFLY", Console.CONSTANTS.sidebar_wildfly_issues_text()); general.addLink("http://wildfly.org/news/", Console.CONSTANTS.sidebar_latest_news()); sections.add(general); SidebarSection help = new SidebarSection(Console.CONSTANTS.sidebar_get_help()); help.addLink("http://www.jboss.org/jdf/", Console.CONSTANTS.sidebar_tutorials_text()); help.addLink("https://community.jboss.org/en/wildfly?view=discussions", Console.CONSTANTS.sidebar_user_forums_text()); help.addLink("irc://freenode.org/#wildfly", Console.CONSTANTS.sidebar_irc_text()); help.addLink("https://lists.jboss.org/mailman/listinfo/wildfly-dev", Console.CONSTANTS.sidebar_developers_mailing_list_text()); sections.add(help); } else if (profile == PRODUCT) { SidebarSection general = new SidebarSection(Console.CONSTANTS.sidebar_general_resources()); general.addLink(Console.CONSTANTS.sidebar_eap_documentation_link(), Console.CONSTANTS.sidebar_eap_documentation_text()); general.addLink(Console.CONSTANTS.sidebar_learn_more_eap_link(), Console.CONSTANTS.sidebar_learn_more_eap_text()); general.addLink(Console.CONSTANTS.sidebar_trouble_ticket_link(), Console.CONSTANTS.sidebar_trouble_ticket_text()); general.addLink(Console.CONSTANTS.sidebar_training_link(), Console.CONSTANTS.sidebar_training_text()); sections.add(general); SidebarSection developer = new SidebarSection(Console.CONSTANTS.sidebar_developer_resources()); developer.addLink(Console.CONSTANTS.sidebar_tutorials_link(), Console.CONSTANTS.sidebar_tutorials_text()); developer.addLink(Console.CONSTANTS.sidebar_eap_community_link(), Console.CONSTANTS.sidebar_eap_community_text()); sections.add(developer); SidebarSection operational = new SidebarSection(Console.CONSTANTS.sidebar_operational_resources()); operational.addLink(Console.CONSTANTS.sidebar_eap_configurations_link(), Console.CONSTANTS.sidebar_eap_configurations_text()); operational.addLink(Console.CONSTANTS.sidebar_knowledgebase_link(), Console.CONSTANTS.sidebar_knowledgebase_text()); operational .addLink(Console.CONSTANTS.sidebar_consulting_link(), Console.CONSTANTS.sidebar_consulting_text()); sections.add(operational); } return sections; } @Override protected void onBind() { super.onBind(); getView().addInfoBoxes(infoBoxes); getView().addContentBoxes(contentBoxes); getView().addSidebarSections(sidebarSections); } @Override protected void onReset() { super.onReset(); header.highlight(NameTokens.HomepagePresenter); } }
Remove domain link from homepage
gui/src/main/java/org/jboss/as/console/client/shared/homepage/HomepagePresenter.java
Remove domain link from homepage
<ide><path>ui/src/main/java/org/jboss/as/console/client/shared/homepage/HomepagePresenter.java <ide> Console.CONSTANTS.section_deployment_intro())); <ide> infoBoxes.add(new InfoBox(NameTokens.ProfileMgmtPresenter, <ide> Console.CONSTANTS.common_label_configuration(), Console.CONSTANTS.section_configuration_intro())); <del> infoBoxes.add(new InfoBox(NameTokens.HostMgmtPresenter, "Domain", <del> Console.CONSTANTS.section_domain_intro())); <add> <ide> infoBoxes.add(new InfoBox(NameTokens.DomainRuntimePresenter, "Runtime", <ide> Console.CONSTANTS.section_runtime_intro())); <ide> }
Java
apache-2.0
d75d5320e5829ca4d0f7f7c5a4b3cfe608f180ac
0
fitermay/intellij-community,jagguli/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,signed/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,consulo/consulo,TangHao1987/intellij-community,diorcety/intellij-community,fnouama/intellij-community,robovm/robovm-studio,semonte/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,signed/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ibinti/intellij-community,semonte/intellij-community,vladmm/intellij-community,adedayo/intellij-community,izonder/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,robovm/robovm-studio,retomerz/intellij-community,TangHao1987/intellij-community,consulo/consulo,diorcety/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,petteyg/intellij-community,retomerz/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,apixandru/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,petteyg/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,fnouama/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,caot/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,holmes/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,izonder/intellij-community,clumsy/intellij-community,joewalnes/idea-community,vladmm/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,suncycheng/intellij-community,allotria/intellij-community,tmpgit/intellij-community,caot/intellij-community,caot/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,da1z/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,robovm/robovm-studio,clumsy/intellij-community,semonte/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,supersven/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,adedayo/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,samthor/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,diorcety/intellij-community,kdwink/intellij-community,da1z/intellij-community,slisson/intellij-community,slisson/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,holmes/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,samthor/intellij-community,da1z/intellij-community,retomerz/intellij-community,vladmm/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,caot/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,caot/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,retomerz/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,consulo/consulo,ryano144/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ibinti/intellij-community,supersven/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,blademainer/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,mglukhikh/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,petteyg/intellij-community,da1z/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,supersven/intellij-community,semonte/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,caot/intellij-community,slisson/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,izonder/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,slisson/intellij-community,izonder/intellij-community,robovm/robovm-studio,petteyg/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,holmes/intellij-community,diorcety/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ernestp/consulo,xfournet/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,da1z/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,da1z/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,signed/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,signed/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,petteyg/intellij-community,asedunov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,fitermay/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,signed/intellij-community,supersven/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,adedayo/intellij-community,supersven/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,petteyg/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ibinti/intellij-community,dslomov/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,kdwink/intellij-community,supersven/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,FHannes/intellij-community,xfournet/intellij-community,hurricup/intellij-community,semonte/intellij-community,signed/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,holmes/intellij-community,consulo/consulo,Lekanich/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,da1z/intellij-community,kool79/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,signed/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,semonte/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,caot/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,izonder/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,consulo/consulo,semonte/intellij-community,izonder/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,vladmm/intellij-community,da1z/intellij-community,jagguli/intellij-community,ibinti/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,supersven/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,hurricup/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,samthor/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,ryano144/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,signed/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,supersven/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,blademainer/intellij-community,FHannes/intellij-community,slisson/intellij-community,samthor/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,hurricup/intellij-community,allotria/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ftomassetti/intellij-community,signed/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,clumsy/intellij-community,blademainer/intellij-community,joewalnes/idea-community,robovm/robovm-studio,adedayo/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,ernestp/consulo,fitermay/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,FHannes/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,dslomov/intellij-community,caot/intellij-community,hurricup/intellij-community,fitermay/intellij-community,holmes/intellij-community,xfournet/intellij-community,ryano144/intellij-community,apixandru/intellij-community,holmes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,supersven/intellij-community,fnouama/intellij-community,holmes/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,orekyuu/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,joewalnes/idea-community,retomerz/intellij-community,caot/intellij-community,vladmm/intellij-community,diorcety/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,holmes/intellij-community,vladmm/intellij-community,robovm/robovm-studio,clumsy/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,slisson/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,retomerz/intellij-community,izonder/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,holmes/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,caot/intellij-community,fitermay/intellij-community,apixandru/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,samthor/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,allotria/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,consulo/consulo,vvv1559/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,Distrotech/intellij-community,caot/intellij-community,ryano144/intellij-community,kool79/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,signed/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,allotria/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,slisson/intellij-community,samthor/intellij-community,ernestp/consulo,da1z/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,supersven/intellij-community,adedayo/intellij-community,da1z/intellij-community,apixandru/intellij-community,ryano144/intellij-community,semonte/intellij-community,ibinti/intellij-community,petteyg/intellij-community,kdwink/intellij-community,FHannes/intellij-community,clumsy/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,apixandru/intellij-community,diorcety/intellij-community,slisson/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,kool79/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,muntasirsyed/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 com.intellij.formatting; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.formatter.FormattingDocumentModelImpl; import com.intellij.psi.formatter.PsiBasedFormattingModel; import com.intellij.util.IncorrectOperationException; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; public class FormatterImpl extends FormatterEx implements ApplicationComponent, IndentFactory, WrapFactory, AlignmentFactory, SpacingFactory, FormattingModelFactory { private static final Logger LOG = Logger.getInstance("#com.intellij.formatting.FormatterImpl"); private int myIsDisabledCount = 0; private final IndentImpl NONE_INDENT = new IndentImpl(IndentImpl.Type.NONE, false); private final IndentImpl myAbsoluteNoneIndent = new IndentImpl(IndentImpl.Type.NONE, true); private final IndentImpl myLabelIndent = new IndentImpl(IndentImpl.Type.LABEL, false); private final IndentImpl myContinuationIndent = new IndentImpl(IndentImpl.Type.CONTINUATION, false); private final IndentImpl myContinutationWithoutFirstIndent = new IndentImpl(IndentImpl.Type.CONTINUATION_WITHOUT_FIRST, false); private final IndentImpl myAbsoluteLabelIndent = new IndentImpl(IndentImpl.Type.LABEL, true); private final IndentImpl myNormalIndent = new IndentImpl(IndentImpl.Type.NORMAL, false); private final SpacingImpl myReadOnlySpacing = new SpacingImpl(0, 0, 0, true, false, true, 0, false, 0); public FormatterImpl() { Indent.setFactory(this); Wrap.setFactory(this); Alignment.setFactory(this); Spacing.setFactory(this); FormattingModelProvider.setFactory(this); } public Alignment createAlignment() { return new AlignmentImpl(); } public Alignment createChildAlignment(final Alignment base) { AlignmentImpl result = new AlignmentImpl(); result.setParent(base); return result; } public Indent getNormalIndent() { return myNormalIndent; } public Indent getNoneIndent() { return NONE_INDENT; } public void format(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final CodeStyleSettings.IndentOptions javaIndentOptions, final FormatTextRanges affectedRanges) throws IncorrectOperationException { disableFormatting(); try { FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, affectedRanges); processor.setJavaIndentOptions(javaIndentOptions); processor.format(model); } finally { enableFormatting(); } } public Wrap createWrap(WrapType type, boolean wrapFirstElement) { return new WrapImpl(type, wrapFirstElement); } public Wrap createChildWrap(final Wrap parentWrap, final WrapType wrapType, final boolean wrapFirstElement) { final WrapImpl result = new WrapImpl(wrapType, wrapFirstElement); result.registerParent((WrapImpl)parentWrap); return result; } public Spacing createSpacing(int minOffset, int maxOffset, int minLineFeeds, final boolean keepLineBreaks, final int keepBlankLines) { return getSpacingImpl(minOffset, maxOffset, minLineFeeds, false, false, keepLineBreaks, keepBlankLines,false, 0); } public Spacing getReadOnlySpacing() { return myReadOnlySpacing; } public Spacing createDependentLFSpacing(int minOffset, int maxOffset, TextRange dependence, boolean keepLineBreaks, int keepBlankLines) { return new DependantSpacingImpl(minOffset, maxOffset, dependence, keepLineBreaks, keepBlankLines); } public void format(FormattingModel model, CodeStyleSettings settings, CodeStyleSettings.IndentOptions indentOptions, FormatTextRanges affectedRanges) throws IncorrectOperationException { disableFormatting(); try { new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, affectedRanges).format(model); } finally { enableFormatting(); } } public void formatWithoutModifications(FormattingDocumentModel model, Block rootBlock, CodeStyleSettings settings, CodeStyleSettings.IndentOptions indentOptions, TextRange affectedRange) throws IncorrectOperationException { disableFormatting(); try { new FormatProcessor(model, rootBlock, settings, indentOptions, new FormatTextRanges(affectedRange, true)).formatWithoutRealModifications(); } finally { enableFormatting(); } } public IndentInfo getWhiteSpaceBefore(final FormattingDocumentModel model, final Block block, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange affectedRange, final boolean mayChangeLineFeeds) { disableFormatting(); try { final FormatProcessor processor = new FormatProcessor(model, block, settings, indentOptions, new FormatTextRanges(affectedRange, true)); final LeafBlockWrapper blockBefore = processor.getBlockAfter(affectedRange.getStartOffset()); LOG.assertTrue(blockBefore != null); WhiteSpace whiteSpace = blockBefore.getWhiteSpace(); LOG.assertTrue(whiteSpace != null); if (!mayChangeLineFeeds) { whiteSpace.setLineFeedsAreReadOnly(); } processor.setAllWhiteSpacesAreReadOnly(); whiteSpace.setReadOnly(false); processor.formatWithoutRealModifications(); return new IndentInfo(whiteSpace.getLineFeeds(), whiteSpace.getIndentOffset(), whiteSpace.getSpaces()); } finally { enableFormatting(); } } public void adjustLineIndentsForRange(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange rangeToAdjust) { disableFormatting(); try { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, indentOptions, new FormatTextRanges(rangeToAdjust, true)); LeafBlockWrapper tokenBlock = processor.getFirstTokenBlock(); while (tokenBlock != null) { final WhiteSpace whiteSpace = tokenBlock.getWhiteSpace(); whiteSpace.setLineFeedsAreReadOnly(true); if (!whiteSpace.containsLineFeeds()) { whiteSpace.setIsReadOnly(true); } tokenBlock = tokenBlock.getNextBlock(); } processor.formatWithoutRealModifications(); processor.performModifications(model); } finally { enableFormatting(); } } public void formatAroundRange(final FormattingModel model, final CodeStyleSettings settings, final TextRange textRange, final FileType fileType) { disableFormatting(); try { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, settings.getIndentOptions(fileType), null); LeafBlockWrapper tokenBlock = processor.getFirstTokenBlock(); while (tokenBlock != null) { final WhiteSpace whiteSpace = tokenBlock.getWhiteSpace(); if (whiteSpace.getEndOffset() < textRange.getStartOffset()) { whiteSpace.setIsReadOnly(true); } else if (whiteSpace.getStartOffset() > textRange.getStartOffset() && whiteSpace.getEndOffset() < textRange.getEndOffset()){ if (whiteSpace.containsLineFeeds()) { whiteSpace.setLineFeedsAreReadOnly(true); } else { whiteSpace.setIsReadOnly(true); } } else if (whiteSpace.getEndOffset() > textRange.getEndOffset() + 1) { whiteSpace.setIsReadOnly(true); } tokenBlock = tokenBlock.getNextBlock(); } processor.formatWithoutRealModifications(); processor.performModifications(model); } finally{ enableFormatting(); } } public int adjustLineIndent(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final int offset, final TextRange affectedRange) throws IncorrectOperationException { disableFormatting(); if (model instanceof PsiBasedFormattingModel) { ((PsiBasedFormattingModel)model).canModifyAllWhiteSpaces(); } try { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, indentOptions, new FormatTextRanges(affectedRange, true), offset); final LeafBlockWrapper blockAfterOffset = processor.getBlockAfter(offset); if (blockAfterOffset != null && blockAfterOffset.contains(offset)) { return offset; } if (blockAfterOffset != null) { return adjustLineIndent(offset, documentModel, processor, indentOptions, model, blockAfterOffset.getWhiteSpace()); } else { return adjustLineIndent(offset, documentModel, processor, indentOptions, model, processor.getLastWhiteSpace()); } } finally { enableFormatting(); } } private static int adjustLineIndent( final int offset, final FormattingDocumentModel documentModel, final FormatProcessor processor, final CodeStyleSettings.IndentOptions indentOptions, final FormattingModel model, final WhiteSpace whiteSpace) { boolean wsContainsCaret = whiteSpace.getStartOffset() <= offset && offset < whiteSpace.getEndOffset(); int lineStartOffset = getLineStartOffset(offset, whiteSpace, documentModel); final IndentInfo indent = calcIndent(offset, documentModel, processor, whiteSpace); final String newWS = whiteSpace.generateWhiteSpace(indentOptions, lineStartOffset, indent).toString(); if (!whiteSpace.equalsToString(newWS)) { try { model.replaceWhiteSpace(whiteSpace.getTextRange(), newWS); } finally { model.commitChanges(); } } final int defaultOffset = offset - whiteSpace.getLength() + newWS.length(); if (wsContainsCaret) { final int ws = whiteSpace.getStartOffset() + CharArrayUtil.shiftForward(newWS, lineStartOffset - whiteSpace.getStartOffset(), " \t"); return Math.max(defaultOffset, ws); } else { return defaultOffset; } } private static boolean hasContentAfterLineBreak(final FormattingDocumentModel documentModel, final int offset, final WhiteSpace whiteSpace) { return documentModel.getLineNumber(offset) == documentModel.getLineNumber(whiteSpace.getEndOffset()) && documentModel.getTextLength() != offset; } public String getLineIndent(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final int offset, final TextRange affectedRange) { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, indentOptions, new FormatTextRanges(affectedRange, true), offset); final LeafBlockWrapper blockAfterOffset = processor.getBlockAfter(offset); if (blockAfterOffset != null) { final WhiteSpace whiteSpace = blockAfterOffset.getWhiteSpace(); final IndentInfo indent = calcIndent(offset, documentModel, processor, whiteSpace); return indent.generateNewWhiteSpace(indentOptions); } return null; } private static IndentInfo calcIndent(int offset, FormattingDocumentModel documentModel, FormatProcessor processor, WhiteSpace whiteSpace) { processor.setAllWhiteSpacesAreReadOnly(); whiteSpace.setLineFeedsAreReadOnly(true); final IndentInfo indent; if (hasContentAfterLineBreak(documentModel, offset, whiteSpace)) { whiteSpace.setReadOnly(false); processor.formatWithoutRealModifications(); indent = new IndentInfo(0, whiteSpace.getIndentOffset(), whiteSpace.getSpaces()); } else { indent = processor.getIndentAt(offset); } return indent; } public static String getText(final FormattingDocumentModel documentModel) { return getCharSequence(documentModel).toString(); } private static CharSequence getCharSequence(final FormattingDocumentModel documentModel) { return documentModel.getText(new TextRange(0, documentModel.getTextLength())); } private static int getLineStartOffset(final int offset, final WhiteSpace whiteSpace, final FormattingDocumentModel documentModel) { int lineStartOffset = offset; CharSequence text = getCharSequence(documentModel); lineStartOffset = CharArrayUtil.shiftBackwardUntil(text, lineStartOffset, " \t\n"); if (lineStartOffset > whiteSpace.getStartOffset()) { if (lineStartOffset >= text.length()) lineStartOffset = text.length() - 1; final int wsStart = whiteSpace.getStartOffset(); int prevEnd; if (text.charAt(lineStartOffset) == '\n' && wsStart <= (prevEnd = documentModel.getLineStartOffset(documentModel.getLineNumber(lineStartOffset - 1))) && documentModel.getText(new TextRange(prevEnd, lineStartOffset)).toString().trim().length() == 0 // ws consists of space only, it is not true for <![CDATA[ ) { lineStartOffset--; } lineStartOffset = CharArrayUtil.shiftBackward(text, lineStartOffset, "\t "); if (lineStartOffset < 0) lineStartOffset = 0; if (lineStartOffset != offset && text.charAt(lineStartOffset) == '\n') { lineStartOffset++; } } return lineStartOffset; } public void adjustTextRange(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange affectedRange, final boolean keepBlankLines, final boolean keepLineBreaks, final boolean changeWSBeforeFirstElement, final boolean changeLineFeedsBeforeFirstElement, @Nullable final IndentInfoStorage indentInfoStorage) { disableFormatting(); try { final FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, new FormatTextRanges(affectedRange, true)); LeafBlockWrapper current = processor.getFirstTokenBlock(); while (current != null) { WhiteSpace whiteSpace = current.getWhiteSpace(); if (!whiteSpace.isReadOnly()) { if (whiteSpace.getStartOffset() > affectedRange.getStartOffset()) { if (whiteSpace.containsLineFeeds() && indentInfoStorage != null) { whiteSpace.setLineFeedsAreReadOnly(true); current.setIndentFromParent(indentInfoStorage.getIndentInfo(current.getStartOffset())); } else { whiteSpace.setReadOnly(true); } } else { if (!changeWSBeforeFirstElement) { whiteSpace.setReadOnly(true); } else { if (!changeLineFeedsBeforeFirstElement) { whiteSpace.setLineFeedsAreReadOnly(true); } final SpacingImpl spaceProperty = current.getSpaceProperty(); if (spaceProperty != null) { boolean needChange = false; int newKeepLineBreaks = spaceProperty.getKeepBlankLines(); boolean newKeepLineBreaksFlag = spaceProperty.shouldKeepLineFeeds(); if (!keepLineBreaks) { needChange = true; newKeepLineBreaksFlag = false; } if (!keepBlankLines) { needChange = true; newKeepLineBreaks = 0; } if (needChange) { assert !(spaceProperty instanceof DependantSpacingImpl); current.setSpaceProperty( getSpacingImpl( spaceProperty.getMinSpaces(), spaceProperty.getMaxSpaces(), spaceProperty.getMinLineFeeds(), spaceProperty.isReadOnly(), spaceProperty.isSafe(), newKeepLineBreaksFlag, newKeepLineBreaks, false, spaceProperty.getPrefLineFeeds() ) ); } } } } } current = current.getNextBlock(); } processor.format(model); } finally { enableFormatting(); } } public void adjustTextRange(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange affectedRange) { disableFormatting(); try { final FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, new FormatTextRanges(affectedRange, true)); LeafBlockWrapper current = processor.getFirstTokenBlock(); while (current != null) { WhiteSpace whiteSpace = current.getWhiteSpace(); if (!whiteSpace.isReadOnly()) { if (whiteSpace.getStartOffset() > affectedRange.getStartOffset()) { whiteSpace.setReadOnly(true); } else { whiteSpace.setReadOnly(false); } } current = current.getNextBlock(); } processor.format(model); } finally { enableFormatting(); } } public void saveIndents(final FormattingModel model, final TextRange affectedRange, IndentInfoStorage storage, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions) { final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), block, settings, indentOptions, new FormatTextRanges(affectedRange, true)); LeafBlockWrapper current = processor.getFirstTokenBlock(); while (current != null) { WhiteSpace whiteSpace = current.getWhiteSpace(); if (!whiteSpace.isReadOnly() && whiteSpace.containsLineFeeds()) { storage.saveIndentInfo(current.calcIndentFromParent(), current.getStartOffset()); } current = current.getNextBlock(); } } public FormattingModel createFormattingModelForPsiFile(final PsiFile file, @NotNull final Block rootBlock, final CodeStyleSettings settings) { return new PsiBasedFormattingModel(file, rootBlock, FormattingDocumentModelImpl.createOn(file)); } public Indent getSpaceIndent(final int spaces) { return new IndentImpl(IndentImpl.Type.SPACES, false, spaces); } public Indent getAbsoluteLabelIndent() { return myAbsoluteLabelIndent; } public Spacing createSafeSpacing(final boolean shouldKeepLineBreaks, final int keepBlankLines) { return getSpacingImpl(0, 0, 0, false, true, shouldKeepLineBreaks, keepBlankLines, false, 0); } public Spacing createKeepingFirstColumnSpacing(final int minSpace, final int maxSpace, final boolean keepLineBreaks, final int keepBlankLines) { return getSpacingImpl(minSpace, maxSpace, -1, false, false, keepLineBreaks, keepBlankLines, true, 0); } public Spacing createSpacing(final int minSpaces, final int maxSpaces, final int minLineFeeds, final boolean keepLineBreaks, final int keepBlankLines, final int prefLineFeeds) { return getSpacingImpl(minSpaces, maxSpaces, -1, false, false, keepLineBreaks, keepBlankLines, false, prefLineFeeds); } private final Map<SpacingImpl,SpacingImpl> ourSharedProperties = new HashMap<SpacingImpl,SpacingImpl>(); private final SpacingImpl ourSharedSpacing = new SpacingImpl(-1,-1,-1,false,false,false,-1,false,0); private SpacingImpl getSpacingImpl(final int minSpaces, final int maxSpaces, final int minLineFeeds, final boolean readOnly, final boolean safe, final boolean keepLineBreaksFlag, final int keepLineBreaks, final boolean keepFirstColumn, int prefLineFeeds) { synchronized(this) { ourSharedSpacing.init(minSpaces, maxSpaces, minLineFeeds, readOnly, safe, keepLineBreaksFlag, keepLineBreaks, keepFirstColumn, prefLineFeeds); SpacingImpl spacing = ourSharedProperties.get(ourSharedSpacing); if (spacing == null) { spacing = new SpacingImpl(minSpaces, maxSpaces, minLineFeeds, readOnly, safe, keepLineBreaksFlag, keepLineBreaks, keepFirstColumn, prefLineFeeds); ourSharedProperties.put(spacing, spacing); } return spacing; } } @NotNull public String getComponentName() { return "FormatterEx"; } public void initComponent() { } public void disposeComponent() { } public Indent getAbsoluteNoneIndent() { return myAbsoluteNoneIndent; } public Indent getLabelIndent() { return myLabelIndent; } public Indent getContinuationIndent() { return myContinuationIndent; } public Indent getContinuationWithoutFirstIndent()//is default { return myContinutationWithoutFirstIndent; } private final Object DISABLING_LOCK = new Object(); public boolean isDisabled() { synchronized (DISABLING_LOCK) { return myIsDisabledCount > 0; } } public void disableFormatting() { synchronized (DISABLING_LOCK) { myIsDisabledCount++; } } public void enableFormatting() { synchronized (DISABLING_LOCK) { if (myIsDisabledCount <= 0) { LOG.error("enableFormatting()/disableFormatting() not paired. DisabledLevel = " + myIsDisabledCount); } myIsDisabledCount--; } } }
platform/lang-impl/src/com/intellij/formatting/FormatterImpl.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 com.intellij.formatting; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.formatter.FormattingDocumentModelImpl; import com.intellij.psi.formatter.PsiBasedFormattingModel; import com.intellij.util.IncorrectOperationException; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; public class FormatterImpl extends FormatterEx implements ApplicationComponent, IndentFactory, WrapFactory, AlignmentFactory, SpacingFactory, FormattingModelFactory { private static final Logger LOG = Logger.getInstance("#com.intellij.formatting.FormatterImpl"); private int myIsDisabledCount = 0; private final IndentImpl NONE_INDENT = new IndentImpl(IndentImpl.Type.NONE, false); private final IndentImpl myAbsoluteNoneIndent = new IndentImpl(IndentImpl.Type.NONE, true); private final IndentImpl myLabelIndent = new IndentImpl(IndentImpl.Type.LABEL, false); private final IndentImpl myContinuationIndent = new IndentImpl(IndentImpl.Type.CONTINUATION, false); private final IndentImpl myContinutationWithoutFirstIndent = new IndentImpl(IndentImpl.Type.CONTINUATION_WITHOUT_FIRST, false); private final IndentImpl myAbsoluteLabelIndent = new IndentImpl(IndentImpl.Type.LABEL, true); private final IndentImpl myNormalIndent = new IndentImpl(IndentImpl.Type.NORMAL, false); private final SpacingImpl myReadOnlySpacing = new SpacingImpl(0, 0, 0, true, false, true, 0, false, 0); public FormatterImpl() { Indent.setFactory(this); Wrap.setFactory(this); Alignment.setFactory(this); Spacing.setFactory(this); FormattingModelProvider.setFactory(this); } public Alignment createAlignment() { return new AlignmentImpl(AlignmentImpl.Type.NORMAL); } public Alignment createChildAlignment(final Alignment base) { AlignmentImpl result = new AlignmentImpl(AlignmentImpl.Type.NORMAL); result.setParent(base); return result; } public Indent getNormalIndent() { return myNormalIndent; } public Indent getNoneIndent() { return NONE_INDENT; } public void format(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final CodeStyleSettings.IndentOptions javaIndentOptions, final FormatTextRanges affectedRanges) throws IncorrectOperationException { disableFormatting(); try { FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, affectedRanges); processor.setJavaIndentOptions(javaIndentOptions); processor.format(model); } finally { enableFormatting(); } } public Wrap createWrap(WrapType type, boolean wrapFirstElement) { return new WrapImpl(type, wrapFirstElement); } public Wrap createChildWrap(final Wrap parentWrap, final WrapType wrapType, final boolean wrapFirstElement) { final WrapImpl result = new WrapImpl(wrapType, wrapFirstElement); result.registerParent((WrapImpl)parentWrap); return result; } public Spacing createSpacing(int minOffset, int maxOffset, int minLineFeeds, final boolean keepLineBreaks, final int keepBlankLines) { return getSpacingImpl(minOffset, maxOffset, minLineFeeds, false, false, keepLineBreaks, keepBlankLines,false, 0); } public Spacing getReadOnlySpacing() { return myReadOnlySpacing; } public Spacing createDependentLFSpacing(int minOffset, int maxOffset, TextRange dependence, boolean keepLineBreaks, int keepBlankLines) { return new DependantSpacingImpl(minOffset, maxOffset, dependence, keepLineBreaks, keepBlankLines); } public void format(FormattingModel model, CodeStyleSettings settings, CodeStyleSettings.IndentOptions indentOptions, FormatTextRanges affectedRanges) throws IncorrectOperationException { disableFormatting(); try { new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, affectedRanges).format(model); } finally { enableFormatting(); } } public void formatWithoutModifications(FormattingDocumentModel model, Block rootBlock, CodeStyleSettings settings, CodeStyleSettings.IndentOptions indentOptions, TextRange affectedRange) throws IncorrectOperationException { disableFormatting(); try { new FormatProcessor(model, rootBlock, settings, indentOptions, new FormatTextRanges(affectedRange, true)).formatWithoutRealModifications(); } finally { enableFormatting(); } } public IndentInfo getWhiteSpaceBefore(final FormattingDocumentModel model, final Block block, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange affectedRange, final boolean mayChangeLineFeeds) { disableFormatting(); try { final FormatProcessor processor = new FormatProcessor(model, block, settings, indentOptions, new FormatTextRanges(affectedRange, true)); final LeafBlockWrapper blockBefore = processor.getBlockAfter(affectedRange.getStartOffset()); LOG.assertTrue(blockBefore != null); WhiteSpace whiteSpace = blockBefore.getWhiteSpace(); LOG.assertTrue(whiteSpace != null); if (!mayChangeLineFeeds) { whiteSpace.setLineFeedsAreReadOnly(); } processor.setAllWhiteSpacesAreReadOnly(); whiteSpace.setReadOnly(false); processor.formatWithoutRealModifications(); return new IndentInfo(whiteSpace.getLineFeeds(), whiteSpace.getIndentOffset(), whiteSpace.getSpaces()); } finally { enableFormatting(); } } public void adjustLineIndentsForRange(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange rangeToAdjust) { disableFormatting(); try { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, indentOptions, new FormatTextRanges(rangeToAdjust, true)); LeafBlockWrapper tokenBlock = processor.getFirstTokenBlock(); while (tokenBlock != null) { final WhiteSpace whiteSpace = tokenBlock.getWhiteSpace(); whiteSpace.setLineFeedsAreReadOnly(true); if (!whiteSpace.containsLineFeeds()) { whiteSpace.setIsReadOnly(true); } tokenBlock = tokenBlock.getNextBlock(); } processor.formatWithoutRealModifications(); processor.performModifications(model); } finally { enableFormatting(); } } public void formatAroundRange(final FormattingModel model, final CodeStyleSettings settings, final TextRange textRange, final FileType fileType) { disableFormatting(); try { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, settings.getIndentOptions(fileType), null); LeafBlockWrapper tokenBlock = processor.getFirstTokenBlock(); while (tokenBlock != null) { final WhiteSpace whiteSpace = tokenBlock.getWhiteSpace(); if (whiteSpace.getEndOffset() < textRange.getStartOffset()) { whiteSpace.setIsReadOnly(true); } else if (whiteSpace.getStartOffset() > textRange.getStartOffset() && whiteSpace.getEndOffset() < textRange.getEndOffset()){ if (whiteSpace.containsLineFeeds()) { whiteSpace.setLineFeedsAreReadOnly(true); } else { whiteSpace.setIsReadOnly(true); } } else if (whiteSpace.getEndOffset() > textRange.getEndOffset() + 1) { whiteSpace.setIsReadOnly(true); } tokenBlock = tokenBlock.getNextBlock(); } processor.formatWithoutRealModifications(); processor.performModifications(model); } finally{ enableFormatting(); } } public int adjustLineIndent(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final int offset, final TextRange affectedRange) throws IncorrectOperationException { disableFormatting(); if (model instanceof PsiBasedFormattingModel) { ((PsiBasedFormattingModel)model).canModifyAllWhiteSpaces(); } try { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, indentOptions, new FormatTextRanges(affectedRange, true), offset); final LeafBlockWrapper blockAfterOffset = processor.getBlockAfter(offset); if (blockAfterOffset != null && blockAfterOffset.contains(offset)) { return offset; } if (blockAfterOffset != null) { return adjustLineIndent(offset, documentModel, processor, indentOptions, model, blockAfterOffset.getWhiteSpace()); } else { return adjustLineIndent(offset, documentModel, processor, indentOptions, model, processor.getLastWhiteSpace()); } } finally { enableFormatting(); } } private static int adjustLineIndent( final int offset, final FormattingDocumentModel documentModel, final FormatProcessor processor, final CodeStyleSettings.IndentOptions indentOptions, final FormattingModel model, final WhiteSpace whiteSpace) { boolean wsContainsCaret = whiteSpace.getStartOffset() <= offset && offset < whiteSpace.getEndOffset(); int lineStartOffset = getLineStartOffset(offset, whiteSpace, documentModel); final IndentInfo indent = calcIndent(offset, documentModel, processor, whiteSpace); final String newWS = whiteSpace.generateWhiteSpace(indentOptions, lineStartOffset, indent).toString(); if (!whiteSpace.equalsToString(newWS)) { try { model.replaceWhiteSpace(whiteSpace.getTextRange(), newWS); } finally { model.commitChanges(); } } final int defaultOffset = offset - whiteSpace.getLength() + newWS.length(); if (wsContainsCaret) { final int ws = whiteSpace.getStartOffset() + CharArrayUtil.shiftForward(newWS, lineStartOffset - whiteSpace.getStartOffset(), " \t"); return Math.max(defaultOffset, ws); } else { return defaultOffset; } } private static boolean hasContentAfterLineBreak(final FormattingDocumentModel documentModel, final int offset, final WhiteSpace whiteSpace) { return documentModel.getLineNumber(offset) == documentModel.getLineNumber(whiteSpace.getEndOffset()) && documentModel.getTextLength() != offset; } public String getLineIndent(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final int offset, final TextRange affectedRange) { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(documentModel, block, settings, indentOptions, new FormatTextRanges(affectedRange, true), offset); final LeafBlockWrapper blockAfterOffset = processor.getBlockAfter(offset); if (blockAfterOffset != null) { final WhiteSpace whiteSpace = blockAfterOffset.getWhiteSpace(); final IndentInfo indent = calcIndent(offset, documentModel, processor, whiteSpace); return indent.generateNewWhiteSpace(indentOptions); } return null; } private static IndentInfo calcIndent(int offset, FormattingDocumentModel documentModel, FormatProcessor processor, WhiteSpace whiteSpace) { processor.setAllWhiteSpacesAreReadOnly(); whiteSpace.setLineFeedsAreReadOnly(true); final IndentInfo indent; if (hasContentAfterLineBreak(documentModel, offset, whiteSpace)) { whiteSpace.setReadOnly(false); processor.formatWithoutRealModifications(); indent = new IndentInfo(0, whiteSpace.getIndentOffset(), whiteSpace.getSpaces()); } else { indent = processor.getIndentAt(offset); } return indent; } public static String getText(final FormattingDocumentModel documentModel) { return getCharSequence(documentModel).toString(); } private static CharSequence getCharSequence(final FormattingDocumentModel documentModel) { return documentModel.getText(new TextRange(0, documentModel.getTextLength())); } private static int getLineStartOffset(final int offset, final WhiteSpace whiteSpace, final FormattingDocumentModel documentModel) { int lineStartOffset = offset; CharSequence text = getCharSequence(documentModel); lineStartOffset = CharArrayUtil.shiftBackwardUntil(text, lineStartOffset, " \t\n"); if (lineStartOffset > whiteSpace.getStartOffset()) { if (lineStartOffset >= text.length()) lineStartOffset = text.length() - 1; final int wsStart = whiteSpace.getStartOffset(); int prevEnd; if (text.charAt(lineStartOffset) == '\n' && wsStart <= (prevEnd = documentModel.getLineStartOffset(documentModel.getLineNumber(lineStartOffset - 1))) && documentModel.getText(new TextRange(prevEnd, lineStartOffset)).toString().trim().length() == 0 // ws consists of space only, it is not true for <![CDATA[ ) { lineStartOffset--; } lineStartOffset = CharArrayUtil.shiftBackward(text, lineStartOffset, "\t "); if (lineStartOffset < 0) lineStartOffset = 0; if (lineStartOffset != offset && text.charAt(lineStartOffset) == '\n') { lineStartOffset++; } } return lineStartOffset; } public void adjustTextRange(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange affectedRange, final boolean keepBlankLines, final boolean keepLineBreaks, final boolean changeWSBeforeFirstElement, final boolean changeLineFeedsBeforeFirstElement, @Nullable final IndentInfoStorage indentInfoStorage) { disableFormatting(); try { final FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, new FormatTextRanges(affectedRange, true)); LeafBlockWrapper current = processor.getFirstTokenBlock(); while (current != null) { WhiteSpace whiteSpace = current.getWhiteSpace(); if (!whiteSpace.isReadOnly()) { if (whiteSpace.getStartOffset() > affectedRange.getStartOffset()) { if (whiteSpace.containsLineFeeds() && indentInfoStorage != null) { whiteSpace.setLineFeedsAreReadOnly(true); current.setIndentFromParent(indentInfoStorage.getIndentInfo(current.getStartOffset())); } else { whiteSpace.setReadOnly(true); } } else { if (!changeWSBeforeFirstElement) { whiteSpace.setReadOnly(true); } else { if (!changeLineFeedsBeforeFirstElement) { whiteSpace.setLineFeedsAreReadOnly(true); } final SpacingImpl spaceProperty = current.getSpaceProperty(); if (spaceProperty != null) { boolean needChange = false; int newKeepLineBreaks = spaceProperty.getKeepBlankLines(); boolean newKeepLineBreaksFlag = spaceProperty.shouldKeepLineFeeds(); if (!keepLineBreaks) { needChange = true; newKeepLineBreaksFlag = false; } if (!keepBlankLines) { needChange = true; newKeepLineBreaks = 0; } if (needChange) { assert !(spaceProperty instanceof DependantSpacingImpl); current.setSpaceProperty( getSpacingImpl( spaceProperty.getMinSpaces(), spaceProperty.getMaxSpaces(), spaceProperty.getMinLineFeeds(), spaceProperty.isReadOnly(), spaceProperty.isSafe(), newKeepLineBreaksFlag, newKeepLineBreaks, false, spaceProperty.getPrefLineFeeds() ) ); } } } } } current = current.getNextBlock(); } processor.format(model); } finally { enableFormatting(); } } public void adjustTextRange(final FormattingModel model, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions, final TextRange affectedRange) { disableFormatting(); try { final FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), model.getRootBlock(), settings, indentOptions, new FormatTextRanges(affectedRange, true)); LeafBlockWrapper current = processor.getFirstTokenBlock(); while (current != null) { WhiteSpace whiteSpace = current.getWhiteSpace(); if (!whiteSpace.isReadOnly()) { if (whiteSpace.getStartOffset() > affectedRange.getStartOffset()) { whiteSpace.setReadOnly(true); } else { whiteSpace.setReadOnly(false); } } current = current.getNextBlock(); } processor.format(model); } finally { enableFormatting(); } } public void saveIndents(final FormattingModel model, final TextRange affectedRange, IndentInfoStorage storage, final CodeStyleSettings settings, final CodeStyleSettings.IndentOptions indentOptions) { final Block block = model.getRootBlock(); final FormatProcessor processor = new FormatProcessor(model.getDocumentModel(), block, settings, indentOptions, new FormatTextRanges(affectedRange, true)); LeafBlockWrapper current = processor.getFirstTokenBlock(); while (current != null) { WhiteSpace whiteSpace = current.getWhiteSpace(); if (!whiteSpace.isReadOnly() && whiteSpace.containsLineFeeds()) { storage.saveIndentInfo(current.calcIndentFromParent(), current.getStartOffset()); } current = current.getNextBlock(); } } public FormattingModel createFormattingModelForPsiFile(final PsiFile file, @NotNull final Block rootBlock, final CodeStyleSettings settings) { return new PsiBasedFormattingModel(file, rootBlock, FormattingDocumentModelImpl.createOn(file)); } public Indent getSpaceIndent(final int spaces) { return new IndentImpl(IndentImpl.Type.SPACES, false, spaces); } public Indent getAbsoluteLabelIndent() { return myAbsoluteLabelIndent; } public Spacing createSafeSpacing(final boolean shouldKeepLineBreaks, final int keepBlankLines) { return getSpacingImpl(0, 0, 0, false, true, shouldKeepLineBreaks, keepBlankLines, false, 0); } public Spacing createKeepingFirstColumnSpacing(final int minSpace, final int maxSpace, final boolean keepLineBreaks, final int keepBlankLines) { return getSpacingImpl(minSpace, maxSpace, -1, false, false, keepLineBreaks, keepBlankLines, true, 0); } public Spacing createSpacing(final int minSpaces, final int maxSpaces, final int minLineFeeds, final boolean keepLineBreaks, final int keepBlankLines, final int prefLineFeeds) { return getSpacingImpl(minSpaces, maxSpaces, -1, false, false, keepLineBreaks, keepBlankLines, false, prefLineFeeds); } private final Map<SpacingImpl,SpacingImpl> ourSharedProperties = new HashMap<SpacingImpl,SpacingImpl>(); private final SpacingImpl ourSharedSpacing = new SpacingImpl(-1,-1,-1,false,false,false,-1,false,0); private SpacingImpl getSpacingImpl(final int minSpaces, final int maxSpaces, final int minLineFeeds, final boolean readOnly, final boolean safe, final boolean keepLineBreaksFlag, final int keepLineBreaks, final boolean keepFirstColumn, int prefLineFeeds) { synchronized(this) { ourSharedSpacing.init(minSpaces, maxSpaces, minLineFeeds, readOnly, safe, keepLineBreaksFlag, keepLineBreaks, keepFirstColumn, prefLineFeeds); SpacingImpl spacing = ourSharedProperties.get(ourSharedSpacing); if (spacing == null) { spacing = new SpacingImpl(minSpaces, maxSpaces, minLineFeeds, readOnly, safe, keepLineBreaksFlag, keepLineBreaks, keepFirstColumn, prefLineFeeds); ourSharedProperties.put(spacing, spacing); } return spacing; } } @NotNull public String getComponentName() { return "FormatterEx"; } public void initComponent() { } public void disposeComponent() { } public Indent getAbsoluteNoneIndent() { return myAbsoluteNoneIndent; } public Indent getLabelIndent() { return myLabelIndent; } public Indent getContinuationIndent() { return myContinuationIndent; } public Indent getContinuationWithoutFirstIndent()//is default { return myContinutationWithoutFirstIndent; } private final Object DISABLING_LOCK = new Object(); public boolean isDisabled() { synchronized (DISABLING_LOCK) { return myIsDisabledCount > 0; } } public void disableFormatting() { synchronized (DISABLING_LOCK) { myIsDisabledCount++; } } public void enableFormatting() { synchronized (DISABLING_LOCK) { if (myIsDisabledCount <= 0) { LOG.error("enableFormatting()/disableFormatting() not paired. DisabledLevel = " + myIsDisabledCount); } myIsDisabledCount--; } } }
IDEA-54671 Alignment of Call Arguments does not work. Adopted to AlignmentImpl constructor signature change
platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java
IDEA-54671 Alignment of Call Arguments does not work.
<ide><path>latform/lang-impl/src/com/intellij/formatting/FormatterImpl.java <ide> } <ide> <ide> public Alignment createAlignment() { <del> return new AlignmentImpl(AlignmentImpl.Type.NORMAL); <add> return new AlignmentImpl(); <ide> } <ide> <ide> public Alignment createChildAlignment(final Alignment base) { <del> AlignmentImpl result = new AlignmentImpl(AlignmentImpl.Type.NORMAL); <add> AlignmentImpl result = new AlignmentImpl(); <ide> result.setParent(base); <ide> return result; <ide> }
Java
apache-2.0
134919615cce88c5b906867631972f257d0c32b5
0
ecsec/open-ecard,ecsec/open-ecard,ecsec/open-ecard
/**************************************************************************** * Copyright (C) 2012-2018 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH ([email protected]) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.richclient; import ch.qos.logback.core.joran.spi.JoranException; import com.sun.jna.Platform; import com.sun.jna.platform.win32.Advapi32Util; import com.sun.jna.platform.win32.Win32Exception; import com.sun.jna.platform.win32.WinReg; import iso.std.iso_iec._24727.tech.schema.EstablishContext; import iso.std.iso_iec._24727.tech.schema.EstablishContextResponse; import iso.std.iso_iec._24727.tech.schema.Initialize; import iso.std.iso_iec._24727.tech.schema.ReleaseContext; import iso.std.iso_iec._24727.tech.schema.Terminate; import java.io.IOException; import java.net.BindException; import java.util.List; import java.net.Socket; import java.net.URL; import java.nio.charset.UnsupportedCharsetException; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.FutureTask; import javax.annotation.Nullable; import org.openecard.addon.AddonManager; import org.openecard.apache.http.HttpException; import org.openecard.apache.http.HttpResponse; import org.openecard.apache.http.entity.ContentType; import org.openecard.apache.http.entity.StringEntity; import org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest; import org.openecard.apache.http.protocol.BasicHttpContext; import org.openecard.apache.http.protocol.HttpContext; import org.openecard.apache.http.protocol.HttpRequestExecutor; import org.openecard.common.AppVersion; import org.openecard.common.ClientEnv; import org.openecard.common.ECardConstants; import org.openecard.common.I18n; import org.openecard.common.OpenecardProperties; import org.openecard.common.WSHelper; import org.openecard.common.sal.state.CardStateMap; import org.openecard.common.sal.state.SALStateCallback; import org.openecard.control.binding.http.HttpBinding; import org.openecard.common.event.EventDispatcherImpl; import org.openecard.common.event.EventType; import org.openecard.gui.message.DialogType; import org.openecard.gui.swing.SwingDialogWrapper; import org.openecard.gui.swing.SwingUserConsent; import org.openecard.gui.swing.common.GUIDefaults; import org.openecard.ifd.protocol.pace.PACEProtocolFactory; import org.openecard.ifd.scio.IFD; import org.openecard.management.TinyManagement; import org.openecard.recognition.CardRecognitionImpl; import org.openecard.richclient.gui.AppTray; import org.openecard.richclient.gui.SettingsAndDefaultViewWrapper; import org.openecard.mdlw.sal.MiddlewareSAL; import org.openecard.mdlw.event.MwStateCallback; import org.openecard.mdlw.sal.config.MiddlewareConfigLoader; import org.openecard.mdlw.sal.config.MiddlewareSALConfig; import org.openecard.sal.SelectorSAL; import org.openecard.sal.TinySAL; import org.openecard.transport.dispatcher.MessageDispatcher; import org.openecard.transport.httpcore.HttpRequestHelper; import org.openecard.transport.httpcore.HttpUtils; import org.openecard.transport.httpcore.StreamHttpClientConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Moritz Horsch * @author Johannes Schmölz * @author Hans-Martin Haase * @author René Lottes * @author Tobias Wich */ public final class RichClient { private static final Logger LOG; private static final I18n LANG; // Tray icon private AppTray tray; // Control interface private HttpBinding httpBinding; // Client environment private ClientEnv env = new ClientEnv(); // Interface Device Layer (IFD) private IFD ifd; // Service Access Layer (SAL) private SelectorSAL sal; // AddonManager private AddonManager manager; // EventDispatcherImpl private EventDispatcherImpl eventDispatcher; // Card recognition private CardRecognitionImpl recognition; // card states private CardStateMap cardStates; // ContextHandle determines a specific IFD layer context private byte[] contextHandle; static { try { // load logger config from HOME if set LogbackConfig.load(); } catch (IOException | JoranException ex) { System.err.println("Failed to load logback config from user config."); ex.printStackTrace(System.err); try { LogbackConfig.loadDefault(); } catch (JoranException ex2) { System.err.println("Failed to load logback default config."); ex.printStackTrace(System.err); } } LOG = LoggerFactory.getLogger(RichClient.class.getName()); LANG = I18n.getTranslation("richclient"); } public static void main(String[] args) { LOG.info("Starting {} {} ...", AppVersion.getName(), AppVersion.getVersion()); RichClient client = new RichClient(); client.setup(); } public void setup() { GUIDefaults.initialize(); String title = LANG.translationForKey("client.startup.failed.headline", AppVersion.getName()); String message = null; // Set up GUI SwingUserConsent gui = new SwingUserConsent(new SwingDialogWrapper()); try { tray = new AppTray(this); tray.beginSetup(); // Set up client environment env = new ClientEnv(); // Set up the Dispatcher MessageDispatcher dispatcher = new MessageDispatcher(env); env.setDispatcher(dispatcher); // Set up EventDispatcherImpl eventDispatcher = new EventDispatcherImpl(); env.setEventDispatcher(eventDispatcher); // Set up Management TinyManagement management = new TinyManagement(env); env.setManagement(management); // Set up MiddlewareConfig MiddlewareConfigLoader mwConfigLoader = new MiddlewareConfigLoader(); List<MiddlewareSALConfig> mwSALConfigs = mwConfigLoader.getMiddlewareSALConfigs(); // Set up CardRecognitionImpl recognition = new CardRecognitionImpl(env); recognition.setGUI(gui); env.setRecognition(recognition); // Set up StateCallbacks cardStates = new CardStateMap(); SALStateCallback salCallback = new SALStateCallback(env, cardStates); eventDispatcher.add(salCallback); MwStateCallback mwCallback = new MwStateCallback(env, cardStates, mwConfigLoader); eventDispatcher.add(mwCallback); // Set up the IFD ifd = new IFD(); ifd.addProtocol(ECardConstants.Protocol.PACE, new PACEProtocolFactory()); ifd.setGUI(gui); ifd.setEnvironment(env); env.setIFD(ifd); // Set up SAL TinySAL mainSal = new TinySAL(env, cardStates); mainSal.setGUI(gui); sal = new SelectorSAL(mainSal, env); env.setSAL(sal); env.setCIFProvider(sal); // Set up Middleware SAL for (MiddlewareSALConfig mwSALConfig : mwSALConfigs) { if (! mwSALConfig.isDisabled()) { MiddlewareSAL mwSal = new MiddlewareSAL(env, cardStates, mwSALConfig); mwSal.setGui(gui); sal.addSpecializedSAL(mwSal); } } // Start up control interface SettingsAndDefaultViewWrapper guiWrapper = new SettingsAndDefaultViewWrapper(); try { manager = new AddonManager(env, gui, cardStates, guiWrapper); guiWrapper.setAddonManager(manager); mainSal.setAddonManager(manager); // initialize http binding int port = 24727; boolean dispatcherMode = false; WinReg.HKEY hk = WinReg.HKEY_LOCAL_MACHINE; String regPath = "SOFTWARE\\OeC"; if (Platform.isWindows()) { LOG.debug("Checking if dispatcher mode should be used."); try { if (regKeyExists(hk, regPath, "Dispatcher_Mode")) { String value = Advapi32Util.registryGetStringValue(hk, regPath, "Dispatcher_Mode"); dispatcherMode = Boolean.valueOf(value); // let socket chose its port port = 0; } } catch (Win32Exception ex) { LOG.warn("Failed to read 'Dispatcher_Mode' registry key. Using normal operation mode.", ex); } } if (! dispatcherMode) { try { port = Integer.parseInt(OpenecardProperties.getProperty("http-binding.port")); } catch (NumberFormatException ex) { LOG.warn("Error in config file, HTTP binding port is malformed."); } } // start HTTP server httpBinding = new HttpBinding(port); httpBinding.setAddonManager(manager); httpBinding.start(); if (dispatcherMode) { long waitTime = getRegInt(hk, regPath, "Retry_Wait_Time", 5000L); long timeout = getRegInt(hk, regPath, "DP_Timeout", 3600000L); // try to register with dispatcher service LOG.debug("Trying to register HTTP binding port with dispatcher service."); final int realPort = httpBinding.getPort(); final URL regUrl = new URL("http://127.0.0.1:24727/dp/register"); FutureTask ft = new FutureTask(new DispatcherRegistrator(regUrl, realPort, waitTime, timeout), 1); Thread registerThread = new Thread(ft, "Register-Dispatcher-Service"); registerThread.setDaemon(true); registerThread.start(); // wait until thread is finished ft.get(); } } catch (BindException e) { message = LANG.translationForKey("client.startup.failed.portinuse", AppVersion.getName()); throw e; } tray.endSetup(env, manager); // Initialize the EventManager eventDispatcher.add(tray.status(), EventType.TERMINAL_ADDED, EventType.TERMINAL_REMOVED, EventType.CARD_INSERTED, EventType.CARD_RECOGNIZED, EventType.CARD_REMOVED); // start event dispatcher eventDispatcher.start(); // initialize SAL WSHelper.checkResult(sal.initialize(new Initialize())); // Perform an EstablishContext to get a ContextHandle try { EstablishContext establishContext = new EstablishContext(); EstablishContextResponse establishContextResponse = ifd.establishContext(establishContext); WSHelper.checkResult(establishContextResponse); contextHandle = establishContextResponse.getContextHandle(); } catch (WSHelper.WSException ex) { message = LANG.translationForKey("client.startup.failed.nocontext"); throw ex; } // perform GC to bring down originally allocated memory new Timer().schedule(new GCTask(), 5000); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); if (message == null || message.isEmpty()) { // Add exception message if no custom message is set message = ex.getMessage(); } // Show dialog to the user and shut down the client String msg = String.format("%s%n%n%s", title, message); gui.obtainMessageDialog().showMessageDialog(msg, AppVersion.getName(), DialogType.ERROR_MESSAGE); teardown(); } catch (Throwable ex) { LOG.error("Unexpected error occurred. Exiting client.", ex); System.exit(1); } } private static class GCTask extends TimerTask { @Override public void run() { System.gc(); System.runFinalization(); System.gc(); // repeat every 5 minutes new Timer().schedule(new GCTask(), 5 * 60 * 1000); } } public void teardown() { try { if (eventDispatcher != null) { eventDispatcher.terminate(); } // TODO: shutdown addon manager and related components? if (manager != null) { manager.shutdown(); } // shutdown control modules if (httpBinding != null) { httpBinding.stop(); } // shutdown SAL if (sal != null) { Terminate terminate = new Terminate(); sal.terminate(terminate); } // shutdown IFD if (ifd != null && contextHandle != null) { ReleaseContext releaseContext = new ReleaseContext(); releaseContext.setContextHandle(contextHandle); ifd.releaseContext(releaseContext); } } catch (Exception ex) { LOG.error("Failed to stop Richclient.", ex); } System.exit(0); } private static class DispatcherRegistrator implements Runnable { private final URL regUrl; private final int bindingPort; private final long waitTime; private final long timeout; public DispatcherRegistrator(URL regUrl, int bindingPort, long waitTime, long timeout) { this.regUrl = regUrl; this.bindingPort = bindingPort; this.waitTime = waitTime; this.timeout = timeout; } @Override public void run() { long startTime = System.currentTimeMillis(); HttpRequestExecutor exec = new HttpRequestExecutor(); HttpContext httpCtx = new BasicHttpContext(); do { try { int port = regUrl.getPort() == -1 ? regUrl.getDefaultPort() : regUrl.getPort(); Socket sock = new Socket(regUrl.getHost(), port); StreamHttpClientConnection con = new StreamHttpClientConnection(sock.getInputStream(), sock.getOutputStream()); BasicHttpEntityEnclosingRequest req; req = new BasicHttpEntityEnclosingRequest("POST", regUrl.getFile()); // prepare request HttpRequestHelper.setDefaultHeader(req, regUrl); ContentType reqContentType = ContentType.create("application/x-www-form-urlencoded", "UTF-8"); String bodyStr = String.format("Port=%d", bindingPort); StringEntity bodyEnt = new StringEntity(bodyStr, reqContentType); req.setEntity(bodyEnt); req.setHeader(bodyEnt.getContentType()); req.setHeader("Content-Length", String.valueOf(bodyEnt.getContentLength())); // send request HttpUtils.dumpHttpRequest(LOG, req); HttpResponse response = exec.execute(req, con, httpCtx); HttpUtils.dumpHttpResponse(LOG, response, null); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204) { return; } else { String msg = "Execution of dispatcher registration is not successful (code={}), trying again ..."; LOG.info(msg, statusCode); } } catch (HttpException | IOException | UnsupportedCharsetException ex) { LOG.error("Failed to send dispatcher registration reguest.", ex); } // terminate in case there is no time left long now = System.currentTimeMillis(); if (now - startTime > timeout) { throw new RuntimeException("Failed to register with dispatcher service in a timely manner."); } // wait a bit and try again try { Thread.sleep(waitTime); } catch (InterruptedException ex) { LOG.info("Dispatcher registration interrupted."); return; } } while (true); } }; private static boolean regKeyExists(WinReg.HKEY hk, String key, String value) { return Advapi32Util.registryKeyExists(hk, key) && Advapi32Util.registryValueExists(hk, key, value); } private static Long getRegInt(WinReg.HKEY hk, String key, String value, @Nullable Long defaultValue) { try { if (regKeyExists(hk, key, value)) { return (long) Advapi32Util.registryGetIntValue(hk, key, value); } } catch (Win32Exception ex) { LOG.debug("Registry key {}\\{} does not exist or has wrong type.", key, value); } return defaultValue; } }
clients/richclient/src/main/java/org/openecard/richclient/RichClient.java
/**************************************************************************** * Copyright (C) 2012-2018 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH ([email protected]) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.richclient; import ch.qos.logback.core.joran.spi.JoranException; import com.sun.jna.Platform; import com.sun.jna.platform.win32.Advapi32Util; import com.sun.jna.platform.win32.Win32Exception; import com.sun.jna.platform.win32.WinReg; import iso.std.iso_iec._24727.tech.schema.EstablishContext; import iso.std.iso_iec._24727.tech.schema.EstablishContextResponse; import iso.std.iso_iec._24727.tech.schema.Initialize; import iso.std.iso_iec._24727.tech.schema.ReleaseContext; import iso.std.iso_iec._24727.tech.schema.Terminate; import java.io.IOException; import java.net.BindException; import java.util.List; import java.net.Socket; import java.net.URL; import java.nio.charset.UnsupportedCharsetException; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.FutureTask; import javax.annotation.Nullable; import org.openecard.addon.AddonManager; import org.openecard.apache.http.HttpException; import org.openecard.apache.http.HttpResponse; import org.openecard.apache.http.entity.ContentType; import org.openecard.apache.http.entity.StringEntity; import org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest; import org.openecard.apache.http.protocol.BasicHttpContext; import org.openecard.apache.http.protocol.HttpContext; import org.openecard.apache.http.protocol.HttpRequestExecutor; import org.openecard.common.AppVersion; import org.openecard.common.ClientEnv; import org.openecard.common.ECardConstants; import org.openecard.common.I18n; import org.openecard.common.OpenecardProperties; import org.openecard.common.WSHelper; import org.openecard.common.sal.state.CardStateMap; import org.openecard.common.sal.state.SALStateCallback; import org.openecard.control.binding.http.HttpBinding; import org.openecard.common.event.EventDispatcherImpl; import org.openecard.common.event.EventType; import org.openecard.gui.message.DialogType; import org.openecard.gui.swing.SwingDialogWrapper; import org.openecard.gui.swing.SwingUserConsent; import org.openecard.gui.swing.common.GUIDefaults; import org.openecard.ifd.protocol.pace.PACEProtocolFactory; import org.openecard.ifd.scio.IFD; import org.openecard.management.TinyManagement; import org.openecard.recognition.CardRecognitionImpl; import org.openecard.richclient.gui.AppTray; import org.openecard.richclient.gui.SettingsAndDefaultViewWrapper; import org.openecard.mdlw.sal.MiddlewareSAL; import org.openecard.mdlw.event.MwStateCallback; import org.openecard.mdlw.sal.config.MiddlewareConfigLoader; import org.openecard.mdlw.sal.config.MiddlewareSALConfig; import org.openecard.sal.SelectorSAL; import org.openecard.sal.TinySAL; import org.openecard.transport.dispatcher.MessageDispatcher; import org.openecard.transport.httpcore.HttpRequestHelper; import org.openecard.transport.httpcore.HttpUtils; import org.openecard.transport.httpcore.StreamHttpClientConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Moritz Horsch * @author Johannes Schmölz * @author Hans-Martin Haase * @author René Lottes * @author Tobias Wich */ public final class RichClient { private static final Logger LOG; private static final I18n LANG; // Tray icon private AppTray tray; // Control interface private HttpBinding httpBinding; // Client environment private ClientEnv env = new ClientEnv(); // Interface Device Layer (IFD) private IFD ifd; // Service Access Layer (SAL) private SelectorSAL sal; // AddonManager private AddonManager manager; // EventDispatcherImpl private EventDispatcherImpl eventDispatcher; // Card recognition private CardRecognitionImpl recognition; // card states private CardStateMap cardStates; // ContextHandle determines a specific IFD layer context private byte[] contextHandle; static { try { // load logger config from HOME if set LogbackConfig.load(); } catch (IOException | JoranException ex) { System.err.println("Failed to load logback config from user config."); ex.printStackTrace(System.err); try { LogbackConfig.loadDefault(); } catch (JoranException ex2) { System.err.println("Failed to load logback default config."); ex.printStackTrace(System.err); } } LOG = LoggerFactory.getLogger(RichClient.class.getName()); LANG = I18n.getTranslation("richclient"); } public static void main(String[] args) { LOG.info("Starting {} {} ...", AppVersion.getName(), AppVersion.getVersion()); RichClient client = new RichClient(); client.setup(); } public void setup() { GUIDefaults.initialize(); String title = LANG.translationForKey("client.startup.failed.headline", AppVersion.getName()); String message = null; // Set up GUI SwingUserConsent gui = new SwingUserConsent(new SwingDialogWrapper()); try { tray = new AppTray(this); tray.beginSetup(); // Set up client environment env = new ClientEnv(); // Set up the Dispatcher MessageDispatcher dispatcher = new MessageDispatcher(env); env.setDispatcher(dispatcher); // Set up EventDispatcherImpl eventDispatcher = new EventDispatcherImpl(); env.setEventDispatcher(eventDispatcher); // Set up Management TinyManagement management = new TinyManagement(env); env.setManagement(management); // Set up MiddlewareConfig MiddlewareConfigLoader mwConfigLoader = new MiddlewareConfigLoader(); List<MiddlewareSALConfig> mwSALConfigs = mwConfigLoader.getMiddlewareSALConfigs(); // Set up CardRecognitionImpl recognition = new CardRecognitionImpl(env); recognition.setGUI(gui); env.setRecognition(recognition); // Set up StateCallbacks cardStates = new CardStateMap(); SALStateCallback salCallback = new SALStateCallback(env, cardStates); eventDispatcher.add(salCallback); MwStateCallback mwCallback = new MwStateCallback(env, cardStates, mwConfigLoader); eventDispatcher.add(mwCallback); // Set up the IFD ifd = new IFD(); ifd.addProtocol(ECardConstants.Protocol.PACE, new PACEProtocolFactory()); ifd.setGUI(gui); ifd.setEnvironment(env); env.setIFD(ifd); // Set up SAL TinySAL mainSal = new TinySAL(env, cardStates); mainSal.setGUI(gui); sal = new SelectorSAL(mainSal, env); env.setSAL(sal); env.setCIFProvider(sal); // Set up Middleware SAL for (MiddlewareSALConfig mwSALConfig : mwSALConfigs) { if (! mwSALConfig.isDisabled()) { MiddlewareSAL mwSal = new MiddlewareSAL(env, cardStates, mwSALConfig); mwSal.setGui(gui); sal.addSpecializedSAL(mwSal); } } // Start up control interface SettingsAndDefaultViewWrapper guiWrapper = new SettingsAndDefaultViewWrapper(); try { manager = new AddonManager(env, gui, cardStates, guiWrapper); guiWrapper.setAddonManager(manager); mainSal.setAddonManager(manager); // initialize http binding int port = 24727; boolean dispatcherMode = false; WinReg.HKEY hk = WinReg.HKEY_LOCAL_MACHINE; String regPath = "SOFTWARE\\OeC"; if (Platform.isWindows()) { LOG.debug("Checking if dispatcher mode should be used."); try { if (regKeyExists(hk, regPath, "Dispatcher_Mode")) { String value = Advapi32Util.registryGetStringValue(hk, regPath, "Dispatcher_Mode"); dispatcherMode = Boolean.valueOf(value); // let socket chose its port port = 0; } } catch (Win32Exception ex) { LOG.warn("Failed to read 'Dispatcher_Mode' registry key. Using normal operation mode.", ex); } } if (! dispatcherMode) { try { port = Integer.parseInt(OpenecardProperties.getProperty("http-binding.port")); } catch (NumberFormatException ex) { LOG.warn("Error in config file, HTTP binding port is malformed."); } } // start HTTP server httpBinding = new HttpBinding(port); httpBinding.setAddonManager(manager); httpBinding.start(); if (dispatcherMode) { long waitTime = getRegInt(hk, regPath, "Retry_Wait_Time", 5000L); long timeout = getRegInt(hk, regPath, "DP_Timeout", 3600000L); // try to register with dispatcher service LOG.debug("Trying to register HTTP binding port with dispatcher service."); final int realPort = httpBinding.getPort(); final URL regUrl = new URL("http://127.0.0.1:24727/dp/register"); FutureTask ft = new FutureTask(new DispatcherRegistrator(regUrl, realPort, waitTime, timeout), 1); Thread registerThread = new Thread(ft, "Register-Dispatcher-Service"); registerThread.setDaemon(true); registerThread.start(); // wait until thread is finished ft.get(); } } catch (BindException e) { message = LANG.translationForKey("client.startup.failed.portinuse", AppVersion.getName()); throw e; } tray.endSetup(env, manager); // Initialize the EventManager eventDispatcher.add(tray.status(), EventType.TERMINAL_ADDED, EventType.TERMINAL_REMOVED, EventType.CARD_INSERTED, EventType.CARD_RECOGNIZED, EventType.CARD_REMOVED); // start event dispatcher eventDispatcher.start(); // initialize SAL WSHelper.checkResult(sal.initialize(new Initialize())); // Perform an EstablishContext to get a ContextHandle try { EstablishContext establishContext = new EstablishContext(); EstablishContextResponse establishContextResponse = ifd.establishContext(establishContext); WSHelper.checkResult(establishContextResponse); contextHandle = establishContextResponse.getContextHandle(); } catch (WSHelper.WSException ex) { message = LANG.translationForKey("client.startup.failed.nocontext"); throw ex; } // perform GC to bring down originally allocated memory new Timer().schedule(new GCTask(), 5000); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); if (message == null || message.isEmpty()) { // Add exception message if no custom message is set message = ex.getMessage(); } // Show dialog to the user and shut down the client String msg = String.format("%s%n%n%s", title, message); gui.obtainMessageDialog().showMessageDialog(msg, AppVersion.getName(), DialogType.ERROR_MESSAGE); teardown(); } catch (Throwable ex) { LOG.error("Unexpected error occurred. Exiting client.", ex); System.exit(1); } } private static class GCTask extends TimerTask { @Override public void run() { System.gc(); System.runFinalization(); System.gc(); // repeat every 5 minutes new Timer().schedule(new GCTask(), 5 * 60 * 1000); } } public void teardown() { try { if (eventDispatcher != null) { eventDispatcher.terminate(); } // TODO: shutdown addon manager and related components? if (manager != null) { manager.shutdown(); } // shutdown control modules if (httpBinding != null) { httpBinding.stop(); } // shutdown SAL if (sal != null) { Terminate terminate = new Terminate(); sal.terminate(terminate); } // shutdown IFD if (ifd != null && contextHandle != null) { ReleaseContext releaseContext = new ReleaseContext(); releaseContext.setContextHandle(contextHandle); ifd.releaseContext(releaseContext); } } catch (Exception ex) { LOG.error("Failed to stop Richclient.", ex); } System.exit(0); } private static class DispatcherRegistrator implements Runnable { private final URL regUrl; private final int bindingPort; private final long waitTime; private final long timeout; public DispatcherRegistrator(URL regUrl, int bindingPort, long waitTime, long timeout) { this.regUrl = regUrl; this.bindingPort = bindingPort; this.waitTime = waitTime; this.timeout = timeout; } @Override public void run() { long startTime = System.currentTimeMillis(); HttpRequestExecutor exec = new HttpRequestExecutor(); HttpContext httpCtx = new BasicHttpContext(); do { try { int port = regUrl.getPort() == -1 ? regUrl.getDefaultPort() : regUrl.getPort(); Socket sock = new Socket(regUrl.getHost(), port); StreamHttpClientConnection con = new StreamHttpClientConnection(sock.getInputStream(), sock.getOutputStream()); BasicHttpEntityEnclosingRequest req; req = new BasicHttpEntityEnclosingRequest("POST", regUrl.getFile()); // prepare request HttpRequestHelper.setDefaultHeader(req, regUrl); ContentType reqContentType = ContentType.create("application/x-www-form-urlencoded", "UTF-8"); String bodyStr = String.format("Port=%d", bindingPort); StringEntity bodyEnt = new StringEntity(bodyStr, reqContentType); req.setEntity(bodyEnt); req.setHeader(bodyEnt.getContentType()); req.setHeader("Content-Length", String.valueOf(bodyEnt.getContentLength())); // send request HttpUtils.dumpHttpRequest(LOG, req); HttpResponse response = exec.execute(req, con, httpCtx); HttpUtils.dumpHttpResponse(LOG, response, null); if (response.getStatusLine().getStatusCode() == 204) { return; } else { LOG.info("Execution of dispatcher registration is not successful, trying again ..."); } } catch (HttpException | IOException | UnsupportedCharsetException ex) { LOG.error("Failed to send dispatcher registration reguest.", ex); } // terminate in case there is no time left long now = System.currentTimeMillis(); if (now - startTime > timeout) { throw new RuntimeException("Failed to register with dispatcher service in a timely manner."); } // wait a bit and try again try { Thread.sleep(waitTime); } catch (InterruptedException ex) { LOG.info("Dispatcher registration interrupted."); return; } } while (true); } }; private static boolean regKeyExists(WinReg.HKEY hk, String key, String value) { return Advapi32Util.registryKeyExists(hk, key) && Advapi32Util.registryValueExists(hk, key, value); } private static Long getRegInt(WinReg.HKEY hk, String key, String value, @Nullable Long defaultValue) { try { if (regKeyExists(hk, key, value)) { return (long) Advapi32Util.registryGetIntValue(hk, key, value); } } catch (Win32Exception ex) { LOG.debug("Registry key {}\\{} does not exist or has wrong type.", key, value); } return defaultValue; } }
Print status code of dispatcher registration failures
clients/richclient/src/main/java/org/openecard/richclient/RichClient.java
Print status code of dispatcher registration failures
<ide><path>lients/richclient/src/main/java/org/openecard/richclient/RichClient.java <ide> HttpResponse response = exec.execute(req, con, httpCtx); <ide> HttpUtils.dumpHttpResponse(LOG, response, null); <ide> <del> if (response.getStatusLine().getStatusCode() == 204) { <add> int statusCode = response.getStatusLine().getStatusCode(); <add> if (statusCode == 204) { <ide> return; <ide> } else { <del> LOG.info("Execution of dispatcher registration is not successful, trying again ..."); <add> String msg = "Execution of dispatcher registration is not successful (code={}), trying again ..."; <add> LOG.info(msg, statusCode); <ide> } <ide> } catch (HttpException | IOException | UnsupportedCharsetException ex) { <ide> LOG.error("Failed to send dispatcher registration reguest.", ex);
Java
apache-2.0
34a7f2529c828ca2149cd150b82020ba93416c96
0
alphafoobar/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,supersven/intellij-community,xfournet/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,jagguli/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,amith01994/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,signed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,fitermay/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,signed/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,apixandru/intellij-community,fitermay/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,kool79/intellij-community,kool79/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,semonte/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,caot/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,retomerz/intellij-community,semonte/intellij-community,retomerz/intellij-community,signed/intellij-community,ryano144/intellij-community,fnouama/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,fnouama/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,fnouama/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,semonte/intellij-community,caot/intellij-community,amith01994/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,amith01994/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ernestp/consulo,holmes/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,FHannes/intellij-community,holmes/intellij-community,caot/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,dslomov/intellij-community,da1z/intellij-community,izonder/intellij-community,hurricup/intellij-community,allotria/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,vladmm/intellij-community,supersven/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,kool79/intellij-community,asedunov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,vladmm/intellij-community,semonte/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,samthor/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,holmes/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,signed/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,asedunov/intellij-community,apixandru/intellij-community,kdwink/intellij-community,holmes/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,apixandru/intellij-community,fnouama/intellij-community,clumsy/intellij-community,consulo/consulo,wreckJ/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,allotria/intellij-community,asedunov/intellij-community,dslomov/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,diorcety/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,caot/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,supersven/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,kdwink/intellij-community,kool79/intellij-community,da1z/intellij-community,da1z/intellij-community,orekyuu/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,supersven/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,slisson/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,petteyg/intellij-community,FHannes/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,hurricup/intellij-community,consulo/consulo,orekyuu/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,dslomov/intellij-community,clumsy/intellij-community,da1z/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,FHannes/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,slisson/intellij-community,supersven/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,allotria/intellij-community,holmes/intellij-community,asedunov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,fnouama/intellij-community,robovm/robovm-studio,signed/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,holmes/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,caot/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,petteyg/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,consulo/consulo,lucafavatella/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,supersven/intellij-community,petteyg/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,supersven/intellij-community,holmes/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,slisson/intellij-community,signed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,caot/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,fitermay/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,slisson/intellij-community,nicolargo/intellij-community,supersven/intellij-community,caot/intellij-community,diorcety/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,slisson/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ibinti/intellij-community,signed/intellij-community,ernestp/consulo,fnouama/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,semonte/intellij-community,vladmm/intellij-community,da1z/intellij-community,fitermay/intellij-community,apixandru/intellij-community,allotria/intellij-community,diorcety/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ernestp/consulo,TangHao1987/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,supersven/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,robovm/robovm-studio,vladmm/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,ibinti/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ernestp/consulo,fitermay/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,petteyg/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,izonder/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,retomerz/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,kool79/intellij-community,tmpgit/intellij-community,kool79/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,retomerz/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,blademainer/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,slisson/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,fitermay/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,caot/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,consulo/consulo,orekyuu/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,allotria/intellij-community,kool79/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,kool79/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,holmes/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,apixandru/intellij-community,FHannes/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,hurricup/intellij-community,xfournet/intellij-community,petteyg/intellij-community,slisson/intellij-community,signed/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,kdwink/intellij-community,clumsy/intellij-community,fnouama/intellij-community,retomerz/intellij-community,kdwink/intellij-community,allotria/intellij-community,holmes/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,ibinti/intellij-community,blademainer/intellij-community,ryano144/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ibinti/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,jagguli/intellij-community,jagguli/intellij-community,semonte/intellij-community,caot/intellij-community,alphafoobar/intellij-community
/* * Copyright 2000-2010 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 org.jetbrains.android.dom.converters; import com.intellij.codeInsight.completion.JavaLookupElementBuilder; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Query; import com.intellij.util.xml.*; import org.jetbrains.android.dom.manifest.Manifest; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author yole */ public class PackageClassConverter extends ResolvingConverter<PsiClass> implements CustomReferenceConverter<PsiClass> { private static final Logger LOG = Logger.getInstance("#org.jetbrains.android.dom.converters.PackageClassConverter"); private final String myExtendClassName; public PackageClassConverter(String extendClassName) { myExtendClassName = extendClassName; } public PackageClassConverter() { myExtendClassName = null; } @NotNull public Collection<? extends PsiClass> getVariants(ConvertContext context) { return Collections.emptyList(); } public PsiClass fromString(@Nullable @NonNls String s, ConvertContext context) { if (s == null) return null; DomElement domElement = context.getInvocationElement(); Manifest manifest = domElement.getParentOfType(Manifest.class, true); if (manifest != null) { s = s.replace('$', '.'); String packageName = manifest.getPackage().getValue(); String className; if (s.startsWith(".")) { className = packageName + s; } else { className = packageName + "." + s; } JavaPsiFacade facade = JavaPsiFacade.getInstance(context.getPsiManager().getProject()); GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(context.getModule()); PsiClass psiClass = facade.findClass(className, scope); if (psiClass == null) { psiClass = facade.findClass(s, scope); } return psiClass; } return null; } @NotNull @Override public PsiReference[] createReferences(GenericDomValue<PsiClass> value, PsiElement element, ConvertContext context) { assert element instanceof XmlAttributeValue; final XmlAttributeValue attrValue = (XmlAttributeValue)element; final String strValue = attrValue.getValue(); final boolean startsWithPoint = strValue.startsWith("."); final int start = attrValue.getValueTextRange().getStartOffset() - attrValue.getTextRange().getStartOffset(); final DomElement domElement = context.getInvocationElement(); final Manifest manifest = domElement.getParentOfType(Manifest.class, true); final String basePackage = manifest == null ? null : manifest.getPackage().getValue(); final ExtendClass extendClassAnnotation = domElement.getAnnotation(ExtendClass.class); final String extendsClassName = extendClassAnnotation != null ? extendClassAnnotation.value() : myExtendClassName; final boolean inModuleOnly = domElement.getAnnotation(CompleteNonModuleClass.class) == null; List<PsiReference> result = new ArrayList<PsiReference>(); final String[] nameParts = strValue.split("\\."); if (nameParts.length == 0) { return PsiReference.EMPTY_ARRAY; } final Module module = context.getModule(); int offset = start; for (int i = 0, n = nameParts.length; i < n - 1; i++) { final String packageName = nameParts[i]; if (packageName.length() > 0) { offset += packageName.length(); final TextRange range = new TextRange(offset - packageName.length(), offset); result.add(new MyReference(element, range, basePackage, startsWithPoint, start, true, module, extendsClassName, inModuleOnly)); } offset++; } final String className = nameParts[nameParts.length - 1]; final String[] classNameParts = className.split("\\$"); for (String s : classNameParts) { if (s.length() > 0) { offset += s.length(); final TextRange range = new TextRange(offset - s.length(), offset); result.add(new MyReference(element, range, basePackage, startsWithPoint, start, false, module, extendsClassName, inModuleOnly)); } offset++; } return result.toArray(new PsiReference[result.size()]); } @Nullable private static String getQualifiedName(@NotNull PsiClass aClass) { PsiElement parent = aClass.getParent(); if (parent instanceof PsiClass) { String parentQName = getQualifiedName((PsiClass)parent); if (parentQName == null) return null; return parentQName + "$" + aClass.getName(); } return aClass.getQualifiedName(); } @Nullable private static String getName(@NotNull PsiClass aClass) { PsiElement parent = aClass.getParent(); if (parent instanceof PsiClass) { String parentName = getName((PsiClass)parent); if (parentName == null) return null; return parentName + "$" + aClass.getName(); } return aClass.getName(); } @Nullable public String toString(@Nullable PsiClass psiClass, ConvertContext context) { DomElement domElement = context.getInvocationElement(); Manifest manifest = domElement.getParentOfType(Manifest.class, true); final String packageName = manifest == null ? null : manifest.getPackage().getValue(); return classToString(psiClass, packageName, ""); } @Nullable private static String classToString(PsiClass psiClass, String basePackageName, String prefix) { if (psiClass == null) return null; String qName = getQualifiedName(psiClass); if (qName == null) return null; PsiFile file = psiClass.getContainingFile(); if (file instanceof PsiClassOwner) { PsiClassOwner psiFile = (PsiClassOwner)file; if (Comparing.equal(psiFile.getPackageName(), basePackageName)) { String name = getName(psiClass); if (name != null) { final String dottedName = '.' + name; if (dottedName.startsWith(prefix)) { return dottedName; } else if (name.startsWith(prefix)) { return name; } } } else if (basePackageName != null && qName.startsWith(basePackageName)) { final String name = qName.substring(basePackageName.length()); if (name.startsWith(prefix)) { return name; } } } return qName; } @NotNull public static Collection<PsiClass> findInheritors(@NotNull final Module module, @NotNull final String className, boolean inModuleOnly) { final Project project = module.getProject(); PsiClass base = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project)); if (base != null) { GlobalSearchScope scope = inModuleOnly ? GlobalSearchScope.moduleWithDependenciesScope(module) : GlobalSearchScope.allScope(project); Query<PsiClass> query = ClassInheritorsSearch.search(base, scope, true); return query.findAll(); } return new ArrayList<PsiClass>(); } private static class MyReference extends PsiReferenceBase<PsiElement> { private final int myStart; private final String myBasePackage; private final boolean myStartsWithPoint; private final boolean myIsPackage; private final Module myModule; private final String myExtendsClass; private final boolean myCompleteOnlyModuleClasses; public MyReference(PsiElement element, TextRange range, String basePackage, boolean startsWithPoint, int start, boolean isPackage, Module module, String extendsClass, boolean completeOnlyModuleClasses) { super(element, range, true); myBasePackage = basePackage; myStartsWithPoint = startsWithPoint; myStart = start; myIsPackage = isPackage; myModule = module; myExtendsClass = extendsClass; myCompleteOnlyModuleClasses = completeOnlyModuleClasses; } @Override public PsiElement resolve() { final PsiManager manager = getElement().getManager(); if (manager instanceof PsiManagerImpl) { return ((PsiManagerImpl)manager).getResolveCache().resolveWithCaching(this, new ResolveCache.Resolver() { @Nullable @Override public PsiElement resolve(PsiReference reference, boolean incompleteCode) { return resolveInner(); } }, false, false); } return resolveInner(); } @Nullable private PsiElement resolveInner() { final int end = getRangeInElement().getEndOffset(); final String value = myElement.getText().substring(myStart, end).replace('$', '.'); final JavaPsiFacade facade = JavaPsiFacade.getInstance(myElement.getProject()); if (!myStartsWithPoint) { final PsiElement element = myIsPackage ? facade.findPackage(value) : facade.findClass(value, myModule.getModuleWithDependenciesScope()); if (element != null) { return element; } } final String relativeName = getRelativeName(value); if (relativeName != null) { return myIsPackage ? facade.findPackage(relativeName) : facade.findClass(relativeName, myModule.getModuleWithDependenciesScope()); } return null; } @Nullable private String getRelativeName(String value) { if (myBasePackage == null) { return null; } return myBasePackage + (myStartsWithPoint ? "" : ".") + value; } @NotNull @Override public Object[] getVariants() { if (myExtendsClass != null) { final List<PsiClass> classes = new ArrayList<PsiClass>(); classes.addAll(findInheritors(myModule, myExtendsClass, myCompleteOnlyModuleClasses)); final List<Object> result = new ArrayList<Object>(classes.size()); for (int i = 0, n = classes.size(); i < n; i++) { final PsiClass psiClass = classes.get(i); final String prefix = myElement.getText().substring(myStart, getRangeInElement().getStartOffset()); String name = classToString(psiClass, myBasePackage, prefix); if (name != null && name.startsWith(prefix)) { name = name.substring(prefix.length()); result.add(JavaLookupElementBuilder.forClass(psiClass, name, true)); } } return ArrayUtil.toObjectArray(result); } return EMPTY_ARRAY; } @Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { if (element instanceof PsiClass || element instanceof PsiPackage) { final String newName = element instanceof PsiClass ? classToString((PsiClass)element, myBasePackage, "") : packageToString((PsiPackage)element, myBasePackage); assert newName != null; final ElementManipulator<PsiElement> manipulator = ElementManipulators.getManipulator(myElement); final TextRange range = new TextRange(myStart, getRangeInElement().getEndOffset()); return manipulator != null ? manipulator.handleContentChange(getElement(), range, newName) : element; } LOG.error("PackageClassConverter resolved to " + element.getClass()); return super.bindToElement(element); } private static String packageToString(PsiPackage psiPackage, String basePackageName) { final String qName = psiPackage.getQualifiedName(); return basePackageName != null && qName.startsWith(basePackageName) ? qName.substring(basePackageName.length()) : qName; } } }
plugins/android/src/org/jetbrains/android/dom/converters/PackageClassConverter.java
/* * Copyright 2000-2010 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 org.jetbrains.android.dom.converters; import com.intellij.codeInsight.completion.JavaLookupElementBuilder; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Query; import com.intellij.util.xml.*; import org.jetbrains.android.dom.manifest.Manifest; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author yole */ public class PackageClassConverter extends ResolvingConverter<PsiClass> implements CustomReferenceConverter<PsiClass> { private static final Logger LOG = Logger.getInstance("#org.jetbrains.android.dom.converters.PackageClassConverter"); private final String myExtendClassName; public PackageClassConverter(String extendClassName) { myExtendClassName = extendClassName; } public PackageClassConverter() { myExtendClassName = null; } @NotNull public Collection<? extends PsiClass> getVariants(ConvertContext context) { return Collections.emptyList(); } public PsiClass fromString(@Nullable @NonNls String s, ConvertContext context) { if (s == null) return null; DomElement domElement = context.getInvocationElement(); Manifest manifest = domElement.getParentOfType(Manifest.class, true); if (manifest != null) { s = s.replace('$', '.'); String packageName = manifest.getPackage().getValue(); String className; if (s.startsWith(".")) { className = packageName + s; } else { className = packageName + "." + s; } JavaPsiFacade facade = JavaPsiFacade.getInstance(context.getPsiManager().getProject()); GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(context.getModule()); PsiClass psiClass = facade.findClass(className, scope); if (psiClass == null) { psiClass = facade.findClass(s, scope); } return psiClass; } return null; } @NotNull @Override public PsiReference[] createReferences(GenericDomValue<PsiClass> value, PsiElement element, ConvertContext context) { assert element instanceof XmlAttributeValue; final XmlAttributeValue attrValue = (XmlAttributeValue)element; final String strValue = attrValue.getValue(); final boolean startsWithPoint = strValue.startsWith("."); final int start = attrValue.getValueTextRange().getStartOffset() - attrValue.getTextRange().getStartOffset(); final DomElement domElement = context.getInvocationElement(); final Manifest manifest = domElement.getParentOfType(Manifest.class, true); final String basePackage = manifest == null ? null : manifest.getPackage().getValue(); final ExtendClass extendClassAnnotation = domElement.getAnnotation(ExtendClass.class); final String extendsClassName = extendClassAnnotation != null ? extendClassAnnotation.value() : myExtendClassName; final boolean inModuleOnly = domElement.getAnnotation(CompleteNonModuleClass.class) == null; List<PsiReference> result = new ArrayList<PsiReference>(); final String[] nameParts = strValue.split("\\."); if (nameParts.length == 0) { return PsiReference.EMPTY_ARRAY; } final Module module = context.getModule(); int offset = start; for (int i = 0, n = nameParts.length; i < n - 1; i++) { final String packageName = nameParts[i]; if (packageName.length() > 0) { offset += packageName.length(); final TextRange range = new TextRange(offset - packageName.length(), offset); result.add(new MyReference(element, range, basePackage, startsWithPoint, start, true, module, extendsClassName, inModuleOnly)); } offset++; } final String className = nameParts[nameParts.length - 1]; final String[] classNameParts = className.split("\\$"); for (String s : classNameParts) { if (s.length() > 0) { offset += s.length(); final TextRange range = new TextRange(offset - s.length(), offset); result.add(new MyReference(element, range, basePackage, startsWithPoint, start, false, module, extendsClassName, inModuleOnly)); } offset++; } return result.toArray(new PsiReference[result.size()]); } @Nullable private static String getQualifiedName(@NotNull PsiClass aClass) { PsiElement parent = aClass.getParent(); if (parent instanceof PsiClass) { String parentQName = getQualifiedName((PsiClass)parent); if (parentQName == null) return null; return parentQName + "$" + aClass.getName(); } return aClass.getQualifiedName(); } @Nullable private static String getName(@NotNull PsiClass aClass) { PsiElement parent = aClass.getParent(); if (parent instanceof PsiClass) { String parentName = getName((PsiClass)parent); if (parentName == null) return null; return parentName + "$" + aClass.getName(); } return aClass.getName(); } @Nullable public String toString(@Nullable PsiClass psiClass, ConvertContext context) { DomElement domElement = context.getInvocationElement(); Manifest manifest = domElement.getParentOfType(Manifest.class, true); final String packageName = manifest == null ? null : manifest.getPackage().getValue(); return classToString(psiClass, packageName, ""); } @Nullable private static String classToString(PsiClass psiClass, String basePackageName, String prefix) { if (psiClass == null) return null; String qName = getQualifiedName(psiClass); if (qName == null) return null; PsiFile file = psiClass.getContainingFile(); if (file instanceof PsiClassOwner) { PsiClassOwner psiFile = (PsiClassOwner)file; if (Comparing.equal(psiFile.getPackageName(), basePackageName)) { String name = getName(psiClass); if (name != null) { final String dottedName = '.' + name; if (dottedName.startsWith(prefix)) { return dottedName; } else if (name.startsWith(prefix)) { return name; } } } else if (basePackageName != null && qName.startsWith(basePackageName)) { final String name = qName.substring(basePackageName.length()); if (name.startsWith(prefix)) { return name; } } } return qName; } @NotNull public static Collection<PsiClass> findInheritors(@NotNull final Module module, @NotNull final String className, boolean inModuleOnly) { final Project project = module.getProject(); PsiClass base = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project)); if (base != null) { GlobalSearchScope scope = inModuleOnly ? GlobalSearchScope.moduleWithDependenciesScope(module) : GlobalSearchScope.allScope(project); Query<PsiClass> query = ClassInheritorsSearch.search(base, scope, true); return query.findAll(); } return new ArrayList<PsiClass>(); } private static class MyReference extends PsiReferenceBase<PsiElement> { private final int myStart; private final String myBasePackage; private final boolean myStartsWithPoint; private final boolean myIsPackage; private final Module myModule; private final String myExtendsClass; private final boolean myCompleteOnlyModuleClasses; public MyReference(PsiElement element, TextRange range, String basePackage, boolean startsWithPoint, int start, boolean isPackage, Module module, String extendsClass, boolean completeOnlyModuleClasses) { super(element, range, true); myBasePackage = basePackage; myStartsWithPoint = startsWithPoint; myStart = start; myIsPackage = isPackage; myModule = module; myExtendsClass = extendsClass; myCompleteOnlyModuleClasses = completeOnlyModuleClasses; } @Override public PsiElement resolve() { final int end = getRangeInElement().getEndOffset(); final String value = myElement.getText().substring(myStart, end).replace('$', '.'); final JavaPsiFacade facade = JavaPsiFacade.getInstance(myElement.getProject()); if (!myStartsWithPoint) { final PsiElement element = myIsPackage ? facade.findPackage(value) : facade.findClass(value, myModule.getModuleWithDependenciesScope()); if (element != null) { return element; } } final String relativeName = getRelativeName(value); if (relativeName != null) { return myIsPackage ? facade.findPackage(relativeName) : facade.findClass(relativeName, myModule.getModuleWithDependenciesScope()); } return null; } @Nullable private String getRelativeName(String value) { if (myBasePackage == null) { return null; } return myBasePackage + (myStartsWithPoint ? "" : ".") + value; } @NotNull @Override public Object[] getVariants() { if (myExtendsClass != null) { final List<PsiClass> classes = new ArrayList<PsiClass>(); classes.addAll(findInheritors(myModule, myExtendsClass, myCompleteOnlyModuleClasses)); final List<Object> result = new ArrayList<Object>(classes.size()); for (int i = 0, n = classes.size(); i < n; i++) { final PsiClass psiClass = classes.get(i); final String prefix = myElement.getText().substring(myStart, getRangeInElement().getStartOffset()); String name = classToString(psiClass, myBasePackage, prefix); if (name != null && name.startsWith(prefix)) { name = name.substring(prefix.length()); result.add(JavaLookupElementBuilder.forClass(psiClass, name, true)); } } return ArrayUtil.toObjectArray(result); } return EMPTY_ARRAY; } @Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { if (element instanceof PsiClass || element instanceof PsiPackage) { final String newName = element instanceof PsiClass ? classToString((PsiClass)element, myBasePackage, "") : packageToString((PsiPackage)element, myBasePackage); assert newName != null; final ElementManipulator<PsiElement> manipulator = ElementManipulators.getManipulator(myElement); final TextRange range = new TextRange(myStart, getRangeInElement().getEndOffset()); return manipulator != null ? manipulator.handleContentChange(getElement(), range, newName) : element; } LOG.error("PackageClassConverter resolved to " + element.getClass()); return super.bindToElement(element); } private static String packageToString(PsiPackage psiPackage, String basePackageName) { final String qName = psiPackage.getQualifiedName(); return basePackageName != null && qName.startsWith(basePackageName) ? qName.substring(basePackageName.length()) : qName; } } }
caching
plugins/android/src/org/jetbrains/android/dom/converters/PackageClassConverter.java
caching
<ide><path>lugins/android/src/org/jetbrains/android/dom/converters/PackageClassConverter.java <ide> import com.intellij.openapi.util.Comparing; <ide> import com.intellij.openapi.util.TextRange; <ide> import com.intellij.psi.*; <add>import com.intellij.psi.impl.PsiManagerImpl; <add>import com.intellij.psi.impl.source.resolve.ResolveCache; <ide> import com.intellij.psi.search.GlobalSearchScope; <ide> import com.intellij.psi.search.searches.ClassInheritorsSearch; <ide> import com.intellij.psi.xml.XmlAttributeValue; <ide> <ide> @Override <ide> public PsiElement resolve() { <add> final PsiManager manager = getElement().getManager(); <add> if (manager instanceof PsiManagerImpl) { <add> return ((PsiManagerImpl)manager).getResolveCache().resolveWithCaching(this, new ResolveCache.Resolver() { <add> @Nullable <add> @Override <add> public PsiElement resolve(PsiReference reference, boolean incompleteCode) { <add> return resolveInner(); <add> } <add> }, false, false); <add> } <add> return resolveInner(); <add> } <add> <add> @Nullable <add> private PsiElement resolveInner() { <ide> final int end = getRangeInElement().getEndOffset(); <ide> final String value = myElement.getText().substring(myStart, end).replace('$', '.'); <ide> final JavaPsiFacade facade = JavaPsiFacade.getInstance(myElement.getProject());
JavaScript
bsd-3-clause
33db16f4e9c1a29c16bf5e8663d65c8f347eeb95
0
Patternslib/Patterns-archive,Patternslib/Patterns-archive,Patternslib/Patterns-archive
define([ "jquery", "pat-parser", "pat-registry", "pat-utils", "pat-inject" ], function($, Parser, registry, utils, inject) { var parser = new Parser("modal"); parser.add_argument("class"); var modal = { name: "modal", jquery_plugin: true, // div's are turned into modals // links and forms inject modals trigger: "div.pat-modal, a.pat-modal, form.pat-modal", init: function($el, opts) { this.$el = $el; return $el.each(function() { var $el = $(this), cfg = parser.parse($el, opts); if ($el.is("div")) modal._init_div1($el, cfg); else modal._init_inject1($el, cfg); }); }, _init_inject1: function($el, cfg) { var opts = { target: "#pat-modal", "class": "pat-modal" + (cfg["class"] ? " " + cfg["class"] : "") }; // if $el is already inside a modal, do not detach #pat-modal, // because this would unnecessarily close the modal itself if (!$el.closest("#pat-modal")) { $("#pat-modal").detach(); } inject.init($el, opts); }, _init_div1: function($el) { var $header = $("<div class='header' />"), activeElement = document.activeElement; $("<button type='button' class='close-panel'>Close</button>").appendTo($header); // We cannot handle text nodes here $el.children(":last, :not(:first)") .wrapAll("<div class='panel-content' />"); $(".panel-content", $el).before($header); $el.children(":first:not(.header)").prependTo($header); // Restore focus in case the active element was a child of $el and // the focus was lost during the wrapping. activeElement.focus(); // event handlers remove modal - first arg to bind is ``this`` $(document).on("click.pat-modal", ".close-panel", modal.destroy.bind($el, $el)); // remove on ESC $(document).on("keyup.pat-modal", modal.destroy.bind($el, $el)); modal.setPosition(); }, setPosition: function() { if (this.$el.length === 0) { return; } var $oldClone = $("#pat-modal-clone"); if ($oldClone.length > 0) { $oldClone.remove(); } var $clone = this.$el.clone(); $clone .attr("id", "pat-modal-clone") .css({ "visibility": "hidden", "position": "absolute", "height": "" }).appendTo("body"); // wait for browser to update DOM setTimeout($.proxy(modal.measure, this), 0); }, measure: function() { var $clone = $("#pat-modal-clone"); if ($clone.length === 0) { return; } var maxHeight = $(window).innerHeight() - $clone.outerHeight(true) + $clone.outerHeight(), height = $clone.outerHeight(); $clone.remove(); if (maxHeight - height < 0) { this.$el.addClass("max-height").css("height", maxHeight); } else { this.$el.removeClass("max-height").css("height", ""); } var top = ($(window).innerHeight() - this.$el.outerHeight(true)) / 2; this.$el.css("top", top); }, destroy: function($el, ev) { if (ev && ev.type === "keyup" && ev.which !== 27) return; $(document).off(".pat-modal"); $el.remove(); } }; $(window).on("resize.pat-modal-position", $.proxy(modal.setPosition, modal)); $(window).on("pat-inject-content-loaded.pat-modal-position", "#pat-modal", $.proxy(modal.setPosition, modal)); $(document).on("patterns-injected.pat-modal-position", "#pat-modal,div.pat-modal", $.proxy(modal.setPosition, modal)); registry.register(modal); return modal; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
src/pat/modal.js
define([ "jquery", "pat-parser", "pat-registry", "pat-utils", "pat-inject" ], function($, Parser, registry, utils, inject) { var parser = new Parser("modal"); parser.add_argument("class"); var modal = { name: "modal", jquery_plugin: true, // div's are turned into modals // links and forms inject modals trigger: "div.pat-modal, a.pat-modal, form.pat-modal", init: function($el, opts) { this.$el = $el; return $el.each(function() { var $el = $(this), cfg = parser.parse($el, opts); if ($el.is("div")) modal._init_div1($el, cfg); else modal._init_inject1($el, cfg); }); }, _init_inject1: function($el, cfg) { var opts = { target: "#pat-modal", "class": "pat-modal" + (cfg["class"] ? " " + cfg["class"] : "") }; // if $el is already inside a modal, do not detach #pat-modal, // because this would unnecessarily close the modal itself if (!$el.closest("#pat-modal")) { $("#pat-modal").detach(); } inject.init($el, opts); }, _init_div1: function($el) { var $header = $("<div class='header' />"), activeElement = document.activeElement; $("<button type='button' class='close-panel'>Close</button>").appendTo($header); // We cannot handle text nodes here $el.children(":last, :not(:first)") .wrapAll("<div class='panel-content' />"); $(".panel-content", $el).before($header); $el.children(":first:not(.header)").prependTo($header); // Restore focus in case the active element was a child of $el and // the focus was lost during the wrapping. activeElement.focus(); // event handlers remove modal - first arg to bind is ``this`` $(document).on("click.pat-modal", ".close-panel", modal.destroy.bind($el, $el)); // remove on ESC $(document).on("keyup.pat-modal", modal.destroy.bind($el, $el)); modal.setPosition(); }, setPosition: function() { if (this.$el.length === 0) { return; } var $oldClone = $("#pat-modal-clone"); if ($oldClone.length > 0) { $oldClone.remove(); } var $clone = this.$el.clone(); $clone .attr("id", "pat-modal-clone") .css({ "visibility": "hidden", "position": "absolute", "height": "" }).appendTo("body"); // wait for browser to update DOM setTimeout($.proxy(modal.measure, this), 0); }, measure: function() { var $clone = $("#pat-modal-clone"); if ($clone.length === 0) { return; } var maxHeight = $(window).innerHeight() - $clone.outerHeight(true) + $clone.outerHeight(), height = $clone.outerHeight(); $clone.remove(); if (maxHeight - height < 0) { this.$el.addClass("max-height").css("height", maxHeight); } else { this.$el.removeClass("max-height").css("height", ""); } var top = ($(window).innerHeight() - this.$el.outerHeight(true)) / 2; this.$el.css("top", top); }, destroy: function($el, ev) { if (ev && ev.type === "keyup" && ev.which !== 27) return; $(document).off(".pat-modal"); $el.remove(); } }; $(window).on("resize.pat-modal-position", modal.setPosition); $(window).on("pat-inject-content-loaded.pat-modal-position", "#pat-modal", modal.setPosition); $(document).on("patterns-injected.pat-modal-position", "#pat-modal,div.pat-modal", modal.setPosition); registry.register(modal); return modal; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
Proxy callbacks to setPosition so that it has correct context. This is related to the previous modal bugfix.
src/pat/modal.js
Proxy callbacks to setPosition so that it has correct context.
<ide><path>rc/pat/modal.js <ide> } <ide> }; <ide> <del> $(window).on("resize.pat-modal-position", modal.setPosition); <add> $(window).on("resize.pat-modal-position", $.proxy(modal.setPosition, modal)); <ide> $(window).on("pat-inject-content-loaded.pat-modal-position", "#pat-modal", <del> modal.setPosition); <add> $.proxy(modal.setPosition, modal)); <ide> $(document).on("patterns-injected.pat-modal-position", "#pat-modal,div.pat-modal", <del> modal.setPosition); <add> $.proxy(modal.setPosition, modal)); <ide> <ide> registry.register(modal); <ide> return modal;
Java
apache-2.0
8d840810d1ea516cc9150cb8825b0a79568f03cb
0
awslabs/aws-dynamodb-encryption-java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.fail; public class MetaStoreTests { private static final String SOURCE_TABLE_NAME = "keystoreTable"; private static final String DESTINATION_TABLE_NAME = "keystoreDestinationTable"; private static final String MATERIAL_NAME = "material"; private static final SecretKey AES_KEY = new SecretKeySpec(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, "AES"); private static final SecretKey TARGET_AES_KEY = new SecretKeySpec(new byte[]{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}, "AES"); private static final SecretKey HMAC_KEY = new SecretKeySpec(new byte[]{0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256"); private static final SecretKey TARGET_HMAC_KEY = new SecretKeySpec(new byte[]{0, 2, 4, 6, 8, 10, 12, 14}, "HmacSHA256"); private static final EncryptionMaterialsProvider BASE_PROVIDER = new SymmetricStaticProvider(AES_KEY, HMAC_KEY); private static final EncryptionMaterialsProvider TARGET_BASE_PROVIDER = new SymmetricStaticProvider(TARGET_AES_KEY, TARGET_HMAC_KEY); private static final DynamoDBEncryptor ENCRYPTOR = DynamoDBEncryptor.getInstance(BASE_PROVIDER); private static final DynamoDBEncryptor TARGET_ENCRYPTOR = DynamoDBEncryptor.getInstance(TARGET_BASE_PROVIDER); private AmazonDynamoDB client; private AmazonDynamoDB targetClient; private MetaStore store; private MetaStore targetStore; private EncryptionContext ctx; private static class TestExtraDataSupplier implements MetaStore.ExtraDataSupplier { private final Map<String, AttributeValue> attributeValueMap; private final Set<String> signedOnlyFieldNames; public TestExtraDataSupplier(final Map<String, AttributeValue> attributeValueMap, final Set<String> signedOnlyFieldNames) { this.attributeValueMap = attributeValueMap; this.signedOnlyFieldNames = signedOnlyFieldNames; } @Override public Map<String, AttributeValue> getAttributes(String materialName, long version) { return this.attributeValueMap; } @Override public Set<String> getSignedOnlyFieldNames() { return this.signedOnlyFieldNames; } } @BeforeMethod public void setup() { client = synchronize(DynamoDBEmbedded.create(), AmazonDynamoDB.class); targetClient = synchronize(DynamoDBEmbedded.create(), AmazonDynamoDB.class); MetaStore.createTable(client, SOURCE_TABLE_NAME, new ProvisionedThroughput(1L, 1L)); //Creating Targeted DynamoDB Object MetaStore.createTable(targetClient, DESTINATION_TABLE_NAME, new ProvisionedThroughput(1L, 1L)); store = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR); targetStore = new MetaStore(targetClient, DESTINATION_TABLE_NAME, TARGET_ENCRYPTOR); ctx = new EncryptionContext.Builder().build(); } @Test public void testNoMaterials() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); } @Test public void singleMaterial() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialExplicitAccess() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialExplicitAccessWithVersion() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialWithImplicitCreation() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov = store.getProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void twoDifferentMaterials() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.newProvider(MATERIAL_NAME); assertEquals(1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); try { prov2.getDecryptionMaterials(ctx(eMat)); fail("Missing expected exception"); } catch (final DynamoDBMappingException ex) { // Expected Exception } final EncryptionMaterials eMat2 = prov2.getEncryptionMaterials(ctx); assertEquals(1, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription())); } @Test public void getOrCreateCollision() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getOrCreate(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void getOrCreateWithContextSupplier() { final Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("CustomKeyId", new AttributeValue().withS("testCustomKeyId")); attributeValueMap.put("KeyToken", new AttributeValue().withS("testKeyToken")); final Set<String> signedOnlyAttributes = new HashSet<>(); signedOnlyAttributes.add("CustomKeyId"); final TestExtraDataSupplier extraDataSupplier = new TestExtraDataSupplier( attributeValueMap, signedOnlyAttributes); final MetaStore metaStore = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier); assertEquals(-1, metaStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = metaStore.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, metaStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = metaStore.getOrCreate(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void replicateIntermediateKeysTest() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); store.replicate(MATERIAL_NAME, 0, targetStore); assertEquals(0, targetStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final DecryptionMaterials dMat = targetStore.getProvider(MATERIAL_NAME, 0).getDecryptionMaterials(ctx(eMat)); assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test(expectedExceptions = IndexOutOfBoundsException.class) public void replicateIntermediateKeysWhenMaterialNotFoundTest() { store.replicate(MATERIAL_NAME, 0, targetStore); } @Test public void newProviderCollision() throws InterruptedException { final SlowNewProvider slowProv = new SlowNewProvider(); assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); assertEquals(-1, slowProv.slowStore.getMaxVersion(MATERIAL_NAME)); slowProv.start(); Thread.sleep(100); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); slowProv.join(); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); assertEquals(0, slowProv.slowStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = slowProv.result; final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test(expectedExceptions = IndexOutOfBoundsException.class) public void invalidVersion() { store.getProvider(MATERIAL_NAME, 1000); } @Test(expectedExceptions = IllegalArgumentException.class) public void invalidSignedOnlyField() { final Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("enc", new AttributeValue().withS("testEncryptionKey")); final Set<String> signedOnlyAttributes = new HashSet<>(); signedOnlyAttributes.add("enc"); final TestExtraDataSupplier extraDataSupplier = new TestExtraDataSupplier( attributeValueMap, signedOnlyAttributes); new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier); } private static EncryptionContext ctx(final EncryptionMaterials mat) { return new EncryptionContext.Builder() .withMaterialDescription(mat.getMaterialDescription()).build(); } private class SlowNewProvider extends Thread { public volatile EncryptionMaterialsProvider result; public ProviderStore slowStore = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR) { @Override public EncryptionMaterialsProvider newProvider(final String materialName) { final long nextId = getMaxVersion(materialName) + 1; try { Thread.sleep(1000); } catch (final InterruptedException e) { // Ignored } return getOrCreate(materialName, nextId); } }; @Override public void run() { result = slowStore.newProvider(MATERIAL_NAME); } } @SuppressWarnings("unchecked") private static <T> T synchronize(final T obj, final Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() { private final Object lock = new Object(); @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { synchronized (lock) { try { return method.invoke(obj, args); } catch (final InvocationTargetException ex) { throw ex.getCause(); } } } } ); } }
src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/MetaStoreTests.java
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.fail; public class MetaStoreTests { private static final String SOURCE_TABLE_NAME = "keystoreTable"; private static final String DESTINATION_TABLE_NAME = "keystoreDestinationTable"; private static final String MATERIAL_NAME = "material"; private static final SecretKey AES_KEY = new SecretKeySpec(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, "AES"); private static final SecretKey TARGET_AES_KEY = new SecretKeySpec(new byte[]{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}, "AES"); private static final SecretKey HMAC_KEY = new SecretKeySpec(new byte[]{0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256"); private static final SecretKey TARGET_HMAC_KEY = new SecretKeySpec(new byte[]{0, 2, 4, 6, 8, 10, 12, 14}, "HmacSHA256"); private static final EncryptionMaterialsProvider BASE_PROVIDER = new SymmetricStaticProvider(AES_KEY, HMAC_KEY); private static final EncryptionMaterialsProvider TARGET_BASE_PROVIDER = new SymmetricStaticProvider(TARGET_AES_KEY, TARGET_HMAC_KEY); private static final DynamoDBEncryptor ENCRYPTOR = DynamoDBEncryptor.getInstance(BASE_PROVIDER); private static final DynamoDBEncryptor TARGET_ENCRYPTOR = DynamoDBEncryptor.getInstance(TARGET_BASE_PROVIDER); private AmazonDynamoDB client; private AmazonDynamoDB targetClient; private MetaStore store; private MetaStore targetStore; private EncryptionContext ctx; private static class TestExtraDataSupplier implements MetaStore.ExtraDataSupplier { private final Map<String, AttributeValue> attributeValueMap; private final Set<String> signedOnlyFieldNames; public TestExtraDataSupplier(final Map<String, AttributeValue> attributeValueMap, final Set<String> signedOnlyFieldNames) { this.attributeValueMap = attributeValueMap; this.signedOnlyFieldNames = signedOnlyFieldNames; } @Override public Map<String, AttributeValue> getAttributes(String materialName, long version) { return this.attributeValueMap; } @Override public Set<String> getSignedOnlyFieldNames() { return this.signedOnlyFieldNames; } } @BeforeMethod public void setup() { client = synchronize(DynamoDBEmbedded.create(), AmazonDynamoDB.class); targetClient = synchronize(DynamoDBEmbedded.create(), AmazonDynamoDB.class); MetaStore.createTable(client, SOURCE_TABLE_NAME, new ProvisionedThroughput(1L, 1L)); //Creating Targeted DynamoDB Object MetaStore.createTable(targetClient, DESTINATION_TABLE_NAME, new ProvisionedThroughput(1L, 1L)); store = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR); targetStore = new MetaStore(targetClient, DESTINATION_TABLE_NAME, TARGET_ENCRYPTOR); ctx = new EncryptionContext.Builder().build(); } @Test public void testNoMaterials() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); } @Test public void singleMaterial() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialExplicitAccess() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialExplicitAccessWithVersion() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void singleMaterialWithImplicitCreation() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov = store.getProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void twoDifferentMaterials() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.newProvider(MATERIAL_NAME); assertEquals(1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription())); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); try { prov2.getDecryptionMaterials(ctx(eMat)); fail("Missing expected exception"); } catch (final DynamoDBMappingException ex) { // Expected Exception } final EncryptionMaterials eMat2 = prov2.getEncryptionMaterials(ctx); assertEquals(1, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription())); } @Test public void getOrCreateCollision() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = store.getOrCreate(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void getOrCreateWithContextSupplier() { final Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("CustomKeyId", new AttributeValue().withS("testCustomKeyId")); attributeValueMap.put("KeyToken", new AttributeValue().withS("testKeyToken")); final Set<String> signedOnlyAttributes = new HashSet<>(); signedOnlyAttributes.add("CustomKeyId"); final TestExtraDataSupplier extraDataSupplier = new TestExtraDataSupplier( attributeValueMap, signedOnlyAttributes); final MetaStore metaStore = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier); assertEquals(-1, metaStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = metaStore.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, metaStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = metaStore.getOrCreate(MATERIAL_NAME, 0); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test public void replicateIntermediateKeysTest() { assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); store.replicate(MATERIAL_NAME, 0, targetStore); assertEquals(0, targetStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final DecryptionMaterials dMat = targetStore.getProvider(MATERIAL_NAME, 0).getDecryptionMaterials(ctx(eMat)); assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test(expectedExceptions = IndexOutOfBoundsException.class) public void replicateIntermediateKeysWhenMaterialNotFoundTest() { store.replicate(MATERIAL_NAME, 0, targetStore); } @Test public void newProviderCollision() throws InterruptedException { final SlowNewProvider slowProv = new SlowNewProvider(); assertEquals(-1, store.getMaxVersion(MATERIAL_NAME)); assertEquals(-1, slowProv.slowStore.getMaxVersion(MATERIAL_NAME)); slowProv.start(); Thread.sleep(100); final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME); slowProv.join(); assertEquals(0, store.getMaxVersion(MATERIAL_NAME)); assertEquals(0, slowProv.slowStore.getMaxVersion(MATERIAL_NAME)); final EncryptionMaterialsProvider prov2 = slowProv.result; final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx); final SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(eMat.getSigningKey(), dMat.getVerificationKey()); } @Test(expectedExceptions = IndexOutOfBoundsException.class) public void invalidVersion() { store.getProvider(MATERIAL_NAME, 1000); } @Test(expected = IllegalArgumentException.class) public void invalidSignedOnlyField() { final Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("enc", new AttributeValue().withS("testEncryptionKey")); final Set<String> signedOnlyAttributes = new HashSet<>(); signedOnlyAttributes.add("enc"); final TestExtraDataSupplier extraDataSupplier = new TestExtraDataSupplier( attributeValueMap, signedOnlyAttributes); new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier); } private static EncryptionContext ctx(final EncryptionMaterials mat) { return new EncryptionContext.Builder() .withMaterialDescription(mat.getMaterialDescription()).build(); } private class SlowNewProvider extends Thread { public volatile EncryptionMaterialsProvider result; public ProviderStore slowStore = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR) { @Override public EncryptionMaterialsProvider newProvider(final String materialName) { final long nextId = getMaxVersion(materialName) + 1; try { Thread.sleep(1000); } catch (final InterruptedException e) { // Ignored } return getOrCreate(materialName, nextId); } }; @Override public void run() { result = slowStore.newProvider(MATERIAL_NAME); } } @SuppressWarnings("unchecked") private static <T> T synchronize(final T obj, final Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() { private final Object lock = new Object(); @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { synchronized (lock) { try { return method.invoke(obj, args); } catch (final InvocationTargetException ex) { throw ex.getCause(); } } } } ); } }
Fix expected exception on @Test Fixes an expected exception test for testng.
src/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/MetaStoreTests.java
Fix expected exception on @Test
<ide><path>rc/test/java/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/MetaStoreTests.java <ide> store.getProvider(MATERIAL_NAME, 1000); <ide> } <ide> <del> @Test(expected = IllegalArgumentException.class) <add> @Test(expectedExceptions = IllegalArgumentException.class) <ide> public void invalidSignedOnlyField() { <ide> final Map<String, AttributeValue> attributeValueMap = new HashMap<>(); <ide> attributeValueMap.put("enc", new AttributeValue().withS("testEncryptionKey"));
JavaScript
apache-2.0
06ed415699c41763d0c36043369cd4f1cb00fd7f
0
mendix/HTMLSnippet,mendix/HTMLSnippet,mendix/HTMLSnippet
/*jslint -W061:false*/ define([ "dojo/_base/declare", "mxui/widget/_WidgetBase", "dojo/dom-style", "dojo/dom-attr", "dojo/dom-construct", "dojo/_base/lang", "dojo/html", "dijit/layout/LinkPane" ], function ( declare, _WidgetBase, domStyle, domAttr, domConstruct, lang, html, LinkPane ) { "use strict"; return declare("HTMLSnippet.widget.HTMLSnippet", [_WidgetBase], { // Set in Modeler contenttype: "html", contents: "", contentsPath: "", onclickmf: "", documentation: "", refreshOnContextChange: false, refreshOnContextUpdate: false, encloseHTMLWithDiv: true, // Internal _objectChangeHandler: null, contextObj: null, postCreate: function () { logger.debug(this.id + ".postCreate"); this._setupEvents(); if (!this.refreshOnContextChange) { this.executeCode(); } }, executeCode: function () { logger.debug(this.id + ".executeCode"); var external = this.contentsPath !== "" ? true : false; switch (this.contenttype) { case "html": if (external) { new LinkPane({ preload: true, loadingMessage: "", href: this.contentsPath, onDownloadError: function () { console.log("Error loading html path"); } }) .placeAt(this.domNode.id) .startup(); } else if (!this.encloseHTMLWithDiv) { html.set(this.domNode, this.contents); } else { domStyle.set(this.domNode, { height: "auto", width: "100%", outline: 0 }); domAttr.set(this.domNode, "style", this.style); // might override height and width var domNode = domConstruct.create("div", { innerHTML: this.contents }); domConstruct.place(domNode, this.domNode, "only"); } break; case "js": case "jsjQuery": if (external) { var scriptNode = document.createElement("script"), intDate = +new Date(); scriptNode.type = "text/javascript"; scriptNode.src = this.contentsPath + "?v=" + intDate.toString(); domConstruct.place(scriptNode, this.domNode, "only"); } else { if (this.contenttype === "jsjQuery") { this._evalJQueryCode(); } else { this.evalJs(); } } break; } }, update: function (obj, callback) { logger.debug(this.id + ".update"); this.contextObj = obj; if (this.refreshOnContextChange) { this.executeCode(); if (this.refreshOnContextUpdate) { if (this._objectChangeHandler !== null) { this.unsubscribe(this._objectChangeHandler); } if (obj) { this._objectChangeHandler = this.subscribe({ guid: obj.getGuid(), callback: lang.hitch(this, function () { this.executeCode(); }) }); } } } this._executeCallback(callback, "update"); }, _setupEvents: function () { logger.debug(this.id + "._setupEvents"); if (this.onclickmf) { this.connect( this.domNode, "click", this._executeMicroflow ); } }, _executeMicroflow: function () { logger.debug(this.id + "._executeMicroflow"); if (this.onclickmf) { var params = {}; if (this.contextObj !== null) { params.applyto = "selection"; params.guids = [this.contextObj.getGuid()]; } mx.ui.action( this.onclickmf, { params: params, callback: function (obj) { logger.debug( this.id + " (executed microflow successfully)." ); }, error: function (error) { logger.error(this.id + error); } }, this ); } }, evalJs: function () { logger.debug(this.id + ".evalJS"); try { eval(this.contents + "\r\n//# sourceURL=" + this.id + ".js"); } catch (error) { this._handleError(error); } }, _evalJQueryCode: function () { logger.debug(this.id + "._evalJQueryCode"); /*** load jQuery ***/ require(["HTMLSnippet/lib/jquery-3.3.1"], lang.hitch(this, function (jquery_3_3_1) { try { (function (snippetCode) { /** * user's are get used to or might expect to have jQuery available globaly * and they will write their code according to that, and since we, in this widget, don't expose * jQuery globaly, we'll check user's code snippet if there is any attemption to access jQuery * from the global scope ( window ). */ var jqueryIdRegex1 = /window.\jQuery/g; var jqueryIdRegex2 = /window.\$/g; snippetCode = snippetCode.replace(jqueryIdRegex1, 'jQuery'); snippetCode = snippetCode.replace(jqueryIdRegex2, '$'); snippetCode = "var jQuery, $; jQuery = $ = this.jquery;" + // make this jQuery version only accessible and availabe in the scope of this anonymous function snippetCode + "console.debug('your code snippet is evaluated and executed against JQuery version:'+ this.jquery.fn.jquery);"; eval(snippetCode); }).call({ jquery: jquery_3_3_1 // pass JQuery as the context of the immediate function which will wrap the code snippet }, this.contents); // pass the code snippet as an arg } catch (error) { this._handleError(error); } })); }, _handleError: function (error) { logger.debug(this.id + "._handleError"); domConstruct.place( '<div class="alert alert-danger">Error while evaluating javascript input: ' + error + "</div>", this.domNode, "only" ); }, _executeCallback: function (cb, from) { logger.debug(this.id + "._executeCallback" + (from ? " from " + from : "")); if (cb && typeof cb === "function") { cb(); } } }); }); require(["HTMLSnippet/widget/HTMLSnippet"]);
src/HTMLSnippet/widget/HTMLSnippet.js
/*jslint -W061:false*/ define([ "dojo/_base/declare", "mxui/widget/_WidgetBase", "dojo/dom-style", "dojo/dom-attr", "dojo/dom-construct", "dojo/_base/lang", "dojo/html", "dijit/layout/LinkPane" ], function (declare, _WidgetBase, domStyle, domAttr, domConstruct, lang, html, LinkPane) { "use strict"; return declare("HTMLSnippet.widget.HTMLSnippet", [_WidgetBase], { // Set in Modeler contenttype: "html", contents: "", contentsPath: "", onclickmf: "", documentation: "", refreshOnContextChange: false, refreshOnContextUpdate: false, encloseHTMLWithDiv: true, // Internal _objectChangeHandler: null, contextObj: null, postCreate: function () { logger.debug(this.id + ".postCreate"); this._setupEvents(); if (!this.refreshOnContextChange) { this.executeCode(); } }, executeCode: function () { logger.debug(this.id + ".executeCode"); var external = this.contentsPath !== "" ? true : false; switch (this.contenttype) { case "html": if (external) { new LinkPane({ preload: true, loadingMessage: "", href: this.contentsPath, onDownloadError: function () { console.log("Error loading html path"); } }).placeAt(this.domNode.id).startup(); } else if (!this.encloseHTMLWithDiv) { html.set(this.domNode, this.contents); } else { domStyle.set(this.domNode, { "height": "auto", "width": "100%", "outline": 0 }); domAttr.set(this.domNode, "style", this.style); // might override height and width var domNode = domConstruct.create("div", { innerHTML: this.contents }); domConstruct.place(domNode, this.domNode, "only"); } break; case "js": case "jsjQuery": if (external) { var scriptNode = document.createElement("script"), intDate = +new Date(); scriptNode.type = "text/javascript"; scriptNode.src = this.contentsPath + "?v=" + intDate.toString(); domConstruct.place(scriptNode, this.domNode, "only"); } else { if (this.contenttype === "jsjQuery") { require([ "HTMLSnippet/lib/jquery-3.3.1" ], lang.hitch(this, this.evalJs)); } else { this.evalJs(); } } break; } }, update: function (obj, callback) { logger.debug(this.id + ".update"); this.contextObj = obj; if (this.refreshOnContextChange) { this.executeCode(); if (this.refreshOnContextUpdate) { if (this._objectChangeHandler !== null) { this.unsubscribe(this._objectChangeHandler); } if (obj) { this._objectChangeHandler = this.subscribe({ guid: obj.getGuid(), callback: lang.hitch(this, function () { this.executeCode(); }) }); } } } this._executeCallback(callback, "update"); }, _setupEvents: function () { logger.debug(this.id + "._setupEvents"); if (this.onclickmf) { this.connect(this.domNode, "click", this._executeMicroflow); } }, _executeMicroflow: function () { logger.debug(this.id + "._executeMicroflow"); if (this.onclickmf) { var params = {}; if (this.contextObj !== null) { params.applyto = "selection"; params.guids = [this.contextObj.getGuid()]; } mx.ui.action(this.onclickmf, { params: params, callback: function (obj) { logger.debug(this.id + " (executed microflow successfully)."); }, error: function (error) { logger.error(this.id + error); } }, this); } }, evalJs: function () { logger.debug(this.id + ".evalJS"); try { eval(this.contents + "\r\n//# sourceURL=" + this.id + ".js"); } catch (e) { domConstruct.place("<div class=\"alert alert-danger\">Error while evaluating javascript input: " + e + "</div>", this.domNode, "only"); } }, _executeCallback: function (cb, from) { logger.debug(this.id + "._executeCallback" + (from ? " from " + from : "")); if (cb && typeof cb === "function") { cb(); } } }); }); require(["HTMLSnippet/widget/HTMLSnippet"]);
wrap Jquery code in its own context
src/HTMLSnippet/widget/HTMLSnippet.js
wrap Jquery code in its own context
<ide><path>rc/HTMLSnippet/widget/HTMLSnippet.js <ide> "dojo/_base/lang", <ide> "dojo/html", <ide> "dijit/layout/LinkPane" <del>], function (declare, _WidgetBase, domStyle, domAttr, domConstruct, lang, html, LinkPane) { <add>], function ( <add> declare, <add> _WidgetBase, <add> domStyle, <add> domAttr, <add> domConstruct, <add> lang, <add> html, <add> LinkPane <add>) { <ide> "use strict"; <ide> <ide> return declare("HTMLSnippet.widget.HTMLSnippet", [_WidgetBase], { <del> <ide> // Set in Modeler <ide> contenttype: "html", <ide> contents: "", <ide> case "html": <ide> if (external) { <ide> new LinkPane({ <del> preload: true, <del> loadingMessage: "", <del> href: this.contentsPath, <del> onDownloadError: function () { <del> console.log("Error loading html path"); <del> } <del> }).placeAt(this.domNode.id).startup(); <add> preload: true, <add> loadingMessage: "", <add> href: this.contentsPath, <add> onDownloadError: function () { <add> console.log("Error loading html path"); <add> } <add> }) <add> .placeAt(this.domNode.id) <add> .startup(); <ide> } else if (!this.encloseHTMLWithDiv) { <ide> html.set(this.domNode, this.contents); <ide> } else { <ide> domStyle.set(this.domNode, { <del> "height": "auto", <del> "width": "100%", <del> "outline": 0 <add> height: "auto", <add> width: "100%", <add> outline: 0 <ide> }); <ide> <ide> domAttr.set(this.domNode, "style", this.style); // might override height and width <ide> intDate = +new Date(); <ide> <ide> scriptNode.type = "text/javascript"; <del> scriptNode.src = this.contentsPath + "?v=" + intDate.toString(); <add> scriptNode.src = <add> this.contentsPath + "?v=" + intDate.toString(); <ide> <ide> domConstruct.place(scriptNode, this.domNode, "only"); <ide> } else { <ide> if (this.contenttype === "jsjQuery") { <del> require([ <del> "HTMLSnippet/lib/jquery-3.3.1" <del> ], lang.hitch(this, this.evalJs)); <add> this._evalJQueryCode(); <ide> } else { <ide> this.evalJs(); <ide> } <ide> _setupEvents: function () { <ide> logger.debug(this.id + "._setupEvents"); <ide> if (this.onclickmf) { <del> this.connect(this.domNode, "click", this._executeMicroflow); <add> this.connect( <add> this.domNode, <add> "click", <add> this._executeMicroflow <add> ); <ide> } <ide> }, <ide> <ide> params.applyto = "selection"; <ide> params.guids = [this.contextObj.getGuid()]; <ide> } <del> mx.ui.action(this.onclickmf, { <del> params: params, <del> callback: function (obj) { <del> logger.debug(this.id + " (executed microflow successfully)."); <add> mx.ui.action( <add> this.onclickmf, { <add> params: params, <add> callback: function (obj) { <add> logger.debug( <add> this.id + " (executed microflow successfully)." <add> ); <add> }, <add> error: function (error) { <add> logger.error(this.id + error); <add> } <ide> }, <del> error: function (error) { <del> logger.error(this.id + error); <del> } <del> }, this); <add> this <add> ); <ide> } <ide> }, <ide> <ide> logger.debug(this.id + ".evalJS"); <ide> try { <ide> eval(this.contents + "\r\n//# sourceURL=" + this.id + ".js"); <del> } catch (e) { <del> domConstruct.place("<div class=\"alert alert-danger\">Error while evaluating javascript input: " + e + "</div>", this.domNode, "only"); <del> } <add> } catch (error) { <add> this._handleError(error); <add> } <add> }, <add> <add> _evalJQueryCode: function () { <add> logger.debug(this.id + "._evalJQueryCode"); <add> /*** load jQuery ***/ <add> require(["HTMLSnippet/lib/jquery-3.3.1"], lang.hitch(this, function (jquery_3_3_1) { <add> try { <add> <add> (function (snippetCode) { <add> <add> /** <add> * user's are get used to or might expect to have jQuery available globaly <add> * and they will write their code according to that, and since we, in this widget, don't expose <add> * jQuery globaly, we'll check user's code snippet if there is any attemption to access jQuery <add> * from the global scope ( window ). <add> */ <add> var jqueryIdRegex1 = /window.\jQuery/g; <add> var jqueryIdRegex2 = /window.\$/g; <add> snippetCode = snippetCode.replace(jqueryIdRegex1, 'jQuery'); <add> snippetCode = snippetCode.replace(jqueryIdRegex2, '$'); <add> <add> snippetCode = "var jQuery, $; jQuery = $ = this.jquery;" + // make this jQuery version only accessible and availabe in the scope of this anonymous function <add> snippetCode + <add> "console.debug('your code snippet is evaluated and executed against JQuery version:'+ this.jquery.fn.jquery);"; <add> eval(snippetCode); <add> }).call({ <add> jquery: jquery_3_3_1 // pass JQuery as the context of the immediate function which will wrap the code snippet <add> }, this.contents); // pass the code snippet as an arg <add> } catch (error) { <add> this._handleError(error); <add> } <add> })); <add> }, <add> <add> <add> _handleError: function (error) { <add> logger.debug(this.id + "._handleError"); <add> domConstruct.place( <add> '<div class="alert alert-danger">Error while evaluating javascript input: ' + <add> error + <add> "</div>", <add> this.domNode, <add> "only" <add> ); <ide> }, <ide> <ide> _executeCallback: function (cb, from) {
Java
epl-1.0
5fa794ea7b1c94127c8dc59c70958d0645b1446f
0
codenvy/plugin-datasource,codenvy/plugin-datasource
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/shared/RequestResultDTO.java
/* * CODENVY CONFIDENTIAL * __________________ * * [2013] - [2014] Codenvy, S.A. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Codenvy S.A. and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Codenvy S.A. * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Codenvy S.A.. */ package com.codenvy.ide.ext.datasource.shared; import java.util.List; import com.codenvy.dto.shared.DTO; @DTO public interface RequestResultDTO { List<List<String>> getLines(); void setLines(List<List<String>> lines); RequestResultDTO withLines(List<List<String>> lines); }
Remove unused class
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/shared/RequestResultDTO.java
Remove unused class
<ide><path>odenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/shared/RequestResultDTO.java <del>/* <del> * CODENVY CONFIDENTIAL <del> * __________________ <del> * <del> * [2013] - [2014] Codenvy, S.A. <del> * All Rights Reserved. <del> * <del> * NOTICE: All information contained herein is, and remains <del> * the property of Codenvy S.A. and its suppliers, <del> * if any. The intellectual and technical concepts contained <del> * herein are proprietary to Codenvy S.A. <del> * and its suppliers and may be covered by U.S. and Foreign Patents, <del> * patents in process, and are protected by trade secret or copyright law. <del> * Dissemination of this information or reproduction of this material <del> * is strictly forbidden unless prior written permission is obtained <del> * from Codenvy S.A.. <del> */ <del>package com.codenvy.ide.ext.datasource.shared; <del> <del>import java.util.List; <del> <del>import com.codenvy.dto.shared.DTO; <del> <del>@DTO <del>public interface RequestResultDTO { <del> <del> List<List<String>> getLines(); <del> <del> void setLines(List<List<String>> lines); <del> <del> RequestResultDTO withLines(List<List<String>> lines); <del>}
Java
mit
27a2df59973bcbd2c03b931c136918251edcac01
0
ZoltanDalmadi/JCardGamesFX
package hu.unideb.inf.JCardGamesFX.klondike; import hu.unideb.inf.JCardGamesFX.model.Card; import hu.unideb.inf.JCardGamesFX.model.CardPile; import hu.unideb.inf.JCardGamesFX.view.CardPileView; import hu.unideb.inf.JCardGamesFX.view.CardTheme; import hu.unideb.inf.JCardGamesFX.view.CardView; import hu.unideb.inf.JCardGamesFX.view.CardViewFactory; import javafx.application.Application; import javafx.collections.ListChangeListener; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import org.json.simple.parser.ParseException; import java.io.IOException; import java.util.Iterator; import java.util.stream.IntStream; public class KlondikeApp extends Application { private static final double WIDTH = 1280; private static final double HEIGHT = 800; private KlondikeGame game; private KlondikeGameArea gameArea; private KlondikeMouseUtil mouseUtil; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { // Game area gameArea = new KlondikeGameArea(new Image("/tableaous/green-felt.png")); // Menu bar KlondikeMenu menuBar = new KlondikeMenu(); // Status bar KlondikeStatusBar statusBar = new KlondikeStatusBar(); // Main element BorderPane bord = new BorderPane(); bord.setCenter(gameArea); bord.setTop(menuBar); bord.setBottom(statusBar); Scene scene = new Scene(bord, WIDTH, HEIGHT); try { CardViewFactory.setCardTheme(new CardTheme("/cardfaces/classic/theme.json", "/backfaces/bb.png")); } catch (IOException | ParseException e) { e.printStackTrace(); } game = new KlondikeGame(); game.startNewGame(); mouseUtil = new KlondikeMouseUtil(game, gameArea); prepareGameAreaForNewGame(); // auto-flip cards IntStream.range(0, game.getStandardPiles().size()).forEach(i -> { CardPileView actPileView = gameArea.getStandardPileViews().get(i); CardPile actPile = game.getPileById(actPileView.getShortID()); actPileView.getCards().addListener( (ListChangeListener<CardView>) c -> { while (c.next()) { if (c.wasRemoved()) { if (!actPileView.isEmpty()) { CardView toFlip = actPileView.getTopCardView(); toFlip.setMouseTransparent(false); if (!toFlip.isFaceDown()) toFlip.flip(); } if (!actPile.isEmpty()) actPile.getTopCard().flip(); } } }); }); primaryStage.setTitle("JavaFX Klondike"); primaryStage.setScene(scene); primaryStage.show(); } private void prepareGameAreaForNewGame() { // deal to piles Iterator<Card> deckIterator = game.getDeck().iterator(); int cardsToPut = 1; for (CardPileView standardPileView : gameArea.getStandardPileViews()) { for (int i = 0; i < cardsToPut; i++) { standardPileView.addCardView(CardViewFactory.createCardView(deckIterator.next())); gameArea.getChildren().add(standardPileView.getTopCardView()); mouseUtil.makeDraggable(standardPileView.getTopCardView()); standardPileView.getTopCardView().setMouseTransparent(true); } standardPileView.getTopCardView().flip(); standardPileView.getTopCardView().setMouseTransparent(false); cardsToPut++; } deckIterator.forEachRemaining(card -> { gameArea.getStockView().addCardView(CardViewFactory.createCardView(card)); gameArea.getChildren().add(gameArea.getStockView().getTopCardView()); }); } }
src/main/java/hu/unideb/inf/JCardGamesFX/klondike/KlondikeApp.java
package hu.unideb.inf.JCardGamesFX.klondike; import hu.unideb.inf.JCardGamesFX.model.Card; import hu.unideb.inf.JCardGamesFX.model.CardPile; import hu.unideb.inf.JCardGamesFX.view.CardPileView; import hu.unideb.inf.JCardGamesFX.view.CardTheme; import hu.unideb.inf.JCardGamesFX.view.CardView; import hu.unideb.inf.JCardGamesFX.view.CardViewFactory; import javafx.application.Application; import javafx.collections.ListChangeListener; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import org.json.simple.parser.ParseException; import java.io.IOException; import java.util.Iterator; import java.util.stream.IntStream; public class KlondikeApp extends Application { private static final double WIDTH = 1280; private static final double HEIGHT = 800; private KlondikeGame game; private KlondikeGameArea gameArea; private KlondikeMouseUtil mouseUtil; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { // Game area gameArea = new KlondikeGameArea(new Image("/tableaous/green-felt.png")); // Menu bar KlondikeMenu menuBar = new KlondikeMenu(); // Status bar KlondikeStatusBar statusBar = new KlondikeStatusBar(); // Main element BorderPane bord = new BorderPane(); bord.setCenter(gameArea); bord.setTop(menuBar); bord.setBottom(statusBar); Scene scene = new Scene(bord, WIDTH, HEIGHT); try { CardViewFactory.setCardTheme(new CardTheme("/cardfaces/classic/theme.json", "/backfaces/bb.png")); } catch (IOException | ParseException e) { e.printStackTrace(); } game = new KlondikeGame(); game.startNewGame(); mouseUtil = new KlondikeMouseUtil(game, gameArea); prepareGameAreaForNewGame(); // auto-flip cards IntStream.range(0, game.getStandardPiles().size()).forEach(i -> { CardPileView actPileView = gameArea.getStandardPileViews().get(i); CardPile actPile = game.getPileById(actPileView.getShortID()); actPileView.getCards().addListener( (ListChangeListener<CardView>) c -> { while (c.next()) { if (c.wasRemoved()) { if (!actPileView.isEmpty()) { CardView toFlip = actPileView.getTopCardView(); toFlip.setMouseTransparent(false); toFlip.flip(); } if (!actPile.isEmpty()) actPile.getTopCard().flip(); } } }); }); primaryStage.setTitle("JavaFX Klondike"); primaryStage.setScene(scene); primaryStage.show(); } private void prepareGameAreaForNewGame() { // deal to piles Iterator<Card> deckIterator = game.getDeck().iterator(); int cardsToPut = 1; for (CardPileView standardPileView : gameArea.getStandardPileViews()) { for (int i = 0; i < cardsToPut; i++) { standardPileView.addCardView(CardViewFactory.createCardView(deckIterator.next())); gameArea.getChildren().add(standardPileView.getTopCardView()); mouseUtil.makeDraggable(standardPileView.getTopCardView()); standardPileView.getTopCardView().setMouseTransparent(true); } standardPileView.getTopCardView().flip(); standardPileView.getTopCardView().setMouseTransparent(false); cardsToPut++; } deckIterator.forEachRemaining(card -> { gameArea.getStockView().addCardView(CardViewFactory.createCardView(card)); gameArea.getChildren().add(gameArea.getStockView().getTopCardView()); }); } }
Added extra check before flipping the card
src/main/java/hu/unideb/inf/JCardGamesFX/klondike/KlondikeApp.java
Added extra check before flipping the card
<ide><path>rc/main/java/hu/unideb/inf/JCardGamesFX/klondike/KlondikeApp.java <ide> if (!actPileView.isEmpty()) { <ide> CardView toFlip = actPileView.getTopCardView(); <ide> toFlip.setMouseTransparent(false); <del> toFlip.flip(); <add> if (!toFlip.isFaceDown()) <add> toFlip.flip(); <ide> } <ide> if (!actPile.isEmpty()) <ide> actPile.getTopCard().flip();
Java
mit
72ee8366d92d14e5bfc254bd7cdeb5810688924c
0
BeYkeRYkt/LightAPI
/* * The MIT License (MIT) * * Copyright 2021 Vladimir Mikhailov <[email protected]> * * 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 ru.beykerykt.lightapi; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import ru.beykerykt.lightapi.chunks.ChunkInfo; import ru.beykerykt.lightapi.events.DeleteLightEvent; import ru.beykerykt.lightapi.events.SetLightEvent; import ru.beykerykt.lightapi.events.UpdateChunkEvent; import ru.beykerykt.minecraft.lightapi.bukkit.api.extension.IBukkitExtension; import ru.beykerykt.minecraft.lightapi.bukkit.internal.handler.IHandler; import ru.beykerykt.minecraft.lightapi.common.api.engine.LightFlag; import ru.beykerykt.minecraft.lightapi.common.internal.chunks.data.IChunkData; @Deprecated public class LightAPI extends JavaPlugin { private static final String DEPRECATED_MSG = "The package \"ru.beykerykt.lightapi\" is outdated! Switch to the new package \"ru.beykerykt.minecraft.lightapi.*\" or turn on the \"force-enable-legacy\" mode."; @Deprecated private static final BlockFace[] SIDES = {BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; private static boolean isBackwardEnabled() { return ((IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension()).isBackwardAvailable(); } @Deprecated private static void log(CommandSender sender, String message) { sender.sendMessage(ChatColor.RED + "<LightAPI-Backward>: " + message); } @Deprecated public static LightAPI getInstance() { return null; } @Deprecated public static boolean createLight(Location location, int lightlevel, boolean async) { return createLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightlevel, async); } @Deprecated public static boolean createLight(final World world, final int x, final int y, final int z, final int lightlevel, boolean async) { return createLight(world, x, y, z, ru.beykerykt.lightapi.LightType.BLOCK, lightlevel, async); } @Deprecated public static boolean deleteLight(Location location, boolean async) { return deleteLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), async); } @Deprecated public static boolean deleteLight(final World world, final int x, final int y, final int z, boolean async) { return deleteLight(world, x, y, z, ru.beykerykt.lightapi.LightType.BLOCK, async); } @Deprecated public static List<ChunkInfo> collectChunks(Location location) { return collectChunks(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Deprecated public static List<ChunkInfo> collectChunks(final World world, final int x, final int y, final int z) { return collectChunks(world, x, y, z, ru.beykerykt.lightapi.LightType.BLOCK, 15); } @Deprecated public static boolean updateChunks(ChunkInfo info) { return updateChunk(info); } @Deprecated public static boolean updateChunk(ChunkInfo info) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); return false; } UpdateChunkEvent event = new UpdateChunkEvent(info); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); // TODO: Say to handler IChunkData newData = handler.createChunkData(event.getChunkInfo().getWorld().getName(), event.getChunkInfo().getChunkX(), event.getChunkInfo().getChunkZ()); newData.setFullSections(); handler.sendChunk(newData); return true; } return false; } @Deprecated public static boolean updateChunks(Location location, Collection<? extends Player> players) { return updateChunks(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), players); } @Deprecated public static boolean updateChunks(World world, int x, int y, int z, Collection<? extends Player> players) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); return false; } IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); for (IChunkData newData : handler.collectChunkSections(world, x, y, z, 15, LightFlag.BLOCK_LIGHTING | LightFlag.SKY_LIGHTING)) { handler.sendChunk(newData); } return true; } @Deprecated public static boolean updateChunk(Location location, Collection<? extends Player> players) { return updateChunk(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), players); } @Deprecated public static boolean updateChunk(World world, int x, int y, int z, Collection<? extends Player> players) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); return false; } IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); IChunkData data = ext.getHandler().createChunkData(world.getName(), x >> 4, z >> 4); data.setFullSections(); handler.sendChunk(data); return true; } @Deprecated public static Block getAdjacentAirBlock(Block block) { for (BlockFace face : SIDES) { if (block.getY() == 0x0 && face == BlockFace.DOWN) { continue; } if (block.getY() == 0xFF && face == BlockFace.UP) { continue; } Block candidate = block.getRelative(face); if (candidate.getType().isTransparent()) { return candidate; } } return block; } // Qvesh's fork - start @Deprecated public static boolean createLight(Location location, ru.beykerykt.lightapi.LightType lightType, int lightlevel, boolean async) { return createLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightType, lightlevel, async); } @Deprecated public static boolean createLight(World world, int x, final int y, final int z, ru.beykerykt.lightapi.LightType lightType, final int lightlevel, boolean async) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); return false; } int flags = LightFlag.NONE; if (lightType == ru.beykerykt.lightapi.LightType.BLOCK) { flags |= LightFlag.BLOCK_LIGHTING; } else if (lightType == ru.beykerykt.lightapi.LightType.SKY) { flags |= LightFlag.SKY_LIGHTING; } final SetLightEvent event = new SetLightEvent(world, x, y, z, lightlevel, async); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { /* if (ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getImplHandler().isAsyncLighting()) { // not supported return false; } */ IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int oldlightlevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); handler.setRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), event.getLightLevel(), flags); handler.recalculateLighting(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); // check light int newLightLevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); return newLightLevel >= oldlightlevel; } return false; } @Deprecated public static boolean deleteLight(Location location, ru.beykerykt.lightapi.LightType lightType, boolean async) { return deleteLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightType, async); } @Deprecated public static boolean deleteLight(final World world, final int x, final int y, final int z, ru.beykerykt.lightapi.LightType lightType, boolean async) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); return false; } int flags = LightFlag.NONE; if (lightType == ru.beykerykt.lightapi.LightType.BLOCK) { flags |= LightFlag.BLOCK_LIGHTING; } else if (lightType == ru.beykerykt.lightapi.LightType.SKY) { flags |= LightFlag.SKY_LIGHTING; } final DeleteLightEvent event = new DeleteLightEvent(world, x, y, z, async); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { /* if (ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getAdapterImpl().isAsyncLighting()) { // not supported return false; } */ IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int oldlightlevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); handler.setRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), 0, flags); handler.recalculateLighting(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); // check light int newLightLevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); return newLightLevel != oldlightlevel; } return false; } public static List<ChunkInfo> collectChunks(Location location, ru.beykerykt.lightapi.LightType lightType, int lightLevel) { return collectChunks(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightType, lightLevel); } public static List<ChunkInfo> collectChunks(World world, int x, int y, int z, ru.beykerykt.lightapi.LightType lightType, int lightLevel) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); return null; } List<ChunkInfo> list = new CopyOnWriteArrayList<ChunkInfo>(); IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int lightTypeNew = LightFlag.BLOCK_LIGHTING; if (lightType == ru.beykerykt.lightapi.LightType.SKY) { lightTypeNew = LightFlag.SKY_LIGHTING; } for (IChunkData newData : handler.collectChunkSections(world, x, y, z, lightLevel, lightTypeNew)) { ChunkInfo info = new ChunkInfo(world, newData.getChunkX(), newData.getChunkZ(), world.getPlayers()); if (!list.contains(info)) { list.add(info); } } return list; } public static boolean updateChunk(ChunkInfo info, ru.beykerykt.lightapi.LightType lightType) { return updateChunk(info, lightType, null); } public static boolean updateChunk(ChunkInfo info, ru.beykerykt.lightapi.LightType lightType, Collection<? extends Player> players) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); return false; } UpdateChunkEvent event = new UpdateChunkEvent(info); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); // TODO: Say to handler IChunkData newData = handler.createChunkData(event.getChunkInfo().getWorld().getName(), event.getChunkInfo().getChunkX(), event.getChunkInfo().getChunkZ()); newData.setFullSections(); handler.sendChunk(newData); return true; } return false; } @Deprecated public static boolean isSupported(World world, ru.beykerykt.lightapi.LightType type) { IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int flag = LightFlag.BLOCK_LIGHTING; if (type == ru.beykerykt.lightapi.LightType.SKY) { flag = LightFlag.SKY_LIGHTING; } return handler.isLightingSupported(world, flag); } @Deprecated public int getUpdateDelayTicks() { return 0; } @Deprecated public void setUpdateDelayTicks(int update_delay_ticks) { } @Deprecated public int getMaxIterationsPerTick() { return 0; } @Deprecated public void setMaxIterationsPerTick(int max_iterations_per_tick) { } // Qvesh's fork - end }
bukkit-backward-support/src/main/java/ru/beykerykt/lightapi/LightAPI.java
/* * The MIT License (MIT) * * Copyright 2021 Vladimir Mikhailov <[email protected]> * * 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 ru.beykerykt.lightapi; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import ru.beykerykt.lightapi.chunks.ChunkInfo; import ru.beykerykt.lightapi.events.DeleteLightEvent; import ru.beykerykt.lightapi.events.SetLightEvent; import ru.beykerykt.lightapi.events.UpdateChunkEvent; import ru.beykerykt.minecraft.lightapi.bukkit.api.extension.IBukkitExtension; import ru.beykerykt.minecraft.lightapi.bukkit.internal.handler.IHandler; import ru.beykerykt.minecraft.lightapi.common.api.engine.LightFlag; import ru.beykerykt.minecraft.lightapi.common.internal.chunks.data.IChunkData; @Deprecated public class LightAPI extends JavaPlugin { @Deprecated private static final BlockFace[] SIDES = {BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; private static boolean isBackwardEnabled() { return ((IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension()).isBackwardAvailable(); } @Deprecated private static void log(CommandSender sender, String message) { sender.sendMessage(ChatColor.RED + "<LightAPI-Backward>: " + message); } @Deprecated public static LightAPI getInstance() { return null; } @Deprecated public static boolean createLight(Location location, int lightlevel, boolean async) { return createLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightlevel, async); } @Deprecated public static boolean createLight(final World world, final int x, final int y, final int z, final int lightlevel, boolean async) { return createLight(world, x, y, z, ru.beykerykt.lightapi.LightType.BLOCK, lightlevel, async); } @Deprecated public static boolean deleteLight(Location location, boolean async) { return deleteLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), async); } @Deprecated public static boolean deleteLight(final World world, final int x, final int y, final int z, boolean async) { return deleteLight(world, x, y, z, ru.beykerykt.lightapi.LightType.BLOCK, async); } @Deprecated public static List<ChunkInfo> collectChunks(Location location) { return collectChunks(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Deprecated public static List<ChunkInfo> collectChunks(final World world, final int x, final int y, final int z) { return collectChunks(world, x, y, z, ru.beykerykt.lightapi.LightType.BLOCK, 15); } @Deprecated public static boolean updateChunks(ChunkInfo info) { return updateChunk(info); } @Deprecated public static boolean updateChunk(ChunkInfo info) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); return false; } UpdateChunkEvent event = new UpdateChunkEvent(info); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); // TODO: Say to handler IChunkData newData = handler.createChunkData(event.getChunkInfo().getWorld().getName(), event.getChunkInfo().getChunkX(), event.getChunkInfo().getChunkZ()); newData.setFullSections(); handler.sendChunk(newData); return true; } return false; } @Deprecated public static boolean updateChunks(Location location, Collection<? extends Player> players) { return updateChunks(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), players); } @Deprecated public static boolean updateChunks(World world, int x, int y, int z, Collection<? extends Player> players) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); return false; } IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); for (IChunkData newData : handler.collectChunkSections(world, x, y, z, 15, LightFlag.BLOCK_LIGHTING | LightFlag.SKY_LIGHTING)) { handler.sendChunk(newData); } return true; } @Deprecated public static boolean updateChunk(Location location, Collection<? extends Player> players) { return updateChunk(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), players); } @Deprecated public static boolean updateChunk(World world, int x, int y, int z, Collection<? extends Player> players) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); return false; } IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); IChunkData data = ext.getHandler().createChunkData(world.getName(), x >> 4, z >> 4); data.setFullSections(); handler.sendChunk(data); return true; } @Deprecated public static Block getAdjacentAirBlock(Block block) { for (BlockFace face : SIDES) { if (block.getY() == 0x0 && face == BlockFace.DOWN) { continue; } if (block.getY() == 0xFF && face == BlockFace.UP) { continue; } Block candidate = block.getRelative(face); if (candidate.getType().isTransparent()) { return candidate; } } return block; } // Qvesh's fork - start @Deprecated public static boolean createLight(Location location, ru.beykerykt.lightapi.LightType lightType, int lightlevel, boolean async) { return createLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightType, lightlevel, async); } @Deprecated public static boolean createLight(World world, int x, final int y, final int z, ru.beykerykt.lightapi.LightType lightType, final int lightlevel, boolean async) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); return false; } int flags = LightFlag.NONE; if (lightType == ru.beykerykt.lightapi.LightType.BLOCK) { flags |= LightFlag.BLOCK_LIGHTING; } else if (lightType == ru.beykerykt.lightapi.LightType.SKY) { flags |= LightFlag.SKY_LIGHTING; } final SetLightEvent event = new SetLightEvent(world, x, y, z, lightlevel, async); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { /* if (ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getImplHandler().isAsyncLighting()) { // not supported return false; } */ IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int oldlightlevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); handler.setRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), event.getLightLevel(), flags); handler.recalculateLighting(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); // check light int newLightLevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); return newLightLevel >= oldlightlevel; } return false; } @Deprecated public static boolean deleteLight(Location location, ru.beykerykt.lightapi.LightType lightType, boolean async) { return deleteLight(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightType, async); } @Deprecated public static boolean deleteLight(final World world, final int x, final int y, final int z, ru.beykerykt.lightapi.LightType lightType, boolean async) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); return false; } int flags = LightFlag.NONE; if (lightType == ru.beykerykt.lightapi.LightType.BLOCK) { flags |= LightFlag.BLOCK_LIGHTING; } else if (lightType == ru.beykerykt.lightapi.LightType.SKY) { flags |= LightFlag.SKY_LIGHTING; } final DeleteLightEvent event = new DeleteLightEvent(world, x, y, z, async); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { /* if (ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getAdapterImpl().isAsyncLighting()) { // not supported return false; } */ IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int oldlightlevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); handler.setRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), 0, flags); handler.recalculateLighting(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); // check light int newLightLevel = handler.getRawLightLevel(event.getWorld(), event.getX(), event.getY(), event.getZ(), flags); return newLightLevel != oldlightlevel; } return false; } public static List<ChunkInfo> collectChunks(Location location, ru.beykerykt.lightapi.LightType lightType, int lightLevel) { return collectChunks(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), lightType, lightLevel); } public static List<ChunkInfo> collectChunks(World world, int x, int y, int z, ru.beykerykt.lightapi.LightType lightType, int lightLevel) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); return null; } List<ChunkInfo> list = new CopyOnWriteArrayList<ChunkInfo>(); IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int lightTypeNew = LightFlag.BLOCK_LIGHTING; if (lightType == ru.beykerykt.lightapi.LightType.SKY) { lightTypeNew = LightFlag.SKY_LIGHTING; } for (IChunkData newData : handler.collectChunkSections(world, x, y, z, lightLevel, lightTypeNew)) { ChunkInfo info = new ChunkInfo(world, newData.getChunkX(), newData.getChunkZ(), world.getPlayers()); if (!list.contains(info)) { list.add(info); } } return list; } public static boolean updateChunk(ChunkInfo info, ru.beykerykt.lightapi.LightType lightType) { return updateChunk(info, lightType, null); } public static boolean updateChunk(ChunkInfo info, ru.beykerykt.lightapi.LightType lightType, Collection<? extends Player> players) { if (!isBackwardEnabled()) { log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); return false; } UpdateChunkEvent event = new UpdateChunkEvent(info); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); // TODO: Say to handler IChunkData newData = handler.createChunkData(event.getChunkInfo().getWorld().getName(), event.getChunkInfo().getChunkX(), event.getChunkInfo().getChunkZ()); newData.setFullSections(); handler.sendChunk(newData); return true; } return false; } @Deprecated public static boolean isSupported(World world, ru.beykerykt.lightapi.LightType type) { IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); IHandler handler = ext.getHandler(); int flag = LightFlag.BLOCK_LIGHTING; if (type == ru.beykerykt.lightapi.LightType.SKY) { flag = LightFlag.SKY_LIGHTING; } return handler.isLightingSupported(world, flag); } @Deprecated public int getUpdateDelayTicks() { return 0; } @Deprecated public void setUpdateDelayTicks(int update_delay_ticks) { } @Deprecated public int getMaxIterationsPerTick() { return 0; } @Deprecated public void setMaxIterationsPerTick(int max_iterations_per_tick) { } // Qvesh's fork - end }
LightAPI: bukkit-backward-support: Update deprecated message Change-Id: I6397c5e869c5c1eaa261376663bf86e7982cf010
bukkit-backward-support/src/main/java/ru/beykerykt/lightapi/LightAPI.java
LightAPI: bukkit-backward-support: Update deprecated message
<ide><path>ukkit-backward-support/src/main/java/ru/beykerykt/lightapi/LightAPI.java <ide> @Deprecated <ide> public class LightAPI extends JavaPlugin { <ide> <add> private static final String DEPRECATED_MSG = <add> "The package \"ru.beykerykt.lightapi\" is outdated! Switch to the new package \"ru.beykerykt.minecraft.lightapi.*\" or turn on the \"force-enable-legacy\" mode."; <add> <ide> @Deprecated <ide> private static final BlockFace[] SIDES = <ide> {BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; <ide> @Deprecated <ide> public static boolean updateChunk(ChunkInfo info) { <ide> if (!isBackwardEnabled()) { <del> log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); <add> log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); <ide> return false; <ide> } <ide> UpdateChunkEvent event = new UpdateChunkEvent(info); <ide> @Deprecated <ide> public static boolean updateChunks(World world, int x, int y, int z, Collection<? extends Player> players) { <ide> if (!isBackwardEnabled()) { <del> log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); <add> log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); <ide> return false; <ide> } <ide> IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); <ide> @Deprecated <ide> public static boolean updateChunk(World world, int x, int y, int z, Collection<? extends Player> players) { <ide> if (!isBackwardEnabled()) { <del> log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); <add> log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); <ide> return false; <ide> } <ide> IBukkitExtension ext = (IBukkitExtension) ru.beykerykt.minecraft.lightapi.common.LightAPI.get().getExtension(); <ide> public static boolean createLight(World world, int x, final int y, final int z, <ide> ru.beykerykt.lightapi.LightType lightType, final int lightlevel, boolean async) { <ide> if (!isBackwardEnabled()) { <del> log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); <add> log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); <ide> return false; <ide> } <ide> int flags = LightFlag.NONE; <ide> public static boolean deleteLight(final World world, final int x, final int y, final int z, <ide> ru.beykerykt.lightapi.LightType lightType, boolean async) { <ide> if (!isBackwardEnabled()) { <del> log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); <add> log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); <ide> return false; <ide> } <ide> int flags = LightFlag.NONE; <ide> public static List<ChunkInfo> collectChunks(World world, int x, int y, int z, <ide> ru.beykerykt.lightapi.LightType lightType, int lightLevel) { <ide> if (!isBackwardEnabled()) { <del> log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); <add> log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); <ide> return null; <ide> } <ide> List<ChunkInfo> list = new CopyOnWriteArrayList<ChunkInfo>(); <ide> public static boolean updateChunk(ChunkInfo info, ru.beykerykt.lightapi.LightType lightType, <ide> Collection<? extends Player> players) { <ide> if (!isBackwardEnabled()) { <del> log(Bukkit.getServer().getConsoleSender(), "Sorry, but now you can not use the old version of the API."); <add> log(Bukkit.getServer().getConsoleSender(), DEPRECATED_MSG); <ide> return false; <ide> } <ide> UpdateChunkEvent event = new UpdateChunkEvent(info);
Java
mit
31f730c8f3ed7e57b5c82a957c9fa5e95b14fceb
0
games647/ChangeSkin
package com.github.games647.changeskin.bukkit.tasks; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.reflect.FieldAccessException; import com.comphenix.protocol.utility.MinecraftVersion; import com.comphenix.protocol.wrappers.EnumWrappers.Difficulty; import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode; import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction; import com.comphenix.protocol.wrappers.PlayerInfoData; import com.comphenix.protocol.wrappers.WrappedChatComponent; import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.github.games647.changeskin.bukkit.ChangeSkinBukkit; import com.github.games647.changeskin.core.ChangeSkinCore; import com.github.games647.changeskin.core.model.SkinData; import com.github.games647.changeskin.core.model.UserPreference; import com.google.common.collect.Lists; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.attribute.Attribute; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class SkinUpdater implements Runnable { protected final ChangeSkinBukkit plugin; private final CommandSender invoker; private final Player receiver; private final SkinData targetSkin; private final boolean keepSkin; public SkinUpdater(ChangeSkinBukkit plugin, CommandSender invoker, Player receiver , SkinData targetSkin, boolean keepSkin) { this.plugin = plugin; this.invoker = invoker; this.receiver = receiver; this.targetSkin = targetSkin; this.keepSkin = keepSkin; } @Override public void run() { if (receiver == null || !receiver.isOnline()) { return; } //uuid was successfull resolved, we could now make a cooldown check if (invoker instanceof Player && plugin.getCore() != null) { plugin.getCore().addCooldown(((Player) invoker).getUniqueId()); } if (plugin.getStorage() != null) { //Save the target uuid from the requesting player source UserPreference preferences = plugin.getStorage().getPreferences(receiver.getUniqueId()); preferences.setTargetSkin(targetSkin); preferences.setKeepSkin(keepSkin); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { if (plugin.getStorage().save(targetSkin)) { plugin.getStorage().save(preferences); } }); } if (plugin.getConfig().getBoolean("instantSkinChange")) { onInstantUpdate(); } else if (invoker != null) { plugin.sendMessage(invoker, "skin-changed-no-instant"); } } private void onInstantUpdate() { WrappedGameProfile gameProfile = WrappedGameProfile.fromPlayer(receiver); //remove existing skins gameProfile.getProperties().clear(); if (targetSkin == null) { plugin.getLogger().info("No-SKIN"); } else { gameProfile.getProperties().put(ChangeSkinCore.SKIN_KEY, plugin.convertToProperty(targetSkin)); } sendUpdate(gameProfile); plugin.sendMessage(receiver, "skin-changed"); if (invoker != null && !receiver.equals(invoker)) { plugin.sendMessage(invoker, "skin-updated"); } } private void sendUpdate(WrappedGameProfile gameProfile) throws FieldAccessException { sendUpdateSelf(gameProfile); //triggers an update for others player to see the new skin Bukkit.getOnlinePlayers().stream() .filter(onlinePlayer -> !onlinePlayer.equals(receiver)) .filter(onlinePlayer -> onlinePlayer.canSee(receiver)) .forEach(onlinePlayer -> { //removes the entity and display the new skin onlinePlayer.hidePlayer(receiver); onlinePlayer.showPlayer(receiver); }); } private void sendUpdateSelf(WrappedGameProfile gameProfile) throws FieldAccessException { Entity vehicle = receiver.getVehicle(); if (vehicle != null) { vehicle.eject(); } ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); NativeGameMode gamemode = NativeGameMode.fromBukkit(receiver.getGameMode()); //remove info PacketContainer removeInfo = protocolManager.createPacket(PacketType.Play.Server.PLAYER_INFO); removeInfo.getPlayerInfoAction().write(0, PlayerInfoAction.REMOVE_PLAYER); WrappedChatComponent displayName = WrappedChatComponent.fromText(receiver.getPlayerListName()); PlayerInfoData playerInfoData = new PlayerInfoData(gameProfile, 0, gamemode, displayName); removeInfo.getPlayerInfoDataLists().write(0, Lists.newArrayList(playerInfoData)); //add info containing the skin data PacketContainer addInfo = protocolManager.createPacket(PacketType.Play.Server.PLAYER_INFO); addInfo.getPlayerInfoAction().write(0, PlayerInfoAction.ADD_PLAYER); addInfo.getPlayerInfoDataLists().write(0, Lists.newArrayList(playerInfoData)); //Respawn packet PacketContainer respawn = protocolManager.createPacket(PacketType.Play.Server.RESPAWN); respawn.getIntegers().write(0, receiver.getWorld().getEnvironment().getId()); respawn.getDifficulties().write(0, Difficulty.valueOf(receiver.getWorld().getDifficulty().toString())); respawn.getGameModes().write(0, gamemode); respawn.getWorldTypeModifier().write(0, receiver.getWorld().getWorldType()); Location location = receiver.getLocation().clone(); PacketContainer teleport = protocolManager.createPacket(PacketType.Play.Server.POSITION); teleport.getModifier().writeDefaults(); teleport.getDoubles().write(0, location.getX()); teleport.getDoubles().write(1, location.getY()); teleport.getDoubles().write(2, location.getZ()); teleport.getFloat().write(0, location.getYaw()); teleport.getFloat().write(1, location.getPitch()); //send an invalid teleport id in order to let Bukkit ignore the incoming confirm packet teleport.getIntegers().writeSafely(0, -1337); try { //remove the old skin - client updates it only on a complete remove and add protocolManager.sendServerPacket(receiver, removeInfo); //adds the skin protocolManager.sendServerPacket(receiver, addInfo); //notify the client that it should update the own skin protocolManager.sendServerPacket(receiver, respawn); //prevent the moved too quickly message protocolManager.sendServerPacket(receiver, teleport); //send the current inventory - otherwise player would have an empty inventory receiver.updateInventory(); PlayerInventory inventory = receiver.getInventory(); inventory.setHeldItemSlot(inventory.getHeldItemSlot()); //this is sync so should be safe to call //triggers updateHealth double oldHealth = receiver.getHealth(); double maxHealth = getHealth(receiver); double healthScale = receiver.getHealthScale(); resetMaxHealth(receiver); receiver.setHealthScale(healthScale); setMaxHealth(receiver, maxHealth); receiver.setHealth(oldHealth); //set to the correct hand position setItemInHand(receiver); //triggers updateAbilities receiver.setWalkSpeed(receiver.getWalkSpeed()); } catch (InvocationTargetException ex) { plugin.getLogger().log(Level.SEVERE, "Exception sending instant skin change packet", ex); } } /** * This is to protect against players with the health boost potion effect. * This stops the max health from going up when the player has health boost since it adds to the max health. * * @param player * @return the actual max health value */ private double getHealth(Player player) { double health = getMaxHealth(player); for(PotionEffect potionEffect : player.getActivePotionEffects()){ //Had to do this because doing if(potionEffect.getType() == PotionEffectType.HEALTH_BOOST) //It wouldn't recognize it as the same. if(potionEffect.getType().getName().equalsIgnoreCase(PotionEffectType.HEALTH_BOOST.getName())){ health -= ((potionEffect.getAmplifier() + 1) * 4); } } return health; } private double getMaxHealth(Player player) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COLOR_UPDATE) >= 0) { return player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); } return player.getMaxHealth(); } private void resetMaxHealth(Player player) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COLOR_UPDATE) >= 0) { setMaxHealth(player, player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue()); return; } player.resetMaxHealth(); } private void setMaxHealth(Player player, double health) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COLOR_UPDATE) >= 0) { player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(health); return; } player.setHealth(health); } private void setItemInHand(Player player) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COMBAT_UPDATE) >= 0) { player.getInventory().setItemInMainHand(player.getInventory().getItemInMainHand()); player.getInventory().setItemInOffHand(player.getInventory().getItemInOffHand()); return; } player.getInventory().setItemInHand(player.getItemInHand()); } }
bukkit/src/main/java/com/github/games647/changeskin/bukkit/tasks/SkinUpdater.java
package com.github.games647.changeskin.bukkit.tasks; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.reflect.FieldAccessException; import com.comphenix.protocol.utility.MinecraftVersion; import com.comphenix.protocol.wrappers.EnumWrappers.Difficulty; import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode; import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction; import com.comphenix.protocol.wrappers.PlayerInfoData; import com.comphenix.protocol.wrappers.WrappedChatComponent; import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.github.games647.changeskin.bukkit.ChangeSkinBukkit; import com.github.games647.changeskin.core.ChangeSkinCore; import com.github.games647.changeskin.core.model.SkinData; import com.github.games647.changeskin.core.model.UserPreference; import com.google.common.collect.Lists; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.attribute.Attribute; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.PlayerInventory; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class SkinUpdater implements Runnable { protected final ChangeSkinBukkit plugin; private final CommandSender invoker; private final Player receiver; private final SkinData targetSkin; private final boolean keepSkin; public SkinUpdater(ChangeSkinBukkit plugin, CommandSender invoker, Player receiver , SkinData targetSkin, boolean keepSkin) { this.plugin = plugin; this.invoker = invoker; this.receiver = receiver; this.targetSkin = targetSkin; this.keepSkin = keepSkin; } @Override public void run() { if (receiver == null || !receiver.isOnline()) { return; } //uuid was successfull resolved, we could now make a cooldown check if (invoker instanceof Player && plugin.getCore() != null) { plugin.getCore().addCooldown(((Player) invoker).getUniqueId()); } if (plugin.getStorage() != null) { //Save the target uuid from the requesting player source UserPreference preferences = plugin.getStorage().getPreferences(receiver.getUniqueId()); preferences.setTargetSkin(targetSkin); preferences.setKeepSkin(keepSkin); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { if (plugin.getStorage().save(targetSkin)) { plugin.getStorage().save(preferences); } }); } if (plugin.getConfig().getBoolean("instantSkinChange")) { onInstantUpdate(); } else if (invoker != null) { plugin.sendMessage(invoker, "skin-changed-no-instant"); } } private void onInstantUpdate() { WrappedGameProfile gameProfile = WrappedGameProfile.fromPlayer(receiver); //remove existing skins gameProfile.getProperties().clear(); if (targetSkin == null) { plugin.getLogger().info("No-SKIN"); } else { gameProfile.getProperties().put(ChangeSkinCore.SKIN_KEY, plugin.convertToProperty(targetSkin)); } sendUpdate(gameProfile); plugin.sendMessage(receiver, "skin-changed"); if (invoker != null && !receiver.equals(invoker)) { plugin.sendMessage(invoker, "skin-updated"); } } private void sendUpdate(WrappedGameProfile gameProfile) throws FieldAccessException { sendUpdateSelf(gameProfile); //triggers an update for others player to see the new skin Bukkit.getOnlinePlayers().stream() .filter(onlinePlayer -> !onlinePlayer.equals(receiver)) .filter(onlinePlayer -> onlinePlayer.canSee(receiver)) .forEach(onlinePlayer -> { //removes the entity and display the new skin onlinePlayer.hidePlayer(receiver); onlinePlayer.showPlayer(receiver); }); } private void sendUpdateSelf(WrappedGameProfile gameProfile) throws FieldAccessException { Entity vehicle = receiver.getVehicle(); if (vehicle != null) { vehicle.eject(); } ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); NativeGameMode gamemode = NativeGameMode.fromBukkit(receiver.getGameMode()); //remove info PacketContainer removeInfo = protocolManager.createPacket(PacketType.Play.Server.PLAYER_INFO); removeInfo.getPlayerInfoAction().write(0, PlayerInfoAction.REMOVE_PLAYER); WrappedChatComponent displayName = WrappedChatComponent.fromText(receiver.getPlayerListName()); PlayerInfoData playerInfoData = new PlayerInfoData(gameProfile, 0, gamemode, displayName); removeInfo.getPlayerInfoDataLists().write(0, Lists.newArrayList(playerInfoData)); //add info containing the skin data PacketContainer addInfo = protocolManager.createPacket(PacketType.Play.Server.PLAYER_INFO); addInfo.getPlayerInfoAction().write(0, PlayerInfoAction.ADD_PLAYER); addInfo.getPlayerInfoDataLists().write(0, Lists.newArrayList(playerInfoData)); //Respawn packet PacketContainer respawn = protocolManager.createPacket(PacketType.Play.Server.RESPAWN); respawn.getIntegers().write(0, receiver.getWorld().getEnvironment().getId()); respawn.getDifficulties().write(0, Difficulty.valueOf(receiver.getWorld().getDifficulty().toString())); respawn.getGameModes().write(0, gamemode); respawn.getWorldTypeModifier().write(0, receiver.getWorld().getWorldType()); Location location = receiver.getLocation().clone(); PacketContainer teleport = protocolManager.createPacket(PacketType.Play.Server.POSITION); teleport.getModifier().writeDefaults(); teleport.getDoubles().write(0, 0D); teleport.getDoubles().write(1, 255D); teleport.getDoubles().write(2, 0D); teleport.getFloat().write(0, location.getYaw()); teleport.getFloat().write(1, location.getPitch()); //send an invalid teleport id in order to let Bukkit ignore the incoming confirm packet teleport.getIntegers().writeSafely(0, -1337); try { //remove the old skin - client updates it only on a complete remove and add protocolManager.sendServerPacket(receiver, removeInfo); //adds the skin protocolManager.sendServerPacket(receiver, addInfo); //notify the client that it should update the own skin protocolManager.sendServerPacket(receiver, respawn); //prevent the moved too quickly message protocolManager.sendServerPacket(receiver, teleport); //send the current inventory - otherwise player would have an empty inventory receiver.updateInventory(); PlayerInventory inventory = receiver.getInventory(); inventory.setHeldItemSlot(inventory.getHeldItemSlot()); //this is sync so should be safe to call //triggers updateHealth double oldHealth = receiver.getHealth(); double maxHealth = getHealth(receiver); double healthScale = receiver.getHealthScale(); resetMaxHealth(receiver); receiver.setHealthScale(healthScale); setMaxHealth(receiver, maxHealth); receiver.setHealth(oldHealth); //set to the correct hand position setItemInHand(receiver); //triggers updateAbilities receiver.setWalkSpeed(receiver.getWalkSpeed()); } catch (InvocationTargetException ex) { plugin.getLogger().log(Level.SEVERE, "Exception sending instant skin change packet", ex); } } /** * This is to protect against players with the health boost potion effect. * This stops the max health from going up when the player has health boost since it adds to the max health. * * @param player * @return the actual max health value */ private double getHealth(Player player) { double health = getMaxHealth(player); for(PotionEffect potionEffect : player.getActivePotionEffects()){ //Had to do this because doing if(potionEffect.getType() == PotionEffectType.HEALTH_BOOST) //It wouldn't recognize it as the same. if(potionEffect.getType().getName().equalsIgnoreCase(PotionEffectType.HEALTH_BOOST.getName())){ health -= ((potionEffect.getAmplifier() + 1) * 4); } } return health; } private double getMaxHealth(Player player) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COLOR_UPDATE) >= 0) { return player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); } return player.getMaxHealth(); } private void resetMaxHealth(Player player) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COLOR_UPDATE) >= 0) { setMaxHealth(player, player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue()); return; } player.resetMaxHealth(); } private void setMaxHealth(Player player, double health) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COLOR_UPDATE) >= 0) { player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(health); return; } player.setHealth(health); } private void setItemInHand(Player player) { if (MinecraftVersion.getCurrentVersion().compareTo(MinecraftVersion.COMBAT_UPDATE) >= 0) { player.getInventory().setItemInMainHand(player.getInventory().getItemInMainHand()); player.getInventory().setItemInOffHand(player.getInventory().getItemInOffHand()); return; } player.getInventory().setItemInHand(player.getItemInHand()); } }
Fix compatibility with NCP (Fixes #58)
bukkit/src/main/java/com/github/games647/changeskin/bukkit/tasks/SkinUpdater.java
Fix compatibility with NCP (Fixes #58)
<ide><path>ukkit/src/main/java/com/github/games647/changeskin/bukkit/tasks/SkinUpdater.java <ide> <ide> PacketContainer teleport = protocolManager.createPacket(PacketType.Play.Server.POSITION); <ide> teleport.getModifier().writeDefaults(); <del> teleport.getDoubles().write(0, 0D); <del> teleport.getDoubles().write(1, 255D); <del> teleport.getDoubles().write(2, 0D); <add> teleport.getDoubles().write(0, location.getX()); <add> teleport.getDoubles().write(1, location.getY()); <add> teleport.getDoubles().write(2, location.getZ()); <ide> teleport.getFloat().write(0, location.getYaw()); <ide> teleport.getFloat().write(1, location.getPitch()); <ide> //send an invalid teleport id in order to let Bukkit ignore the incoming confirm packet
Java
apache-2.0
error: pathspec 'app/src/main/java/org/apache/taverna/mobile/ui/workflowdetail/WorkflowDetailActivity.java' did not match any file(s) known to git
4477d1dd420377e9ad1ab1963e63e4c1e0b8fb3d
1
apache/incubator-taverna-mobile,sagar15795/incubator-taverna-mobile,ianwdunlop/incubator-taverna-mobile,apache/incubator-taverna-mobile,sagar15795/incubator-taverna-mobile
package org.apache.taverna.mobile.ui.workflowdetail; import org.apache.taverna.mobile.R; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; public class WorkflowDetailActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_workflow); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.frame_container, WorkflowDetailFragment.newInstance(getIntent().getStringExtra("id"))) .commit(); } } }
app/src/main/java/org/apache/taverna/mobile/ui/workflowdetail/WorkflowDetailActivity.java
add workflow detail activity
app/src/main/java/org/apache/taverna/mobile/ui/workflowdetail/WorkflowDetailActivity.java
add workflow detail activity
<ide><path>pp/src/main/java/org/apache/taverna/mobile/ui/workflowdetail/WorkflowDetailActivity.java <add>package org.apache.taverna.mobile.ui.workflowdetail; <add> <add> <add>import org.apache.taverna.mobile.R; <add> <add>import android.os.Bundle; <add>import android.support.annotation.Nullable; <add>import android.support.v7.app.AppCompatActivity; <add> <add>public class WorkflowDetailActivity extends AppCompatActivity { <add> <add> @Override <add> protected void onCreate(@Nullable Bundle savedInstanceState) { <add> super.onCreate(savedInstanceState); <add> setContentView(R.layout.activity_detail_workflow); <add> <add> if (savedInstanceState == null) { <add> getSupportFragmentManager().beginTransaction() <add> .add(R.id.frame_container, WorkflowDetailFragment.newInstance(getIntent().getStringExtra("id"))) <add> .commit(); <add> } <add> <add> } <add>}
Java
mpl-2.0
4a02bc7ad83c38238f85b0bb813ad7fc1ec3cf9f
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.jhv.plugins.eveplugin.draw; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.util.HashSet; import org.helioviewer.jhv.base.interval.Interval; import org.helioviewer.jhv.base.time.JHVDate; import org.helioviewer.jhv.base.time.TimeUtils; import org.helioviewer.jhv.data.datatype.event.JHVEventHighlightListener; import org.helioviewer.jhv.data.datatype.event.JHVRelatedEvents; import org.helioviewer.jhv.layers.Layers; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.TimeListener; import org.helioviewer.jhv.plugins.eveplugin.DrawConstants; import org.helioviewer.jhv.plugins.eveplugin.EVEPlugin; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorElement; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModelListener; import org.helioviewer.jhv.viewmodel.view.View; public class DrawController implements LineDataSelectorModelListener, JHVEventHighlightListener, LayersListener, TimeListener { public TimeAxis selectedAxis; public TimeAxis availableAxis; private static final HashSet<DrawControllerListener> listeners = new HashSet<DrawControllerListener>(); private final DrawControllerOptionsPanel optionsPanel; private Rectangle graphSize; private boolean isLocked; private long latestMovieTime; private Rectangle graphArea; public DrawController() { graphSize = new Rectangle(); long d = System.currentTimeMillis(); availableAxis = new TimeAxis(d - TimeUtils.DAY_IN_MILLIS, d); selectedAxis = new TimeAxis(availableAxis.start, availableAxis.end); isLocked = false; latestMovieTime = Long.MIN_VALUE; optionsPanel = new DrawControllerOptionsPanel(); EVEPlugin.ldsm.addLineDataSelectorModelListener(this); } public Component getOptionsPanel() { return optionsPanel; } public void addDrawControllerListener(DrawControllerListener listener) { listeners.add(listener); } public void removeDrawControllerListener(DrawControllerListener listener) { listeners.remove(listener); } public void setSelectedInterval(long newStart, long newEnd) { selectedAxis.set(newStart, newEnd, true); setAvailableInterval(); } public void moveX(double pixelDistance) { selectedAxis.move(graphArea.x, graphArea.width, pixelDistance); setAvailableInterval(); } private void zoomX(int x, double factor) { selectedAxis.zoom(graphArea.x, graphArea.width, x, factor); setAvailableInterval(); } private void moveAndZoomY(Point p, double distanceY, int scrollDistance, boolean zoom, boolean move) { boolean yAxisVerticalCondition = (p.y > graphArea.y && p.y <= graphArea.y + graphArea.height); boolean inRightYAxes = p.x > graphArea.x + graphArea.width && yAxisVerticalCondition; boolean inLeftYAxis = p.x < graphArea.x && yAxisVerticalCondition; int rightYAxisNumber = (p.x - (graphArea.x + graphArea.width)) / DrawConstants.RIGHT_AXIS_WIDTH; int ct = -1; for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { if (el.showYAxis()) { if ((rightYAxisNumber == ct && inRightYAxes) || (ct == -1 && inLeftYAxis)) { if (move) el.getYAxis().shiftDownPixels(distanceY, graphArea.height); if (zoom) el.getYAxis().zoomSelectedRange(scrollDistance, graphSize.height - p.y - graphArea.y, graphArea.height); el.yaxisChanged(); } else if ((!inRightYAxes && !inLeftYAxis) && move) { el.getYAxis().shiftDownPixels(distanceY, graphArea.height); } ct++; } } fireRedrawRequest(); } public void resetAxis(Point p) { boolean yAxisVerticalCondition = (p.y > graphArea.y && p.y <= graphArea.y + graphArea.height); boolean inRightYAxes = p.x > graphArea.x + graphArea.width && yAxisVerticalCondition; boolean inLeftYAxis = p.x < graphArea.x && yAxisVerticalCondition; int rightYAxisNumber = (p.x - (graphArea.x + graphArea.width)) / DrawConstants.RIGHT_AXIS_WIDTH; int ct = -1; for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { if (el.showYAxis()) { if ((rightYAxisNumber == ct && inRightYAxes) || (ct == -1 && inLeftYAxis)) { el.resetAxis(); } else if (!inRightYAxes && !inLeftYAxis) { el.zoomToFitAxis(); } ct++; } } fireRedrawRequest(); } public void moveY(Point p, double distanceY) { moveAndZoomY(p, distanceY, 0, false, true); } private void zoomY(Point p, int scrollDistance) { moveAndZoomY(p, 0, scrollDistance, true, false); } public void zoomXY(Point p, int scrollDistance, boolean shift, boolean alt) { double zoomTimeFactor = 10; boolean inGraphArea = (p.x >= graphArea.x && p.x <= graphArea.x + graphArea.width && p.y > graphArea.y && p.y <= graphArea.y + graphArea.height); boolean inXAxisOrAboveGraph = (p.x >= graphArea.x && p.x <= graphArea.x + graphArea.width && (p.y <= graphArea.y || p.y >= graphArea.y + graphArea.height)); if (inGraphArea || inXAxisOrAboveGraph) { if ((!alt && !shift) || inXAxisOrAboveGraph) { zoomX(p.x, zoomTimeFactor * scrollDistance); } else if (shift) { moveX(zoomTimeFactor * scrollDistance); } } zoomY(p, scrollDistance); } public void moveAllAxes(double distanceY) { for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { if (el.showYAxis()) { el.getYAxis().shiftDownPixels(distanceY, graphArea.height); } } } private void setAvailableInterval() { long availableStart = availableAxis.start; long availableEnd = availableAxis.end; if ((selectedAxis.start <= availableAxis.start || selectedAxis.end >= availableAxis.end)) { availableStart = Math.min(selectedAxis.start, availableStart); availableEnd = Math.max(selectedAxis.end, availableEnd); Interval availableInterval = TimeUtils.makeCompleteDay(availableStart, availableEnd); availableAxis.start = availableInterval.start; availableAxis.end = availableInterval.end; } for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { el.fetchData(selectedAxis, availableAxis); } optionsPanel.fetchData(selectedAxis, availableAxis); fireRedrawRequest(); } private void centraliseSelected(long time) { if (time != Long.MIN_VALUE && latestMovieTime != time && isLocked && availableAxis.start <= time && availableAxis.end >= time) { latestMovieTime = time; long selectedIntervalDiff = selectedAxis.end - selectedAxis.start; selectedAxis.set(time - ((long) (0.5 * selectedIntervalDiff)), time + ((long) (0.5 * selectedIntervalDiff)), false); fireRedrawRequest(); for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { el.fetchData(selectedAxis, availableAxis); } } } public Interval getSelectedInterval() { return new Interval(selectedAxis.start, selectedAxis.end); } public void setGraphInformation(Rectangle graphSize) { this.graphSize = graphSize; createGraphArea(); fireRedrawRequest(); } private void createGraphArea() { int height = graphSize.height - (DrawConstants.GRAPH_TOP_SPACE + DrawConstants.GRAPH_BOTTOM_SPACE); int noRightAxes = Math.max(0, (EVEPlugin.ldsm.getNumberOfAxes() - 1)); int width = (graphSize.width - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + noRightAxes * DrawConstants.RIGHT_AXIS_WIDTH)); graphArea = new Rectangle(DrawConstants.GRAPH_LEFT_SPACE, DrawConstants.GRAPH_TOP_SPACE, width, height); } public Rectangle getGraphArea() { return graphArea; } public Rectangle getGraphSize() { return graphSize; } public boolean isLocked() { return isLocked; } public void setLocked(boolean isLocked) { this.isLocked = isLocked; if (isLocked && latestMovieTime != Long.MIN_VALUE) { centraliseSelected(latestMovieTime); } } @Override public void lineDataRemoved(LineDataSelectorElement element) { createGraphArea(); fireRedrawRequest(); } @Override public void lineDataUpdated(LineDataSelectorElement element) { } @Override public void lineDataAdded(LineDataSelectorElement element) { createGraphArea(); } @Override public void timeChanged(JHVDate date) { centraliseSelected(date.milli); fireRedrawRequestMovieFrameChanged(date.milli); } @Override public void eventHightChanged(JHVRelatedEvents event) { fireRedrawRequest(); } @Override public void layerAdded(View view) { setSelectedInterval(Layers.getStartDate().milli, Layers.getEndDate().milli); } @Override public void activeLayerChanged(View view) { if (view == null) { fireRedrawRequestMovieFrameChanged(Long.MIN_VALUE); optionsPanel.lockButton.setEnabled(false); } else { fireMovieIntervalChanged(view.getFirstTime().milli, view.getLastTime().milli); optionsPanel.lockButton.setEnabled(true); } } public void fireRedrawRequest() { for (DrawControllerListener l : listeners) { l.drawRequest(); } } private void fireRedrawRequestMovieFrameChanged(long time) { for (DrawControllerListener l : listeners) { l.drawMovieLineRequest(time); } } private void fireMovieIntervalChanged(long start, long end) { for (DrawControllerListener l : listeners) { l.movieIntervalChanged(start, end); } } }
src/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/draw/DrawController.java
package org.helioviewer.jhv.plugins.eveplugin.draw; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.util.HashSet; import org.helioviewer.jhv.base.interval.Interval; import org.helioviewer.jhv.base.time.JHVDate; import org.helioviewer.jhv.base.time.TimeUtils; import org.helioviewer.jhv.data.datatype.event.JHVEventHighlightListener; import org.helioviewer.jhv.data.datatype.event.JHVRelatedEvents; import org.helioviewer.jhv.layers.Layers; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.TimeListener; import org.helioviewer.jhv.plugins.eveplugin.DrawConstants; import org.helioviewer.jhv.plugins.eveplugin.EVEPlugin; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorElement; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModelListener; import org.helioviewer.jhv.viewmodel.view.View; public class DrawController implements LineDataSelectorModelListener, JHVEventHighlightListener, LayersListener, TimeListener { public TimeAxis selectedAxis; public TimeAxis availableAxis; private static final HashSet<DrawControllerListener> listeners = new HashSet<DrawControllerListener>(); private final DrawControllerOptionsPanel optionsPanel; private Rectangle graphSize; private boolean isLocked; private long latestMovieTime; private Rectangle graphArea; public DrawController() { graphSize = new Rectangle(); long d = System.currentTimeMillis(); availableAxis = new TimeAxis(d - TimeUtils.DAY_IN_MILLIS, d); selectedAxis = new TimeAxis(availableAxis.start, availableAxis.end); isLocked = false; latestMovieTime = Long.MIN_VALUE; optionsPanel = new DrawControllerOptionsPanel(); EVEPlugin.ldsm.addLineDataSelectorModelListener(this); } public Component getOptionsPanel() { return optionsPanel; } public void addDrawControllerListener(DrawControllerListener listener) { listeners.add(listener); } public void removeDrawControllerListener(DrawControllerListener listener) { listeners.remove(listener); } public void setSelectedInterval(long newStart, long newEnd) { selectedAxis.set(newStart, newEnd, true); setAvailableInterval(); } public void moveX(double pixelDistance) { selectedAxis.move(graphArea.x, graphArea.width, pixelDistance); setAvailableInterval(); } private void zoomX(int x, double factor) { selectedAxis.zoom(graphArea.x, graphArea.width, x, factor); setAvailableInterval(); } private void moveAndZoomY(Point p, double distanceY, int scrollDistance, boolean zoom, boolean move) { boolean yAxisVerticalCondition = (p.y > graphArea.y && p.y <= graphArea.y + graphArea.height); boolean inRightYAxes = p.x > graphArea.x + graphArea.width && yAxisVerticalCondition; boolean inLeftYAxis = p.x < graphArea.x && yAxisVerticalCondition; int rightYAxisNumber = (p.x - (graphArea.x + graphArea.width)) / DrawConstants.RIGHT_AXIS_WIDTH; int ct = -1; for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { if (el.showYAxis()) { if ((rightYAxisNumber == ct && inRightYAxes) || (ct == -1 && inLeftYAxis)) { if (move) el.getYAxis().shiftDownPixels(distanceY, graphArea.height); if (zoom) el.getYAxis().zoomSelectedRange(scrollDistance, graphSize.height - p.y - graphArea.y, graphArea.height); el.yaxisChanged(); } else if ((!inRightYAxes && !inLeftYAxis) && move) { el.getYAxis().shiftDownPixels(distanceY, graphArea.height); } ct++; } } fireRedrawRequest(); } public void resetAxis(Point p) { boolean yAxisVerticalCondition = (p.y > graphArea.y && p.y <= graphArea.y + graphArea.height); boolean inRightYAxes = p.x > graphArea.x + graphArea.width && yAxisVerticalCondition; boolean inLeftYAxis = p.x < graphArea.x && yAxisVerticalCondition; int rightYAxisNumber = (p.x - (graphArea.x + graphArea.width)) / DrawConstants.RIGHT_AXIS_WIDTH; int ct = -1; for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { if (el.showYAxis()) { if ((rightYAxisNumber == ct && inRightYAxes) || (ct == -1 && inLeftYAxis)) { el.resetAxis(); } else if (!inRightYAxes && !inLeftYAxis) { el.zoomToFitAxis(); } ct++; } } fireRedrawRequest(); } public void moveY(Point p, double distanceY) { moveAndZoomY(p, distanceY, 0, false, true); } private void zoomY(Point p, int scrollDistance) { moveAndZoomY(p, 0, scrollDistance, true, false); } public void zoomXY(Point p, int scrollDistance, boolean shift, boolean alt) { double zoomTimeFactor = 10; boolean inGraphArea = (p.x >= graphArea.x && p.x <= graphArea.x + graphArea.width && p.y > graphArea.y && p.y <= graphArea.y + graphArea.height); boolean inXAxisOrAboveGraph = (p.x >= graphArea.x && p.x <= graphArea.x + graphArea.width && (p.y <= graphArea.y || p.y >= graphArea.y + graphArea.height)); if (inGraphArea || inXAxisOrAboveGraph) { if ((!alt && !shift) || inXAxisOrAboveGraph) { zoomX(p.x, zoomTimeFactor * scrollDistance); } else if (shift) { moveX(zoomTimeFactor * scrollDistance); } } zoomY(p, scrollDistance); } public void moveAllAxes(double distanceY) { for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { if (el.showYAxis()) { el.getYAxis().shiftDownPixels(distanceY, graphArea.height); } } } private void setAvailableInterval() { long availableStart = availableAxis.start; long availableEnd = availableAxis.end; if ((selectedAxis.start <= availableAxis.start || selectedAxis.end >= availableAxis.end)) { availableStart = Math.min(selectedAxis.start, availableStart); availableEnd = Math.max(selectedAxis.end, availableEnd); Interval availableInterval = TimeUtils.makeCompleteDay(availableStart, availableEnd); availableAxis.start = availableInterval.start; availableAxis.end = availableInterval.end; } fireRedrawRequest(); for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { el.fetchData(selectedAxis, availableAxis); } optionsPanel.fetchData(selectedAxis, availableAxis); } private void centraliseSelected(long time) { if (time != Long.MIN_VALUE && latestMovieTime != time && isLocked && availableAxis.start <= time && availableAxis.end >= time) { latestMovieTime = time; long selectedIntervalDiff = selectedAxis.end - selectedAxis.start; selectedAxis.set(time - ((long) (0.5 * selectedIntervalDiff)), time + ((long) (0.5 * selectedIntervalDiff)), false); fireRedrawRequest(); for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { el.fetchData(selectedAxis, availableAxis); } } } public Interval getSelectedInterval() { return new Interval(selectedAxis.start, selectedAxis.end); } public void setGraphInformation(Rectangle graphSize) { this.graphSize = graphSize; createGraphArea(); fireRedrawRequest(); } private void createGraphArea() { int height = graphSize.height - (DrawConstants.GRAPH_TOP_SPACE + DrawConstants.GRAPH_BOTTOM_SPACE); int noRightAxes = Math.max(0, (EVEPlugin.ldsm.getNumberOfAxes() - 1)); int width = (graphSize.width - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + noRightAxes * DrawConstants.RIGHT_AXIS_WIDTH)); graphArea = new Rectangle(DrawConstants.GRAPH_LEFT_SPACE, DrawConstants.GRAPH_TOP_SPACE, width, height); } public Rectangle getGraphArea() { return graphArea; } public Rectangle getGraphSize() { return graphSize; } public boolean isLocked() { return isLocked; } public void setLocked(boolean isLocked) { this.isLocked = isLocked; if (isLocked && latestMovieTime != Long.MIN_VALUE) { centraliseSelected(latestMovieTime); } } @Override public void lineDataRemoved(LineDataSelectorElement element) { createGraphArea(); fireRedrawRequest(); } @Override public void lineDataUpdated(LineDataSelectorElement element) { } @Override public void lineDataAdded(LineDataSelectorElement element) { createGraphArea(); } @Override public void timeChanged(JHVDate date) { centraliseSelected(date.milli); fireRedrawRequestMovieFrameChanged(date.milli); } @Override public void eventHightChanged(JHVRelatedEvents event) { fireRedrawRequest(); } @Override public void layerAdded(View view) { setSelectedInterval(Layers.getStartDate().milli, Layers.getEndDate().milli); } @Override public void activeLayerChanged(View view) { if (view == null) { fireRedrawRequestMovieFrameChanged(Long.MIN_VALUE); optionsPanel.lockButton.setEnabled(false); } else { fireMovieIntervalChanged(view.getFirstTime().milli, view.getLastTime().milli); optionsPanel.lockButton.setEnabled(true); } } public void fireRedrawRequest() { for (DrawControllerListener l : listeners) { l.drawRequest(); } } private void fireRedrawRequestMovieFrameChanged(long time) { for (DrawControllerListener l : listeners) { l.drawMovieLineRequest(time); } } private void fireMovieIntervalChanged(long start, long end) { for (DrawControllerListener l : listeners) { l.movieIntervalChanged(start, end); } } }
move function call git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@7308 b4e469a2-07ce-4b26-9273-4d7d95a670c7
src/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/draw/DrawController.java
move function call
<ide><path>rc/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/draw/DrawController.java <ide> availableAxis.end = availableInterval.end; <ide> } <ide> <del> fireRedrawRequest(); <ide> for (LineDataSelectorElement el : EVEPlugin.ldsm.getAllLineDataSelectorElements()) { <ide> el.fetchData(selectedAxis, availableAxis); <ide> } <ide> optionsPanel.fetchData(selectedAxis, availableAxis); <add> fireRedrawRequest(); <ide> } <ide> <ide> private void centraliseSelected(long time) {
Java
agpl-3.0
f4c765379378bc1fcd0ad704707498f126b485b1
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
c65e9ddc-2e5f-11e5-9284-b827eb9e62be
hello.java
c6591e52-2e5f-11e5-9284-b827eb9e62be
c65e9ddc-2e5f-11e5-9284-b827eb9e62be
hello.java
c65e9ddc-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>c6591e52-2e5f-11e5-9284-b827eb9e62be <add>c65e9ddc-2e5f-11e5-9284-b827eb9e62be
Java
mit
bbe3b487f81e61a7a836fbf1bd651010852720fc
0
mzmine/mzmine3,mzmine/mzmine3
/* * Copyright 2006-2018 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 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. * * MZmine 2 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 MZmine 2; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.sf.mzmine.parameters.parametertypes; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.Collection; import javax.swing.JFrame; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import net.sf.mzmine.parameters.Parameter; public class WindowSettingsParameter implements Parameter<Object>, ComponentListener { private static final String SIZE_ELEMENT = "size"; private static final String POSITION_ELEMENT = "position"; private static final String MAXIMIZED_ELEMENT = "maximized"; private static Point startPosition; private Point position; private Dimension dimension; private boolean isMaximized = false; private Point offset = new Point(20, 20); @Override public String getName() { return "Window state"; } @Override public WindowSettingsParameter cloneParameter() { return this; } @Override public boolean checkValue(Collection<String> errorMessages) { return true; } @Override public void loadValueFromXML(Element xmlElement) { // Window position NodeList posElement = xmlElement.getElementsByTagName(POSITION_ELEMENT); if (posElement.getLength() == 1) { String posString = posElement.item(0).getTextContent(); String posArray[] = posString.split(":"); if (posArray.length == 2) { int posX = Integer.valueOf(posArray[0]); int posY = Integer.valueOf(posArray[1]); position = new Point(posX, posY); } } // Window size NodeList sizeElement = xmlElement.getElementsByTagName(SIZE_ELEMENT); if (sizeElement.getLength() == 1) { String sizeString = sizeElement.item(0).getTextContent(); String sizeArray[] = sizeString.split(":"); if (sizeArray.length == 2) { int width = Integer.parseInt(sizeArray[0]); int height = Integer.parseInt(sizeArray[1]); dimension = new Dimension(width, height); } } // Window maximized NodeList maximizedElement = xmlElement.getElementsByTagName(MAXIMIZED_ELEMENT); if (maximizedElement.getLength() == 1) { String maximizedString = maximizedElement.item(0).getTextContent(); isMaximized = Boolean.valueOf(maximizedString); } } @Override public void saveValueToXML(Element xmlElement) { // Add elements Document doc = xmlElement.getOwnerDocument(); if (position != null) { Element positionElement = doc.createElement(POSITION_ELEMENT); xmlElement.appendChild(positionElement); positionElement.setTextContent(position.x + ":" + position.y); } if (dimension != null) { Element sizeElement = doc.createElement(SIZE_ELEMENT); xmlElement.appendChild(sizeElement); sizeElement.setTextContent(dimension.width + ":" + dimension.height); } Element maximizedElement = doc.createElement(MAXIMIZED_ELEMENT); xmlElement.appendChild(maximizedElement); maximizedElement.setTextContent(String.valueOf(isMaximized)); } @Override public Object getValue() { return null; } @Override public void setValue(Object newValue) { // ignore } /** * Set window size and position according to the values in this instance */ public void applySettingsToWindow(JFrame frame) { if (position != null) { if (!isMaximized) { // Reset to default, if we go outside screen limits Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Point bottomRightPos = new Point(position.x + offset.x + frame.getWidth(), position.y + offset.y + frame.getHeight()); if (startPosition != null && !(new Rectangle(screenSize).contains(bottomRightPos))) { position = new Point(startPosition); } // Keep translating otherwise position.translate(offset.x, offset.y); } frame.setLocation(position); if (startPosition == null) startPosition = new Point(position); } if (dimension != null) { frame.setSize(dimension); } if (isMaximized) { frame.setExtendedState(Frame.MAXIMIZED_HORIZ | Frame.MAXIMIZED_VERT); } // when still outside of screen // e.g. changing from 2 screens to one if (!isOnScreen(frame)) { // Maximise on screen 1 frame.setLocation(0, 0); frame.setSize(1024, 800); frame.setExtendedState(Frame.MAXIMIZED_HORIZ | Frame.MAXIMIZED_VERT); } } public boolean isOnScreen(JFrame frame) { Rectangle virtualBounds = getVirtualBounds(); return virtualBounds.contains(frame.getBounds()); } public static Rectangle getVirtualBounds() { Rectangle bounds = new Rectangle(0, 0, 0, 0); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice lstGDs[] = ge.getScreenDevices(); for (GraphicsDevice gd : lstGDs) { bounds.add(gd.getDefaultConfiguration().getBounds()); } return bounds; } @Override public void componentMoved(ComponentEvent e) { if (!(e.getComponent() instanceof JFrame)) return; JFrame frame = (JFrame) e.getComponent(); int state = frame.getExtendedState(); isMaximized = ((state & Frame.MAXIMIZED_HORIZ) != 0) && ((state & Frame.MAXIMIZED_VERT) != 0); if (!isMaximized) { position = frame.getLocation(); } } @Override public void componentResized(ComponentEvent e) { if (!(e.getComponent() instanceof JFrame)) return; JFrame frame = (JFrame) e.getComponent(); int state = frame.getExtendedState(); isMaximized = ((state & Frame.MAXIMIZED_HORIZ) != 0) && ((state & Frame.MAXIMIZED_VERT) != 0); if (!isMaximized) { dimension = frame.getSize(); } } @Override public void componentHidden(ComponentEvent e) { // ignore } @Override public void componentShown(ComponentEvent e) { // ignore } }
src/main/java/net/sf/mzmine/parameters/parametertypes/WindowSettingsParameter.java
/* * Copyright 2006-2018 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 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. * * MZmine 2 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 MZmine 2; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.sf.mzmine.parameters.parametertypes; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.Collection; import javax.swing.JFrame; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import net.sf.mzmine.parameters.Parameter; public class WindowSettingsParameter implements Parameter<Object>, ComponentListener { private static final String SIZE_ELEMENT = "size"; private static final String POSITION_ELEMENT = "position"; private static final String MAXIMIZED_ELEMENT = "maximized"; private static Point startPosition; private Point position; private Dimension dimension; private boolean isMaximized = false; private Point offset = new Point(20, 20); @Override public String getName() { return "Window state"; } @Override public WindowSettingsParameter cloneParameter() { return this; } @Override public boolean checkValue(Collection<String> errorMessages) { return true; } @Override public void loadValueFromXML(Element xmlElement) { // Window position NodeList posElement = xmlElement.getElementsByTagName(POSITION_ELEMENT); if (posElement.getLength() == 1) { String posString = posElement.item(0).getTextContent(); String posArray[] = posString.split(":"); if (posArray.length == 2) { int posX = Integer.valueOf(posArray[0]); int posY = Integer.valueOf(posArray[1]); position = new Point(posX, posY); } } // Window size NodeList sizeElement = xmlElement.getElementsByTagName(SIZE_ELEMENT); if (sizeElement.getLength() == 1) { String sizeString = sizeElement.item(0).getTextContent(); String sizeArray[] = sizeString.split(":"); if (sizeArray.length == 2) { int width = Integer.parseInt(sizeArray[0]); int height = Integer.parseInt(sizeArray[1]); dimension = new Dimension(width, height); } } // Window maximized NodeList maximizedElement = xmlElement.getElementsByTagName(MAXIMIZED_ELEMENT); if (maximizedElement.getLength() == 1) { String maximizedString = maximizedElement.item(0).getTextContent(); isMaximized = Boolean.valueOf(maximizedString); } } @Override public void saveValueToXML(Element xmlElement) { // Add elements Document doc = xmlElement.getOwnerDocument(); if (position != null) { Element positionElement = doc.createElement(POSITION_ELEMENT); xmlElement.appendChild(positionElement); positionElement.setTextContent(position.x + ":" + position.y); } if (dimension != null) { Element sizeElement = doc.createElement(SIZE_ELEMENT); xmlElement.appendChild(sizeElement); sizeElement.setTextContent(dimension.width + ":" + dimension.height); } Element maximizedElement = doc.createElement(MAXIMIZED_ELEMENT); xmlElement.appendChild(maximizedElement); maximizedElement.setTextContent(String.valueOf(isMaximized)); } @Override public Object getValue() { return null; } @Override public void setValue(Object newValue) { // ignore } /** * Set window size and position according to the values in this instance */ public void applySettingsToWindow(JFrame frame) { if (position != null) { if (!isMaximized) { // Reset to default, if we go outside screen limits Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Point bottomRightPos = new Point(position.x + offset.x + frame.getWidth(), position.y + offset.y + frame.getHeight()); if (startPosition != null && !(new Rectangle(screenSize).contains(bottomRightPos))) { position = new Point(startPosition); } // Keep translating otherwise position.translate(offset.x, offset.y); } frame.setLocation(position); if (startPosition == null) startPosition = new Point(position); } if (dimension != null) { frame.setSize(dimension); } if (isMaximized) { frame.setExtendedState(Frame.MAXIMIZED_HORIZ | Frame.MAXIMIZED_VERT); } if (!isOnScreen(frame)) { frame.setLocation(0, 0); frame.setSize(1024, 800); frame.setExtendedState(Frame.MAXIMIZED_HORIZ | Frame.MAXIMIZED_VERT); } } public boolean isOnScreen(JFrame frame) { Rectangle virtualBounds = getVirtualBounds(); return virtualBounds.contains(frame.getBounds()); } public static Rectangle getVirtualBounds() { Rectangle bounds = new Rectangle(0, 0, 0, 0); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice lstGDs[] = ge.getScreenDevices(); for (GraphicsDevice gd : lstGDs) { bounds.add(gd.getDefaultConfiguration().getBounds()); } return bounds; } @Override public void componentMoved(ComponentEvent e) { if (!(e.getComponent() instanceof JFrame)) return; JFrame frame = (JFrame) e.getComponent(); int state = frame.getExtendedState(); isMaximized = ((state & Frame.MAXIMIZED_HORIZ) != 0) && ((state & Frame.MAXIMIZED_VERT) != 0); if (!isMaximized) { position = frame.getLocation(); } } @Override public void componentResized(ComponentEvent e) { if (!(e.getComponent() instanceof JFrame)) return; JFrame frame = (JFrame) e.getComponent(); int state = frame.getExtendedState(); isMaximized = ((state & Frame.MAXIMIZED_HORIZ) != 0) && ((state & Frame.MAXIMIZED_VERT) != 0); if (!isMaximized) { dimension = frame.getSize(); } } @Override public void componentHidden(ComponentEvent e) { // ignore } @Override public void componentShown(ComponentEvent e) { // ignore } }
Comments
src/main/java/net/sf/mzmine/parameters/parametertypes/WindowSettingsParameter.java
Comments
<ide><path>rc/main/java/net/sf/mzmine/parameters/parametertypes/WindowSettingsParameter.java <ide> frame.setExtendedState(Frame.MAXIMIZED_HORIZ | Frame.MAXIMIZED_VERT); <ide> } <ide> <add> // when still outside of screen <add> // e.g. changing from 2 screens to one <ide> if (!isOnScreen(frame)) { <add> // Maximise on screen 1 <ide> frame.setLocation(0, 0); <ide> frame.setSize(1024, 800); <ide> frame.setExtendedState(Frame.MAXIMIZED_HORIZ | Frame.MAXIMIZED_VERT);
Java
bsd-3-clause
a87227196b1159edbf42dd4a52b4e7ca2789964b
0
crbb/sulong,PrinzKatharina/sulong,lxp/sulong,PrinzKatharina/sulong,crbb/sulong,crbb/sulong,lxp/sulong,PrinzKatharina/sulong,lxp/sulong,lxp/sulong,crbb/sulong,PrinzKatharina/sulong
/* * Copyright (c) 2016, Oracle and/or its affiliates. * * All rights reserved. * * 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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 com.oracle.truffle.llvm.nodes.base; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; public abstract class LLVMStackFrameNuller { private final FrameSlot frameSlot; LLVMStackFrameNuller(FrameSlot slot) { this.frameSlot = slot; } public void nullifySlot(VirtualFrame frame) { nullify(frame, frameSlot); } abstract void nullify(VirtualFrame frame, FrameSlot slot); public static final class LLVMBooleanNuller extends LLVMStackFrameNuller { public LLVMBooleanNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setBoolean(slot, false); } } public static final class LLVMByteNuller extends LLVMStackFrameNuller { public LLVMByteNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setByte(slot, (byte) 0); } } public static final class LLVMIntNuller extends LLVMStackFrameNuller { public LLVMIntNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setInt(slot, 0); } } public static final class LLVMLongNuller extends LLVMStackFrameNuller { public LLVMLongNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setLong(slot, 0); } } public static final class LLVMFloatNuller extends LLVMStackFrameNuller { public LLVMFloatNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setFloat(slot, 0); } } public static final class LLVMDoubleNull extends LLVMStackFrameNuller { public LLVMDoubleNull(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setDouble(slot, 0); } } public static final class LLVMObjectNuller extends LLVMStackFrameNuller { public LLVMObjectNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setObject(slot, null); } } }
projects/com.oracle.truffle.llvm.nodes/src/com/oracle/truffle/llvm/nodes/base/LLVMStackFrameNuller.java
/* * Copyright (c) 2016, Oracle and/or its affiliates. * * All rights reserved. * * 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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 com.oracle.truffle.llvm.nodes.base; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; public abstract class LLVMStackFrameNuller { private final FrameSlot frameSlot; LLVMStackFrameNuller(FrameSlot slot) { this.frameSlot = slot; } public void nullifySlot(VirtualFrame frame) { nullify(frame, frameSlot); } abstract void nullify(VirtualFrame frame, FrameSlot slot); public static class LLVMBooleanNuller extends LLVMStackFrameNuller { public LLVMBooleanNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setBoolean(slot, false); } } public static class LLVMByteNuller extends LLVMStackFrameNuller { public LLVMByteNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setByte(slot, (byte) 0); } } public static class LLVMIntNuller extends LLVMStackFrameNuller { public LLVMIntNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setInt(slot, 0); } } public static class LLVMLongNuller extends LLVMStackFrameNuller { public LLVMLongNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setLong(slot, 0); } } public static class LLVMFloatNuller extends LLVMStackFrameNuller { public LLVMFloatNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setFloat(slot, 0); } } public static class LLVMDoubleNull extends LLVMStackFrameNuller { public LLVMDoubleNull(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setDouble(slot, 0); } } public static class LLVMObjectNuller extends LLVMStackFrameNuller { public LLVMObjectNuller(FrameSlot slot) { super(slot); } @Override void nullify(VirtualFrame frame, FrameSlot slot) { frame.setObject(slot, null); } } }
Make the stack nuller classes final
projects/com.oracle.truffle.llvm.nodes/src/com/oracle/truffle/llvm/nodes/base/LLVMStackFrameNuller.java
Make the stack nuller classes final
<ide><path>rojects/com.oracle.truffle.llvm.nodes/src/com/oracle/truffle/llvm/nodes/base/LLVMStackFrameNuller.java <ide> <ide> abstract void nullify(VirtualFrame frame, FrameSlot slot); <ide> <del> public static class LLVMBooleanNuller extends LLVMStackFrameNuller { <add> public static final class LLVMBooleanNuller extends LLVMStackFrameNuller { <ide> <ide> public LLVMBooleanNuller(FrameSlot slot) { <ide> super(slot); <ide> <ide> } <ide> <del> public static class LLVMByteNuller extends LLVMStackFrameNuller { <add> public static final class LLVMByteNuller extends LLVMStackFrameNuller { <ide> <ide> public LLVMByteNuller(FrameSlot slot) { <ide> super(slot); <ide> <ide> } <ide> <del> public static class LLVMIntNuller extends LLVMStackFrameNuller { <add> public static final class LLVMIntNuller extends LLVMStackFrameNuller { <ide> <ide> public LLVMIntNuller(FrameSlot slot) { <ide> super(slot); <ide> <ide> } <ide> <del> public static class LLVMLongNuller extends LLVMStackFrameNuller { <add> public static final class LLVMLongNuller extends LLVMStackFrameNuller { <ide> <ide> public LLVMLongNuller(FrameSlot slot) { <ide> super(slot); <ide> <ide> } <ide> <del> public static class LLVMFloatNuller extends LLVMStackFrameNuller { <add> public static final class LLVMFloatNuller extends LLVMStackFrameNuller { <ide> <ide> public LLVMFloatNuller(FrameSlot slot) { <ide> super(slot); <ide> <ide> } <ide> <del> public static class LLVMDoubleNull extends LLVMStackFrameNuller { <add> public static final class LLVMDoubleNull extends LLVMStackFrameNuller { <ide> <ide> public LLVMDoubleNull(FrameSlot slot) { <ide> super(slot); <ide> <ide> } <ide> <del> public static class LLVMObjectNuller extends LLVMStackFrameNuller { <add> public static final class LLVMObjectNuller extends LLVMStackFrameNuller { <ide> <ide> public LLVMObjectNuller(FrameSlot slot) { <ide> super(slot);
JavaScript
mit
7b90adbccfedfa82390eaf19f9f8b13a228fa00b
0
jakutis/httpinvoke,fuzeman/httpinvoke,jakutis/httpinvoke,fuzeman/httpinvoke
/* global httpinvoke, url, method, options, cb */ /* global nextTick, mixInPromise, pass, progress, reject, resolve, supportedMethods, isArray, isArrayBufferView, isFormData, isByteArray, _undefined */ /* global setTimeout */ /* global crossDomain */// this one is a hack, because when in nodejs this is not really defined, but it is never needed /* jshint -W020 */ var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter; hook = function(type, args) { var hooks = httpinvoke._hooks[type]; for(var i = 0; i < hooks.length; i += 1) { args = hooks[i].apply(null, args); } return args; }; /*************** COMMON initialize parameters **************/ var downloadTimeout, uploadTimeout, timeout; if(!method) { // 1 argument // method, options, cb skipped method = 'GET'; options = {}; } else if(!options) { // 2 arguments if(typeof method === 'string') { // options. cb skipped options = {}; } else if(typeof method === 'object') { // method, cb skipped options = method; method = 'GET'; } else { // method, options skipped options = { finished: method }; method = 'GET'; } } else if(!cb) { // 3 arguments if(typeof method === 'object') { // method skipped method.finished = options; options = method; method = 'GET'; } else if(typeof options === 'function') { // options skipped options = { finished: options }; } // cb skipped } else { // 4 arguments options.finished = cb; } var safeCallback = function(name, aspectBefore, aspectAfter) { return function() { var args, _cb, failedOnHook = false, fail = function(err, args) { _cb = cb; cb = null; nextTick(function() { /* jshint expr:true */ _cb && _cb(err); /* jshint expr:false */ promise(); if(!_cb && !failedOnHook) { throw err; } }); return name === 'finished' ? [err] : args; }; aspectBefore.apply(null, args); try { args = hook(name, [].slice.call(arguments)); } catch(err) { failedOnHook = true; args = fail(err, args); } if(options[name]) { try { options[name].apply(null, args); } catch(err) { args = fail(err, args); } } aspectAfter.apply(null, args); }; }; failWithoutRequest = function(cb, err) { if(!(err instanceof Error)) { // create error here, instead of nextTick, to preserve stack err = new Error('Error code #' + err +'. See https://github.com/jakutis/httpinvoke#error-codes'); } nextTick(function() { if(cb === null) { return; } cb(err); }); promise = function() { }; return mixInPromise(promise); }; uploadProgressCb = safeCallback('uploading', pass, function(current, total) { promise[progress]({ type: 'upload', current: current, total: total }); }); downloadProgressCb = safeCallback('downloading', pass, function(current, total, partial) { promise[progress]({ type: 'download', current: current, total: total, partial: partial }); }); statusCb = safeCallback('gotStatus', function() { statusCb = null; if(downloadTimeout) { setTimeout(function() { if(cb) { cb(new Error('download timeout')); promise(); } }, downloadTimeout); } }, function(statusCode, headers) { promise[progress]({ type: 'headers', statusCode: statusCode, headers: headers }); }); cb = safeCallback('finished', function() { cb = null; promise(); }, function(err, body, statusCode, headers) { var res = { body: body, statusCode: statusCode, headers: headers }; if(err) { return promise[reject](err, res); } promise[resolve](res); }); var converters = options.converters || {}; var inputConverter; inputHeaders = options.headers || {}; outputHeaders = {}; exposedHeaders = options.corsExposedHeaders || []; exposedHeaders.push.apply(exposedHeaders, ['Cache-Control', 'Content-Language', 'Content-Type', 'Content-Length', 'Expires', 'Last-Modified', 'Pragma', 'Content-Range', 'Content-Encoding']); /*************** COMMON convert and validate parameters **************/ var partialOutputMode = options.partialOutputMode || 'disabled'; if(partialOutputMode.indexOf(',') >= 0 || ',disabled,chunked,joined,'.indexOf(',' + partialOutputMode + ',') < 0) { return failWithoutRequest(cb, [3]); } if(method.indexOf(',') >= 0 || !httpinvoke.anyMethod && supportedMethods.indexOf(',' + method + ',') < 0) { return failWithoutRequest(cb, [4, method]); } var optionsOutputType = options.outputType; outputBinary = optionsOutputType === 'bytearray'; if(!optionsOutputType || optionsOutputType === 'text' || outputBinary) { outputConverter = pass; } else if(converters['text ' + optionsOutputType]) { outputConverter = converters['text ' + optionsOutputType]; outputBinary = false; } else if(converters['bytearray ' + optionsOutputType]) { outputConverter = converters['bytearray ' + optionsOutputType]; outputBinary = true; } else { return failWithoutRequest(cb, [5, optionsOutputType]); } inputConverter = pass; var optionsInputType = options.inputType; input = options.input; if(input !== _undefined) { if(!optionsInputType || optionsInputType === 'auto') { if(typeof input !== 'string' && !isByteArray(input) && !isFormData(input)) { return failWithoutRequest(cb, [6]); } } else if(optionsInputType === 'text') { if(typeof input !== 'string') { return failWithoutRequest(cb, [7]); } } else if (optionsInputType === 'formdata') { if(!isFormData(input)) { return failWithoutRequest(cb, [8]); } } else if (optionsInputType === 'bytearray') { if(!isByteArray(input)) { return failWithoutRequest(cb, [9]); } } else if(converters[optionsInputType + ' text']) { inputConverter = converters[optionsInputType + ' text']; } else if(converters[optionsInputType + ' bytearray']) { inputConverter = converters[optionsInputType + ' bytearray']; } else if(converters[optionsInputType + ' formdata']) { inputConverter = converters[optionsInputType + ' formdata']; } else { return failWithoutRequest(cb, [10, optionsInputType]); } if(typeof input === 'object' && !isFormData(input)) { if(global.ArrayBuffer && input instanceof global.ArrayBuffer) { input = new global.Uint8Array(input); } else if(isArrayBufferView(input)) { input = new global.Uint8Array(input.buffer, input.byteOffset, input.byteLength); } } try { input = inputConverter(input); } catch(err) { return failWithoutRequest(cb, err); } } else { if(optionsInputType && optionsInputType !== 'auto') { return failWithoutRequest(cb, [11]); } if(inputHeaders['Content-Type']) { return failWithoutRequest(cb, [12]); } } var isValidTimeout = function(timeout) { return timeout > 0 && timeout < 1073741824; }; var optionsTimeout = options.timeout; if(optionsTimeout !== _undefined) { if(typeof optionsTimeout === 'number' && isValidTimeout(optionsTimeout)) { timeout = optionsTimeout; } else if(isArray(optionsTimeout) && optionsTimeout.length === 2 && isValidTimeout(optionsTimeout[0]) && isValidTimeout(optionsTimeout[1])) { if(httpinvoke.corsFineGrainedTimeouts || !crossDomain) { uploadTimeout = optionsTimeout[0]; downloadTimeout = optionsTimeout[1]; } else { timeout = optionsTimeout[0] + optionsTimeout[1]; } } else { return failWithoutRequest(cb, [13]); } } if(uploadTimeout) { setTimeout(function() { if(statusCb) { cb(new Error('upload timeout')); promise(); } }, uploadTimeout); } if(timeout) { setTimeout(function() { if(cb) { cb(new Error('timeout')); promise(); } }, timeout); }
src/common/closures.js
/* global httpinvoke, url, method, options, cb */ /* global nextTick, mixInPromise, pass, progress, reject, resolve, supportedMethods, isArray, isArrayBufferView, isFormData, isByteArray, _undefined */ /* global setTimeout */ /* global crossDomain */// this one is a hack, because when in nodejs this is not really defined, but it is never needed /* jshint -W020 */ var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter; hook = function(type, args) { var hooks = httpinvoke._hooks[type]; for(var i = 0; i < hooks.length; i += 1) { args = hooks[i].apply(null, args); } return args; }; /*************** COMMON initialize parameters **************/ var downloadTimeout, uploadTimeout, timeout; if(!method) { // 1 argument // method, options, cb skipped method = 'GET'; options = {}; } else if(!options) { // 2 arguments if(typeof method === 'string') { // options. cb skipped options = {}; } else if(typeof method === 'object') { // method, cb skipped options = method; method = 'GET'; } else { // method, options skipped options = { finished: method }; method = 'GET'; } } else if(!cb) { // 3 arguments if(typeof method === 'object') { // method skipped method.finished = options; options = method; method = 'GET'; } else if(typeof options === 'function') { // options skipped options = { finished: options }; } // cb skipped } else { // 4 arguments options.finished = cb; } var safeCallback = function(name, aspectBefore, aspectAfter) { return function() { var args, _cb, failedOnHook = false, fail = function(err, args) { _cb = cb; cb = null; nextTick(function() { /* jshint expr:true */ _cb && _cb(err); /* jshint expr:false */ promise(); if(!_cb && !failedOnHook) { throw err; } }); return name === 'finished' ? [err] : args; }; aspectBefore.apply(null, args); try { args = hook(name, [].slice.call(arguments)); } catch(err) { failedOnHook = true; args = fail(err, args); } if(options[name]) { try { options[name].apply(null, args); } catch(err) { args = fail(err, args); } } aspectAfter.apply(null, args); }; }; failWithoutRequest = function(cb, err) { if(!(err instanceof Error)) { // create error here, instead of nextTick, to preserve stack err = new Error('Error code #' + err +'. See https://github.com/jakutis/httpinvoke#error-codes'); } nextTick(function() { if(cb === null) { return; } cb(err); }); promise = function() { }; return mixInPromise(promise); }; uploadProgressCb = safeCallback('uploading', pass, function(current, total) { promise[progress]({ type: 'upload', current: current, total: total }); }); downloadProgressCb = safeCallback('downloading', pass, function(current, total, partial) { promise[progress]({ type: 'download', current: current, total: total, partial: partial }); }); statusCb = safeCallback('gotStatus', function() { statusCb = null; if(downloadTimeout) { setTimeout(function() { if(cb) { cb(new Error('download timeout')); promise(); } }, downloadTimeout); } }, function(statusCode, headers) { promise[progress]({ type: 'headers', statusCode: statusCode, headers: headers }); }); cb = safeCallback('finished', function() { cb = null; promise(); }, function(err, body, statusCode, headers) { var res = { body: body, statusCode: statusCode, headers: headers }; if(err) { return promise[reject](err, res); } promise[resolve](res); }); var fixPositiveOpt = function(opt) { if(options[opt] === _undefined) { options[opt] = 0; } else if(typeof options[opt] === 'number') { if(options[opt] < 0) { return failWithoutRequest(cb, [1, opt]); } } else { return failWithoutRequest(cb, [2, opt]); } }; var converters = options.converters || {}; var inputConverter; inputHeaders = options.headers || {}; outputHeaders = {}; exposedHeaders = options.corsExposedHeaders || []; exposedHeaders.push.apply(exposedHeaders, ['Cache-Control', 'Content-Language', 'Content-Type', 'Content-Length', 'Expires', 'Last-Modified', 'Pragma', 'Content-Range', 'Content-Encoding']); /*************** COMMON convert and validate parameters **************/ var partialOutputMode = options.partialOutputMode || 'disabled'; if(partialOutputMode.indexOf(',') >= 0 || ',disabled,chunked,joined,'.indexOf(',' + partialOutputMode + ',') < 0) { return failWithoutRequest(cb, [3]); } if(method.indexOf(',') >= 0 || !httpinvoke.anyMethod && supportedMethods.indexOf(',' + method + ',') < 0) { return failWithoutRequest(cb, [4, method]); } var optionsOutputType = options.outputType; outputBinary = optionsOutputType === 'bytearray'; if(!optionsOutputType || optionsOutputType === 'text' || outputBinary) { outputConverter = pass; } else if(converters['text ' + optionsOutputType]) { outputConverter = converters['text ' + optionsOutputType]; outputBinary = false; } else if(converters['bytearray ' + optionsOutputType]) { outputConverter = converters['bytearray ' + optionsOutputType]; outputBinary = true; } else { return failWithoutRequest(cb, [5, optionsOutputType]); } inputConverter = pass; var optionsInputType = options.inputType; input = options.input; if(input !== _undefined) { if(!optionsInputType || optionsInputType === 'auto') { if(typeof input !== 'string' && !isByteArray(input) && !isFormData(input)) { return failWithoutRequest(cb, [6]); } } else if(optionsInputType === 'text') { if(typeof input !== 'string') { return failWithoutRequest(cb, [7]); } } else if (optionsInputType === 'formdata') { if(!isFormData(input)) { return failWithoutRequest(cb, [8]); } } else if (optionsInputType === 'bytearray') { if(!isByteArray(input)) { return failWithoutRequest(cb, [9]); } } else if(converters[optionsInputType + ' text']) { inputConverter = converters[optionsInputType + ' text']; } else if(converters[optionsInputType + ' bytearray']) { inputConverter = converters[optionsInputType + ' bytearray']; } else if(converters[optionsInputType + ' formdata']) { inputConverter = converters[optionsInputType + ' formdata']; } else { return failWithoutRequest(cb, [10, optionsInputType]); } if(typeof input === 'object' && !isFormData(input)) { if(global.ArrayBuffer && input instanceof global.ArrayBuffer) { input = new global.Uint8Array(input); } else if(isArrayBufferView(input)) { input = new global.Uint8Array(input.buffer, input.byteOffset, input.byteLength); } } try { input = inputConverter(input); } catch(err) { return failWithoutRequest(cb, err); } } else { if(optionsInputType && optionsInputType !== 'auto') { return failWithoutRequest(cb, [11]); } if(inputHeaders['Content-Type']) { return failWithoutRequest(cb, [12]); } } var isValidTimeout = function(timeout) { return timeout > 0 && timeout < 1073741824; }; var optionsTimeout = options.timeout; if(optionsTimeout !== _undefined) { if(typeof optionsTimeout === 'number' && isValidTimeout(optionsTimeout)) { timeout = optionsTimeout; } else if(isArray(optionsTimeout) && optionsTimeout.length === 2 && isValidTimeout(optionsTimeout[0]) && isValidTimeout(optionsTimeout[1])) { if(httpinvoke.corsFineGrainedTimeouts || !crossDomain) { uploadTimeout = optionsTimeout[0]; downloadTimeout = optionsTimeout[1]; } else { timeout = optionsTimeout[0] + optionsTimeout[1]; } } else { return failWithoutRequest(cb, [13]); } } if(uploadTimeout) { setTimeout(function() { if(statusCb) { cb(new Error('upload timeout')); promise(); } }, uploadTimeout); } if(timeout) { setTimeout(function() { if(cb) { cb(new Error('timeout')); promise(); } }, timeout); }
remove unused fixPositiveOpt
src/common/closures.js
remove unused fixPositiveOpt
<ide><path>rc/common/closures.js <ide> } <ide> promise[resolve](res); <ide> }); <del>var fixPositiveOpt = function(opt) { <del> if(options[opt] === _undefined) { <del> options[opt] = 0; <del> } else if(typeof options[opt] === 'number') { <del> if(options[opt] < 0) { <del> return failWithoutRequest(cb, [1, opt]); <del> } <del> } else { <del> return failWithoutRequest(cb, [2, opt]); <del> } <del>}; <ide> var converters = options.converters || {}; <ide> var inputConverter; <ide> inputHeaders = options.headers || {};
Java
apache-2.0
56f1cc12aef1b37ec35f8889105ee109f2c8c925
0
darranl/directory-shared
/* * 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.directory.shared.ldap.schema.comparators; import org.apache.directory.shared.ldap.csn.Csn; import org.apache.directory.shared.ldap.entry.StringValue; import org.apache.directory.shared.ldap.schema.LdapComparator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A comparator for CSN. * * The CSN are ordered depending on an evaluation of its component, in this order : * - time, * - changeCount, * - sid * - modifierNumber * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$ */ public class CsnComparator extends LdapComparator<Object> { /** A logger for this class */ private static final Logger LOG = LoggerFactory.getLogger( CsnComparator.class ); /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** * The CsnComparator constructor. Its OID is the CsnMatch matching * rule OID. */ public CsnComparator( String oid ) { super( oid ); } /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare( Object csnObj1, Object csnObj2 ) { LOG.debug( "comparing CSN objects '{}' with '{}'", csnObj1, csnObj2 ); // ------------------------------------------------------------------- // Handle some basis cases // ------------------------------------------------------------------- if ( csnObj1 == null ) { return ( csnObj2 == null ) ? 0 : -1; } if ( csnObj2 == null ) { return 1; } String csnStr1 = null; String csnStr2 = null; if( csnObj1 instanceof StringValue ) { csnStr1 = ( ( StringValue ) csnObj1 ).get(); } else { csnStr1 = csnObj1.toString(); } if( csnObj2 instanceof StringValue ) { csnStr2 = ( ( StringValue ) csnObj2 ).get(); } else { csnStr2 = csnObj2.toString(); } Csn csn1 = new Csn( csnStr1 ); Csn csn2 = new Csn( csnStr2 ); return csn1.compareTo( csn2 ); } }
ldap/src/main/java/org/apache/directory/shared/ldap/schema/comparators/CsnComparator.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.directory.shared.ldap.schema.comparators; import org.apache.directory.shared.ldap.csn.Csn; import org.apache.directory.shared.ldap.schema.LdapComparator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A comparator for CSN. * * The CSN are ordered depending on an evaluation of its component, in this order : * - time, * - changeCount, * - sid * - modifierNumber * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$ */ public class CsnComparator extends LdapComparator<String> { /** A logger for this class */ private static final Logger LOG = LoggerFactory.getLogger( CsnComparator.class ); /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** * The CsnComparator constructor. Its OID is the CsnMatch matching * rule OID. */ public CsnComparator( String oid ) { super( oid ); } /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare( String csnStr1, String csnStr2 ) { LOG.debug( "comparing CSN objects '{}' with '{}'", csnStr1, csnStr2 ); // ------------------------------------------------------------------- // Handle some basis cases // ------------------------------------------------------------------- if ( csnStr1 == null ) { return ( csnStr2 == null ) ? 0 : -1; } if ( csnStr2 == null ) { return 1; } Csn csn1 = new Csn( csnStr1 ); Csn csn2 = new Csn( csnStr2 ); if ( csn1.getTimestamp() != csn2.getTimestamp() ) { return ( csn1.getTimestamp() < csn2.getTimestamp() ? -1 : 1 ); } if ( csn1.getChangeCount() != csn2.getChangeCount() ) { return ( csn1.getChangeCount() < csn2.getChangeCount() ? -1 : 1 ); } if ( csn1.getReplicaId() != csn2.getReplicaId() ) { return ( csn1.getReplicaId() < csn2.getReplicaId() ? -1 : 1 ); } if ( csn1.getOperationNumber() != csn2.getOperationNumber() ) { return ( csn1.getOperationNumber() < csn2.getOperationNumber() ? -1 : 1 ); } return 0; } }
fixed for the case where CSN is sent encapsulated in StringValue object git-svn-id: a98780f44e7643575d86f056c30a4189ca15db44@939626 13f79535-47bb-0310-9956-ffa450edef68
ldap/src/main/java/org/apache/directory/shared/ldap/schema/comparators/CsnComparator.java
fixed for the case where CSN is sent encapsulated in StringValue object
<ide><path>dap/src/main/java/org/apache/directory/shared/ldap/schema/comparators/CsnComparator.java <ide> <ide> <ide> import org.apache.directory.shared.ldap.csn.Csn; <add>import org.apache.directory.shared.ldap.entry.StringValue; <ide> import org.apache.directory.shared.ldap.schema.LdapComparator; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> * @author <a href="mailto:[email protected]">Apache Directory Project</a> <ide> * @version $Rev$ <ide> */ <del>public class CsnComparator extends LdapComparator<String> <add>public class CsnComparator extends LdapComparator<Object> <ide> { <ide> /** A logger for this class */ <ide> private static final Logger LOG = LoggerFactory.getLogger( CsnComparator.class ); <ide> /** <ide> * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) <ide> */ <del> public int compare( String csnStr1, String csnStr2 ) <add> public int compare( Object csnObj1, Object csnObj2 ) <ide> { <del> LOG.debug( "comparing CSN objects '{}' with '{}'", csnStr1, csnStr2 ); <add> LOG.debug( "comparing CSN objects '{}' with '{}'", csnObj1, csnObj2 ); <ide> <ide> // ------------------------------------------------------------------- <ide> // Handle some basis cases <ide> // ------------------------------------------------------------------- <del> if ( csnStr1 == null ) <add> if ( csnObj1 == null ) <ide> { <del> return ( csnStr2 == null ) ? 0 : -1; <add> return ( csnObj2 == null ) ? 0 : -1; <ide> } <ide> <del> if ( csnStr2 == null ) <add> if ( csnObj2 == null ) <ide> { <ide> return 1; <add> } <add> <add> String csnStr1 = null; <add> String csnStr2 = null; <add> <add> if( csnObj1 instanceof StringValue ) <add> { <add> csnStr1 = ( ( StringValue ) csnObj1 ).get(); <add> } <add> else <add> { <add> csnStr1 = csnObj1.toString(); <add> } <add> <add> if( csnObj2 instanceof StringValue ) <add> { <add> csnStr2 = ( ( StringValue ) csnObj2 ).get(); <add> } <add> else <add> { <add> csnStr2 = csnObj2.toString(); <ide> } <ide> <ide> Csn csn1 = new Csn( csnStr1 ); <ide> Csn csn2 = new Csn( csnStr2 ); <ide> <del> if ( csn1.getTimestamp() != csn2.getTimestamp() ) <del> { <del> return ( csn1.getTimestamp() < csn2.getTimestamp() ? -1 : 1 ); <del> } <del> <del> if ( csn1.getChangeCount() != csn2.getChangeCount() ) <del> { <del> return ( csn1.getChangeCount() < csn2.getChangeCount() ? -1 : 1 ); <del> } <del> <del> if ( csn1.getReplicaId() != csn2.getReplicaId() ) <del> { <del> return ( csn1.getReplicaId() < csn2.getReplicaId() ? -1 : 1 ); <del> } <del> <del> if ( csn1.getOperationNumber() != csn2.getOperationNumber() ) <del> { <del> return ( csn1.getOperationNumber() < csn2.getOperationNumber() ? -1 : 1 ); <del> } <del> <del> return 0; <add> return csn1.compareTo( csn2 ); <ide> } <ide> }
Java
mit
1c7d52b0e39301f07866701eeac3bc0023a71b59
0
jimmikaelkael/BungeePerms,CodeCrafter47/BungeePerms
package net.alpenblock.bungeeperms; import java.io.File; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import net.alpenblock.bungeeperms.config.YamlConfiguration; import net.alpenblock.bungeeperms.io.BackEndType; import net.alpenblock.bungeeperms.io.UUIDPlayerDBType; import net.alpenblock.bungeeperms.uuid.UUIDFetcher; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Plugin; public class BungeePerms extends Plugin implements Listener { private static BungeePerms instance; public static BungeePerms getInstance() { return instance; } private BungeeCord bc; private Config config; private Debug debug; private PermissionsManager pm; private int fetchercooldown; private boolean tabcomplete; private boolean notifypromote; private boolean notifydemote; private Listener tablistener; @Override public void onLoad() { //static instance = this; bc = BungeeCord.getInstance(); //check for config file existance File f = new File(getDataFolder(), "/config.yml"); if (!f.exists() | !f.isFile()) { bc.getLogger().info("[BungeePerms] no config file found -> copy packed default config.yml to data folder ..."); f.getParentFile().mkdirs(); try { //file ffnen ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("config.yml"); if (url != null) { URLConnection connection = url.openConnection(); connection.setUseCaches(false); YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(connection.getInputStream()); defConfig.save(f); } } catch (Exception e) { e.printStackTrace(); } bc.getLogger().info("[BungeePerms] copied default config.yml to data folder"); } config = new Config(this, "/config.yml"); config.load(); loadConfig(); debug = new Debug(this, config, "BP"); //load commands loadcmds(); pm = new PermissionsManager(this, config, debug); } private void loadConfig() { fetchercooldown = config.getInt("uuidfetcher.cooldown", 3000); tabcomplete = config.getBoolean("tabcomplete", false); notifypromote = config.getBoolean("notify.promote", false); notifydemote = config.getBoolean("notify.demote", false); } @Override public void onEnable() { bc.getLogger().info("Activating BungeePerms ..."); pm.enable(); if (tabcomplete) { tablistener = new TabListener(); BungeeCord.getInstance().getPluginManager().registerListener(this, tablistener); } } @Override public void onDisable() { bc.getLogger().info("Deactivating BungeePerms ..."); pm.disable(); if (tabcomplete) { BungeeCord.getInstance().getPluginManager().registerListener(this, tablistener); } } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!cmd.getName().equalsIgnoreCase("bungeeperms")) { return false; } if (args.length == 0) { sender.sendMessage(ChatColor.GOLD + "Welcome to BungeePerms, a BungeeCord permissions plugin"); sender.sendMessage(Color.Text + "Version " + ChatColor.GOLD + this.getDescription().getVersion()); sender.sendMessage(Color.Text + "Author " + ChatColor.GOLD + this.getDescription().getAuthor()); return true; } else if (args.length > 0) { if (args[0].equalsIgnoreCase("help")) { return handleHelp(sender, args); } else if (args[0].equalsIgnoreCase("reload")) { return handleReload(sender, args); } else if (args[0].equalsIgnoreCase("users")) { return handleUsers(sender, args); } else if (args[0].equalsIgnoreCase("user")) { return handleUserCommands(sender, args); } else if (args[0].equalsIgnoreCase("groups")) { return handleGroups(sender, args); } else if (args[0].equalsIgnoreCase("group")) { return handleGroupCommands(sender, args); } else if (args[0].equalsIgnoreCase("promote")) { return handlePromote(sender, args); } else if (args[0].equalsIgnoreCase("demote")) { return handleDemote(sender, args); } else if (args[0].equalsIgnoreCase("format")) { return handleFormat(sender, args); } else if (args[0].equalsIgnoreCase("cleanup")) { return handleCleanup(sender, args); } else if (args[0].equalsIgnoreCase("backend")) { return handleBackend(sender, args); //todo: remove this } else if (args[0].equalsIgnoreCase("migrate")) { return handleMigrate(sender, args); } else if (args[0].equalsIgnoreCase("uuid")) { return handleUUID(sender, args); } } return false; } private boolean handleHelp(CommandSender sender, String args[]) { //todo: better help output with pages if (pm.hasOrConsole(sender, "bungeeperms.help", true)) { showHelp(sender); return true; } return true; } private boolean handleReload(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.reload", true)) { return true; } loadConfig(); pm.loadConfig(); pm.loadPerms(); pm.sendPMAll("reloadall"); sender.sendMessage(Color.Text + "Permissions reloaded"); return true; } private boolean handleUsers(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.users.list", true)) { return true; } if (args.length == 1) { List<String> users = pm.getRegisteredUsers(); if (users.isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { String out = Color.Text + "Following players are registered: "; for (int i = 0; i < users.size(); i++) { out += Color.User + users.get(i) + Color.Text + (i + 1 < users.size() ? ", " : ""); } sender.sendMessage(out); } return true; } else if (args.length == 2) { //for counting if (!args[1].equalsIgnoreCase("-c")) { return false; } if (pm.getRegisteredUsers().isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { sender.sendMessage(Color.Text + "There are " + Color.Value + pm.getRegisteredUsers().size() + Color.Text + " players registered."); } return true; } else { Messages.sendTooManyArgsMessage(sender); return true; } } private boolean handleUserCommands(CommandSender sender, String args[]) { if (args.length < 3) { Messages.sendTooLessArgsMessage(sender); return true; } if (args[2].equalsIgnoreCase("list")) { return handleUserCommandsList(sender, args); } else if (args[2].equalsIgnoreCase("groups")) { return handleUserCommandsGroups(sender, args); } else if (args[2].equalsIgnoreCase("info")) { return handleUserCommandsInfo(sender, args); } else if (args[2].equalsIgnoreCase("delete")) { return handleUserCommandsDelete(sender, args); } else if (Statics.argAlias(args[2], "add", "addperm", "addpermission")) { return handleUserCommandsPermAdd(sender, args); } else if (Statics.argAlias(args[2], "remove", "removeperm", "removepermission")) { return handleUserCommandsPermRemove(sender, args); } else if (args[2].equalsIgnoreCase("has")) { return handleUserCommandsHas(sender, args); } else if (args[2].equalsIgnoreCase("addgroup")) { return handleUserCommandsGroupAdd(sender, args); } else if (args[2].equalsIgnoreCase("removegroup")) { return handleUserCommandsGroupRemove(sender, args); } else if (args[2].equalsIgnoreCase("setgroup")) { return handleUserCommandsGroupSet(sender, args); } return false; } //user commands private boolean handleUserCommandsList(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.list", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 5)) { return true; } String player = Statics.getFullPlayerName(args[1]); String server = args.length > 3 ? args[3].toLowerCase() : null; String world = args.length > 4 ? args[4].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Permissions of the player " + Color.User + user.getName() + Color.Text + " (" + Color.User + user.getUUID() + Color.Text + "):"); List<BPPermission> perms = user.getPermsWithOrigin(server, world); for (BPPermission perm : perms) { sender.sendMessage(Color.Text + "- " + Color.Value + perm.getPermission() + Color.Text + " (" + Color.Value + (!perm.isGroup() && perm.getOrigin().equalsIgnoreCase(player) ? "own" : perm.getOrigin()) + Color.Text + (perm.getServer() != null ? " | " + Color.Value + perm.getServer() + Color.Text : "") + (perm.getWorld() != null ? " | " + Color.Value + perm.getWorld() + Color.Text : "") + ")"); } return true; } private boolean handleUserCommandsGroups(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.groups", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Groups of the player " + Color.User + user.getName() + Color.Text + ":"); for (Group g : user.getGroups()) { sender.sendMessage(Color.Text + "- " + Color.Value + g.getName()); } return true; } private boolean handleUserCommandsInfo(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.info", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "About " + Color.User + user.getName()); sender.sendMessage(Color.Text + "UUID: " + Color.Value + user.getUUID()); String groups = ""; for (int i = 0; i < user.getGroups().size(); i++) { groups += Color.Value + user.getGroups().get(i).getName() + Color.Text + " (" + Color.Value + user.getGroups().get(i).getPerms().size() + Color.Text + ")" + (i + 1 < user.getGroups().size() ? ", " : ""); } sender.sendMessage(Color.Text + "Groups: " + groups); //all group perms sender.sendMessage(Color.Text + "Effective permissions: " + Color.Value + user.getEffectivePerms().size());//TODO return true; } private boolean handleUserCommandsDelete(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.delete", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } pm.deleteUser(user); sender.sendMessage(Color.Text + "User deleted"); return true; } private boolean handleUserCommandsPermAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String player = Statics.getFullPlayerName(args[1]); String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } if (server == null) { if (user.getExtraperms().contains("-" + perm)) { pm.removeUserPerm(user, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + "."); } else if (!user.getExtraperms().contains(perm)) { pm.addUserPerm(user, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + "."); } } else { if (world == null) { List<String> perserverperms = user.getServerPerms().get(server); if (perserverperms == null) { perserverperms = new ArrayList<>(); user.getServerPerms().put(server, perserverperms); } if (perserverperms.contains("-" + perm)) { pm.removeUserPerServerPerm(user, server, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains(perm)) { pm.addUserPerServerPerm(user, server, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " alreday has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } else { Map<String, List<String>> perserverperms = user.getServerWorldPerms().get(server); if (perserverperms == null) { perserverperms = new HashMap<>(); user.getServerWorldPerms().put(server, perserverperms); } List<String> perserverworldperms = perserverperms.get(world); if (perserverworldperms == null) { perserverworldperms = new ArrayList<>(); perserverperms.put(world, perserverworldperms); } if (perserverworldperms.contains("-" + perm)) { pm.removeUserPerServerWorldPerm(user, server, world, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains(perm)) { pm.addUserPerServerWorldPerm(user, server, world, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " alreday has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleUserCommandsPermRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String player = Statics.getFullPlayerName(args[1]); String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } if (server == null) { if (user.getExtraperms().contains(perm)) { pm.removeUserPerm(user, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + "."); } else if (!user.getExtraperms().contains("-" + perm)) { pm.addUserPerm(user, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + "."); } } else { if (world == null) { List<String> perserverperms = user.getServerPerms().get(server); if (perserverperms == null) { perserverperms = new ArrayList<>(); user.getServerPerms().put(server, perserverperms); } if (perserverperms.contains(perm)) { pm.removeUserPerServerPerm(user, server, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains("-" + perm)) { pm.addUserPerServerPerm(user, server, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } else { Map<String, List<String>> perserverperms = user.getServerWorldPerms().get(server); if (perserverperms == null) { perserverperms = new HashMap<>(); user.getServerWorldPerms().put(server, perserverperms); } List<String> perserverworldperms = perserverperms.get(world); if (perserverworldperms == null) { perserverworldperms = new ArrayList<>(); perserverperms.put(world, perserverworldperms); } if (perserverworldperms.contains(perm)) { pm.removeUserPerServerWorldPerm(user, server, world, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains("-" + perm)) { pm.addUserPerServerWorldPerm(user, server, world, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleUserCommandsHas(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.has", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String player = Statics.getFullPlayerName(args[1]); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } if (server == null) { boolean has = pm.hasPerm(player, args[3].toLowerCase()); sender.sendMessage(Color.Text + "Player " + Color.User + user.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } else { if (world == null) { boolean has = pm.hasPermOnServer(user.getName(), args[3].toLowerCase(), server); sender.sendMessage(Color.Text + "Player " + Color.User + user.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } else { boolean has = pm.hasPermOnServerInWorld(user.getName(), args[3].toLowerCase(), server, world); sender.sendMessage(Color.Text + "Player " + Color.User + user.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } } return true; } private boolean handleUserCommandsGroupAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.group.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String player = Statics.getFullPlayerName(args[1]); String groupname = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.User + groupname + Color.Error + " does not exist!"); return true; } User u = pm.getUser(player); if (u == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } List<Group> groups = u.getGroups(); for (Group g : groups) { if (g.getName().equalsIgnoreCase(group.getName())) { sender.sendMessage(Color.Error + "Player is already in group " + Color.Value + groupname + Color.Error + "!"); return true; } } pm.addUserGroup(u, group); sender.sendMessage(Color.Text + "Added group " + Color.Value + groupname + Color.Text + " to player " + Color.User + u.getName() + Color.Text + "."); return true; } private boolean handleUserCommandsGroupRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.group.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String player = Statics.getFullPlayerName(args[1]); String groupname = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.User + groupname + Color.Error + " does not exist!"); return true; } User u = pm.getUser(player); if (u == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } List<Group> groups = u.getGroups(); for (Group g : groups) { if (g.getName().equalsIgnoreCase(group.getName())) { pm.removeUserGroup(u, group); sender.sendMessage(Color.Text + "Removed group " + Color.Value + groupname + Color.Text + " from player " + Color.User + u.getName() + Color.Text + "."); return true; } } sender.sendMessage(Color.Error + "Player is not in group " + Color.Value + groupname + Color.Error + "!"); return true; } private boolean handleUserCommandsGroupSet(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.group.set", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String player = Statics.getFullPlayerName(args[1]); String groupname = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.User + groupname + Color.Error + " does not exist!"); return true; } User u = pm.getUser(player); if (u == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } List<Group> laddergroups = pm.getLadderGroups(group.getLadder()); for (Group g : laddergroups) { pm.removeUserGroup(u, g); } pm.addUserGroup(u, group); sender.sendMessage(Color.Text + "Set group " + Color.Value + groupname + Color.Text + " for player " + Color.User + u.getName() + Color.Text + "."); return true; } //end user commands private boolean handleGroups(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.groups", true)) { return true; } if (!Statics.matchArgs(sender, args, 1)) { return true; } if (pm.getGroups().isEmpty()) { sender.sendMessage(Color.Text + "No groups found!"); } else { sender.sendMessage(Color.Text + "There are following groups:"); for (String l : pm.getLadders()) { for (Group g : pm.getLadderGroups(l)) { sender.sendMessage(Color.Text + "- " + Color.Value + g.getName() + Color.Text + " (" + Color.Value + l + Color.Text + ")"); } } } return true; } private boolean handleGroupCommands(CommandSender sender, String args[]) { if (args.length < 3) { Messages.sendTooLessArgsMessage(sender); return true; } if (args[2].equalsIgnoreCase("list")) { return handleGroupCommandsList(sender, args); } else if (args[2].equalsIgnoreCase("info")) { return handleGroupCommandsInfo(sender, args); } else if (args[2].equalsIgnoreCase("users")) { return handleGroupCommandsUsers(sender, args); } else if (args[2].equalsIgnoreCase("create")) { return handleGroupCommandsCreate(sender, args); } else if (args[2].equalsIgnoreCase("delete")) { return handleGroupCommandsDelete(sender, args); } else if (Statics.argAlias(args[2], "add", "addperm", "addpermission")) { return handleGroupCommandsPermAdd(sender, args); } else if (Statics.argAlias(args[2], "remove", "removeperm", "removepermission")) { return handleGroupCommandsPermRemove(sender, args); } else if (Statics.argAlias(args[2], "has", "check")) { return handleGroupCommandsHas(sender, args); } else if (Statics.argAlias(args[2], "addinherit", "addinheritance")) { return handleGroupCommandsInheritAdd(sender, args); } else if (Statics.argAlias(args[2], "removeinherit", "removeinheritance")) { return handleGroupCommandsInheritRemove(sender, args); } else if (args[2].equalsIgnoreCase("rank")) { return handleGroupCommandsRank(sender, args); } else if (args[2].equalsIgnoreCase("weight")) { return handleGroupCommandsWeight(sender, args); } else if (args[2].equalsIgnoreCase("ladder")) { return handleGroupCommandsLadder(sender, args); } else if (args[2].equalsIgnoreCase("default")) { return handleGroupCommandsDefault(sender, args); } else if (args[2].equalsIgnoreCase("display")) { return handleGroupCommandsDisplay(sender, args); } else if (args[2].equalsIgnoreCase("prefix")) { return handleGroupCommandsPrefix(sender, args); } else if (args[2].equalsIgnoreCase("suffix")) { return handleGroupCommandsSuffix(sender, args); } return false; } //group commands private boolean handleGroupCommandsList(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.list", true)) { return true; } if (args.length > 5) { Messages.sendTooManyArgsMessage(sender); return true; } String groupname = args[1]; String server = args.length > 3 ? args[3] : null; String world = args.length > 4 ? args[4] : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Permissions of the group " + Color.Value + group.getName() + Color.Text + ":"); List<BPPermission> perms = group.getPermsWithOrigin(server, world); for (BPPermission perm : perms) { sender.sendMessage(Color.Text + "- " + Color.Value + perm.getPermission() + Color.Text + " (" + Color.Value + (perm.getOrigin().equalsIgnoreCase(groupname) ? "own" : perm.getOrigin()) + Color.Text + (perm.getServer() != null ? " | " + Color.Value + perm.getServer() + Color.Text : "") + (perm.getWorld() != null ? " | " + Color.Value + perm.getWorld() + Color.Text : "") + ")"); } return true; } private boolean handleGroupCommandsInfo(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.info", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String groupname = args[1]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Info to group " + Color.Value + group.getName() + Color.Text + ":"); //inheritances String inheritances = ""; for (int i = 0; i < group.getInheritances().size(); i++) { inheritances += Color.Value + group.getInheritances().get(i) + Color.Text + " (" + Color.Value + pm.getGroup(group.getInheritances().get(i)).getPerms().size() + Color.Text + ")" + (i + 1 < group.getInheritances().size() ? ", " : ""); } if (inheritances.length() == 0) { inheritances = Color.Text + "(none)"; } sender.sendMessage(Color.Text + "Inheritances: " + inheritances); //group perms sender.sendMessage(Color.Text + "Group permissions: " + Color.Value + group.getPerms().size()); //group rank sender.sendMessage(Color.Text + "Rank: " + Color.Value + group.getRank()); //group weight sender.sendMessage(Color.Text + "Weight: " + Color.Value + group.getWeight()); //group ladder sender.sendMessage(Color.Text + "Ladder: " + Color.Value + group.getLadder()); //default sender.sendMessage(Color.Text + "Default: " + Color.Value + (group.isDefault() ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(group.isDefault()).toUpperCase()); //all group perms sender.sendMessage(Color.Text + "Effective permissions: " + Color.Value + group.getEffectivePerms().size()); //display sender.sendMessage(Color.Text + "Dislay name: " + ChatColor.RESET + (group.getDisplay().length() > 0 ? group.getDisplay() : Color.Text + "(none)")); //prefix sender.sendMessage(Color.Text + "Prefix: " + ChatColor.RESET + (group.getPrefix().length() > 0 ? group.getPrefix() : Color.Text + "(none)")); //suffix sender.sendMessage(Color.Text + "Suffix: " + ChatColor.RESET + (group.getSuffix().length() > 0 ? group.getSuffix() : Color.Text + "(none)")); return true; } private boolean handleGroupCommandsUsers(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.users", true)) { return true; } if (args.length > 4) { Messages.sendTooManyArgsMessage(sender); return true; } String groupname = args[1]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " doesn't exists!"); return true; } List<String> users = pm.getGroupUsers(group); if (args.length == 3) { if (users.isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { String out = Color.Text + "Following players are in group " + Color.Value + group.getName() + Color.Text + ": "; for (int i = 0; i < users.size(); i++) { out += Color.User + users.get(i) + Color.Text + (i + 1 < users.size() ? ", " : ""); } sender.sendMessage(out); } return true; } else if (args.length == 4) { if (!args[3].equalsIgnoreCase("-c")) { return false; } if (users.isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { sender.sendMessage(Color.Text + "There are " + Color.Value + users.size() + Color.Text + " players in group " + Color.Value + group.getName() + Color.Text + "."); } return true; } return true; } private boolean handleGroupCommandsCreate(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.create", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String groupname = args[1]; if (pm.getGroup(groupname) != null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " already exists!"); return true; } Group group = new Group(groupname, new ArrayList<String>(), new ArrayList<String>(), new HashMap<String, Server>(), 1500, 1500, "default", false, "", "", ""); pm.addGroup(group); sender.sendMessage(Color.Text + "Group " + Color.Value + groupname + Color.Text + " created."); return true; } private boolean handleGroupCommandsDelete(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.delete", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String groupname = args[1]; Group group = pm.getGroup(groupname); if (group != null) { sender.sendMessage(Color.Text + "Group deletion in progress ... this may take a while (backend integrity check)."); pm.deleteGroup(group); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " deleted."); } else { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); } return true; } private boolean handleGroupCommandsPermAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String groupname = args[1]; String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } //global perm if (server == null) { if (group.getPerms().contains("-" + perm)) { pm.removeGroupPerm(group, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + "."); } else if (!group.getPerms().contains(perm)) { pm.addGroupPerm(group, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + "."); } } else { Server srv = group.getServers().get(server); if (srv == null) { srv = new Server(server, new ArrayList<String>(), new HashMap<String, World>(), "", "", ""); group.getServers().put(server, srv); } //per server perm if (world == null) { List<String> perserverperms = srv.getPerms(); if (perserverperms.contains("-" + perm)) { pm.removeGroupPerServerPerm(group, server, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains(perm)) { pm.addGroupPerServerPerm(group, server, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } //per server world perms else { World w = srv.getWorlds().get(world); if (w == null) { w = new World(world, new ArrayList<String>(), "", "", ""); srv.getWorlds().put(world, w); } List<String> perserverworldperms = w.getPerms(); if (perserverworldperms.contains("-" + perm)) { pm.removeGroupPerServerWorldPerm(group, server, world, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains(perm)) { pm.addGroupPerServerWorldPerm(group, server, world, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleGroupCommandsPermRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String groupname = args[1]; String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } //global perm if (server == null) { if (group.getPerms().contains(perm)) { pm.removeGroupPerm(group, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + "."); } else if (!group.getPerms().contains("-" + perm)) { pm.addGroupPerm(group, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + "."); } } else { Server srv = group.getServers().get(server); if (srv == null) { srv = new Server(server, new ArrayList<String>(), new HashMap<String, World>(), "", "", ""); group.getServers().put(server, srv); } //per server perm if (world == null) { List<String> perserverperms = srv.getPerms(); if (perserverperms.contains(perm)) { pm.removeGroupPerServerPerm(group, server, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains("-" + perm)) { pm.addGroupPerServerPerm(group, server, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } else { World w = srv.getWorlds().get(world); if (w == null) { w = new World(world, new ArrayList<String>(), "", "", ""); srv.getWorlds().put(world, w); } List<String> perserverworldperms = w.getPerms(); if (perserverworldperms.contains(perm)) { pm.removeGroupPerServerWorldPerm(group, server, world, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains("-" + perm)) { pm.addGroupPerServerWorldPerm(group, server, world, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleGroupCommandsHas(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.has", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String groupname = args[1]; String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } //global perm if (server == null) { boolean has = group.has(perm.toLowerCase()); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } else { //per server perm if (world == null) { boolean has = group.hasOnServer(perm.toLowerCase(), server); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } //per server world perm else { boolean has = group.hasOnServerInWorld(perm.toLowerCase(), server, world); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } } return true; } private boolean handleGroupCommandsInheritAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.inheritances.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; String addgroup = args[3]; //check group existance Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } Group toadd = pm.getGroup(addgroup); if (toadd == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + addgroup + Color.Error + " does not exist!"); return true; } List<String> inheritances = group.getInheritances(); //check for already existing inheritance for (String s : inheritances) { if (s.equalsIgnoreCase(toadd.getName())) { sender.sendMessage(Color.Error + "The group already inherits from " + Color.Value + addgroup + Color.Error + "!"); return true; } } pm.addGroupInheritance(group, toadd); sender.sendMessage(Color.Text + "Added inheritance " + Color.Value + addgroup + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsInheritRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.inheritances.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; String removegroup = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } Group toremove = pm.getGroup(removegroup); if (toremove == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + removegroup + Color.Error + " does not exist!"); return true; } List<String> inheritances = group.getInheritances(); for (String s : inheritances) { if (s.equalsIgnoreCase(toremove.getName())) { pm.removeGroupInheritance(group, toremove); sender.sendMessage(Color.Text + "Removed inheritance " + Color.Value + removegroup + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + "."); return true; } } sender.sendMessage(Color.Error + "The group " + Color.Value + group.getName() + Color.Error + " does not inherit from group " + Color.Value + removegroup + Color.Error + "!"); return true; } private boolean handleGroupCommandsRank(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.rank", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; int rank; try { rank = Integer.parseInt(args[3]); if (rank < 1) { throw new Exception(); } } catch (Exception e) { sender.sendMessage(Color.Error + "A whole number greater than 0 is required!"); return true; } Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.rankGroup(group, rank); sender.sendMessage(Color.Text + "Group rank set for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsWeight(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.weight", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; int weight; try { weight = Integer.parseInt(args[3]); if (weight < 1) { throw new Exception(); } } catch (Exception e) { sender.sendMessage(Color.Error + "A whole number greater than 0 is required!"); return true; } Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.weightGroup(group, weight); sender.sendMessage(Color.Text + "Group weight set for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsLadder(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.ladder", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; String ladder = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.ladderGroup(group, ladder); sender.sendMessage(Color.Text + "Group ladder set for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsDefault(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.default", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; boolean isdefault; try { isdefault = parseTrueFalse(args[3]); } catch (Exception e) { sender.sendMessage(Color.Error + "A form of '" + Color.Value + "true" + Color.Error + "','" + Color.Value + "false" + Color.Error + "','" + Color.Value + "yes" + Color.Error + "' or '" + Color.Value + "no" + Color.Error + "' is required!"); return true; } Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupDefault(group, isdefault); sender.sendMessage(Color.Text + "Marked group " + Color.Value + group.getName() + Color.Text + " as " + (isdefault ? "" : "non-") + "default."); return true; } private boolean handleGroupCommandsDisplay(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.display", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 6)) { return true; } String groupname = args[1]; String display = args.length > 3 ? args[3] : ""; String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupDisplay(group, display, server, world); sender.sendMessage(Color.Text + "Set display name for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsPrefix(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.prefix", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 6)) { return true; } String groupname = args[1]; String prefix = args.length > 3 ? args[3] : ""; String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupPrefix(group, prefix, server, world); sender.sendMessage(Color.Text + "Set prefix for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsSuffix(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.suffix", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 6)) { return true; } String groupname = args[1]; String suffix = args.length > 3 ? args[3] : ""; String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupSuffix(group, suffix, server, world); sender.sendMessage(Color.Text + "Set suffix for group " + Color.Value + group.getName() + Color.Text + "."); return true; } //end group commands private boolean handlePromote(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.promote", true)) { return true; } //2 or 3 args expected if (!Statics.matchArgs(sender, args, 2, 3)) { return true; } //get user String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + args[1] + Color.Error + " does not exist!"); return true; } //get next group by ladder Group playergroup = null; Group nextgroup = null; //ladder specified by sender if (args.length == 3) { String ladder = args[2]; playergroup = user.getGroupByLadder(ladder); if (playergroup != null) { nextgroup = pm.getNextGroup(playergroup); } else { List<Group> laddergroups = pm.getLadderGroups(ladder); if (!laddergroups.isEmpty()) { nextgroup = laddergroups.get(0); } } } //no ladder specified ... assume main ladder else { playergroup = pm.getMainGroup(user); if (playergroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " doesn't have a group!"); return true; } nextgroup = pm.getNextGroup(playergroup); } if (nextgroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " can't be promoted!"); return true; } //check permissions if (!pm.hasOrConsole(sender, "bungeeperms.promote." + nextgroup.getName(), true)) { return true; } //permission checks if sender is a player if (sender instanceof ProxiedPlayer) { User issuer = pm.getUser(sender.getName()); if (issuer == null) { sender.sendMessage(Color.Error + "You do not exist!"); return true; } Group issuergroup = pm.getMainGroup(issuer); if (issuergroup == null) { sender.sendMessage(Color.Error + "You don't have a group!"); return true; } if (!(issuergroup.getRank() < nextgroup.getRank())) { sender.sendMessage(Color.Error + "You can't promote the player " + Color.User + user.getName() + Color.Error + "!"); return true; } } //promote player //remove old group if neccessary if (playergroup != null) { pm.removeUserGroup(user, playergroup); } pm.addUserGroup(user, nextgroup); sender.sendMessage(Color.User + user.getName() + Color.Text + " is now " + Color.Value + nextgroup.getName() + Color.Text + "!"); //promote msg to user if(notifypromote) { ProxiedPlayer pp = bc.getPlayer(user.getName()); if(pp != null) { pp.sendMessage(Color.Text + "You were promoted to " + Color.Value + nextgroup.getName() + Color.Text + "!"); } } return true; } private boolean handleDemote(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.demote", true)) { return true; } //2 or 3 args expected if (!Statics.matchArgs(sender, args, 2, 3)) { return true; } //get user String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + args[1] + Color.Error + " does not exist!"); return true; } //get previous by ladder Group playergroup = null; Group previousgroup = null; //ladder specified by sender if (args.length == 3) { String ladder = args[2]; playergroup = user.getGroupByLadder(ladder); if (playergroup != null) { previousgroup = pm.getPreviousGroup(playergroup); } } //no ladder specified ... assume main ladder else { playergroup = pm.getMainGroup(user); if (playergroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " doesn't have a group!"); return true; } previousgroup = pm.getPreviousGroup(playergroup); } if (previousgroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " can't be demoted!"); return true; } //check permissions if (!pm.hasOrConsole(sender, "bungeeperms.demote." + previousgroup.getName(), true)) { return true; } //permision checks if sender is a player if (sender instanceof ProxiedPlayer) { User issuer = pm.getUser(sender.getName()); if (issuer == null) { sender.sendMessage(Color.Error + "You do not exist!"); return true; } Group issuergroup = pm.getMainGroup(issuer); if (issuergroup == null) { sender.sendMessage(Color.Error + "You don't have a group!"); return true; } if (!(issuergroup.getRank() < playergroup.getRank())) { sender.sendMessage(Color.Error + "You can't demote the player " + Color.User + user.getName() + Color.Error + "!"); return true; } } //demote //remove old group if neccessary if (playergroup != null) { pm.removeUserGroup(user, playergroup); } pm.addUserGroup(user, previousgroup); sender.sendMessage(Color.User + user.getName() + Color.Text + " is now " + Color.Value + previousgroup.getName() + Color.Text + "!"); //demote msg to user if(notifydemote) { ProxiedPlayer pp = bc.getPlayer(user.getName()); if(pp != null) { pp.sendMessage(Color.Text + "You were demoted to " + Color.Value + previousgroup.getName() + Color.Text + "!"); } } return true; } private boolean handleFormat(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.format", true)) { return true; } sender.sendMessage(Color.Text + "Formating permissions file/table ..."); pm.format(); sender.sendMessage(Color.Message + "Finished formating."); return true; } private boolean handleCleanup(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.cleanup", true)) { return true; } sender.sendMessage(Color.Text + "Cleaning up permissions file/table ..."); int deleted = pm.cleanup(); sender.sendMessage(Color.Message + "Finished cleaning. Deleted " + Color.Value + deleted + " users" + Color.Message + "."); return true; } private boolean handleBackend(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.backend", true)) { return true; } if (args.length == 1) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + pm.getBackEnd().getType().name() + Color.Text + " as backend"); } else if (args.length == 2) { String stype = args[1]; BackEndType type = BackEndType.getByName(stype); if (type == null) { sender.sendMessage(Color.Error + "Invalid backend type! " + Color.Value + BackEndType.YAML.name() + Color.Error + ", " + Color.Value + BackEndType.MySQL.name() + Color.Error + " or " + Color.Value + BackEndType.MySQL2.name() + Color.Error + " is required!"); return true; } if (type == pm.getBackEnd().getType()) { sender.sendMessage(Color.Error + "Invalid backend type! You can't migrate from " + Color.Value + pm.getBackEnd().getType().name() + Color.Error + " to " + Color.Value + type.name() + Color.Error + "!"); return true; } sender.sendMessage(Color.Text + "Migrating permissions to " + Color.Value + type.name() + Color.Text + " ..."); pm.migrateBackEnd(type); sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleMigrate(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.migrate", true)) { return true; } //minimal 2 args if (args.length < 2) { Messages.sendTooLessArgsMessage(sender); return true; } String migratetype = args[1]; if (migratetype.equalsIgnoreCase("backend")) { return handleMigrateBackend(sender, args); } else if (migratetype.equalsIgnoreCase("useuuid")) { return handleMigrateUseUUID(sender, args); } else if (migratetype.equalsIgnoreCase("uuidplayerdb")) { return handleMigrateUUIDPlayerDB(sender, args); } else { return false; } } private boolean handleMigrateBackend(CommandSender sender, String args[]) { if (args.length == 2) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + pm.getBackEnd().getType().name() + Color.Text + " as backend"); } else if (args.length == 3) { String stype = args[2]; BackEndType type = BackEndType.getByName(stype); if (type == null) { sender.sendMessage(Color.Error + "Invalid backend type! " + Color.Value + BackEndType.YAML.name() + Color.Error + ", " + Color.Value + BackEndType.MySQL.name() + Color.Error + " or " + Color.Value + BackEndType.MySQL2.name() + Color.Error + " is required!"); return true; } if (type == pm.getBackEnd().getType()) { sender.sendMessage(Color.Error + "Invalid backend type! You can't migrate to same type!"); return true; } sender.sendMessage(Color.Text + "Migrating permissions to " + Color.Value + type.name() + Color.Text + " ..."); pm.migrateBackEnd(type); sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleMigrateUseUUID(CommandSender sender, String args[]) { if (args.length == 2) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + (pm.isUseUUIDs() ? "UUIDs" : "player names") + Color.Text + " for player identification"); } else if (args.length == 3) { String stype = args[2]; Boolean type = null; try { type = parseTrueFalse(stype); } catch (Exception e) { } if (type == null) { sender.sendMessage(Color.Error + "Invalid use-uuid type! " + Color.Value + "true" + Color.Error + " or " + Color.Value + "false" + Color.Error + " is required!"); return true; } if (type == pm.isUseUUIDs()) { sender.sendMessage(Color.Error + "Invalid use-uuid type! You can't migrate to same type!"); return true; } if (type) { sender.sendMessage(Color.Text + "Migrating permissions using UUIDs for player identification ..."); //fetch uuids from mojang sender.sendMessage(Color.Text + "Fetching UUIDs ..."); UUIDFetcher fetcher = new UUIDFetcher(pm.getBackEnd().getRegisteredUsers(), fetchercooldown); fetcher.fetchUUIDs(); Map<String, UUID> uuids = fetcher.getUUIDs(); sender.sendMessage(Color.Message + "Finished fetching."); //migrate permissions backend sender.sendMessage(Color.Text + "Migrating player identification ..."); pm.migrateUseUUID(uuids); sender.sendMessage(Color.Message + "Finished player identification migration."); //add fetched uuids to uuidplayerdb sender.sendMessage(Color.Text + "Applying fetched data to player-uuid-database ..."); for (Map.Entry<String, UUID> e : uuids.entrySet()) { pm.getUUIDPlayerDB().update(e.getValue(), e.getKey()); } sender.sendMessage(Color.Message + "Finished applying of fetched data to player-uuid-database."); } else { sender.sendMessage(Color.Text + "Migrating permissions using player names for player identification ..."); //fetch playernames from mojang sender.sendMessage(Color.Text + "Fetching " + (type ? "UUIDs" : "player names") + " ..."); UUIDFetcher fetcher = new UUIDFetcher(pm.getBackEnd().getRegisteredUsers(), fetchercooldown); fetcher.fetchPlayerNames(); Map<UUID, String> playernames = fetcher.getPlayerNames(); sender.sendMessage(Color.Message + "Finished fetching."); //migrate permissions backend sender.sendMessage(Color.Text + "Migrating player identification ..."); pm.migrateUsePlayerNames(playernames); sender.sendMessage(Color.Message + "Finished player identification migration."); //add fetched playername to uuidplayerdb sender.sendMessage(Color.Text + "Applying fetched data to player-uuid-database ..."); for (Map.Entry<UUID, String> e : playernames.entrySet()) { pm.getUUIDPlayerDB().update(e.getKey(), e.getValue()); } sender.sendMessage(Color.Message + "Finished applying of fetched data to player-uuid-database."); } sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleMigrateUUIDPlayerDB(CommandSender sender, String args[]) { if (args.length == 2) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + pm.getUUIDPlayerDB().getType().name() + Color.Text + " as uuid player database"); } else if (args.length == 3) { String stype = args[2]; UUIDPlayerDBType type = UUIDPlayerDBType.getByName(stype); if (type == null) { sender.sendMessage(Color.Error + "Invalid backend type! " + Color.Value + UUIDPlayerDBType.None.name() + Color.Error + ", " + Color.Value + UUIDPlayerDBType.YAML.name() + Color.Error + " or " + Color.Value + UUIDPlayerDBType.MySQL.name() + Color.Error + " is required!"); return true; } if (type == pm.getUUIDPlayerDB().getType()) { sender.sendMessage(Color.Error + "Invalid uuid-player-database type! You can't migrate to same type!"); return true; } sender.sendMessage(Color.Text + "Migrating uuid-player-database to " + Color.Value + type.name() + Color.Text + " ..."); pm.migrateUUIDPlayerDB(type); sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleUUID(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.uuid", true)) { return true; } if (!Statics.matchArgs(sender, args, 2, 3)) { return true; } boolean reverse = false; boolean mojang = false; String what = args[1]; UUID uuidwhat = Statics.parseUUID(what); if (args.length > 2) { String params = args[2]; if (params.startsWith("-")) { reverse = params.contains("r"); mojang = params.contains("m"); } } if (reverse) { if (uuidwhat == null) { sender.sendMessage(Color.Error + "UUID invalid!"); return true; } } if (mojang && reverse) { String name = UUIDFetcher.getPlayerNameFromMojang(uuidwhat); if (name == null) { sender.sendMessage(Color.Text + "Mojang does not know this player."); } else { sender.sendMessage(Color.Text + "Mojang says: Player name of " + Color.Value + uuidwhat + Color.Text + " is " + Color.User + name + Color.Text + "."); } } else if (mojang && !reverse) { UUID uuid = UUIDFetcher.getUUIDFromMojang(what, null); if (uuid == null) { sender.sendMessage(Color.Text + "Mojang does not know this player."); } else { sender.sendMessage(Color.Text + "Mojang says: UUID of " + Color.User + what + Color.Text + " is " + Color.Value + uuid + Color.Text + "."); } } else if (!mojang && reverse) { String name = pm.getUUIDPlayerDB().getPlayerName(uuidwhat); if (name == null) { sender.sendMessage(Color.Text + "The UUID-player database does not know this player."); } else { sender.sendMessage(Color.Text + "The UUID-player database says: Player name of " + Color.Value + uuidwhat + Color.Text + " is " + Color.User + name + Color.Text + "."); } } else if (!mojang && !reverse) { UUID uuid = pm.getUUIDPlayerDB().getUUID(what); if (uuid == null) { sender.sendMessage(Color.Text + "The UUID-player database does not know this player."); } else { sender.sendMessage(Color.Text + "The UUID-player database says: UUID of " + Color.User + what + Color.Text + " is " + Color.Value + uuid + Color.Text + "."); } } return true; } private void showHelp(CommandSender sender) { sender.sendMessage(ChatColor.GOLD + " ------ BungeePerms - Help -----"); sender.sendMessage(ChatColor.GRAY + "Aliases: " + ChatColor.GOLD + "/bp"); sender.sendMessage(ChatColor.GOLD + "/bungeeperms" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Welcomes you to BungeePerms"); if (pm.hasPermOrConsole(sender, "bungeeperms.help")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms help" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows this help"); } if (pm.hasPermOrConsole(sender, "bungeeperms.reload")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms reload" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Reloads the permissions"); } if (pm.hasPermOrConsole(sender, "bungeeperms.users")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms users [-c]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the users [or shows the amount of them]"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.info")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> info" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows information to the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.delete")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> delete" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Deletes the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> addperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Adds a permission to the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> removeperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Remove a permission from the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.has")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> has <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Checks if the given user has the given permission"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.list")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> list" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the permissions of the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.group.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> addgroup <groupname>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Added the given group to the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.group.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> removegroup <groupname>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Removes the given group from the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.group.set")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> setgroup <groupname>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the given group as the main group for the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.groups")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> groups" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the groups the given user is in"); } if (pm.hasPermOrConsole(sender, "bungeeperms.groups")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms groups" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the groups"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.info")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> info" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows information about the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.users")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> users [-c]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the users of the given group [or shows the amount of them]"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.create")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> create" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Create a group with the given name"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.delete")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> delete" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Create the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.inheritances.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> addinherit <group>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Adds a inheritance to the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.inheritances.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> removeinherit <group>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Remove a inheritance from the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.rank")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> rank <new rank>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the rank for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.weight")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> weight <new weight>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the weight for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.ladder")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> ladder <new ladder>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the ladder for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.default")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> default <true|false>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Determines whether the given group is a default group or not"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.display")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> display [displayname> [server [world]]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the display name for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.prefix")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> prefix [prefix> [server [world]]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the prefix for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.suffix")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> suffix [suffix> [server [world]]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the suffix for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> addperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Adds a permission to the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> removeperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Remove a permission from the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.has")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> has <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Checks if the given group has the given permission"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.list")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> list" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the permissions of the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.promote")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms promote <username> [ladder]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Promotes the given user to the next rank"); } if (pm.hasPermOrConsole(sender, "bungeeperms.demote")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms demote <username> [ladder]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Demotes the given user to the previous rank"); } if (pm.hasPermOrConsole(sender, "bungeeperms.format")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms format" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Reformates the permission.yml or mysql table - " + ChatColor.RED + " BE CAREFUL"); } if (pm.hasPermOrConsole(sender, "bungeeperms.cleanup")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms cleanup" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Cleans up the permission.yml or mysql table - " + ChatColor.RED + " !BE VERY CAREFUL! - removes a lot of players from the permissions.yml if configured"); } if (pm.hasPermOrConsole(sender, "bungeeperms.backend")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms backend [yaml|mysql|mysql2]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows the used permissions database (file or mysql table) [or migrates to the given database] - " + ChatColor.RED + " !BE CAREFUL! (MAKE A BACKUP BEFORE EXECUTING)"); } if (pm.hasPermOrConsole(sender, "bungeeperms.migrate")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms migrate <backend [yaml|mysql|mysql2]|useuuid [true|false]|uuidplayerdb [None,YAML|MySQL]>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Does migrations of different data (permissions, uuid) or shows status - " + ChatColor.RED + " !BE CAREFUL! (MAKE A BACKUP BEFORE EXECUTING)"); } if (pm.hasPermOrConsole(sender, "bungeeperms.uuid")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms uuid <player|uuid> [-rm]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Gets the UUID of a player from database (-r: reverse; -m: ask mojang)"); } sender.sendMessage(ChatColor.GOLD + "---------------------------------------------------"); } private void loadcmds() { bc.getPluginManager().registerCommand(this, new Command("bungeeperms", null, "bp") { @Override public void execute(final CommandSender sender, final String[] args) { final Command cmd = this; BungeeCord.getInstance().getScheduler().runAsync(instance, new Runnable() { @Override public void run() { if (!BungeePerms.this.onCommand(sender, cmd, "", args)) { sender.sendMessage(Color.Error + "[BungeePerms] Command not found"); } } }); } }); } private boolean parseTrueFalse(String truefalse) { if (Statics.argAlias(truefalse, "true", "yes", "t", "y", "+")) { return true; } else if (Statics.argAlias(truefalse, "false", "no", "f", "n", "-")) { return false; } throw new IllegalArgumentException("truefalse does not represent a boolean value"); } public PermissionsManager getPermissionsManager() { return pm; } }
src/main/java/net/alpenblock/bungeeperms/BungeePerms.java
package net.alpenblock.bungeeperms; import java.io.File; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import net.alpenblock.bungeeperms.config.YamlConfiguration; import net.alpenblock.bungeeperms.io.BackEndType; import net.alpenblock.bungeeperms.io.UUIDPlayerDBType; import net.alpenblock.bungeeperms.uuid.UUIDFetcher; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Plugin; public class BungeePerms extends Plugin implements Listener { private static BungeePerms instance; public static BungeePerms getInstance() { return instance; } private BungeeCord bc; private Config config; private Debug debug; private PermissionsManager pm; private int fetchercooldown; private boolean tabcomplete; private boolean notifypromote; private boolean notifydemote; private Listener tablistener; @Override public void onLoad() { //static instance = this; bc = BungeeCord.getInstance(); //check for config file existance File f = new File(getDataFolder(), "/config.yml"); if (!f.exists() | !f.isFile()) { bc.getLogger().info("[BungeePerms] no config file found -> copy packed default config.yml to data folder ..."); f.getParentFile().mkdirs(); try { //file ffnen ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("config.yml"); if (url != null) { URLConnection connection = url.openConnection(); connection.setUseCaches(false); YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(connection.getInputStream()); defConfig.save(f); } } catch (Exception e) { e.printStackTrace(); } bc.getLogger().info("[BungeePerms] copied default config.yml to data folder"); } config = new Config(this, "/config.yml"); config.load(); loadConfig(); debug = new Debug(this, config, "BP"); //load commands loadcmds(); pm = new PermissionsManager(this, config, debug); } private void loadConfig() { fetchercooldown = config.getInt("uuidfetcher.cooldown", 3000); tabcomplete = config.getBoolean("tabcomplete", false); notifypromote = config.getBoolean("notify.promote", false); notifydemote = config.getBoolean("notify.demote", false); } @Override public void onEnable() { bc.getLogger().info("Activating BungeePerms ..."); pm.enable(); if (tabcomplete) { tablistener = new TabListener(); BungeeCord.getInstance().getPluginManager().registerListener(this, tablistener); } } @Override public void onDisable() { bc.getLogger().info("Deactivating BungeePerms ..."); pm.disable(); if (tabcomplete) { BungeeCord.getInstance().getPluginManager().registerListener(this, tablistener); } } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!cmd.getName().equalsIgnoreCase("bungeeperms")) { return false; } if (args.length == 0) { sender.sendMessage(ChatColor.GOLD + "Welcome to BungeePerms, a BungeeCord permissions plugin"); sender.sendMessage(Color.Text + "Version " + ChatColor.GOLD + this.getDescription().getVersion()); sender.sendMessage(Color.Text + "Author " + ChatColor.GOLD + this.getDescription().getAuthor()); return true; } else if (args.length > 0) { if (args[0].equalsIgnoreCase("help")) { return handleHelp(sender, args); } else if (args[0].equalsIgnoreCase("reload")) { return handleReload(sender, args); } else if (args[0].equalsIgnoreCase("users")) { return handleUsers(sender, args); } else if (args[0].equalsIgnoreCase("user")) { return handleUserCommands(sender, args); } else if (args[0].equalsIgnoreCase("groups")) { return handleGroups(sender, args); } else if (args[0].equalsIgnoreCase("group")) { return handleGroupCommands(sender, args); } else if (args[0].equalsIgnoreCase("promote")) { return handlePromote(sender, args); } else if (args[0].equalsIgnoreCase("demote")) { return handleDemote(sender, args); } else if (args[0].equalsIgnoreCase("format")) { return handleFormat(sender, args); } else if (args[0].equalsIgnoreCase("cleanup")) { return handleCleanup(sender, args); } else if (args[0].equalsIgnoreCase("backend")) { return handleBackend(sender, args); //todo: remove this } else if (args[0].equalsIgnoreCase("migrate")) { return handleMigrate(sender, args); } else if (args[0].equalsIgnoreCase("uuid")) { return handleUUID(sender, args); } } return false; } private boolean handleHelp(CommandSender sender, String args[]) { //todo: better help output with pages if (pm.hasOrConsole(sender, "bungeeperms.help", true)) { showHelp(sender); return true; } return true; } private boolean handleReload(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.reload", true)) { return true; } pm.loadConfig(); pm.loadPerms(); pm.sendPMAll("reloadall"); sender.sendMessage(Color.Text + "Permissions reloaded"); return true; } private boolean handleUsers(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.users.list", true)) { return true; } if (args.length == 1) { List<String> users = pm.getRegisteredUsers(); if (users.isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { String out = Color.Text + "Following players are registered: "; for (int i = 0; i < users.size(); i++) { out += Color.User + users.get(i) + Color.Text + (i + 1 < users.size() ? ", " : ""); } sender.sendMessage(out); } return true; } else if (args.length == 2) { //for counting if (!args[1].equalsIgnoreCase("-c")) { return false; } if (pm.getRegisteredUsers().isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { sender.sendMessage(Color.Text + "There are " + Color.Value + pm.getRegisteredUsers().size() + Color.Text + " players registered."); } return true; } else { Messages.sendTooManyArgsMessage(sender); return true; } } private boolean handleUserCommands(CommandSender sender, String args[]) { if (args.length < 3) { Messages.sendTooLessArgsMessage(sender); return true; } if (args[2].equalsIgnoreCase("list")) { return handleUserCommandsList(sender, args); } else if (args[2].equalsIgnoreCase("groups")) { return handleUserCommandsGroups(sender, args); } else if (args[2].equalsIgnoreCase("info")) { return handleUserCommandsInfo(sender, args); } else if (args[2].equalsIgnoreCase("delete")) { return handleUserCommandsDelete(sender, args); } else if (Statics.argAlias(args[2], "add", "addperm", "addpermission")) { return handleUserCommandsPermAdd(sender, args); } else if (Statics.argAlias(args[2], "remove", "removeperm", "removepermission")) { return handleUserCommandsPermRemove(sender, args); } else if (args[2].equalsIgnoreCase("has")) { return handleUserCommandsHas(sender, args); } else if (args[2].equalsIgnoreCase("addgroup")) { return handleUserCommandsGroupAdd(sender, args); } else if (args[2].equalsIgnoreCase("removegroup")) { return handleUserCommandsGroupRemove(sender, args); } else if (args[2].equalsIgnoreCase("setgroup")) { return handleUserCommandsGroupSet(sender, args); } return false; } //user commands private boolean handleUserCommandsList(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.list", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 5)) { return true; } String player = Statics.getFullPlayerName(args[1]); String server = args.length > 3 ? args[3].toLowerCase() : null; String world = args.length > 4 ? args[4].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Permissions of the player " + Color.User + user.getName() + Color.Text + " (" + Color.User + user.getUUID() + Color.Text + "):"); List<BPPermission> perms = user.getPermsWithOrigin(server, world); for (BPPermission perm : perms) { sender.sendMessage(Color.Text + "- " + Color.Value + perm.getPermission() + Color.Text + " (" + Color.Value + (!perm.isGroup() && perm.getOrigin().equalsIgnoreCase(player) ? "own" : perm.getOrigin()) + Color.Text + (perm.getServer() != null ? " | " + Color.Value + perm.getServer() + Color.Text : "") + (perm.getWorld() != null ? " | " + Color.Value + perm.getWorld() + Color.Text : "") + ")"); } return true; } private boolean handleUserCommandsGroups(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.groups", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Groups of the player " + Color.User + user.getName() + Color.Text + ":"); for (Group g : user.getGroups()) { sender.sendMessage(Color.Text + "- " + Color.Value + g.getName()); } return true; } private boolean handleUserCommandsInfo(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.info", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "About " + Color.User + user.getName()); sender.sendMessage(Color.Text + "UUID: " + Color.Value + user.getUUID()); String groups = ""; for (int i = 0; i < user.getGroups().size(); i++) { groups += Color.Value + user.getGroups().get(i).getName() + Color.Text + " (" + Color.Value + user.getGroups().get(i).getPerms().size() + Color.Text + ")" + (i + 1 < user.getGroups().size() ? ", " : ""); } sender.sendMessage(Color.Text + "Groups: " + groups); //all group perms sender.sendMessage(Color.Text + "Effective permissions: " + Color.Value + user.getEffectivePerms().size());//TODO return true; } private boolean handleUserCommandsDelete(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.delete", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } pm.deleteUser(user); sender.sendMessage(Color.Text + "User deleted"); return true; } private boolean handleUserCommandsPermAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String player = Statics.getFullPlayerName(args[1]); String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } if (server == null) { if (user.getExtraperms().contains("-" + perm)) { pm.removeUserPerm(user, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + "."); } else if (!user.getExtraperms().contains(perm)) { pm.addUserPerm(user, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + "."); } } else { if (world == null) { List<String> perserverperms = user.getServerPerms().get(server); if (perserverperms == null) { perserverperms = new ArrayList<>(); user.getServerPerms().put(server, perserverperms); } if (perserverperms.contains("-" + perm)) { pm.removeUserPerServerPerm(user, server, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains(perm)) { pm.addUserPerServerPerm(user, server, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " alreday has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } else { Map<String, List<String>> perserverperms = user.getServerWorldPerms().get(server); if (perserverperms == null) { perserverperms = new HashMap<>(); user.getServerWorldPerms().put(server, perserverperms); } List<String> perserverworldperms = perserverperms.get(world); if (perserverworldperms == null) { perserverworldperms = new ArrayList<>(); perserverperms.put(world, perserverworldperms); } if (perserverworldperms.contains("-" + perm)) { pm.removeUserPerServerWorldPerm(user, server, world, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains(perm)) { pm.addUserPerServerWorldPerm(user, server, world, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " alreday has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleUserCommandsPermRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String player = Statics.getFullPlayerName(args[1]); String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } if (server == null) { if (user.getExtraperms().contains(perm)) { pm.removeUserPerm(user, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + "."); } else if (!user.getExtraperms().contains("-" + perm)) { pm.addUserPerm(user, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + "."); } } else { if (world == null) { List<String> perserverperms = user.getServerPerms().get(server); if (perserverperms == null) { perserverperms = new ArrayList<>(); user.getServerPerms().put(server, perserverperms); } if (perserverperms.contains(perm)) { pm.removeUserPerServerPerm(user, server, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains("-" + perm)) { pm.addUserPerServerPerm(user, server, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } else { Map<String, List<String>> perserverperms = user.getServerWorldPerms().get(server); if (perserverperms == null) { perserverperms = new HashMap<>(); user.getServerWorldPerms().put(server, perserverperms); } List<String> perserverworldperms = perserverperms.get(world); if (perserverworldperms == null) { perserverworldperms = new ArrayList<>(); perserverperms.put(world, perserverworldperms); } if (perserverworldperms.contains(perm)) { pm.removeUserPerServerWorldPerm(user, server, world, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains("-" + perm)) { pm.addUserPerServerWorldPerm(user, server, world, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from player " + Color.User + user.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The player " + Color.Value + user.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleUserCommandsHas(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.perms.has", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String player = Statics.getFullPlayerName(args[1]); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } if (server == null) { boolean has = pm.hasPerm(player, args[3].toLowerCase()); sender.sendMessage(Color.Text + "Player " + Color.User + user.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } else { if (world == null) { boolean has = pm.hasPermOnServer(user.getName(), args[3].toLowerCase(), server); sender.sendMessage(Color.Text + "Player " + Color.User + user.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } else { boolean has = pm.hasPermOnServerInWorld(user.getName(), args[3].toLowerCase(), server, world); sender.sendMessage(Color.Text + "Player " + Color.User + user.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } } return true; } private boolean handleUserCommandsGroupAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.group.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String player = Statics.getFullPlayerName(args[1]); String groupname = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.User + groupname + Color.Error + " does not exist!"); return true; } User u = pm.getUser(player); if (u == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } List<Group> groups = u.getGroups(); for (Group g : groups) { if (g.getName().equalsIgnoreCase(group.getName())) { sender.sendMessage(Color.Error + "Player is already in group " + Color.Value + groupname + Color.Error + "!"); return true; } } pm.addUserGroup(u, group); sender.sendMessage(Color.Text + "Added group " + Color.Value + groupname + Color.Text + " to player " + Color.User + u.getName() + Color.Text + "."); return true; } private boolean handleUserCommandsGroupRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.group.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String player = Statics.getFullPlayerName(args[1]); String groupname = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.User + groupname + Color.Error + " does not exist!"); return true; } User u = pm.getUser(player); if (u == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } List<Group> groups = u.getGroups(); for (Group g : groups) { if (g.getName().equalsIgnoreCase(group.getName())) { pm.removeUserGroup(u, group); sender.sendMessage(Color.Text + "Removed group " + Color.Value + groupname + Color.Text + " from player " + Color.User + u.getName() + Color.Text + "."); return true; } } sender.sendMessage(Color.Error + "Player is not in group " + Color.Value + groupname + Color.Error + "!"); return true; } private boolean handleUserCommandsGroupSet(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.user.group.set", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String player = Statics.getFullPlayerName(args[1]); String groupname = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.User + groupname + Color.Error + " does not exist!"); return true; } User u = pm.getUser(player); if (u == null) { sender.sendMessage(Color.Error + "The player " + Color.User + player + Color.Error + " does not exist!"); return true; } List<Group> laddergroups = pm.getLadderGroups(group.getLadder()); for (Group g : laddergroups) { pm.removeUserGroup(u, g); } pm.addUserGroup(u, group); sender.sendMessage(Color.Text + "Set group " + Color.Value + groupname + Color.Text + " for player " + Color.User + u.getName() + Color.Text + "."); return true; } //end user commands private boolean handleGroups(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.groups", true)) { return true; } if (!Statics.matchArgs(sender, args, 1)) { return true; } if (pm.getGroups().isEmpty()) { sender.sendMessage(Color.Text + "No groups found!"); } else { sender.sendMessage(Color.Text + "There are following groups:"); for (String l : pm.getLadders()) { for (Group g : pm.getLadderGroups(l)) { sender.sendMessage(Color.Text + "- " + Color.Value + g.getName() + Color.Text + " (" + Color.Value + l + Color.Text + ")"); } } } return true; } private boolean handleGroupCommands(CommandSender sender, String args[]) { if (args.length < 3) { Messages.sendTooLessArgsMessage(sender); return true; } if (args[2].equalsIgnoreCase("list")) { return handleGroupCommandsList(sender, args); } else if (args[2].equalsIgnoreCase("info")) { return handleGroupCommandsInfo(sender, args); } else if (args[2].equalsIgnoreCase("users")) { return handleGroupCommandsUsers(sender, args); } else if (args[2].equalsIgnoreCase("create")) { return handleGroupCommandsCreate(sender, args); } else if (args[2].equalsIgnoreCase("delete")) { return handleGroupCommandsDelete(sender, args); } else if (Statics.argAlias(args[2], "add", "addperm", "addpermission")) { return handleGroupCommandsPermAdd(sender, args); } else if (Statics.argAlias(args[2], "remove", "removeperm", "removepermission")) { return handleGroupCommandsPermRemove(sender, args); } else if (Statics.argAlias(args[2], "has", "check")) { return handleGroupCommandsHas(sender, args); } else if (Statics.argAlias(args[2], "addinherit", "addinheritance")) { return handleGroupCommandsInheritAdd(sender, args); } else if (Statics.argAlias(args[2], "removeinherit", "removeinheritance")) { return handleGroupCommandsInheritRemove(sender, args); } else if (args[2].equalsIgnoreCase("rank")) { return handleGroupCommandsRank(sender, args); } else if (args[2].equalsIgnoreCase("weight")) { return handleGroupCommandsWeight(sender, args); } else if (args[2].equalsIgnoreCase("ladder")) { return handleGroupCommandsLadder(sender, args); } else if (args[2].equalsIgnoreCase("default")) { return handleGroupCommandsDefault(sender, args); } else if (args[2].equalsIgnoreCase("display")) { return handleGroupCommandsDisplay(sender, args); } else if (args[2].equalsIgnoreCase("prefix")) { return handleGroupCommandsPrefix(sender, args); } else if (args[2].equalsIgnoreCase("suffix")) { return handleGroupCommandsSuffix(sender, args); } return false; } //group commands private boolean handleGroupCommandsList(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.list", true)) { return true; } if (args.length > 5) { Messages.sendTooManyArgsMessage(sender); return true; } String groupname = args[1]; String server = args.length > 3 ? args[3] : null; String world = args.length > 4 ? args[4] : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Permissions of the group " + Color.Value + group.getName() + Color.Text + ":"); List<BPPermission> perms = group.getPermsWithOrigin(server, world); for (BPPermission perm : perms) { sender.sendMessage(Color.Text + "- " + Color.Value + perm.getPermission() + Color.Text + " (" + Color.Value + (perm.getOrigin().equalsIgnoreCase(groupname) ? "own" : perm.getOrigin()) + Color.Text + (perm.getServer() != null ? " | " + Color.Value + perm.getServer() + Color.Text : "") + (perm.getWorld() != null ? " | " + Color.Value + perm.getWorld() + Color.Text : "") + ")"); } return true; } private boolean handleGroupCommandsInfo(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.info", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String groupname = args[1]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } sender.sendMessage(Color.Text + "Info to group " + Color.Value + group.getName() + Color.Text + ":"); //inheritances String inheritances = ""; for (int i = 0; i < group.getInheritances().size(); i++) { inheritances += Color.Value + group.getInheritances().get(i) + Color.Text + " (" + Color.Value + pm.getGroup(group.getInheritances().get(i)).getPerms().size() + Color.Text + ")" + (i + 1 < group.getInheritances().size() ? ", " : ""); } if (inheritances.length() == 0) { inheritances = Color.Text + "(none)"; } sender.sendMessage(Color.Text + "Inheritances: " + inheritances); //group perms sender.sendMessage(Color.Text + "Group permissions: " + Color.Value + group.getPerms().size()); //group rank sender.sendMessage(Color.Text + "Rank: " + Color.Value + group.getRank()); //group weight sender.sendMessage(Color.Text + "Weight: " + Color.Value + group.getWeight()); //group ladder sender.sendMessage(Color.Text + "Ladder: " + Color.Value + group.getLadder()); //default sender.sendMessage(Color.Text + "Default: " + Color.Value + (group.isDefault() ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(group.isDefault()).toUpperCase()); //all group perms sender.sendMessage(Color.Text + "Effective permissions: " + Color.Value + group.getEffectivePerms().size()); //display sender.sendMessage(Color.Text + "Dislay name: " + ChatColor.RESET + (group.getDisplay().length() > 0 ? group.getDisplay() : Color.Text + "(none)")); //prefix sender.sendMessage(Color.Text + "Prefix: " + ChatColor.RESET + (group.getPrefix().length() > 0 ? group.getPrefix() : Color.Text + "(none)")); //suffix sender.sendMessage(Color.Text + "Suffix: " + ChatColor.RESET + (group.getSuffix().length() > 0 ? group.getSuffix() : Color.Text + "(none)")); return true; } private boolean handleGroupCommandsUsers(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.users", true)) { return true; } if (args.length > 4) { Messages.sendTooManyArgsMessage(sender); return true; } String groupname = args[1]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " doesn't exists!"); return true; } List<String> users = pm.getGroupUsers(group); if (args.length == 3) { if (users.isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { String out = Color.Text + "Following players are in group " + Color.Value + group.getName() + Color.Text + ": "; for (int i = 0; i < users.size(); i++) { out += Color.User + users.get(i) + Color.Text + (i + 1 < users.size() ? ", " : ""); } sender.sendMessage(out); } return true; } else if (args.length == 4) { if (!args[3].equalsIgnoreCase("-c")) { return false; } if (users.isEmpty()) { sender.sendMessage(Color.Text + "No players found!"); } else { sender.sendMessage(Color.Text + "There are " + Color.Value + users.size() + Color.Text + " players in group " + Color.Value + group.getName() + Color.Text + "."); } return true; } return true; } private boolean handleGroupCommandsCreate(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.create", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String groupname = args[1]; if (pm.getGroup(groupname) != null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " already exists!"); return true; } Group group = new Group(groupname, new ArrayList<String>(), new ArrayList<String>(), new HashMap<String, Server>(), 1500, 1500, "default", false, "", "", ""); pm.addGroup(group); sender.sendMessage(Color.Text + "Group " + Color.Value + groupname + Color.Text + " created."); return true; } private boolean handleGroupCommandsDelete(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.delete", true)) { return true; } if (!Statics.matchArgs(sender, args, 3)) { return true; } String groupname = args[1]; Group group = pm.getGroup(groupname); if (group != null) { sender.sendMessage(Color.Text + "Group deletion in progress ... this may take a while (backend integrity check)."); pm.deleteGroup(group); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " deleted."); } else { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); } return true; } private boolean handleGroupCommandsPermAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String groupname = args[1]; String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } //global perm if (server == null) { if (group.getPerms().contains("-" + perm)) { pm.removeGroupPerm(group, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + "."); } else if (!group.getPerms().contains(perm)) { pm.addGroupPerm(group, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + "."); } } else { Server srv = group.getServers().get(server); if (srv == null) { srv = new Server(server, new ArrayList<String>(), new HashMap<String, World>(), "", "", ""); group.getServers().put(server, srv); } //per server perm if (world == null) { List<String> perserverperms = srv.getPerms(); if (perserverperms.contains("-" + perm)) { pm.removeGroupPerServerPerm(group, server, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains(perm)) { pm.addGroupPerServerPerm(group, server, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } //per server world perms else { World w = srv.getWorlds().get(world); if (w == null) { w = new World(world, new ArrayList<String>(), "", "", ""); srv.getWorlds().put(world, w); } List<String> perserverworldperms = w.getPerms(); if (perserverworldperms.contains("-" + perm)) { pm.removeGroupPerServerWorldPerm(group, server, world, "-" + perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains(perm)) { pm.addGroupPerServerWorldPerm(group, server, world, perm); sender.sendMessage(Color.Text + "Added permission " + Color.Value + perm + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " already has the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleGroupCommandsPermRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String groupname = args[1]; String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } //global perm if (server == null) { if (group.getPerms().contains(perm)) { pm.removeGroupPerm(group, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + "."); } else if (!group.getPerms().contains("-" + perm)) { pm.addGroupPerm(group, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + "."); } } else { Server srv = group.getServers().get(server); if (srv == null) { srv = new Server(server, new ArrayList<String>(), new HashMap<String, World>(), "", "", ""); group.getServers().put(server, srv); } //per server perm if (world == null) { List<String> perserverperms = srv.getPerms(); if (perserverperms.contains(perm)) { pm.removeGroupPerServerPerm(group, server, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else if (!perserverperms.contains("-" + perm)) { pm.addGroupPerServerPerm(group, server, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + "."); } } else { World w = srv.getWorlds().get(world); if (w == null) { w = new World(world, new ArrayList<String>(), "", "", ""); srv.getWorlds().put(world, w); } List<String> perserverworldperms = w.getPerms(); if (perserverworldperms.contains(perm)) { pm.removeGroupPerServerWorldPerm(group, server, world, perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else if (!perserverworldperms.contains("-" + perm)) { pm.addGroupPerServerWorldPerm(group, server, world, "-" + perm); sender.sendMessage(Color.Text + "Removed permission " + Color.Value + perm + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } else { sender.sendMessage(Color.Text + "The group " + Color.Value + group.getName() + Color.Text + " never had the permission " + Color.Value + perm + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + "."); } } } return true; } private boolean handleGroupCommandsHas(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.perms.has", true)) { return true; } if (!Statics.matchArgs(sender, args, 4, 6)) { return true; } String groupname = args[1]; String perm = args[3].toLowerCase(); String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } //global perm if (server == null) { boolean has = group.has(perm.toLowerCase()); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } else { //per server perm if (world == null) { boolean has = group.hasOnServer(perm.toLowerCase(), server); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } //per server world perm else { boolean has = group.hasOnServerInWorld(perm.toLowerCase(), server, world); sender.sendMessage(Color.Text + "Group " + Color.Value + group.getName() + Color.Text + " has the permission " + Color.Value + args[3] + Color.Text + " on server " + Color.Value + server + Color.Text + " in world " + Color.Value + world + Color.Text + ": " + (has ? ChatColor.GREEN : ChatColor.RED) + String.valueOf(has).toUpperCase()); } } return true; } private boolean handleGroupCommandsInheritAdd(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.inheritances.add", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; String addgroup = args[3]; //check group existance Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } Group toadd = pm.getGroup(addgroup); if (toadd == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + addgroup + Color.Error + " does not exist!"); return true; } List<String> inheritances = group.getInheritances(); //check for already existing inheritance for (String s : inheritances) { if (s.equalsIgnoreCase(toadd.getName())) { sender.sendMessage(Color.Error + "The group already inherits from " + Color.Value + addgroup + Color.Error + "!"); return true; } } pm.addGroupInheritance(group, toadd); sender.sendMessage(Color.Text + "Added inheritance " + Color.Value + addgroup + Color.Text + " to group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsInheritRemove(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.inheritances.remove", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; String removegroup = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } Group toremove = pm.getGroup(removegroup); if (toremove == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + removegroup + Color.Error + " does not exist!"); return true; } List<String> inheritances = group.getInheritances(); for (String s : inheritances) { if (s.equalsIgnoreCase(toremove.getName())) { pm.removeGroupInheritance(group, toremove); sender.sendMessage(Color.Text + "Removed inheritance " + Color.Value + removegroup + Color.Text + " from group " + Color.Value + group.getName() + Color.Text + "."); return true; } } sender.sendMessage(Color.Error + "The group " + Color.Value + group.getName() + Color.Error + " does not inherit from group " + Color.Value + removegroup + Color.Error + "!"); return true; } private boolean handleGroupCommandsRank(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.rank", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; int rank; try { rank = Integer.parseInt(args[3]); if (rank < 1) { throw new Exception(); } } catch (Exception e) { sender.sendMessage(Color.Error + "A whole number greater than 0 is required!"); return true; } Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.rankGroup(group, rank); sender.sendMessage(Color.Text + "Group rank set for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsWeight(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.weight", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; int weight; try { weight = Integer.parseInt(args[3]); if (weight < 1) { throw new Exception(); } } catch (Exception e) { sender.sendMessage(Color.Error + "A whole number greater than 0 is required!"); return true; } Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.weightGroup(group, weight); sender.sendMessage(Color.Text + "Group weight set for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsLadder(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.ladder", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; String ladder = args[3]; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.ladderGroup(group, ladder); sender.sendMessage(Color.Text + "Group ladder set for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsDefault(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.default", true)) { return true; } if (!Statics.matchArgs(sender, args, 4)) { return true; } String groupname = args[1]; boolean isdefault; try { isdefault = parseTrueFalse(args[3]); } catch (Exception e) { sender.sendMessage(Color.Error + "A form of '" + Color.Value + "true" + Color.Error + "','" + Color.Value + "false" + Color.Error + "','" + Color.Value + "yes" + Color.Error + "' or '" + Color.Value + "no" + Color.Error + "' is required!"); return true; } Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupDefault(group, isdefault); sender.sendMessage(Color.Text + "Marked group " + Color.Value + group.getName() + Color.Text + " as " + (isdefault ? "" : "non-") + "default."); return true; } private boolean handleGroupCommandsDisplay(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.display", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 6)) { return true; } String groupname = args[1]; String display = args.length > 3 ? args[3] : ""; String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupDisplay(group, display, server, world); sender.sendMessage(Color.Text + "Set display name for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsPrefix(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.prefix", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 6)) { return true; } String groupname = args[1]; String prefix = args.length > 3 ? args[3] : ""; String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupPrefix(group, prefix, server, world); sender.sendMessage(Color.Text + "Set prefix for group " + Color.Value + group.getName() + Color.Text + "."); return true; } private boolean handleGroupCommandsSuffix(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.group.suffix", true)) { return true; } if (!Statics.matchArgs(sender, args, 3, 6)) { return true; } String groupname = args[1]; String suffix = args.length > 3 ? args[3] : ""; String server = args.length > 4 ? args[4].toLowerCase() : null; String world = args.length > 5 ? args[5].toLowerCase() : null; Group group = pm.getGroup(groupname); if (group == null) { sender.sendMessage(Color.Error + "The group " + Color.Value + groupname + Color.Error + " does not exist!"); return true; } pm.setGroupSuffix(group, suffix, server, world); sender.sendMessage(Color.Text + "Set suffix for group " + Color.Value + group.getName() + Color.Text + "."); return true; } //end group commands private boolean handlePromote(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.promote", true)) { return true; } //2 or 3 args expected if (!Statics.matchArgs(sender, args, 2, 3)) { return true; } //get user String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + args[1] + Color.Error + " does not exist!"); return true; } //get next group by ladder Group playergroup = null; Group nextgroup = null; //ladder specified by sender if (args.length == 3) { String ladder = args[2]; playergroup = user.getGroupByLadder(ladder); if (playergroup != null) { nextgroup = pm.getNextGroup(playergroup); } else { List<Group> laddergroups = pm.getLadderGroups(ladder); if (!laddergroups.isEmpty()) { nextgroup = laddergroups.get(0); } } } //no ladder specified ... assume main ladder else { playergroup = pm.getMainGroup(user); if (playergroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " doesn't have a group!"); return true; } nextgroup = pm.getNextGroup(playergroup); } if (nextgroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " can't be promoted!"); return true; } //check permissions if (!pm.hasOrConsole(sender, "bungeeperms.promote." + nextgroup.getName(), true)) { return true; } //permission checks if sender is a player if (sender instanceof ProxiedPlayer) { User issuer = pm.getUser(sender.getName()); if (issuer == null) { sender.sendMessage(Color.Error + "You do not exist!"); return true; } Group issuergroup = pm.getMainGroup(issuer); if (issuergroup == null) { sender.sendMessage(Color.Error + "You don't have a group!"); return true; } if (!(issuergroup.getRank() < nextgroup.getRank())) { sender.sendMessage(Color.Error + "You can't promote the player " + Color.User + user.getName() + Color.Error + "!"); return true; } } //promote player //remove old group if neccessary if (playergroup != null) { pm.removeUserGroup(user, playergroup); } pm.addUserGroup(user, nextgroup); sender.sendMessage(Color.User + user.getName() + Color.Text + " is now " + Color.Value + nextgroup.getName() + Color.Text + "!"); //promote msg to user if(notifypromote) { ProxiedPlayer pp = bc.getPlayer(user.getName()); if(pp != null) { pp.sendMessage(Color.Text + "You were promoted to " + Color.Value + nextgroup.getName() + Color.Text + "!"); } } return true; } private boolean handleDemote(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.demote", true)) { return true; } //2 or 3 args expected if (!Statics.matchArgs(sender, args, 2, 3)) { return true; } //get user String player = Statics.getFullPlayerName(args[1]); User user = pm.getUser(player); if (user == null) { sender.sendMessage(Color.Error + "The player " + Color.User + args[1] + Color.Error + " does not exist!"); return true; } //get previous by ladder Group playergroup = null; Group previousgroup = null; //ladder specified by sender if (args.length == 3) { String ladder = args[2]; playergroup = user.getGroupByLadder(ladder); if (playergroup != null) { previousgroup = pm.getPreviousGroup(playergroup); } } //no ladder specified ... assume main ladder else { playergroup = pm.getMainGroup(user); if (playergroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " doesn't have a group!"); return true; } previousgroup = pm.getPreviousGroup(playergroup); } if (previousgroup == null) { sender.sendMessage(Color.Error + "The player " + Color.User + user.getName() + Color.Error + " can't be demoted!"); return true; } //check permissions if (!pm.hasOrConsole(sender, "bungeeperms.demote." + previousgroup.getName(), true)) { return true; } //permision checks if sender is a player if (sender instanceof ProxiedPlayer) { User issuer = pm.getUser(sender.getName()); if (issuer == null) { sender.sendMessage(Color.Error + "You do not exist!"); return true; } Group issuergroup = pm.getMainGroup(issuer); if (issuergroup == null) { sender.sendMessage(Color.Error + "You don't have a group!"); return true; } if (!(issuergroup.getRank() < playergroup.getRank())) { sender.sendMessage(Color.Error + "You can't demote the player " + Color.User + user.getName() + Color.Error + "!"); return true; } } //demote //remove old group if neccessary if (playergroup != null) { pm.removeUserGroup(user, playergroup); } pm.addUserGroup(user, previousgroup); sender.sendMessage(Color.User + user.getName() + Color.Text + " is now " + Color.Value + previousgroup.getName() + Color.Text + "!"); //demote msg to user if(notifydemote) { ProxiedPlayer pp = bc.getPlayer(user.getName()); if(pp != null) { pp.sendMessage(Color.Text + "You were demoted to " + Color.Value + previousgroup.getName() + Color.Text + "!"); } } return true; } private boolean handleFormat(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.format", true)) { return true; } sender.sendMessage(Color.Text + "Formating permissions file/table ..."); pm.format(); sender.sendMessage(Color.Message + "Finished formating."); return true; } private boolean handleCleanup(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.cleanup", true)) { return true; } sender.sendMessage(Color.Text + "Cleaning up permissions file/table ..."); int deleted = pm.cleanup(); sender.sendMessage(Color.Message + "Finished cleaning. Deleted " + Color.Value + deleted + " users" + Color.Message + "."); return true; } private boolean handleBackend(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.backend", true)) { return true; } if (args.length == 1) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + pm.getBackEnd().getType().name() + Color.Text + " as backend"); } else if (args.length == 2) { String stype = args[1]; BackEndType type = BackEndType.getByName(stype); if (type == null) { sender.sendMessage(Color.Error + "Invalid backend type! " + Color.Value + BackEndType.YAML.name() + Color.Error + ", " + Color.Value + BackEndType.MySQL.name() + Color.Error + " or " + Color.Value + BackEndType.MySQL2.name() + Color.Error + " is required!"); return true; } if (type == pm.getBackEnd().getType()) { sender.sendMessage(Color.Error + "Invalid backend type! You can't migrate from " + Color.Value + pm.getBackEnd().getType().name() + Color.Error + " to " + Color.Value + type.name() + Color.Error + "!"); return true; } sender.sendMessage(Color.Text + "Migrating permissions to " + Color.Value + type.name() + Color.Text + " ..."); pm.migrateBackEnd(type); sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleMigrate(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.migrate", true)) { return true; } //minimal 2 args if (args.length < 2) { Messages.sendTooLessArgsMessage(sender); return true; } String migratetype = args[1]; if (migratetype.equalsIgnoreCase("backend")) { return handleMigrateBackend(sender, args); } else if (migratetype.equalsIgnoreCase("useuuid")) { return handleMigrateUseUUID(sender, args); } else if (migratetype.equalsIgnoreCase("uuidplayerdb")) { return handleMigrateUUIDPlayerDB(sender, args); } else { return false; } } private boolean handleMigrateBackend(CommandSender sender, String args[]) { if (args.length == 2) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + pm.getBackEnd().getType().name() + Color.Text + " as backend"); } else if (args.length == 3) { String stype = args[2]; BackEndType type = BackEndType.getByName(stype); if (type == null) { sender.sendMessage(Color.Error + "Invalid backend type! " + Color.Value + BackEndType.YAML.name() + Color.Error + ", " + Color.Value + BackEndType.MySQL.name() + Color.Error + " or " + Color.Value + BackEndType.MySQL2.name() + Color.Error + " is required!"); return true; } if (type == pm.getBackEnd().getType()) { sender.sendMessage(Color.Error + "Invalid backend type! You can't migrate to same type!"); return true; } sender.sendMessage(Color.Text + "Migrating permissions to " + Color.Value + type.name() + Color.Text + " ..."); pm.migrateBackEnd(type); sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleMigrateUseUUID(CommandSender sender, String args[]) { if (args.length == 2) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + (pm.isUseUUIDs() ? "UUIDs" : "player names") + Color.Text + " for player identification"); } else if (args.length == 3) { String stype = args[2]; Boolean type = null; try { type = parseTrueFalse(stype); } catch (Exception e) { } if (type == null) { sender.sendMessage(Color.Error + "Invalid use-uuid type! " + Color.Value + "true" + Color.Error + " or " + Color.Value + "false" + Color.Error + " is required!"); return true; } if (type == pm.isUseUUIDs()) { sender.sendMessage(Color.Error + "Invalid use-uuid type! You can't migrate to same type!"); return true; } if (type) { sender.sendMessage(Color.Text + "Migrating permissions using UUIDs for player identification ..."); //fetch uuids from mojang sender.sendMessage(Color.Text + "Fetching UUIDs ..."); UUIDFetcher fetcher = new UUIDFetcher(pm.getBackEnd().getRegisteredUsers(), fetchercooldown); fetcher.fetchUUIDs(); Map<String, UUID> uuids = fetcher.getUUIDs(); sender.sendMessage(Color.Message + "Finished fetching."); //migrate permissions backend sender.sendMessage(Color.Text + "Migrating player identification ..."); pm.migrateUseUUID(uuids); sender.sendMessage(Color.Message + "Finished player identification migration."); //add fetched uuids to uuidplayerdb sender.sendMessage(Color.Text + "Applying fetched data to player-uuid-database ..."); for (Map.Entry<String, UUID> e : uuids.entrySet()) { pm.getUUIDPlayerDB().update(e.getValue(), e.getKey()); } sender.sendMessage(Color.Message + "Finished applying of fetched data to player-uuid-database."); } else { sender.sendMessage(Color.Text + "Migrating permissions using player names for player identification ..."); //fetch playernames from mojang sender.sendMessage(Color.Text + "Fetching " + (type ? "UUIDs" : "player names") + " ..."); UUIDFetcher fetcher = new UUIDFetcher(pm.getBackEnd().getRegisteredUsers(), fetchercooldown); fetcher.fetchPlayerNames(); Map<UUID, String> playernames = fetcher.getPlayerNames(); sender.sendMessage(Color.Message + "Finished fetching."); //migrate permissions backend sender.sendMessage(Color.Text + "Migrating player identification ..."); pm.migrateUsePlayerNames(playernames); sender.sendMessage(Color.Message + "Finished player identification migration."); //add fetched playername to uuidplayerdb sender.sendMessage(Color.Text + "Applying fetched data to player-uuid-database ..."); for (Map.Entry<UUID, String> e : playernames.entrySet()) { pm.getUUIDPlayerDB().update(e.getKey(), e.getValue()); } sender.sendMessage(Color.Message + "Finished applying of fetched data to player-uuid-database."); } sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleMigrateUUIDPlayerDB(CommandSender sender, String args[]) { if (args.length == 2) { sender.sendMessage(Color.Text + "Currently using " + Color.Value + pm.getUUIDPlayerDB().getType().name() + Color.Text + " as uuid player database"); } else if (args.length == 3) { String stype = args[2]; UUIDPlayerDBType type = UUIDPlayerDBType.getByName(stype); if (type == null) { sender.sendMessage(Color.Error + "Invalid backend type! " + Color.Value + UUIDPlayerDBType.None.name() + Color.Error + ", " + Color.Value + UUIDPlayerDBType.YAML.name() + Color.Error + " or " + Color.Value + UUIDPlayerDBType.MySQL.name() + Color.Error + " is required!"); return true; } if (type == pm.getUUIDPlayerDB().getType()) { sender.sendMessage(Color.Error + "Invalid uuid-player-database type! You can't migrate to same type!"); return true; } sender.sendMessage(Color.Text + "Migrating uuid-player-database to " + Color.Value + type.name() + Color.Text + " ..."); pm.migrateUUIDPlayerDB(type); sender.sendMessage(Color.Message + "Finished migration."); } else { Messages.sendTooManyArgsMessage(sender); } return true; } private boolean handleUUID(CommandSender sender, String args[]) { if (!pm.hasOrConsole(sender, "bungeeperms.uuid", true)) { return true; } if (!Statics.matchArgs(sender, args, 2, 3)) { return true; } boolean reverse = false; boolean mojang = false; String what = args[1]; UUID uuidwhat = Statics.parseUUID(what); if (args.length > 2) { String params = args[2]; if (params.startsWith("-")) { reverse = params.contains("r"); mojang = params.contains("m"); } } if (reverse) { if (uuidwhat == null) { sender.sendMessage(Color.Error + "UUID invalid!"); return true; } } if (mojang && reverse) { String name = UUIDFetcher.getPlayerNameFromMojang(uuidwhat); if (name == null) { sender.sendMessage(Color.Text + "Mojang does not know this player."); } else { sender.sendMessage(Color.Text + "Mojang says: Player name of " + Color.Value + uuidwhat + Color.Text + " is " + Color.User + name + Color.Text + "."); } } else if (mojang && !reverse) { UUID uuid = UUIDFetcher.getUUIDFromMojang(what, null); if (uuid == null) { sender.sendMessage(Color.Text + "Mojang does not know this player."); } else { sender.sendMessage(Color.Text + "Mojang says: UUID of " + Color.User + what + Color.Text + " is " + Color.Value + uuid + Color.Text + "."); } } else if (!mojang && reverse) { String name = pm.getUUIDPlayerDB().getPlayerName(uuidwhat); if (name == null) { sender.sendMessage(Color.Text + "The UUID-player database does not know this player."); } else { sender.sendMessage(Color.Text + "The UUID-player database says: Player name of " + Color.Value + uuidwhat + Color.Text + " is " + Color.User + name + Color.Text + "."); } } else if (!mojang && !reverse) { UUID uuid = pm.getUUIDPlayerDB().getUUID(what); if (uuid == null) { sender.sendMessage(Color.Text + "The UUID-player database does not know this player."); } else { sender.sendMessage(Color.Text + "The UUID-player database says: UUID of " + Color.User + what + Color.Text + " is " + Color.Value + uuid + Color.Text + "."); } } return true; } private void showHelp(CommandSender sender) { sender.sendMessage(ChatColor.GOLD + " ------ BungeePerms - Help -----"); sender.sendMessage(ChatColor.GRAY + "Aliases: " + ChatColor.GOLD + "/bp"); sender.sendMessage(ChatColor.GOLD + "/bungeeperms" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Welcomes you to BungeePerms"); if (pm.hasPermOrConsole(sender, "bungeeperms.help")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms help" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows this help"); } if (pm.hasPermOrConsole(sender, "bungeeperms.reload")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms reload" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Reloads the permissions"); } if (pm.hasPermOrConsole(sender, "bungeeperms.users")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms users [-c]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the users [or shows the amount of them]"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.info")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> info" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows information to the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.delete")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> delete" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Deletes the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> addperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Adds a permission to the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> removeperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Remove a permission from the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.has")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> has <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Checks if the given user has the given permission"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.perms.list")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> list" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the permissions of the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.group.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> addgroup <groupname>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Added the given group to the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.group.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> removegroup <groupname>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Removes the given group from the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.group.set")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> setgroup <groupname>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the given group as the main group for the given user"); } if (pm.hasPermOrConsole(sender, "bungeeperms.user.groups")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms user <username> groups" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the groups the given user is in"); } if (pm.hasPermOrConsole(sender, "bungeeperms.groups")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms groups" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the groups"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.info")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> info" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows information about the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.users")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> users [-c]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the users of the given group [or shows the amount of them]"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.create")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> create" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Create a group with the given name"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.delete")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> delete" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Create the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.inheritances.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> addinherit <group>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Adds a inheritance to the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.inheritances.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> removeinherit <group>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Remove a inheritance from the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.rank")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> rank <new rank>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the rank for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.weight")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> weight <new weight>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the weight for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.ladder")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> ladder <new ladder>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the ladder for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.default")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> default <true|false>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Determines whether the given group is a default group or not"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.display")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> display [displayname> [server [world]]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the display name for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.prefix")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> prefix [prefix> [server [world]]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the prefix for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.suffix")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> suffix [suffix> [server [world]]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Sets the suffix for the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.add")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> addperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Adds a permission to the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.remove")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> removeperm <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Remove a permission from the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.has")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> has <permission> [server [world]]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Checks if the given group has the given permission"); } if (pm.hasPermOrConsole(sender, "bungeeperms.group.perms.list")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms group <groupname> list" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Lists the permissions of the given group"); } if (pm.hasPermOrConsole(sender, "bungeeperms.promote")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms promote <username> [ladder]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Promotes the given user to the next rank"); } if (pm.hasPermOrConsole(sender, "bungeeperms.demote")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms demote <username> [ladder]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Demotes the given user to the previous rank"); } if (pm.hasPermOrConsole(sender, "bungeeperms.format")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms format" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Reformates the permission.yml or mysql table - " + ChatColor.RED + " BE CAREFUL"); } if (pm.hasPermOrConsole(sender, "bungeeperms.cleanup")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms cleanup" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Cleans up the permission.yml or mysql table - " + ChatColor.RED + " !BE VERY CAREFUL! - removes a lot of players from the permissions.yml if configured"); } if (pm.hasPermOrConsole(sender, "bungeeperms.backend")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms backend [yaml|mysql|mysql2]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Shows the used permissions database (file or mysql table) [or migrates to the given database] - " + ChatColor.RED + " !BE CAREFUL! (MAKE A BACKUP BEFORE EXECUTING)"); } if (pm.hasPermOrConsole(sender, "bungeeperms.migrate")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms migrate <backend [yaml|mysql|mysql2]|useuuid [true|false]|uuidplayerdb [None,YAML|MySQL]>" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Does migrations of different data (permissions, uuid) or shows status - " + ChatColor.RED + " !BE CAREFUL! (MAKE A BACKUP BEFORE EXECUTING)"); } if (pm.hasPermOrConsole(sender, "bungeeperms.uuid")) { sender.sendMessage(ChatColor.GOLD + "/bungeeperms uuid <player|uuid> [-rm]" + ChatColor.WHITE + " - " + ChatColor.GRAY + "Gets the UUID of a player from database (-r: reverse; -m: ask mojang)"); } sender.sendMessage(ChatColor.GOLD + "---------------------------------------------------"); } private void loadcmds() { bc.getPluginManager().registerCommand(this, new Command("bungeeperms", null, "bp") { @Override public void execute(final CommandSender sender, final String[] args) { final Command cmd = this; BungeeCord.getInstance().getScheduler().runAsync(instance, new Runnable() { @Override public void run() { if (!BungeePerms.this.onCommand(sender, cmd, "", args)) { sender.sendMessage(Color.Error + "[BungeePerms] Command not found"); } } }); } }); } private boolean parseTrueFalse(String truefalse) { if (Statics.argAlias(truefalse, "true", "yes", "t", "y", "+")) { return true; } else if (Statics.argAlias(truefalse, "false", "no", "f", "n", "-")) { return false; } throw new IllegalArgumentException("truefalse does not represent a boolean value"); } public PermissionsManager getPermissionsManager() { return pm; } }
also reload command handling variable fromm config
src/main/java/net/alpenblock/bungeeperms/BungeePerms.java
also reload command handling variable fromm config
<ide><path>rc/main/java/net/alpenblock/bungeeperms/BungeePerms.java <ide> return true; <ide> } <ide> <add> loadConfig(); <ide> pm.loadConfig(); <ide> pm.loadPerms(); <ide> pm.sendPMAll("reloadall");
JavaScript
mit
3e5a6fd48c775dbde1639b347efe7653825b2f9c
0
camshaft/imago
/** * Module dependencies */ var envs = require('envs'); var Transloadit = require('transloadit'); var proxy = require('simple-http-proxy'); function noop() {} /** * Initialize default params */ var params = [ ['width', null, '1-5000', 'Width of the new image, in pixels'], ['height', null, '1-5000', 'Height of the new image, in pixels'], ['strip', false, 'boolean', 'Strips all metadata from the image. This is useful to keep thumbnails as small as possible.'], ['flatten', true, 'boolean', 'Flattens all layers onto the specified background to achieve better results from transparent formats to non-transparent formats, as explained in the ImageMagick documentation.\nNote To preserve animations, GIF files are not flattened when this is set to true. To flatten GIF animations, use the frame parameter.'], ['correct_gamma', false, 'boolean', 'Prevents gamma errors common in many image scaling algorithms.'], ['quality', 92, '1-100', 'Controls the image compression for JPG and PNG images.'], ['background', '#FFFFFF', 'string', 'Either the hexadecimal code or name of the color used to fill the background (only used for the pad resize strategy).'], ['resize_strategy', 'fit', 'fit|stretch|pad|crop|fillcrop', 'https://transloadit.com/docs/conversion-robots#resize-strategies'], ['zoom', true, 'boolean', 'If this is set to false, smaller images will not be stretched to the desired width and height. For details about the impact of zooming for your preferred resize strategy, see the list of available resize strategies.'], ['format', null, 'jpg|png|gif|tiff', 'The available formats are "jpg", "png", "gif", and "tiff".'], ['gravity', 'center', 'center|top|bottom|left|right', 'The direction from which the image is to be cropped. The available options are "center", "top", "bottom", "left", and "right". You can also combine options with a hyphen, such as "bottom-right".'], ['frame', null, 'integer', 'Use this parameter when dealing with animated GIF files to specify which frame of the GIF is used for the operation. Specify 1 to use the first frame, 2 to use the second, and so on.'], ['colorspace', null, 'string', 'Sets the image colorspace. For details about the available values, see the ImageMagick documentation. Please note that if you were using "RGB", we recommend using "sRGB" instead as of 2014-02-04. ImageMagick might try to find the most efficient colorspace based on the color of an image, and default to e.g. "Gray". To force colors, you might then have to use this parameter in combination with type "TrueColor"'], ['type', null, 'string', 'Sets the image color type. For details about the available values, see the ImageMagick documentation. If you\'re using colorspace, ImageMagick might try to find the most efficient based on the color of an image, and default to e.g. "Gray". To force colors, could e.g. set this parameter to "TrueColor"'], ['sepia', null, 'number', 'Sets the sepia tone in percent. Valid values range from 0 - 99.'], ['rotation', true, 'string|boolean|integer', 'Determines whether the image should be rotated. Set this to true to auto-rotate images that are rotated in a wrong way, or depend on EXIF rotation settings. You can also set this to an integer to specify the rotation in degrees. You can also specify "degrees" to rotate only when the image width exceeds the height (or "degrees" if the width must be less than the height). Specify false to disable auto-fixing of images that are rotated in a wrong way.'], ['compress', null, 'string', 'Specifies pixel compression for when the image is written. Valid values are None, "BZip", "Fax", "Group4", "JPEG", "JPEG2000", "Lossless", "LZW", "RLE", and "Zip". Compression is disabled by default.'], ['blur', null, 'string', 'Specifies gaussian blur, using a value with the form {radius}x{sigma}. The radius value specifies the size of area the operator should look at when spreading pixels, and should typically be either "0" or at least two times the sigma value. The sigma value is an approximation of how many pixels the image is "spread"; think of it as the size of the brush used to blur the image. This number is a floating point value, enabling small values like "0.5" to be used.'], ['crop_x1'], ['crop_y1'], ['crop_x2'], ['crop_y2'], ['text'], ['progressive', true, 'boolean', 'Interlaces the image if set to true, which makes the image load progressively in browsers. Instead of rendering the image from top to bottom, the browser will first show a low-res blurry version of the images which is then quickly replaced with the actual image as the data arrives. This greatly increases the user experience, but comes at a cost of a file size increase by around 10%.'], ['transparent', null, 'string', 'Make this color transparent within the image.'], ['clip', false, 'mixed', 'Apply the clipping path to other operations in the resize job, if one is present. If set to true, it will automatically take the first clipping path. If set to a string it finds a clipping path by that name.'], ['negate', false, 'boolean', 'Replace each pixel with its complementary color, effictively negating the image. Especially useful when testing clipping.'], ['density', null, 'string', 'While in-memory quality and file format depth specifies the color resolution, the density of an image is the spatial (space) resolution of the image. That is the density (in pixels per inch) of an image and defines how far apart (or how big) the individual pixels are. It defines the size of the image in real world terms when displayed on devices or printed.\n\nYou can set this value to a specific width or in the format widthxheight.\n\nIf your converted image has a low resolution, please try using the density parameter to resolve that.'], ['force_accept', false, 'boolean', 'Robots may accept only certain file types - all other possible input files are ignored. \nThis means the /video/encode robot for example will never touch an image while the /image/resize robot will never look at a video.\nWith the force_accept parameter you can force a robot to accept all files thrown at him, regardless if it would normally accept them.'], ['watermark_url', null, 'string', 'A url indicating a PNG image to be overlaid above this image. Please note that you can also supply the watermark via another assembly step.'], ['watermark_position', 'center', 'string', 'The position at which the watermark is placed. The available options are "center", "top", "bottom", "left", and "right". You can also combine options, such as "bottom-right".\n\nThis setting puts the watermark in the specified corner. To use a specific pixel offset for the watermark, you will need to add the padding to the image itself.'], ['watermark_size', null, 'string', 'The size of the watermark, as a percentage.\nFor example, a value of "50%" means that size of the watermark will be 50% of the size of image on which it is placed.'], ['watermark_resize_strategy', 'fit', 'string', 'Available values are "fit" and "stretch".'] ]; /** * Initialize the imago middleware * * @param {Object} opts * @return {Function} */ module.exports = function(opts) { opts = opts || {}; var client = createClient(opts); var bucket = opts.s3Bucket || envs('S3_BUCKET'); var key = opts.s3Key || envs('AWS_ACCESS_KEY_ID'); var secret = opts.s3Secret || envs('AWS_SECRET_ACCESS_KEY'); var transformAssembly = opts.onassembly || noop; return function processImage(req, res, next) { if (req.url === '/') return api(req, res, next); var assembly = { params: { steps: steps(key, secret, bucket, req) } }; set(req.query, assembly.params, 'template_id'); var transformed = (transformAssembly || noop)(assembly, req); var end = profile(req, 'transloadit.resize'); client(transformed || assembly, function(err, result) { end({ error: err && err.message, assembly: result && result.assembly_url }); if (err) return next(err); var url = result.results.out[0].url; req.url = ''; res.on('header', function() { if (res.statusCode !== 200) return; res.set('cache-control', 'max-age=31536000, public'); }); proxy(url)(req, res, next); }); }; }; function api(req, res, next) { res.json({ params: params.reduce(function(acc, args) { var key = args[0]; acc[key] = { type: args[2], value: args[1], info: args[3] }; return acc; }, {}) }); } /** * Create a transloadit client * * @param {Object} opts * @return {Function} */ function createClient(opts) { var client = new Transloadit({ authKey : opts.transloaditAuthKey || envs('TRANSLOADIT_AUTH_KEY'), authSecret : opts.transloaditAuthSecret || envs('TRANSLOADIT_SECRET_KEY') }); function create(assembly, cb) { client.createAssembly(assembly, handle.bind(null, cb)); } function poll(url, cb) { setTimeout(function() { client._remoteJson({ url: url }, handle.bind(null, cb)); }, 500); } function handle(cb, err, result) { if (err) return cb(err); if (result.error) return cb(new Error(result.message)); if (result.ok !== 'ASSEMBLY_COMPLETED') return poll(result.assembly_url, cb); cb(err, result); } return create; } /** * Profile a transloadit request * * @param {Request} req * @param {String} str * @param {Object} opts * @return {Function} */ function profile(req, str, opts) { var metric = req.metric; if (!metric) return noop; var profile = metric.profile; if (!profile) return noop; return req.metric.profile(str, opts); } /** * Format the out params * * @param {String} use * @param {Object} query * @return {Object} */ function formatOut(use, query) { var assembly = { robot: '/image/resize', use: use }; var s = set.bind(null, query, assembly); params.forEach(function(args) { s.apply(null, args); }); if (assembly.text) deepParse(assembly.text); return assembly; } /** * Set a value on the assembly * * @param {Object} query * @param {Object} assembly * @param {String} key * @param {Any} defaultValue * @param {Function?} transform */ function set(query, assembly, key, defaultValue) { var val = query[key]; if (typeof val !== 'undefined') assembly[key] = val; else if (defaultValue !== null) assembly[key] = defaultValue; if (assembly[key] !== null) assembly[key] = deepParse(assembly[key]); } /** * Calculate assembly steps * * @param {String} key * @param {String} secret * @param {String} bucket * @param {Object} req */ function steps(key, secret, bucket, req) { var outPrevStep = 'import'; var steps = { import: { robot: '/s3/import', key: key, secret: secret, bucket: bucket, path: req.url.split('?')[0].substr(1) } } //cropping passed if (req.query.crop) { steps['crop'] = { robot: '/image/resize', use: 'import', crop: req.query.crop, resize_strategy: "crop" }; outPrevStep = 'crop'; } steps['out'] = formatOut(outPrevStep, req.query); return steps; } /** * Deep parse an object */ function deepParse(val) { if (typeof val !== 'object') return parse(val); if (Array.isArray(val)) return val.map(deepParse); return Object.keys(val).reduce(function(acc, key) { acc[key] = deepParse(val[key]) return acc; }, {}); } /** * Parse a query value * * @param {String} val * @return {String|Boolean|Number} */ function parse(val) { if (val === 'true') return true; if (val === 'false') return false; var num = parseInt(val); if (!isNaN(num)) return num; return val; }
index.js
/** * Module dependencies */ var envs = require('envs'); var Transloadit = require('transloadit'); var proxy = require('simple-http-proxy'); function noop() {} /** * Initialize default params */ var params = [ ['width', null, '1-5000', 'Width of the new image, in pixels'], ['height', null, '1-5000', 'Height of the new image, in pixels'], ['strip', false, 'boolean', 'Strips all metadata from the image. This is useful to keep thumbnails as small as possible.'], ['flatten', true, 'boolean', 'Flattens all layers onto the specified background to achieve better results from transparent formats to non-transparent formats, as explained in the ImageMagick documentation.\nNote To preserve animations, GIF files are not flattened when this is set to true. To flatten GIF animations, use the frame parameter.'], ['correct_gamma', false, 'boolean', 'Prevents gamma errors common in many image scaling algorithms.'], ['quality', 92, '1-100', 'Controls the image compression for JPG and PNG images.'], ['background', '#FFFFFF', 'string', 'Either the hexadecimal code or name of the color used to fill the background (only used for the pad resize strategy).'], ['resize_strategy', 'fit', 'fit|stretch|pad|crop|fillcrop', 'https://transloadit.com/docs/conversion-robots#resize-strategies'], ['zoom', true, 'boolean', 'If this is set to false, smaller images will not be stretched to the desired width and height. For details about the impact of zooming for your preferred resize strategy, see the list of available resize strategies.'], ['format', null, 'jpg|png|gif|tiff', 'The available formats are "jpg", "png", "gif", and "tiff".'], ['gravity', 'center', 'center|top|bottom|left|right', 'The direction from which the image is to be cropped. The available options are "center", "top", "bottom", "left", and "right". You can also combine options with a hyphen, such as "bottom-right".'], ['frame', null, 'integer', 'Use this parameter when dealing with animated GIF files to specify which frame of the GIF is used for the operation. Specify 1 to use the first frame, 2 to use the second, and so on.'], ['colorspace', null, 'string', 'Sets the image colorspace. For details about the available values, see the ImageMagick documentation. Please note that if you were using "RGB", we recommend using "sRGB" instead as of 2014-02-04. ImageMagick might try to find the most efficient colorspace based on the color of an image, and default to e.g. "Gray". To force colors, you might then have to use this parameter in combination with type "TrueColor"'], ['type', null, 'string', 'Sets the image color type. For details about the available values, see the ImageMagick documentation. If you\'re using colorspace, ImageMagick might try to find the most efficient based on the color of an image, and default to e.g. "Gray". To force colors, could e.g. set this parameter to "TrueColor"'], ['sepia', null, 'number', 'Sets the sepia tone in percent. Valid values range from 0 - 99.'], ['rotation', true, 'string|boolean|integer', 'Determines whether the image should be rotated. Set this to true to auto-rotate images that are rotated in a wrong way, or depend on EXIF rotation settings. You can also set this to an integer to specify the rotation in degrees. You can also specify "degrees" to rotate only when the image width exceeds the height (or "degrees" if the width must be less than the height). Specify false to disable auto-fixing of images that are rotated in a wrong way.'], ['compress', null, 'string', 'Specifies pixel compression for when the image is written. Valid values are None, "BZip", "Fax", "Group4", "JPEG", "JPEG2000", "Lossless", "LZW", "RLE", and "Zip". Compression is disabled by default.'], ['blur', null, 'string', 'Specifies gaussian blur, using a value with the form {radius}x{sigma}. The radius value specifies the size of area the operator should look at when spreading pixels, and should typically be either "0" or at least two times the sigma value. The sigma value is an approximation of how many pixels the image is "spread"; think of it as the size of the brush used to blur the image. This number is a floating point value, enabling small values like "0.5" to be used.'], ['crop_x1'], ['crop_y1'], ['crop_x2'], ['crop_y2'], ['text'], ['progressive', true, 'boolean', 'Interlaces the image if set to true, which makes the image load progressively in browsers. Instead of rendering the image from top to bottom, the browser will first show a low-res blurry version of the images which is then quickly replaced with the actual image as the data arrives. This greatly increases the user experience, but comes at a cost of a file size increase by around 10%.'], ['transparent', null, 'string', 'Make this color transparent within the image.'], ['clip', false, 'mixed', 'Apply the clipping path to other operations in the resize job, if one is present. If set to true, it will automatically take the first clipping path. If set to a string it finds a clipping path by that name.'], ['negate', false, 'boolean', 'Replace each pixel with its complementary color, effictively negating the image. Especially useful when testing clipping.'], ['density', null, 'string', 'While in-memory quality and file format depth specifies the color resolution, the density of an image is the spatial (space) resolution of the image. That is the density (in pixels per inch) of an image and defines how far apart (or how big) the individual pixels are. It defines the size of the image in real world terms when displayed on devices or printed.\n\nYou can set this value to a specific width or in the format widthxheight.\n\nIf your converted image has a low resolution, please try using the density parameter to resolve that.'], ['force_accept', false, 'boolean', 'Robots may accept only certain file types - all other possible input files are ignored. \nThis means the /video/encode robot for example will never touch an image while the /image/resize robot will never look at a video.\nWith the force_accept parameter you can force a robot to accept all files thrown at him, regardless if it would normally accept them.'], ['watermark_url', null, 'string', 'A url indicating a PNG image to be overlaid above this image. Please note that you can also supply the watermark via another assembly step.'], ['watermark_position', 'center', 'string', 'The position at which the watermark is placed. The available options are "center", "top", "bottom", "left", and "right". You can also combine options, such as "bottom-right".\n\nThis setting puts the watermark in the specified corner. To use a specific pixel offset for the watermark, you will need to add the padding to the image itself.'], ['watermark_size', null, 'string', 'The size of the watermark, as a percentage.\nFor example, a value of "50%" means that size of the watermark will be 50% of the size of image on which it is placed.'], ['watermark_resize_strategy', 'fit', 'string', 'Available values are "fit" and "stretch".'] ]; /** * Initialize the imago middleware * * @param {Object} opts * @return {Function} */ module.exports = function(opts) { opts = opts || {}; var client = createClient(opts); var bucket = opts.s3Bucket || envs('S3_BUCKET'); var key = opts.s3Key || envs('AWS_ACCESS_KEY_ID'); var secret = opts.s3Secret || envs('AWS_SECRET_ACCESS_KEY'); var transformAssembly = opts.onassembly || noop; return function processImage(req, res, next) { if (req.url === '/') return api(req, res, next); var assembly = { params: { steps: steps(key, secret, bucket, req) } }; set(req.query, assembly.params, 'template_id'); var transformed = (transformAssembly || noop)(assembly, req); var end = profile(req, 'transloadit.resize'); client(transformed || assembly, function(err, result) { end({ error: err && err.message, assembly: result && result.assembly_url }); if (err) return next(err); var url = result.results.out[0].url; req.url = ''; res.on('header', function() { if (res.statusCode !== 200) return; res.set('cache-control', 'max-age=31536000, public'); }); proxy(url)(req, res, next); }); }; }; function api(req, res, next) { res.json({ params: params.reduce(function(acc, args) { var key = args[0]; acc[key] = { type: args[2], value: args[1], info: args[3] }; return acc; }, {}) }); } /** * Create a transloadit client * * @param {Object} opts * @return {Function} */ function createClient(opts) { var client = new Transloadit({ authKey : opts.transloaditAuthKey || envs('TRANSLOADIT_AUTH_KEY'), authSecret : opts.transloaditAuthSecret || envs('TRANSLOADIT_SECRET_KEY') }); function create(assembly, cb) { client.createAssembly(assembly, handle.bind(null, cb)); } function poll(url, cb) { setTimeout(function() { client._remoteJson({ url: url }, handle.bind(null, cb)); }, 500); } function handle(cb, err, result) { if (err) return cb(err); if (result.error) return cb(new Error(result.message)); if (result.ok !== 'ASSEMBLY_COMPLETED') return poll(result.assembly_url, cb); cb(err, result); } return create; } /** * Profile a transloadit request * * @param {Request} req * @param {String} str * @param {Object} opts * @return {Function} */ function profile(req, str, opts) { var metric = req.metric; if (!metric) return noop; var profile = metric.profile; if (!profile) return noop; return req.metric.profile(str, opts); } /** * Format the out params * * @param {String} use * @param {Object} query * @return {Object} */ function formatOut(use, query) { var assembly = { robot: '/image/resize', use: use }; var s = set.bind(null, query, assembly); params.forEach(function(args) { s.apply(null, args); }); if (assembly.text) deepParse(assembly.text); return assembly; } /** * Set a value on the assembly * * @param {Object} query * @param {Object} assembly * @param {String} key * @param {Any} defaultValue * @param {Function?} transform */ function set(query, assembly, key, defaultValue) { var val = query[key]; if (typeof val !== 'undefined') assembly[key] = val; else if (defaultValue !== null) assembly[key] = defaultValue; if (assembly[key] !== null) assembly[key] = deepParse(assembly[key]); } /** * Calculate assembly steps * * @param {String} key * @param {String} secret * @param {String} bucket * @param {Object} req */ function steps(key, secret, bucket, req) { var outPrevStep = 'import'; var steps = { import: { robot: '/s3/import', key: key, secret: secret, bucket: bucket, path: req.url.split('?')[0].substr(1) } } //cropping passed if (req.query.crop) { steps['crop'] = { robot: '/image/resize', use: 'import', crop: req.query.crop, }; outPrevStep = 'crop'; } steps['out'] = formatOut(outPrevStep, req.query); return steps; } /** * Deep parse an object */ function deepParse(val) { if (typeof val !== 'object') return parse(val); if (Array.isArray(val)) return val.map(deepParse); return Object.keys(val).reduce(function(acc, key) { acc[key] = deepParse(val[key]) return acc; }, {}); } /** * Parse a query value * * @param {String} val * @return {String|Boolean|Number} */ function parse(val) { if (val === 'true') return true; if (val === 'false') return false; var num = parseInt(val); if (!isNaN(num)) return num; return val; }
need to set resize_strategy
index.js
need to set resize_strategy
<ide><path>ndex.js <ide> robot: '/image/resize', <ide> use: 'import', <ide> crop: req.query.crop, <add> resize_strategy: "crop" <ide> }; <ide> <ide> outPrevStep = 'crop';
Java
apache-2.0
9f741344f003258c4d6f27a5f7b7f9c1825d1dcf
0
maduhu/head,maduhu/head,maduhu/head,AArhin/head,AArhin/head,maduhu/head,AArhin/head,AArhin/head,maduhu/head,AArhin/head
package org.mifos.ui.core.controller; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.time.DateFormatUtils; import org.mifos.application.admin.servicefacade.PersonnelServiceFacade; import org.mifos.application.servicefacade.CenterServiceFacade; import org.mifos.application.servicefacade.LoanAccountServiceFacade; import org.mifos.config.servicefacade.ConfigurationServiceFacade; import org.mifos.config.servicefacade.dto.AccountingConfigurationDto; import org.mifos.dto.domain.AdminDocumentDto; import org.mifos.dto.domain.LoanAccountDetailsDto; import org.mifos.dto.domain.LoanActivityDto; import org.mifos.dto.domain.LoanInstallmentDetailsDto; import org.mifos.dto.domain.OriginalScheduleInfoDto; import org.mifos.dto.screen.AccountPaymentDto; import org.mifos.dto.screen.LoanInformationDto; import org.mifos.dto.screen.TransactionHistoryDto; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.platform.questionnaire.service.QuestionnaireServiceFacade; import org.mifos.reports.admindocuments.AdminDocumentsServiceFacade; import org.mifos.ui.core.controller.util.helpers.SitePreferenceHelper; import org.mifos.ui.core.controller.util.helpers.UrlHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import freemarker.ext.servlet.IncludePage; @Controller public class ViewLoanAccountDetailsController { private static final Integer GROUP_LOAN_PARENT = 1; @Autowired private LoanAccountServiceFacade loanAccountServiceFacade; @Autowired private CenterServiceFacade centerServiceFacade; @Autowired private PersonnelServiceFacade personnelServiceFacade; @Autowired private QuestionnaireServiceFacade questionnaireServiceFacade; @Autowired private ConfigurationServiceFacade configurationServiceFacade; @Autowired private AdminDocumentsServiceFacade adminDocumentsServiceFacade; private final SitePreferenceHelper sitePreferenceHelper = new SitePreferenceHelper(); @RequestMapping(value = "/viewLoanAccountDetails", method=RequestMethod.GET) public ModelAndView showLoanAccountDetails(HttpServletRequest request, HttpServletResponse response) throws ApplicationException { ModelAndView modelAndView = new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountDetails", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); boolean containsQGForCloseLoan = questionnaireServiceFacade.getQuestionGroupInstances(loanInformationDto.getAccountId(), "Close", "Loan").size() > 0; modelAndView.addObject("containsQGForCloseLoan", containsQGForCloseLoan); // for mifostabletag List<LoanActivityDto> activities = loanInformationDto.getRecentAccountActivity(); for (LoanActivityDto activity : activities) { activity.setUserPrefferedDate(DateFormatUtils.format(activity.getActionDate(), "dd/MM/yyyy", personnelServiceFacade.getUserPreferredLocale())); } request.getSession().setAttribute("recentAccountActivities", loanInformationDto.getRecentAccountActivity()); //for GLIM if ( configurationServiceFacade.isGlimEnabled() && loanInformationDto.isGroup()) { List<LoanAccountDetailsDto> loanAccountsDetails = loanAccountServiceFacade.retrieveLoanAccountDetails(loanInformationDto); addEmptyBuisnessActivities(loanAccountsDetails); modelAndView.addObject("loanAccountDetailsView"); request.setAttribute("loanAccountDetailsView", loanAccountsDetails); } modelAndView.addObject("backPageUrl", UrlHelper.constructCurrentPageUrl(request)); request.getSession().setAttribute("backPageUrl", request.getAttribute("currentPageUrl")); loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountAllActivity", method=RequestMethod.GET) public ModelAndView showLoanAccountAllActivity(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountAllActivity", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); modelAndView.addObject("currentDate", new Date()); List<LoanActivityDto> allLoanAccountActivities = this.loanAccountServiceFacade.retrieveAllLoanAccountActivities(globalAccountNum); request.setAttribute("loanAllActivityView", allLoanAccountActivities); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountTransactionHistory", method=RequestMethod.GET) public ModelAndView showLoanAccountTransactionHistory(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountTransactionHistory", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); AccountingConfigurationDto configurationDto = this.configurationServiceFacade.getAccountingConfiguration(); modelAndView.addObject("GLCodeMode", configurationDto.getGlCodeMode()); List<TransactionHistoryDto> transactionHistoryDto = this.centerServiceFacade.retrieveAccountTransactionHistory(globalAccountNum); request.setAttribute("trxnHistoryList", transactionHistoryDto); return modelAndView; } @RequestMapping(value = "/viewLoanAccountPayments", method=RequestMethod.GET) public ModelAndView showLoanAccountPayments(HttpServletRequest request, HttpServletResponse response, @RequestParam String globalAccountNum){ ModelAndView modelAndView = new ModelAndView("viewLoanAccountPayments"); List<AccountPaymentDto> loanAccountPayments = loanAccountServiceFacade.getLoanAccountPayments(globalAccountNum); for (AccountPaymentDto accountPaymentDto : loanAccountPayments){ List<AdminDocumentDto> adminDocuments = adminDocumentsServiceFacade.getAdminDocumentsForAccountPayment(accountPaymentDto.getPaymentId()); if (adminDocuments != null && !adminDocuments.isEmpty()){ accountPaymentDto.setAdminDocuments(adminDocuments); } } modelAndView.addObject("loanType", loanAccountServiceFacade.getGroupLoanType(globalAccountNum)); modelAndView.addObject("loanAccountPayments", loanAccountPayments); return modelAndView; } @RequestMapping(value = "/printPaymentReceipt", method=RequestMethod.GET) public ModelAndView showLastPaymentReceipt(HttpServletRequest request, HttpServletResponse response, @RequestParam (required=false) String globalAccountNum){ ModelAndView modelAndView = new ModelAndView("printPaymentReceipt"); String gan = null; if(globalAccountNum==null) { gan = request.getSession().getAttribute("globalAccountNum").toString(); } else { gan = globalAccountNum; } AccountPaymentDto loanAccountPayment = loanAccountServiceFacade.getLoanAccountPayments(gan).get(0); if (loanAccountServiceFacade.getGroupLoanType(gan).equals(GROUP_LOAN_PARENT)) { Integer accountId = loanAccountServiceFacade.retrieveLoanInformation(gan).getAccountId(); List<AccountPaymentDto> loanAccountPayments = loanAccountServiceFacade.getLoanAccountPayments(gan); for (AccountPaymentDto payment : loanAccountPayments) { if (payment.getAccount().getAccountId() == accountId) { loanAccountPayment = payment; break; } } } List<AdminDocumentDto> adminDocuments = adminDocumentsServiceFacade.getAdminDocumentsForAccountPayment(loanAccountPayment.getPaymentId()); if (adminDocuments != null && !adminDocuments.isEmpty()){ loanAccountPayment.setAdminDocuments(adminDocuments); } modelAndView.addObject("loanAccountPayment", loanAccountPayment); modelAndView.addObject("globalAccountNum", gan); return modelAndView; } @RequestMapping(value = "/viewLoanAccountNextInstallmentDetails", method=RequestMethod.GET) public ModelAndView showLoanAccountNextInstallmentDetails(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountNextInstallmentDetails", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); LoanInstallmentDetailsDto loanInstallmentDetailsDto = this.loanAccountServiceFacade.retrieveInstallmentDetails(loanInformationDto.getAccountId()); modelAndView.addObject("loanInformationDto", loanInformationDto); modelAndView.addObject("loanInstallmentDetailsDto", loanInstallmentDetailsDto); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountRepaymentSchedule", method=RequestMethod.GET) public ModelAndView showLoanAccountRepaymentSchedule(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountRepaymentSchedule", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); modelAndView.addObject("currentDate", new Date()); OriginalScheduleInfoDto originalScheduleInfoDto = loanAccountServiceFacade.retrieveOriginalLoanSchedule(globalAccountNum); modelAndView.addObject("isOriginalScheduleAvailable", originalScheduleInfoDto.hasOriginalInstallments()); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountOriginalSchedule", method=RequestMethod.GET) public ModelAndView showLoanAccountOriginalSchedule(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountOriginalSchedule", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); OriginalScheduleInfoDto originalScheduleInfoDto = loanAccountServiceFacade.retrieveOriginalLoanSchedule(globalAccountNum); modelAndView.addObject("originalScheduleInfoDto", originalScheduleInfoDto); // for mifostabletag request.setAttribute("originalInstallments", originalScheduleInfoDto.getOriginalLoanScheduleInstallments()); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } private void addEmptyBuisnessActivities(List<LoanAccountDetailsDto> loanAccountDetails) { for (LoanAccountDetailsDto details : loanAccountDetails) { if (details.getBusinessActivity() == null) { details.setBusinessActivity("-"); details.setBusinessActivityName("-"); } } } }
userInterface/src/main/java/org/mifos/ui/core/controller/ViewLoanAccountDetailsController.java
package org.mifos.ui.core.controller; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.time.DateFormatUtils; import org.mifos.application.admin.servicefacade.PersonnelServiceFacade; import org.mifos.application.servicefacade.CenterServiceFacade; import org.mifos.application.servicefacade.LoanAccountServiceFacade; import org.mifos.config.servicefacade.ConfigurationServiceFacade; import org.mifos.config.servicefacade.dto.AccountingConfigurationDto; import org.mifos.dto.domain.AdminDocumentDto; import org.mifos.dto.domain.LoanAccountDetailsDto; import org.mifos.dto.domain.LoanActivityDto; import org.mifos.dto.domain.LoanInstallmentDetailsDto; import org.mifos.dto.domain.OriginalScheduleInfoDto; import org.mifos.dto.screen.AccountPaymentDto; import org.mifos.dto.screen.LoanInformationDto; import org.mifos.dto.screen.TransactionHistoryDto; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.platform.questionnaire.service.QuestionnaireServiceFacade; import org.mifos.reports.admindocuments.AdminDocumentsServiceFacade; import org.mifos.ui.core.controller.util.helpers.SitePreferenceHelper; import org.mifos.ui.core.controller.util.helpers.UrlHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import freemarker.ext.servlet.IncludePage; @Controller public class ViewLoanAccountDetailsController { @Autowired private LoanAccountServiceFacade loanAccountServiceFacade; @Autowired private CenterServiceFacade centerServiceFacade; @Autowired private PersonnelServiceFacade personnelServiceFacade; @Autowired private QuestionnaireServiceFacade questionnaireServiceFacade; @Autowired private ConfigurationServiceFacade configurationServiceFacade; @Autowired private AdminDocumentsServiceFacade adminDocumentsServiceFacade; private final SitePreferenceHelper sitePreferenceHelper = new SitePreferenceHelper(); @RequestMapping(value = "/viewLoanAccountDetails", method=RequestMethod.GET) public ModelAndView showLoanAccountDetails(HttpServletRequest request, HttpServletResponse response) throws ApplicationException { ModelAndView modelAndView = new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountDetails", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); boolean containsQGForCloseLoan = questionnaireServiceFacade.getQuestionGroupInstances(loanInformationDto.getAccountId(), "Close", "Loan").size() > 0; modelAndView.addObject("containsQGForCloseLoan", containsQGForCloseLoan); // for mifostabletag List<LoanActivityDto> activities = loanInformationDto.getRecentAccountActivity(); for (LoanActivityDto activity : activities) { activity.setUserPrefferedDate(DateFormatUtils.format(activity.getActionDate(), "dd/MM/yyyy", personnelServiceFacade.getUserPreferredLocale())); } request.getSession().setAttribute("recentAccountActivities", loanInformationDto.getRecentAccountActivity()); //for GLIM if ( configurationServiceFacade.isGlimEnabled() && loanInformationDto.isGroup()) { List<LoanAccountDetailsDto> loanAccountsDetails = loanAccountServiceFacade.retrieveLoanAccountDetails(loanInformationDto); addEmptyBuisnessActivities(loanAccountsDetails); modelAndView.addObject("loanAccountDetailsView"); request.setAttribute("loanAccountDetailsView", loanAccountsDetails); } modelAndView.addObject("backPageUrl", UrlHelper.constructCurrentPageUrl(request)); request.getSession().setAttribute("backPageUrl", request.getAttribute("currentPageUrl")); loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountAllActivity", method=RequestMethod.GET) public ModelAndView showLoanAccountAllActivity(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountAllActivity", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); modelAndView.addObject("currentDate", new Date()); List<LoanActivityDto> allLoanAccountActivities = this.loanAccountServiceFacade.retrieveAllLoanAccountActivities(globalAccountNum); request.setAttribute("loanAllActivityView", allLoanAccountActivities); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountTransactionHistory", method=RequestMethod.GET) public ModelAndView showLoanAccountTransactionHistory(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountTransactionHistory", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); AccountingConfigurationDto configurationDto = this.configurationServiceFacade.getAccountingConfiguration(); modelAndView.addObject("GLCodeMode", configurationDto.getGlCodeMode()); List<TransactionHistoryDto> transactionHistoryDto = this.centerServiceFacade.retrieveAccountTransactionHistory(globalAccountNum); request.setAttribute("trxnHistoryList", transactionHistoryDto); return modelAndView; } @RequestMapping(value = "/viewLoanAccountPayments", method=RequestMethod.GET) public ModelAndView showLoanAccountPayments(HttpServletRequest request, HttpServletResponse response, @RequestParam String globalAccountNum){ ModelAndView modelAndView = new ModelAndView("viewLoanAccountPayments"); List<AccountPaymentDto> loanAccountPayments = loanAccountServiceFacade.getLoanAccountPayments(globalAccountNum); for (AccountPaymentDto accountPaymentDto : loanAccountPayments){ List<AdminDocumentDto> adminDocuments = adminDocumentsServiceFacade.getAdminDocumentsForAccountPayment(accountPaymentDto.getPaymentId()); if (adminDocuments != null && !adminDocuments.isEmpty()){ accountPaymentDto.setAdminDocuments(adminDocuments); } } modelAndView.addObject("loanType", loanAccountServiceFacade.getGroupLoanType(globalAccountNum)); modelAndView.addObject("loanAccountPayments", loanAccountPayments); return modelAndView; } @RequestMapping(value = "/printPaymentReceipt", method=RequestMethod.GET) public ModelAndView showLastPaymentReceipt(HttpServletRequest request, HttpServletResponse response, @RequestParam (required=false) String globalAccountNum){ ModelAndView modelAndView = new ModelAndView("printPaymentReceipt"); String gan = null; if(globalAccountNum==null) { gan = request.getSession().getAttribute("globalAccountNum").toString(); } else { gan = globalAccountNum; } AccountPaymentDto loanAccountPayment = loanAccountServiceFacade.getLoanAccountPayments(gan).get(0); List<AdminDocumentDto> adminDocuments = adminDocumentsServiceFacade.getAdminDocumentsForAccountPayment(loanAccountPayment.getPaymentId()); if (adminDocuments != null && !adminDocuments.isEmpty()){ loanAccountPayment.setAdminDocuments(adminDocuments); } modelAndView.addObject("loanAccountPayment", loanAccountPayment); modelAndView.addObject("globalAccountNum", gan); return modelAndView; } @RequestMapping(value = "/viewLoanAccountNextInstallmentDetails", method=RequestMethod.GET) public ModelAndView showLoanAccountNextInstallmentDetails(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountNextInstallmentDetails", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); LoanInstallmentDetailsDto loanInstallmentDetailsDto = this.loanAccountServiceFacade.retrieveInstallmentDetails(loanInformationDto.getAccountId()); modelAndView.addObject("loanInformationDto", loanInformationDto); modelAndView.addObject("loanInstallmentDetailsDto", loanInstallmentDetailsDto); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountRepaymentSchedule", method=RequestMethod.GET) public ModelAndView showLoanAccountRepaymentSchedule(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountRepaymentSchedule", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); modelAndView.addObject("currentDate", new Date()); OriginalScheduleInfoDto originalScheduleInfoDto = loanAccountServiceFacade.retrieveOriginalLoanSchedule(globalAccountNum); modelAndView.addObject("isOriginalScheduleAvailable", originalScheduleInfoDto.hasOriginalInstallments()); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } @RequestMapping(value = "/viewLoanAccountOriginalSchedule", method=RequestMethod.GET) public ModelAndView showLoanAccountOriginalSchedule(HttpServletRequest request, HttpServletResponse response){ ModelAndView modelAndView =new ModelAndView(); sitePreferenceHelper.resolveSiteType(modelAndView, "viewLoanAccountOriginalSchedule", request); modelAndView.addObject("include_page", new IncludePage(request, response)); String globalAccountNum = request.getParameter("globalAccountNum"); LoanInformationDto loanInformationDto = loanAccountServiceFacade.retrieveLoanInformation(globalAccountNum); modelAndView.addObject("loanInformationDto", loanInformationDto); OriginalScheduleInfoDto originalScheduleInfoDto = loanAccountServiceFacade.retrieveOriginalLoanSchedule(globalAccountNum); modelAndView.addObject("originalScheduleInfoDto", originalScheduleInfoDto); // for mifostabletag request.setAttribute("originalInstallments", originalScheduleInfoDto.getOriginalLoanScheduleInstallments()); this.loanAccountServiceFacade.putLoanBusinessKeyInSession(globalAccountNum, request); return modelAndView; } private void addEmptyBuisnessActivities(List<LoanAccountDetailsDto> loanAccountDetails) { for (LoanAccountDetailsDto details : loanAccountDetails) { if (details.getBusinessActivity() == null) { details.setBusinessActivity("-"); details.setBusinessActivityName("-"); } } } }
MIFOS-5965: Fixed printing receipt
userInterface/src/main/java/org/mifos/ui/core/controller/ViewLoanAccountDetailsController.java
MIFOS-5965: Fixed printing receipt
<ide><path>serInterface/src/main/java/org/mifos/ui/core/controller/ViewLoanAccountDetailsController.java <ide> <ide> @Controller <ide> public class ViewLoanAccountDetailsController { <add> <add> private static final Integer GROUP_LOAN_PARENT = 1; <ide> <ide> @Autowired <ide> private LoanAccountServiceFacade loanAccountServiceFacade; <ide> gan = globalAccountNum; <ide> } <ide> AccountPaymentDto loanAccountPayment = loanAccountServiceFacade.getLoanAccountPayments(gan).get(0); <add> <add> if (loanAccountServiceFacade.getGroupLoanType(gan).equals(GROUP_LOAN_PARENT)) { <add> Integer accountId = loanAccountServiceFacade.retrieveLoanInformation(gan).getAccountId(); <add> List<AccountPaymentDto> loanAccountPayments = loanAccountServiceFacade.getLoanAccountPayments(gan); <add> for (AccountPaymentDto payment : loanAccountPayments) { <add> if (payment.getAccount().getAccountId() == accountId) { <add> loanAccountPayment = payment; <add> break; <add> } <add> } <add> } <add> <ide> List<AdminDocumentDto> adminDocuments = adminDocumentsServiceFacade.getAdminDocumentsForAccountPayment(loanAccountPayment.getPaymentId()); <ide> if (adminDocuments != null && !adminDocuments.isEmpty()){ <ide> loanAccountPayment.setAdminDocuments(adminDocuments);
JavaScript
agpl-3.0
36d582a960676654c5ca005fc2c462b455e8eeb6
0
khilnani/quickedit,khilnani/quickedit,khilnani/quickedit
define([ 'jquery', 'underscore', 'views/base', 'globals/eventbus', 'bootbox', 'modules/cloudstore', 'ace', 'codemirror', 'css!libs/codemirror/codemirror-4.8.0.css', 'add2home', 'css!libs/add2home/add2home.css', 'sha256', 'aes'], function($, _, BaseView, EventBus, bootbox, CloudStore, ace, CodeMirror) { "use strict"; console.log("ContainerView."); var ContainerView = BaseView.extend({ el: $('#container'), message: undefined, events: { "keyup #password": "passwordsMatch", "keyup #password2": "passwordsMatch", "click #encrypt": "encryptMessage", "click #decrypt": "decryptMessage", "click #message": "refreshMessage", "keyup #message": "refreshMessage", "click #clearMessage": "clearMessage", "click #dbChooseFile": "readFile", "click #dbSaveFile": "saveFile", "click #backToTop": "backToTop", "click #logout": "logout" }, logout: function () { CloudStore.logout(); }, readFile: function () { console.group("readFile"); var promise = CloudStore.readFile(); var message = this.message; promise.done( function( text ) { console.log("read."); $('#message').val( text ) //message.setValue( text ); EventBus.trigger('message:updated'); console.groupEnd(); }); promise.fail( function( ) { console.log("read failed."); console.groupEnd(); }); }, saveFile: function () { console.group("saveFile"); //var promise = CloudStore.saveFile( this.message.getValue() ); var promise = CloudStore.saveFile( $('#message').val() ); promise.done( function( ) { console.log("saved."); console.groupEnd(); }); promise.fail( function( ) { console.log("save failed."); console.groupEnd(); }); }, encrypt: function (text, pass) { //console.log('pass:' + pass + ' encrypt IN:' + text); var key = Sha256.hash(pass); var encrypted = Aes.Ctr.encrypt(text, key, 256); //console.log('encrypt OUT:' + encrypted); return encrypted; }, decrypt: function (text, pass) { //console.log('pass:' + pass + ' decrypt IN:' + text); var key = Sha256.hash(pass); var decrypted = Aes.Ctr.decrypt(text, key, 256); //console.log('decrypt OUT:' + decrypted); return decrypted; }, encryptMessage: function() { console.group("encryptMessage()"); if ( this.passwordsMatch() ) { $('#message').val( this.encrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.encrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, decryptMessage: function () { console.group("decryptMessage()"); if( this.passwordsMatch() ) { $('#message').val( this.decrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.decrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, refreshMessage: function () { console.log("refreshMessage()"); var m = $('#message'); $("#count").text( m.val().length ); m.autosize({ append: '\n'}); //$("#count").text( this.message.getValue().length ); //this.message.renderer.adjustWrapLimit() //this.message.resize(); }, clearMessage: function () { var message = this.message; bootbox.confirm("Clear message?", function(result) { if(result == true) { $('#message').val(''); $('#message').trigger('change'); //message.setValue(''); EventBus.trigger('message:updated'); } }); }, passwordsMatch: function () { console.log("passwordsMatch()"); if( $('#password').val() == $('#password2').val() ) { $('#passGroup').removeClass("has-error"); $('#passwordError').addClass("hidden"); return true; } $('#passGroup').addClass("has-error"); $('#passwordError').removeClass("hidden"); this.backToTop(); return false; }, backToTop: function () { $("html, body").animate({ scrollTop: 0 }, "slow"); }, initialize: function(options) { console.log("ContainerView()"); BaseView.prototype.initialize.call(this, options); //this.message = window.ace.edit("message"); //this.message.setOptions({ // minLines: 10, // maxLines: 1000 //}); var editor = CodeMirror.fromTextArea(document.getElementById("message"), { lineNumbers: true, styleActiveLine: true, matchBrackets: true }); this.refreshMessage(); EventBus.on('message:updated', function(){ console.log('message:updated'); //$('#message').select(); this.refreshMessage(); }, this); }, destroy: function() { EventBus.off('message:updated'); BaseView.prototype.destroy.call(this); } }); return ContainerView; });
static/views/container.js
define([ 'jquery', 'underscore', 'views/base', 'globals/eventbus', 'bootbox', 'modules/cloudstore', 'ace', 'codemirror', 'add2home', 'css!libs/add2home/add2home.css', 'sha256', 'aes'], function($, _, BaseView, EventBus, bootbox, CloudStore, ace, CodeMirror) { "use strict"; console.log("ContainerView."); var ContainerView = BaseView.extend({ el: $('#container'), message: undefined, events: { "keyup #password": "passwordsMatch", "keyup #password2": "passwordsMatch", "click #encrypt": "encryptMessage", "click #decrypt": "decryptMessage", "click #message": "refreshMessage", "keyup #message": "refreshMessage", "click #clearMessage": "clearMessage", "click #dbChooseFile": "readFile", "click #dbSaveFile": "saveFile", "click #backToTop": "backToTop", "click #logout": "logout" }, logout: function () { CloudStore.logout(); }, readFile: function () { console.group("readFile"); var promise = CloudStore.readFile(); var message = this.message; promise.done( function( text ) { console.log("read."); $('#message').val( text ) //message.setValue( text ); EventBus.trigger('message:updated'); console.groupEnd(); }); promise.fail( function( ) { console.log("read failed."); console.groupEnd(); }); }, saveFile: function () { console.group("saveFile"); //var promise = CloudStore.saveFile( this.message.getValue() ); var promise = CloudStore.saveFile( $('#message').val() ); promise.done( function( ) { console.log("saved."); console.groupEnd(); }); promise.fail( function( ) { console.log("save failed."); console.groupEnd(); }); }, encrypt: function (text, pass) { //console.log('pass:' + pass + ' encrypt IN:' + text); var key = Sha256.hash(pass); var encrypted = Aes.Ctr.encrypt(text, key, 256); //console.log('encrypt OUT:' + encrypted); return encrypted; }, decrypt: function (text, pass) { //console.log('pass:' + pass + ' decrypt IN:' + text); var key = Sha256.hash(pass); var decrypted = Aes.Ctr.decrypt(text, key, 256); //console.log('decrypt OUT:' + decrypted); return decrypted; }, encryptMessage: function() { console.group("encryptMessage()"); if ( this.passwordsMatch() ) { $('#message').val( this.encrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.encrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, decryptMessage: function () { console.group("decryptMessage()"); if( this.passwordsMatch() ) { $('#message').val( this.decrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.decrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, refreshMessage: function () { console.log("refreshMessage()"); var m = $('#message'); $("#count").text( m.val().length ); m.autosize({ append: '\n'}); //$("#count").text( this.message.getValue().length ); //this.message.renderer.adjustWrapLimit() //this.message.resize(); }, clearMessage: function () { var message = this.message; bootbox.confirm("Clear message?", function(result) { if(result == true) { $('#message').val(''); $('#message').trigger('change'); //message.setValue(''); EventBus.trigger('message:updated'); } }); }, passwordsMatch: function () { console.log("passwordsMatch()"); if( $('#password').val() == $('#password2').val() ) { $('#passGroup').removeClass("has-error"); $('#passwordError').addClass("hidden"); return true; } $('#passGroup').addClass("has-error"); $('#passwordError').removeClass("hidden"); this.backToTop(); return false; }, backToTop: function () { $("html, body").animate({ scrollTop: 0 }, "slow"); }, initialize: function(options) { console.log("ContainerView()"); BaseView.prototype.initialize.call(this, options); //this.message = window.ace.edit("message"); //this.message.setOptions({ // minLines: 10, // maxLines: 1000 //}); var editor = CodeMirror.fromTextArea(document.getElementById("message"), { lineNumbers: true, styleActiveLine: true, matchBrackets: true }); this.refreshMessage(); EventBus.on('message:updated', function(){ console.log('message:updated'); //$('#message').select(); this.refreshMessage(); }, this); }, destroy: function() { EventBus.off('message:updated'); BaseView.prototype.destroy.call(this); } }); return ContainerView; });
Update container.js
static/views/container.js
Update container.js
<ide><path>tatic/views/container.js <ide> define([ <ide> 'jquery', 'underscore', 'views/base', 'globals/eventbus', 'bootbox', 'modules/cloudstore', 'ace', 'codemirror', <del> 'add2home', 'css!libs/add2home/add2home.css', 'sha256', 'aes'], <add> 'css!libs/codemirror/codemirror-4.8.0.css', 'add2home', 'css!libs/add2home/add2home.css', 'sha256', 'aes'], <ide> function($, _, BaseView, EventBus, bootbox, CloudStore, ace, CodeMirror) { <ide> "use strict"; <ide>
Java
apache-2.0
8aa8bb97884607065ec2263d03a37e7ba7f1fd41
0
projectbuendia/buendia,danilogit/buendia,fcruz/buendia,felipsimoes/buendia,FabioFiuza/buendia,TeixeiraRafael/buendia,pedromarins/buendia,luisfdeandrade/buendia,llvasconcellos/buendia,jozadaquebatista/buendia,projectbuendia/buendia,felipsimoes/buendia,christianrafael/buendia,projectbuendia/buendia,TeixeiraRafael/buendia,danilogit/buendia,christianrafael/buendia,llvasconcellos/buendia,G1DR4/buendia,G1DR4/buendia,projectbuendia/buendia,fcruz/buendia,llvasconcellos/buendia,felipsimoes/buendia,luisfdeandrade/buendia,G1DR4/buendia,fcruz/buendia,christianrafael/buendia,viniciusboson/buendia,viniciusboson/buendia,G1DR4/buendia,TeixeiraRafael/buendia,llvasconcellos/buendia,viniciusboson/buendia,viniciusboson/buendia,christianrafael/buendia,pedromarins/buendia,danilogit/buendia,danilogit/buendia,TeixeiraRafael/buendia,FabioFiuza/buendia,pedromarins/buendia,TeixeiraRafael/buendia,danilogit/buendia,pedromarins/buendia,jozadaquebatista/buendia,luisfdeandrade/buendia,felipsimoes/buendia,jozadaquebatista/buendia,projectbuendia/buendia,fcruz/buendia,felipsimoes/buendia,jozadaquebatista/buendia,FabioFiuza/buendia,pedromarins/buendia,G1DR4/buendia,danilogit/buendia,G1DR4/buendia,christianrafael/buendia,FabioFiuza/buendia,fcruz/buendia,pedromarins/buendia,fcruz/buendia,luisfdeandrade/buendia,christianrafael/buendia,jozadaquebatista/buendia,llvasconcellos/buendia,luisfdeandrade/buendia,felipsimoes/buendia,FabioFiuza/buendia,FabioFiuza/buendia,viniciusboson/buendia,llvasconcellos/buendia,TeixeiraRafael/buendia,viniciusboson/buendia,jozadaquebatista/buendia,luisfdeandrade/buendia
package org.openmrs.projectbuendia.webservices.rest; import org.apache.commons.lang3.StringUtils; import org.openmrs.*; import org.openmrs.api.*; import org.openmrs.api.context.Context; import org.openmrs.module.webservices.rest.SimpleObject; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.Resource; import org.openmrs.module.webservices.rest.web.representation.Representation; import org.openmrs.module.webservices.rest.web.resource.api.Creatable; import org.openmrs.module.webservices.rest.web.resource.api.Listable; import org.openmrs.module.webservices.rest.web.resource.api.Retrievable; import org.openmrs.module.webservices.rest.web.resource.api.Searchable; import org.openmrs.module.webservices.rest.web.resource.api.Updatable; import org.openmrs.module.webservices.rest.web.response.ObjectNotFoundException; import org.openmrs.module.webservices.rest.web.response.ResponseException; import org.projectbuendia.openmrs.webservices.rest.RestController; import java.util.*; /** * Resource for xform templates (i.e. forms without data). * Note: this is under org.openmrs as otherwise the resource annotation isn't picked up. */ @Resource(name = RestController.REST_VERSION_1_AND_NAMESPACE + "/patient", supportedClass = Patient.class, supportedOpenmrsVersions = "1.10.*") public class PatientResource implements Listable, Searchable, Retrievable, Creatable, Updatable { // Fake values private static final User CREATOR = new User(1); private static final String FACILITY_NAME = "Kailahun"; // TODO(kpy): Use a real facility name. // JSON property names private static final String ID = "id"; private static final String UUID = "uuid"; private static final String GENDER = "gender"; private static final String AGE = "age"; private static final String AGE_UNIT = "age_unit"; // "years" or "months" private static final String MONTHS_VALUE = "months"; private static final String AGE_TYPE = "type"; private static final String YEARS_VALUE = "years"; private static final String MONTHS_TYPE = "months"; private static final String YEARS_TYPE = "years"; private static final String GIVEN_NAME = "given_name"; private static final String FAMILY_NAME = "family_name"; private static final String ASSIGNED_LOCATION = "assigned_location"; private static final String ZONE = "zone"; private static final String TENT = "tent"; private static final String BED = "bed"; private static final String STATUS = "status"; // OpenMRS object names private static final String MSF_IDENTIFIER = "MSF"; private static final String EBOLA_STATUS_PROGRAM_NAME = "Ebola status program"; private static final String EBOLA_STATUS_WORKFLOW_NAME = "Ebola status workflow"; // OpenMRS object UUIDs private static final String EBOLA_STATUS_PROGRAM_UUID = "849c86fa-6f3d-11e4-b2f4-040ccecfdba4"; private static final String EBOLA_STATUS_PROGRAM_CONCEPT_UUID = "8c00e1b5-6f35-11e4-a3fa-040ccecfdba4"; private static final String EBOLA_STATUS_WORKFLOW_CONCEPT_UUID = "107f9c7a-6f3b-11e4-ba22-040ccecfdba4"; private static final String ZONE_LOCATION_TAG_UUID = "1c22989d-3b87-47d3-9459-b54aafbd1169"; private static final String TENT_LOCATION_TAG_UUID = "4c92578f-cde9-4b99-b641-f3b9e0cc268d"; private static final String BED_LOCATION_TAG_UUID = "f2cf9e4e-a197-4c44-9290-0d3dd963838e"; private static final String ASSIGNED_ZONE_PERSON_ATTRIBUTE_TYPE_UUID = "1c22989d-3b87-47d3-9459-b54aafbd1169"; private static final String ASSIGNED_TENT_PERSON_ATTRIBUTE_TYPE_UUID = "4c92578f-cde9-4b99-b641-f3b9e0cc268d"; private static final String ASSIGNED_BED_PERSON_ATTRIBUTE_TYPE_UUID = "f2cf9e4e-a197-4c44-9290-0d3dd963838e"; // The elements of each triple are: // 1. The key, which is how the status is represented in JSON. // 2. The concept name, which is a short phrase to avoid collision with other concepts. // 3. The UUID of the ProgramWorkflowState that represents the status. private static final String[][] EBOLA_STATUS_KEYS_NAMES_AND_UUIDS = { {"SUSPECTED_CASE", "suspected ebola case", "041a7b80-6f13-11e4-b6d3-040ccecfdba4"}, {"PROBABLE_CASE", "probable ebola case", "0ae8fd9c-6f13-11e4-9ad7-040ccecfdba4"}, {"CONFIRMED_CASE", "confirmed ebola case", "11a8a9c0-6f13-11e4-8c91-040ccecfdba4"}, {"NON_CASE", "not an ebola case", "b517037a-6f13-11e4-b5f2-040ccecfdba4"}, {"CONVALESCENT", "convalescing at ebola facility", "c1349bd7-6f13-11e4-b315-040ccecfdba4"}, {"READY_FOR_DISCHARGE", "ready for discharge from ebola facility", "e45ef19e-6f13-11e4-b630-040ccecfdba4"}, {"DISCHARGED", "discharged from ebola facility", "e4a20c4a-6f13-11e4-b315-040ccecfdba4"}, {"SUSPECTED_DEATH", "suspected death at ebola facility", "e4c09b7d-6f13-11e4-b315-040ccecfdba4"}, {"CONFIRMED_DEATH", "confirmed death at ebola facility", "e4da31e1-6f13-11e4-b315-040ccecfdba4"}, }; private static Map<String, String> EBOLA_STATUS_KEYS_BY_UUID = new HashMap<>(); private static Map<String, String> EBOLA_STATUS_UUIDS_BY_KEY = new HashMap<>(); static { for (String[] keyNameUuid : EBOLA_STATUS_KEYS_NAMES_AND_UUIDS) { EBOLA_STATUS_KEYS_BY_UUID.put(keyNameUuid[2], keyNameUuid[0]); EBOLA_STATUS_UUIDS_BY_KEY.put(keyNameUuid[0], keyNameUuid[2]); } } private final PatientService patientService; private final PersonAttributeType assignedZoneAttrType; private final PersonAttributeType assignedTentAttrType; private final PersonAttributeType assignedBedAttrType; public PatientResource() { patientService = Context.getPatientService(); assignedZoneAttrType = getPersonAttributeType( ASSIGNED_ZONE_PERSON_ATTRIBUTE_TYPE_UUID, "assigned_zone"); assignedTentAttrType = getPersonAttributeType( ASSIGNED_TENT_PERSON_ATTRIBUTE_TYPE_UUID, "assigned_tent"); assignedBedAttrType = getPersonAttributeType( ASSIGNED_BED_PERSON_ATTRIBUTE_TYPE_UUID, "assigned_bed"); } @Override public SimpleObject getAll(RequestContext requestContext) throws ResponseException { List<Patient> patients = patientService.getAllPatients(); return getSimpleObjectWithResults(patients); } /** * Converts a date to a year with a fractional part, e.g. Jan 1, 1970 * becomes 1970.0; Jul 1, 1970 becomes approximately 1970.5. */ private double dateToFractionalYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); double daysInYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR); return calendar.get(Calendar.YEAR) + calendar.get(Calendar.DAY_OF_YEAR) / daysInYear; } private Date fractionalYearToDate(double year) { int yearInt = (int) Math.floor(year); double yearFrac = year - yearInt; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, yearInt); calendar.set(Calendar.DAY_OF_YEAR, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long millis = calendar.getTimeInMillis(); int daysInYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR); millis += yearFrac * daysInYear * 24 * 3600 * 1000; return new Date(millis); } /** Estimate the age of a person in years, given their birthdate. */ private double birthDateToAge(Date birthDate) { return dateToFractionalYear(new Date()) - dateToFractionalYear(birthDate); } private SimpleObject patientToJson(Patient patient) { SimpleObject jsonForm = new SimpleObject(); if (patient != null) { jsonForm.add(UUID, patient.getUuid()); PatientIdentifier patientIdentifier = patient.getPatientIdentifier(getMsfIdentifierType()); if (patientIdentifier != null) { jsonForm.add(ID, patientIdentifier.getIdentifier()); } jsonForm.add(GENDER, patient.getGender()); double age = birthDateToAge(patient.getBirthdate()); SimpleObject ageObject = new SimpleObject(); if (age < 1.0) { ageObject.add(MONTHS_VALUE, (int) Math.floor(age * 12)); ageObject.add(AGE_TYPE, MONTHS_TYPE); } else { ageObject.add(YEARS_VALUE, (int) Math.floor(age)); ageObject.add(AGE_TYPE, YEARS_TYPE); } jsonForm.add(AGE, ageObject); jsonForm.add(GIVEN_NAME, patient.getGivenName()); jsonForm.add(FAMILY_NAME, patient.getFamilyName()); String assignedZoneId = getPersonAttributeValue(patient, assignedZoneAttrType); String assignedTentId = getPersonAttributeValue(patient, assignedTentAttrType); String assignedBedId = getPersonAttributeValue(patient, assignedBedAttrType); if (assignedZoneId != null || assignedTentId != null || assignedBedId != null) { SimpleObject location = new SimpleObject(); if (assignedZoneId != null) { location.add(ZONE, getLocationLeafName(assignedZoneId)); } if (assignedTentId != null) { location.add(TENT, getLocationLeafName(assignedTentId)); } if (assignedBedId != null) { location.add(BED, getLocationLeafName(assignedBedId)); } jsonForm.add(ASSIGNED_LOCATION, location); } PatientProgram patientProgram = getEbolaStatusPatientProgram(patient); PatientState patientState = patientProgram.getCurrentState( getEbolaStatusProgramWorkflow()); if (patientState != null) { jsonForm.add(STATUS, getKeyByState(patientState.getState())); } jsonForm.add("created_timestamp_utc", patient.getDateCreated().getTime()); } return jsonForm; } @Override public Object create(SimpleObject simpleObject, RequestContext requestContext) throws ResponseException { // We really want this to use XForms, but lets have a simple default implementation for early testing if (!simpleObject.containsKey(ID)) { throw new InvalidObjectDataException("JSON object lacks required \"id\" field"); } PatientIdentifierType identifierType = getMsfIdentifierType(); ArrayList<PatientIdentifierType> identifierTypes = new ArrayList<>(); identifierTypes.add(identifierType); String id = (String) simpleObject.get(ID); List<Patient> existing = patientService.getPatients(null, id, identifierTypes, true /* exact identifier match */); if (!existing.isEmpty()) { throw new InvalidObjectDataException("Patient with this ID already exists: " + id); } Patient patient = new Patient(); // TODO(nfortescue): do this properly from authentication patient.setCreator(CREATOR); patient.setDateCreated(new Date()); if (simpleObject.containsKey(GENDER)) { patient.setGender((String) simpleObject.get(GENDER)); } if (simpleObject.containsKey(AGE)) { double number = ((Number) simpleObject.get(AGE)).doubleValue(); if ("months".equals(simpleObject.get(AGE_UNIT))) { long millis = (long) Math.floor( new Date().getTime() - number * 365.24 / 12 * 24 * 3600 * 1000); patient.setBirthdate(new Date(millis)); } else { // default to years patient.setBirthdate(fractionalYearToDate( dateToFractionalYear(new Date()) - number)); } } PersonName pn = new PersonName(); if (simpleObject.containsKey(GIVEN_NAME)) { pn.setGivenName((String) simpleObject.get(GIVEN_NAME)); } if (simpleObject.containsKey(FAMILY_NAME)) { pn.setFamilyName((String) simpleObject.get(FAMILY_NAME)); } pn.setCreator(patient.getCreator()); pn.setDateCreated(patient.getDateCreated()); patient.addName(pn); // Identifier with fake location PatientIdentifier identifier = new PatientIdentifier(); identifier.setCreator(patient.getCreator()); identifier.setDateCreated(patient.getDateCreated()); identifier.setIdentifier(id); identifier.setLocation(getLocationByName(FACILITY_NAME, null, null)); identifier.setIdentifierType(identifierType); identifier.setPreferred(true); patient.addIdentifier(identifier); // Assigned zone, tent, and bed (convert integer 2 to string "2") setPatientAssignedLocation(patient, FACILITY_NAME, "" + simpleObject.get("assigned_zone"), "" + simpleObject.get("assigned_tent"), "" + simpleObject.get("assigned_bed")); patientService.savePatient(patient); // Status if (simpleObject.containsKey(STATUS)) { ProgramWorkflowState workflowState = getStateByKey((String) simpleObject.get(STATUS)); if (workflowState != null) { ProgramWorkflowService workflowService = Context.getProgramWorkflowService(); PatientProgram patientProgram = getEbolaStatusPatientProgram(patient); patientProgram.transitionToState(workflowState, new Date()); workflowService.savePatientProgram(patientProgram); patientService.savePatient(patient); } } return patientToJson(patient); } private PatientIdentifierType getMsfIdentifierType() { PatientIdentifierType identifierType = patientService.getPatientIdentifierTypeByName(MSF_IDENTIFIER); if (identifierType == null) { identifierType = new PatientIdentifierType(); identifierType.setName(MSF_IDENTIFIER); identifierType.setDescription("MSF patient identifier"); identifierType.setFormatDescription("[facility code].[patient number]"); patientService.savePatientIdentifierType(identifierType); } return identifierType; } public static Concept getConcept(String name, String uuid, String typeUuid) { ConceptService conceptService = Context.getConceptService(); Concept concept = conceptService.getConceptByUuid(uuid); if (concept == null) { concept = new Concept(); concept.setUuid(uuid); concept.setShortName(new ConceptName(name, new Locale("en"))); concept.setDatatype(conceptService.getConceptDatatypeByUuid(typeUuid)); concept.setConceptClass(conceptService.getConceptClassByUuid(ConceptClass.MISC_UUID)); conceptService.saveConcept(concept); } return concept; } /** Get the key (e.g. "confirmed") for an ebola status by workflow state. */ private String getKeyByState(ProgramWorkflowState state) { return EBOLA_STATUS_KEYS_BY_UUID.get(state.getConcept().getUuid()); } /** Get the workflow state for an ebola status by key (e.g. "suspected"). */ private ProgramWorkflowState getStateByKey(String key) { ProgramWorkflow workflow = getEbolaStatusProgramWorkflow(); ConceptService conceptService = Context.getConceptService(); String uuid = EBOLA_STATUS_UUIDS_BY_KEY.get(key); return uuid == null ? null : workflow.getState(conceptService.getConceptByUuid(uuid)); } private ProgramWorkflow getEbolaStatusProgramWorkflow() { ProgramWorkflow workflow = null; for (ProgramWorkflow w : getEbolaStatusProgram().getWorkflows()) { workflow = w; } return workflow; } /** * Get the "Ebola status" Program, creating the Program if it doesn't exist yet * (including its ProgramWorkflow, the workflow's ProgramWorkflowStates, and the * Concepts corresponding to those states). */ public static Program getEbolaStatusProgram() { ProgramWorkflowService workflowService = Context.getProgramWorkflowService(); Program program = workflowService.getProgramByUuid(EBOLA_STATUS_PROGRAM_UUID); if (program == null) { program = new Program(); program.setName(EBOLA_STATUS_PROGRAM_NAME); program.setUuid(EBOLA_STATUS_PROGRAM_UUID); program.setDescription(EBOLA_STATUS_PROGRAM_NAME); program.setConcept(getConcept(EBOLA_STATUS_PROGRAM_NAME, EBOLA_STATUS_PROGRAM_CONCEPT_UUID, ConceptDatatype.N_A_UUID)); workflowService.saveProgram(program); } Set<ProgramWorkflow> workflows = program.getWorkflows(); if (workflows.isEmpty()) { ProgramWorkflow workflow = new ProgramWorkflow(); workflow.setName(EBOLA_STATUS_WORKFLOW_NAME); workflow.setDescription(EBOLA_STATUS_WORKFLOW_NAME); workflow.setConcept(getConcept(EBOLA_STATUS_WORKFLOW_NAME, EBOLA_STATUS_WORKFLOW_CONCEPT_UUID, ConceptDatatype.N_A_UUID)); workflow.setProgram(program); for (String[] keyNameUuid : EBOLA_STATUS_KEYS_NAMES_AND_UUIDS) { ProgramWorkflowState state = new ProgramWorkflowState(); state.setConcept(getConcept(keyNameUuid[1], keyNameUuid[2], ConceptDatatype.CODED_UUID)); state.setName(keyNameUuid[1]); state.setInitial(false); state.setTerminal(false); workflow.addState(state); } program.addWorkflow(workflow); workflowService.saveProgram(program); } return program; } /** * Get the PatientProgram associating this Patient with the "Ebola status" Program, * creating the PatientProgram if it doesn't exist yet. */ public static PatientProgram getEbolaStatusPatientProgram(Patient patient) { ProgramWorkflowService workflowService = Context.getProgramWorkflowService(); Program program = getEbolaStatusProgram(); List<PatientProgram> patientPrograms = workflowService.getPatientPrograms(patient, program, null, null, null, null, false); PatientProgram patientProgram; if (patientPrograms.isEmpty()) { patientProgram = new PatientProgram(); patientProgram.setPatient(patient); patientProgram.setProgram(program); workflowService.savePatientProgram(patientProgram); } else { patientProgram = patientPrograms.get(0); } return patientProgram; } @Override public String getUri(Object instance) { Patient patient = (Patient) instance; Resource res = getClass().getAnnotation(Resource.class); return RestConstants.URI_PREFIX + res.name() + "/" + patient.getUuid(); } @Override public SimpleObject search(RequestContext requestContext) throws ResponseException { // Partial string query for searches. String query = requestContext.getParameter("q"); // If set, also search on uuid. By default uuid is skipped. boolean searchUuid = (requestContext.getParameter("searchUuid") != null); // Retrieve all patients and filter the list based on the query. List<Patient> filteredPatients = filterPatients(query, searchUuid, patientService.getAllPatients()); return getSimpleObjectWithResults(filteredPatients); } @Override public Object retrieve(String uuid, RequestContext requestContext) throws ResponseException { Patient patient = patientService.getPatientByUuid(uuid); if (patient == null) { throw new ObjectNotFoundException(); } return patientToJson(patient); } @Override public List<Representation> getAvailableRepresentations() { return Arrays.asList(Representation.DEFAULT); } private List<Patient> filterPatients(String query, boolean searchUuid, List<Patient> allPatients) { List<Patient> filteredPatients = new ArrayList<>(); // Filter patients by id, name, and MSF id. Don't use patientService.getPatients() for // this, as the behavior does not match the expected behavior from the API docs. PatientIdentifierType msfIdentifierType = patientService.getPatientIdentifierTypeByName(MSF_IDENTIFIER); for (Patient patient : allPatients) { boolean match = false; // First check the patient's full name. for (PersonName name : patient.getNames()) { if (StringUtils.containsIgnoreCase(name.getFullName(), query)) { match = true; break; } } // Short-circuit on name match. if (match) { filteredPatients.add(patient); continue; } // Next check the patient's MSF id. for (PatientIdentifier identifier : patient.getPatientIdentifiers(msfIdentifierType)) { if (StringUtils.containsIgnoreCase(identifier.getIdentifier(), query)) { match = true; break; } } if (match || (searchUuid && StringUtils.containsIgnoreCase(patient.getUuid(), query))) { filteredPatients.add(patient); } } return filteredPatients; } private SimpleObject getSimpleObjectWithResults(List<Patient> patients) { List<SimpleObject> jsonResults = new ArrayList<>(); for (Patient patient : patients) { jsonResults.add(patientToJson(patient)); } SimpleObject list = new SimpleObject(); list.add("results", jsonResults); return list; } private static LocationTag getLocationTag(String uuid, String name) { LocationService locationService = Context.getLocationService(); LocationTag tag = locationService.getLocationTagByUuid(uuid); if (tag == null) { tag = new LocationTag(); tag.setUuid(uuid); tag.setName(name); tag.setDescription(name); locationService.saveLocationTag(tag); } return tag; } private static PersonAttributeType getPersonAttributeType(String uuid, String name) { PersonService personService = Context.getPersonService(); PersonAttributeType personAttributeType = personService.getPersonAttributeTypeByUuid(uuid); if (personAttributeType == null) { personAttributeType = new PersonAttributeType(); personAttributeType.setUuid(uuid); personAttributeType.setName(name); personAttributeType.setDescription(name); personService.savePersonAttributeType(personAttributeType); } return personAttributeType; } private static Location getLocationByName(String locationName, LocationTag tag, Location parent) { LocationService locationService = Context.getLocationService(); Location location = locationService.getLocation(locationName); if (location == null) { location = new Location(); location.setName(locationName); location.setDescription(locationName); if (tag != null) { Set<LocationTag> tags = new HashSet<>(); tags.add(tag); location.setTags(tags); } if (parent != null) { location.setParentLocation(parent); } locationService.saveLocation(location); } return location; } private static String getLocationLeafName(String locationId) { LocationService locationService = Context.getLocationService(); Location location = locationService.getLocation(Integer.valueOf(locationId)); if (location != null) { // The location name is a path consisting of comma-separated components, // with each component prefixed by the tag name for that level. String locationName = location.getName(); String[] components = locationName.split(","); String leafName = components[components.length - 1].trim(); for (LocationTag tag : location.getTags()) { String tagUuid = tag.getUuid(); String tagName = tag.getName(); if (ZONE_LOCATION_TAG_UUID.equals(tagUuid) || TENT_LOCATION_TAG_UUID.equals(tagUuid) || BED_LOCATION_TAG_UUID.equals(tagUuid)) { if (leafName.startsWith(tagName)) { leafName = leafName.substring(tagName.length()).trim(); } } } return leafName; } return null; } private static Location getLocationByPath(String facilityName, String zoneName, String tentName, String bedName) { LocationTag zoneTag = getLocationTag(ZONE_LOCATION_TAG_UUID, "Zone"); LocationTag tentTag = getLocationTag(TENT_LOCATION_TAG_UUID, "Tent"); LocationTag bedTag = getLocationTag(BED_LOCATION_TAG_UUID, "Bed"); // To ensure that each Location has a unique name, construct a fully qualified // location name consisting of comma-separated components, with each component // prefixed by the tag name for that level, e.g. "Facility Kailahun, Zone 2, Tent 1" // as distinct from "Tent 1" in any other zone or facility. String facilityLocationName = null; String zoneLocationName = null; String tentLocationName = null; String bedLocationName = null; Location result = null; if (facilityName != null) { facilityLocationName = "Facility " + facilityName; Location facility = result = getLocationByName(facilityLocationName, null, null); if (zoneName != null) { zoneLocationName = facilityLocationName + ", Zone " + zoneName; Location zone = result = getLocationByName(zoneLocationName, zoneTag, facility); if (tentName != null) { tentLocationName = zoneLocationName + ", Tent " + tentName; Location tent = result = getLocationByName(tentLocationName, tentTag, zone); if (bedName != null) { bedLocationName = tentLocationName + ", Bed " + bedName; Location bed = result = getLocationByName(bedLocationName, bedTag, tent); } } } } return result; } @Override public Object update(String uuid, SimpleObject simpleObject, RequestContext requestContext) throws ResponseException { Patient patient = patientService.getPatientByUuid(uuid); if (patient == null) { throw new ObjectNotFoundException(); } String facilityName = FACILITY_NAME; String zoneName = getPersonAttributeValue(patient, assignedZoneAttrType); String tentName = getPersonAttributeValue(patient, assignedTentAttrType); String bedName = getPersonAttributeValue(patient, assignedBedAttrType); for (String key : simpleObject.keySet()) { if ("assigned_zone".equals(key)) { zoneName = (String) simpleObject.get(key); } else if ("assigned_tent".equals(key)) { tentName = (String) simpleObject.get(key); } else if ("assigned_bed".equals(key)) { bedName = (String) simpleObject.get(key); } else { throw new InvalidObjectDataException("Patient has no such property or property is not updatable: " + key); } } setPatientAssignedLocation(patient, facilityName, zoneName, tentName, bedName); return patient; } private void setPatientAssignedLocation( Patient patient, String facilityName, String zoneName, String tentName, String bedName) { if (zoneName != null) { setPersonAttributeValue(patient, assignedZoneAttrType, "" + getLocationByPath(facilityName, zoneName, null, null).getLocationId()); if (tentName != null) { setPersonAttributeValue(patient, assignedTentAttrType, "" + getLocationByPath(facilityName, zoneName, tentName, null).getLocationId()); if (bedName != null) { setPersonAttributeValue(patient, assignedBedAttrType, "" + getLocationByPath(facilityName, zoneName, tentName, bedName).getLocationId()); } } } } private static String getPersonAttributeValue(Person person, PersonAttributeType attrType) { PersonAttribute attribute = person.getAttribute(attrType); return attribute != null ? attribute.getValue() : null; } private static void setPersonAttributeValue(Person person, PersonAttributeType attrType, String value) { PersonService personService = Context.getPersonService(); PersonAttribute attribute = person.getAttribute(attrType); if (attribute == null) { attribute = new PersonAttribute(); attribute.setAttributeType(attrType); person.addAttribute(attribute); } attribute.setValue(value); personService.savePerson(person); } }
projectbuendia.openmrs/omod/src/main/java/org/openmrs/projectbuendia/webservices/rest/PatientResource.java
package org.openmrs.projectbuendia.webservices.rest; import org.apache.commons.lang3.StringUtils; import org.openmrs.*; import org.openmrs.api.*; import org.openmrs.api.context.Context; import org.openmrs.module.webservices.rest.SimpleObject; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.Resource; import org.openmrs.module.webservices.rest.web.representation.Representation; import org.openmrs.module.webservices.rest.web.resource.api.Creatable; import org.openmrs.module.webservices.rest.web.resource.api.Listable; import org.openmrs.module.webservices.rest.web.resource.api.Retrievable; import org.openmrs.module.webservices.rest.web.resource.api.Searchable; import org.openmrs.module.webservices.rest.web.resource.api.Updatable; import org.openmrs.module.webservices.rest.web.response.ObjectNotFoundException; import org.openmrs.module.webservices.rest.web.response.ResponseException; import org.projectbuendia.openmrs.webservices.rest.RestController; import java.util.*; /** * Resource for xform templates (i.e. forms without data). * Note: this is under org.openmrs as otherwise the resource annotation isn't picked up. */ @Resource(name = RestController.REST_VERSION_1_AND_NAMESPACE + "/patient", supportedClass = Patient.class, supportedOpenmrsVersions = "1.10.*") public class PatientResource implements Listable, Searchable, Retrievable, Creatable, Updatable { // Fake values private static final User CREATOR = new User(1); private static final String FACILITY_NAME = "Kailahun"; // TODO(kpy): Use a real facility name. // JSON property names private static final String ID = "id"; private static final String UUID = "uuid"; private static final String GENDER = "gender"; private static final String AGE = "age"; private static final String AGE_UNIT = "age_unit"; // "years" or "months" private static final String MONTHS_VALUE = "months"; private static final String AGE_TYPE = "type"; private static final String YEARS_VALUE = "years"; private static final String MONTHS_TYPE = "months"; private static final String YEARS_TYPE = "years"; private static final String GIVEN_NAME = "given_name"; private static final String FAMILY_NAME = "family_name"; private static final String ASSIGNED_LOCATION = "assigned_location"; private static final String ZONE = "zone"; private static final String TENT = "tent"; private static final String BED = "bed"; private static final String STATUS = "status"; // OpenMRS object names private static final String MSF_IDENTIFIER = "MSF"; private static final String EBOLA_STATUS_PROGRAM_NAME = "Ebola status program"; private static final String EBOLA_STATUS_WORKFLOW_NAME = "Ebola status workflow"; // OpenMRS object UUIDs private static final String EBOLA_STATUS_PROGRAM_UUID = "849c86fa-6f3d-11e4-b2f4-040ccecfdba4"; private static final String EBOLA_STATUS_PROGRAM_CONCEPT_UUID = "8c00e1b5-6f35-11e4-a3fa-040ccecfdba4"; private static final String EBOLA_STATUS_WORKFLOW_CONCEPT_UUID = "107f9c7a-6f3b-11e4-ba22-040ccecfdba4"; private static final String ZONE_LOCATION_TAG_UUID = "1c22989d-3b87-47d3-9459-b54aafbd1169"; private static final String TENT_LOCATION_TAG_UUID = "4c92578f-cde9-4b99-b641-f3b9e0cc268d"; private static final String BED_LOCATION_TAG_UUID = "f2cf9e4e-a197-4c44-9290-0d3dd963838e"; private static final String ASSIGNED_ZONE_PERSON_ATTRIBUTE_TYPE_UUID = "1c22989d-3b87-47d3-9459-b54aafbd1169"; private static final String ASSIGNED_TENT_PERSON_ATTRIBUTE_TYPE_UUID = "4c92578f-cde9-4b99-b641-f3b9e0cc268d"; private static final String ASSIGNED_BED_PERSON_ATTRIBUTE_TYPE_UUID = "f2cf9e4e-a197-4c44-9290-0d3dd963838e"; // The elements of each triple are: // 1. The key, which is how the status is represented in JSON. // 2. The concept name, which is a short phrase to avoid collision with other concepts. // 3. The UUID of the ProgramWorkflowState that represents the status. private static final String[][] EBOLA_STATUS_KEYS_NAMES_AND_UUIDS = { {"SUSPECTED_CASE", "suspected ebola case", "041a7b80-6f13-11e4-b6d3-040ccecfdba4"}, {"PROBABLE_CASE", "probable ebola case", "0ae8fd9c-6f13-11e4-9ad7-040ccecfdba4"}, {"CONFIRMED_CASE", "confirmed ebola case", "11a8a9c0-6f13-11e4-8c91-040ccecfdba4"}, {"NON_CASE", "not an ebola case", "b517037a-6f13-11e4-b5f2-040ccecfdba4"}, {"CONVALESCENT", "convalescing at ebola facility", "c1349bd7-6f13-11e4-b315-040ccecfdba4"}, {"READY_FOR_DISCHARGE", "ready for discharge from ebola facility", "e45ef19e-6f13-11e4-b630-040ccecfdba4"}, {"DISCHARGED", "discharged from ebola facility", "e4a20c4a-6f13-11e4-b315-040ccecfdba4"}, {"SUSPECTED_DEAD", "suspected death at ebola facility", "e4c09b7d-6f13-11e4-b315-040ccecfdba4"}, {"CONFIRMED_DEAD", "confirmed death at ebola facility", "e4da31e1-6f13-11e4-b315-040ccecfdba4"}, }; private static Map<String, String> EBOLA_STATUS_KEYS_BY_UUID = new HashMap<>(); private static Map<String, String> EBOLA_STATUS_UUIDS_BY_KEY = new HashMap<>(); static { for (String[] keyNameUuid : EBOLA_STATUS_KEYS_NAMES_AND_UUIDS) { EBOLA_STATUS_KEYS_BY_UUID.put(keyNameUuid[2], keyNameUuid[0]); EBOLA_STATUS_UUIDS_BY_KEY.put(keyNameUuid[0], keyNameUuid[2]); } } private final PatientService patientService; private final PersonAttributeType assignedZoneAttrType; private final PersonAttributeType assignedTentAttrType; private final PersonAttributeType assignedBedAttrType; public PatientResource() { patientService = Context.getPatientService(); assignedZoneAttrType = getPersonAttributeType( ASSIGNED_ZONE_PERSON_ATTRIBUTE_TYPE_UUID, "assigned_zone"); assignedTentAttrType = getPersonAttributeType( ASSIGNED_TENT_PERSON_ATTRIBUTE_TYPE_UUID, "assigned_tent"); assignedBedAttrType = getPersonAttributeType( ASSIGNED_BED_PERSON_ATTRIBUTE_TYPE_UUID, "assigned_bed"); } @Override public SimpleObject getAll(RequestContext requestContext) throws ResponseException { List<Patient> patients = patientService.getAllPatients(); return getSimpleObjectWithResults(patients); } /** * Converts a date to a year with a fractional part, e.g. Jan 1, 1970 * becomes 1970.0; Jul 1, 1970 becomes approximately 1970.5. */ private double dateToFractionalYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); double daysInYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR); return calendar.get(Calendar.YEAR) + calendar.get(Calendar.DAY_OF_YEAR) / daysInYear; } private Date fractionalYearToDate(double year) { int yearInt = (int) Math.floor(year); double yearFrac = year - yearInt; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, yearInt); calendar.set(Calendar.DAY_OF_YEAR, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long millis = calendar.getTimeInMillis(); int daysInYear = calendar.getActualMaximum(Calendar.DAY_OF_YEAR); millis += yearFrac * daysInYear * 24 * 3600 * 1000; return new Date(millis); } /** Estimate the age of a person in years, given their birthdate. */ private double birthDateToAge(Date birthDate) { return dateToFractionalYear(new Date()) - dateToFractionalYear(birthDate); } private SimpleObject patientToJson(Patient patient) { SimpleObject jsonForm = new SimpleObject(); if (patient != null) { jsonForm.add(UUID, patient.getUuid()); PatientIdentifier patientIdentifier = patient.getPatientIdentifier(getMsfIdentifierType()); if (patientIdentifier != null) { jsonForm.add(ID, patientIdentifier.getIdentifier()); } jsonForm.add(GENDER, patient.getGender()); double age = birthDateToAge(patient.getBirthdate()); SimpleObject ageObject = new SimpleObject(); if (age < 1.0) { ageObject.add(MONTHS_VALUE, (int) Math.floor(age * 12)); ageObject.add(AGE_TYPE, MONTHS_TYPE); } else { ageObject.add(YEARS_VALUE, (int) Math.floor(age)); ageObject.add(AGE_TYPE, YEARS_TYPE); } jsonForm.add(AGE, ageObject); jsonForm.add(GIVEN_NAME, patient.getGivenName()); jsonForm.add(FAMILY_NAME, patient.getFamilyName()); String assignedZoneId = getPersonAttributeValue(patient, assignedZoneAttrType); String assignedTentId = getPersonAttributeValue(patient, assignedTentAttrType); String assignedBedId = getPersonAttributeValue(patient, assignedBedAttrType); if (assignedZoneId != null || assignedTentId != null || assignedBedId != null) { SimpleObject location = new SimpleObject(); if (assignedZoneId != null) { location.add(ZONE, getLocationLeafName(assignedZoneId)); } if (assignedTentId != null) { location.add(TENT, getLocationLeafName(assignedTentId)); } if (assignedBedId != null) { location.add(BED, getLocationLeafName(assignedBedId)); } jsonForm.add(ASSIGNED_LOCATION, location); } PatientProgram patientProgram = getEbolaStatusPatientProgram(patient); PatientState patientState = patientProgram.getCurrentState( getEbolaStatusProgramWorkflow()); if (patientState != null) { jsonForm.add(STATUS, getKeyByState(patientState.getState())); } jsonForm.add("created_timestamp_utc", patient.getDateCreated().getTime()); } return jsonForm; } @Override public Object create(SimpleObject simpleObject, RequestContext requestContext) throws ResponseException { // We really want this to use XForms, but lets have a simple default implementation for early testing if (!simpleObject.containsKey(ID)) { throw new InvalidObjectDataException("JSON object lacks required \"id\" field"); } PatientIdentifierType identifierType = getMsfIdentifierType(); ArrayList<PatientIdentifierType> identifierTypes = new ArrayList<>(); identifierTypes.add(identifierType); String id = (String) simpleObject.get(ID); List<Patient> existing = patientService.getPatients(null, id, identifierTypes, true /* exact identifier match */); if (!existing.isEmpty()) { throw new InvalidObjectDataException("Patient with this ID already exists: " + id); } Patient patient = new Patient(); // TODO(nfortescue): do this properly from authentication patient.setCreator(CREATOR); patient.setDateCreated(new Date()); if (simpleObject.containsKey(GENDER)) { patient.setGender((String) simpleObject.get(GENDER)); } if (simpleObject.containsKey(AGE)) { double number = ((Number) simpleObject.get(AGE)).doubleValue(); if ("months".equals(simpleObject.get(AGE_UNIT))) { long millis = (long) Math.floor( new Date().getTime() - number * 365.24 / 12 * 24 * 3600 * 1000); patient.setBirthdate(new Date(millis)); } else { // default to years patient.setBirthdate(fractionalYearToDate( dateToFractionalYear(new Date()) - number)); } } PersonName pn = new PersonName(); if (simpleObject.containsKey(GIVEN_NAME)) { pn.setGivenName((String) simpleObject.get(GIVEN_NAME)); } if (simpleObject.containsKey(FAMILY_NAME)) { pn.setFamilyName((String) simpleObject.get(FAMILY_NAME)); } pn.setCreator(patient.getCreator()); pn.setDateCreated(patient.getDateCreated()); patient.addName(pn); // Identifier with fake location PatientIdentifier identifier = new PatientIdentifier(); identifier.setCreator(patient.getCreator()); identifier.setDateCreated(patient.getDateCreated()); identifier.setIdentifier(id); identifier.setLocation(getLocationByName(FACILITY_NAME, null, null)); identifier.setIdentifierType(identifierType); identifier.setPreferred(true); patient.addIdentifier(identifier); // Assigned zone, tent, and bed (convert integer 2 to string "2") setPatientAssignedLocation(patient, FACILITY_NAME, "" + simpleObject.get("assigned_zone"), "" + simpleObject.get("assigned_tent"), "" + simpleObject.get("assigned_bed")); patientService.savePatient(patient); // Status if (simpleObject.containsKey(STATUS)) { ProgramWorkflowState workflowState = getStateByKey((String) simpleObject.get(STATUS)); if (workflowState != null) { ProgramWorkflowService workflowService = Context.getProgramWorkflowService(); PatientProgram patientProgram = getEbolaStatusPatientProgram(patient); patientProgram.transitionToState(workflowState, new Date()); workflowService.savePatientProgram(patientProgram); patientService.savePatient(patient); } } return patientToJson(patient); } private PatientIdentifierType getMsfIdentifierType() { PatientIdentifierType identifierType = patientService.getPatientIdentifierTypeByName(MSF_IDENTIFIER); if (identifierType == null) { identifierType = new PatientIdentifierType(); identifierType.setName(MSF_IDENTIFIER); identifierType.setDescription("MSF patient identifier"); identifierType.setFormatDescription("[facility code].[patient number]"); patientService.savePatientIdentifierType(identifierType); } return identifierType; } public static Concept getConcept(String name, String uuid, String typeUuid) { ConceptService conceptService = Context.getConceptService(); Concept concept = conceptService.getConceptByUuid(uuid); if (concept == null) { concept = new Concept(); concept.setUuid(uuid); concept.setShortName(new ConceptName(name, new Locale("en"))); concept.setDatatype(conceptService.getConceptDatatypeByUuid(typeUuid)); concept.setConceptClass(conceptService.getConceptClassByUuid(ConceptClass.MISC_UUID)); conceptService.saveConcept(concept); } return concept; } /** Get the key (e.g. "confirmed") for an ebola status by workflow state. */ private String getKeyByState(ProgramWorkflowState state) { return EBOLA_STATUS_KEYS_BY_UUID.get(state.getConcept().getUuid()); } /** Get the workflow state for an ebola status by key (e.g. "suspected"). */ private ProgramWorkflowState getStateByKey(String key) { ProgramWorkflow workflow = getEbolaStatusProgramWorkflow(); ConceptService conceptService = Context.getConceptService(); String uuid = EBOLA_STATUS_UUIDS_BY_KEY.get(key); return uuid == null ? null : workflow.getState(conceptService.getConceptByUuid(uuid)); } private ProgramWorkflow getEbolaStatusProgramWorkflow() { ProgramWorkflow workflow = null; for (ProgramWorkflow w : getEbolaStatusProgram().getWorkflows()) { workflow = w; } return workflow; } /** * Get the "Ebola status" Program, creating the Program if it doesn't exist yet * (including its ProgramWorkflow, the workflow's ProgramWorkflowStates, and the * Concepts corresponding to those states). */ public static Program getEbolaStatusProgram() { ProgramWorkflowService workflowService = Context.getProgramWorkflowService(); Program program = workflowService.getProgramByUuid(EBOLA_STATUS_PROGRAM_UUID); if (program == null) { program = new Program(); program.setName(EBOLA_STATUS_PROGRAM_NAME); program.setUuid(EBOLA_STATUS_PROGRAM_UUID); program.setDescription(EBOLA_STATUS_PROGRAM_NAME); program.setConcept(getConcept(EBOLA_STATUS_PROGRAM_NAME, EBOLA_STATUS_PROGRAM_CONCEPT_UUID, ConceptDatatype.N_A_UUID)); workflowService.saveProgram(program); } Set<ProgramWorkflow> workflows = program.getWorkflows(); if (workflows.isEmpty()) { ProgramWorkflow workflow = new ProgramWorkflow(); workflow.setName(EBOLA_STATUS_WORKFLOW_NAME); workflow.setDescription(EBOLA_STATUS_WORKFLOW_NAME); workflow.setConcept(getConcept(EBOLA_STATUS_WORKFLOW_NAME, EBOLA_STATUS_WORKFLOW_CONCEPT_UUID, ConceptDatatype.N_A_UUID)); workflow.setProgram(program); for (String[] keyNameUuid : EBOLA_STATUS_KEYS_NAMES_AND_UUIDS) { ProgramWorkflowState state = new ProgramWorkflowState(); state.setConcept(getConcept(keyNameUuid[1], keyNameUuid[2], ConceptDatatype.CODED_UUID)); state.setName(keyNameUuid[1]); state.setInitial(false); state.setTerminal(false); workflow.addState(state); } program.addWorkflow(workflow); workflowService.saveProgram(program); } return program; } /** * Get the PatientProgram associating this Patient with the "Ebola status" Program, * creating the PatientProgram if it doesn't exist yet. */ public static PatientProgram getEbolaStatusPatientProgram(Patient patient) { ProgramWorkflowService workflowService = Context.getProgramWorkflowService(); Program program = getEbolaStatusProgram(); List<PatientProgram> patientPrograms = workflowService.getPatientPrograms(patient, program, null, null, null, null, false); PatientProgram patientProgram; if (patientPrograms.isEmpty()) { patientProgram = new PatientProgram(); patientProgram.setPatient(patient); patientProgram.setProgram(program); workflowService.savePatientProgram(patientProgram); } else { patientProgram = patientPrograms.get(0); } return patientProgram; } @Override public String getUri(Object instance) { Patient patient = (Patient) instance; Resource res = getClass().getAnnotation(Resource.class); return RestConstants.URI_PREFIX + res.name() + "/" + patient.getUuid(); } @Override public SimpleObject search(RequestContext requestContext) throws ResponseException { // Partial string query for searches. String query = requestContext.getParameter("q"); // If set, also search on uuid. By default uuid is skipped. boolean searchUuid = (requestContext.getParameter("searchUuid") != null); // Retrieve all patients and filter the list based on the query. List<Patient> filteredPatients = filterPatients(query, searchUuid, patientService.getAllPatients()); return getSimpleObjectWithResults(filteredPatients); } @Override public Object retrieve(String uuid, RequestContext requestContext) throws ResponseException { Patient patient = patientService.getPatientByUuid(uuid); if (patient == null) { throw new ObjectNotFoundException(); } return patientToJson(patient); } @Override public List<Representation> getAvailableRepresentations() { return Arrays.asList(Representation.DEFAULT); } private List<Patient> filterPatients(String query, boolean searchUuid, List<Patient> allPatients) { List<Patient> filteredPatients = new ArrayList<>(); // Filter patients by id, name, and MSF id. Don't use patientService.getPatients() for // this, as the behavior does not match the expected behavior from the API docs. PatientIdentifierType msfIdentifierType = patientService.getPatientIdentifierTypeByName(MSF_IDENTIFIER); for (Patient patient : allPatients) { boolean match = false; // First check the patient's full name. for (PersonName name : patient.getNames()) { if (StringUtils.containsIgnoreCase(name.getFullName(), query)) { match = true; break; } } // Short-circuit on name match. if (match) { filteredPatients.add(patient); continue; } // Next check the patient's MSF id. for (PatientIdentifier identifier : patient.getPatientIdentifiers(msfIdentifierType)) { if (StringUtils.containsIgnoreCase(identifier.getIdentifier(), query)) { match = true; break; } } if (match || (searchUuid && StringUtils.containsIgnoreCase(patient.getUuid(), query))) { filteredPatients.add(patient); } } return filteredPatients; } private SimpleObject getSimpleObjectWithResults(List<Patient> patients) { List<SimpleObject> jsonResults = new ArrayList<>(); for (Patient patient : patients) { jsonResults.add(patientToJson(patient)); } SimpleObject list = new SimpleObject(); list.add("results", jsonResults); return list; } private static LocationTag getLocationTag(String uuid, String name) { LocationService locationService = Context.getLocationService(); LocationTag tag = locationService.getLocationTagByUuid(uuid); if (tag == null) { tag = new LocationTag(); tag.setUuid(uuid); tag.setName(name); tag.setDescription(name); locationService.saveLocationTag(tag); } return tag; } private static PersonAttributeType getPersonAttributeType(String uuid, String name) { PersonService personService = Context.getPersonService(); PersonAttributeType personAttributeType = personService.getPersonAttributeTypeByUuid(uuid); if (personAttributeType == null) { personAttributeType = new PersonAttributeType(); personAttributeType.setUuid(uuid); personAttributeType.setName(name); personAttributeType.setDescription(name); personService.savePersonAttributeType(personAttributeType); } return personAttributeType; } private static Location getLocationByName(String locationName, LocationTag tag, Location parent) { LocationService locationService = Context.getLocationService(); Location location = locationService.getLocation(locationName); if (location == null) { location = new Location(); location.setName(locationName); location.setDescription(locationName); if (tag != null) { Set<LocationTag> tags = new HashSet<>(); tags.add(tag); location.setTags(tags); } if (parent != null) { location.setParentLocation(parent); } locationService.saveLocation(location); } return location; } private static String getLocationLeafName(String locationId) { LocationService locationService = Context.getLocationService(); Location location = locationService.getLocation(Integer.valueOf(locationId)); if (location != null) { // The location name is a path consisting of comma-separated components, // with each component prefixed by the tag name for that level. String locationName = location.getName(); String[] components = locationName.split(","); String leafName = components[components.length - 1].trim(); for (LocationTag tag : location.getTags()) { String tagUuid = tag.getUuid(); String tagName = tag.getName(); if (ZONE_LOCATION_TAG_UUID.equals(tagUuid) || TENT_LOCATION_TAG_UUID.equals(tagUuid) || BED_LOCATION_TAG_UUID.equals(tagUuid)) { if (leafName.startsWith(tagName)) { leafName = leafName.substring(tagName.length()).trim(); } } } return leafName; } return null; } private static Location getLocationByPath(String facilityName, String zoneName, String tentName, String bedName) { LocationTag zoneTag = getLocationTag(ZONE_LOCATION_TAG_UUID, "Zone"); LocationTag tentTag = getLocationTag(TENT_LOCATION_TAG_UUID, "Tent"); LocationTag bedTag = getLocationTag(BED_LOCATION_TAG_UUID, "Bed"); // To ensure that each Location has a unique name, construct a fully qualified // location name consisting of comma-separated components, with each component // prefixed by the tag name for that level, e.g. "Facility Kailahun, Zone 2, Tent 1" // as distinct from "Tent 1" in any other zone or facility. String facilityLocationName = null; String zoneLocationName = null; String tentLocationName = null; String bedLocationName = null; Location result = null; if (facilityName != null) { facilityLocationName = "Facility " + facilityName; Location facility = result = getLocationByName(facilityLocationName, null, null); if (zoneName != null) { zoneLocationName = facilityLocationName + ", Zone " + zoneName; Location zone = result = getLocationByName(zoneLocationName, zoneTag, facility); if (tentName != null) { tentLocationName = zoneLocationName + ", Tent " + tentName; Location tent = result = getLocationByName(tentLocationName, tentTag, zone); if (bedName != null) { bedLocationName = tentLocationName + ", Bed " + bedName; Location bed = result = getLocationByName(bedLocationName, bedTag, tent); } } } } return result; } @Override public Object update(String uuid, SimpleObject simpleObject, RequestContext requestContext) throws ResponseException { Patient patient = patientService.getPatientByUuid(uuid); if (patient == null) { throw new ObjectNotFoundException(); } String facilityName = FACILITY_NAME; String zoneName = getPersonAttributeValue(patient, assignedZoneAttrType); String tentName = getPersonAttributeValue(patient, assignedTentAttrType); String bedName = getPersonAttributeValue(patient, assignedBedAttrType); for (String key : simpleObject.keySet()) { if ("assigned_zone".equals(key)) { zoneName = (String) simpleObject.get(key); } else if ("assigned_tent".equals(key)) { tentName = (String) simpleObject.get(key); } else if ("assigned_bed".equals(key)) { bedName = (String) simpleObject.get(key); } else { throw new InvalidObjectDataException("Patient has no such property or property is not updatable: " + key); } } setPatientAssignedLocation(patient, facilityName, zoneName, tentName, bedName); return patient; } private void setPatientAssignedLocation( Patient patient, String facilityName, String zoneName, String tentName, String bedName) { if (zoneName != null) { setPersonAttributeValue(patient, assignedZoneAttrType, "" + getLocationByPath(facilityName, zoneName, null, null).getLocationId()); if (tentName != null) { setPersonAttributeValue(patient, assignedTentAttrType, "" + getLocationByPath(facilityName, zoneName, tentName, null).getLocationId()); if (bedName != null) { setPersonAttributeValue(patient, assignedBedAttrType, "" + getLocationByPath(facilityName, zoneName, tentName, bedName).getLocationId()); } } } } private static String getPersonAttributeValue(Person person, PersonAttributeType attrType) { PersonAttribute attribute = person.getAttribute(attrType); return attribute != null ? attribute.getValue() : null; } private static void setPersonAttributeValue(Person person, PersonAttributeType attrType, String value) { PersonService personService = Context.getPersonService(); PersonAttribute attribute = person.getAttribute(attrType); if (attribute == null) { attribute = new PersonAttribute(); attribute.setAttributeType(attrType); person.addAttribute(attribute); } attribute.setValue(value); personService.savePerson(person); } }
Fix new status keys.
projectbuendia.openmrs/omod/src/main/java/org/openmrs/projectbuendia/webservices/rest/PatientResource.java
Fix new status keys.
<ide><path>rojectbuendia.openmrs/omod/src/main/java/org/openmrs/projectbuendia/webservices/rest/PatientResource.java <ide> {"CONVALESCENT", "convalescing at ebola facility", "c1349bd7-6f13-11e4-b315-040ccecfdba4"}, <ide> {"READY_FOR_DISCHARGE", "ready for discharge from ebola facility", "e45ef19e-6f13-11e4-b630-040ccecfdba4"}, <ide> {"DISCHARGED", "discharged from ebola facility", "e4a20c4a-6f13-11e4-b315-040ccecfdba4"}, <del> {"SUSPECTED_DEAD", "suspected death at ebola facility", "e4c09b7d-6f13-11e4-b315-040ccecfdba4"}, <del> {"CONFIRMED_DEAD", "confirmed death at ebola facility", "e4da31e1-6f13-11e4-b315-040ccecfdba4"}, <add> {"SUSPECTED_DEATH", "suspected death at ebola facility", "e4c09b7d-6f13-11e4-b315-040ccecfdba4"}, <add> {"CONFIRMED_DEATH", "confirmed death at ebola facility", "e4da31e1-6f13-11e4-b315-040ccecfdba4"}, <ide> }; <ide> private static Map<String, String> EBOLA_STATUS_KEYS_BY_UUID = new HashMap<>(); <ide> private static Map<String, String> EBOLA_STATUS_UUIDS_BY_KEY = new HashMap<>();
Java
apache-2.0
0094754a55a31ebf96878613659b3a5011435b76
0
wso2/carbon-uuf,this/carbon-uuf,this/carbon-uuf,Shan1024/carbon-uuf,sajithar/carbon-uuf,Shan1024/carbon-uuf,sajithar/carbon-uuf,wso2/carbon-uuf,wso2/carbon-uuf,Shan1024/carbon-uuf,wso2/carbon-uuf,this/carbon-uuf,Shan1024/carbon-uuf,this/carbon-uuf
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.carbon.uuf.api; import org.wso2.carbon.uuf.exception.InvalidTypeException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; /** * Represents a Configuration object of a particular UUF component. */ public class Configuration extends HashMap<String, Object> { // TODO: 6/8/16 Cache values of 'contextPath', 'theme', 'loginPageUri', 'menu', 'errorPages' configs public static final String KEY_CONTEXT_PATH = "contextPath"; public static final String KEY_THEME = "theme"; public static final String KEY_LOGIN_PAGE_URI = "loginPageUri"; public static final String KEY_MENU = "menu"; public static final String KEY_ERROR_PAGES = "errorPages"; public Configuration(Map<?, ?> rawMap) { this(rawMap.size()); merge(rawMap); } private Configuration(int initialCapacity) { super(initialCapacity); } public Optional<String> getContextPath() { Object contextPathObj = get(KEY_CONTEXT_PATH); if (contextPathObj == null) { return Optional.<String>empty(); } if (!(contextPathObj instanceof String)) { throw new InvalidTypeException( "Value of 'contextPath' in the app configuration must be a string. Instead found '" + contextPathObj.getClass().getName() + "'."); } String contextPath = (String) contextPathObj; if (contextPath.isEmpty()) { throw new IllegalArgumentException("Value of 'contextPath' in the app configuration cannot be empty."); } else if (contextPath.charAt(0) != '/') { throw new IllegalArgumentException("Value of 'contextPath' in the app configuration must start with '/'."); } return Optional.of(contextPath); } public Optional<String> getThemeName() { Object themeNameObj = get(KEY_THEME); if (themeNameObj == null) { return Optional.<String>empty(); } if (!(themeNameObj instanceof String)) { throw new InvalidTypeException( "Value of 'theme' in the app configuration must be a string. Instead found '" + themeNameObj.getClass().getName() + "'."); } String themeName = (String) themeNameObj; if (themeName.isEmpty()) { throw new IllegalArgumentException("Value of 'theme' in the app configuration cannot be empty."); } return Optional.of(themeName); } public Optional<String> getLoginPageUri() { Object loginPageUriObj = get(KEY_LOGIN_PAGE_URI); if (loginPageUriObj == null) { return Optional.<String>empty(); } if (!(loginPageUriObj instanceof String)) { throw new InvalidTypeException( "Value of 'loginPageUri' in the app configuration must be a string. Instead found '" + loginPageUriObj.getClass().getName() + "'."); } String loginPageUri = (String) loginPageUriObj; if (loginPageUri.isEmpty()) { throw new IllegalArgumentException("Value of 'loginPageUri' in the app configuration cannot be empty."); } if (loginPageUri.charAt(0) == '/') { throw new IllegalArgumentException( "Value of 'loginPageUri' in the app configuration must start with a '/'. Instead found '" + loginPageUri.charAt(0) + "' at the beginning."); } return Optional.of(loginPageUri); } /** * Returns the list of menu-items of the menu identified by the given {@code name}. If there is no menu associated * with the given name, then an {@code null} is returned. * * @param name name of the menu * @return menu-items */ @SuppressWarnings("unchecked") public Map<String, Map> getMenu(String name) { // Validate menu property. Object menuObj = super.get(KEY_MENU); if (menuObj == null) { return Collections.<String, Map>emptyMap(); } else if (!(menuObj instanceof Map)) { throw new InvalidTypeException( "Value of 'menu' in the configurations must be a Map<String, Map>. Instead found " + menuObj.getClass().getName() + "."); } // Validate requested menu. Object menuMapObj = ((Map) menuObj).get(name); if (menuMapObj == null) { return Collections.<String, Map>emptyMap(); } else if (!(menuMapObj instanceof Map)) { throw new InvalidTypeException("Menu '" + name + "' must be a Map<String, Map>. Instead found " + menuObj.getClass().getName() + "."); } Map<?, ?> menuMap = (Map) menuMapObj; // Validate menu items. for (Map.Entry entry : menuMap.entrySet()) { if (!(entry.getKey() instanceof String)) { throw new InvalidTypeException("Menu '" + name + "' must be a Map<String, Map>. Instead found a '" + entry.getKey().getClass().getName() + "' key."); } if (!(entry.getValue() instanceof Map)) { throw new InvalidTypeException("Menu '" + name + "' must be a Map<String, Map>. Instead found a '" + entry.getValue().getClass().getName() + "' value at key '" + entry.getKey() + "'."); } } return (Map<String, Map>) menuMap; } @SuppressWarnings("unchecked") public Map<String, String> getErrorPages() { Object errorPagesObj = get(KEY_ERROR_PAGES); if (errorPagesObj == null) { return Collections.<String, String>emptyMap(); } if (errorPagesObj instanceof Map) { Map<?, ?> errorPagesMap = (Map) errorPagesObj; for (Entry<?, ?> entry : errorPagesMap.entrySet()) { if (!(entry.getKey() instanceof String)) { throw new InvalidTypeException( "Value of 'errorPages' in the app configuration must be a Map<String, String>." + " Instead found a '" + entry.getKey().getClass().getName() + "' key."); } if (!(entry.getValue() instanceof String)) { throw new InvalidTypeException( "Value of 'errorPages' in the app configuration must be a Map<String, String> " + "Instead found a '" + entry.getValue().getClass().getName() + "' value at key '" + entry.getKey() + "'."); } } return (Map<String, String>) errorPagesMap; } else { throw new InvalidTypeException( "Value of 'errorPages' in the app configuration must be a Map<String, String>. " + "Instead found '" + errorPagesObj.getClass().getName() + "'."); } } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object putIfAbsent(String key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object replace(String key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public boolean replace(String key, Object oldValue, Object newValue) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public void replaceAll(BiFunction<? super String, ? super Object, ?> function) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object compute(String key, BiFunction<? super String, ? super Object, ?> remappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object computeIfPresent(String key, BiFunction<? super String, ? super Object, ?> remappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object computeIfAbsent(String key, Function<? super String, ?> mappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object merge(String key, Object value, BiFunction<? super Object, ? super Object, ?> remappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } public void merge(Map<?, ?> rawMap) { // TODO: 7/7/16 lock configuration after deploying the app for (Entry<?, ?> entry : rawMap.entrySet()) { if (entry.getKey() instanceof String) { super.compute((String) entry.getKey(), (key, oldValue) -> { Object newValue = entry.getValue(); if (oldValue == null) { return newValue; // Add the new value. } if (newValue instanceof Map && oldValue instanceof Map) { return deepMergeMap((Map) oldValue, (Map) newValue); } else if (newValue instanceof List && oldValue instanceof List) { return deepMergeList((List) oldValue, (List) newValue); } return newValue; // Cannot merge if not a Map or a List, hence replace with the new value. }); } else { throw new InvalidTypeException("Configurations must be a Map<String, Object>. Instead found a '" + entry.getKey().getClass().getName() + "' key."); } } } @SuppressWarnings("unchecked") private static Map deepMergeMap(Map oldMap, Map newMap) { for (Object key : newMap.keySet()) { Object newValueObj = newMap.get(key); Object oldValueObj = oldMap.get(key); if (oldValueObj instanceof Map && newValueObj instanceof Map) { oldMap.put(key, deepMergeMap((Map) oldValueObj, (Map) newValueObj)); } else if (oldValueObj instanceof List && newValueObj instanceof List) { oldMap.put(key, deepMergeList((List) oldValueObj, (List) newValueObj)); } else { oldMap.put(key, newValueObj); } } return oldMap; } @SuppressWarnings("unchecked") private static List deepMergeList(List oldList, List newList) { for (Object newItemObj : newList) { int oldIndex = oldList.indexOf(newItemObj); if (oldIndex != -1) { Object oldItemObj = oldList.get(oldIndex); if (oldItemObj instanceof List && newItemObj instanceof List) { oldList.set(oldIndex, deepMergeList((List) oldItemObj, (List) newItemObj)); } else if (oldItemObj instanceof Map && newItemObj instanceof Map) { oldList.set(oldIndex, deepMergeMap((Map) oldItemObj, (Map) newItemObj)); } else { oldList.set(oldIndex, newItemObj); } } else { oldList.add(newItemObj); } } return oldList; } public static Configuration emptyConfiguration() { return new Configuration(0); } }
components/uuf-core/src/main/java/org/wso2/carbon/uuf/api/Configuration.java
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.carbon.uuf.api; import org.wso2.carbon.uuf.exception.InvalidTypeException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; /** * Represents a Configuration object of a particular UUF component. */ public class Configuration extends HashMap<String, Object> { // TODO: 6/8/16 Cache values of 'contextPath', 'theme', 'loginPageUri', 'menu', 'errorPages' configs public static final String KEY_CONTEXT_PATH = "contextPath"; public static final String KEY_THEME = "theme"; public static final String KEY_LOGIN_PAGE_URI = "loginPageUri"; public static final String KEY_MENU = "menu"; public static final String KEY_ERROR_PAGES = "errorPages"; public Configuration(Map<?, ?> rawMap) { this(rawMap.size()); merge(rawMap); } private Configuration(int initialCapacity) { super(initialCapacity); } public Optional<String> getContextPath() { Object contextPathObj = get(KEY_CONTEXT_PATH); if (contextPathObj == null) { return Optional.<String>empty(); } if (!(contextPathObj instanceof String)) { throw new InvalidTypeException( "Value of 'contextPath' in the app configuration must be a string. Instead found '" + contextPathObj.getClass().getName() + "'."); } String contextPath = (String) contextPathObj; if (contextPath.isEmpty()) { throw new IllegalArgumentException("Value of 'contextPath' in the app configuration cannot be empty."); } else if (contextPath.charAt(0) != '/') { throw new IllegalArgumentException("Value of 'contextPath' in the app configuration must start with '/'."); } return Optional.of(contextPath); } public Optional<String> getThemeName() { Object themeNameObj = get(KEY_THEME); if (themeNameObj == null) { return Optional.<String>empty(); } if (!(themeNameObj instanceof String)) { throw new InvalidTypeException( "Value of 'theme' in the app configuration must be a string. Instead found '" + themeNameObj.getClass().getName() + "'."); } String themeName = (String) themeNameObj; if (themeName.isEmpty()) { throw new IllegalArgumentException("Value of 'theme' in the app configuration cannot be empty."); } return Optional.of(themeName); } public Optional<String> getLoginPageUri() { Object loginPageUriObj = get(KEY_LOGIN_PAGE_URI); if (loginPageUriObj == null) { return Optional.<String>empty(); } if (!(loginPageUriObj instanceof String)) { throw new InvalidTypeException( "Value of 'loginPageUri' in the app configuration must be a string. Instead found '" + loginPageUriObj.getClass().getName() + "'."); } String loginPageUri = (String) loginPageUriObj; if (loginPageUri.isEmpty()) { throw new IllegalArgumentException("Value of 'loginPageUri' in the app configuration cannot be empty."); } if (loginPageUri.charAt(0) == '/') { throw new IllegalArgumentException( "Value of 'loginPageUri' in the app configuration must start with a '/'. Instead found '" + loginPageUri.charAt(0) + "' at the beginning."); } return Optional.of(loginPageUri); } /** * Returns the list of menu-items of the menu identified by the given {@code name}. If there is no menu associated * with the given name, then an {@code null} is returned. * * @param name name of the menu * @return menu-items */ @SuppressWarnings("unchecked") public Map<String, Map> getMenu(String name) { // Validate menu property. Object menuObj = super.get(KEY_MENU); if (menuObj == null) { return Collections.<String, Map>emptyMap(); } else if (!(menuObj instanceof Map)) { throw new InvalidTypeException( "Value of 'menu' in the configurations must be a Map<String, Map>. Instead found " + menuObj.getClass().getName() + "."); } // Validate requested menu. Object menuMapObj = ((Map) menuObj).get(name); if (menuMapObj == null) { return Collections.<String, Map>emptyMap(); } else if (!(menuMapObj instanceof Map)) { throw new InvalidTypeException("Menu '" + name + "' must be a Map<String, Map>. Instead found " + menuObj.getClass().getName() + "."); } Map<?, ?> menuMap = (Map) menuMapObj; // Validate menu items. for (Map.Entry entry : menuMap.entrySet()) { if (!(entry.getKey() instanceof String)) { throw new InvalidTypeException("Menu '" + name + "' must be a Map<String, Map>. Instead found a '" + entry.getKey().getClass().getName() + "' key."); } if (!(entry.getValue() instanceof Map)) { throw new InvalidTypeException("Menu '" + name + "' must be a Map<String, Map>. Instead found a '" + entry.getValue().getClass().getName() + "' value at key '" + entry.getKey() + "'."); } } return (Map<String, Map>) menuMap; } @SuppressWarnings("unchecked") public Map<String, String> getErrorPages() { Object errorPagesObj = get(KEY_ERROR_PAGES); if (errorPagesObj == null) { return Collections.<String, String>emptyMap(); } if (errorPagesObj instanceof Map) { Map<?, ?> errorPagesMap = (Map) errorPagesObj; for (Entry<?, ?> entry : errorPagesMap.entrySet()) { if (!(entry.getKey() instanceof String)) { throw new InvalidTypeException( "Value of 'errorPages' in the app configuration must be a Map<String, String>." + " Instead found a '" + entry.getKey().getClass().getName() + "' key."); } if (!(entry.getValue() instanceof String)) { throw new InvalidTypeException( "Value of 'errorPages' in the app configuration must be a Map<String, String> " + "Instead found a '" + entry.getValue().getClass().getName() + "' value at key '" + entry.getKey() + "'."); } } return (Map<String, String>) errorPagesMap; } else { throw new InvalidTypeException( "Value of 'errorPages' in the app configuration must be a Map<String, String>. " + "Instead found '" + errorPagesObj.getClass().getName() + "'."); } } public String getAsString(String key) { Object value = super.get(key); if ((value == null) || (value instanceof String)) { return (String) value; } else { throw new InvalidTypeException( "Value of '" + key + "' in the configuration must be a string. Instead found '" + value.getClass().getName() + "'."); } } public String getAsStringOrDefault(String key, String defaultValue) { String value = getAsString(key); return (value == null) ? defaultValue : value; } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object putIfAbsent(String key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object replace(String key, Object value) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public boolean replace(String key, Object oldValue, Object newValue) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public void replaceAll(BiFunction<? super String, ? super Object, ?> function) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object compute(String key, BiFunction<? super String, ? super Object, ?> remappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object computeIfPresent(String key, BiFunction<? super String, ? super Object, ?> remappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object computeIfAbsent(String key, Function<? super String, ?> mappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } @Override public Object merge(String key, Object value, BiFunction<? super Object, ? super Object, ?> remappingFunction) { throw new UnsupportedOperationException("Cannot change Configuration."); } public void merge(Map<?, ?> rawMap) { // TODO: 7/7/16 lock configuration after deploying the app for (Entry<?, ?> entry : rawMap.entrySet()) { if (entry.getKey() instanceof String) { super.compute((String) entry.getKey(), (key, oldValue) -> { Object newValue = entry.getValue(); if (oldValue == null) { return newValue; // Add the new value. } if (newValue instanceof Map && oldValue instanceof Map) { return deepMergeMap((Map) oldValue, (Map) newValue); } else if (newValue instanceof List && oldValue instanceof List) { return deepMergeList((List) oldValue, (List) newValue); } return newValue; // Cannot merge if not a Map or a List, hence replace with the new value. }); } else { throw new InvalidTypeException("Configurations must be a Map<String, Object>. Instead found a '" + entry.getKey().getClass().getName() + "' key."); } } } @SuppressWarnings("unchecked") private static Map deepMergeMap(Map oldMap, Map newMap) { for (Object key : newMap.keySet()) { Object newValueObj = newMap.get(key); Object oldValueObj = oldMap.get(key); if (oldValueObj instanceof Map && newValueObj instanceof Map) { oldMap.put(key, deepMergeMap((Map) oldValueObj, (Map) newValueObj)); } else if (oldValueObj instanceof List && newValueObj instanceof List) { oldMap.put(key, deepMergeList((List) oldValueObj, (List) newValueObj)); } else { oldMap.put(key, newValueObj); } } return oldMap; } @SuppressWarnings("unchecked") private static List deepMergeList(List oldList, List newList) { for (Object newItemObj : newList) { int oldIndex = oldList.indexOf(newItemObj); if (oldIndex != -1) { Object oldItemObj = oldList.get(oldIndex); if (oldItemObj instanceof List && newItemObj instanceof List) { oldList.set(oldIndex, deepMergeList((List) oldItemObj, (List) newItemObj)); } else if (oldItemObj instanceof Map && newItemObj instanceof Map) { oldList.set(oldIndex, deepMergeMap((Map) oldItemObj, (Map) newItemObj)); } else { oldList.set(oldIndex, newItemObj); } } else { oldList.add(newItemObj); } } return oldList; } public static Configuration emptyConfiguration() { return new Configuration(0); } }
removed 'getAsString' method from Configuration class
components/uuf-core/src/main/java/org/wso2/carbon/uuf/api/Configuration.java
removed 'getAsString' method from Configuration class
<ide><path>omponents/uuf-core/src/main/java/org/wso2/carbon/uuf/api/Configuration.java <ide> } <ide> } <ide> <del> public String getAsString(String key) { <del> Object value = super.get(key); <del> if ((value == null) || (value instanceof String)) { <del> return (String) value; <del> } else { <del> throw new InvalidTypeException( <del> "Value of '" + key + "' in the configuration must be a string. Instead found '" + <del> value.getClass().getName() + "'."); <del> } <del> } <del> <del> public String getAsStringOrDefault(String key, String defaultValue) { <del> String value = getAsString(key); <del> return (value == null) ? defaultValue : value; <del> } <del> <ide> @Override <ide> public Object put(String key, Object value) { <ide> throw new UnsupportedOperationException("Cannot change Configuration.");
Java
apache-2.0
215591de030928e2510550a081491aed1afa424d
0
b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.datastore.server.request; import com.b2international.snowowl.core.domain.BranchContext; import com.b2international.snowowl.core.exceptions.ComponentNotFoundException; import com.b2international.snowowl.snomed.core.domain.SnomedReferenceSetMember; import com.b2international.snowowl.snomed.datastore.SnomedRefSetMemberLookupService; import com.b2international.snowowl.snomed.datastore.index.refset.SnomedRefSetMemberIndexEntry; /** * @since 4.5 */ class SnomedRefSetMemberReadRequest extends SnomedRefSetMemberRequest<BranchContext, SnomedReferenceSetMember> { private final String componentId; SnomedRefSetMemberReadRequest(String id) { this.componentId = id; } @Override public SnomedReferenceSetMember execute(BranchContext context) { final SnomedRefSetMemberIndexEntry member = new SnomedRefSetMemberLookupService().getComponent(context.branch().branchPath(), componentId); if (member == null) { throw new ComponentNotFoundException("Reference Set Member", componentId); } else { return new SnomedReferenceSetMemberConverter().apply(member); } } @Override protected Class<SnomedReferenceSetMember> getReturnType() { return SnomedReferenceSetMember.class; } }
snomed/com.b2international.snowowl.snomed.datastore.server/src/com/b2international/snowowl/snomed/datastore/server/request/SnomedRefSetMemberReadRequest.java
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.datastore.server.request; import com.b2international.snowowl.core.domain.BranchContext; import com.b2international.snowowl.datastore.editor.service.ComponentNotFoundException; import com.b2international.snowowl.snomed.core.domain.SnomedReferenceSetMember; import com.b2international.snowowl.snomed.datastore.SnomedRefSetMemberLookupService; import com.b2international.snowowl.snomed.datastore.index.refset.SnomedRefSetMemberIndexEntry; /** * @since 4.5 */ class SnomedRefSetMemberReadRequest extends SnomedRefSetMemberRequest<BranchContext, SnomedReferenceSetMember> { private final String componentId; SnomedRefSetMemberReadRequest(String id) { this.componentId = id; } @Override public SnomedReferenceSetMember execute(BranchContext context) { final SnomedRefSetMemberIndexEntry member = new SnomedRefSetMemberLookupService().getComponent(context.branch().branchPath(), componentId); if (member == null) { throw new ComponentNotFoundException("Reference Set Member", componentId); } else { return new SnomedReferenceSetMemberConverter().apply(member); } } @Override protected Class<SnomedReferenceSetMember> getReturnType() { return SnomedReferenceSetMember.class; } }
SO-1710: fixed references to ComponentNotFoundException
snomed/com.b2international.snowowl.snomed.datastore.server/src/com/b2international/snowowl/snomed/datastore/server/request/SnomedRefSetMemberReadRequest.java
SO-1710: fixed references to ComponentNotFoundException
<ide><path>nomed/com.b2international.snowowl.snomed.datastore.server/src/com/b2international/snowowl/snomed/datastore/server/request/SnomedRefSetMemberReadRequest.java <ide> package com.b2international.snowowl.snomed.datastore.server.request; <ide> <ide> import com.b2international.snowowl.core.domain.BranchContext; <del>import com.b2international.snowowl.datastore.editor.service.ComponentNotFoundException; <add>import com.b2international.snowowl.core.exceptions.ComponentNotFoundException; <ide> import com.b2international.snowowl.snomed.core.domain.SnomedReferenceSetMember; <ide> import com.b2international.snowowl.snomed.datastore.SnomedRefSetMemberLookupService; <ide> import com.b2international.snowowl.snomed.datastore.index.refset.SnomedRefSetMemberIndexEntry;
JavaScript
bsd-3-clause
ba457dfb6fe516c51b7c77ebbd25ce00f9662778
0
erpframework/joose-js,erpframework/joose-js,rzel/joose-js,erpframework/joose-js,erpframework/joose-js,rzel/joose-js,rzel/joose-js,rzel/joose-js
/* Module("my.namespace", function () { Class("Test", { }) }) */ (function (Class) { Class("Joose.Module", { has: { _name: { is: "rw" }, _elements: { is: "rw" }, _container: { is: "rw" } }, classMethods: { setup: function (name, functionThatCreatesClassesAndRoles) { var me = this; var parts = name.split("."); var object = joose.top; var soFar = [] var module; for(var i = 0; i < parts.length; i++) { var part = parts[i]; if(part == "meta") { throw "Module names may not include a part called 'meta'." } var cur = object[part]; soFar.push(part) var name = soFar.join(".") if(typeof cur == "undefined") { object[part] = {}; module = new Joose.Module(name) module.setContainer(object[part]) object[part].meta = module Joose.Module._allModules.push(object[part]) } else { module = cur.meta; if(!(module && module.meta && (module.meta.isa(Joose.Module)))) { throw "Trying to setup module "+name+" failed. There is already something else: "+module } } object = object[part] } var before = joose.currentModule joose.currentModule = module if(functionThatCreatesClassesAndRoles) { functionThatCreatesClassesAndRoles(object); } joose.currentModule = before; return object }, getAllModules: function () { return this._allModules } }, methods: { alias: function (destination) { var me = this; if(arguments.length == 0) { return this } Joose.A.each(this.getElements(), function (thing) { var global = me.globalName(thing.meta.className()); if(destination[global] === thing) { // already there return } if(typeof destination[global] != "undefined") { throw "There is already something else in the spot "+global } destination[global] = thing; }) }, globalName: function (name) { var moduleName = this.getName(); if(name.indexOf(moduleName) != 0) { throw "All things inside me should have a name that starts with "+moduleName+". Name is "+name } var rest = name.substr(moduleName.length + 1); // + 1 to remove the trailing dot if(rest.indexOf(".") != -1) { throw "The things inside me should have no more dots in there name. Name is "+rest } return rest }, removeGlobalSymbols: function () { Joose.A.each(this.getElements(), function (thing) { var global = this.globalName(thing.getName()); delete joose.top[global] }) }, initialize: function (name) { this.setElements([]) this.setName(name); }, isEmpty: function () { return this.getElements().length == 0 }, addElement: function (ele) { if(!(ele || ele.meta)) { throw "You may only add things that are Joose objects" } this._elements.push(ele) }, getNames: function () { var names = []; Joose.A.each(this.getElements(), function (ele) { names.push(ele.meta.getName()) }); return names } } }) })(JooseClass) __global__ = {}; __global__.meta = new Joose.Module(); __global__.meta.setName("__global__"); __global__.meta.setContainer(__global__); Joose.Module._allModules = [__global__]; JooseModule("__global__.nomodule", function () {}) __global__.nomodule.meta._elements = joose.globalObjects
lib/Joose/Module.js
/* Module("my.namespace", function () { Class("Test", { }) }) */ (function (Class) { Class("Joose.Module", { has: { _name: { is: "rw" }, _elements: { is: "rw" }, _container: { is: "rw" } }, classMethods: { setup: function (name, functionThatCreatesClassesAndRoles) { var me = this; var parts = name.split("."); var object = joose.top; var soFar = [] var module; for(var i = 0; i < parts.length; i++) { var part = parts[i]; if(part == "meta") { throw "Module names may not include a part called 'meta'." } var cur = object[part]; soFar.push(part) var name = soFar.join(".") if(typeof cur == "undefined") { object[part] = {}; module = new Joose.Module(name) module.setContainer(object[part]) object[part].meta = module Joose.Module._allModules.push(object[part]) } else { module = cur.meta; if(!(module && module.meta && (module.meta.isa(Joose.Module)))) { throw "Trying to setup module "+name+" failed. There is already something else: "+module } } object = object[part] } var before = joose.currentModule joose.currentModule = module if(functionThatCreatesClassesAndRoles) { functionThatCreatesClassesAndRoles(object); } joose.currentModule = before; return object }, getAllModules: function () { return this._allModules } }, methods: { alias: function (destination) { var me = this; if(arguments.length == 0) { return this } Joose.A.each(this.getElements(), function (thing) { var global = me.globalName(thing.meta.className()); if(destination[global] === thing) { // already there console.log('whats there is the same thing already'); return } if(typeof destination[global] != "undefined") { console.log('throwing exception'); throw "There is already something else in the spot "+global } destination[global] = thing; }) }, globalName: function (name) { var moduleName = this.getName(); if(name.indexOf(moduleName) != 0) { throw "All things inside me should have a name that starts with "+moduleName+". Name is "+name } var rest = name.substr(moduleName.length + 1); // + 1 to remove the trailing dot if(rest.indexOf(".") != -1) { throw "The things inside me should have no more dots in there name. Name is "+rest } return rest }, removeGlobalSymbols: function () { Joose.A.each(this.getElements(), function (thing) { var global = this.globalName(thing.getName()); delete joose.top[global] }) }, initialize: function (name) { this.setElements([]) this.setName(name); }, isEmpty: function () { return this.getElements().length == 0 }, addElement: function (ele) { if(!(ele || ele.meta)) { throw "You may only add things that are Joose objects" } this._elements.push(ele) }, getNames: function () { var names = []; Joose.A.each(this.getElements(), function (ele) { names.push(ele.meta.getName()) }); return names } } }) })(JooseClass) __global__ = {}; __global__.meta = new Joose.Module(); __global__.meta.setName("__global__"); __global__.meta.setContainer(__global__); Joose.Module._allModules = [__global__]; JooseModule("__global__.nomodule", function () {}) __global__.nomodule.meta._elements = joose.globalObjects
Remove left over debugging statements
lib/Joose/Module.js
Remove left over debugging statements
<ide><path>ib/Joose/Module.js <ide> var global = me.globalName(thing.meta.className()); <ide> <ide> if(destination[global] === thing) { // already there <del> console.log('whats there is the same thing already'); <ide> return <ide> } <ide> if(typeof destination[global] != "undefined") { <del> console.log('throwing exception'); <ide> throw "There is already something else in the spot "+global <ide> } <ide>
Java
apache-2.0
85076b981bbc9b0c380bd5e3a0c3ea4dad27f0e2
0
rei-yu/sleepiness_android
package com.reiyu.sleepin; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.ParseAnalytics; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.List; public class MainActivity extends AppCompatActivity { String date; int flower_num; ArrayList<String> memberList; int current_score; String current_username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ParseAnalytics.trackAppOpenedInBackground(getIntent()); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); flower_num = 0; if (!(sp.getBoolean("@string/signed_in", false))) { Log.e("Main Activity", "user null"); startActivity(new Intent(MainActivity.this, SignInFragment.class)); } else { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); date = year + "/" + (month + 1) + "/" + day; // TODO: should consider user change (fundamentally should judge from get response) if ((sp.getString("@string/record_updated", null) == null) || (!(sp.getString("@string/record_updated", null).equals(date)))) { Log.e("RECORD_UPDATED", String.valueOf(date) + ":" + " data not yet recorded"); startActivity(new Intent(MainActivity.this, WakeUpFragment.class)); } else { setContentView(R.layout.activity_main); String msg = sp.getString("@string/username", null) + "'s Flower"; setTitle(msg); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); String msg = ReflectFragment.getSession(); int session_num = ReflectFragment.getSessionNum(); if (session_num == 0) { Toast.makeText(MainActivity.this, "Session is 9:00 ~ 21:00\nPlease wait until 10:30 for reflection", Toast.LENGTH_LONG).show(); } else if ((sp.getString("@string/sleepiness_updated", null) == null) || (!(sp.getString("@string/sleepiness_updated", null).equals(date + session_num)))) { startActivity(new Intent(MainActivity.this, ReflectFragment.class)); } else { Toast.makeText(MainActivity.this, "You have already reflected\nsession " + msg + ".", Toast.LENGTH_LONG).show(); } } }); showMainFlower(); getGroup(); } } } @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_main, 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_sign_out) { signOut(); return true; } return super.onOptionsItemSelected(item); } private void signOut() { ParseUser.logOut(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.edit().putBoolean("@string/signed_in", false).commit(); sp.edit().putString("@string/username", null).commit(); sp.edit().putString("@string/email", null).commit(); startActivity(new Intent(MainActivity.this, SignInFragment.class)); } public void getFlowerState() { // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); // int score = sp.getInt("@string/healthy_score", -1); ParseQuery<ParseObject> query_score = ParseQuery.getQuery("SleepinessRecord"); if (memberList.size() > 0) { current_username = memberList.get(0); memberList.remove(0); query_score.whereEqualTo("username", current_username); query_score.orderByDescending("createdAt"); query_score.getFirstInBackground(new GetCallback<ParseObject>() { public void done(ParseObject sleepinessRecord, ParseException e) { if (sleepinessRecord != null) { int score = sleepinessRecord.getInt("score"); current_score = score; Log.e("FlowerRecordScore", String.valueOf(score)); ParseQuery<ParseObject> query = ParseQuery.getQuery("FlowerRecord"); query.whereEqualTo("username", current_username); query.orderByDescending("createdAt"); query.getFirstInBackground(new GetCallback<ParseObject>() { public void done(ParseObject flowerRecord, ParseException e) { if (e == null) { boolean hasClover2 = flowerRecord.getBoolean("hasClover2"); boolean hasButterfly2 = flowerRecord.getBoolean("hasButterfly2"); boolean hasClover = flowerRecord.getBoolean("hasClover"); boolean hasLadybug = flowerRecord.getBoolean("hasLadybug"); boolean hasButterfly = flowerRecord.getBoolean("hasButterfly"); boolean hasLeaf = flowerRecord.getBoolean("hasLeaf"); boolean hasPot = flowerRecord.getBoolean("hasPot"); Log.e("FlowerRecordState", "success"); ImageView flower; switch (flower_num) { case 3: flower = (ImageView) findViewById(R.id.flower4); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; case 2: flower = (ImageView) findViewById(R.id.flower3); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; case 1: flower = (ImageView) findViewById(R.id.flower2); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; case 0: flower = (ImageView) findViewById(R.id.flower1); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; } } else { Log.e("FlowerRecordState", "Error: " + e.getMessage()); } } }); } else { Log.e("FlowerRecordScore", "Error: " + e.getMessage()); } getFlowerState(); } }); } } private void showFlower(ImageView flower, int score, Boolean hasClover2, boolean hasButterfly2, boolean hasClover, boolean hasLadybug, boolean hasButterfly, boolean hasLeaf, boolean hasPot) { Log.e("showFlower", "called"); if (score < 0) { Toast.makeText(MainActivity.this, "Could not load score", Toast.LENGTH_LONG).show(); } else { if (score > 60) { if (hasClover2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a_y); } else if (hasButterfly2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a); } else if (hasClover) { flower.setImageResource(R.drawable.happy_u_l_b_t_c); } else if (hasLadybug) { flower.setImageResource(R.drawable.happy_u_l_b_t); } else if (hasButterfly) { flower.setImageResource(R.drawable.happy_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.happy_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.happy_u); } else { flower.setImageResource(R.drawable.happy); } } else if (score > 30) { if (hasButterfly) { flower.setImageResource(R.drawable.nogood_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.nogood_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.nogood_u); } else { flower.setImageResource(R.drawable.nogood); } } else { if (hasPot) { flower.setImageResource(R.drawable.bad_u); } else { flower.setImageResource(R.drawable.bad); } } } } private void showMainFlower() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); int score = sp.getInt("@string/healthy_score", -1); if (score < 0) { Toast.makeText(MainActivity.this, "Could not load score", Toast.LENGTH_LONG).show(); } else { boolean hasClover2 = sp.getBoolean("@string/clover2", false); boolean hasButterfly2 = sp.getBoolean("@string/butterfly2", false); boolean hasClover = sp.getBoolean("@string/clover", false); boolean hasLadybug = sp.getBoolean("@string/ladybug", false); boolean hasButterfly = sp.getBoolean("@string/clover2", false); boolean hasLeaf = sp.getBoolean("@string/leaf", false); boolean hasPot = sp.getBoolean("@string/pot", false); ImageView flower = (ImageView) findViewById(R.id.flower); if (score > 60) { if (hasClover2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a_y); } else if (hasButterfly2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a); } else if (hasClover) { flower.setImageResource(R.drawable.happy_u_l_b_t_c); } else if (hasLadybug) { flower.setImageResource(R.drawable.happy_u_l_b_t); } else if (hasButterfly) { flower.setImageResource(R.drawable.happy_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.happy_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.happy_u); } else { flower.setImageResource(R.drawable.happy); } } else if (score > 30) { if (hasButterfly) { flower.setImageResource(R.drawable.nogood_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.nogood_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.nogood_u); } else { flower.setImageResource(R.drawable.nogood); } } else { if (hasPot) { flower.setImageResource(R.drawable.bad_u); } else { flower.setImageResource(R.drawable.bad); } } } } private void getGroup() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); int group_id = sp.getInt("@string/group_id", -1); ParseQuery<ParseUser> query = ParseUser.getQuery(); query.whereEqualTo("group_id", group_id); query.findInBackground(new FindCallback<ParseUser>() { public void done(List<ParseUser> memberObject, ParseException e) { if (e == null) { if (memberObject.size() > 0) { HashSet<String> usernameSet = new HashSet<>(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); for (ParseUser member : memberObject) { String name = member.getString("username"); if (!name.equals(sp.getString("@string/username", null))) { usernameSet.add(name); Log.e("getMember", member.getString("username")); } } sp.edit().putStringSet("@string/member_set", usernameSet); memberList = new ArrayList<>(usernameSet); getFlowerState(); } else { Log.e("getGroup Null", "invalid group_id : " + memberList.toString()); } } else { Log.e("getGroup", "Error: " + e.getMessage()); } } }); } }
ParseStarterProject/src/main/java/com/reiyu/sleepin/MainActivity.java
package com.reiyu.sleepin; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.ParseAnalytics; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.List; public class MainActivity extends AppCompatActivity { String date; int flower_num; ArrayList<String> memberList; int current_score; String current_username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ParseAnalytics.trackAppOpenedInBackground(getIntent()); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); flower_num = 0; if (!(sp.getBoolean("@string/signed_in", false))) { Log.e("Main Activity", "user null"); startActivity(new Intent(MainActivity.this, SignInFragment.class)); } else { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); date = year + "/" + (month + 1) + "/" + day; // TODO: should consider user change (fundamentally should judge from get response) if ((sp.getString("@string/record_updated", null) == null) || (!(sp.getString("@string/record_updated", null).equals(date)))) { Log.e("RECORD_UPDATED", String.valueOf(date) + ":" + " data not yet recorded"); startActivity(new Intent(MainActivity.this, WakeUpFragment.class)); } else { setContentView(R.layout.activity_main); String msg = sp.getString("@string/username", null) + "'s Flower"; setTitle(msg); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); String msg = ReflectFragment.getSession(); int session_num = ReflectFragment.getSessionNum(); if (session_num == 0) { Toast.makeText(MainActivity.this, "Session is 9:00 ~ 21:00\nPlease wait until 10:30 for reflection", Toast.LENGTH_LONG).show(); } else if ((sp.getString("@string/sleepiness_updated", null) == null) || (!(sp.getString("@string/sleepiness_updated", null).equals(date + session_num)))) { startActivity(new Intent(MainActivity.this, ReflectFragment.class)); } else { Toast.makeText(MainActivity.this, "You have already reflected\nsession " + msg + ".", Toast.LENGTH_LONG).show(); } } }); showMainFlower(); getGroup(); } } } @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_main, 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_sign_out) { signOut(); return true; } return super.onOptionsItemSelected(item); } private void signOut() { ParseUser.logOut(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.edit().putBoolean("@string/signed_in", false).commit(); sp.edit().putString("@string/username", null).commit(); sp.edit().putString("@string/email", null).commit(); startActivity(new Intent(MainActivity.this, SignInFragment.class)); } public void getFlowerState() { // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); // int score = sp.getInt("@string/healthy_score", -1); ParseQuery<ParseObject> query_score = ParseQuery.getQuery("SleepinessRecord"); if (memberList.size() > 0) { current_username = memberList.get(0); memberList.remove(0); query_score.whereEqualTo("username", current_username); query_score.orderByDescending("createdAt"); query_score.getFirstInBackground(new GetCallback<ParseObject>() { public void done(ParseObject sleepinessRecord, ParseException e) { if (sleepinessRecord != null) { int score = sleepinessRecord.getInt("score"); current_score = score; Log.e("FlowerRecordScore", String.valueOf(score)); ParseQuery<ParseObject> query = ParseQuery.getQuery("FlowerRecord"); query.whereEqualTo("username", current_username); query.orderByDescending("createdAt"); query.getFirstInBackground(new GetCallback<ParseObject>() { public void done(ParseObject flowerRecord, ParseException e) { if (e == null) { boolean hasClover2 = flowerRecord.getBoolean("hasClover2"); boolean hasButterfly2 = flowerRecord.getBoolean("hasButterfly2"); boolean hasClover = flowerRecord.getBoolean("hasClover"); boolean hasLadybug = flowerRecord.getBoolean("hasLadybug"); boolean hasButterfly = flowerRecord.getBoolean("hasButterfly"); boolean hasLeaf = flowerRecord.getBoolean("hasLeaf"); boolean hasPot = flowerRecord.getBoolean("hasPot"); Log.e("FlowerRecordState", "success"); ImageView flower; switch (flower_num) { case 3: flower = (ImageView) findViewById(R.id.flower4); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; case 2: flower = (ImageView) findViewById(R.id.flower3); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; case 1: flower = (ImageView) findViewById(R.id.flower2); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; case 0: flower = (ImageView) findViewById(R.id.flower1); showFlower(flower, current_score, hasClover2, hasButterfly2, hasClover, hasLadybug, hasButterfly, hasLeaf, hasPot); flower_num += 1; break; } } else { Log.e("FlowerRecordState", "Error: " + e.getMessage()); } } }); } else { Log.e("FlowerRecordScore", "Error: " + e.getMessage()); } getFlowerState(); } }); } } private void showFlower(ImageView flower, int score, Boolean hasClover2, boolean hasButterfly2, boolean hasClover, boolean hasLadybug, boolean hasButterfly, boolean hasLeaf, boolean hasPot) { Log.e("showFlower", "called"); if (score < 0) { Toast.makeText(MainActivity.this, "Could not load score", Toast.LENGTH_LONG).show(); } else { if (score > 60) { if (hasClover2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a_y); } else if (hasButterfly2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a); } else if (hasClover) { flower.setImageResource(R.drawable.happy_u_l_b_t_c); } else if (hasLadybug) { flower.setImageResource(R.drawable.happy_u_l_b_t); } else if (hasButterfly) { flower.setImageResource(R.drawable.happy_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.happy_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.happy_u); } else { flower.setImageResource(R.drawable.happy); } } else if (score > 30) { if (hasButterfly) { flower.setImageResource(R.drawable.nogood_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.nogood_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.nogood_u); } else { flower.setImageResource(R.drawable.nogood); } } else { if (hasPot) { flower.setImageResource(R.drawable.bad_u); } else { flower.setImageResource(R.drawable.bad); } } } } // // private void getGroupFlower(int n, ArrayList<String> usernameList) { // switch (n - 1) { // case 4: // getFlowerState(4, usernameList.get(3)); // case 3: // getFlowerState(3, usernameList.get(2)); // case 2: // getFlowerState(2, usernameList.get(1)); // case 1: // getFlowerState(1, usernameList.get(0)); // default: // SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); // getFlowerState(0, sp.getString("@string/username", null)); // break; // } // } private void showMainFlower() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); int score = sp.getInt("@string/healthy_score", -1); if (score < 0) { Toast.makeText(MainActivity.this, "Could not load score", Toast.LENGTH_LONG).show(); } else { boolean hasClover2 = sp.getBoolean("@string/clover2", false); boolean hasButterfly2 = sp.getBoolean("@string/butterfly2", false); boolean hasClover = sp.getBoolean("@string/clover", false); boolean hasLadybug = sp.getBoolean("@string/ladybug", false); boolean hasButterfly = sp.getBoolean("@string/clover2", false); boolean hasLeaf = sp.getBoolean("@string/leaf", false); boolean hasPot = sp.getBoolean("@string/pot", false); ImageView flower = (ImageView) findViewById(R.id.flower); if (score > 60) { if (hasClover2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a_y); } else if (hasButterfly2) { flower.setImageResource(R.drawable.happy_u_l_b_t_c_a); } else if (hasClover) { flower.setImageResource(R.drawable.happy_u_l_b_t_c); } else if (hasLadybug) { flower.setImageResource(R.drawable.happy_u_l_b_t); } else if (hasButterfly) { flower.setImageResource(R.drawable.happy_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.happy_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.happy_u); } else { flower.setImageResource(R.drawable.happy); } } else if (score > 30) { if (hasButterfly) { flower.setImageResource(R.drawable.nogood_u_l_b); } else if (hasLeaf) { flower.setImageResource(R.drawable.nogood_u_l); } else if (hasPot) { flower.setImageResource(R.drawable.nogood_u); } else { flower.setImageResource(R.drawable.nogood); } } else { if (hasPot) { flower.setImageResource(R.drawable.bad_u); } else { flower.setImageResource(R.drawable.bad); } } } } private void getGroup() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); int group_id = sp.getInt("@string/group_id", -1); ParseQuery<ParseUser> query = ParseUser.getQuery(); query.whereEqualTo("group_id", group_id); query.findInBackground(new FindCallback<ParseUser>() { public void done(List<ParseUser> memberObject, ParseException e) { if (e == null) { if (memberObject.size() > 0) { HashSet<String> usernameSet = new HashSet<>(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); for (ParseUser member : memberObject) { String name = member.getString("username"); if (!name.equals(sp.getString("@string/username", null))) { usernameSet.add(name); Log.e("getMember", member.getString("username")); } } sp.edit().putStringSet("@string/member_set", usernameSet); memberList = new ArrayList<>(usernameSet); getFlowerState(); } else { Log.e("getGroup Null", "invalid group_id : " + memberList.toString()); } } else { Log.e("getGroup", "Error: " + e.getMessage()); } } }); } }
refactor
ParseStarterProject/src/main/java/com/reiyu/sleepin/MainActivity.java
refactor
<ide><path>arseStarterProject/src/main/java/com/reiyu/sleepin/MainActivity.java <ide> } <ide> } <ide> } <del>// <del>// private void getGroupFlower(int n, ArrayList<String> usernameList) { <del>// switch (n - 1) { <del>// case 4: <del>// getFlowerState(4, usernameList.get(3)); <del>// case 3: <del>// getFlowerState(3, usernameList.get(2)); <del>// case 2: <del>// getFlowerState(2, usernameList.get(1)); <del>// case 1: <del>// getFlowerState(1, usernameList.get(0)); <del>// default: <del>// SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); <del>// getFlowerState(0, sp.getString("@string/username", null)); <del>// break; <del>// } <del>// } <ide> <ide> private void showMainFlower() { <ide> SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Java
bsd-3-clause
07fcde3b73b1c728cb067df1ae41c24cf1668950
0
olafmaas/jmonkeyengine,Georgeto/jmonkeyengine,tr0k/jmonkeyengine,zzuegg/jmonkeyengine,olafmaas/jmonkeyengine,atomixnmc/jmonkeyengine,delftsre/jmonkeyengine,davidB/jmonkeyengine,skapi1992/jmonkeyengine,danteinforno/jmonkeyengine,danteinforno/jmonkeyengine,davidB/jmonkeyengine,mbenson/jmonkeyengine,bsmr-java/jmonkeyengine,yetanotherindie/jMonkey-Engine,OpenGrabeso/jmonkeyengine,zzuegg/jmonkeyengine,delftsre/jmonkeyengine,phr00t/jmonkeyengine,weilichuang/jmonkeyengine,phr00t/jmonkeyengine,bertleft/jmonkeyengine,yetanotherindie/jMonkey-Engine,atomixnmc/jmonkeyengine,yetanotherindie/jMonkey-Engine,d235j/jmonkeyengine,bsmr-java/jmonkeyengine,g-rocket/jmonkeyengine,InShadow/jmonkeyengine,weilichuang/jmonkeyengine,mbenson/jmonkeyengine,amit2103/jmonkeyengine,weilichuang/jmonkeyengine,jMonkeyEngine/jmonkeyengine,d235j/jmonkeyengine,tr0k/jmonkeyengine,g-rocket/jmonkeyengine,mbenson/jmonkeyengine,danteinforno/jmonkeyengine,yetanotherindie/jMonkey-Engine,phr00t/jmonkeyengine,rbottema/jmonkeyengine,d235j/jmonkeyengine,davidB/jmonkeyengine,Georgeto/jmonkeyengine,bertleft/jmonkeyengine,wrvangeest/jmonkeyengine,rbottema/jmonkeyengine,GreenCubes/jmonkeyengine,olafmaas/jmonkeyengine,InShadow/jmonkeyengine,tr0k/jmonkeyengine,Georgeto/jmonkeyengine,atomixnmc/jmonkeyengine,skapi1992/jmonkeyengine,davidB/jmonkeyengine,wrvangeest/jmonkeyengine,delftsre/jmonkeyengine,olafmaas/jmonkeyengine,delftsre/jmonkeyengine,OpenGrabeso/jmonkeyengine,atomixnmc/jmonkeyengine,rbottema/jmonkeyengine,sandervdo/jmonkeyengine,yetanotherindie/jMonkey-Engine,mbenson/jmonkeyengine,sandervdo/jmonkeyengine,Georgeto/jmonkeyengine,GreenCubes/jmonkeyengine,davidB/jmonkeyengine,skapi1992/jmonkeyengine,g-rocket/jmonkeyengine,Georgeto/jmonkeyengine,zzuegg/jmonkeyengine,bertleft/jmonkeyengine,tr0k/jmonkeyengine,bsmr-java/jmonkeyengine,OpenGrabeso/jmonkeyengine,wrvangeest/jmonkeyengine,d235j/jmonkeyengine,g-rocket/jmonkeyengine,Georgeto/jmonkeyengine,d235j/jmonkeyengine,jMonkeyEngine/jmonkeyengine,aaronang/jmonkeyengine,nickschot/jmonkeyengine,nickschot/jmonkeyengine,atomixnmc/jmonkeyengine,skapi1992/jmonkeyengine,danteinforno/jmonkeyengine,weilichuang/jmonkeyengine,GreenCubes/jmonkeyengine,aaronang/jmonkeyengine,mbenson/jmonkeyengine,d235j/jmonkeyengine,rbottema/jmonkeyengine,sandervdo/jmonkeyengine,OpenGrabeso/jmonkeyengine,weilichuang/jmonkeyengine,g-rocket/jmonkeyengine,amit2103/jmonkeyengine,danteinforno/jmonkeyengine,yetanotherindie/jMonkey-Engine,jMonkeyEngine/jmonkeyengine,davidB/jmonkeyengine,zzuegg/jmonkeyengine,sandervdo/jmonkeyengine,OpenGrabeso/jmonkeyengine,wrvangeest/jmonkeyengine,OpenGrabeso/jmonkeyengine,amit2103/jmonkeyengine,mbenson/jmonkeyengine,nickschot/jmonkeyengine,g-rocket/jmonkeyengine,amit2103/jmonkeyengine,aaronang/jmonkeyengine,nickschot/jmonkeyengine,bsmr-java/jmonkeyengine,aaronang/jmonkeyengine,danteinforno/jmonkeyengine,amit2103/jmonkeyengine,jMonkeyEngine/jmonkeyengine,InShadow/jmonkeyengine,bertleft/jmonkeyengine,amit2103/jmonkeyengine,weilichuang/jmonkeyengine,phr00t/jmonkeyengine,InShadow/jmonkeyengine,atomixnmc/jmonkeyengine,GreenCubes/jmonkeyengine
/* * 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.jme3.gde.scenecomposer.tools.shortcuts; import com.jme3.asset.AssetManager; import com.jme3.gde.core.sceneexplorer.SceneExplorerTopComponent; import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; import com.jme3.gde.core.sceneviewer.SceneViewerTopComponent; import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; import com.jme3.gde.scenecomposer.SceneComposerToolController; import com.jme3.input.KeyInput; import com.jme3.input.event.KeyInputEvent; import com.jme3.math.Vector2f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import org.openide.loaders.DataObject; import org.openide.util.Lookup; /** * * @author dokthar */ public class DeleteShortcut extends ShortcutTool { @Override public boolean isActivableBy(KeyInputEvent kie) { if (kie.getKeyCode() == KeyInput.KEY_X && kie.isPressed()) { ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); if (!scm.isActive() && scm.isShiftDown()) { // ^ can't be enable if an other shortcut is allready active return true; } } return false; } @Override public void cancel() { terminate(); } @Override public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates. hideMarker(); if (selectedSpatial != null) { delete(); } terminate(); } private void delete() { Spatial selected = toolController.getSelectedSpatial(); Node parent = selected.getParent(); selected.removeFromParent(); actionPerformed(new DeleteUndo(selected, parent)); selected = null; toolController.updateSelection(selected); final JmeNode rootNode = toolController.getRootNode(); refreshSelected(rootNode, parent); } private void refreshSelected(final JmeNode jmeRootNode, final Node parent) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { jmeRootNode.getChild(parent).refresh(false); } }); } @Override public void keyPressed(KeyInputEvent kie) { } @Override public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { } @Override public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { } @Override public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject, JmeSpatial selectedSpatial) { } @Override public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { } @Override public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { } private class DeleteUndo extends AbstractUndoableSceneEdit { private Spatial spatial; private Node parent; DeleteUndo(Spatial spatial, Node parent) { this.spatial = spatial; this.parent = parent; } @Override public void sceneUndo() { parent.attachChild(spatial); } @Override public void sceneRedo() { spatial.removeFromParent(); } } }
sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DeleteShortcut.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.jme3.gde.scenecomposer.tools.shortcuts; import com.jme3.asset.AssetManager; import com.jme3.gde.core.sceneexplorer.SceneExplorerTopComponent; import com.jme3.gde.core.sceneexplorer.nodes.JmeNode; import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial; import com.jme3.gde.core.sceneviewer.SceneViewerTopComponent; import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit; import com.jme3.gde.scenecomposer.SceneComposerToolController; import com.jme3.input.KeyInput; import com.jme3.input.event.KeyInputEvent; import com.jme3.math.Vector2f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import org.openide.loaders.DataObject; import org.openide.util.Lookup; /** * * @author dokthar */ public class DeleteShortcut extends ShortcutTool { @Override public boolean isActivableBy(KeyInputEvent kie) { if (kie.getKeyCode() == KeyInput.KEY_X && kie.isPressed()) { if (Lookup.getDefault().lookup(ShortcutManager.class).isShiftDown()) { return true; } } return false; } @Override public void cancel() { terminate(); } @Override public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) { super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates. hideMarker(); if (selectedSpatial != null) { delete(); } terminate(); } private void delete() { Spatial selected = toolController.getSelectedSpatial(); Node parent = selected.getParent(); selected.removeFromParent(); actionPerformed(new DeleteUndo(selected, parent)); selected = null; toolController.updateSelection(selected); final JmeNode rootNode = toolController.getRootNode(); refreshSelected(rootNode, parent); } private void refreshSelected(final JmeNode jmeRootNode, final Node parent) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { jmeRootNode.getChild(parent).refresh(false); } }); } @Override public void keyPressed(KeyInputEvent kie) { } @Override public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { } @Override public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) { } @Override public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject, JmeSpatial selectedSpatial) { } @Override public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { } @Override public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { } private class DeleteUndo extends AbstractUndoableSceneEdit { private Spatial spatial; private Node parent; DeleteUndo(Spatial spatial, Node parent) { this.spatial = spatial; this.parent = parent; } @Override public void sceneUndo() { parent.attachChild(spatial); } @Override public void sceneRedo() { spatial.removeFromParent(); } } }
SDK SceneComposer : the DeleteShortcut cannot be activated if an other shortcut is already active
sdk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DeleteShortcut.java
SDK SceneComposer : the DeleteShortcut cannot be activated if an other shortcut is already active
<ide><path>dk/jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/DeleteShortcut.java <ide> @Override <ide> public boolean isActivableBy(KeyInputEvent kie) { <ide> if (kie.getKeyCode() == KeyInput.KEY_X && kie.isPressed()) { <del> if (Lookup.getDefault().lookup(ShortcutManager.class).isShiftDown()) { <add> ShortcutManager scm = Lookup.getDefault().lookup(ShortcutManager.class); <add> if (!scm.isActive() && scm.isShiftDown()) { <add> // ^ can't be enable if an other shortcut is allready active <ide> return true; <ide> } <ide> } <ide> @Override <ide> public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) { <ide> } <del> <add> <ide> private class DeleteUndo extends AbstractUndoableSceneEdit { <ide> <ide> private Spatial spatial;
Java
mit
b8ea65947199fd3ab70383f426697a5eb18bb9c6
0
BitLimit/Tweaks
package com.bitlimit.Tweaks; import com.sk89q.worldedit.bukkit.BukkitBiomeType; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import java.util.HashMap; import java.util.List; public class Tweaks extends JavaPlugin { private int weatherId; @Override public void onEnable() { new TweaksListener(this); this.getCommand("tweaks").setExecutor(new TweaksCommandExecutor(this)); this.saveConfig(); } @Override public void onDisable() { this.getServer().getScheduler().cancelTask(this.weatherId); this.saveConfig(); } @Override public void saveConfig() { super.saveConfig(); this.getConfig().options().copyDefaults(true); this.reloadConfig(); setRepeatingTaskEnabled(this.getConfig().getConfigurationSection("weather").getBoolean("enabled")); } public void setRepeatingTaskEnabled(boolean enabled) { Server server = this.getServer(); BukkitScheduler scheduler = server.getScheduler(); final long baseDuration = 1200L; if (enabled && this.weatherId == 0) { class BitLimitRecurringTask implements Runnable { Plugin plugin; BitLimitRecurringTask(Plugin p) { plugin = p; } public void run() { for (HashMap<String, Object> worldDefinition : (List<HashMap<String, Object>>)this.plugin.getConfig().getConfigurationSection("weather").getList("worlds")) { String worldName = (String)worldDefinition.get("name"); World world = this.plugin.getServer().getWorld(worldName); if (!world.hasStorm()) { int weatherDuration = world.getWeatherDuration(); Double ratio = (Double)worldDefinition.get("reduction"); int counterAmount = (int)(baseDuration * ratio); world.setWeatherDuration(weatherDuration + counterAmount); } } } } this.weatherId = scheduler.scheduleSyncRepeatingTask(this, new BitLimitRecurringTask(this), baseDuration, baseDuration); } else if (this.weatherId != 0) { scheduler.cancelTask(this.weatherId); this.weatherId = 0; } } }
src/main/java/com/bitlimit/Tweaks/Tweaks.java
package com.bitlimit.Tweaks; import com.sk89q.worldedit.bukkit.BukkitBiomeType; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import java.util.HashMap; import java.util.List; public class Tweaks extends JavaPlugin { private int weatherId; @Override public void onEnable() { new TweaksListener(this); this.getCommand("tweaks").setExecutor(new TweaksCommandExecutor(this)); this.saveConfig(); } @Override public void onDisable() { this.getServer().getScheduler().cancelTask(this.weatherId); this.saveConfig(); } @Override public void saveConfig() { super.saveConfig(); this.getConfig().options().copyDefaults(true); this.reloadConfig(); setRepeatingTaskEnabled(this.getConfig().getConfigurationSection("weather").getBoolean("enabled")); } public void setRepeatingTaskEnabled(boolean enabled) { Server server = this.getServer(); BukkitScheduler scheduler = server.getScheduler(); final long baseDuration = 1200L; if (enabled && this.weatherId == 0) { class BitLimitRecurringTask implements Runnable { Plugin plugin; BitLimitRecurringTask(Plugin p) { plugin = p; } public void run() { for (HashMap<String, Object> worldDefinition : (List<HashMap<String, Object>>)this.plugin.getConfig().getConfigurationSection("weather").getList("worlds")) { String worldName = (String)worldDefinition.get("name"); World world = this.plugin.getServer().getWorld(worldName); if (!world.hasStorm()) { int weatherDuration = world.getWeatherDuration(); Double ratio = (Double)worldDefinition.get("reduction"); int counterAmount = (int)(baseDuration * ratio); world.setWeatherDuration(weatherDuration + counterAmount); Bukkit.broadcastMessage("Reducing weather counter with ratio " + ratio + " in world " + world); } } } } this.weatherId = scheduler.scheduleSyncRepeatingTask(this, new BitLimitRecurringTask(this), baseDuration, baseDuration); } else if (this.weatherId != 0) { scheduler.cancelTask(this.weatherId); this.weatherId = 0; } } }
Remove superfluous debug broadcast.
src/main/java/com/bitlimit/Tweaks/Tweaks.java
Remove superfluous debug broadcast.
<ide><path>rc/main/java/com/bitlimit/Tweaks/Tweaks.java <ide> Double ratio = (Double)worldDefinition.get("reduction"); <ide> int counterAmount = (int)(baseDuration * ratio); <ide> world.setWeatherDuration(weatherDuration + counterAmount); <del> <del> Bukkit.broadcastMessage("Reducing weather counter with ratio " + ratio + " in world " + world); <ide> } <ide> } <ide> }
JavaScript
mit
47e059205722af1259d5a1c20dcb5fc83d070786
0
andersonmcook/node-cal
"use strict"; const zellers = require('./zellers.js'); let month = {}; month.generateMonth = function (year, month) { let months = [ , 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const calendarMonth = new Date(year, month).getMonth(); const displayYear = new Date(year, month).getFullYear(); const topLine = `${months[calendarMonth]} ${displayYear}`; const spaceCount = parseInt((20 - topLine.length) / 2); const space = " "; return `${space.repeat(spaceCount)}${topLine}`; }; module.exports = month;
lib/month.js
"use strict"; const zellers = require('./zellers.js'); let month = {}; month.generateMonth = function (year, month) { let months = [ , 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const calendarMonth = new Date(year, month).getMonth(); const displayYear = new Date(year, month).getFullYear(); const topLine = `${months[calendarMonth]} ${displayYear}`; const spaceCount = parseInt((20 - topLine.length) / 2); let spaces = ""; (function (spaceCount) { for (let i = 0; i < spaceCount; i++) { spaces += " "; } return spaces; })(spaceCount); return `${spaces}${months[calendarMonth]} ${displayYear}`; }; module.exports = month;
refactored using repeat()
lib/month.js
refactored using repeat()
<ide><path>ib/month.js <ide> const displayYear = new Date(year, month).getFullYear(); <ide> const topLine = `${months[calendarMonth]} ${displayYear}`; <ide> const spaceCount = parseInt((20 - topLine.length) / 2); <del> let spaces = ""; <del> (function (spaceCount) { <del> for (let i = 0; i < spaceCount; i++) { <del> spaces += " "; <del> } <del> return spaces; <del> })(spaceCount); <del> return `${spaces}${months[calendarMonth]} ${displayYear}`; <add> const space = " "; <add> return `${space.repeat(spaceCount)}${topLine}`; <ide> }; <ide> <ide> module.exports = month;
Java
agpl-3.0
219fb54a5669322a20c0b92ce0cc1304d3a6e110
0
imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms
package imcode.server.document.textdocument; import java.io.IOException; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import com.imcode.imcms.api.I18nLanguage; import com.imcode.util.ImageSize; @Entity(name="I18nImage") //@IdClass(ImageId.class) @Table(name="images") @NamedQueries({ @NamedQuery(name="Image.getByLanguageId", query="select i from I18nImage i where i.metaId = :metaId and i.language.id = :languageId"), @NamedQuery(name="Image.getLanguagesToImagesByMetaId", query="select l, i from I18nImage i right join i.language l where (i.metaId = :metaId and i.name = :name) or i.metaId is null order by l.systemDefault desc"), @NamedQuery(name="Image.getAllImages", query="select i from I18nImage i where i.metaId = :metaId"), @NamedQuery(name="Image.getAllDocumentImagesByLanguage", query="select i from I18nImage i where i.metaId = :metaId and i.language.id = :languageId"), @NamedQuery(name="Image.getDefaultImage", query="select i from I18nImage i where i.metaId = :metaId and i.name = :name and i.language.systemDefault is true") }) public class ImageDomainObject implements Serializable, Cloneable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="image_id") private Long id; @Transient private ImageSource source = new NullImageSource(); //@Id @Column(name="meta_id") private int metaId; /** * 'name' is a legacy identifier. * Actually this is natural key. */ //@Id private String name = ""; private int width; private int height; private int border; private String align = ""; @Column(name="alt_text") private String alternateText = ""; @Column(name="low_scr") private String lowResolutionUrl = ""; @Column(name="v_space") private int verticalSpace; @Column(name="h_space") private int horizontalSpace; private String target = ""; @Column(name="linkurl") private String linkUrl = ""; @Column(name="imgurl") private String imageUrl; private Integer type; /** * i18n support */ @OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="language_id", referencedColumnName="language_id") private I18nLanguage language; public String getName() { return name; } public ImageSize getDisplayImageSize() { ImageSize realImageSize = getRealImageSize( ); int wantedWidth = getWidth( ); int wantedHeight = getHeight( ); if ( 0 == wantedWidth && 0 != wantedHeight && 0 != realImageSize.getHeight( ) ) { wantedWidth = (int)( realImageSize.getWidth( ) * ( (double)wantedHeight / realImageSize.getHeight( ) ) ); } else if ( 0 == wantedHeight && 0 != wantedWidth && 0 != realImageSize.getWidth( ) ) { wantedHeight = (int)( realImageSize.getHeight( ) * ( (double)wantedWidth / realImageSize.getWidth( ) ) ); } else if ( 0 == wantedWidth && 0 == wantedHeight ) { wantedWidth = realImageSize.getWidth( ); wantedHeight = realImageSize.getHeight( ); } return new ImageSize( wantedWidth, wantedHeight ); } public ImageSize getRealImageSize() { ImageSize imageSize = new ImageSize( 0, 0 ); if ( !isEmpty( ) ) { try { imageSize = source.getImageSize( ); } catch ( IOException ignored ) {} } return imageSize; } public int getWidth() { return width; } public int getHeight() { return height; } public int getBorder() { return border; } public String getAlign() { return align; } public String getAlternateText() { return alternateText; } public String getLowResolutionUrl() { return lowResolutionUrl; } public int getVerticalSpace() { return verticalSpace; } public int getHorizontalSpace() { return horizontalSpace; } public String getTarget() { return target; } public String getLinkUrl() { return linkUrl; } public void setName(String image_name) { this.name = image_name; } public void setWidth(int image_width) { this.width = image_width; } public void setHeight(int image_height) { this.height = image_height; } public void setBorder(int image_border) { this.border = image_border; } public void setAlign(String image_align) { this.align = image_align; } public void setAlternateText(String alt_text) { this.alternateText = alt_text; } public void setLowResolutionUrl(String low_scr) { this.lowResolutionUrl = low_scr; } public void setVerticalSpace(int v_space) { this.verticalSpace = v_space; } public void setHorizontalSpace(int h_space) { this.horizontalSpace = h_space; } public void setTarget(String target) { this.target = target; } public void setLinkUrl(String image_ref_link) { this.linkUrl = image_ref_link; } public void setSourceAndClearSize(ImageSource source) { setSource( source ); setWidth( 0 ); setHeight( 0 ); } public void setSource(ImageSource source) { if (null == source) { throw new NullArgumentException("source"); } this.source = source; } public boolean isEmpty() { return source.isEmpty( ); } public String getUrlPath(String contextPath) { String urlPathRelativeToContextPath = getUrlPathRelativeToContextPath( ); if ( StringUtils.isBlank( urlPathRelativeToContextPath ) ) { return ""; } return contextPath + urlPathRelativeToContextPath; } public String getUrlPathRelativeToContextPath() { return source.getUrlPathRelativeToContextPath( ); } public long getSize() { if ( isEmpty( ) ) { return 0; } try { return source.getInputStreamSource( ).getSize( ); } catch ( IOException e ) { return 0; } } public ImageSource getSource() { if ( isEmpty( ) ) { return new NullImageSource( ); } return source; } public boolean equals( Object obj ) { if ( !( obj instanceof ImageDomainObject ) ) { return false; } final ImageDomainObject o = (ImageDomainObject)obj; return new EqualsBuilder().append(source.toStorageString(), o.getSource().toStorageString()) .append(name, o.getName()) .append(width, o.getWidth()) .append(height, o.getHeight()) .append(border, o .getBorder()) .append(align, o.getAlign()) .append(alternateText,o.getAlternateText()) .append(lowResolutionUrl, o.getLowResolutionUrl()) .append(verticalSpace, o.getVerticalSpace()) .append(horizontalSpace, o.getHorizontalSpace()) .append(target, o.getTarget()) .append(linkUrl, o.getLinkUrl()) .isEquals(); } public int hashCode() { return new HashCodeBuilder() .append(source.toStorageString()) .append(name).append(width).append(height) .append(border).append(align).append(alternateText) .append(lowResolutionUrl).append(verticalSpace).append(horizontalSpace) .append(target).append(linkUrl) .toHashCode(); } public I18nLanguage getLanguage() { return language; } public void setLanguage(I18nLanguage language) { this.language = language; } public int getMetaId() { return metaId; } public void setMetaId(int metaId) { this.metaId = metaId; } public ImageDomainObject clone() { try { return (ImageDomainObject)super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
server/src/imcode/server/document/textdocument/ImageDomainObject.java
package imcode.server.document.textdocument; import com.imcode.imcms.api.I18nLanguage; import com.imcode.imcms.api.ImageId; import com.imcode.util.ImageSize; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.hibernate.annotations.AccessType; import java.io.IOException; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; @Entity(name="I18nImage") //@IdClass(ImageId.class) @Table(name="images") @NamedQueries({ @NamedQuery(name="Image.getByLanguageId", query="select i from I18nImage i where i.metaId = :metaId and i.language.id = :languageId"), @NamedQuery(name="Image.getLanguagesToImagesByMetaId", query="select l, i from I18nImage i right join i.language l where (i.metaId = :metaId and i.name = :name) or i.metaId is null order by l.systemDefault desc"), @NamedQuery(name="Image.getAllImages", query="select i from I18nImage i where i.metaId = :metaId"), @NamedQuery(name="Image.getAllDocumentImagesByLanguage", query="select i from I18nImage i where i.metaId = :metaId and i.language.id = :languageId"), @NamedQuery(name="Image.getDefaultImage", query="select i from I18nImage i where i.metaId = :metaId and i.name = :name and i.language.systemDefault is true") }) public class ImageDomainObject implements Serializable, Cloneable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="image_id") private Long id; @Transient private ImageSource source = new NullImageSource(); //@Id @Column(name="meta_id") private int metaId; /** * 'name' is a legacy identifier. * Actually this is natural key. */ //@Id private String name = ""; private int width; private int height; private int border; private String align = ""; @Column(name="alt_text") private String alternateText = ""; @Column(name="low_scr") private String lowResolutionUrl = ""; @Column(name="v_space") private int verticalSpace; @Column(name="h_space") private int horizontalSpace; private String target = ""; @Column(name="linkurl") private String linkUrl = ""; @Column(name="imgurl") private String imageUrl; private Integer type; /** * i18n support */ @OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="language_id", referencedColumnName="language_id") private I18nLanguage language; public String getName() { return name; } public ImageSize getDisplayImageSize() { ImageSize realImageSize = getRealImageSize( ); int wantedWidth = getWidth( ); int wantedHeight = getHeight( ); if ( 0 == wantedWidth && 0 != wantedHeight && 0 != realImageSize.getHeight( ) ) { wantedWidth = (int)( realImageSize.getWidth( ) * ( (double)wantedHeight / realImageSize.getHeight( ) ) ); } else if ( 0 == wantedHeight && 0 != wantedWidth && 0 != realImageSize.getWidth( ) ) { wantedHeight = (int)( realImageSize.getHeight( ) * ( (double)wantedWidth / realImageSize.getWidth( ) ) ); } else if ( 0 == wantedWidth && 0 == wantedHeight ) { wantedWidth = realImageSize.getWidth( ); wantedHeight = realImageSize.getHeight( ); } return new ImageSize( wantedWidth, wantedHeight ); } public ImageSize getRealImageSize() { ImageSize imageSize = new ImageSize( 0, 0 ); if ( !isEmpty( ) ) { try { imageSize = source.getImageSize( ); } catch ( IOException ignored ) {} } return imageSize; } public int getWidth() { return width; } public int getHeight() { return height; } public int getBorder() { return border; } public String getAlign() { return align; } public String getAlternateText() { return alternateText; } public String getLowResolutionUrl() { return lowResolutionUrl; } public int getVerticalSpace() { return verticalSpace; } public int getHorizontalSpace() { return horizontalSpace; } public String getTarget() { return target; } public String getLinkUrl() { return linkUrl; } public void setName(String image_name) { this.name = image_name; } public void setWidth(int image_width) { this.width = image_width; } public void setHeight(int image_height) { this.height = image_height; } public void setBorder(int image_border) { this.border = image_border; } public void setAlign(String image_align) { this.align = image_align; } public void setAlternateText(String alt_text) { this.alternateText = alt_text; } public void setLowResolutionUrl(String low_scr) { this.lowResolutionUrl = low_scr; } public void setVerticalSpace(int v_space) { this.verticalSpace = v_space; } public void setHorizontalSpace(int h_space) { this.horizontalSpace = h_space; } public void setTarget(String target) { this.target = target; } public void setLinkUrl(String image_ref_link) { this.linkUrl = image_ref_link; } public void setSourceAndClearSize(ImageSource source) { setSource( source ); setWidth( 0 ); setHeight( 0 ); } public void setSource(ImageSource source) { if (null == source) { throw new NullArgumentException("source"); } this.source = source; } public boolean isEmpty() { return source.isEmpty( ); } public String getUrlPath(String contextPath) { String urlPathRelativeToContextPath = getUrlPathRelativeToContextPath( ); if ( StringUtils.isBlank( urlPathRelativeToContextPath ) ) { return ""; } return contextPath + urlPathRelativeToContextPath; } public String getUrlPathRelativeToContextPath() { return source.getUrlPathRelativeToContextPath( ); } public long getSize() { if ( isEmpty( ) ) { return 0; } try { return source.getInputStreamSource( ).getSize( ); } catch ( IOException e ) { return 0; } } public ImageSource getSource() { if ( isEmpty( ) ) { return new NullImageSource( ); } return source; } public boolean equals( Object obj ) { if ( !( obj instanceof ImageDomainObject ) ) { return false; } final ImageDomainObject o = (ImageDomainObject)obj; return new EqualsBuilder().append(source.toStorageString(), o.getSource().toStorageString()) .append(name, o.getName()) .append(width, o.getWidth()) .append(height, o.getHeight()) .append(border, o .getBorder()) .append(align, o.getAlign()) .append(alternateText,o.getAlternateText()) .append(lowResolutionUrl, o.getLowResolutionUrl()) .append(verticalSpace, o.getVerticalSpace()) .append(horizontalSpace, o.getHorizontalSpace()) .append(target, o.getTarget()) .append(linkUrl, o.getLinkUrl()) .isEquals(); } public int hashCode() { return new HashCodeBuilder() .append(source.toStorageString()) .append(name).append(width).append(height) .append(border).append(align).append(alternateText) .append(lowResolutionUrl).append(verticalSpace).append(horizontalSpace) .append(target).append(linkUrl) .toHashCode(); } public I18nLanguage getLanguage() { return language; } public void setLanguage(I18nLanguage language) { this.language = language; } public int getMetaId() { return metaId; } public void setMetaId(int metaId) { this.metaId = metaId; } public ImageDomainObject clone() { try { return (ImageDomainObject)super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
Issue 7153: Removed invalid import git-svn-id: b7e9aa1d6cd963481915708f70423d437278b157@10693 bd66a97b-2aff-0310-9095-89ca5cabf5a6
server/src/imcode/server/document/textdocument/ImageDomainObject.java
Issue 7153: Removed invalid import
<ide><path>erver/src/imcode/server/document/textdocument/ImageDomainObject.java <ide> package imcode.server.document.textdocument; <del> <del>import com.imcode.imcms.api.I18nLanguage; <del>import com.imcode.imcms.api.ImageId; <del>import com.imcode.util.ImageSize; <del>import org.apache.commons.lang.StringUtils; <del>import org.apache.commons.lang.NullArgumentException; <del>import org.apache.commons.lang.builder.EqualsBuilder; <del>import org.apache.commons.lang.builder.HashCodeBuilder; <del>import org.hibernate.annotations.AccessType; <ide> <ide> import java.io.IOException; <ide> import java.io.Serializable; <ide> import javax.persistence.GeneratedValue; <ide> import javax.persistence.GenerationType; <ide> import javax.persistence.Id; <del>import javax.persistence.IdClass; <ide> import javax.persistence.JoinColumn; <ide> import javax.persistence.NamedQueries; <ide> import javax.persistence.NamedQuery; <ide> import javax.persistence.OneToOne; <ide> import javax.persistence.Table; <ide> import javax.persistence.Transient; <add> <add>import org.apache.commons.lang.NullArgumentException; <add>import org.apache.commons.lang.StringUtils; <add>import org.apache.commons.lang.builder.EqualsBuilder; <add>import org.apache.commons.lang.builder.HashCodeBuilder; <add> <add>import com.imcode.imcms.api.I18nLanguage; <add>import com.imcode.util.ImageSize; <ide> <ide> @Entity(name="I18nImage") <ide> //@IdClass(ImageId.class)
JavaScript
mit
d26c196eb41ef2c8abcd3f3cb43ca7ea81fe1aba
0
kenfehling/react-router-nested-history,kenfehling/react-router-nested-history,kenfehling/react-router-nested-history
import React from 'react' import { Container, WindowGroup, Window, HistoryMatch } from 'react-router-nested-history' import WindowMaster1 from '../components/WindowMaster1' import WindowMaster2 from '../components/WindowMaster2' import WindowPage from '../components/WindowPage' import './Windows.css' const windowName = (index:number) => 'window' + (index + 1) const windowUrl = (index:number) => '/windows/' + (index + 1) const ExampleWindow = ({index, masterComponent}) => ( <Window className={`window ${windowName(index)}`}> <Container name={windowName(index)} initialUrl={windowUrl(index)} patterns={[windowUrl(index), windowUrl(index) + '/:page']} > <HistoryMatch exactly pattern={windowUrl(index)} component={masterComponent} /> <HistoryMatch exactly pattern={windowUrl(index) + '/:page'} component={WindowPage} /> </Container> </Window> ) export default () => ( <div className="windows"> <h2>Windows example</h2> <div className="description"> <p>Each window has its own individual history.</p> <p>Clicking on a window brings it to the front.</p> </div> <WindowGroup name='windows' hideInactiveContainers={false} useDefaultContainer={false}> <ExampleWindow index={0} masterComponent={WindowMaster1} /> <ExampleWindow index={1} masterComponent={WindowMaster2} /> </WindowGroup> </div> )
src/containers/Windows.js
import React from 'react' import {Container, WindowGroup, Window, HistoryMatch} from 'react-router-nested-history' import WindowMaster1 from '../components/WindowMaster1' import WindowMaster2 from '../components/WindowMaster2' import WindowPage from '../components/WindowPage' import './Windows.css' const windowName = (index:number) => 'window' + (index + 1) const windowUrl = (index:number) => '/windows/' + (index + 1) const ExampleWindow = ({index, masterComponent}) => ( <Window className={`window ${windowName(index)}`}> <Container name={windowName(index)} initialUrl={windowUrl(index)} patterns={[windowUrl(index), windowUrl(index) + '/:page']} > <HistoryMatch exactly pattern={windowUrl(index)} component={masterComponent} /> <HistoryMatch exactly pattern={windowUrl(index) + '/:page'} component={WindowPage} /> </Container> </Window> ) export default () => ( <div className="windows"> <h2>Windows example</h2> <div className="description"> <p>Each window has its own individual history.</p> <p>Clicking on a window brings it to the front.</p> </div> <WindowGroup name='windows' hideInactiveContainers={false} useDefaultContainer={false}> <ExampleWindow index={0} masterComponent={WindowMaster1} /> <ExampleWindow index={1} masterComponent={WindowMaster2} /> </WindowGroup> </div> )
Upgraded Webpack
src/containers/Windows.js
Upgraded Webpack
<ide><path>rc/containers/Windows.js <ide> import React from 'react' <del>import {Container, WindowGroup, Window, HistoryMatch} from 'react-router-nested-history' <add>import { <add> Container, WindowGroup, Window, HistoryMatch <add>} from 'react-router-nested-history' <ide> import WindowMaster1 from '../components/WindowMaster1' <ide> import WindowMaster2 from '../components/WindowMaster2' <ide> import WindowPage from '../components/WindowPage'
Java
apache-2.0
b5a6c97c7f0417fa688b5093f86445dfc9dc0cb9
0
joewalnes/idea-community,izonder/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,adedayo/intellij-community,retomerz/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,slisson/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,semonte/intellij-community,vvv1559/intellij-community,allotria/intellij-community,holmes/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,allotria/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,allotria/intellij-community,supersven/intellij-community,consulo/consulo,Distrotech/intellij-community,petteyg/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,semonte/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,retomerz/intellij-community,fnouama/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ryano144/intellij-community,jexp/idea2,adedayo/intellij-community,fnouama/intellij-community,supersven/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,samthor/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,signed/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,signed/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,jexp/idea2,ol-loginov/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,izonder/intellij-community,fitermay/intellij-community,hurricup/intellij-community,supersven/intellij-community,jexp/idea2,salguarnieri/intellij-community,izonder/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,holmes/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,semonte/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,ernestp/consulo,muntasirsyed/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,joewalnes/idea-community,FHannes/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,caot/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,asedunov/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,fitermay/intellij-community,petteyg/intellij-community,slisson/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,izonder/intellij-community,kool79/intellij-community,kool79/intellij-community,robovm/robovm-studio,hurricup/intellij-community,slisson/intellij-community,jexp/idea2,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,retomerz/intellij-community,dslomov/intellij-community,joewalnes/idea-community,amith01994/intellij-community,blademainer/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,clumsy/intellij-community,izonder/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,signed/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,consulo/consulo,vladmm/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,clumsy/intellij-community,hurricup/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,da1z/intellij-community,petteyg/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,ernestp/consulo,hurricup/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,caot/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,jexp/idea2,vladmm/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,diorcety/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,signed/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,ahb0327/intellij-community,petteyg/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,blademainer/intellij-community,robovm/robovm-studio,kdwink/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,kool79/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,caot/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,slisson/intellij-community,ryano144/intellij-community,caot/intellij-community,dslomov/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,supersven/intellij-community,vladmm/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,blademainer/intellij-community,semonte/intellij-community,holmes/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,hurricup/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,dslomov/intellij-community,supersven/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,diorcety/intellij-community,da1z/intellij-community,slisson/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,slisson/intellij-community,xfournet/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,adedayo/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,semonte/intellij-community,da1z/intellij-community,kdwink/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,slisson/intellij-community,apixandru/intellij-community,adedayo/intellij-community,clumsy/intellij-community,jagguli/intellij-community,semonte/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,kool79/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,ol-loginov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,diorcety/intellij-community,semonte/intellij-community,holmes/intellij-community,samthor/intellij-community,apixandru/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,semonte/intellij-community,fitermay/intellij-community,kdwink/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ibinti/intellij-community,petteyg/intellij-community,holmes/intellij-community,retomerz/intellij-community,signed/intellij-community,signed/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,allotria/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,signed/intellij-community,xfournet/intellij-community,FHannes/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,supersven/intellij-community,consulo/consulo,wreckJ/intellij-community,clumsy/intellij-community,samthor/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,da1z/intellij-community,ibinti/intellij-community,caot/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,fnouama/intellij-community,asedunov/intellij-community,holmes/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,holmes/intellij-community,asedunov/intellij-community,caot/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,allotria/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,jexp/idea2,allotria/intellij-community,da1z/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,xfournet/intellij-community,ryano144/intellij-community,dslomov/intellij-community,samthor/intellij-community,consulo/consulo,allotria/intellij-community,gnuhub/intellij-community,samthor/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,consulo/consulo,fitermay/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,supersven/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,izonder/intellij-community,amith01994/intellij-community,ibinti/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,clumsy/intellij-community,kool79/intellij-community,ernestp/consulo,suncycheng/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,semonte/intellij-community,da1z/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,clumsy/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,semonte/intellij-community,caot/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,signed/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,vladmm/intellij-community,FHannes/intellij-community,kool79/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,jexp/idea2,xfournet/intellij-community,youdonghai/intellij-community,caot/intellij-community,jagguli/intellij-community,joewalnes/idea-community,asedunov/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,signed/intellij-community,allotria/intellij-community,izonder/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,xfournet/intellij-community,ryano144/intellij-community,asedunov/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ryano144/intellij-community,da1z/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,FHannes/intellij-community,allotria/intellij-community,signed/intellij-community,vladmm/intellij-community,fnouama/intellij-community,robovm/robovm-studio,holmes/intellij-community
package com.intellij.codeInsight.completion; import com.intellij.codeInsight.TailType; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.psi.*; import com.intellij.psi.filters.*; import com.intellij.psi.filters.classes.*; import com.intellij.psi.filters.element.ExcludeDeclaredFilter; import com.intellij.psi.filters.element.ModifierFilter; import com.intellij.psi.filters.element.ReferenceOnFilter; import com.intellij.psi.filters.getters.UpWalkGetter; import com.intellij.psi.filters.position.*; import com.intellij.psi.filters.types.TypeCodeFragmentIsVoidEnabledFilter; public class JavaCompletionData extends CompletionData{ protected static final String[] MODIFIERS_LIST = { "public", "protected", "private", "static", "final", "native", "abstract", "synchronized", "volatile", "transient" }; private static final String[] ourBlockFinalizers = {"{", "}", ";", ":", "else"}; public JavaCompletionData(){ declareCompletionSpaces(); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, TrueFilter.INSTANCE); variant.includeScopeClass(PsiVariable.class); variant.includeScopeClass(PsiClass.class); variant.includeScopeClass(PsiFile.class); variant.addCompletion(new ModifierChooser()); registerVariant(variant); initVariantsInFileScope(); initVariantsInClassScope(); initVariantsInMethodScope(); initVariantsInFieldScope(); defineScopeEquivalence(PsiMethod.class, PsiClassInitializer.class); defineScopeEquivalence(PsiMethod.class, PsiCodeFragment.class); } private void declareCompletionSpaces() { declareFinalScope(PsiFile.class); { // Class body final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("{"))); variant.includeScopeClass(PsiClass.class, true); this.registerVariant(variant); } { // Method body final CompletionVariant variant = new CompletionVariant(new InsideElementFilter(new ClassFilter(PsiCodeBlock.class))); variant.includeScopeClass(PsiMethod.class, true); variant.includeScopeClass(PsiClassInitializer.class, true); this.registerVariant(variant); } { // Field initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiField.class, true); this.registerVariant(variant); } declareFinalScope(PsiLiteralExpression.class); declareFinalScope(PsiComment.class); } protected void initVariantsInFileScope(){ // package keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new StartElementFilter()); variant.addCompletion(PsiKeyword.PACKAGE); this.registerVariant(variant); } // import keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new OrFilter( new StartElementFilter(), END_OF_BLOCK )); variant.addCompletion(PsiKeyword.IMPORT); this.registerVariant(variant); } // other in file scope { final ElementFilter position = new OrFilter(new ElementFilter[]{ END_OF_BLOCK, new LeftNeighbour(new TextFilter(MODIFIERS_LIST)), new StartElementFilter() }); final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, position); variant.includeScopeClass(PsiClass.class); variant.addCompletion(PsiKeyword.CLASS); variant.addCompletion(PsiKeyword.INTERFACE); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(PsiTypeCodeFragment.class, new StartElementFilter()); addPrimitiveTypes(variant, TailType.NONE); final CompletionVariant variant1 = new CompletionVariant(PsiTypeCodeFragment.class, new AndFilter( new StartElementFilter(), new TypeCodeFragmentIsVoidEnabledFilter() ) ); variant1.addCompletion(PsiKeyword.VOID, TailType.NONE); registerVariant(variant); registerVariant(variant1); } } /** * aClass == null for JspDeclaration scope */ protected void initVariantsInClassScope() { // Completion for extends keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(new AfterElementFilter(new TextFilter("{"))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new NotFilter(new ScopeFilter(new EnumFilter())), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS); variant.excludeScopeClass(PsiAnonymousClass.class); variant.excludeScopeClass(PsiTypeParameter.class); this.registerVariant(variant); } // Completion for implements keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(new AfterElementFilter(new TextFilter("{"))), new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), new NotFilter(new ScopeFilter(new InterfaceFilter())) }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.IMPLEMENTS); variant.excludeScopeClass(PsiAnonymousClass.class); this.registerVariant(variant); } // Completion after extends in interface, type parameter and implements in class // position { final ElementFilter position = new AndFilter( new NotFilter(new AfterElementFilter(new TextFilter("{"))), new OrFilter( new ElementFilter [] { new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, ",")), new ScopeFilter(new InterfaceFilter()) ), new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, "&")), new ScopeFilter(new ClassFilter(PsiTypeParameter.class)) ), new LeftNeighbour(new TextFilter(PsiKeyword.IMPLEMENTS, ",")) } ) ); // completion final OrFilter flags = new OrFilter(); flags.addFilter(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new InterfaceFilter() }) )); flags.addFilter(new ClassFilter(PsiPackage.class)); CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(flags); this.registerVariant(variant); } // Completion for classes in class extends // position { final ElementFilter position = new AndFilter( new NotFilter(new AfterElementFilter(new TextFilter("{"))), new AndFilter(new ElementFilter[]{ new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS)), new ScopeFilter(new NotFilter(new InterfaceFilter())) }) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new NotFilter(new InterfaceFilter()), new ModifierFilter(PsiModifier.FINAL, false) }) )); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // declaration start // position final CompletionVariant variant = new CompletionVariant(PsiClass.class, new AndFilter( new AfterElementFilter(new TextFilter("{")), new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter(MODIFIERS_LIST)) ))); // completion addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.VOID); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS, TailType.SPACE); this.registerVariant(variant); } } private void initVariantsInMethodScope() { { // parameters list completion final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter(new String[]{"(", ",", "final"}))); variant.includeScopeClass(PsiParameterList.class, true); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.FINAL); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } // Completion for classes in method throws section // position { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter(")"), new ParentElementFilter(new ClassFilter(PsiParameterList.class)))); // completion CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.THROWS); this.registerVariant(variant); //in annotation methods variant = new CompletionVariant(PsiAnnotationMethod.class, position); variant.addCompletion(PsiKeyword.DEFAULT); this.registerVariant(variant); } { // Completion for classes in method throws section // position final ElementFilter position = new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.THROWS, ",")), new InsideElementFilter(new ClassFilter(PsiReferenceList.class)) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiMethod.class, true); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // completion for declarations final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter("final")))); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.CLASS); this.registerVariant(variant); } // Completion in cast expressions { final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new AndFilter( new TextFilter("("), new ParentElementFilter(new OrFilter( new ClassFilter(PsiParenthesizedExpression.class), new ClassFilter(PsiTypeCastExpression.class)))))); addPrimitiveTypes(variant); this.registerVariant(variant); } { // instanceof keyword final ElementFilter position = new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiVariable.class)), new TextFilter("this"), new AndFilter(new TextFilter(")"), new ParentElementFilter(new AndFilter( new ClassFilter(PsiTypeCastExpression.class, false), new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpression.class)), new ClassFilter(PsiExpression.class))))), new AndFilter(new TextFilter("]"), new ParentElementFilter(new ClassFilter(PsiArrayAccessExpression.class))) })); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.includeScopeClass(PsiMethod.class); variant.addCompletionFilter(new FalseFilter()); variant.addCompletion(PsiKeyword.INSTANCEOF); this.registerVariant(variant); } { // after instanceof keyword final ElementFilter position = new PreviousElementFilter(new TextFilter(PsiKeyword.INSTANCEOF)); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // after final keyword final ElementFilter position = new AndFilter(new SuperParentFilter(new ClassFilter(PsiCodeBlock.class)), new LeftNeighbour(new TextFilter(PsiKeyword.FINAL))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiDeclarationStatement.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); addPrimitiveTypes(variant); this.registerVariant(variant); } { // Keyword completion in start of declaration final CompletionVariant variant = new CompletionVariant(PsiMethod.class, END_OF_BLOCK); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); addKeywords(variant); this.registerVariant(variant); } { // Keyword completion in returns final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new TextFilter("return"))); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new TextFilter("try")), new ParentElementFilter(new ClassFilter(PsiTryStatement.class)))))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, true); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new NotFilter(new TextFilter("try"))), new ParentElementFilter(new ClassFilter(PsiTryStatement.class)))))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, false); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); //variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } { // Completion for catches final CompletionVariant variant = new CompletionVariant(PsiTryStatement.class, new PreviousElementFilter(new AndFilter( new ParentElementFilter(new ClassFilter(PsiTryStatement.class)), new TextFilter("(") ))); variant.includeScopeClass(PsiParameter.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } // Completion for else expression // completion { final ElementFilter position = new LeftNeighbour( new OrFilter( new AndFilter(new TextFilter("}"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 3)), new AndFilter(new TextFilter(";"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 2)) )); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.ELSE); this.registerVariant(variant); } { // Super/This keyword completion final ElementFilter position = new LeftNeighbour( new AndFilter( new TextFilter("."), new LeftNeighbour( new ReferenceOnFilter(new GeneratorFilter(EqualsFilter.class, new UpWalkGetter(new ClassFilter(PsiClass.class)))) ))); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.SUPER, TailType.DOT); variant.addCompletion(PsiKeyword.THIS, TailType.DOT); this.registerVariant(variant); } { // Class field completion final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour( new AndFilter(new TextFilter("."), new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiClass.class)), new TextFilter(PRIMITIVE_TYPES), new TextFilter("]") }))))); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.CLASS, TailType.NONE); this.registerVariant(variant); } { // break completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new OrFilter( new ScopeFilter(new ClassFilter(PsiSwitchStatement.class)), new InsideElementFilter(new ClassFilter(PsiBlockStatement.class))))); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.includeScopeClass(PsiSwitchStatement.class, false); variant.addCompletion(PsiKeyword.BREAK); this.registerVariant(variant); } { // continue completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new InsideElementFilter(new ClassFilter(PsiBlockStatement.class)))); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.addCompletion(PsiKeyword.CONTINUE); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant( new AndFilter( END_OF_BLOCK, new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchLabelStatement.class)), new LeftNeighbour(new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 2), new AndFilter(new TextFilter(";", "}"),new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 3) )))))); variant.includeScopeClass(PsiSwitchStatement.class, true); variant.addCompletion(PsiKeyword.CASE, TailType.SPACE); variant.addCompletion(PsiKeyword.DEFAULT, ':'); this.registerVariant(variant); } { // primitive arrays after new final CompletionVariant variant = new CompletionVariant(PsiExpression.class, new LeftNeighbour( new AndFilter(new TextFilter("new"), new LeftNeighbour(new NotFilter(new TextFilter(".", "throw"))))) ); variant.includeScopeClass(PsiNewExpression.class, true); addPrimitiveTypes(variant); variant.setItemProperty(LookupItem.BRACKETS_COUNT_ATTR, new Integer(1)); this.registerVariant(variant); } { // after new final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter("new"))); variant.includeScopeClass(PsiNewExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new AndFilter( new ScopeFilter(new ParentElementFilter(new ClassFilter(PsiThrowStatement.class))), new ParentElementFilter(new ClassFilter(PsiNewExpression.class))) ); variant.includeScopeClass(PsiNewExpression.class, false); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); this.registerVariant(variant); } { // completion in reference parameters final CompletionVariant variant = new CompletionVariant(TrueFilter.INSTANCE); variant.includeScopeClass(PsiReferenceParameterList.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // null completion final CompletionVariant variant = new CompletionVariant(new NotFilter(new LeftNeighbour(new TextFilter(".")))); variant.addCompletion("null",TailType.NONE); variant.includeScopeClass(PsiExpressionList.class); this.registerVariant(variant); } } private void initVariantsInFieldScope() { { // completion in initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiVariable.class, false); variant.addCompletionFilterOnElement(new OrFilter( new ClassFilter(PsiVariable.class, false), new ExcludeDeclaredFilter(new ClassFilter(PsiVariable.class)) )); this.registerVariant(variant); } } private static void addPrimitiveTypes(CompletionVariant variant){ addPrimitiveTypes(variant, CompletionVariant.DEFAULT_TAIL_TYPE); } private static void addPrimitiveTypes(CompletionVariant variant, int tailType){ variant.addCompletion(new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.CHAR }, tailType); } private static void addKeywords(CompletionVariant variant){ variant.addCompletion(PsiKeyword.SWITCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.WHILE, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FOR, TailType.LPARENTH); variant.addCompletion(PsiKeyword.TRY, '{'); variant.addCompletion(PsiKeyword.THROW, TailType.SPACE); variant.addCompletion(PsiKeyword.RETURN, TailType.SPACE); variant.addCompletion(PsiKeyword.NEW, TailType.SPACE); variant.addCompletion(PsiKeyword.ASSERT, TailType.SPACE); } static final ElementFilter END_OF_BLOCK = new AndFilter( new LeftNeighbour(new OrFilter(new ElementFilter[]{ new TextFilter(ourBlockFinalizers), new TextFilter("*/"), new AndFilter( new TextFilter(")"), new NotFilter( new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpressionList.class)), new ParentElementFilter(new ClassFilter(PsiParameterList.class)) ) ) ) })), new NotFilter(new TextFilter("."))); private static final String[] PRIMITIVE_TYPES = new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.VOID, PsiKeyword.CHAR, PsiKeyword.BYTE }; }
source/com/intellij/codeInsight/completion/JavaCompletionData.java
package com.intellij.codeInsight.completion; import com.intellij.codeInsight.TailType; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.psi.*; import com.intellij.psi.filters.*; import com.intellij.psi.filters.classes.*; import com.intellij.psi.filters.element.ExcludeDeclaredFilter; import com.intellij.psi.filters.element.ModifierFilter; import com.intellij.psi.filters.element.ReferenceOnFilter; import com.intellij.psi.filters.getters.UpWalkGetter; import com.intellij.psi.filters.position.*; import com.intellij.psi.filters.types.TypeCodeFragmentIsVoidEnabledFilter; class JavaCompletionData extends CompletionData{ protected static final String[] MODIFIERS_LIST = { "public", "protected", "private", "static", "final", "native", "abstract", "synchronized", "volatile", "transient" }; private static final String[] ourBlockFinalizers = {"{", "}", ";", ":", "else"}; public JavaCompletionData(){ declareCompletionSpaces(); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, TrueFilter.INSTANCE); variant.includeScopeClass(PsiVariable.class); variant.includeScopeClass(PsiClass.class); variant.includeScopeClass(PsiFile.class); variant.addCompletion(new ModifierChooser()); registerVariant(variant); initVariantsInFileScope(); initVariantsInClassScope(); initVariantsInMethodScope(); initVariantsInFieldScope(); defineScopeEquivalence(PsiMethod.class, PsiClassInitializer.class); defineScopeEquivalence(PsiMethod.class, PsiCodeFragment.class); } private void declareCompletionSpaces() { declareFinalScope(PsiFile.class); { // Class body final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("{"))); variant.includeScopeClass(PsiClass.class, true); this.registerVariant(variant); } { // Method body final CompletionVariant variant = new CompletionVariant(new InsideElementFilter(new ClassFilter(PsiCodeBlock.class))); variant.includeScopeClass(PsiMethod.class, true); variant.includeScopeClass(PsiClassInitializer.class, true); this.registerVariant(variant); } { // Field initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiField.class, true); this.registerVariant(variant); } declareFinalScope(PsiLiteralExpression.class); declareFinalScope(PsiComment.class); } protected void initVariantsInFileScope(){ // package keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new StartElementFilter()); variant.addCompletion(PsiKeyword.PACKAGE); this.registerVariant(variant); } // import keyword completion { final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new OrFilter( new StartElementFilter(), END_OF_BLOCK )); variant.addCompletion(PsiKeyword.IMPORT); this.registerVariant(variant); } // other in file scope { final ElementFilter position = new OrFilter(new ElementFilter[]{ END_OF_BLOCK, new LeftNeighbour(new TextFilter(MODIFIERS_LIST)), new StartElementFilter() }); final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, position); variant.includeScopeClass(PsiClass.class); variant.addCompletion(PsiKeyword.CLASS); variant.addCompletion(PsiKeyword.INTERFACE); registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(PsiTypeCodeFragment.class, new StartElementFilter()); addPrimitiveTypes(variant, TailType.NONE); final CompletionVariant variant1 = new CompletionVariant(PsiTypeCodeFragment.class, new AndFilter( new StartElementFilter(), new TypeCodeFragmentIsVoidEnabledFilter() ) ); variant1.addCompletion(PsiKeyword.VOID, TailType.NONE); registerVariant(variant); registerVariant(variant1); } } /** * aClass == null for JspDeclaration scope */ protected void initVariantsInClassScope() { // Completion for extends keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(new AfterElementFilter(new TextFilter("{"))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new NotFilter(new ScopeFilter(new EnumFilter())), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS); variant.excludeScopeClass(PsiAnonymousClass.class); variant.excludeScopeClass(PsiTypeParameter.class); this.registerVariant(variant); } // Completion for implements keyword // position { final ElementFilter position = new AndFilter(new ElementFilter[]{ new NotFilter(new AfterElementFilter(new TextFilter("{"))), new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))), new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))), new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))), new LeftNeighbour(new OrFilter( new ClassFilter(PsiIdentifier.class), new TextFilter(">"))), new NotFilter(new ScopeFilter(new InterfaceFilter())) }); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.IMPLEMENTS); variant.excludeScopeClass(PsiAnonymousClass.class); this.registerVariant(variant); } // Completion after extends in interface, type parameter and implements in class // position { final ElementFilter position = new AndFilter( new NotFilter(new AfterElementFilter(new TextFilter("{"))), new OrFilter( new ElementFilter [] { new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, ",")), new ScopeFilter(new InterfaceFilter()) ), new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, "&")), new ScopeFilter(new ClassFilter(PsiTypeParameter.class)) ), new LeftNeighbour(new TextFilter(PsiKeyword.IMPLEMENTS, ",")) } ) ); // completion final OrFilter flags = new OrFilter(); flags.addFilter(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new InterfaceFilter() }) )); flags.addFilter(new ClassFilter(PsiPackage.class)); CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(flags); this.registerVariant(variant); } // Completion for classes in class extends // position { final ElementFilter position = new AndFilter( new NotFilter(new AfterElementFilter(new TextFilter("{"))), new AndFilter(new ElementFilter[]{ new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS)), new ScopeFilter(new NotFilter(new InterfaceFilter())) }) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiClass.class, true); variant.excludeScopeClass(PsiAnonymousClass.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter( new AndFilter(new ElementFilter[]{ new ClassFilter(PsiClass.class), new NotFilter(new AssignableFromContextFilter()), new NotFilter(new InterfaceFilter()), new ModifierFilter(PsiModifier.FINAL, false) }) )); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // declaration start // position final CompletionVariant variant = new CompletionVariant(PsiClass.class, new AndFilter( new AfterElementFilter(new TextFilter("{")), new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter(MODIFIERS_LIST)) ))); // completion addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.VOID); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))); variant.includeScopeClass(PsiClass.class, true); variant.addCompletion(PsiKeyword.EXTENDS, TailType.SPACE); this.registerVariant(variant); } } private void initVariantsInMethodScope() { { // parameters list completion final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter(new String[]{"(", ",", "final"}))); variant.includeScopeClass(PsiParameterList.class, true); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.FINAL); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } // Completion for classes in method throws section // position { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter(")"), new ParentElementFilter(new ClassFilter(PsiParameterList.class)))); // completion CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.THROWS); this.registerVariant(variant); //in annotation methods variant = new CompletionVariant(PsiAnnotationMethod.class, position); variant.addCompletion(PsiKeyword.DEFAULT); this.registerVariant(variant); } { // Completion for classes in method throws section // position final ElementFilter position = new AndFilter( new LeftNeighbour(new TextFilter(PsiKeyword.THROWS, ",")), new InsideElementFilter(new ClassFilter(PsiReferenceList.class)) ); // completion final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiMethod.class, true); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } { // completion for declarations final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter("final")))); addPrimitiveTypes(variant); variant.addCompletion(PsiKeyword.CLASS); this.registerVariant(variant); } // Completion in cast expressions { final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new AndFilter( new TextFilter("("), new ParentElementFilter(new OrFilter( new ClassFilter(PsiParenthesizedExpression.class), new ClassFilter(PsiTypeCastExpression.class)))))); addPrimitiveTypes(variant); this.registerVariant(variant); } { // instanceof keyword final ElementFilter position = new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiVariable.class)), new TextFilter("this"), new AndFilter(new TextFilter(")"), new ParentElementFilter(new AndFilter( new ClassFilter(PsiTypeCastExpression.class, false), new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpression.class)), new ClassFilter(PsiExpression.class))))), new AndFilter(new TextFilter("]"), new ParentElementFilter(new ClassFilter(PsiArrayAccessExpression.class))) })); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.includeScopeClass(PsiMethod.class); variant.addCompletionFilter(new FalseFilter()); variant.addCompletion(PsiKeyword.INSTANCEOF); this.registerVariant(variant); } { // after instanceof keyword final ElementFilter position = new PreviousElementFilter(new TextFilter(PsiKeyword.INSTANCEOF)); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // after final keyword final ElementFilter position = new AndFilter(new SuperParentFilter(new ClassFilter(PsiCodeBlock.class)), new LeftNeighbour(new TextFilter(PsiKeyword.FINAL))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiDeclarationStatement.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); addPrimitiveTypes(variant); this.registerVariant(variant); } { // Keyword completion in start of declaration final CompletionVariant variant = new CompletionVariant(PsiMethod.class, END_OF_BLOCK); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); addKeywords(variant); this.registerVariant(variant); } { // Keyword completion in returns final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new TextFilter("return"))); variant.addCompletion(PsiKeyword.THIS, TailType.NONE); variant.addCompletion(PsiKeyword.SUPER, TailType.NONE); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new TextFilter("try")), new ParentElementFilter(new ClassFilter(PsiTryStatement.class)))))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, true); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } // Catch/Finnaly completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), new ParentElementFilter(new AndFilter( new LeftNeighbour(new NotFilter(new TextFilter("try"))), new ParentElementFilter(new ClassFilter(PsiTryStatement.class)))))); final CompletionVariant variant = new CompletionVariant(position); variant.includeScopeClass(PsiCodeBlock.class, false); variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FINALLY, '{'); //variant.addCompletionFilter(new FalseFilter()); this.registerVariant(variant); } { // Completion for catches final CompletionVariant variant = new CompletionVariant(PsiTryStatement.class, new PreviousElementFilter(new AndFilter( new ParentElementFilter(new ClassFilter(PsiTryStatement.class)), new TextFilter("(") ))); variant.includeScopeClass(PsiParameter.class); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class)); this.registerVariant(variant); } // Completion for else expression // completion { final ElementFilter position = new LeftNeighbour( new OrFilter( new AndFilter(new TextFilter("}"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 3)), new AndFilter(new TextFilter(";"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 2)) )); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.addCompletion(PsiKeyword.ELSE); this.registerVariant(variant); } { // Super/This keyword completion final ElementFilter position = new LeftNeighbour( new AndFilter( new TextFilter("."), new LeftNeighbour( new ReferenceOnFilter(new GeneratorFilter(EqualsFilter.class, new UpWalkGetter(new ClassFilter(PsiClass.class)))) ))); final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.SUPER, TailType.DOT); variant.addCompletion(PsiKeyword.THIS, TailType.DOT); this.registerVariant(variant); } { // Class field completion final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour( new AndFilter(new TextFilter("."), new LeftNeighbour(new OrFilter(new ElementFilter[]{ new ReferenceOnFilter(new ClassFilter(PsiClass.class)), new TextFilter(PRIMITIVE_TYPES), new TextFilter("]") }))))); variant.includeScopeClass(PsiVariable.class); variant.addCompletion(PsiKeyword.CLASS, TailType.NONE); this.registerVariant(variant); } { // break completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new OrFilter( new ScopeFilter(new ClassFilter(PsiSwitchStatement.class)), new InsideElementFilter(new ClassFilter(PsiBlockStatement.class))))); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.includeScopeClass(PsiSwitchStatement.class, false); variant.addCompletion(PsiKeyword.BREAK); this.registerVariant(variant); } { // continue completion final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new InsideElementFilter(new ClassFilter(PsiBlockStatement.class)))); variant.includeScopeClass(PsiForeachStatement.class, false); variant.includeScopeClass(PsiForStatement.class, false); variant.includeScopeClass(PsiWhileStatement.class, false); variant.includeScopeClass(PsiDoWhileStatement.class, false); variant.addCompletion(PsiKeyword.CONTINUE); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant( new AndFilter( END_OF_BLOCK, new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchLabelStatement.class)), new LeftNeighbour(new OrFilter( new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 2), new AndFilter(new TextFilter(";", "}"),new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 3) )))))); variant.includeScopeClass(PsiSwitchStatement.class, true); variant.addCompletion(PsiKeyword.CASE, TailType.SPACE); variant.addCompletion(PsiKeyword.DEFAULT, ':'); this.registerVariant(variant); } { // primitive arrays after new final CompletionVariant variant = new CompletionVariant(PsiExpression.class, new LeftNeighbour( new AndFilter(new TextFilter("new"), new LeftNeighbour(new NotFilter(new TextFilter(".", "throw"))))) ); variant.includeScopeClass(PsiNewExpression.class, true); addPrimitiveTypes(variant); variant.setItemProperty(LookupItem.BRACKETS_COUNT_ATTR, new Integer(1)); this.registerVariant(variant); } { // after new final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter("new"))); variant.includeScopeClass(PsiNewExpression.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { final CompletionVariant variant = new CompletionVariant(new AndFilter( new ScopeFilter(new ParentElementFilter(new ClassFilter(PsiThrowStatement.class))), new ParentElementFilter(new ClassFilter(PsiNewExpression.class))) ); variant.includeScopeClass(PsiNewExpression.class, false); variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable"))); this.registerVariant(variant); } { // completion in reference parameters final CompletionVariant variant = new CompletionVariant(TrueFilter.INSTANCE); variant.includeScopeClass(PsiReferenceParameterList.class, true); variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class)); this.registerVariant(variant); } { // null completion final CompletionVariant variant = new CompletionVariant(new NotFilter(new LeftNeighbour(new TextFilter(".")))); variant.addCompletion("null",TailType.NONE); variant.includeScopeClass(PsiExpressionList.class); this.registerVariant(variant); } } private void initVariantsInFieldScope() { { // completion in initializer final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("="))); variant.includeScopeClass(PsiVariable.class, false); variant.addCompletionFilterOnElement(new OrFilter( new ClassFilter(PsiVariable.class, false), new ExcludeDeclaredFilter(new ClassFilter(PsiVariable.class)) )); this.registerVariant(variant); } } private static void addPrimitiveTypes(CompletionVariant variant){ addPrimitiveTypes(variant, CompletionVariant.DEFAULT_TAIL_TYPE); } private static void addPrimitiveTypes(CompletionVariant variant, int tailType){ variant.addCompletion(new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.CHAR }, tailType); } private static void addKeywords(CompletionVariant variant){ variant.addCompletion(PsiKeyword.SWITCH, TailType.LPARENTH); variant.addCompletion(PsiKeyword.WHILE, TailType.LPARENTH); variant.addCompletion(PsiKeyword.FOR, TailType.LPARENTH); variant.addCompletion(PsiKeyword.TRY, '{'); variant.addCompletion(PsiKeyword.THROW, TailType.SPACE); variant.addCompletion(PsiKeyword.RETURN, TailType.SPACE); variant.addCompletion(PsiKeyword.NEW, TailType.SPACE); variant.addCompletion(PsiKeyword.ASSERT, TailType.SPACE); } static final ElementFilter END_OF_BLOCK = new AndFilter( new LeftNeighbour(new OrFilter(new ElementFilter[]{ new TextFilter(ourBlockFinalizers), new TextFilter("*/"), new AndFilter( new TextFilter(")"), new NotFilter( new OrFilter( new ParentElementFilter(new ClassFilter(PsiExpressionList.class)), new ParentElementFilter(new ClassFilter(PsiParameterList.class)) ) ) ) })), new NotFilter(new TextFilter("."))); private static final String[] PRIMITIVE_TYPES = new String[]{ PsiKeyword.SHORT, PsiKeyword.BOOLEAN, PsiKeyword.DOUBLE, PsiKeyword.LONG, PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.VOID, PsiKeyword.CHAR, PsiKeyword.BYTE }; }
completion data now is public
source/com/intellij/codeInsight/completion/JavaCompletionData.java
completion data now is public
<ide><path>ource/com/intellij/codeInsight/completion/JavaCompletionData.java <ide> import com.intellij.psi.filters.position.*; <ide> import com.intellij.psi.filters.types.TypeCodeFragmentIsVoidEnabledFilter; <ide> <del>class JavaCompletionData extends CompletionData{ <add>public class JavaCompletionData extends CompletionData{ <ide> <ide> protected static final String[] MODIFIERS_LIST = { <ide> "public", "protected", "private",
JavaScript
unlicense
715181b27f96a7db6b68ff5a0f963c4fd2e06ed9
0
geraldbaeck/NIUsLittleHelper,geraldbaeck/NIUsLittleHelper
function cleanName(name) { if (name) { name = name.replace(/(\r\n|\n|\r)/gm, '').replace('\t', ''); while (name.includes(' ')) { name = name.replace(' ', ' ').trim(); } } else { name = '-'; } return name; } // extrahiert Mitarbeiterdaten aus dem Link // eg. <a href="javascript:SEmpFNRID('0ba9916e-e305-4df6-b318-a671013118a1');">Bäck (7822)</a> function getEmployeeDataFromLink(link, link_identifier='EmployeeNumberID') { var employeeData = { displayName: cleanName($(link).text()), id: undefined, url: undefined } var rawID = $(link).attr('href'); if (rawID != undefined) { employeeData.id = rawID.substring(rawID.indexOf('\'') + 1,rawID.lastIndexOf('\'')); employeeData.url = 'https://niu.wrk.at/Kripo/Employee/shortemployee.aspx?' + link_identifier + '=' + employeeData.id; } return employeeData; } // erstellt ein Kalendar Export Element function createCalElement(termin) { return createCalendar({ options: { class: 'calExport', id: termin.id, // You can pass an ID. If you don't, one will be generated linkText: '<img src="' + chrome.extension.getURL('/img/addCal.png') + '" style="margin-right:0.2em;"><span style="display:table-cell;vertical-align:middle;">Export</span>', }, data: termin }); } // berechnet aus der angegebenen Zeitspanne im NIU (zb 18:00 - 00:00) // die Dauer in Stunden // currentDateString: das im NIU verwendete Datum eg. "19.03.2017" // timeString: im Niu verwendete Zeitpsanne eg "18:00 - 00:00" // returns hours (float) function getDurationFromTimeString(currentDateString, timeString) { var startTime = timeString.substring(0, 6); var stopTime = timeString.substring(8, 15).trim(); var pattern = /(\d{2})\.(\d{2})\.(\d{4})/; startDate = new Date(currentDateString.replace(pattern,'$3-$2-$1 ') + startTime); stopDate = new Date(currentDateString.replace(pattern,'$3-$2-$1 ') + stopTime); if (stopDate <= startDate) { stopDate.setDate(stopDate.getDate() + 1); // add one day if dienst ends on the next day }; var hours = Math.abs(stopDate - startDate) / 36e5; return hours; } // liest die verfügbaren Funktionen aus der Dienstplan-Tabelle aus // header: jquery object of table header tr function getDuties(header) { duties = {}; header.find('td').each(function(key, val) { if ($(val).hasClass('DRCShift')) { duties[key.toString()] = $(val).text(); } }); return duties; } // gibt die spaltennummer einer tabelle für eine bestimmte headerklasse zurück // CAVE: gibt nur die erste Spaltennummer zurück, weiter vorkommen werden ignoriert. function getHeaderNumber(header, className) { var nr; header.find('td').each(function(key, val) { if ($(val).hasClass(className)) { nr = key; return false; // break the jquery.each loop (very weird) } }); return nr; } // erstellt die fertige VCard function createVCard(employee) { function addVCardEntry(k, v) { vCard += k + ":" + v + "\n"; } var vCard = 'BEGIN:VCARD\nVERSION:3.0\n'; vCard += "ORG:Österreichisches Rotes Kreuz - Landesverband Wien\n"; vCard += "PROFILE:VCARD\n"; vCard += "TZ:+0100\n"; vCard += "CATEGORIES:WRK,ÖRK\n"; addVCardEntry("FN", employee.nameFull); addVCardEntry("N", employee.nameLast + ';' + employee.nameFirst + ';;;') addVCardEntry("URL", employee.url); addVCardEntry("REV", new Date().toISOString()); addVCardEntry("PHOTO;TYPE=PNG", employee.imageUrl); addVCardEntry("UID", 'urn:uuid:' + employee.uid); addVCardEntry("NOTE", employee.notes); console.log(employee.contacts); $.each(employee.contacts, function() { addVCardEntry(this.k, this.v); }); vCard += 'END:VCARD\n' return vCard; } // holt die verfügbaren MitarbeiterInnenDaten function scrapeEmployee(jqObj, employeeLink) { var employee = {}; // Name var nameString = $(jqObj).find('#ctl00_main_shortEmpl_EmployeeName').text().trim(); employee.nameFull = nameString.substring(0, nameString.indexOf('(')).trim(); var nameArr = employee.nameFull.split(/\s+/); employee.nameFirst = nameArr.slice(0, -1).join(' '); employee.nameLast = nameArr.pop(); employee.dienstnummer = nameString.substring(nameString.indexOf('(') + 1, nameString.indexOf(')')); console.log('Scraped:' + employee.FN + '(' + employee.dienstnummer + ')'); // Foto employee.imageUrl = new URL($($(jqObj).find('#ctl00_main_shortEmpl_EmployeeImage')[0]).attr('src'), employeeLink).href; employee.url = employeeLink; employee.uid = getUID(employeeLink); // Funktionen/Berechtigungen Notizen employee.notes = 'WRK Dienstnummer: ' + employee.dienstnummer; $('.PermissionRow').each(function () { employee.notes += '\\n' + $(this).find('.PermissionType').text().trim() + ': ' + $(this).find('.PermissionName').text().trim(); }); employee.contacts = scrapeContactPoint(jqObj, "ctl00_main_shortEmpl_contacts_m_tblPersonContactMain"); console.log(employee); return employee; } function createVCFDownloadLink(employee, vCard) { var file = new Blob([vCard]); var a = document.createElement('a'); a.href = window.URL.createObjectURL(file); $(a).append('<img alt="Download VCF" style="margin:7px;" src="' + chrome.extension.getURL('/img/vcf32.png') + '">'); a.download = employee.nameFull.replace(/[^a-z0-9]/gi, '_').toLowerCase() + '.vcf'; // set a safe file name a.id = 'vcfLink'; return a; } // query url for the UID function getUID(url) { url = url.toLowerCase(); var param = 'employeeid'; if (url.includes('employeenumberid')) { param = 'employeenumberid'; } var u = new URL(url); return u.searchParams.get(param); } // Kontaktmöglichkeiten function scrapeContactPoint(jqObj, tid) { var contactPoints = []; var values = []; $(jqObj).find('table#'+ tid + ' tbody tr[id]').each(function () { var key; switch ($($(this).find('span[id]')[0]).text().split(' ')[0]) { case 'Telefon': key = 'TEL;'; break; case 'Handy': case 'Bereitschaft': key = 'TEL;TYPE=cell;' break; case 'Fax': key = 'TEL;TYPE=fax;' break; case 'e-mail': key = 'EMAIL;TYPE=internet;' break; default: break; } switch ($($(this).find('span[id]')[0]).text().split(' ')[1]) { case 'geschäftlich': case 'WRK': key += 'TYPE=work;'; break; case 'privat': key += 'TYPE=home;'; break; default: break; } if (key) { // ignore Notruf Pager var point = {}; var value = $($(this).find('span[id]')[1]).text().trim(); if($.inArray(value, values)<0) { // deduplication point['k'] = key.substring(0, key.length - 1); point['v'] = value; contactPoints.push(point); values.push(value); } } }); return contactPoints; }
src/content_scripts/lib/calendar-lib.js
function cleanName(name) { if (name) { name = name.replace(/(\r\n|\n|\r)/gm, '').replace('\t', ''); while (name.includes(' ')) { name = name.replace(' ', ' ').trim(); } } else { name = '-'; } return name; } // extrahiert Mitarbeiterdaten aus dem Link // eg. <a href="javascript:SEmpFNRID('0ba9916e-e305-4df6-b318-a671013118a1');">Bäck (7822)</a> function getEmployeeDataFromLink(link, link_identifier='EmployeeNumberID') { var employeeData = { displayName: cleanName($(link).text()), id: undefined, url: undefined } var rawID = $(link).attr('href'); if (rawID != undefined) { employeeData.id = rawID.substring(rawID.indexOf('\'') + 1,rawID.lastIndexOf('\'')); employeeData.url = 'https://niu.wrk.at/Kripo/Employee/shortemployee.aspx?' + link_identifier + '=' + employeeData.id; } return employeeData; } // erstellt ein Kalendar Export Element function createCalElement(termin) { return createCalendar({ options: { class: 'calExport', id: termin.id, // You can pass an ID. If you don't, one will be generated linkText: '<img src="' + chrome.extension.getURL('/img/addCal.png') + '" style="margin-right:0.2em;"><span style="display:table-cell;vertical-align:middle;">Export</span>', }, data: termin }); } // berechnet aus der angegebenen Zeitspanne im NIU (zb 18:00 - 00:00) // die Dauer in Stunden // currentDateString: das im NIU verwendete Datum eg. "19.03.2017" // timeString: im Niu verwendete Zeitpsanne eg "18:00 - 00:00" // returns hours (float) function getDurationFromTimeString(currentDateString, timeString) { var startTime = timeString.substring(0, 6); var stopTime = timeString.substring(8, 15).trim(); var pattern = /(\d{2})\.(\d{2})\.(\d{4})/; startDate = new Date(currentDateString.replace(pattern,'$3-$2-$1 ') + startTime); stopDate = new Date(currentDateString.replace(pattern,'$3-$2-$1 ') + stopTime); if (stopDate <= startDate) { stopDate.setDate(stopDate.getDate() + 1); // add one day if dienst ends on the next day }; var hours = Math.abs(stopDate - startDate) / 36e5; return hours; } // liest die verfügbaren Funktionen aus der Dienstplan-Tabelle aus // header: jquery object of table header tr function getDuties(header) { duties = {}; header.find('td').each(function(key, val) { if ($(val).hasClass('DRCShift')) { duties[key.toString()] = $(val).text(); } }); return duties; } // gibt die spaltennummer einer tabelle für eine bestimmte headerklasse zurück // CAVE: gibt nur die erste Spaltennummer zurück, weiter vorkommen werden ignoriert. function getHeaderNumber(header, className) { var nr; header.find('td').each(function(key, val) { if ($(val).hasClass(className)) { nr = key; return false; // break the jquery.each loop (very weird) } }); return nr; } // erstellt die fertige VCard function createVCard(employee) { function addVCardEntry(k, v) { vCard += k + ":" + v + "\n"; } var vCard = 'BEGIN:VCARD\nVERSION:3.0\n'; vCard += "ORG:Österreichisches Rotes Kreuz - Landesverband Wien\n"; vCard += "PROFILE:VCARD\n"; vCard += "TZ:+0100\n"; vCard += "CATEGORIES:WRK,ÖRK\n"; addVCardEntry("FN", employee.nameFull); addVCardEntry("N", employee.nameLast + ';' + employee.nameFirst + ';;;') addVCardEntry("URL", employee.url); addVCardEntry("REV", new Date().toISOString()); addVCardEntry("PHOTO;TYPE=PNG", employee.imageUrl); addVCardEntry("UID", 'urn:uuid:' + employee.uid); addVCardEntry("NOTE", employee.notes); console.log(employee.contacts); $.each(employee.contacts, function() { addVCardEntry(this.k, this.v); }); vCard += 'END:VCARD\n' return vCard; } // holt die verfügbaren MitarbeiterInnenDaten function scrapeEmployee(jqObj, employeeLink) { var employee = {}; // Name var nameString = $(jqObj).find('#ctl00_main_shortEmpl_EmployeeName').text().trim(); employee.nameFull = nameString.substring(0, nameString.indexOf('(')).trim(); var nameArr = employee.nameFull.split(/\s+/); employee.nameFirst = nameArr.slice(0, -1).join(' '); employee.nameLast = nameArr.pop(); employee.dienstnummer = nameString.substring(nameString.indexOf('(') + 1, nameString.indexOf(')')); console.log('Scraped:' + employee.FN + '(' + employee.dienstnummer + ')'); // Foto employee.imageUrl = new URL($($(jqObj).find('#ctl00_main_shortEmpl_EmployeeImage')[0]).attr('src'), employeeLink).href; employee.url = employeeLink; employee.uid = getUID(employeeLink); // Funktionen/Berechtigungen Notizen employee.notes = 'WRK Dienstnummer: ' + employee.dienstnummer; $('.PermissionRow').each(function () { employee.notes += '\\n' + $(this).find('.PermissionType').text().trim() + ': ' + $(this).find('.PermissionName').text().trim(); }); employee.contacts = scrapeContactPoint(jqObj, "ctl00_main_shortEmpl_contacts_m_tblPersonContactMain"); console.log(employee); return employee; } function createVCFDownloadLink(employee, vCard) { var file = new Blob([vCard]); var a = document.createElement('a'); a.href = window.URL.createObjectURL(file); $(a).append('<img alt="Download VCF" style="margin:7px;" src="' + chrome.extension.getURL('/img/vcf32.png') + '">'); a.download = employee.nameFull.replace(/[^a-z0-9]/gi, '_').toLowerCase() + '.vcf'; // set a safe file name a.id = 'vcfLink'; return a; } // query url for the UID function getUID(url) { var name = 'EmployeeID'; if (url.includes('EmployeeNumberID')) { name = 'EmployeeNumberID'; } var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url); return results[1] || 0; } // Kontaktmöglichkeiten function scrapeContactPoint(jqObj, tid) { var contactPoints = []; var values = []; $(jqObj).find('table#'+ tid + ' tbody tr[id]').each(function () { var key; switch ($($(this).find('span[id]')[0]).text().split(' ')[0]) { case 'Telefon': key = 'TEL;'; break; case 'Handy': case 'Bereitschaft': key = 'TEL;TYPE=cell;' break; case 'Fax': key = 'TEL;TYPE=fax;' break; case 'e-mail': key = 'EMAIL;TYPE=internet;' break; default: break; } switch ($($(this).find('span[id]')[0]).text().split(' ')[1]) { case 'geschäftlich': case 'WRK': key += 'TYPE=work;'; break; case 'privat': key += 'TYPE=home;'; break; default: break; } if (key) { // ignore Notruf Pager var point = {}; var value = $($(this).find('span[id]')[1]).text().trim(); if($.inArray(value, values)<0) { // deduplication point['k'] = key.substring(0, key.length - 1); point['v'] = value; contactPoints.push(point); values.push(value); } } }); return contactPoints; }
more robust uuid routine
src/content_scripts/lib/calendar-lib.js
more robust uuid routine
<ide><path>rc/content_scripts/lib/calendar-lib.js <ide> <ide> // query url for the UID <ide> function getUID(url) { <del> var name = 'EmployeeID'; <del> if (url.includes('EmployeeNumberID')) { <del> name = 'EmployeeNumberID'; <del> } <del> var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url); <del> return results[1] || 0; <add> url = url.toLowerCase(); <add> var param = 'employeeid'; <add> if (url.includes('employeenumberid')) { <add> param = 'employeenumberid'; <add> } <add> var u = new URL(url); <add> return u.searchParams.get(param); <ide> } <ide> <ide> // Kontaktmöglichkeiten
Java
apache-2.0
91b5a9b13444863e2481f1c005b47bfea9d378ec
0
emre-aydin/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.internal.partition.impl; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.ClusterState; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.impl.MemberImpl; import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.instance.StaticMemberNodeContext; import com.hazelcast.internal.partition.InternalPartition; import com.hazelcast.internal.partition.PartitionReplica; import com.hazelcast.internal.partition.PartitionTableView; import com.hazelcast.spi.exception.TargetNotMemberException; import com.hazelcast.spi.exception.WrongTargetException; import com.hazelcast.spi.impl.operationservice.ExceptionAction; import com.hazelcast.spi.impl.operationservice.Operation; import com.hazelcast.spi.impl.operationservice.impl.OperationServiceImpl; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.OverridePropertyRule; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.hazelcast.instance.impl.HazelcastInstanceFactory.newHazelcastInstance; import static com.hazelcast.instance.impl.TestUtil.terminateInstance; import static com.hazelcast.internal.cluster.impl.AdvancedClusterStateTest.changeClusterStateEventually; import static com.hazelcast.internal.cluster.impl.ClusterJoinManager.STALE_JOIN_PREVENTION_DURATION_PROP; import static com.hazelcast.internal.util.UuidUtil.newUnsecureUUID; import static com.hazelcast.test.Accessors.getClusterService; import static com.hazelcast.test.Accessors.getNode; import static com.hazelcast.test.Accessors.getOperationService; import static com.hazelcast.test.Accessors.getPartitionService; import static com.hazelcast.test.OverridePropertyRule.clear; import static com.hazelcast.test.TestHazelcastInstanceFactory.initOrCreateConfig; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class FrozenPartitionTableTest extends HazelcastTestSupport { @Rule public final OverridePropertyRule ruleStaleJoinPreventionDuration = clear(STALE_JOIN_PREVENTION_DURATION_PROP); @Test public void partitionTable_isFrozen_whenNodesLeave_duringClusterStateIsFrozen() { testPartitionTableIsFrozenDuring(ClusterState.FROZEN); } @Test public void partitionTable_isFrozen_whenNodesLeave_duringClusterStateIsPassive() { testPartitionTableIsFrozenDuring(ClusterState.PASSIVE); } private void testPartitionTableIsFrozenDuring(final ClusterState clusterState) { final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3); HazelcastInstance[] instances = factory.newInstances(); warmUpPartitions(instances); changeClusterStateEventually(instances[0], clusterState); List<HazelcastInstance> instancesList = new ArrayList<HazelcastInstance>(asList(instances)); Collections.shuffle(instancesList); final PartitionTableView partitionTable = getPartitionTable(instances[0]); while (instancesList.size() > 1) { final HazelcastInstance instanceToShutdown = instancesList.remove(0); instanceToShutdown.shutdown(); for (HazelcastInstance instance : instancesList) { assertClusterSizeEventually(instancesList.size(), instance); assertEquals(partitionTable, getPartitionTable(instance)); } } } @Test public void partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIsFrozen() { partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIs(ClusterState.FROZEN); } @Test public void partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIsPassive() { partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIs(ClusterState.PASSIVE); } private void partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIs(ClusterState state) { Config config = new Config(); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(4); HazelcastInstance[] instances = factory.newInstances(config, 3); HazelcastInstance hz1 = instances[0]; HazelcastInstance hz2 = instances[1]; HazelcastInstance hz3 = instances[2]; Address hz3Address = getNode(hz3).getThisAddress(); warmUpPartitions(instances); final PartitionTableView partitionTable = getPartitionTable(hz1); changeClusterStateEventually(hz2, state); final Member member3 = getClusterService(hz3).getLocalMember(); terminateInstance(hz2); terminateInstance(hz3); hz3 = factory.newHazelcastInstance(hz3Address); final Member newMember3 = getClusterService(hz3).getLocalMember(); assertClusterSizeEventually(2, hz1, hz3); final List<HazelcastInstance> instanceList = asList(hz1, hz3); assertTrueAllTheTime(new AssertTask() { @Override public void run() { for (HazelcastInstance instance : instanceList) { PartitionTableView newPartitionTable = getPartitionTable(instance); for (int i = 0; i < newPartitionTable.length(); i++) { for (int j = 0; j < InternalPartition.MAX_REPLICA_COUNT; j++) { PartitionReplica replica = partitionTable.getReplica(i, j); PartitionReplica newReplica = newPartitionTable.getReplica(i, j); if (replica == null) { assertNull(newReplica); } else if (replica.equals(PartitionReplica.from(member3))) { assertEquals(PartitionReplica.from(newMember3), newReplica); } else { assertEquals(replica, newReplica); } } } } } }, 5); } @Test public void partitionTable_shouldBeFixed_whenMemberLeaves_inFrozenState_thenStateChangesToActive() { testPartitionTableIsHealedWhenClusterStateIsActiveAfter(ClusterState.FROZEN); } @Test public void partitionTable_shouldBeFixed_whenMemberLeaves_inPassiveState_thenStateChangesToActive() { testPartitionTableIsHealedWhenClusterStateIsActiveAfter(ClusterState.PASSIVE); } private void testPartitionTableIsHealedWhenClusterStateIsActiveAfter(final ClusterState clusterState) { final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3); HazelcastInstance[] instances = factory.newInstances(); warmUpPartitions(instances); changeClusterStateEventually(instances[0], clusterState); List<HazelcastInstance> instancesList = new ArrayList<HazelcastInstance>(asList(instances)); Collections.shuffle(instancesList); final HazelcastInstance instanceToShutdown = instancesList.remove(0); final Address addressToShutdown = getNode(instanceToShutdown).getThisAddress(); instanceToShutdown.shutdown(); for (HazelcastInstance instance : instancesList) { assertClusterSizeEventually(2, instance); } changeClusterStateEventually(instancesList.get(0), ClusterState.ACTIVE); waitAllForSafeState(instancesList); for (HazelcastInstance instance : instancesList) { PartitionTableView partitionTable = getPartitionTable(instance); for (int i = 0; i < partitionTable.length(); i++) { for (PartitionReplica replica : partitionTable.getReplicas(i)) { if (replica == null) { continue; } assertNotEquals(addressToShutdown, replica.address()); } } } } @Test public void partitionTable_shouldBeFixed_whenMemberRestarts_usingNewUuid() { ruleStaleJoinPreventionDuration.setOrClearProperty("5"); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz1 = factory.newHazelcastInstance(); HazelcastInstance hz2 = factory.newHazelcastInstance(); HazelcastInstance hz3 = factory.newHazelcastInstance(); assertClusterSizeEventually(3, hz2, hz3); warmUpPartitions(hz1, hz2, hz3); changeClusterStateEventually(hz3, ClusterState.FROZEN); int member3PartitionId = getPartitionId(hz3); MemberImpl member3 = getNode(hz3).getLocalMember(); hz3.shutdown(); assertClusterSizeEventually(2, hz1, hz2); hz3 = newHazelcastInstance(initOrCreateConfig(new Config()), randomName(), new StaticMemberNodeContext(factory, newUnsecureUUID(), member3.getAddress())); assertClusterSizeEventually(3, hz1, hz2); waitAllForSafeState(hz1, hz2, hz3); OperationServiceImpl operationService = getOperationService(hz1); operationService.invokeOnPartition(null, new NonRetryablePartitionOperation(), member3PartitionId).join(); } @Test public void partitionTable_shouldBeFixed_whenMemberRestarts_usingUuidOfAnotherMissingMember() { ruleStaleJoinPreventionDuration.setOrClearProperty("5"); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz1 = factory.newHazelcastInstance(); HazelcastInstance hz2 = factory.newHazelcastInstance(); HazelcastInstance hz3 = factory.newHazelcastInstance(); HazelcastInstance hz4 = factory.newHazelcastInstance(); assertClusterSizeEventually(4, hz2, hz3); warmUpPartitions(hz1, hz2, hz3, hz4); changeClusterStateEventually(hz4, ClusterState.FROZEN); int member3PartitionId = getPartitionId(hz3); int member4PartitionId = getPartitionId(hz4); MemberImpl member3 = getNode(hz3).getLocalMember(); MemberImpl member4 = getNode(hz4).getLocalMember(); hz3.shutdown(); hz4.shutdown(); assertClusterSizeEventually(2, hz1, hz2); newHazelcastInstance(initOrCreateConfig(new Config()), randomName(), new StaticMemberNodeContext(factory, member4.getUuid(), member3.getAddress())); assertClusterSizeEventually(3, hz1, hz2); OperationServiceImpl operationService = getOperationService(hz1); operationService.invokeOnPartition(null, new NonRetryablePartitionOperation(), member3PartitionId).join(); try { operationService.invokeOnPartition(null, new NonRetryablePartitionOperation(), member4PartitionId).joinInternal(); fail("Invocation to missing member should have failed!"); } catch (TargetNotMemberException ignored) { } } private static PartitionTableView getPartitionTable(HazelcastInstance instance) { return getPartitionService(instance).createPartitionTableView(); } public static class NonRetryablePartitionOperation extends Operation { @Override public void run() throws Exception { } @Override public ExceptionAction onInvocationException(Throwable throwable) { if (throwable instanceof WrongTargetException || throwable instanceof TargetNotMemberException) { return ExceptionAction.THROW_EXCEPTION; } return super.onInvocationException(throwable); } } }
hazelcast/src/test/java/com/hazelcast/internal/partition/impl/FrozenPartitionTableTest.java
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.internal.partition.impl; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.ClusterState; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.impl.MemberImpl; import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.instance.StaticMemberNodeContext; import com.hazelcast.internal.partition.InternalPartition; import com.hazelcast.internal.partition.PartitionReplica; import com.hazelcast.internal.partition.PartitionTableView; import com.hazelcast.spi.exception.TargetNotMemberException; import com.hazelcast.spi.exception.WrongTargetException; import com.hazelcast.spi.impl.operationservice.ExceptionAction; import com.hazelcast.spi.impl.operationservice.Operation; import com.hazelcast.spi.impl.operationservice.impl.OperationServiceImpl; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.OverridePropertyRule; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.hazelcast.instance.impl.HazelcastInstanceFactory.newHazelcastInstance; import static com.hazelcast.instance.impl.TestUtil.terminateInstance; import static com.hazelcast.internal.cluster.impl.AdvancedClusterStateTest.changeClusterStateEventually; import static com.hazelcast.internal.cluster.impl.ClusterJoinManager.STALE_JOIN_PREVENTION_DURATION_PROP; import static com.hazelcast.internal.util.UuidUtil.newUnsecureUUID; import static com.hazelcast.test.Accessors.getClusterService; import static com.hazelcast.test.Accessors.getNode; import static com.hazelcast.test.Accessors.getOperationService; import static com.hazelcast.test.Accessors.getPartitionService; import static com.hazelcast.test.OverridePropertyRule.clear; import static com.hazelcast.test.TestHazelcastInstanceFactory.initOrCreateConfig; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class FrozenPartitionTableTest extends HazelcastTestSupport { @Rule public final OverridePropertyRule ruleStaleJoinPreventionDuration = clear(STALE_JOIN_PREVENTION_DURATION_PROP); @Test public void partitionTable_isFrozen_whenNodesLeave_duringClusterStateIsFrozen() { testPartitionTableIsFrozenDuring(ClusterState.FROZEN); } @Test public void partitionTable_isFrozen_whenNodesLeave_duringClusterStateIsPassive() { testPartitionTableIsFrozenDuring(ClusterState.PASSIVE); } private void testPartitionTableIsFrozenDuring(final ClusterState clusterState) { final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3); HazelcastInstance[] instances = factory.newInstances(); warmUpPartitions(instances); changeClusterStateEventually(instances[0], clusterState); List<HazelcastInstance> instancesList = new ArrayList<HazelcastInstance>(asList(instances)); Collections.shuffle(instancesList); final PartitionTableView partitionTable = getPartitionTable(instances[0]); while (instancesList.size() > 1) { final HazelcastInstance instanceToShutdown = instancesList.remove(0); instanceToShutdown.shutdown(); for (HazelcastInstance instance : instancesList) { assertClusterSizeEventually(instancesList.size(), instance); assertEquals(partitionTable, getPartitionTable(instance)); } } } @Test public void partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIsFrozen() { partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIs(ClusterState.FROZEN); } @Test public void partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIsPassive() { partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIs(ClusterState.PASSIVE); } private void partitionTable_isFrozen_whenMemberReJoins_duringClusterStateIs(ClusterState state) { Config config = new Config(); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(4); HazelcastInstance[] instances = factory.newInstances(config, 3); HazelcastInstance hz1 = instances[0]; HazelcastInstance hz2 = instances[1]; HazelcastInstance hz3 = instances[2]; Address hz3Address = getNode(hz3).getThisAddress(); warmUpPartitions(instances); final PartitionTableView partitionTable = getPartitionTable(hz1); changeClusterStateEventually(hz2, state); final Member member3 = getClusterService(hz3).getLocalMember(); terminateInstance(hz2); terminateInstance(hz3); hz3 = factory.newHazelcastInstance(hz3Address); final Member newMember3 = getClusterService(hz3).getLocalMember(); assertClusterSizeEventually(2, hz1, hz3); final List<HazelcastInstance> instanceList = asList(hz1, hz3); assertTrueAllTheTime(new AssertTask() { @Override public void run() { for (HazelcastInstance instance : instanceList) { PartitionTableView newPartitionTable = getPartitionTable(instance); for (int i = 0; i < newPartitionTable.length(); i++) { for (int j = 0; j < InternalPartition.MAX_REPLICA_COUNT; j++) { PartitionReplica replica = partitionTable.getReplica(i, j); PartitionReplica newReplica = newPartitionTable.getReplica(i, j); if (replica == null) { assertNull(newReplica); } else if (replica.equals(PartitionReplica.from(member3))) { assertEquals(PartitionReplica.from(newMember3), newReplica); } else { assertEquals(replica, newReplica); } } } } } }, 5); } @Test public void partitionTable_shouldBeFixed_whenMemberLeaves_inFrozenState_thenStateChangesToActive() { testPartitionTableIsHealedWhenClusterStateIsActiveAfter(ClusterState.FROZEN); } @Test public void partitionTable_shouldBeFixed_whenMemberLeaves_inPassiveState_thenStateChangesToActive() { testPartitionTableIsHealedWhenClusterStateIsActiveAfter(ClusterState.PASSIVE); } private void testPartitionTableIsHealedWhenClusterStateIsActiveAfter(final ClusterState clusterState) { final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3); HazelcastInstance[] instances = factory.newInstances(); warmUpPartitions(instances); changeClusterStateEventually(instances[0], clusterState); List<HazelcastInstance> instancesList = new ArrayList<HazelcastInstance>(asList(instances)); Collections.shuffle(instancesList); final HazelcastInstance instanceToShutdown = instancesList.remove(0); final Address addressToShutdown = getNode(instanceToShutdown).getThisAddress(); instanceToShutdown.shutdown(); for (HazelcastInstance instance : instancesList) { assertClusterSizeEventually(2, instance); } changeClusterStateEventually(instancesList.get(0), ClusterState.ACTIVE); waitAllForSafeState(instancesList); for (HazelcastInstance instance : instancesList) { PartitionTableView partitionTable = getPartitionTable(instance); for (int i = 0; i < partitionTable.length(); i++) { for (PartitionReplica replica : partitionTable.getReplicas(i)) { if (replica == null) { continue; } assertNotEquals(addressToShutdown, replica.address()); } } } } @Test public void partitionTable_shouldBeFixed_whenMemberRestarts_usingNewUuid() { ruleStaleJoinPreventionDuration.setOrClearProperty("5"); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz1 = factory.newHazelcastInstance(); HazelcastInstance hz2 = factory.newHazelcastInstance(); HazelcastInstance hz3 = factory.newHazelcastInstance(); assertClusterSizeEventually(3, hz2, hz3); warmUpPartitions(hz1, hz2, hz3); changeClusterStateEventually(hz3, ClusterState.FROZEN); int member3PartitionId = getPartitionId(hz3); MemberImpl member3 = getNode(hz3).getLocalMember(); hz3.shutdown(); assertClusterSizeEventually(2, hz1, hz2); newHazelcastInstance(initOrCreateConfig(new Config()), randomName(), new StaticMemberNodeContext(factory, newUnsecureUUID(), member3.getAddress())); assertClusterSizeEventually(3, hz1, hz2); OperationServiceImpl operationService = getOperationService(hz1); operationService.invokeOnPartition(null, new NonRetryablePartitionOperation(), member3PartitionId).join(); } @Test public void partitionTable_shouldBeFixed_whenMemberRestarts_usingUuidOfAnotherMissingMember() { ruleStaleJoinPreventionDuration.setOrClearProperty("5"); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz1 = factory.newHazelcastInstance(); HazelcastInstance hz2 = factory.newHazelcastInstance(); HazelcastInstance hz3 = factory.newHazelcastInstance(); HazelcastInstance hz4 = factory.newHazelcastInstance(); assertClusterSizeEventually(4, hz2, hz3); warmUpPartitions(hz1, hz2, hz3, hz4); changeClusterStateEventually(hz4, ClusterState.FROZEN); int member3PartitionId = getPartitionId(hz3); int member4PartitionId = getPartitionId(hz4); MemberImpl member3 = getNode(hz3).getLocalMember(); MemberImpl member4 = getNode(hz4).getLocalMember(); hz3.shutdown(); hz4.shutdown(); assertClusterSizeEventually(2, hz1, hz2); newHazelcastInstance(initOrCreateConfig(new Config()), randomName(), new StaticMemberNodeContext(factory, member4.getUuid(), member3.getAddress())); assertClusterSizeEventually(3, hz1, hz2); OperationServiceImpl operationService = getOperationService(hz1); operationService.invokeOnPartition(null, new NonRetryablePartitionOperation(), member3PartitionId).join(); try { operationService.invokeOnPartition(null, new NonRetryablePartitionOperation(), member4PartitionId).joinInternal(); fail("Invocation to missing member should have failed!"); } catch (TargetNotMemberException ignored) { } } private static PartitionTableView getPartitionTable(HazelcastInstance instance) { return getPartitionService(instance).createPartitionTableView(); } public static class NonRetryablePartitionOperation extends Operation { @Override public void run() throws Exception { } @Override public ExceptionAction onInvocationException(Throwable throwable) { if (throwable instanceof WrongTargetException || throwable instanceof TargetNotMemberException) { return ExceptionAction.THROW_EXCEPTION; } return super.onInvocationException(throwable); } } }
Ensures FrozenPartitionTableTest waits for partitions update Before sending partition operation, ensure partition table is updated on all members
hazelcast/src/test/java/com/hazelcast/internal/partition/impl/FrozenPartitionTableTest.java
Ensures FrozenPartitionTableTest waits for partitions update
<ide><path>azelcast/src/test/java/com/hazelcast/internal/partition/impl/FrozenPartitionTableTest.java <ide> hz3.shutdown(); <ide> assertClusterSizeEventually(2, hz1, hz2); <ide> <del> newHazelcastInstance(initOrCreateConfig(new Config()), <add> hz3 = newHazelcastInstance(initOrCreateConfig(new Config()), <ide> randomName(), new StaticMemberNodeContext(factory, newUnsecureUUID(), member3.getAddress())); <ide> assertClusterSizeEventually(3, hz1, hz2); <add> waitAllForSafeState(hz1, hz2, hz3); <ide> <ide> OperationServiceImpl operationService = getOperationService(hz1); <ide> operationService.invokeOnPartition(null, new NonRetryablePartitionOperation(), member3PartitionId).join();
Java
apache-2.0
d376c2a5d8dad8b8faea5206d2b739dc6c6a551d
0
PKRoma/stephenerialization,PKRoma/stephenerialization
package com.enragedginger.stephenerialization.preprocessing; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.*; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import java.io.IOException; import java.io.Writer; import java.util.Set; import com.enragedginger.stephenerialization.annotations.*; import jdk.nashorn.internal.codegen.CompilationException; /** * Processes {@link Stephenerializable} annotations and builds stephenerialization logic * at compile time instead of run time. * * @author Stephen Hopper */ @SupportedAnnotationTypes(value = {"com.enragedginger.stephenerialization.annotations.Stephenerializable"}) public class StephenerializableAnnotationProcessor extends AbstractProcessor { @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Messager messager = processingEnv.getMessager(); for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { try { processAnnotation(element, messager); } catch (Exception e) { throw new RuntimeException("An error occurred while preprocessing Stephenerialization annotations.", e); } } } return true; } private void processAnnotation(Element element, Messager messager) throws IOException, ClassNotFoundException { Stephenerializable stephenerializable = element.getAnnotation(Stephenerializable.class); String className = element.toString(); String simpleName = element.getSimpleName().toString(); String generatedClassName = className + "Stephenerializer"; String simpleGeneratedClassName = simpleName + "Stephenerializer"; Filer filer = processingEnv.getFiler(); JavaFileObject sourceFile = filer.createSourceFile(generatedClassName, element); StephenerializationPreprocessorFieldGenerator generator = new StephenerializationPreprocessorFieldGenerator(); Set<StephenerializationPreprocessorField> fields = generator.generateFields(element); Writer w = sourceFile.openWriter(); writePackageImportsAndClass(w, element, simpleGeneratedClassName); writeWriteMethod(w, className, fields, stephenerializable); writeReadMethod(w, className, fields); //close class w.write("}\n"); w.close(); messager.printMessage(Diagnostic.Kind.NOTE, generatedClassName); } /** * Writes the opening of the stephenerializer class. * @param w The class's writer. * @param element The element which references the class which is being processed. * @param simpleGeneratedClassName The simple name of the generated class. * @throws IOException If an error occurs. */ private void writePackageImportsAndClass(Writer w, Element element, String simpleGeneratedClassName) throws IOException { //write package and class declaration name PackageElement p = processingEnv.getElementUtils().getPackageOf(element); w.write("package " + p.getQualifiedName().toString() + ";\n\n"); w.write("import com.enragedginger.stephenerialization.StephenerializationException;\n" + "import java.io.ObjectInputStream;\n" + "import java.io.ObjectOutputStream;\n\n"); w.write("class " + simpleGeneratedClassName + " {\n"); } /** * Creates the read method on the class. * * @param w The class's writer. * @param className The fullname of the class for which this stephenerializer is being created. * @param fields The fields on the object. * @param stephenerializable The Stephenerializable annotation on the class. * @throws IOException If an error occurs. */ private void writeWriteMethod(Writer w, String className, Set<StephenerializationPreprocessorField> fields, Stephenerializable stephenerializable) throws IOException { //write stephenerialize method w.write("public static void stephenerialize(" + className + " object, ObjectOutputStream stream) {\n"); if (fields != null && !fields.isEmpty()) { w.write("try {\n"); w.write("stream.writeInt(" + stephenerializable.version() + ");\n"); for (StephenerializationPreprocessorField field : fields) { w.write("stream.writeObject(object." + field.getGetterName() + "());\n"); } w.write("} catch (Exception e) {\n"); w.write("throw new StephenerializationException(\"An error occurred during Stephenerialization.\", e);\n"); w.write("}\n"); } w.write("}\n\n"); } /** * Creates the write method on the class. * * @param w The class's writer. * @param className The fullname of the class for which this stephenerializer is being created. * @param fields The fields on the object. * @throws IOException If an error occurs. */ private void writeReadMethod(Writer w, String className, Set<StephenerializationPreprocessorField> fields) throws IOException { //write read method w.write("public static void destephenerialize(" + className + " object, ObjectInputStream stream) {\n"); if (fields != null && !fields.isEmpty()) { w.write("try {\n"); w.write("final int version = stream.readInt();\n"); Integer previousVersion = null; for (StephenerializationPreprocessorField field : fields) { if (previousVersion == null) { previousVersion = field.getVersion(); w.write("if (version >= " + field.getVersion() + ") {\n"); } if (previousVersion != field.getVersion()) { w.write("}\n"); w.write("if (version >= " + field.getVersion() + ") {\n"); } w.write("object." + field.getSetterName() + "("); if (!field.isPrimitive()) { w.write("(" + field.getFieldTypeName() + ") "); } else { w.write("(" + field.getCastType() + ") "); } //w.write("stream." + field.getObjectInputStreamMethod() + "());\n"); w.write("stream.readObject());\n"); previousVersion = field.getVersion(); } w.write("}\n"); //close last if block w.write("} catch (Exception e) {\n"); w.write("e.printStackTrace();\n"); w.write("throw new StephenerializationException(\"An error occurred during Destephenerialization.\", e);\n"); w.write("}\n"); } w.write("}\n"); } }
src/main/java/com/enragedginger/stephenerialization/preprocessing/StephenerializableAnnotationProcessor.java
package com.enragedginger.stephenerialization.preprocessing; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.*; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import java.io.IOException; import java.io.Writer; import java.util.Set; import com.enragedginger.stephenerialization.annotations.*; /** * Processes {@link Stephenerializable} annotations and builds stephenerialization logic * at compile time instead of run time. * * @author Stephen Hopper */ @SupportedAnnotationTypes(value = {"com.enragedginger.stephenerialization.annotations.Stephenerializable"}) public class StephenerializableAnnotationProcessor extends AbstractProcessor { @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Messager messager = processingEnv.getMessager(); for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { try { processAnnotation(element, messager); } catch (Exception e) { e.printStackTrace(); } } } return true; } private void processAnnotation(Element element, Messager messager) throws IOException, ClassNotFoundException { Stephenerializable stephenerializable = element.getAnnotation(Stephenerializable.class); String className = element.toString(); String simpleName = element.getSimpleName().toString(); String generatedClassName = className + "Stephenerializer"; String simpleGeneratedClassName = simpleName + "Stephenerializer"; Filer filer = processingEnv.getFiler(); JavaFileObject sourceFile = filer.createSourceFile(generatedClassName, element); StephenerializationPreprocessorFieldGenerator generator = new StephenerializationPreprocessorFieldGenerator(); Set<StephenerializationPreprocessorField> fields = generator.generateFields(element); Writer w = sourceFile.openWriter(); //write package and class declaration name PackageElement p = processingEnv.getElementUtils().getPackageOf(element); w.write("package " + p.getQualifiedName().toString() + ";\n\n"); w.write("import com.enragedginger.stephenerialization.StephenerializationException;\n" + "import java.io.ObjectInputStream;\n" + "import java.io.ObjectOutputStream;\n\n"); w.write("class " + simpleGeneratedClassName + " {\n"); //write stephenerialize method w.write("public static void stephenerialize(" + className + " object, ObjectOutputStream stream) {\n"); if (fields != null && !fields.isEmpty()) { w.write("try {\n"); w.write("stream.writeInt(" + stephenerializable.version() + ");\n"); for (StephenerializationPreprocessorField field : fields) { w.write("stream.writeObject(object." + field.getGetterName() + "());\n"); } w.write("} catch (Exception e) {\n"); w.write("throw new StephenerializationException(\"An error occurred during Stephenerialization.\", e);\n"); w.write("}\n"); } w.write("}\n\n"); //write read method w.write("public static void destephenerialize(" + className + " object, ObjectInputStream stream) {\n"); if (fields != null && !fields.isEmpty()) { w.write("try {\n"); w.write("final int version = stream.readInt();\n"); Integer previousVersion = null; for (StephenerializationPreprocessorField field : fields) { if (previousVersion == null) { previousVersion = field.getVersion(); w.write("if (version >= " + field.getVersion() + ") {\n"); } if (previousVersion != field.getVersion()) { w.write("}\n"); w.write("if (version >= " + field.getVersion() + ") {\n"); } w.write("object." + field.getSetterName() + "("); if (!field.isPrimitive()) { w.write("(" + field.getFieldTypeName() + ") "); } else { w.write("(" + field.getCastType() + ") "); } //w.write("stream." + field.getObjectInputStreamMethod() + "());\n"); w.write("stream.readObject());\n"); previousVersion = field.getVersion(); } w.write("}\n"); //close last if block w.write("} catch (Exception e) {\n"); w.write("e.printStackTrace();\n"); w.write("throw new StephenerializationException(\"An error occurred during Destephenerialization.\", e);\n"); w.write("}\n"); } w.write("}\n"); //close class w.write("}\n"); w.close(); messager.printMessage(Diagnostic.Kind.NOTE, generatedClassName); } }
Tidied up preprocessor looks and logic.
src/main/java/com/enragedginger/stephenerialization/preprocessing/StephenerializableAnnotationProcessor.java
Tidied up preprocessor looks and logic.
<ide><path>rc/main/java/com/enragedginger/stephenerialization/preprocessing/StephenerializableAnnotationProcessor.java <ide> import java.util.Set; <ide> <ide> import com.enragedginger.stephenerialization.annotations.*; <add>import jdk.nashorn.internal.codegen.CompilationException; <ide> <ide> /** <ide> * Processes {@link Stephenerializable} annotations and builds stephenerialization logic <ide> try { <ide> processAnnotation(element, messager); <ide> } catch (Exception e) { <del> e.printStackTrace(); <add> throw new RuntimeException("An error occurred while preprocessing Stephenerialization annotations.", e); <ide> } <ide> } <ide> } <ide> <ide> Writer w = sourceFile.openWriter(); <ide> <add> writePackageImportsAndClass(w, element, simpleGeneratedClassName); <add> writeWriteMethod(w, className, fields, stephenerializable); <add> writeReadMethod(w, className, fields); <add> <add> //close class <add> w.write("}\n"); <add> w.close(); <add> messager.printMessage(Diagnostic.Kind.NOTE, generatedClassName); <add> } <add> <add> /** <add> * Writes the opening of the stephenerializer class. <add> * @param w The class's writer. <add> * @param element The element which references the class which is being processed. <add> * @param simpleGeneratedClassName The simple name of the generated class. <add> * @throws IOException If an error occurs. <add> */ <add> private void writePackageImportsAndClass(Writer w, Element element, String simpleGeneratedClassName) throws IOException { <ide> //write package and class declaration name <ide> PackageElement p = processingEnv.getElementUtils().getPackageOf(element); <ide> w.write("package " + p.getQualifiedName().toString() + ";\n\n"); <ide> "import java.io.ObjectInputStream;\n" + <ide> "import java.io.ObjectOutputStream;\n\n"); <ide> w.write("class " + simpleGeneratedClassName + " {\n"); <add> } <ide> <add> /** <add> * Creates the read method on the class. <add> * <add> * @param w The class's writer. <add> * @param className The fullname of the class for which this stephenerializer is being created. <add> * @param fields The fields on the object. <add> * @param stephenerializable The Stephenerializable annotation on the class. <add> * @throws IOException If an error occurs. <add> */ <add> private void writeWriteMethod(Writer w, String className, Set<StephenerializationPreprocessorField> fields, <add> Stephenerializable stephenerializable) throws IOException { <ide> //write stephenerialize method <ide> w.write("public static void stephenerialize(" + className + " object, ObjectOutputStream stream) {\n"); <ide> <ide> w.write("}\n"); <ide> } <ide> w.write("}\n\n"); <add> } <ide> <add> /** <add> * Creates the write method on the class. <add> * <add> * @param w The class's writer. <add> * @param className The fullname of the class for which this stephenerializer is being created. <add> * @param fields The fields on the object. <add> * @throws IOException If an error occurs. <add> */ <add> private void writeReadMethod(Writer w, String className, Set<StephenerializationPreprocessorField> fields) throws IOException { <ide> //write read method <ide> w.write("public static void destephenerialize(" + className + " object, ObjectInputStream stream) {\n"); <ide> if (fields != null && !fields.isEmpty()) { <ide> w.write("}\n"); <ide> } <ide> w.write("}\n"); <del> <del> <del> //close class <del> w.write("}\n"); <del> w.close(); <del> messager.printMessage(Diagnostic.Kind.NOTE, generatedClassName); <ide> } <ide> }
Java
apache-2.0
8be7c8c4680fd9bf3f40a54d96cfc92253b019a2
0
asedunov/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,samthor/intellij-community,asedunov/intellij-community,allotria/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,holmes/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,blademainer/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,slisson/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,slisson/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,asedunov/intellij-community,da1z/intellij-community,ryano144/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,semonte/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,supersven/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,vladmm/intellij-community,jagguli/intellij-community,amith01994/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,FHannes/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,allotria/intellij-community,tmpgit/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,kool79/intellij-community,slisson/intellij-community,fitermay/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,caot/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,xfournet/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,izonder/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,izonder/intellij-community,clumsy/intellij-community,kdwink/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,da1z/intellij-community,da1z/intellij-community,amith01994/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,caot/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,slisson/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,ibinti/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,kool79/intellij-community,blademainer/intellij-community,izonder/intellij-community,clumsy/intellij-community,dslomov/intellij-community,kool79/intellij-community,adedayo/intellij-community,samthor/intellij-community,caot/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,caot/intellij-community,blademainer/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ahb0327/intellij-community,supersven/intellij-community,vvv1559/intellij-community,supersven/intellij-community,petteyg/intellij-community,allotria/intellij-community,hurricup/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,izonder/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,hurricup/intellij-community,diorcety/intellij-community,petteyg/intellij-community,caot/intellij-community,FHannes/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,kool79/intellij-community,caot/intellij-community,samthor/intellij-community,Distrotech/intellij-community,izonder/intellij-community,petteyg/intellij-community,dslomov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,xfournet/intellij-community,signed/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,da1z/intellij-community,robovm/robovm-studio,ibinti/intellij-community,blademainer/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ryano144/intellij-community,supersven/intellij-community,asedunov/intellij-community,blademainer/intellij-community,kool79/intellij-community,izonder/intellij-community,apixandru/intellij-community,vladmm/intellij-community,allotria/intellij-community,supersven/intellij-community,caot/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,jagguli/intellij-community,amith01994/intellij-community,robovm/robovm-studio,izonder/intellij-community,ryano144/intellij-community,asedunov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,apixandru/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,Distrotech/intellij-community,supersven/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,retomerz/intellij-community,izonder/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,kdwink/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,blademainer/intellij-community,retomerz/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,signed/intellij-community,vladmm/intellij-community,robovm/robovm-studio,ibinti/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,holmes/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,dslomov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,fitermay/intellij-community,apixandru/intellij-community,robovm/robovm-studio,hurricup/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,petteyg/intellij-community,clumsy/intellij-community,allotria/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,signed/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,fitermay/intellij-community,izonder/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,signed/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,dslomov/intellij-community,xfournet/intellij-community,holmes/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,semonte/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,adedayo/intellij-community,apixandru/intellij-community,caot/intellij-community,samthor/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,slisson/intellij-community,asedunov/intellij-community,retomerz/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,kdwink/intellij-community,signed/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,allotria/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,amith01994/intellij-community,apixandru/intellij-community,jagguli/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,supersven/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,holmes/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,kool79/intellij-community,da1z/intellij-community,xfournet/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,diorcety/intellij-community,kool79/intellij-community,FHannes/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,blademainer/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,holmes/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,caot/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,samthor/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,ryano144/intellij-community,holmes/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,slisson/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,clumsy/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,allotria/intellij-community,hurricup/intellij-community,fnouama/intellij-community,da1z/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,jagguli/intellij-community,petteyg/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ryano144/intellij-community,supersven/intellij-community,tmpgit/intellij-community,allotria/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,amith01994/intellij-community
package com.jetbrains.python; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.jetbrains.python.psi.LanguageLevel; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; import java.util.regex.Pattern; /** * @author dcheryasov */ @NonNls public class PyNames { public static final String SITE_PACKAGES = "site-packages"; private PyNames() { } public static final String INIT = "__init__"; public static final String DICT = "__dict__"; public static final String DOT_PY = ".py"; public static final String INIT_DOT_PY = INIT + DOT_PY; public static final String NEW = "__new__"; public static final String GETATTR = "__getattr__"; public static final String GETATTRIBUTE = "__getattribute__"; public static final String CLASS = "__class__"; public static final String DUNDER_METACLASS = "__metaclass__"; public static final String METACLASS = "metaclass"; public static final String TYPE = "type"; public static final String SUPER = "super"; public static final String OBJECT = "object"; public static final String NONE = "None"; public static final String TRUE = "True"; public static final String FALSE = "False"; public static final String FAKE_OLD_BASE = "___Classobj"; public static final String FAKE_GENERATOR = "__generator"; public static final String FAKE_NAMEDTUPLE = "__namedtuple"; public static final String FUTURE_MODULE = "__future__"; public static final String UNICODE_LITERALS = "unicode_literals"; public static final String CLASSMETHOD = "classmethod"; public static final String STATICMETHOD = "staticmethod"; public static final String PROPERTY = "property"; public static final String SETTER = "setter"; public static final String DELETER = "deleter"; public static final String GETTER = "getter"; public static final String ALL = "__all__"; public static final String SLOTS = "__slots__"; public static final String DEBUG = "__debug__"; public static final String ISINSTANCE = "isinstance"; public static final String ASSERT_IS_INSTANCE = "assertIsInstance"; public static final String HAS_ATTR = "hasattr"; public static final String DOCFORMAT = "__docformat__"; public static final String DIRNAME = "dirname"; public static final String ABSPATH = "abspath"; public static final String JOIN = "join"; public static final String REPLACE = "replace"; public static final String FILE = "__file__"; public static final String PARDIR = "pardir"; public static final String CURDIR = "curdir"; public static final String WARN = "warn"; public static final String DEPRECATION_WARNING = "DeprecationWarning"; public static final String PENDING_DEPRECATION_WARNING = "PendingDeprecationWarning"; public static final String CONTAINER = "Container"; public static final String HASHABLE = "Hashable"; public static final String ITERABLE = "Iterable"; public static final String ITERATOR = "Iterator"; public static final String SIZED = "Sized"; public static final String CALLABLE = "Callable"; public static final String SEQUENCE = "Sequence"; public static final String MAPPING = "Mapping"; public static final String COMPLEX = "Complex"; public static final String REAL = "Real"; public static final String RATIONAL = "Rational"; public static final String INTEGRAL = "Integral"; public static final String CONTAINS = "__contains__"; public static final String HASH = "__hash__"; public static final String ITER = "__iter__"; public static final String NEXT = "next"; public static final String DUNDER_NEXT = "__next__"; public static final String LEN = "__len__"; public static final String CALL = "__call__"; public static final String GETITEM = "__getitem__"; public static final String SETITEM = "__setitem__"; public static final String DELITEM = "__delitem__"; public static final String POS = "__pos__"; public static final String NEG = "__neg__"; public static final String DIV = "__div__"; public static final String TRUEDIV = "__truediv__"; public static final String NAME = "__name__"; public static final String ENTER = "__enter__"; public static final String CALLABLE_BUILTIN = "callable"; public static final String NAMEDTUPLE = "namedtuple"; public static final String COLLECTIONS = "collections"; public static final String COLLECTIONS_NAMEDTUPLE = COLLECTIONS + "." + NAMEDTUPLE; public static final String ABSTRACTMETHOD = "abstractmethod"; public static final String TUPLE = "tuple"; public static final String SET = "set"; public static final String KEYS = "keys"; public static final String PASS = "pass"; public static final String NOSE_TEST = "nose"; public static final String PY_TEST = "pytest"; public static final String AT_TEST = "Attest"; public static final String AT_TEST_IMPORT = "attest"; public static final String TEST_CASE = "TestCase"; public static final String PYCACHE = "__pycache__"; public static final String NOT_IMPLEMENTED_ERROR = "NotImplementedError"; /** * Contains all known predefined names of "__foo__" form. */ public static ImmutableSet<String> UnderscoredAttributes = ImmutableSet.of( "__all__", "__author__", "__bases__", "__dict__", "__doc__", "__docformat__", "__file__", "__members__", "__metaclass__", "__mod__", "__mro__", "__name__", "__path__", "__qualname__", "__self__", "__slots__", "__version__" ); public static ImmutableSet<String> COMPARISON_OPERATORS = ImmutableSet.of( "__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__", "__cmp__", "__contains__" ); public static ImmutableSet<String> SUBSCRIPTION_OPERATORS = ImmutableSet.of( GETITEM, SETITEM, DELITEM ); public static class BuiltinDescription { private final String mySignature; public BuiltinDescription(String signature) { mySignature = signature; } public String getSignature() { return mySignature; } // TODO: doc string, too } private static final BuiltinDescription _only_self_descr = new BuiltinDescription("(self)"); private static final BuiltinDescription _self_other_descr = new BuiltinDescription("(self, other)"); private static final BuiltinDescription _self_item_descr = new BuiltinDescription("(self, item)"); private static final BuiltinDescription _self_key_descr = new BuiltinDescription("(self, key)"); private static final ImmutableMap<String, BuiltinDescription> BuiltinMethods = ImmutableMap.<String, BuiltinDescription>builder() .put("__abs__", _only_self_descr) .put("__add__", _self_other_descr) .put("__and__", _self_other_descr) //_BuiltinMethods.put("__all__", _only_self_descr); //_BuiltinMethods.put("__author__", _only_self_descr); //_BuiltinMethods.put("__bases__", _only_self_descr); .put("__call__", new BuiltinDescription("(self, *args, **kwargs)")) //_BuiltinMethods.put("__class__", _only_self_descr); .put("__cmp__", _self_other_descr) .put("__coerce__", _self_other_descr) .put("__complex__", _only_self_descr) .put("__contains__", _self_item_descr) //_BuiltinMethods.put("__debug__", _only_self_descr); .put("__del__", _only_self_descr) .put("__delete__", new BuiltinDescription("(self, instance)")) .put("__delattr__", _self_item_descr) .put("__delitem__", _self_key_descr) .put("__delslice__", new BuiltinDescription("(self, i, j)")) //_BuiltinMethods.put("__dict__", _only_self_descr); .put("__divmod__", _self_other_descr) //_BuiltinMethods.put("__doc__", _only_self_descr); //_BuiltinMethods.put("__docformat__", _only_self_descr); .put("__enter__", _only_self_descr) .put("__exit__", new BuiltinDescription("(self, exc_type, exc_val, exc_tb)")) .put("__eq__", _self_other_descr) //_BuiltinMethods.put("__file__", _only_self_descr); .put("__float__", _only_self_descr) .put("__floordiv__", _self_other_descr) //_BuiltinMethods.put("__future__", _only_self_descr); .put("__ge__", _self_other_descr) .put("__get__", new BuiltinDescription("(self, instance, owner)")) .put("__getattr__", _self_item_descr) .put("__getattribute__", _self_item_descr) .put("__getitem__", _self_item_descr) //_BuiltinMethods.put("__getslice__", new BuiltinDescription("(self, i, j)")); .put("__gt__", _self_other_descr) .put("__hash__", _only_self_descr) .put("__hex__", _only_self_descr) .put("__iadd__", _self_other_descr) .put("__iand__", _self_other_descr) .put("__idiv__", _self_other_descr) .put("__ifloordiv__", _self_other_descr) //_BuiltinMethods.put("__import__", _only_self_descr); .put("__ilshift__", _self_other_descr) .put("__imod__", _self_other_descr) .put("__imul__", _self_other_descr) .put("__index__", _only_self_descr) .put(INIT, _only_self_descr) .put("__int__", _only_self_descr) .put("__invert__", _only_self_descr) .put("__ior__", _self_other_descr) .put("__ipow__", _self_other_descr) .put("__irshift__", _self_other_descr) .put("__isub__", _self_other_descr) .put("__iter__", _only_self_descr) .put("__itruediv__", _self_other_descr) .put("__ixor__", _self_other_descr) .put("__le__", _self_other_descr) .put("__len__", _only_self_descr) .put("__long__", _only_self_descr) .put("__lshift__", _self_other_descr) .put("__lt__", _self_other_descr) //_BuiltinMethods.put("__members__", _only_self_descr); //_BuiltinMethods.put("__metaclass__", _only_self_descr); .put("__mod__", _self_other_descr) //_BuiltinMethods.put("__mro__", _only_self_descr); .put("__mul__", _self_other_descr) //_BuiltinMethods.put("__name__", _only_self_descr); .put("__ne__", _self_other_descr) .put("__neg__", _only_self_descr) .put(NEW, new BuiltinDescription("(cls, *args, **kwargs)")) .put("__oct__", _only_self_descr) .put("__or__", _self_other_descr) //_BuiltinMethods.put("__path__", _only_self_descr); .put("__pos__", _only_self_descr) .put("__pow__", new BuiltinDescription("(self, power, modulo=None)")) .put("__radd__", _self_other_descr) .put("__rand__", _self_other_descr) .put("__rdiv__", _self_other_descr) .put("__rdivmod__", _self_other_descr) .put("__reduce__", _only_self_descr) .put("__repr__", _only_self_descr) .put("__rfloordiv__", _self_other_descr) .put("__rlshift__", _self_other_descr) .put("__rmod__", _self_other_descr) .put("__rmul__", _self_other_descr) .put("__ror__", _self_other_descr) .put("__rpow__", new BuiltinDescription("(self, power, modulo=None)")) .put("__rrshift__", _self_other_descr) .put("__rshift__", _self_other_descr) .put("__rsub__", _self_other_descr) .put("__rtruediv__", _self_other_descr) .put("__rxor__", _self_other_descr) .put("__set__", new BuiltinDescription("(self, instance, value)")) .put("__setattr__", new BuiltinDescription("(self, key, value)")) .put("__setitem__", new BuiltinDescription("(self, key, value)")) .put("__setslice__", new BuiltinDescription("(self, i, j, sequence)")) //_BuiltinMethods.put("__self__", _only_self_descr); //_BuiltinMethods.put("__slots__", _only_self_descr); .put("__str__", _only_self_descr) .put("__sub__", _self_other_descr) .put("__truediv__", _self_other_descr) .put("__unicode__", _only_self_descr) //_BuiltinMethods.put("__version__", _only_self_descr); .put("__xor__", _self_other_descr) .build(); public static ImmutableMap<String, BuiltinDescription> PY2_BUILTIN_METHODS = ImmutableMap.<String, BuiltinDescription>builder() .putAll(BuiltinMethods) .put("__nonzero__", _only_self_descr) .put("__div__", _self_other_descr) .build(); public static ImmutableMap<String, BuiltinDescription> PY3_BUILTIN_METHODS = ImmutableMap.<String, BuiltinDescription>builder() .putAll(BuiltinMethods) .put("__bool__", _only_self_descr) .build(); public static ImmutableMap<String, BuiltinDescription> getBuiltinMethods(LanguageLevel level) { return level.isPy3K() ? PY3_BUILTIN_METHODS : PY2_BUILTIN_METHODS; } // canonical names, not forced by interpreter public static final String CANONICAL_SELF = "self"; public static final String BASESTRING = "basestring"; /** * Contains keywords as of CPython 2.5. */ public static ImmutableSet<String> Keywords = ImmutableSet.of( "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try" ); public static Set<String> BuiltinInterfaces = ImmutableSet.of( CALLABLE, HASHABLE, ITERABLE, ITERATOR, SIZED, CONTAINER, SEQUENCE, MAPPING, COMPLEX, REAL, RATIONAL, INTEGRAL ); /** * TODO: dependency on language level. * @param name what to check * @return true iff the name is either a keyword or a reserved name, like None. * */ public static boolean isReserved(@NonNls String name) { return Keywords.contains(name) || NONE.equals(name) || "as".equals(name) || "with".equals(name); } // NOTE: includes unicode only good for py3k private final static Pattern IDENTIFIER_PATTERN = Pattern.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*"); /** * TODO: dependency on language level. * @param name what to check * @return true iff name is not reserved and is a well-formed identifier. */ public static boolean isIdentifier(@NotNull @NonNls String name) { return !isReserved(name) && isIdentifierString(name); } public static boolean isIdentifierString(String name) { return IDENTIFIER_PATTERN.matcher(name).matches(); } public static boolean isRightOperatorName(@Nullable String name) { return name != null && name.matches("__r[a-z]+__"); } }
python/psi-api/src/com/jetbrains/python/PyNames.java
package com.jetbrains.python; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.jetbrains.python.psi.LanguageLevel; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; import java.util.regex.Pattern; /** * @author dcheryasov */ @NonNls public class PyNames { public static final String SITE_PACKAGES = "site-packages"; private PyNames() { } public static final String INIT = "__init__"; public static final String DICT = "__dict__"; public static final String DOT_PY = ".py"; public static final String INIT_DOT_PY = INIT + DOT_PY; public static final String NEW = "__new__"; public static final String GETATTR = "__getattr__"; public static final String GETATTRIBUTE = "__getattribute__"; public static final String CLASS = "__class__"; public static final String DUNDER_METACLASS = "__metaclass__"; public static final String METACLASS = "metaclass"; public static final String TYPE = "type"; public static final String SUPER = "super"; public static final String OBJECT = "object"; public static final String NONE = "None"; public static final String TRUE = "True"; public static final String FALSE = "False"; public static final String FAKE_OLD_BASE = "___Classobj"; public static final String FAKE_GENERATOR = "__generator"; public static final String FAKE_NAMEDTUPLE = "__namedtuple"; public static final String FUTURE_MODULE = "__future__"; public static final String UNICODE_LITERALS = "unicode_literals"; public static final String CLASSMETHOD = "classmethod"; public static final String STATICMETHOD = "staticmethod"; public static final String PROPERTY = "property"; public static final String SETTER = "setter"; public static final String DELETER = "deleter"; public static final String GETTER = "getter"; public static final String ALL = "__all__"; public static final String SLOTS = "__slots__"; public static final String DEBUG = "__debug__"; public static final String ISINSTANCE = "isinstance"; public static final String ASSERT_IS_INSTANCE = "assertIsInstance"; public static final String HAS_ATTR = "hasattr"; public static final String DOCFORMAT = "__docformat__"; public static final String DIRNAME = "dirname"; public static final String ABSPATH = "abspath"; public static final String JOIN = "join"; public static final String REPLACE = "replace"; public static final String FILE = "__file__"; public static final String PARDIR = "pardir"; public static final String CURDIR = "curdir"; public static final String WARN = "warn"; public static final String DEPRECATION_WARNING = "DeprecationWarning"; public static final String PENDING_DEPRECATION_WARNING = "PendingDeprecationWarning"; public static final String CONTAINER = "Container"; public static final String HASHABLE = "Hashable"; public static final String ITERABLE = "Iterable"; public static final String ITERATOR = "Iterator"; public static final String SIZED = "Sized"; public static final String CALLABLE = "Callable"; public static final String SEQUENCE = "Sequence"; public static final String MAPPING = "Mapping"; public static final String COMPLEX = "Complex"; public static final String REAL = "Real"; public static final String RATIONAL = "Rational"; public static final String INTEGRAL = "Integral"; public static final String CONTAINS = "__contains__"; public static final String HASH = "__hash__"; public static final String ITER = "__iter__"; public static final String NEXT = "next"; public static final String DUNDER_NEXT = "__next__"; public static final String LEN = "__len__"; public static final String CALL = "__call__"; public static final String GETITEM = "__getitem__"; public static final String SETITEM = "__setitem__"; public static final String DELITEM = "__delitem__"; public static final String POS = "__pos__"; public static final String NEG = "__neg__"; public static final String DIV = "__div__"; public static final String TRUEDIV = "__truediv__"; public static final String NAME = "__name__"; public static final String ENTER = "__enter__"; public static final String CALLABLE_BUILTIN = "callable"; public static final String NAMEDTUPLE = "namedtuple"; public static final String COLLECTIONS = "collections"; public static final String COLLECTIONS_NAMEDTUPLE = COLLECTIONS + "." + NAMEDTUPLE; public static final String ABSTRACTMETHOD = "abstractmethod"; public static final String TUPLE = "tuple"; public static final String SET = "set"; public static final String KEYS = "keys"; public static final String PASS = "pass"; public static final String NOSE_TEST = "nose"; public static final String PY_TEST = "pytest"; public static final String AT_TEST = "Attest"; public static final String AT_TEST_IMPORT = "attest"; public static final String TEST_CASE = "TestCase"; public static final String PYCACHE = "__pycache__"; public static final String NOT_IMPLEMENTED_ERROR = "NotImplementedError"; /** * Contains all known predefined names of "__foo__" form. */ public static ImmutableSet<String> UnderscoredAttributes = ImmutableSet.of( "__all__", "__author__", "__bases__", "__dict__", "__doc__", "__docformat__", "__file__", "__members__", "__metaclass__", "__mod__", "__mro__", "__name__", "__path__", "__qualname__", "__self__", "__slots__", "__version__" ); public static ImmutableSet<String> COMPARISON_OPERATORS = ImmutableSet.of( "__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__", "__cmp__", "__contains__" ); public static ImmutableSet<String> SUBSCRIPTION_OPERATORS = ImmutableSet.of( GETITEM, SETITEM, DELITEM ); public static class BuiltinDescription { private final String mySignature; public BuiltinDescription(String signature) { mySignature = signature; } public String getSignature() { return mySignature; } // TODO: doc string, too } private static final BuiltinDescription _only_self_descr = new BuiltinDescription("(self)"); private static final BuiltinDescription _self_other_descr = new BuiltinDescription("(self, other)"); private static final BuiltinDescription _self_item_descr = new BuiltinDescription("(self, item)"); private static final BuiltinDescription _self_key_descr = new BuiltinDescription("(self, key)"); private static final ImmutableMap<String, BuiltinDescription> BuiltinMethods = ImmutableMap.<String, BuiltinDescription>builder() .put("__abs__", _only_self_descr) .put("__add__", _self_other_descr) .put("__and__", _self_other_descr) //_BuiltinMethods.put("__all__", _only_self_descr); //_BuiltinMethods.put("__author__", _only_self_descr); //_BuiltinMethods.put("__bases__", _only_self_descr); .put("__call__", new BuiltinDescription("(self, *args, **kwargs)")) //_BuiltinMethods.put("__class__", _only_self_descr); .put("__cmp__", _self_other_descr) .put("__coerce__", _self_other_descr) .put("__complex__", _only_self_descr) .put("__contains__", _self_item_descr) //_BuiltinMethods.put("__debug__", _only_self_descr); .put("__del__", _only_self_descr) .put("__delete__", new BuiltinDescription("(self, instance)")) .put("__delattr__", _self_item_descr) .put("__delitem__", _self_key_descr) .put("__delslice__", new BuiltinDescription("(self, i, j)")) //_BuiltinMethods.put("__dict__", _only_self_descr); .put("__div__", _self_other_descr) .put("__divmod__", _self_other_descr) //_BuiltinMethods.put("__doc__", _only_self_descr); //_BuiltinMethods.put("__docformat__", _only_self_descr); .put("__enter__", _only_self_descr) .put("__exit__", new BuiltinDescription("(self, exc_type, exc_val, exc_tb)")) .put("__eq__", _self_other_descr) //_BuiltinMethods.put("__file__", _only_self_descr); .put("__float__", _only_self_descr) .put("__floordiv__", _self_other_descr) //_BuiltinMethods.put("__future__", _only_self_descr); .put("__ge__", _self_other_descr) .put("__get__", new BuiltinDescription("(self, instance, owner)")) .put("__getattr__", _self_item_descr) .put("__getattribute__", _self_item_descr) .put("__getitem__", _self_item_descr) //_BuiltinMethods.put("__getslice__", new BuiltinDescription("(self, i, j)")); .put("__gt__", _self_other_descr) .put("__hash__", _only_self_descr) .put("__hex__", _only_self_descr) .put("__iadd__", _self_other_descr) .put("__iand__", _self_other_descr) .put("__idiv__", _self_other_descr) .put("__ifloordiv__", _self_other_descr) //_BuiltinMethods.put("__import__", _only_self_descr); .put("__ilshift__", _self_other_descr) .put("__imod__", _self_other_descr) .put("__imul__", _self_other_descr) .put("__index__", _only_self_descr) .put(INIT, _only_self_descr) .put("__int__", _only_self_descr) .put("__invert__", _only_self_descr) .put("__ior__", _self_other_descr) .put("__ipow__", _self_other_descr) .put("__irshift__", _self_other_descr) .put("__isub__", _self_other_descr) .put("__iter__", _only_self_descr) .put("__itruediv__", _self_other_descr) .put("__ixor__", _self_other_descr) .put("__le__", _self_other_descr) .put("__len__", _only_self_descr) .put("__long__", _only_self_descr) .put("__lshift__", _self_other_descr) .put("__lt__", _self_other_descr) //_BuiltinMethods.put("__members__", _only_self_descr); //_BuiltinMethods.put("__metaclass__", _only_self_descr); .put("__mod__", _self_other_descr) //_BuiltinMethods.put("__mro__", _only_self_descr); .put("__mul__", _self_other_descr) //_BuiltinMethods.put("__name__", _only_self_descr); .put("__ne__", _self_other_descr) .put("__neg__", _only_self_descr) .put(NEW, new BuiltinDescription("(cls, *args, **kwargs)")) .put("__oct__", _only_self_descr) .put("__or__", _self_other_descr) //_BuiltinMethods.put("__path__", _only_self_descr); .put("__pos__", _only_self_descr) .put("__pow__", new BuiltinDescription("(self, power, modulo=None)")) .put("__radd__", _self_other_descr) .put("__rand__", _self_other_descr) .put("__rdiv__", _self_other_descr) .put("__rdivmod__", _self_other_descr) .put("__reduce__", _only_self_descr) .put("__repr__", _only_self_descr) .put("__rfloordiv__", _self_other_descr) .put("__rlshift__", _self_other_descr) .put("__rmod__", _self_other_descr) .put("__rmul__", _self_other_descr) .put("__ror__", _self_other_descr) .put("__rpow__", new BuiltinDescription("(self, power, modulo=None)")) .put("__rrshift__", _self_other_descr) .put("__rshift__", _self_other_descr) .put("__rsub__", _self_other_descr) .put("__rtruediv__", _self_other_descr) .put("__rxor__", _self_other_descr) .put("__set__", new BuiltinDescription("(self, instance, value)")) .put("__setattr__", new BuiltinDescription("(self, key, value)")) .put("__setitem__", new BuiltinDescription("(self, key, value)")) .put("__setslice__", new BuiltinDescription("(self, i, j, sequence)")) //_BuiltinMethods.put("__self__", _only_self_descr); //_BuiltinMethods.put("__slots__", _only_self_descr); .put("__str__", _only_self_descr) .put("__sub__", _self_other_descr) .put("__truediv__", _self_other_descr) .put("__unicode__", _only_self_descr) //_BuiltinMethods.put("__version__", _only_self_descr); .put("__xor__", _self_other_descr) .build(); public static ImmutableMap<String, BuiltinDescription> PY2_BUILTIN_METHODS = ImmutableMap.<String, BuiltinDescription>builder() .putAll(BuiltinMethods) .put("__nonzero__", _only_self_descr) .build(); public static ImmutableMap<String, BuiltinDescription> PY3_BUILTIN_METHODS = ImmutableMap.<String, BuiltinDescription>builder() .putAll(BuiltinMethods) .put("__bool__", _only_self_descr) .build(); public static ImmutableMap<String, BuiltinDescription> getBuiltinMethods(LanguageLevel level) { return level.isPy3K() ? PY3_BUILTIN_METHODS : PY2_BUILTIN_METHODS; } // canonical names, not forced by interpreter public static final String CANONICAL_SELF = "self"; public static final String BASESTRING = "basestring"; /** * Contains keywords as of CPython 2.5. */ public static ImmutableSet<String> Keywords = ImmutableSet.of( "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try" ); public static Set<String> BuiltinInterfaces = ImmutableSet.of( CALLABLE, HASHABLE, ITERABLE, ITERATOR, SIZED, CONTAINER, SEQUENCE, MAPPING, COMPLEX, REAL, RATIONAL, INTEGRAL ); /** * TODO: dependency on language level. * @param name what to check * @return true iff the name is either a keyword or a reserved name, like None. * */ public static boolean isReserved(@NonNls String name) { return Keywords.contains(name) || NONE.equals(name) || "as".equals(name) || "with".equals(name); } // NOTE: includes unicode only good for py3k private final static Pattern IDENTIFIER_PATTERN = Pattern.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*"); /** * TODO: dependency on language level. * @param name what to check * @return true iff name is not reserved and is a well-formed identifier. */ public static boolean isIdentifier(@NotNull @NonNls String name) { return !isReserved(name) && isIdentifierString(name); } public static boolean isIdentifierString(String name) { return IDENTIFIER_PATTERN.matcher(name).matches(); } public static boolean isRightOperatorName(@Nullable String name) { return name != null && name.matches("__r[a-z]+__"); } }
fixed PY-10346 __div__ still highlighted as special method in Python3
python/psi-api/src/com/jetbrains/python/PyNames.java
fixed PY-10346 __div__ still highlighted as special method in Python3
<ide><path>ython/psi-api/src/com/jetbrains/python/PyNames.java <ide> .put("__delitem__", _self_key_descr) <ide> .put("__delslice__", new BuiltinDescription("(self, i, j)")) <ide> //_BuiltinMethods.put("__dict__", _only_self_descr); <del> .put("__div__", _self_other_descr) <ide> .put("__divmod__", _self_other_descr) <ide> //_BuiltinMethods.put("__doc__", _only_self_descr); <ide> //_BuiltinMethods.put("__docformat__", _only_self_descr); <ide> public static ImmutableMap<String, BuiltinDescription> PY2_BUILTIN_METHODS = ImmutableMap.<String, BuiltinDescription>builder() <ide> .putAll(BuiltinMethods) <ide> .put("__nonzero__", _only_self_descr) <add> .put("__div__", _self_other_descr) <ide> .build(); <ide> <ide> public static ImmutableMap<String, BuiltinDescription> PY3_BUILTIN_METHODS = ImmutableMap.<String, BuiltinDescription>builder()
JavaScript
mit
f89f660dee4468b7a8fe88041bd3b9f7b72dacfc
0
stefankendall/mysteryproject,stefankendall/mysteryproject
Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', padding: '20 20 20 20', items: [ ], padding: '20 20 20 20', launch: function() { Ext.create('Rally.data.wsapi.Store', { model: 'User', autoLoad: true, filters: [ { property: 'TeamMemberships', operator: 'contains', value: Rally.util.Ref.getRelativeUri(this.getContext().getProject()) } ], listeners: { load: this._addBoard, scope: this } }); }, _addBoard: function() { var columns = [ { value: null, columnHeaderConfig: { headerData: {planEstimate: 'Unestimated'} } } ]; var estimateValues = [0, 1, 2, 3, 5, 8, 13, 20]; _.each(estimateValues, function(estimate) { columns.push({ value: estimate, columnHeaderConfig: { headerData: {planEstimate: estimate} } }); }); this.add({ xtype: 'rallycardboard', types: ['User Story'], attribute: 'PlanEstimate', context: this.getContext(), columnConfig: { columnHeaderConfig: { headerTpl: '{planEstimate}' } }, storeConfig: { filters: [ { property: 'Iteration', operation: '=', value: '' }, { property: 'DirectChildrenCount', operation: '=', value: '0' } ] }, columns: columns }); } });
js/App.js
Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', padding: '20 20 20 20', items: [ ], padding: '20 20 20 20', launch: function() { Ext.create('Rally.data.wsapi.Store', { model: 'User', autoLoad: true, filters: [ { property: 'TeamMemberships', operator: 'contains', value: Rally.util.Ref.getRelativeUri(this.getContext().getProject()) } ], listeners: { load: this._addBoard, scope: this } }); }, _addBoard: function() { var columns = [ { value: null, columnHeaderConfig: { headerData: {planEstimate: 'Unestimated'} } } ]; var estimateValues = [0, 1, 2, 3, 5, 8, 13, 20]; _.each(estimateValues, function(estimate) { columns.push({ value: estimate, columnHeaderConfig: { headerData: {planEstimate: estimate} } }); }); this.add({ xtype: 'rallycardboard', types: ['User Story'], attribute: 'PlanEstimate', context: this.getContext(), columnConfig: { columnHeaderConfig: { headerTpl: '{planEstimate}' } }, storeConfig: { filters: [ { property: 'Iteration', operation: '=', value: '' } ] }, columns: columns }); } });
DirectCHildrenCount filter
js/App.js
DirectCHildrenCount filter
<ide><path>s/App.js <ide> property: 'Iteration', <ide> operation: '=', <ide> value: '' <add> }, <add> { <add> property: 'DirectChildrenCount', <add> operation: '=', <add> value: '0' <ide> } <ide> ] <ide> },
Java
apache-2.0
57313333483bcb9d9d07ee298b48769dca4abd86
0
a5anka/carbon-registry,arunasujith/carbon-registry,prasa7/carbon-registry,prasa7/carbon-registry,daneshk/carbon-registry,madawas/carbon-registry,a5anka/carbon-registry,Rajith90/carbon-registry,denuwanthi/carbon-registry,daneshk/carbon-registry,wso2/carbon-registry,laki88/carbon-registry,malakasilva/carbon-registry,sameerak/carbon-registry,cnapagoda/carbon-registry,cnapagoda/carbon-registry,pulasthi/carbon-registry,maheshika/carbon-registry,shashikap/carbon-registry,thushara35/carbon-registry,shashikap/carbon-registry,sameerak/carbon-registry,wso2/carbon-registry,arunasujith/carbon-registry,thusithathilina/carbon-registry,denuwanthi/carbon-registry,daneshk/carbon-registry,wso2/carbon-registry,prasa7/carbon-registry,maheshika/carbon-registry,thusithathilina/carbon-registry,denuwanthi/carbon-registry,madawas/carbon-registry,Rajith90/carbon-registry,malakasilva/carbon-registry,sameerak/carbon-registry,maheshika/carbon-registry,arunasujith/carbon-registry,Rajith90/carbon-registry,thushara35/carbon-registry,laki88/carbon-registry,cnapagoda/carbon-registry,Rajith90/carbon-registry,a5anka/carbon-registry,maheshika/carbon-registry,arunasujith/carbon-registry,daneshk/carbon-registry,shashikap/carbon-registry,shashikap/carbon-registry,malakasilva/carbon-registry,thushara35/carbon-registry,thusithathilina/carbon-registry,wso2/carbon-registry,madawas/carbon-registry,thusithathilina/carbon-registry,pulasthi/carbon-registry,madawas/carbon-registry,denuwanthi/carbon-registry,prasa7/carbon-registry,thushara35/carbon-registry,laki88/carbon-registry,pulasthi/carbon-registry,laki88/carbon-registry,cnapagoda/carbon-registry,pulasthi/carbon-registry,sameerak/carbon-registry
/* * Copyright (c) 2005-2010, 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.registry.extensions.utils; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.axis2.context.MessageContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.registry.api.Collection; import org.wso2.carbon.registry.core.*; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryCoreServiceComponent; import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext; import org.wso2.carbon.registry.core.pagination.PaginationContext; import org.wso2.carbon.registry.core.pagination.PaginationUtils; import org.wso2.carbon.registry.core.session.CurrentSession; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.registry.core.utils.MediaTypesUtils; import org.wso2.carbon.registry.core.utils.RegistryUtils; import org.wso2.carbon.registry.extensions.beans.ServiceDocumentsBean; import org.wso2.carbon.registry.extensions.handlers.utils.EndpointUtils; import org.wso2.carbon.user.core.service.RealmService; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; public class CommonUtil { private static final Log log = LogFactory.getLog(CommonUtil.class); private static Random generator = new Random(); public static String getUniqueNameforNamespace(String commonSchemaLocation, String targetNamespace1) { String resourcePath; String targetNamespace = targetNamespace1.replaceAll("\\s+$", ""); targetNamespace = targetNamespace.replace("://", RegistryConstants.PATH_SEPARATOR); targetNamespace = targetNamespace.replace(".", RegistryConstants.PATH_SEPARATOR); targetNamespace = targetNamespace.replace("#", RegistryConstants.PATH_SEPARATOR); while (targetNamespace.indexOf("//") > 0) { targetNamespace = targetNamespace.replace("//", "/"); } if (commonSchemaLocation.endsWith(RegistryConstants.PATH_SEPARATOR)) { resourcePath = new StringBuilder() .append(commonSchemaLocation) .append(targetNamespace).toString(); } else { resourcePath = new StringBuilder() .append(commonSchemaLocation) .append(RegistryConstants.PATH_SEPARATOR) .append(targetNamespace).toString(); } if (!targetNamespace.endsWith(RegistryConstants.PATH_SEPARATOR)) { resourcePath = new StringBuilder().append(resourcePath).append(RegistryConstants.PATH_SEPARATOR).toString(); } return resourcePath; } /** * Returned path fragment will always contain leading and trailing slashes * * @param namespace * @return the path fragment derived from the namespace */ public static String derivePathFragmentFromNamespace(String namespace) { String packageName; if (namespace == null || (packageName = URLProcessor.deriveRegistryPath(namespace)) == null) { return "//"; } String pathFragment = RegistryConstants.PATH_SEPARATOR + packageName.replace(".", RegistryConstants.PATH_SEPARATOR); if (pathFragment.endsWith(RegistryConstants.PATH_SEPARATOR)) { return pathFragment; } else { return pathFragment + RegistryConstants.PATH_SEPARATOR; } } public static String getServiceName(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Name")) != null) { return overview.getFirstChildWithName(new QName("Name")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")).getText(); } } return ""; } /** * Read service version that is input from the user. * * @param element * @return */ public static String getServiceVersion(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Version")) != null) { return overview.getFirstChildWithName(new QName("Version")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")).getText(); } } return ""; } public static void setServiceName(OMElement element, String serviceName) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Name")) != null) { overview.getFirstChildWithName(new QName("Name")).setText(serviceName); return; } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")).setText(serviceName); } } } public static String getServiceNamespace(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Namespace")) != null) { return overview.getFirstChildWithName(new QName("Namespace")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")).getText(); } } return ""; } public static String computeServicePathWithVersion(String path, String version) throws RegistryException { String temp = version; String suffix = "-SNAPSHOT"; if (temp.endsWith(suffix)) { temp = temp.substring(0, temp.length() - suffix.length()); } if (!temp.matches(CommonConstants.SERVICE_VERSION_REGEX)) { String msg = "The specified service version " + version + " is invalid. " + "The requested path to store the service: " + path + "."; log.error(msg); throw new RegistryException(msg); } return path + RegistryConstants.PATH_SEPARATOR + version + RegistryConstants.PATH_SEPARATOR + "service"; } public static String computeProcessPathWithVersion(String path, String version) throws RegistryException { if (!version.matches(CommonConstants.SERVICE_VERSION_REGEX)) { String msg = "The specified process version " + version + " is invalid. " + "The requested path to store the process: " + path + "."; log.error(msg); throw new RegistryException(msg); } return path + RegistryConstants.PATH_SEPARATOR + version.replace(".", RegistryConstants.PATH_SEPARATOR) + RegistryConstants.PATH_SEPARATOR + "process"; } public static String computeSLAPathWithVersion(String path, String version) throws RegistryException { if (!version.matches(CommonConstants.SERVICE_VERSION_REGEX)) { String msg = "The specified sla version " + version + " is invalid. " + "The requested path to store the sla: " + path + "."; log.error(msg); throw new RegistryException(msg); } return path + RegistryConstants.PATH_SEPARATOR + version.replace(".", RegistryConstants.PATH_SEPARATOR) + RegistryConstants.PATH_SEPARATOR + "sla"; } public static void setServiceNamespace(OMElement element, String namespace) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Namespace")) != null) { overview.getFirstChildWithName(new QName("Namespace")).setText(namespace); return; } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")).setText(namespace); } } } public static OMElement[] getEndpointEntries(OMElement element) { OMElement endPoints = element.getFirstChildWithName(new QName("endpoints")); if (endPoints != null) { Iterator it = endPoints.getChildrenWithLocalName("entry"); List<OMElement> endpointList = new ArrayList<OMElement>(); while (it.hasNext()) { endpointList.add(((OMElement) it.next())); } return endpointList.toArray(new OMElement[endpointList.size()]); } endPoints = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "endpoints")); if (endPoints != null) { Iterator it = endPoints.getChildrenWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "entry")); List<OMElement> endpointList = new ArrayList<OMElement>(); while (it.hasNext()) { endpointList.add(((OMElement) it.next())); } return endpointList.toArray(new OMElement[endpointList.size()]); } return null; } public static void setEndpointEntries(OMElement element, OMElement[] endPointsList) { OMElement endPoints = element.getFirstChildWithName(new QName("endpoints")); if (endPointsList != null) { if (endPoints != null) { Iterator it = endPoints.getChildElements(); while (it.hasNext()) { OMElement omElement = (OMElement) it.next(); omElement.detach(); } for (OMElement endPoint : endPointsList) { endPoints.addChild(endPoint); } return; } endPoints = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "endpoints")); if (endPoints != null) { Iterator it = endPoints.getChildElements(); while (it.hasNext()) { OMElement omElement = (OMElement) it.next(); omElement.detach(); } for (OMElement endPoint : endPointsList) { endPoints.addChild(endPoint); } } } } public static void setServiceVersion(OMElement element, String version) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Version")) != null) { overview.getFirstChildWithName(new QName("Version")).setText(version); return; } else { OMElement omElement = OMAbstractFactory.getOMFactory().createOMElement(new QName("Version")); omElement.setText(version); overview.addChild(omElement); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")).setText(version); } else { OMElement omElement = OMAbstractFactory.getOMFactory().createOMElement( new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")); omElement.setText(version); overview.addChild(omElement); } } } public static void setDefinitionURL(OMElement element, String namespace) { // This is a path relative to the chroot OMElement overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "interface")); if(overview == null){ OMElement interfaceElement = OMAbstractFactory.getOMFactory().createOMElement( new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "interface")); OMElement wsdlURLElement = OMAbstractFactory.getOMFactory().createOMElement( new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")); wsdlURLElement.setText(namespace); interfaceElement.addChild(wsdlURLElement); element.addChild(interfaceElement); return; } if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")).setText(namespace); } } public static String getDefinitionURL(OMElement element) { // This will return a path relative to the chroot OMElement overview = element.getFirstChildWithName(new QName("Interface")); if (overview != null) { if (overview.getFirstChildWithName(new QName("WSDL-URL")) != null) { return overview.getFirstChildWithName(new QName("WSDL-URL")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "interface")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")).getText(); } } return ""; } public static String getWorkflowURL(OMElement element) { // This will return a path relative to the chroot OMElement overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "definition")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "bpelURL")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "bpelURL")).getText(); } } return ""; } public static ArrayList<ServiceDocumentsBean> getDocLinks(OMElement element) { ArrayList<ServiceDocumentsBean> documents = new ArrayList<ServiceDocumentsBean>(); OMElement docLinks = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "docLinks")); if (docLinks != null) { for (int itemNo = 0; itemNo <= CommonConstants.NO_OF_DOCUMENTS_ALLOWED; itemNo++) { ServiceDocumentsBean document = new ServiceDocumentsBean(); //This is used because items are separated in xml by appending number to the end, //<documentLinks> // <url></url><documentType></documentType> <url1></url1><documentType1></documentType1> // </documentLinks> String appender = (itemNo == 0 ? "" : "" + itemNo + ""); String description = CommonConstants.DOCUMENT_DESC + appender; String url = CommonConstants.DOCUMENT_URL + appender; String type = CommonConstants.DOCUMENT_TYPE + appender; if (docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, url)) != null) { String documentUrl = docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, url)).getText(); document.setDocumentUrl(documentUrl); } if (document.getDocumentUrl() == null||document.getDocumentUrl().isEmpty() ){ break; }else{ documents.add(document); } if (docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, description)) != null) { String documentDesc = docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, description)).getText(); document.setDocumentDescription(documentDesc); } if (docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, type)) != null) { String documentType = docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, type)).getText(); document.setDocumentType(documentType); } } } return documents; } public static String getServiceDescription(OMElement element) { OMElement overview; overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "description")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "description")).getText(); } } return null; } public static void addService(OMElement service, RequestContext context)throws RegistryException{ Registry registry = context.getRegistry(); Resource resource = registry.newResource(); String tempNamespace = CommonUtil.derivePathFragmentFromNamespace( CommonUtil.getServiceNamespace(service)); String path = getChrootedServiceLocation(registry, context.getRegistryContext()) + tempNamespace + CommonUtil.getServiceName(service); String content = service.toString(); resource.setContent(RegistryUtils.encodeString(content)); resource.setMediaType(RegistryConstants.SERVICE_MEDIA_TYPE); // when saving the resource we are expecting to call the service media type handler, so // we intentionally release the lock here. boolean lockAlreadyAcquired = !CommonUtil.isUpdateLockAvailable(); CommonUtil.releaseUpdateLock(); try { // We check for an existing resource and add its UUID here. if(registry.resourceExists(path)){ Resource existingResource = registry.get(path); resource.setUUID(existingResource.getUUID()); } else { resource.setUUID(UUID.randomUUID().toString()); } resource.setProperty("registry.DefinitionImport","true"); registry.put(path, resource); String defaultLifeCycle = getDefaultServiceLifecycle(registry); if(defaultLifeCycle != null && !defaultLifeCycle.isEmpty()) registry.associateAspect(resource.getId(),defaultLifeCycle); } finally { if (lockAlreadyAcquired) { CommonUtil.acquireUpdateLock(); } } registry.addAssociation(path,RegistryUtils.getAbsolutePath(registry.getRegistryContext(), CommonUtil.getDefinitionURL(service)), CommonConstants.DEPENDS); registry.addAssociation(RegistryUtils.getAbsolutePath(registry.getRegistryContext(), CommonUtil.getDefinitionURL(service)),path, CommonConstants.USED_BY); } private static String getChrootedServiceLocation(Registry registry, RegistryContext registryContext) { return RegistryUtils.getAbsolutePath(registryContext, registry.getRegistryContext().getServicePath()); // service path contains the base } private static String getDefaultServiceLifecycle(Registry registry) throws RegistryException { String[] rxtList = null; String lifecycle = ""; rxtList = MediaTypesUtils.getResultPaths(registry, CommonConstants.RXT_MEDIA_TYPE); for (String rxtcontent : rxtList) { Resource resource = registry.get(rxtcontent); Object content = resource.getContent(); String elementString; if (content instanceof String) { elementString = (String) content; } else { elementString = RegistryUtils.decodeBytes((byte[]) content); } OMElement configElement = null; try { configElement = AXIOMUtil.stringToOM(elementString); } catch (XMLStreamException e) { throw new RegistryException("Error while serializing to OM content from String", e); } if ("service".equals(configElement.getAttributeValue(new QName("shortName")))) { OMElement lifecycleElement = configElement.getFirstChildWithName( new QName("lifecycle")); if (lifecycleElement != null) { lifecycle = lifecycleElement.getText(); } } } return lifecycle; } /* public static void removeArtifactEntry(Registry registry, String artifactId) throws RegistryException { Resource resource; boolean governancePath = false; String govIndexPath = RegistryUtils.getRelativePath(registry.getRegistryContext(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH); if (registry.resourceExists(CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH)) { resource = registry.get(CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH); } else if (registry.resourceExists(govIndexPath)) { resource = registry.get(govIndexPath); governancePath = true; } else { String msg = "The artifact index doesn't exist. artifact index path: " + CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH + "."; log.error(msg); throw new RegistryException(msg); } resource.removeProperty(artifactId); if(governancePath){ registry.put(govIndexPath, resource); }else{ registry.put(CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH, resource); } } */ /** * Adding a governance artifact entry with relative values * * @param registry system registry (without governance base path) * @param artifactId the artifact id * @param artifactPath relative path * @throws RegistryException throws if the operation failed */ /* public static void addGovernanceArtifactEntryWithRelativeValues(Registry registry, String artifactId, String artifactPath) throws RegistryException { if (isArtifactIndexMapExisting()) { addToArtifactIndexMap(artifactId, artifactPath); return; } addGovernanceArtifactEntriesWithRelativeValues(registry, Collections.singletonMap(artifactId, artifactPath)); } */ /* public static void addGovernanceArtifactEntriesWithRelativeValues( Registry registry, Map<String, String> artifactMap) throws RegistryException { String govIndexPath = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH); try { Resource govIndexResource; String path = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), RegistryConstants.LOCAL_REPOSITORY_BASE_PATH); registry.put(path, registry.get(path)); if (registry.resourceExists(govIndexPath)) { govIndexResource = registry.get(govIndexPath); } else { govIndexResource = registry.newResource(); } String firstArtifactId = null; for (Map.Entry<String, String> e : artifactMap.entrySet()) { if (firstArtifactId == null) { firstArtifactId = e.getKey(); } govIndexResource.setProperty(e.getKey(), e.getValue()); } ((ResourceImpl) govIndexResource).setVersionableChange(false); registry.put(govIndexPath, govIndexResource); // Since puts can happen in multiple transactions, synchronization would not solve this issue. // Therefore, we need to rely on DBs properly doing row-level locking. In such a setup, puts // to a single row, would automatically be serialized. if (firstArtifactId != null && registry.get(govIndexPath).getProperty(firstArtifactId) == null) { // We have detected a concurrent modification, so we will retry. // But first, back-off for a while, to ensure that all threads get an equal chance. try { // Wait from 0 to 1s. Thread.sleep(generator.nextInt(11) * 100); } catch (InterruptedException ignored) { } addGovernanceArtifactEntriesWithRelativeValues(registry, artifactMap); } } catch (RegistryException e) { String msg = "Error in adding entries for the governance artifacts."; log.error(msg); throw new RegistryException(msg, e); } } */ /** * Adding a governance artifact entry with absolute values * * @param registry system registry (without governance base path) * @param artifactId the artifact id * @param artifactPath absolute path * @throws RegistryException throws if the operation failed */ /* public static void addGovernanceArtifactEntryWithAbsoluteValues(Registry registry, String artifactId, String artifactPath) throws RegistryException { String relativeArtifactPath = RegistryUtils.getRelativePath( registry.getRegistryContext(), artifactPath); // adn then get the relative path to the GOVERNANCE_BASE_PATH relativeArtifactPath = RegistryUtils.getRelativePathToOriginal(relativeArtifactPath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH); addGovernanceArtifactEntryWithRelativeValues(registry, artifactId, relativeArtifactPath); } */ // handling the possibility that handlers are not called within each other. private static InheritableThreadLocal<Map<String, String>> artifactIndexMap = new InheritableThreadLocal<Map<String, String>>() { protected Map<String, String> initialValue() { return null; } }; public static boolean isArtifactIndexMapExisting() { return artifactIndexMap.get() != null; } public static void createArtifactIndexMap() { artifactIndexMap.set(new ConcurrentHashMap<String, String>()); } public static void addToArtifactIndexMap(String key, String value) { artifactIndexMap.get().put(key, value); } public static Map<String, String> getAndRemoveArtifactIndexMap() { Map<String, String> output = artifactIndexMap.get(); artifactIndexMap.set(null); return output; } // handling the possibility that handlers are not called within each other. private static InheritableThreadLocal<Map<String, String>> symbolicLinkMap = new InheritableThreadLocal<Map<String, String>>() { protected Map<String, String> initialValue() { return null; } }; public static boolean isSymbolicLinkMapExisting() { return symbolicLinkMap.get() != null; } public static void createSymbolicLinkMap() { symbolicLinkMap.set(new ConcurrentHashMap<String, String>()); } public static void addToSymbolicLinkMap(String key, String value) { symbolicLinkMap.get().put(key, value); } public static Map<String, String> getAndRemoveSymbolicLinkMap() { Map<String, String> output = symbolicLinkMap.get(); symbolicLinkMap.set(null); return output; } private static InheritableThreadLocal<Set<String>> importedArtifacts = new InheritableThreadLocal<Set<String>>() { protected Set<String> initialValue() { return new ConcurrentSkipListSet<String>(); } }; public static void loadImportedArtifactMap() { importedArtifacts.get(); } public static void clearImportedArtifactMap() { importedArtifacts.remove(); } public static void addImportedArtifact(String path) { importedArtifacts.get().add(path); } public static boolean isImportedArtifactExisting(String path) { return importedArtifacts.get().contains(path); } // handling the possibility that handlers are not called within each other. private static ThreadLocal<Boolean> scmTaskInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isSCMLockAvailable() { return !scmTaskInProgress.get(); } public static void acquireSCMLock() { scmTaskInProgress.set(true); } public static void releaseSCMLock() { scmTaskInProgress.set(false); } // handling the possibility that handlers are not called within each other. private static ThreadLocal<Boolean> updateInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isUpdateLockAvailable() { return !updateInProgress.get(); } public static void acquireUpdateLock() { updateInProgress.set(true); } public static void releaseUpdateLock() { updateInProgress.set(false); } private static ThreadLocal<Boolean> deleteInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isDeleteLockAvailable() { return !deleteInProgress.get(); } public static void acquireDeleteLock() { deleteInProgress.set(true); } public static void releaseDeleteLock() { deleteInProgress.set(false); } private static ThreadLocal<Boolean> restoringInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isRestoringLockAvailable() { return !restoringInProgress.get(); } public static void acquireRestoringLock() { restoringInProgress.set(true); } public static void releaseRestoringLock() { restoringInProgress.set(false); } private static ThreadLocal<Boolean> addingAssociationInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isAddingAssociationLockAvailable() { return !addingAssociationInProgress.get(); } public static void acquireAddingAssociationLock() { addingAssociationInProgress.set(true); } public static void releaseAddingAssociationLock() { addingAssociationInProgress.set(false); } public static String getEndpointPathFromUrl(String url) { String urlToPath = EndpointUtils.deriveEndpointFromUrl(url); return EndpointUtils.getEndpointLocation() + urlToPath; } public static Registry getUnchrootedSystemRegistry(RequestContext requestContext) throws RegistryException { Registry registry = requestContext.getRegistry(); RealmService realmService = registry.getRegistryContext().getRealmService(); String systemUser = CarbonConstants.REGISTRY_SYSTEM_USERNAME; return new UserRegistry(systemUser, CurrentSession.getTenantId(), registry, realmService, null); } public static String getConsumerType(OMElement element) { //get rid of this method OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Type")) != null) { return overview.getFirstChildWithName(new QName("Type")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")).getText(); } } return ""; } public static String getPeopleGroup(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Group")) != null) { return overview.getFirstChildWithName(new QName("Group")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "group")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "group")).getText(); } } return ""; } public static String getPeopleType(OMElement element) { //get rid of this method OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Type")) != null) { return overview.getFirstChildWithName(new QName("Type")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")).getText(); } } return ""; } public static Association[] getDependenciesRecursively(Registry registry, String resourcePath) throws RegistryException { return getDependenciesRecursively(registry, resourcePath, new ArrayList<String>()); } private static Association[] getDependenciesRecursively(Registry registry, String resourcePath, List<String> traversedDependencyPaths) throws RegistryException { List<Association> dependencies = new ArrayList<Association>(); if (!traversedDependencyPaths.contains(resourcePath)) { traversedDependencyPaths.add(resourcePath); List<Association> tempDependencies = Arrays.asList(registry.getAssociations(resourcePath, CommonConstants.DEPENDS)); for (Association association : tempDependencies) { if (!traversedDependencyPaths.contains(association.getDestinationPath())) { dependencies.add(association); List<Association> childDependencies = Arrays.asList( getDependenciesRecursively( registry, association.getDestinationPath(), traversedDependencyPaths) ); if (!childDependencies.isEmpty()) { dependencies.addAll(childDependencies); } } } } return dependencies.toArray(new Association[dependencies.size()]); } }
components/registry/org.wso2.carbon.registry.extensions/src/main/java/org/wso2/carbon/registry/extensions/utils/CommonUtil.java
/* * Copyright (c) 2005-2010, 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.registry.extensions.utils; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.axis2.context.MessageContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.registry.api.Collection; import org.wso2.carbon.registry.core.*; import org.wso2.carbon.registry.core.config.RegistryContext; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.internal.RegistryCoreServiceComponent; import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext; import org.wso2.carbon.registry.core.pagination.PaginationContext; import org.wso2.carbon.registry.core.pagination.PaginationUtils; import org.wso2.carbon.registry.core.session.CurrentSession; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.registry.core.utils.MediaTypesUtils; import org.wso2.carbon.registry.core.utils.RegistryUtils; import org.wso2.carbon.registry.extensions.beans.ServiceDocumentsBean; import org.wso2.carbon.registry.extensions.handlers.utils.EndpointUtils; import org.wso2.carbon.user.core.service.RealmService; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; public class CommonUtil { private static final Log log = LogFactory.getLog(CommonUtil.class); private static Random generator = new Random(); public static String getUniqueNameforNamespace(String commonSchemaLocation, String targetNamespace1) { String resourcePath; String targetNamespace = targetNamespace1.replaceAll("\\s+$", ""); targetNamespace = targetNamespace.replace("://", RegistryConstants.PATH_SEPARATOR); targetNamespace = targetNamespace.replace(".", RegistryConstants.PATH_SEPARATOR); targetNamespace = targetNamespace.replace("#", RegistryConstants.PATH_SEPARATOR); while (targetNamespace.indexOf("//") > 0) { targetNamespace = targetNamespace.replace("//", "/"); } if (commonSchemaLocation.endsWith(RegistryConstants.PATH_SEPARATOR)) { resourcePath = new StringBuilder() .append(commonSchemaLocation) .append(targetNamespace).toString(); } else { resourcePath = new StringBuilder() .append(commonSchemaLocation) .append(RegistryConstants.PATH_SEPARATOR) .append(targetNamespace).toString(); } if (!targetNamespace.endsWith(RegistryConstants.PATH_SEPARATOR)) { resourcePath = new StringBuilder().append(resourcePath).append(RegistryConstants.PATH_SEPARATOR).toString(); } return resourcePath; } /** * Returned path fragment will always contain leading and trailing slashes * * @param namespace * @return the path fragment derived from the namespace */ public static String derivePathFragmentFromNamespace(String namespace) { String packageName; if (namespace == null || (packageName = URLProcessor.deriveRegistryPath(namespace)) == null) { return "//"; } String pathFragment = RegistryConstants.PATH_SEPARATOR + packageName.replace(".", RegistryConstants.PATH_SEPARATOR); if (pathFragment.endsWith(RegistryConstants.PATH_SEPARATOR)) { return pathFragment; } else { return pathFragment + RegistryConstants.PATH_SEPARATOR; } } public static String getServiceName(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Name")) != null) { return overview.getFirstChildWithName(new QName("Name")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")).getText(); } } return ""; } /** * Read service version that is input from the user. * * @param element * @return */ public static String getServiceVersion(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Version")) != null) { return overview.getFirstChildWithName(new QName("Version")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")).getText(); } } return ""; } public static void setServiceName(OMElement element, String serviceName) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Name")) != null) { overview.getFirstChildWithName(new QName("Name")).setText(serviceName); return; } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "name")).setText(serviceName); } } } public static String getServiceNamespace(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Namespace")) != null) { return overview.getFirstChildWithName(new QName("Namespace")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")).getText(); } } return ""; } public static String computeServicePathWithVersion(String path, String version) throws RegistryException { String temp = version; String suffix = "-SNAPSHOT"; if (temp.endsWith(suffix)) { temp = temp.substring(0, temp.length() - suffix.length()); } if (!temp.matches(CommonConstants.SERVICE_VERSION_REGEX)) { String msg = "The specified service version " + version + " is invalid. " + "The requested path to store the service: " + path + "."; log.error(msg); throw new RegistryException(msg); } return path + RegistryConstants.PATH_SEPARATOR + version + RegistryConstants.PATH_SEPARATOR + "service"; } public static String computeProcessPathWithVersion(String path, String version) throws RegistryException { if (!version.matches(CommonConstants.SERVICE_VERSION_REGEX)) { String msg = "The specified process version " + version + " is invalid. " + "The requested path to store the process: " + path + "."; log.error(msg); throw new RegistryException(msg); } return path + RegistryConstants.PATH_SEPARATOR + version.replace(".", RegistryConstants.PATH_SEPARATOR) + RegistryConstants.PATH_SEPARATOR + "process"; } public static String computeSLAPathWithVersion(String path, String version) throws RegistryException { if (!version.matches(CommonConstants.SERVICE_VERSION_REGEX)) { String msg = "The specified sla version " + version + " is invalid. " + "The requested path to store the sla: " + path + "."; log.error(msg); throw new RegistryException(msg); } return path + RegistryConstants.PATH_SEPARATOR + version.replace(".", RegistryConstants.PATH_SEPARATOR) + RegistryConstants.PATH_SEPARATOR + "sla"; } public static void setServiceNamespace(OMElement element, String namespace) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Namespace")) != null) { overview.getFirstChildWithName(new QName("Namespace")).setText(namespace); return; } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "namespace")).setText(namespace); } } } public static OMElement[] getEndpointEntries(OMElement element) { OMElement endPoints = element.getFirstChildWithName(new QName("endpoints")); if (endPoints != null) { Iterator it = endPoints.getChildrenWithLocalName("entry"); List<OMElement> endpointList = new ArrayList<OMElement>(); while (it.hasNext()) { endpointList.add(((OMElement) it.next())); } return endpointList.toArray(new OMElement[endpointList.size()]); } endPoints = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "endpoints")); if (endPoints != null) { Iterator it = endPoints.getChildrenWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "entry")); List<OMElement> endpointList = new ArrayList<OMElement>(); while (it.hasNext()) { endpointList.add(((OMElement) it.next())); } return endpointList.toArray(new OMElement[endpointList.size()]); } return null; } public static void setEndpointEntries(OMElement element, OMElement[] endPointsList) { OMElement endPoints = element.getFirstChildWithName(new QName("endpoints")); if (endPointsList != null) { if (endPoints != null) { Iterator it = endPoints.getChildElements(); while (it.hasNext()) { OMElement omElement = (OMElement) it.next(); omElement.detach(); } for (OMElement endPoint : endPointsList) { endPoints.addChild(endPoint); } return; } endPoints = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "endpoints")); if (endPoints != null) { Iterator it = endPoints.getChildElements(); while (it.hasNext()) { OMElement omElement = (OMElement) it.next(); omElement.detach(); } for (OMElement endPoint : endPointsList) { endPoints.addChild(endPoint); } } } } public static void setServiceVersion(OMElement element, String version) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Version")) != null) { overview.getFirstChildWithName(new QName("Version")).setText(version); return; } else { OMElement omElement = OMAbstractFactory.getOMFactory().createOMElement(new QName("Version")); omElement.setText(version); overview.addChild(omElement); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")).setText(version); } else { OMElement omElement = OMAbstractFactory.getOMFactory().createOMElement( new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "version")); omElement.setText(version); overview.addChild(omElement); } } } public static void setDefinitionURL(OMElement element, String namespace) { // This is a path relative to the chroot OMElement overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "interface")); if(overview == null){ OMElement interfaceElement = OMAbstractFactory.getOMFactory().createOMElement( new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "interface")); OMElement wsdlURLElement = OMAbstractFactory.getOMFactory().createOMElement( new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")); wsdlURLElement.setText(namespace); interfaceElement.addChild(wsdlURLElement); element.addChild(interfaceElement); return; } if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")) != null) { overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")).setText(namespace); } } public static String getDefinitionURL(OMElement element) { // This will return a path relative to the chroot OMElement overview = element.getFirstChildWithName(new QName("Interface")); if (overview != null) { if (overview.getFirstChildWithName(new QName("WSDL-URL")) != null) { return overview.getFirstChildWithName(new QName("WSDL-URL")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "interface")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "wsdlURL")).getText(); } } return ""; } public static String getWorkflowURL(OMElement element) { // This will return a path relative to the chroot OMElement overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "definition")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "bpelURL")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "bpelURL")).getText(); } } return ""; } public static ArrayList<ServiceDocumentsBean> getDocLinks(OMElement element) { ArrayList<ServiceDocumentsBean> documents = new ArrayList<ServiceDocumentsBean>(); OMElement docLinks = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "docLinks")); if (docLinks != null) { for (int itemNo = 0; itemNo <= CommonConstants.NO_OF_DOCUMENTS_ALLOWED; itemNo++) { ServiceDocumentsBean document = new ServiceDocumentsBean(); //This is used because items are separated in xml by appending number to the end, //<documentLinks> // <url></url><documentType></documentType> <url1></url1><documentType1></documentType1> // </documentLinks> String appender = (itemNo == 0 ? "" : "" + itemNo + ""); String description = CommonConstants.DOCUMENT_DESC + appender; String url = CommonConstants.DOCUMENT_URL + appender; String type = CommonConstants.DOCUMENT_TYPE + appender; if (docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, url)) != null) { String documentUrl = docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, url)).getText(); document.setDocumentUrl(documentUrl); } if (document.getDocumentUrl() == null||document.getDocumentUrl().isEmpty() ){ break; }else{ documents.add(document); } if (docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, description)) != null) { String documentDesc = docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, description)).getText(); document.setDocumentDescription(documentDesc); } if (docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, type)) != null) { String documentType = docLinks.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, type)).getText(); document.setDocumentType(documentType); } } } return documents; } public static String getServiceDescription(OMElement element) { OMElement overview; overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "description")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "description")).getText(); } } return null; } public static void addService(OMElement service, RequestContext context)throws RegistryException{ Registry registry = context.getRegistry(); Resource resource = registry.newResource(); String tempNamespace = CommonUtil.derivePathFragmentFromNamespace( CommonUtil.getServiceNamespace(service)); String path = getChrootedServiceLocation(registry, context.getRegistryContext()) + tempNamespace + CommonUtil.getServiceName(service); String content = service.toString(); resource.setContent(RegistryUtils.encodeString(content)); resource.setMediaType(RegistryConstants.SERVICE_MEDIA_TYPE); // when saving the resource we are expecting to call the service media type handler, so // we intentionally release the lock here. boolean lockAlreadyAcquired = !CommonUtil.isUpdateLockAvailable(); CommonUtil.releaseUpdateLock(); try { // We check for an existing resource and add its UUID here. if(registry.resourceExists(path)){ Resource existingResource = registry.get(path); resource.setUUID(existingResource.getUUID()); } else { resource.setUUID(UUID.randomUUID().toString()); } resource.setProperty("registry.DefinitionImport","true"); registry.put(path, resource); String defaultLifeCycle = getDefaultServiceLifecycle(registry); if(defaultLifeCycle != null && !defaultLifeCycle.isEmpty()) registry.associateAspect(resource.getId(),defaultLifeCycle); } finally { if (lockAlreadyAcquired) { CommonUtil.acquireUpdateLock(); } } registry.addAssociation(path,RegistryUtils.getAbsolutePath(registry.getRegistryContext(), CommonUtil.getDefinitionURL(service)), CommonConstants.DEPENDS); registry.addAssociation(RegistryUtils.getAbsolutePath(registry.getRegistryContext(), CommonUtil.getDefinitionURL(service)),path, CommonConstants.USED_BY); } private static String getChrootedServiceLocation(Registry registry, RegistryContext registryContext) { return RegistryUtils.getAbsolutePath(registryContext, registry.getRegistryContext().getServicePath()); // service path contains the base } private static String getDefaultServiceLifecycle(Registry registry) throws RegistryException { String[] rxtList = null; String lifecycle = ""; rxtList = MediaTypesUtils.getResultPaths(registry, CommonConstants.RXT_MEDIA_TYPE); for (String rxtcontent : rxtList) { OMElement configElement = null; try { configElement = AXIOMUtil.stringToOM(rxtcontent); } catch (XMLStreamException e) { throw new RegistryException("Error while serializing to OM content from String", e); } if ("service".equals(configElement.getAttributeValue(new QName("shortName")))) { OMElement lifecycleElement = configElement.getFirstChildWithName( new QName("lifecycle")); if (lifecycleElement != null) { lifecycle = lifecycleElement.getText(); } } } return lifecycle; } /* public static void removeArtifactEntry(Registry registry, String artifactId) throws RegistryException { Resource resource; boolean governancePath = false; String govIndexPath = RegistryUtils.getRelativePath(registry.getRegistryContext(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH); if (registry.resourceExists(CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH)) { resource = registry.get(CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH); } else if (registry.resourceExists(govIndexPath)) { resource = registry.get(govIndexPath); governancePath = true; } else { String msg = "The artifact index doesn't exist. artifact index path: " + CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH + "."; log.error(msg); throw new RegistryException(msg); } resource.removeProperty(artifactId); if(governancePath){ registry.put(govIndexPath, resource); }else{ registry.put(CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH, resource); } } */ /** * Adding a governance artifact entry with relative values * * @param registry system registry (without governance base path) * @param artifactId the artifact id * @param artifactPath relative path * @throws RegistryException throws if the operation failed */ /* public static void addGovernanceArtifactEntryWithRelativeValues(Registry registry, String artifactId, String artifactPath) throws RegistryException { if (isArtifactIndexMapExisting()) { addToArtifactIndexMap(artifactId, artifactPath); return; } addGovernanceArtifactEntriesWithRelativeValues(registry, Collections.singletonMap(artifactId, artifactPath)); } */ /* public static void addGovernanceArtifactEntriesWithRelativeValues( Registry registry, Map<String, String> artifactMap) throws RegistryException { String govIndexPath = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + CommonConstants.GOVERNANCE_ARTIFACT_INDEX_PATH); try { Resource govIndexResource; String path = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), RegistryConstants.LOCAL_REPOSITORY_BASE_PATH); registry.put(path, registry.get(path)); if (registry.resourceExists(govIndexPath)) { govIndexResource = registry.get(govIndexPath); } else { govIndexResource = registry.newResource(); } String firstArtifactId = null; for (Map.Entry<String, String> e : artifactMap.entrySet()) { if (firstArtifactId == null) { firstArtifactId = e.getKey(); } govIndexResource.setProperty(e.getKey(), e.getValue()); } ((ResourceImpl) govIndexResource).setVersionableChange(false); registry.put(govIndexPath, govIndexResource); // Since puts can happen in multiple transactions, synchronization would not solve this issue. // Therefore, we need to rely on DBs properly doing row-level locking. In such a setup, puts // to a single row, would automatically be serialized. if (firstArtifactId != null && registry.get(govIndexPath).getProperty(firstArtifactId) == null) { // We have detected a concurrent modification, so we will retry. // But first, back-off for a while, to ensure that all threads get an equal chance. try { // Wait from 0 to 1s. Thread.sleep(generator.nextInt(11) * 100); } catch (InterruptedException ignored) { } addGovernanceArtifactEntriesWithRelativeValues(registry, artifactMap); } } catch (RegistryException e) { String msg = "Error in adding entries for the governance artifacts."; log.error(msg); throw new RegistryException(msg, e); } } */ /** * Adding a governance artifact entry with absolute values * * @param registry system registry (without governance base path) * @param artifactId the artifact id * @param artifactPath absolute path * @throws RegistryException throws if the operation failed */ /* public static void addGovernanceArtifactEntryWithAbsoluteValues(Registry registry, String artifactId, String artifactPath) throws RegistryException { String relativeArtifactPath = RegistryUtils.getRelativePath( registry.getRegistryContext(), artifactPath); // adn then get the relative path to the GOVERNANCE_BASE_PATH relativeArtifactPath = RegistryUtils.getRelativePathToOriginal(relativeArtifactPath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH); addGovernanceArtifactEntryWithRelativeValues(registry, artifactId, relativeArtifactPath); } */ // handling the possibility that handlers are not called within each other. private static InheritableThreadLocal<Map<String, String>> artifactIndexMap = new InheritableThreadLocal<Map<String, String>>() { protected Map<String, String> initialValue() { return null; } }; public static boolean isArtifactIndexMapExisting() { return artifactIndexMap.get() != null; } public static void createArtifactIndexMap() { artifactIndexMap.set(new ConcurrentHashMap<String, String>()); } public static void addToArtifactIndexMap(String key, String value) { artifactIndexMap.get().put(key, value); } public static Map<String, String> getAndRemoveArtifactIndexMap() { Map<String, String> output = artifactIndexMap.get(); artifactIndexMap.set(null); return output; } // handling the possibility that handlers are not called within each other. private static InheritableThreadLocal<Map<String, String>> symbolicLinkMap = new InheritableThreadLocal<Map<String, String>>() { protected Map<String, String> initialValue() { return null; } }; public static boolean isSymbolicLinkMapExisting() { return symbolicLinkMap.get() != null; } public static void createSymbolicLinkMap() { symbolicLinkMap.set(new ConcurrentHashMap<String, String>()); } public static void addToSymbolicLinkMap(String key, String value) { symbolicLinkMap.get().put(key, value); } public static Map<String, String> getAndRemoveSymbolicLinkMap() { Map<String, String> output = symbolicLinkMap.get(); symbolicLinkMap.set(null); return output; } private static InheritableThreadLocal<Set<String>> importedArtifacts = new InheritableThreadLocal<Set<String>>() { protected Set<String> initialValue() { return new ConcurrentSkipListSet<String>(); } }; public static void loadImportedArtifactMap() { importedArtifacts.get(); } public static void clearImportedArtifactMap() { importedArtifacts.remove(); } public static void addImportedArtifact(String path) { importedArtifacts.get().add(path); } public static boolean isImportedArtifactExisting(String path) { return importedArtifacts.get().contains(path); } // handling the possibility that handlers are not called within each other. private static ThreadLocal<Boolean> scmTaskInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isSCMLockAvailable() { return !scmTaskInProgress.get(); } public static void acquireSCMLock() { scmTaskInProgress.set(true); } public static void releaseSCMLock() { scmTaskInProgress.set(false); } // handling the possibility that handlers are not called within each other. private static ThreadLocal<Boolean> updateInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isUpdateLockAvailable() { return !updateInProgress.get(); } public static void acquireUpdateLock() { updateInProgress.set(true); } public static void releaseUpdateLock() { updateInProgress.set(false); } private static ThreadLocal<Boolean> deleteInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isDeleteLockAvailable() { return !deleteInProgress.get(); } public static void acquireDeleteLock() { deleteInProgress.set(true); } public static void releaseDeleteLock() { deleteInProgress.set(false); } private static ThreadLocal<Boolean> restoringInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isRestoringLockAvailable() { return !restoringInProgress.get(); } public static void acquireRestoringLock() { restoringInProgress.set(true); } public static void releaseRestoringLock() { restoringInProgress.set(false); } private static ThreadLocal<Boolean> addingAssociationInProgress = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return false; } }; public static boolean isAddingAssociationLockAvailable() { return !addingAssociationInProgress.get(); } public static void acquireAddingAssociationLock() { addingAssociationInProgress.set(true); } public static void releaseAddingAssociationLock() { addingAssociationInProgress.set(false); } public static String getEndpointPathFromUrl(String url) { String urlToPath = EndpointUtils.deriveEndpointFromUrl(url); return EndpointUtils.getEndpointLocation() + urlToPath; } public static Registry getUnchrootedSystemRegistry(RequestContext requestContext) throws RegistryException { Registry registry = requestContext.getRegistry(); RealmService realmService = registry.getRegistryContext().getRealmService(); String systemUser = CarbonConstants.REGISTRY_SYSTEM_USERNAME; return new UserRegistry(systemUser, CurrentSession.getTenantId(), registry, realmService, null); } public static String getConsumerType(OMElement element) { //get rid of this method OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Type")) != null) { return overview.getFirstChildWithName(new QName("Type")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")).getText(); } } return ""; } public static String getPeopleGroup(OMElement element) { OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Group")) != null) { return overview.getFirstChildWithName(new QName("Group")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "group")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "group")).getText(); } } return ""; } public static String getPeopleType(OMElement element) { //get rid of this method OMElement overview = element.getFirstChildWithName(new QName("Overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName("Type")) != null) { return overview.getFirstChildWithName(new QName("Type")).getText(); } } overview = element.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "overview")); if (overview != null) { if (overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")) != null) { return overview.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "type")).getText(); } } return ""; } public static Association[] getDependenciesRecursively(Registry registry, String resourcePath) throws RegistryException { return getDependenciesRecursively(registry, resourcePath, new ArrayList<String>()); } private static Association[] getDependenciesRecursively(Registry registry, String resourcePath, List<String> traversedDependencyPaths) throws RegistryException { List<Association> dependencies = new ArrayList<Association>(); if (!traversedDependencyPaths.contains(resourcePath)) { traversedDependencyPaths.add(resourcePath); List<Association> tempDependencies = Arrays.asList(registry.getAssociations(resourcePath, CommonConstants.DEPENDS)); for (Association association : tempDependencies) { if (!traversedDependencyPaths.contains(association.getDestinationPath())) { dependencies.add(association); List<Association> childDependencies = Arrays.asList( getDependenciesRecursively( registry, association.getDestinationPath(), traversedDependencyPaths) ); if (!childDependencies.isEmpty()) { dependencies.addAll(childDependencies); } } } } return dependencies.toArray(new Association[dependencies.size()]); } }
Fixed LC read issue
components/registry/org.wso2.carbon.registry.extensions/src/main/java/org/wso2/carbon/registry/extensions/utils/CommonUtil.java
Fixed LC read issue
<ide><path>omponents/registry/org.wso2.carbon.registry.extensions/src/main/java/org/wso2/carbon/registry/extensions/utils/CommonUtil.java <ide> rxtList = MediaTypesUtils.getResultPaths(registry, CommonConstants.RXT_MEDIA_TYPE); <ide> <ide> for (String rxtcontent : rxtList) { <add> Resource resource = registry.get(rxtcontent); <add> Object content = resource.getContent(); <add> String elementString; <add> if (content instanceof String) { <add> elementString = (String) content; <add> } else { <add> elementString = RegistryUtils.decodeBytes((byte[]) content); <add> } <ide> OMElement configElement = null; <ide> try { <del> configElement = AXIOMUtil.stringToOM(rxtcontent); <add> configElement = AXIOMUtil.stringToOM(elementString); <ide> } catch (XMLStreamException e) { <ide> throw new RegistryException("Error while serializing to OM content from String", e); <ide> }
JavaScript
mit
d6a365739483e4a177096a3f3dada6abc2c62777
0
why2pac/knex-automigrate
const fs = require('fs') const helper = require('./index/helper') module.exports = function (opts) { return new Promise(function (resolve, reject) { opts = opts || {} const knex = require('knex')(opts.config) // TODO: Migration PK (Y,N) // TODO: Migration Indexes (Y,N) // TODO: Migration Unique Attr. (Y,N) // TODO: Migration Reference Attr. (Y,N) var tabler = function () { var appended = [] return new Proxy({}, { get: function (target, method) { if (method === '__appended__') { return appended } if (typeof (method) !== 'string' || ['constructor'].indexOf(method) !== -1) { return undefined } return function (a, b, c) { var proxy = tabler() appended.push([proxy, method, [a, b, c]]) return proxy } } }) } var migrator = async function (tableName, fn, initRows) { var exists = await knex.schema.hasTable(tableName) if (!exists) { await knex.schema.createTable(tableName, function (table) { fn(table) }) } else { var existColumns = await knex.from(tableName).columnInfo() var existIndexes = await (require('./index')(knex, tableName)) var schemaColumns = {} var schemaIndexes = {pk: [], uk: [], key: [], fk: []} await knex.schema.alterTable(tableName, function (table) { var prevColumnName var columnName var proxy = tabler() fn(proxy) var column = function (t, e, depth) { if (!e || !e[0]) return var method = e[1] var args = e[2] if (depth === 0) { columnName = e[2][0] schemaColumns[columnName] = true } // If exists primary key already. if ((method === 'increments' || method === 'bigIncrements') && existIndexes.pk.length > 0) { return t } if (method === 'index') { schemaIndexes.key.push(typeof (args[0]) === 'string' ? [args[0]] : args[0]) // If exists index already. if (existIndexes.isIndexExists(args[0], args[1])) { return t } } var isAppliable = true if (method === 'references') { schemaIndexes.fk.push([columnName, typeof (args[0]) === 'string' ? [args[0]] : args[0]]) // If exists foreign key already. if (existIndexes.isForeignKeyExists(columnName, args[0])) { isAppliable = false } } if (method === 'unique') { var keys = args[0] || columnName schemaIndexes.uk.push(typeof (keys) === 'string' ? [keys] : keys) // If exists unique index already. if (existIndexes.isUniqueExists(args[0] || columnName)) { isAppliable = false if (depth === 0) { return t } } } if (method === 'primary') { let keys = args[0] || columnName schemaIndexes.pk.push(typeof (keys) === 'string' ? [keys] : keys) // If exists primary key already. if (existIndexes.isPrimaryKeyExists(args[0] || columnName)) { isAppliable = false if (depth === 0) { return t } } } if (isAppliable) { let fn = t[method] t = fn.apply(t, args) } e[0].__appended__.forEach(function (e) { t = column(t, e, depth + 1) }) if (depth === 0) { if (['index', 'unique'].indexOf(method) === -1) { if (existColumns[columnName]) { t.alter() } else { if (prevColumnName) { t = t.after(prevColumnName) } else { t = t.first() } } } prevColumnName = columnName } return t } proxy.__appended__.forEach(function (e) { column(table, e, 0) }) // Drop unused columns. var dropColumns = [] Object.keys(existColumns).forEach(function (e) { if (!schemaColumns[e]) { Object.keys(existIndexes.fk).forEach(function (key) { if (helper.isArrayEqual([e], existIndexes.fk[key].key)) { table.dropForeign(undefined, key) } }) dropColumns.push(e) } }) if (dropColumns.length > 0) { table.dropColumns(dropColumns) } // Drop unused indexes. Object.keys(existIndexes.key).forEach(function (key) { var found = false schemaIndexes.key.forEach(function (sKey) { if (helper.isArrayEqual(existIndexes.key[key], sKey)) found = true }) schemaIndexes.fk.forEach(function (sKey) { sKey = typeof (sKey[0]) === 'string' ? [sKey[0]] : sKey[0] if (helper.isArrayEqual(existIndexes.key[key], sKey)) found = true }) if (!found) { table.dropIndex(undefined, key) } }) Object.keys(existIndexes.uk).forEach(function (key) { var found = false schemaIndexes.uk.forEach(function (sKey) { if (helper.isArrayEqual(existIndexes.uk[key], sKey)) found = true }) if (!found) { table.dropUnique(undefined, key) } }) }) } if (typeof initRows === 'function') { const existRows = (await knex.count('* AS cnt').from(tableName))[0].cnt if (!existRows) { const rows = initRows(opts.config) if (rows && rows.length) { await knex.batchInsert(tableName, rows); } } } return tableName } var promises = [] opts.path = opts.cwd || process.cwd() const dummyMigrator = (a, b, c) => { return { call: async () => { const res = await migrator(a, b, c) return res } } } fs.readdirSync(opts.path).forEach(function (name) { if (name.slice(0, 6) !== 'table_') return require(opts.path + '/' + name).auto(dummyMigrator, knex).forEach(function (e) { promises.push([name, e]) }) }) var execute = function (i) { promises[i][1].call().then(function (res) { console.info('* Table `' + res + '` has been migrated.') if (i < promises.length - 1) { execute(i + 1) } else { resolve() } }).catch(function (err) { console.error('* Table `' + promises[i][0] + '` migration failed.') reject(err) }) } if (promises.length > 0) { execute(0) } else { console.info('* No schema exist.') } }) }
lib/automigrate.js
const fs = require('fs') const helper = require('./index/helper') module.exports = function (opts) { return new Promise(function (resolve, reject) { opts = opts || {} const knex = require('knex')(opts.config) // TODO: Migration PK (Y,N) // TODO: Migration Indexes (Y,N) // TODO: Migration Unique Attr. (Y,N) // TODO: Migration Reference Attr. (Y,N) var tabler = function () { var appended = [] return new Proxy({}, { get: function (target, method) { if (method === '__appended__') { return appended } if (typeof (method) !== 'string' || ['constructor'].indexOf(method) !== -1) { return undefined } return function (a, b, c) { var proxy = tabler() appended.push([proxy, method, [a, b, c]]) return proxy } } }) } var migrator = async function (tableName, fn, recursive) { var exists = await knex.schema.hasTable(tableName) if (!exists) { await knex.schema.createTable(tableName, function (table) { fn(table) }) } else { var existColumns = await knex.from(tableName).columnInfo() var existIndexes = await (require('./index')(knex, tableName)) var schemaColumns = {} var schemaIndexes = {pk: [], uk: [], key: [], fk: []} await knex.schema.alterTable(tableName, function (table) { var prevColumnName var columnName var proxy = tabler() fn(proxy) var column = function (t, e, depth) { if (!e || !e[0]) return var method = e[1] var args = e[2] if (depth === 0) { columnName = e[2][0] schemaColumns[columnName] = true } // If exists primary key already. if ((method === 'increments' || method === 'bigIncrements') && existIndexes.pk.length > 0) { return t } if (method === 'index') { schemaIndexes.key.push(typeof (args[0]) === 'string' ? [args[0]] : args[0]) // If exists index already. if (existIndexes.isIndexExists(args[0], args[1])) { return t } } var isAppliable = true if (method === 'references') { schemaIndexes.fk.push([columnName, typeof (args[0]) === 'string' ? [args[0]] : args[0]]) // If exists foreign key already. if (existIndexes.isForeignKeyExists(columnName, args[0])) { isAppliable = false } } if (method === 'unique') { var keys = args[0] || columnName schemaIndexes.uk.push(typeof (keys) === 'string' ? [keys] : keys) // If exists unique index already. if (existIndexes.isUniqueExists(args[0] || columnName)) { isAppliable = false if (depth === 0) { return t } } } if (method === 'primary') { let keys = args[0] || columnName schemaIndexes.pk.push(typeof (keys) === 'string' ? [keys] : keys) // If exists primary key already. if (existIndexes.isPrimaryKeyExists(args[0] || columnName)) { isAppliable = false if (depth === 0) { return t } } } if (isAppliable) { let fn = t[method] t = fn.apply(t, args) } e[0].__appended__.forEach(function (e) { t = column(t, e, depth + 1) }) if (depth === 0) { if (['index', 'unique'].indexOf(method) === -1) { if (existColumns[columnName]) { t.alter() } else { if (prevColumnName) { t = t.after(prevColumnName) } else { t = t.first() } } } prevColumnName = columnName } return t } proxy.__appended__.forEach(function (e) { column(table, e, 0) }) // Drop unused columns. var dropColumns = [] Object.keys(existColumns).forEach(function (e) { if (!schemaColumns[e]) { Object.keys(existIndexes.fk).forEach(function (key) { if (helper.isArrayEqual([e], existIndexes.fk[key].key)) { table.dropForeign(undefined, key) } }) dropColumns.push(e) } }) if (dropColumns.length > 0) { table.dropColumns(dropColumns) } // Drop unused indexes. Object.keys(existIndexes.key).forEach(function (key) { var found = false schemaIndexes.key.forEach(function (sKey) { if (helper.isArrayEqual(existIndexes.key[key], sKey)) found = true }) schemaIndexes.fk.forEach(function (sKey) { sKey = typeof (sKey[0]) === 'string' ? [sKey[0]] : sKey[0] if (helper.isArrayEqual(existIndexes.key[key], sKey)) found = true }) if (!found) { table.dropIndex(undefined, key) } }) Object.keys(existIndexes.uk).forEach(function (key) { var found = false schemaIndexes.uk.forEach(function (sKey) { if (helper.isArrayEqual(existIndexes.uk[key], sKey)) found = true }) if (!found) { table.dropUnique(undefined, key) } }) }) } return tableName } var promises = [] opts.path = opts.cwd || process.cwd() const dummyMigrator = (a, b) => { return { call: async () => { const res = await migrator(a, b) return res } } } fs.readdirSync(opts.path).forEach(function (name) { if (name.slice(0, 6) !== 'table_') return require(opts.path + '/' + name).auto(dummyMigrator, knex).forEach(function (e) { promises.push([name, e]) }) }) var execute = function (i) { promises[i][1].call().then(function (res) { console.info('* Table `' + res + '` has been migrated.') if (i < promises.length - 1) { execute(i + 1) } else { resolve() } }).catch(function (err) { console.error('* Table `' + promises[i][0] + '` migration failed.') reject(err) }) } if (promises.length > 0) { execute(0) } else { console.info('* No schema exist.') } }) }
Support initial rows.
lib/automigrate.js
Support initial rows.
<ide><path>ib/automigrate.js <ide> }) <ide> } <ide> <del> var migrator = async function (tableName, fn, recursive) { <add> var migrator = async function (tableName, fn, initRows) { <ide> var exists = await knex.schema.hasTable(tableName) <ide> <ide> if (!exists) { <ide> }) <ide> } <ide> <add> if (typeof initRows === 'function') { <add> const existRows = (await knex.count('* AS cnt').from(tableName))[0].cnt <add> <add> if (!existRows) { <add> const rows = initRows(opts.config) <add> <add> if (rows && rows.length) { <add> await knex.batchInsert(tableName, rows); <add> } <add> } <add> } <add> <ide> return tableName <ide> } <ide> <ide> var promises = [] <ide> opts.path = opts.cwd || process.cwd() <ide> <del> const dummyMigrator = (a, b) => { <add> const dummyMigrator = (a, b, c) => { <ide> return { <ide> call: async () => { <del> const res = await migrator(a, b) <add> const res = await migrator(a, b, c) <ide> return res <ide> } <ide> }
Java
apache-2.0
f367d16890fe308c074a955844cb1968576c5c20
0
dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2015 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * 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.jkiss.dbeaver.registry.maven; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.runtime.RuntimeUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.xml.XMLException; import org.jkiss.utils.xml.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.IOException; import java.io.InputStream; import java.util.*; /** * Maven artifact version descriptor (POM). */ public class MavenArtifactVersion { static final Log log = Log.getLog(MavenArtifactVersion.class); public static final String PROP_PROJECT_VERSION = "project.version"; public static final String PROP_PROJECT_GROUP_ID = "project.groupId"; public static final String PROP_PROJECT_ARTIFACT_ID = "project.artifactId"; private MavenLocalVersion localVersion; private String name; private String version; private String description; private String url; private MavenLocalVersion parent; private Map<String, String> properties = new LinkedHashMap<>(); private List<MavenArtifactLicense> licenses = new ArrayList<>(); private List<MavenArtifactDependency> dependencies; private List<MavenArtifactDependency> dependencyManagement; private final GeneralUtils.IVariableResolver variableResolver = new GeneralUtils.IVariableResolver() { @Override public String get(String name) { String value = properties.get(name); if (value == null) { if (name.equals(PROP_PROJECT_VERSION)) { value = version; } else if (name.equals(PROP_PROJECT_GROUP_ID)) { value = localVersion.getArtifact().getGroupId(); } else if (name.equals(PROP_PROJECT_ARTIFACT_ID)) { value = localVersion.getArtifact().getArtifactId(); } else if (parent != null) { return parent.getMetaData().variableResolver.get(name); } } return value; } }; MavenArtifactVersion(DBRProgressMonitor monitor, MavenLocalVersion localVersion) throws IOException { this.localVersion = localVersion; loadPOM(monitor); } MavenArtifactVersion(MavenLocalVersion localVersion, String name, String version) { this.localVersion = localVersion; this.name = name; this.version = version; } public MavenLocalVersion getLocalVersion() { return localVersion; } public String getName() { return name; } public String getVersion() { return version; } public String getDescription() { return description; } public String getUrl() { return url; } public MavenLocalVersion getParent() { return parent; } void setParent(MavenLocalVersion parent) { this.parent = parent; } void addDependency(MavenArtifactDependency dependency) { if (dependencies == null) { dependencies = new ArrayList<>(); } dependencies.add(dependency); } public Map<String, String> getProperties() { return properties; } public List<MavenArtifactLicense> getLicenses() { return licenses; } public List<MavenArtifactDependency> getDependencies(DBRProgressMonitor monitor) { if (parent != null) { List<MavenArtifactDependency> parentDependencies = parent.getMetaData(monitor).getDependencies(monitor); if (!CommonUtils.isEmpty(parentDependencies)) { if (CommonUtils.isEmpty(dependencies)) { return parentDependencies; } List<MavenArtifactDependency> result = new ArrayList<>(dependencies.size() + parentDependencies.size()); result.addAll(dependencies); result.addAll(parentDependencies); return result; } } return this.dependencies; } public void removeDependency(MavenArtifactDependency dependency) { if (this.dependencies != null) { this.dependencies.remove(dependency); } } List<MavenArtifactDependency> getDependencies() { return dependencies; } @Override public String toString() { return localVersion.toString(); } private void loadPOM(DBRProgressMonitor monitor) throws IOException { String pomURL = localVersion.getArtifact().getFileURL(localVersion.getVersion(), MavenArtifact.FILE_POM); monitor.subTask("Load POM " + localVersion); Document pomDocument; try (InputStream mdStream = RuntimeUtils.openConnectionStream(pomURL)) { pomDocument = XMLUtils.parseDocument(mdStream); } catch (XMLException e) { throw new IOException("Error parsing POM", e); } Element root = pomDocument.getDocumentElement(); name = XMLUtils.getChildElementBody(root, "name"); url = XMLUtils.getChildElementBody(root, "url"); version = XMLUtils.getChildElementBody(root, "version"); description = XMLUtils.getChildElementBody(root, "description"); { // Parent Element parentElement = XMLUtils.getChildElement(root, "parent"); if (parentElement != null) { String parentGroupId = XMLUtils.getChildElementBody(parentElement, "groupId"); String parentArtifactId = XMLUtils.getChildElementBody(parentElement, "artifactId"); String parentVersion = XMLUtils.getChildElementBody(parentElement, "version"); if (parentGroupId == null || parentArtifactId == null || parentVersion == null) { log.error("Broken parent reference: " + parentGroupId + ":" + parentArtifactId + ":" + parentVersion); } else { MavenArtifactReference parentReference = new MavenArtifactReference( parentGroupId, parentArtifactId, parentVersion ); if (this.version == null) { this.version = parentReference.getVersion(); } MavenArtifact parentArtifact = MavenRegistry.getInstance().findArtifact(parentReference); if (parentArtifact == null) { log.error("Artifact [" + this + "] parent [" + parentReference + "] not found"); } else { parent = parentArtifact.resolveVersion(monitor, parentReference.getVersion(), false); } } } } { // Properties Element propsElement = XMLUtils.getChildElement(root, "properties"); if (propsElement != null) { for (Element prop : XMLUtils.getChildElementList(propsElement)) { properties.put(prop.getTagName(), XMLUtils.getElementBody(prop)); } } } { // Licenses Element licensesElement = XMLUtils.getChildElement(root, "licenses"); if (licensesElement != null) { for (Element prop : XMLUtils.getChildElementList(licensesElement, "license")) { licenses.add(new MavenArtifactLicense( XMLUtils.getChildElementBody(prop, "name"), XMLUtils.getChildElementBody(prop, "url") )); } } } { // Dependencies Element dmElement = XMLUtils.getChildElement(root, "dependencyManagement"); if (dmElement != null) { dependencyManagement = parseDependencies(monitor, dmElement, true); } dependencies = parseDependencies(monitor, root, false); } monitor.worked(1); } private List<MavenArtifactDependency> parseDependencies(DBRProgressMonitor monitor, Element element, boolean depManagement) { List<MavenArtifactDependency> result = new ArrayList<>(); Element dependenciesElement = XMLUtils.getChildElement(element, "dependencies"); if (dependenciesElement != null) { for (Element dep : XMLUtils.getChildElementList(dependenciesElement, "dependency")) { String groupId = evaluateString(XMLUtils.getChildElementBody(dep, "groupId")); String artifactId = evaluateString(XMLUtils.getChildElementBody(dep, "artifactId")); if (groupId == null || artifactId == null) { log.warn("Broken dependency reference: " + groupId + ":" + artifactId); continue; } MavenArtifactDependency.Scope scope = MavenArtifactDependency.Scope.COMPILE; String scopeName = XMLUtils.getChildElementBody(dep, "scope"); if (!CommonUtils.isEmpty(scopeName)) { scope = MavenArtifactDependency.Scope.valueOf(scopeName.toUpperCase(Locale.ENGLISH)); } boolean optional = CommonUtils.getBoolean(XMLUtils.getChildElementBody(dep, "optional"), false); // TODO: maybe we should include some of them if (depManagement || (!optional && includesScope(scope))) { String version = evaluateString(XMLUtils.getChildElementBody(dep, "version")); if (version == null) { version = findDependencyVersion(monitor, groupId, artifactId); } if (version == null) { log.error("Can't resolve artifact [" + groupId + ":" + artifactId + "] version. Skip."); continue; } MavenArtifactDependency dependency = new MavenArtifactDependency( evaluateString(groupId), evaluateString(artifactId), evaluateString(version), scope, optional ); result.add(dependency); if (!depManagement) { // Exclusions Element exclusionsElement = XMLUtils.getChildElement(dep, "exclusions"); if (exclusionsElement != null) { for (Element exclusion : XMLUtils.getChildElementList(exclusionsElement, "exclusion")) { dependency.addExclusion( new MavenArtifactReference( CommonUtils.notEmpty(XMLUtils.getChildElementBody(exclusion, "groupId")), CommonUtils.notEmpty(XMLUtils.getChildElementBody(exclusion, "artifactId")), "")); } } } } } } return result; } private boolean includesScope(MavenArtifactDependency.Scope scope) { return scope == MavenArtifactDependency.Scope.COMPILE || scope == MavenArtifactDependency.Scope.RUNTIME/* || scope == MavenArtifactDependency.Scope.PROVIDED*/; } private String findDependencyVersion(DBRProgressMonitor monitor, String groupId, String artifactId) { if (dependencyManagement != null) { for (MavenArtifactDependency dmArtifact : dependencyManagement) { if (dmArtifact.getGroupId().equals(groupId) && dmArtifact.getArtifactId().equals(artifactId)) { return dmArtifact.getVersion(); } } } return parent == null ? null : parent.getMetaData(monitor).findDependencyVersion(monitor, groupId, artifactId); } private String evaluateString(String value) { if (value == null) { return null; } return GeneralUtils.replaceVariables(value, variableResolver); } }
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/registry/maven/MavenArtifactVersion.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2015 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * 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.jkiss.dbeaver.registry.maven; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.runtime.RuntimeUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.xml.XMLException; import org.jkiss.utils.xml.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.IOException; import java.io.InputStream; import java.util.*; /** * Maven artifact version descriptor (POM). */ public class MavenArtifactVersion { static final Log log = Log.getLog(MavenArtifactVersion.class); public static final String PROP_PROJECT_VERSION = "project.version"; public static final String PROP_PROJECT_GROUP_ID = "project.groupId"; public static final String PROP_PROJECT_ARTIFACT_ID = "project.artifactId"; private MavenLocalVersion localVersion; private String name; private String version; private String description; private String url; private MavenLocalVersion parent; private Map<String, String> properties = new LinkedHashMap<>(); private List<MavenArtifactLicense> licenses = new ArrayList<>(); private List<MavenArtifactDependency> dependencies; private List<MavenArtifactDependency> dependencyManagement; private final GeneralUtils.IVariableResolver variableResolver = new GeneralUtils.IVariableResolver() { @Override public String get(String name) { String value = properties.get(name); if (value == null) { if (name.equals(PROP_PROJECT_VERSION)) { value = version; } else if (name.equals(PROP_PROJECT_GROUP_ID)) { value = localVersion.getArtifact().getGroupId(); } else if (name.equals(PROP_PROJECT_ARTIFACT_ID)) { value = localVersion.getArtifact().getArtifactId(); } else if (parent != null) { return parent.getMetaData().variableResolver.get(name); } } return value; } }; MavenArtifactVersion(DBRProgressMonitor monitor, MavenLocalVersion localVersion) throws IOException { this.localVersion = localVersion; loadPOM(monitor); } MavenArtifactVersion(MavenLocalVersion localVersion, String name, String version) { this.localVersion = localVersion; this.name = name; this.version = version; } public MavenLocalVersion getLocalVersion() { return localVersion; } public String getName() { return name; } public String getVersion() { return version; } public String getDescription() { return description; } public String getUrl() { return url; } public MavenLocalVersion getParent() { return parent; } void setParent(MavenLocalVersion parent) { this.parent = parent; } void addDependency(MavenArtifactDependency dependency) { if (dependencies == null) { dependencies = new ArrayList<>(); } dependencies.add(dependency); } public Map<String, String> getProperties() { return properties; } public List<MavenArtifactLicense> getLicenses() { return licenses; } public List<MavenArtifactDependency> getDependencies(DBRProgressMonitor monitor) { if (parent != null) { List<MavenArtifactDependency> parentDependencies = parent.getMetaData(monitor).getDependencies(monitor); if (!CommonUtils.isEmpty(parentDependencies)) { if (CommonUtils.isEmpty(dependencies)) { return parentDependencies; } List<MavenArtifactDependency> result = new ArrayList<>(dependencies.size() + parentDependencies.size()); result.addAll(dependencies); result.addAll(parentDependencies); return result; } } return this.dependencies; } public void removeDependency(MavenArtifactDependency dependency) { if (this.dependencies != null) { this.dependencies.remove(dependency); } } List<MavenArtifactDependency> getDependencies() { return dependencies; } @Override public String toString() { return localVersion.toString(); } private void loadPOM(DBRProgressMonitor monitor) throws IOException { String pomURL = localVersion.getArtifact().getFileURL(localVersion.getVersion(), MavenArtifact.FILE_POM); monitor.subTask("Load POM " + localVersion); Document pomDocument; try (InputStream mdStream = RuntimeUtils.openConnectionStream(pomURL)) { pomDocument = XMLUtils.parseDocument(mdStream); } catch (XMLException e) { throw new IOException("Error parsing POM", e); } Element root = pomDocument.getDocumentElement(); name = XMLUtils.getChildElementBody(root, "name"); url = XMLUtils.getChildElementBody(root, "url"); version = XMLUtils.getChildElementBody(root, "version"); description = XMLUtils.getChildElementBody(root, "description"); { // Parent Element parentElement = XMLUtils.getChildElement(root, "parent"); if (parentElement != null) { String parentGroupId = XMLUtils.getChildElementBody(parentElement, "groupId"); String parentArtifactId = XMLUtils.getChildElementBody(parentElement, "artifactId"); String parentVersion = XMLUtils.getChildElementBody(parentElement, "version"); if (parentGroupId == null || parentArtifactId == null || parentVersion == null) { log.error("Broken parent reference: " + parentGroupId + ":" + parentArtifactId + ":" + parentVersion); } else { MavenArtifactReference parentReference = new MavenArtifactReference( parentGroupId, parentArtifactId, parentVersion ); if (this.version == null) { this.version = parentReference.getVersion(); } MavenArtifact parentArtifact = MavenRegistry.getInstance().findArtifact(parentReference); if (parentArtifact == null) { log.error("Artifact [" + this + "] parent [" + parentReference + "] not found"); } else { parent = parentArtifact.resolveVersion(monitor, parentReference.getVersion(), false); } } } } { // Properties Element propsElement = XMLUtils.getChildElement(root, "properties"); if (propsElement != null) { for (Element prop : XMLUtils.getChildElementList(propsElement)) { properties.put(prop.getTagName(), XMLUtils.getElementBody(prop)); } } } { // Licenses Element licensesElement = XMLUtils.getChildElement(root, "licenses"); if (licensesElement != null) { for (Element prop : XMLUtils.getChildElementList(licensesElement, "license")) { licenses.add(new MavenArtifactLicense( XMLUtils.getChildElementBody(prop, "name"), XMLUtils.getChildElementBody(prop, "url") )); } } } { // Dependencies Element dmElement = XMLUtils.getChildElement(root, "dependencyManagement"); if (dmElement != null) { dependencyManagement = parseDependencies(monitor, dmElement, true); } dependencies = parseDependencies(monitor, root, false); } monitor.worked(1); } private List<MavenArtifactDependency> parseDependencies(DBRProgressMonitor monitor, Element element, boolean depManagement) { List<MavenArtifactDependency> result = new ArrayList<>(); Element dependenciesElement = XMLUtils.getChildElement(element, "dependencies"); if (dependenciesElement != null) { for (Element dep : XMLUtils.getChildElementList(dependenciesElement, "dependency")) { String groupId = evaluateString(XMLUtils.getChildElementBody(dep, "groupId")); String artifactId = evaluateString(XMLUtils.getChildElementBody(dep, "artifactId")); if (groupId == null || artifactId == null) { log.warn("Broken dependency reference: " + groupId + ":" + artifactId); continue; } String version = evaluateString(XMLUtils.getChildElementBody(dep, "version")); if (version == null) { version = findDependencyVersion(monitor, groupId, artifactId); } if (version == null) { log.error("Can't resolve artifact [" + groupId + ":" + artifactId + "] version. Skip."); continue; } MavenArtifactDependency.Scope scope = MavenArtifactDependency.Scope.COMPILE; String scopeName = XMLUtils.getChildElementBody(dep, "scope"); if (!CommonUtils.isEmpty(scopeName)) { scope = MavenArtifactDependency.Scope.valueOf(scopeName.toUpperCase(Locale.ENGLISH)); } boolean optional = CommonUtils.getBoolean(XMLUtils.getChildElementBody(dep, "optional"), false); // TODO: maybe we should include some of them if (depManagement || (!optional && includesScope(scope))) { MavenArtifactDependency dependency = new MavenArtifactDependency( evaluateString(groupId), evaluateString(artifactId), evaluateString(version), scope, optional ); result.add(dependency); if (!depManagement) { // Exclusions Element exclusionsElement = XMLUtils.getChildElement(dep, "exclusions"); if (exclusionsElement != null) { for (Element exclusion : XMLUtils.getChildElementList(exclusionsElement, "exclusion")) { dependency.addExclusion( new MavenArtifactReference( CommonUtils.notEmpty(XMLUtils.getChildElementBody(exclusion, "groupId")), CommonUtils.notEmpty(XMLUtils.getChildElementBody(exclusion, "artifactId")), "")); } } } } } } return result; } private boolean includesScope(MavenArtifactDependency.Scope scope) { return scope == MavenArtifactDependency.Scope.COMPILE || scope == MavenArtifactDependency.Scope.RUNTIME/* || scope == MavenArtifactDependency.Scope.PROVIDED*/; } private String findDependencyVersion(DBRProgressMonitor monitor, String groupId, String artifactId) { if (dependencyManagement != null) { for (MavenArtifactDependency dmArtifact : dependencyManagement) { if (dmArtifact.getGroupId().equals(groupId) && dmArtifact.getArtifactId().equals(artifactId)) { return dmArtifact.getVersion(); } } } return parent == null ? null : parent.getMetaData(monitor).findDependencyVersion(monitor, groupId, artifactId); } private String evaluateString(String value) { if (value == null) { return null; } return GeneralUtils.replaceVariables(value, variableResolver); } }
Resolve fix Former-commit-id: 49c890ac0ea9793d9d02e29f7c47ca75af4607c8
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/registry/maven/MavenArtifactVersion.java
Resolve fix
<ide><path>lugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/registry/maven/MavenArtifactVersion.java <ide> log.warn("Broken dependency reference: " + groupId + ":" + artifactId); <ide> continue; <ide> } <del> String version = evaluateString(XMLUtils.getChildElementBody(dep, "version")); <del> if (version == null) { <del> version = findDependencyVersion(monitor, groupId, artifactId); <del> } <del> if (version == null) { <del> log.error("Can't resolve artifact [" + groupId + ":" + artifactId + "] version. Skip."); <del> continue; <del> } <ide> MavenArtifactDependency.Scope scope = MavenArtifactDependency.Scope.COMPILE; <ide> String scopeName = XMLUtils.getChildElementBody(dep, "scope"); <ide> if (!CommonUtils.isEmpty(scopeName)) { <ide> <ide> // TODO: maybe we should include some of them <ide> if (depManagement || (!optional && includesScope(scope))) { <add> String version = evaluateString(XMLUtils.getChildElementBody(dep, "version")); <add> if (version == null) { <add> version = findDependencyVersion(monitor, groupId, artifactId); <add> } <add> if (version == null) { <add> log.error("Can't resolve artifact [" + groupId + ":" + artifactId + "] version. Skip."); <add> continue; <add> } <add> <ide> MavenArtifactDependency dependency = new MavenArtifactDependency( <ide> evaluateString(groupId), <ide> evaluateString(artifactId),
Java
epl-1.0
b17034333da22030b1796106f68ae80db91ee6ec
0
markoer/kura,ctron/kura,ymai/kura,darionct/kura,ctron/kura,MMaiero/kura,gavinying/kura,cdealti/kura,nicolatimeus/kura,MMaiero/kura,rohitdubey12/kura,gavinying/kura,ctron/kura,ymai/kura,markoer/kura,ctron/kura,darionct/kura,MMaiero/kura,ctron/kura,amitjoy/kura,amitjoy/kura,rohitdubey12/kura,nicolatimeus/kura,markoer/kura,rohitdubey12/kura,cdealti/kura,darionct/kura,MMaiero/kura,nicolatimeus/kura,markoer/kura,amitjoy/kura,cdealti/kura,gavinying/kura,darionct/kura,ymai/kura,MMaiero/kura,cdealti/kura,amitjoy/kura,markoer/kura,ctron/kura,amitjoy/kura,ymai/kura,MMaiero/kura,rohitdubey12/kura,gavinying/kura,gavinying/kura,rohitdubey12/kura,markoer/kura,nicolatimeus/kura,darionct/kura,nicolatimeus/kura,cdealti/kura,ymai/kura,cdealti/kura,nicolatimeus/kura,gavinying/kura,darionct/kura,amitjoy/kura,ymai/kura
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech * Red Hat Inc *******************************************************************************/ package org.eclipse.kura.core.util; import java.util.Arrays; /** * Utilities to quickly sort an array of values * @deprecated Use sort methods from {@link Arrays} instead */ @Deprecated public final class QuickSort { private QuickSort() { } /** * @deprecated Use {@link Arrays#sort(int[])} instead */ @Deprecated public static void sort(int[] array) { Arrays.sort(array); } /** * @deprecated Use {@link Arrays#sort(long[])} instead */ @Deprecated public static void sort(long[] array) { Arrays.sort(array); } }
kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/util/QuickSort.java
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.core.util; /** * Utilities to quickly sort an array of values */ public class QuickSort { public static void sort(int[] array) { if (array.length > 0) { sort(array, 0, array.length - 1); } } public static void sort(long[] array) { if (array.length > 0) { sort(array, 0, array.length - 1); } } private static void sort(int[] array, int lo, int hi) { int i = lo, j = hi, h; int x = array[(lo + hi) / 2]; // partition do { while (array[i] < x) { i++; } while (array[j] > x) { j--; } if (i <= j) { h = array[i]; array[i] = array[j]; array[j] = h; i++; j--; } } while (i <= j); // recursion if (lo < j) { sort(array, lo, j); } if (i < hi) { sort(array, i, hi); } } private static void sort(long[] array, int lo, int hi) { int i = lo, j = hi; long h; long x = array[(lo + hi) / 2]; // partition do { while (array[i] < x) { i++; } while (array[j] > x) { j--; } if (i <= j) { h = array[i]; array[i] = array[j]; array[j] = h; i++; j--; } } while (i <= j); // recursion if (lo < j) { sort(array, lo, j); } if (i < hi) { sort(array, i, hi); } } /* * public static void sort(int[] array) { * quicksort(array, 0, array.length - 1); * } * * private static void quicksort(int[] array, int left, int right) { * if (right <= left) return; * int i = partition(array, left, right); * quicksort(array, left, i-1); * quicksort(array, i+1, right); * } * * private static int partition(int[] array, int left, int right) { * int i = left, j = right; * int tmp; * int pivot = array[(left + right) / 2]; * * while (i <= j) { * while (array[i] < pivot) { * i++; * } * * while (array[j] > pivot) { * j--; * } * * if (i <= j) { * tmp = array[i]; * array[i] = array[j]; * array[j] = tmp; * i++; * j--; * } * } * * return i; * } * * public static void sort(long[] array) { * quicksort(array, 0, array.length - 1); * } * * private static void quicksort(long[] array, int left, int right) { * if (right <= left) return; * int i = partition(array, left, right); * quicksort(array, left, i-1); * quicksort(array, i+1, right); * } * * private static int partition(long[] array, int left, int right) { * int i = left, j = right; * long tmp; * long pivot = array[(left + right) / 2]; * * while (i <= j) { * while (array[i] < pivot) { * i++; * } * * while (array[j] > pivot) { * j--; * } * * if (i <= j) { * tmp = array[i]; * array[i] = array[j]; * array[j] = tmp; * i++; * j--; * } * } * * return i; * } */ }
Clean up and deprecate QuickSort * Forward all calls to plain Java methods * Deprecate class and methods, comment * Prevent subclassing Signed-off-by: Jens Reimann <[email protected]>
kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/util/QuickSort.java
Clean up and deprecate QuickSort
<ide><path>ura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/util/QuickSort.java <ide> /******************************************************************************* <del> * Copyright (c) 2011, 2016 Eurotech and/or its affiliates <add> * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others <ide> * <ide> * All rights reserved. This program and the accompanying materials <ide> * are made available under the terms of the Eclipse Public License v1.0 <ide> * <ide> * Contributors: <ide> * Eurotech <add> * Red Hat Inc <ide> *******************************************************************************/ <ide> package org.eclipse.kura.core.util; <ide> <add>import java.util.Arrays; <add> <ide> /** <ide> * Utilities to quickly sort an array of values <add> * @deprecated Use sort methods from {@link Arrays} instead <ide> */ <del>public class QuickSort { <add>@Deprecated <add>public final class QuickSort { <ide> <del> public static void sort(int[] array) { <del> if (array.length > 0) { <del> sort(array, 0, array.length - 1); <del> } <add> private QuickSort() { <ide> } <ide> <del> public static void sort(long[] array) { <del> if (array.length > 0) { <del> sort(array, 0, array.length - 1); <del> } <add> /** <add> * @deprecated Use {@link Arrays#sort(int[])} instead <add> */ <add> @Deprecated <add> public static void sort(int[] array) { <add> Arrays.sort(array); <ide> } <ide> <del> private static void sort(int[] array, int lo, int hi) { <del> int i = lo, j = hi, h; <del> int x = array[(lo + hi) / 2]; <del> <del> // partition <del> do { <del> while (array[i] < x) { <del> i++; <del> } <del> while (array[j] > x) { <del> j--; <del> } <del> if (i <= j) { <del> h = array[i]; <del> array[i] = array[j]; <del> array[j] = h; <del> i++; <del> j--; <del> } <del> } while (i <= j); <del> <del> // recursion <del> if (lo < j) { <del> sort(array, lo, j); <del> } <del> if (i < hi) { <del> sort(array, i, hi); <del> } <add> /** <add> * @deprecated Use {@link Arrays#sort(long[])} instead <add> */ <add> @Deprecated <add> public static void sort(long[] array) { <add> Arrays.sort(array); <ide> } <del> <del> private static void sort(long[] array, int lo, int hi) { <del> int i = lo, j = hi; <del> long h; <del> long x = array[(lo + hi) / 2]; <del> <del> // partition <del> do { <del> while (array[i] < x) { <del> i++; <del> } <del> while (array[j] > x) { <del> j--; <del> } <del> if (i <= j) { <del> h = array[i]; <del> array[i] = array[j]; <del> array[j] = h; <del> i++; <del> j--; <del> } <del> } while (i <= j); <del> <del> // recursion <del> if (lo < j) { <del> sort(array, lo, j); <del> } <del> if (i < hi) { <del> sort(array, i, hi); <del> } <del> } <del> <del> /* <del> * public static void sort(int[] array) { <del> * quicksort(array, 0, array.length - 1); <del> * } <del> * <del> * private static void quicksort(int[] array, int left, int right) { <del> * if (right <= left) return; <del> * int i = partition(array, left, right); <del> * quicksort(array, left, i-1); <del> * quicksort(array, i+1, right); <del> * } <del> * <del> * private static int partition(int[] array, int left, int right) { <del> * int i = left, j = right; <del> * int tmp; <del> * int pivot = array[(left + right) / 2]; <del> * <del> * while (i <= j) { <del> * while (array[i] < pivot) { <del> * i++; <del> * } <del> * <del> * while (array[j] > pivot) { <del> * j--; <del> * } <del> * <del> * if (i <= j) { <del> * tmp = array[i]; <del> * array[i] = array[j]; <del> * array[j] = tmp; <del> * i++; <del> * j--; <del> * } <del> * } <del> * <del> * return i; <del> * } <del> * <del> * public static void sort(long[] array) { <del> * quicksort(array, 0, array.length - 1); <del> * } <del> * <del> * private static void quicksort(long[] array, int left, int right) { <del> * if (right <= left) return; <del> * int i = partition(array, left, right); <del> * quicksort(array, left, i-1); <del> * quicksort(array, i+1, right); <del> * } <del> * <del> * private static int partition(long[] array, int left, int right) { <del> * int i = left, j = right; <del> * long tmp; <del> * long pivot = array[(left + right) / 2]; <del> * <del> * while (i <= j) { <del> * while (array[i] < pivot) { <del> * i++; <del> * } <del> * <del> * while (array[j] > pivot) { <del> * j--; <del> * } <del> * <del> * if (i <= j) { <del> * tmp = array[i]; <del> * array[i] = array[j]; <del> * array[j] = tmp; <del> * i++; <del> * j--; <del> * } <del> * } <del> * <del> * return i; <del> * } <del> */ <ide> }
Java
apache-2.0
4097c7e0d1be1c383466ca70c5ec61ca86fa7ce6
0
vauvenal5/pieShare,vauvenal5/pieShare
/* * 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 org.pieShare.pieTools.pieUtilities.service.security; import javax.crypto.Cipher; /** * * @author Svetoslav */ public interface IProviderService { String getProviderName(); String getFileHashAlorithm(); Cipher getPasswordEncryptioCipher(); Cipher getEnDeCryptCipher(); }
pieUtilities/src/main/java/org/pieShare/pieTools/pieUtilities/service/security/IProviderService.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 org.pieShare.pieTools.pieUtilities.service.security; /** * * @author Svetoslav */ public interface IProviderService { String getProviderName(); String getFileHashAlorithm(); String getPasswordEncryptionAlgorithm(); String getEnDeCryptAlgorithm(); }
provider returns Cipher now
pieUtilities/src/main/java/org/pieShare/pieTools/pieUtilities/service/security/IProviderService.java
provider returns Cipher now
<ide><path>ieUtilities/src/main/java/org/pieShare/pieTools/pieUtilities/service/security/IProviderService.java <ide> * and open the template in the editor. <ide> */ <ide> package org.pieShare.pieTools.pieUtilities.service.security; <add> <add>import javax.crypto.Cipher; <ide> <ide> /** <ide> * <ide> <ide> String getFileHashAlorithm(); <ide> <del> String getPasswordEncryptionAlgorithm(); <add> Cipher getPasswordEncryptioCipher(); <ide> <del> String getEnDeCryptAlgorithm(); <add> Cipher getEnDeCryptCipher(); <ide> }
JavaScript
mit
fb5e00686fa051740ba1a77b17d00f0cd9581e0a
0
coe-google-apps-support/Mailman,coe-google-apps-support/Mailman,coe-google-apps-support/Mailman
// TODO Performance improvements in here could be very important. var EmailService = { startMergeTemplate: function(template) { try { MergeTemplateService.validate(template); EmailService.validate(template.mergeData.data); } catch(e) { log(e); throw e; } log('Starting merge template ' + template.id); var ss = Utility.getSpreadsheet(); var sheet = ss.getSheetByName(template.mergeData.sheet); var range = sheet.getDataRange(); var header = HeaderService.get(template.mergeData.sheet, template.mergeData.headerRow); var sendHelper; if (template.mergeData.conditional == null) { sendHelper = EmailService.sendHelper; } else { sendHelper = EmailService.conditionalSendHelper; } for (var i = parseInt(template.mergeData.headerRow); i < range.getNumRows(); i++) { var row = range.offset(i, 0, 1, range.getNumColumns()); try { // We only timestamp when the email successfully sends. if (sendHelper(header, row.getDisplayValues()[0], template)) { var timestampName = template.mergeData.timestampColumn.replace(/(<<|>>)/g, ''); var timeCell = row.getCell(1, header.indexOf(timestampName) + 1); var currentDate = new Date(); var datetime = (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes() + ':' + currentDate.getSeconds(); timeCell.setValue(datetime); } } catch (e) { log(e); } } log('Ending merge template...'); }, /** * Sends a test email to the current user. * * @param {string} sheetName The name of the Sheet to send from. * @param {string} headerRow The 1-based row the header is in. * @param {string} subject The whack-whacked subject. * @param {string} body The whack whacked body. */ sendTest: function(sheetName, headerRow, subject, body) { log('Sending test email'); var ss = Utility.getSpreadsheet(); var sheet = ss.getSheetByName(sheetName); var range = sheet.getDataRange(); var header = HeaderService.get(sheetName, headerRow); var row = range.offset(parseInt(headerRow), 0, 1, range.getNumColumns()).getDisplayValues()[0]; var combinedObj = {}; for (var j = 0; j < header.length; j++) { combinedObj[header[j]] = row[j]; } // Convert <<>> tags to actual text. var subject = EmailService.replaceTags(subject, combinedObj); var body = EmailService.replaceTags(body, combinedObj); EmailService.send(Session.getActiveUser().getEmail(), subject, body); }, send: function(to, subject, body, cc, bcc) { if (to === '' || to == null) { return; } var htmlEmail = HtmlService.createTemplateFromFile('email-template'); htmlEmail.id = Utility.getSpreadsheet().getId(); htmlEmail.bodyArray = body.split('\n'); log('Sending email to ' + JSON.stringify({ to: to, cc: cc, bcc: bcc })); GmailApp.sendEmail(to, subject, body, { htmlBody: htmlEmail.evaluate().getContent(), cc: cc, bcc: bcc }); }, /** * Validates the supplied MergeData.data. This can be found in MergeTemplate.mergeData.data. This is specifically * for mail merge. * Note, this throws errors if the data is invalid. * * @param {Object} data The data payload containing to, subject and body. */ validate: function(data) { if (data == null) { throw new Error('MergeTemplate.mergeData.data is null'); } if (data.to == null) { throw new Error('MergeTemplate.mergeData.data.to is null'); } if (data.subject == null) { throw new Error('MergeTemplate.mergeData.data.subject is null'); } if (data.body == null) { throw new Error('MergeTemplate.mergeData.data.body is null'); } }, /******* Private / utility functions *******/ /** * Sends an email based upon a MergeTemplate. Whack whacks are swapped out. * Handles to, subject and body fields. * * @param {String[]} headerRow An array of header values. * @param {String[]} row An array of row values. * @param {Object} template The MergeTemplate used to send the email. See the client-side object for info. * @return {Boolean} true if the email was sent, false otherwise. */ sendHelper: function(headerRow, row, template) { var combinedObj = {}; for (var j = 0; j < headerRow.length; j++) { combinedObj[headerRow[j]] = row[j]; } // Convert <<>> tags to actual text. var to = EmailService.replaceTags(template.mergeData.data.to, combinedObj); var subject = EmailService.replaceTags(template.mergeData.data.subject, combinedObj); var body = EmailService.replaceTags(template.mergeData.data.body, combinedObj); var cc; var bcc; if (template.mergeData.data.cc != null) { cc = EmailService.replaceTags(template.mergeData.data.cc, combinedObj);; } if (template.mergeData.data.bcc != null) { bcc = EmailService.replaceTags(template.mergeData.data.bcc, combinedObj);; } EmailService.send(to, subject, body, cc, bcc); return true; }, /** * Sends an email based upon a MergeTemplate. Tags are swapped out. * Handles to, subject, body, conditional and timestampColumn fields. * * @param {String[]} headerRow An array of header values. * @param {String[]} row An array of row values. * @param {Object} template The MergeTemplate used to send the email. See the client-side Object for info. * @return {Boolean} true if the email was sent, false otherwise. */ conditionalSendHelper: function(headerRow, row, template) { var combinedObj = {}; for (var j = 0; j < headerRow.length; j++) { combinedObj[headerRow[j]] = row[j]; } // Convert <<>> tags to actual text. var to = EmailService.replaceTags(template.mergeData.data.to, combinedObj); var subject = EmailService.replaceTags(template.mergeData.data.subject, combinedObj); var body = EmailService.replaceTags(template.mergeData.data.body, combinedObj); var sendColumn = EmailService.replaceTags(template.mergeData.conditional, combinedObj); var cc; var bcc; if (template.mergeData.data.cc != null) { cc = EmailService.replaceTags(template.mergeData.data.cc, combinedObj);; } if (template.mergeData.data.bcc != null) { bcc = EmailService.replaceTags(template.mergeData.data.bcc, combinedObj);; } if (sendColumn.toLowerCase() == 'true') { EmailService.send(to, subject, body, cc, bcc); return true; } return false; }, /** * This function replaces all instances of <<tags>> with the data in headerToData. * * @param {string} text The string that contains the tags. * @param {Object} headerToData A key-value pair where the key is a column name and the value is the data in the * column. * @return {string} The text with all tags replaced with data. */ replaceTags: function(text, headerToData) { var dataText = text.replace(/<<.*?>>/g, function(match, offset, string) { var columnName = match.slice(2, match.length - 2); return headerToData[columnName]; }); return dataText; } };
src/GAS/services/email-service.js
// TODO Performance improvements in here could be very important. var EmailService = { startMergeTemplate: function(template) { try { MergeTemplateService.validate(template); EmailService.validate(template.mergeData.data); } catch(e) { log(e); throw e; } log('Starting merge template ' + template.id); var ss = Utility.getSpreadsheet(); var sheet = ss.getSheetByName(template.mergeData.sheet); var range = sheet.getDataRange(); var header = HeaderService.get(template.mergeData.sheet, template.mergeData.headerRow); var sendHelper; if (template.mergeData.conditional == null) { sendHelper = EmailService.sendHelper; } else { sendHelper = EmailService.conditionalSendHelper; } for (var i = parseInt(template.mergeData.headerRow); i < range.getNumRows(); i++) { var row = range.offset(i, 0, 1, range.getNumColumns()); try { // We only timestamp when the email successfully sends. if (sendHelper(header, row.getDisplayValues()[0], template)) { var timestampName = template.mergeData.timestampColumn.replace(/(<<|>>)/g, ''); var timeCell = row.getCell(1, header.indexOf(timestampName) + 1); var currentDate = new Date(); var datetime = (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes() + ':' + currentDate.getSeconds(); timeCell.setValue(datetime); } } catch (e) { log(e); } } log('Ending merge template...'); }, /** * Sends a test email to the current user. * * @param {string} sheetName The name of the Sheet to send from. * @param {string} headerRow The 1-based row the header is in. * @param {string} subject The whack-whacked subject. * @param {string} body The whack whacked body. */ sendTest: function(sheetName, headerRow, subject, body) { log('Sending test email'); var ss = Utility.getSpreadsheet(); var sheet = ss.getSheetByName(sheetName); var range = sheet.getDataRange(); var header = HeaderService.get(sheetName, headerRow); var row = range.offset(parseInt(headerRow), 0, 1, range.getNumColumns()).getDisplayValues()[0]; var combinedObj = {}; for (var j = 0; j < header.length; j++) { combinedObj[header[j]] = row[j]; } // Convert <<>> tags to actual text. var subject = EmailService.replaceTags(subject, combinedObj); var body = EmailService.replaceTags(body, combinedObj); EmailService.send(Session.getActiveUser().getEmail(), subject, body); }, send: function(to, subject, body, cc, bcc) { var htmlEmail = HtmlService.createTemplateFromFile('email-template'); htmlEmail.id = Utility.getSpreadsheet().getId(); htmlEmail.bodyArray = body.split('\n'); log('Sending email to ' + JSON.stringify({ to: to, cc: cc, bcc: bcc })); GmailApp.sendEmail(to, subject, body, { htmlBody: htmlEmail.evaluate().getContent(), cc: cc, bcc: bcc }); }, /** * Validates the supplied MergeData.data. This can be found in MergeTemplate.mergeData.data. This is specifically * for mail merge. * Note, this throws errors if the data is invalid. * * @param {Object} data The data payload containing to, subject and body. */ validate: function(data) { if (data == null) { throw new Error('MergeTemplate.mergeData.data is null'); } if (data.to == null) { throw new Error('MergeTemplate.mergeData.data.to is null'); } if (data.subject == null) { throw new Error('MergeTemplate.mergeData.data.subject is null'); } if (data.body == null) { throw new Error('MergeTemplate.mergeData.data.body is null'); } }, /******* Private / utility functions *******/ /** * Sends an email based upon a MergeTemplate. Whack whacks are swapped out. * Handles to, subject and body fields. * * @param {String[]} headerRow An array of header values. * @param {String[]} row An array of row values. * @param {Object} template The MergeTemplate used to send the email. See the client-side object for info. * @return {Boolean} true if the email was sent, false otherwise. */ sendHelper: function(headerRow, row, template) { var combinedObj = {}; for (var j = 0; j < headerRow.length; j++) { combinedObj[headerRow[j]] = row[j]; } // Convert <<>> tags to actual text. var to = EmailService.replaceTags(template.mergeData.data.to, combinedObj); var subject = EmailService.replaceTags(template.mergeData.data.subject, combinedObj); var body = EmailService.replaceTags(template.mergeData.data.body, combinedObj); var cc; var bcc; if (template.mergeData.data.cc != null) { cc = EmailService.replaceTags(template.mergeData.data.cc, combinedObj);; } if (template.mergeData.data.bcc != null) { bcc = EmailService.replaceTags(template.mergeData.data.bcc, combinedObj);; } EmailService.send(to, subject, body, cc, bcc); return true; }, /** * Sends an email based upon a MergeTemplate. Tags are swapped out. * Handles to, subject, body, conditional and timestampColumn fields. * * @param {String[]} headerRow An array of header values. * @param {String[]} row An array of row values. * @param {Object} template The MergeTemplate used to send the email. See the client-side Object for info. * @return {Boolean} true if the email was sent, false otherwise. */ conditionalSendHelper: function(headerRow, row, template) { var combinedObj = {}; for (var j = 0; j < headerRow.length; j++) { combinedObj[headerRow[j]] = row[j]; } // Convert <<>> tags to actual text. var to = EmailService.replaceTags(template.mergeData.data.to, combinedObj); var subject = EmailService.replaceTags(template.mergeData.data.subject, combinedObj); var body = EmailService.replaceTags(template.mergeData.data.body, combinedObj); var sendColumn = EmailService.replaceTags(template.mergeData.conditional, combinedObj); var cc; var bcc; if (template.mergeData.data.cc != null) { cc = EmailService.replaceTags(template.mergeData.data.cc, combinedObj);; } if (template.mergeData.data.bcc != null) { bcc = EmailService.replaceTags(template.mergeData.data.bcc, combinedObj);; } if (sendColumn.toLowerCase() == 'true') { EmailService.send(to, subject, body, cc, bcc); return true; } return false; }, /** * This function replaces all instances of <<tags>> with the data in headerToData. * * @param {string} text The string that contains the tags. * @param {Object} headerToData A key-value pair where the key is a column name and the value is the data in the * column. * @return {string} The text with all tags replaced with data. */ replaceTags: function(text, headerToData) { var dataText = text.replace(/<<.*?>>/g, function(match, offset, string) { var columnName = match.slice(2, match.length - 2); return headerToData[columnName]; }); return dataText; } };
Added a requirement for emails to have a to field.
src/GAS/services/email-service.js
Added a requirement for emails to have a to field.
<ide><path>rc/GAS/services/email-service.js <ide> }, <ide> <ide> send: function(to, subject, body, cc, bcc) { <add> if (to === '' || to == null) { <add> return; <add> } <add> <ide> var htmlEmail = HtmlService.createTemplateFromFile('email-template'); <ide> htmlEmail.id = Utility.getSpreadsheet().getId(); <ide> htmlEmail.bodyArray = body.split('\n');
Java
apache-2.0
ac3506cfed32d8c57472f7cf4a8d92e2e66193e7
0
Valkryst/VTerminal
package com.valkryst.VTerminal.component; import com.valkryst.VTerminal.Screen; import com.valkryst.VTerminal.Tile; import com.valkryst.VTerminal.palette.ColorPalette; import lombok.NonNull; import lombok.Setter; import lombok.ToString; import java.awt.*; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.ReentrantReadWriteLock; @ToString public class Layer extends Component { /** The components on the layer. */ private final List<Component> components = new ArrayList<>(0); /** The lock used to control access to the components. */ private final ReentrantReadWriteLock componentsLock = new ReentrantReadWriteLock(); /** The screen that the layer resides on. */ @Setter private Screen rootScreen; /** * Constructs a new Layer at position (0, 0) with the default color palette. * * @param dimensions * The dimensions of the layer. */ public Layer(final @NonNull Dimension dimensions) { this(dimensions, null, null); } /** * Constructs a new Layer with the default color palette. * * @param dimensions * The dimensions of the layer. * * @param position * The position of the layer within it's parent. */ public Layer(final @NonNull Dimension dimensions, final Point position) { this(dimensions, position, null); } /** * Constructs a new Layer. * * @param dimensions * The dimensions of the layer. * * @param position * The position of the layer within it's parent. * * If null, then the position (0, 0) is used. * * @param colorPalette * The color palette to color the layer with. * * If null, then the default color palette is used. */ public Layer(final @NonNull Dimension dimensions, final Point position, ColorPalette colorPalette) { super(dimensions, (position == null ? new Point(0, 0) : position)); if (colorPalette == null) { colorPalette = new ColorPalette(); } for (int y = 0 ; y < super.tiles.getHeight() ; y++) { for (int x = 0 ; x < super.tiles.getWidth() ; x++) { final Tile tile = super.tiles.getTileAt(x, y); tile.setBackgroundColor(colorPalette.getLayer_defaultBackground()); tile.setForegroundColor(colorPalette.getLayer_defaultForeground()); } } } @Override public void setColorPalette(final ColorPalette colorPalette, final boolean redraw) { if (colorPalette == null) { return; } this.colorPalette = colorPalette; // Change the color of the layer's tiles. final Color backgroundColor = colorPalette.getLayer_defaultBackground(); final Color foregroundColor = colorPalette.getLayer_defaultForeground(); for (int y = 0 ; y < super.tiles.getHeight() ; y++) { for (int x = 0 ; x < super.tiles.getWidth() ; x++) { final Tile tile = super.tiles.getTileAt(x, y); tile.setBackgroundColor(backgroundColor); tile.setForegroundColor(foregroundColor); } } // Change child component color palettes. componentsLock.readLock().lock(); for (final Component component : components) { component.setColorPalette(colorPalette, false); } componentsLock.readLock().unlock(); // Redraw if necessary if (redraw) { try { redrawFunction.run(); } catch (final IllegalStateException ignored) { /* * If we set the color palette before the screen is displayed, then it'll throw... * * IllegalStateException: Component must have a valid peer * * We can just ignore it in this case, because the screen will be drawn when it is displayed for * the first time. */ } } } /** * Adds one or more components to the layer. * * @param components * The components. */ public void addComponent(final Component ... components) { if (components == null) { return; } for (final Component component : components) { if (component == null) { return; } if (component.equals(this)) { return; } final int x = this.getTiles().getXPosition() + component.getTiles().getXPosition(); final int y = this.getTiles().getYPosition() + component.getTiles().getYPosition(); component.setBoundingBoxOrigin(x, y); if (component instanceof Layer) { final Queue<Component> subComponents = new ConcurrentLinkedQueue<>(); subComponents.add(component); while(subComponents.size() > 0) { final Component temp = subComponents.remove(); if (rootScreen != null) { // Set the component's redraw function temp.setRedrawFunction(rootScreen::draw); // Create and add the component's listeners temp.createEventListeners(rootScreen); for (final EventListener listener : temp.getEventListeners()) { rootScreen.addListener(listener); } } // If the component's a layer, then we need to deal with it's sub-components. if (temp instanceof Layer) { ((Layer) temp).setRootScreen(rootScreen); subComponents.addAll(((Layer) temp).getComponents()); updateChildBoundingBoxesOfLayer((Layer) temp); } } } // Add the component componentsLock.writeLock().lock(); super.tiles.addChild(component.getTiles()); this.components.add(component); componentsLock.writeLock().unlock(); /* * This line is relevant only when adding components to a Layer that's already on a Screen. * * Before a Layer is first added to a Screen, none of the sub-components will have had their listeners * initialized. The initialization is done when the Layer is being added to the Screen. */ if (rootScreen != null) { // Set the component's redraw function component.setRedrawFunction(rootScreen::draw); for (final EventListener listener : component.getEventListeners()) { rootScreen.addListener(listener); } } } } /** * Removes one or more components from the layer. * * @param components * The components. */ public void removeComponent(final Component ... components) { if (components == null) { return; } for (final Component component : components) { if (component == null) { return; } // Remove the component componentsLock.writeLock().lock(); super.tiles.removeChild(component.getTiles()); this.components.remove(component); componentsLock.writeLock().unlock(); // Unset the component's redraw function component.setRedrawFunction(() -> {}); // Remove the event listeners of the component and all of it's sub-components. final Queue<Component> subComponents = new ConcurrentLinkedQueue<>(); subComponents.add(component); while (subComponents.size() > 0) { final Component temp = subComponents.remove(); if (temp instanceof Layer) { subComponents.addAll(((Layer) temp).getComponents()); } for (final EventListener listener : temp.getEventListeners()) { rootScreen.removeListener(listener); } } // Reset all of the tiles where the component used to be. final int startX = component.getTiles().getXPosition(); final int startY = component.getTiles().getYPosition(); final int endX = startX + component.getTiles().getWidth(); final int endY = startY + component.getTiles().getHeight(); for (int y = startY; y < endY; y++) { for (int x = startX; x < endX; x++) { final Tile tile = tiles.getTileAt(x, y); if (tile != null) { tile.reset(); if (rootScreen != null) { tile.setBackgroundColor(rootScreen.getColorPalette().getDefaultBackground()); tile.setForegroundColor(rootScreen.getColorPalette().getDefaultForeground()); } } } } } } /** Removes all components from the layer. */ public void removeAllComponents() { final Queue<Component> subComponents = new ConcurrentLinkedQueue<>(components); while (subComponents.size() > 0) { removeComponent(subComponents.remove()); } } /** * Recursively updates the bounding box origin points of a layer, all of it's child components, and all of * the child components of any layer that is a child to the screen. * * @param layer * The layer. */ private void updateChildBoundingBoxesOfLayer(final Layer layer) { if (layer == null) { return; } for (final Component component : layer.getComponents()) { final int x = layer.getBoundingBoxOrigin().x + component.getTiles().getXPosition(); final int y = layer.getBoundingBoxOrigin().y + component.getTiles().getYPosition(); component.setBoundingBoxOrigin(x, y); if (component instanceof Layer) { updateChildBoundingBoxesOfLayer((Layer) component); } } } /** * Retrieves all components which use a specific ID. * * @param id * The ID to search for. * * @return * All components using the ID. */ public List<Component> getComponentsByID(final String id) { if (id == null || id.isEmpty() || components.size() == 0) { return new ArrayList<>(0); } final List<Component> results = new ArrayList<>(1); for (final Component component : components) { if (component.getId().equals(id)) { results.add(component); } } return results; } /** * Retrieves an unmodifiable list of the layer's components. * * @return * An unmodifiable list of the layer's components. */ public List<Component> getComponents() { return Collections.unmodifiableList(components); } }
src/com/valkryst/VTerminal/component/Layer.java
package com.valkryst.VTerminal.component; import com.valkryst.VTerminal.Screen; import com.valkryst.VTerminal.Tile; import com.valkryst.VTerminal.palette.ColorPalette; import lombok.NonNull; import lombok.Setter; import lombok.ToString; import java.awt.*; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.ReentrantReadWriteLock; @ToString public class Layer extends Component { /** The components on the layer. */ private final List<Component> components = new ArrayList<>(0); /** The lock used to control access to the components. */ private final ReentrantReadWriteLock componentsLock = new ReentrantReadWriteLock(); /** The screen that the layer resides on. */ @Setter private Screen rootScreen; /** * Constructs a new Layer at position (0, 0) with the default color palette. * * @param dimensions * The dimensions of the layer. */ public Layer(final @NonNull Dimension dimensions) { this(dimensions, null, null); } /** * Constructs a new Layer with the default color palette. * * @param dimensions * The dimensions of the layer. * * @param position * The position of the layer within it's parent. */ public Layer(final @NonNull Dimension dimensions, final Point position) { this(dimensions, position, null); } /** * Constructs a new Layer. * * @param dimensions * The dimensions of the layer. * * @param position * The position of the layer within it's parent. * * If null, then the position (0, 0) is used. * * @param colorPalette * The color palette to color the layer with. * * If null, then the default color palette is used. */ public Layer(final @NonNull Dimension dimensions, final Point position, ColorPalette colorPalette) { super(dimensions, (position == null ? new Point(0, 0) : position)); if (colorPalette == null) { colorPalette = new ColorPalette(); } for (int y = 0 ; y < super.tiles.getHeight() ; y++) { for (int x = 0 ; x < super.tiles.getWidth() ; x++) { final Tile tile = super.tiles.getTileAt(x, y); tile.setBackgroundColor(colorPalette.getLayer_defaultBackground()); tile.setForegroundColor(colorPalette.getLayer_defaultForeground()); } } } @Override public void setColorPalette(final ColorPalette colorPalette, final boolean redraw) { if (colorPalette == null) { return; } this.colorPalette = colorPalette; // Change the color of the layer's tiles. final Color backgroundColor = colorPalette.getLayer_defaultBackground(); final Color foregroundColor = colorPalette.getLayer_defaultForeground(); for (int y = 0 ; y < super.tiles.getHeight() ; y++) { for (int x = 0 ; x < super.tiles.getWidth() ; x++) { final Tile tile = super.tiles.getTileAt(x, y); tile.setBackgroundColor(backgroundColor); tile.setForegroundColor(foregroundColor); } } // Change child component color palettes. componentsLock.readLock().lock(); for (final Component component : components) { component.setColorPalette(colorPalette, false); } componentsLock.readLock().unlock(); // Redraw if necessary if (redraw) { try { redrawFunction.run(); } catch (final IllegalStateException ignored) { /* * If we set the color palette before the screen is displayed, then it'll throw... * * IllegalStateException: Component must have a valid peer * * We can just ignore it in this case, because the screen will be drawn when it is displayed for * the first time. */ } } } /** * Adds one or more components to the layer. * * @param components * The components. */ public void addComponent(final Component ... components) { if (components == null) { return; } for (final Component component : components) { if (component == null) { return; } if (component.equals(this)) { return; } final int x = this.getTiles().getXPosition() + component.getTiles().getXPosition(); final int y = this.getTiles().getYPosition() + component.getTiles().getYPosition(); component.setBoundingBoxOrigin(x, y); if (component instanceof Layer) { final Queue<Component> subComponents = new ConcurrentLinkedQueue<>(); subComponents.add(component); while(subComponents.size() > 0) { final Component temp = subComponents.remove(); if (rootScreen != null) { // Set the component's redraw function temp.setRedrawFunction(rootScreen::draw); // Create and add the component's listeners temp.createEventListeners(rootScreen); for (final EventListener listener : temp.getEventListeners()) { rootScreen.addListener(listener); } } // If the component's a layer, then we need to deal with it's sub-components. if (temp instanceof Layer) { ((Layer) temp).setRootScreen(rootScreen); subComponents.addAll(((Layer) temp).getComponents()); updateChildBoundingBoxesOfLayer((Layer) temp); } } } // Add the component componentsLock.writeLock().lock(); super.tiles.addChild(component.getTiles()); this.components.add(component); componentsLock.writeLock().unlock(); /* * This line is relevant only when adding components to a Layer that's already on a Screen. * * Before a Layer is first added to a Screen, none of the sub-components will have had their listeners * initialized. The initialization is done when the Layer is being added to the Screen. */ if (rootScreen != null) { // Set the component's redraw function component.setRedrawFunction(rootScreen::draw); for (final EventListener listener : component.getEventListeners()) { rootScreen.addListener(listener); } } } } /** * Removes one or more components from the layer. * * @param components * The components. */ public void removeComponent(final Component ... components) { if (components == null) { return; } for (final Component component : components) { if (component == null) { return; } // Remove the component componentsLock.writeLock().lock(); super.tiles.removeChild(component.getTiles()); this.components.remove(component); componentsLock.writeLock().unlock(); // Unset the component's redraw function component.setRedrawFunction(() -> {}); // Remove the event listeners of the component and all of it's sub-components. final Queue<Component> subComponents = new ConcurrentLinkedQueue<>(); subComponents.add(component); while(subComponents.size() > 0) { final Component temp = subComponents.remove(); if (temp instanceof Layer) { subComponents.addAll(((Layer) temp).getComponents()); } for (final EventListener listener : temp.getEventListeners()) { rootScreen.removeListener(listener); } } // Remove all of the component's listeners from the root screen: for (final EventListener listener : component.getEventListeners()) { rootScreen.removeListener(listener); } // Reset all of the tiles where the component used to be. final int startX = component.getTiles().getXPosition(); final int startY = component.getTiles().getYPosition(); final int endX = startX + component.getTiles().getWidth(); final int endY = startY + component.getTiles().getHeight(); for (int y = startY; y < endY; y++) { for (int x = startX; x < endX; x++) { final Tile tile = tiles.getTileAt(x, y); if (tile != null) { tile.reset(); System.out.println(tile + " " + rootScreen + " " + rootScreen.getColorPalette()); tile.setBackgroundColor(rootScreen.getColorPalette().getDefaultBackground()); tile.setForegroundColor(rootScreen.getColorPalette().getDefaultForeground()); } } } } } /** Removes all components from the layer. */ public void removeAllComponents() { final Queue<Component> subComponents = new ConcurrentLinkedQueue<>(components); while (subComponents.size() > 0) { removeComponent(subComponents.remove()); } } /** * Recursively updates the bounding box origin points of a layer, all of it's child components, and all of * the child components of any layer that is a child to the screen. * * @param layer * The layer. */ private void updateChildBoundingBoxesOfLayer(final Layer layer) { if (layer == null) { return; } for (final Component component : layer.getComponents()) { final int x = layer.getBoundingBoxOrigin().x + component.getTiles().getXPosition(); final int y = layer.getBoundingBoxOrigin().y + component.getTiles().getYPosition(); component.setBoundingBoxOrigin(x, y); if (component instanceof Layer) { updateChildBoundingBoxesOfLayer((Layer) component); } } } /** * Retrieves all components which use a specific ID. * * @param id * The ID to search for. * * @return * All components using the ID. */ public List<Component> getComponentsByID(final String id) { if (id == null || id.isEmpty() || components.size() == 0) { return new ArrayList<>(0); } final List<Component> results = new ArrayList<>(1); for (final Component component : components) { if (component.getId().equals(id)) { results.add(component); } } return results; } /** * Retrieves an unmodifiable list of the layer's components. * * @return * An unmodifiable list of the layer's components. */ public List<Component> getComponents() { return Collections.unmodifiableList(components); } }
Removes unnecessary code from the removeComponent function. Replaces debug printout with null check in the removeComponent function, when resetting tiles.
src/com/valkryst/VTerminal/component/Layer.java
Removes unnecessary code from the removeComponent function. Replaces debug printout with null check in the removeComponent function, when resetting tiles.
<ide><path>rc/com/valkryst/VTerminal/component/Layer.java <ide> final Queue<Component> subComponents = new ConcurrentLinkedQueue<>(); <ide> subComponents.add(component); <ide> <del> while(subComponents.size() > 0) { <add> while (subComponents.size() > 0) { <ide> final Component temp = subComponents.remove(); <ide> <ide> if (temp instanceof Layer) { <ide> for (final EventListener listener : temp.getEventListeners()) { <ide> rootScreen.removeListener(listener); <ide> } <del> } <del> <del> // Remove all of the component's listeners from the root screen: <del> for (final EventListener listener : component.getEventListeners()) { <del> rootScreen.removeListener(listener); <ide> } <ide> <ide> // Reset all of the tiles where the component used to be. <ide> <ide> if (tile != null) { <ide> tile.reset(); <del> System.out.println(tile + " " + rootScreen + " " + rootScreen.getColorPalette()); <del> tile.setBackgroundColor(rootScreen.getColorPalette().getDefaultBackground()); <del> tile.setForegroundColor(rootScreen.getColorPalette().getDefaultForeground()); <add> <add> if (rootScreen != null) { <add> tile.setBackgroundColor(rootScreen.getColorPalette().getDefaultBackground()); <add> tile.setForegroundColor(rootScreen.getColorPalette().getDefaultForeground()); <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
5218cf4c16761a0f8ca9887b543c3bc7fc81b3d6
0
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
/* * Copyright 2002-2022 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 * * https://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.springframework.beans.factory.aot; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.lang.Nullable; /** * AOT processor that makes bean factory initialization contributions by * processing {@link ConfigurableListableBeanFactory} instances. * * @author Phillip Webb * @author Stephane Nicoll * @since 6.0 * @see BeanFactoryInitializationAotContribution */ @FunctionalInterface public interface BeanFactoryInitializationAotProcessor { /** * Process the given {@link ConfigurableListableBeanFactory} instance * ahead-of-time and return a contribution or {@code null}. * <p> * Processors are free to use any techniques they like to analyze the given * bean factory. Most typically use reflection to find fields or methods to * use in the contribution. Contributions typically generate source code or * resource files that can be used when the AOT optimized application runs. * <p> * If the given bean factory does not contain anything that is relevant to * the processor, it should return a {@code null} contribution. * @param beanFactory the bean factory to process * @return a {@link BeanFactoryInitializationAotContribution} or {@code null} */ @Nullable BeanFactoryInitializationAotContribution processAheadOfTime( ConfigurableListableBeanFactory beanFactory); }
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanFactoryInitializationAotProcessor.java
/* * Copyright 2002-2022 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 * * https://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.springframework.beans.factory.aot; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.lang.Nullable; /** * AOT processor that makes bean factory initialization contributions by * processing {@link ConfigurableListableBeanFactory} instances. * * <p>Note: Beans implementing interface will not have registration methods * generated during AOT processing unless they also implement * {@link org.springframework.beans.factory.aot.BeanRegistrationExcludeFilter}. * * @author Phillip Webb * @author Stephane Nicoll * @since 6.0 * @see BeanFactoryInitializationAotContribution */ @FunctionalInterface public interface BeanFactoryInitializationAotProcessor { /** * Process the given {@link ConfigurableListableBeanFactory} instance * ahead-of-time and return a contribution or {@code null}. * <p> * Processors are free to use any techniques they like to analyze the given * bean factory. Most typically use reflection to find fields or methods to * use in the contribution. Contributions typically generate source code or * resource files that can be used when the AOT optimized application runs. * <p> * If the given bean factory does not contain anything that is relevant to * the processor, it should return a {@code null} contribution. * @param beanFactory the bean factory to process * @return a {@link BeanFactoryInitializationAotContribution} or {@code null} */ @Nullable BeanFactoryInitializationAotContribution processAheadOfTime( ConfigurableListableBeanFactory beanFactory); }
Fix BeanFactoryInitializationAotProcessor javadoc Update javadoc since BeanRegistrationExcludeFilter is not longer an exclude signal See gh-28833
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanFactoryInitializationAotProcessor.java
Fix BeanFactoryInitializationAotProcessor javadoc
<ide><path>pring-beans/src/main/java/org/springframework/beans/factory/aot/BeanFactoryInitializationAotProcessor.java <ide> /** <ide> * AOT processor that makes bean factory initialization contributions by <ide> * processing {@link ConfigurableListableBeanFactory} instances. <del> * <del> * <p>Note: Beans implementing interface will not have registration methods <del> * generated during AOT processing unless they also implement <del> * {@link org.springframework.beans.factory.aot.BeanRegistrationExcludeFilter}. <ide> * <ide> * @author Phillip Webb <ide> * @author Stephane Nicoll
Java
apache-2.0
92be6262923503f8f5dc9edcf357f3e3bc0fae7d
0
MatthewTamlin/Spyglass
package com.matthewtamlin.spyglass.library; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.FIELD}) public @interface BindBoolean { int annotationId(); boolean ignoreIfAttributeMissing() default false; boolean defaultValue() default false; int defaultResourceId() default 0; }
library/src/main/java/com/matthewtamlin/spyglass/library/BindBoolean.java
package com.matthewtamlin.spyglass.library; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.FIELD}) public @interface BindBoolean { int annotationId(); boolean ignoreIfAttributeMissing() default false; boolean defaultValue() default false; }
Added default resource ID element
library/src/main/java/com/matthewtamlin/spyglass/library/BindBoolean.java
Added default resource ID element
<ide><path>ibrary/src/main/java/com/matthewtamlin/spyglass/library/BindBoolean.java <ide> boolean ignoreIfAttributeMissing() default false; <ide> <ide> boolean defaultValue() default false; <add> <add> int defaultResourceId() default 0; <ide> }
Java
apache-2.0
c4b7f04e1879c0b818f59fc0012eb4007f48eeb9
0
subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai
package io.subutai.core.environment.rest.ui; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public interface RestService { @GET @Produces( { MediaType.APPLICATION_JSON } ) public Response listEnvironments(); @GET @Path( "domain" ) @Produces( { MediaType.TEXT_PLAIN } ) public Response getDefaultDomainName(); @POST @Path( "blueprint" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response saveBlueprint( @FormParam( "blueprint_json" ) String content); @GET @Path( "blueprint" ) @Produces( { MediaType.TEXT_PLAIN } ) public Response getBlueprints(); @GET @Path( "container/{containerId}" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response getContainerEnvironmentId( @PathParam( "containerId" ) String containerId ); @GET @Path( "{environmentId}" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response viewEnvironment( @PathParam( "environmentId" ) String environmentId ); @POST public Response createEnvironment( @FormParam( "name" ) String environmentName, @FormParam( "topology" ) String topologyJsonString, @FormParam( "subnet" ) String subnetCidr, @FormParam( "key" ) String sshKey ); @POST @Path( "grow" ) public Response growEnvironment( @FormParam( "environmentId" ) String environmentId, @FormParam( "topology" ) String topologyJsonString ); @POST @Path( "key" ) public Response setSshKey( @FormParam( "environmentId" ) String environmentId, @FormParam( "key" ) String key ); @DELETE @Path( "{environmentId}/keys" ) public Response removeSshKey( @PathParam( "environmentId" ) String environmentId ); @DELETE @Path( "{environmentId}" ) public Response destroyEnvironment( @PathParam( "environmentId" ) String environmentId ); @DELETE @Path( "container/{containerId}" ) public Response destroyContainer( @PathParam( "containerId" ) String containerId ); @GET @Path( "container/{containerId}/state" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response getContainerState( @PathParam( "containerId" ) String containerId ); @POST @Path( "container/{containerId}/start" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response startContainer( @PathParam( "containerId" ) String containerId ); @POST @Path( "container/{containerId}/stop" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response stopContainer( @PathParam( "containerId" ) String containerId ); }
management/server/core/environment-manager/environment-manager-rest-ui/src/main/java/io/subutai/core/environment/rest/ui/RestService.java
package io.subutai.core.environment.rest.ui; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public interface RestService { @GET @Produces( { MediaType.APPLICATION_JSON } ) public Response listEnvironments(); @GET @Path( "domain" ) @Produces( { MediaType.TEXT_PLAIN } ) public Response getDefaultDomainName(); @POST @Path( "blueprint" ) @Produces( { MediaType.TEXT_PLAIN } ) public Response saveBlueprint( @FormParam( "blueprint_json" ) String content); @GET @Path( "blueprint" ) @Produces( { MediaType.TEXT_PLAIN } ) public Response getBlueprints(); @GET @Path( "container/{containerId}" ) @Produces( { MediaType.TEXT_PLAIN } ) public Response getContainerEnvironmentId( @PathParam( "containerId" ) String containerId ); @GET @Path( "{environmentId}" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response viewEnvironment( @PathParam( "environmentId" ) String environmentId ); @POST public Response createEnvironment( @FormParam( "name" ) String environmentName, @FormParam( "topology" ) String topologyJsonString, @FormParam( "subnet" ) String subnetCidr, @FormParam( "key" ) String sshKey ); @POST @Path( "grow" ) public Response growEnvironment( @FormParam( "environmentId" ) String environmentId, @FormParam( "topology" ) String topologyJsonString ); @POST @Path( "key" ) public Response setSshKey( @FormParam( "environmentId" ) String environmentId, @FormParam( "key" ) String key ); @DELETE @Path( "{environmentId}/keys" ) public Response removeSshKey( @PathParam( "environmentId" ) String environmentId ); @DELETE @Path( "{environmentId}" ) public Response destroyEnvironment( @PathParam( "environmentId" ) String environmentId ); @DELETE @Path( "container/{containerId}" ) public Response destroyContainer( @PathParam( "containerId" ) String containerId ); @GET @Path( "container/{containerId}/state" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response getContainerState( @PathParam( "containerId" ) String containerId ); @POST @Path( "container/{containerId}/start" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response startContainer( @PathParam( "containerId" ) String containerId ); @POST @Path( "container/{containerId}/stop" ) @Produces( { MediaType.APPLICATION_JSON } ) public Response stopContainer( @PathParam( "containerId" ) String containerId ); }
SS-3696 rest-ui fix
management/server/core/environment-manager/environment-manager-rest-ui/src/main/java/io/subutai/core/environment/rest/ui/RestService.java
SS-3696 rest-ui fix
<ide><path>anagement/server/core/environment-manager/environment-manager-rest-ui/src/main/java/io/subutai/core/environment/rest/ui/RestService.java <ide> <ide> @POST <ide> @Path( "blueprint" ) <del> @Produces( { MediaType.TEXT_PLAIN } ) <add> @Produces( { MediaType.APPLICATION_JSON } ) <ide> public Response saveBlueprint( @FormParam( "blueprint_json" ) String content); <ide> <ide> @GET <ide> <ide> @GET <ide> @Path( "container/{containerId}" ) <del> @Produces( { MediaType.TEXT_PLAIN } ) <add> @Produces( { MediaType.APPLICATION_JSON } ) <ide> public Response getContainerEnvironmentId( @PathParam( "containerId" ) String containerId ); <ide> <ide>
Java
apache-2.0
error: pathspec 'web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/geod22351/HeatmapTableWithDifferentRegulationsButDefaultQueryParams.java' did not match any file(s) known to git
18dbc2ac85c3097aab778921b571e0bb0401f9ba
1
gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas
/* * Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.atlas.acceptance.selenium.tests.geod22351; import org.junit.Test; import uk.ac.ebi.atlas.acceptance.selenium.pages.HeatmapTablePage; import uk.ac.ebi.atlas.acceptance.selenium.utils.SeleniumFixture; import uk.ac.ebi.atlas.acceptance.selenium.utils.SinglePageSeleniumFixture; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertThat; public class HeatmapTableWithDifferentRegulationsButDefaultQueryParams extends SeleniumFixture { private static final String E_GEOD_22351_ACCESSION = "E-GEOD-22351"; protected HeatmapTablePage subject; @Test public void verifyQueryFactorLableAndHeatmapHeaders(){ subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=UP&displayLevels=true"); subject.get(); assertThat(subject.getQueryFactorLabel(), is("Contrast")); assertThat(subject.getFactorValueHeaders().size(), is(1)); assertThat(subject.getFactorValueHeaders().get(0), startsWith("genotype")); } @Test public void verifyResultsWithRegulationUp() { subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=UP&displayLevels=true"); subject.get(); assertThat(subject.getGeneCount(), containsString("of 40")); assertThat(subject.getSelectedGenes().size(), is(40)); assertThat(subject.getSelectedGenes().subList(0,3), contains("Gpnmb","Cst7","Itgax")); assertThat(subject.getGeneProfile(1).size(), is(1)); assertThat(subject.getGeneProfile(1).get(0), is("3.30119188460638E-13")); assertThat(subject.getLastGeneProfile().size(), is(1)); assertThat(subject.getLastGeneProfile().get(0), is("0.0414522894483861")); } @Test public void verifyResultsWithRegulationDown() { subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=DOWN&displayLevels=true"); subject.get(); assertThat(subject.getGeneCount(), containsString("of 9")); assertThat(subject.getSelectedGenes().size(), is(9)); assertThat(subject.getSelectedGenes().subList(0,3), contains("Gm15512", "Pla2g3", "Pmp2")); assertThat(subject.getGeneProfile(1).size(), is(1)); assertThat(subject.getGeneProfile(1).get(0), is("6.61209253228153E-5")); assertThat(subject.getLastGeneProfile().size(), is(1)); assertThat(subject.getLastGeneProfile().get(0), is("0.0414522894483861")); } @Test public void verifyResultsWithRegulationUpDown() { subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=UP_DOWN&displayLevels=true"); subject.get(); assertThat(subject.getGeneCount(), containsString("of 49")); assertThat(subject.getSelectedGenes().size(), is(49)); assertThat(subject.getSelectedGenes().subList(0,3), contains("Gpnmb","Cst7","Itgax")); assertThat(subject.getGeneProfile(1).size(), is(1)); assertThat(subject.getGeneProfile(1).get(0), is("3.30119188460638E-13")); assertThat(subject.getLastGeneProfile().size(), is(1)); assertThat(subject.getLastGeneProfile().get(0), is("0.0414522894483861")); } }
web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/geod22351/HeatmapTableWithDifferentRegulationsButDefaultQueryParams.java
added selenium test that does assertions on heatmap table content for up, down and up/down regulation
web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/geod22351/HeatmapTableWithDifferentRegulationsButDefaultQueryParams.java
added selenium test that does assertions on heatmap table content for up, down and up/down regulation
<ide><path>eb/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/geod22351/HeatmapTableWithDifferentRegulationsButDefaultQueryParams.java <add>/* <add> * Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * <add> * <add> * For further details of the Gene Expression Atlas project, including source code, <add> * downloads and documentation, please see: <add> * <add> * http://gxa.github.com/gxa <add> */ <add> <add>package uk.ac.ebi.atlas.acceptance.selenium.tests.geod22351; <add> <add>import org.junit.Test; <add>import uk.ac.ebi.atlas.acceptance.selenium.pages.HeatmapTablePage; <add>import uk.ac.ebi.atlas.acceptance.selenium.utils.SeleniumFixture; <add>import uk.ac.ebi.atlas.acceptance.selenium.utils.SinglePageSeleniumFixture; <add> <add>import static org.hamcrest.Matchers.contains; <add>import static org.hamcrest.Matchers.is; <add>import static org.hamcrest.Matchers.startsWith; <add>import static org.hamcrest.core.StringContains.containsString; <add>import static org.junit.Assert.assertThat; <add> <add>public class HeatmapTableWithDifferentRegulationsButDefaultQueryParams extends SeleniumFixture { <add> <add> private static final String E_GEOD_22351_ACCESSION = "E-GEOD-22351"; <add> protected HeatmapTablePage subject; <add> <add> @Test <add> public void verifyQueryFactorLableAndHeatmapHeaders(){ <add> subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=UP&displayLevels=true"); <add> subject.get(); <add> <add> assertThat(subject.getQueryFactorLabel(), is("Contrast")); <add> <add> assertThat(subject.getFactorValueHeaders().size(), is(1)); <add> assertThat(subject.getFactorValueHeaders().get(0), startsWith("genotype")); <add> } <add> <add> @Test <add> public void verifyResultsWithRegulationUp() { <add> subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=UP&displayLevels=true"); <add> subject.get(); <add> assertThat(subject.getGeneCount(), containsString("of 40")); <add> <add> assertThat(subject.getSelectedGenes().size(), is(40)); <add> assertThat(subject.getSelectedGenes().subList(0,3), contains("Gpnmb","Cst7","Itgax")); <add> <add> assertThat(subject.getGeneProfile(1).size(), is(1)); <add> assertThat(subject.getGeneProfile(1).get(0), is("3.30119188460638E-13")); <add> <add> assertThat(subject.getLastGeneProfile().size(), is(1)); <add> assertThat(subject.getLastGeneProfile().get(0), is("0.0414522894483861")); <add> } <add> <add> @Test <add> public void verifyResultsWithRegulationDown() { <add> subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=DOWN&displayLevels=true"); <add> subject.get(); <add> assertThat(subject.getGeneCount(), containsString("of 9")); <add> <add> assertThat(subject.getSelectedGenes().size(), is(9)); <add> assertThat(subject.getSelectedGenes().subList(0,3), contains("Gm15512", "Pla2g3", "Pmp2")); <add> <add> assertThat(subject.getGeneProfile(1).size(), is(1)); <add> assertThat(subject.getGeneProfile(1).get(0), is("6.61209253228153E-5")); <add> <add> assertThat(subject.getLastGeneProfile().size(), is(1)); <add> assertThat(subject.getLastGeneProfile().get(0), is("0.0414522894483861")); <add> } <add> <add> @Test <add> public void verifyResultsWithRegulationUpDown() { <add> subject = new HeatmapTablePage(driver, E_GEOD_22351_ACCESSION, "regulation=UP_DOWN&displayLevels=true"); <add> subject.get(); <add> assertThat(subject.getGeneCount(), containsString("of 49")); <add> <add> assertThat(subject.getSelectedGenes().size(), is(49)); <add> assertThat(subject.getSelectedGenes().subList(0,3), contains("Gpnmb","Cst7","Itgax")); <add> <add> assertThat(subject.getGeneProfile(1).size(), is(1)); <add> assertThat(subject.getGeneProfile(1).get(0), is("3.30119188460638E-13")); <add> <add> assertThat(subject.getLastGeneProfile().size(), is(1)); <add> assertThat(subject.getLastGeneProfile().get(0), is("0.0414522894483861")); <add> } <add> <add>}
Java
apache-2.0
4d8b1a5895a379b6a43c3ac22a963b6e06867182
0
Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,ptrd/jmeter-plugins,ptrd/jmeter-plugins,ptrd/jmeter-plugins,Sausageo/jmeter-plugins,ptrd/jmeter-plugins,ptrd/jmeter-plugins
package kg.apc.perfmon.metrics; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * * @author undera */ public class ExecMetricTest extends TestCase { public ExecMetricTest(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(ExecMetricTest.class); return suite; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } /** * Test of getValue method, of class RunMetric. */ public void testGetValue() throws Exception { System.out.println("getValue"); StringBuffer res = new StringBuffer(); //default is linux os String cmd = "echo:123"; if(System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { cmd = "cmd:/C:echo:123"; } ExecMetric instance = new ExecMetric(MetricParams.createFromString(cmd)); instance.getValue(res); assertTrue(Double.parseDouble(res.toString()) == 123); } /* public void testGetValue2() throws Exception { System.out.println("getValue"); StringBuffer res = new StringBuffer(); ExecMetric instance = new ExecMetric(MetricParams.createFromString("/usr/bin/perl:-e:\"print 100*rand(1);\"")); instance.getValue(res); assertTrue(Double.parseDouble(res.toString()) > 0); } */ }
agent/test/kg/apc/perfmon/metrics/ExecMetricTest.java
package kg.apc.perfmon.metrics; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * * @author undera */ public class ExecMetricTest extends TestCase { public ExecMetricTest(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(ExecMetricTest.class); return suite; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } /** * Test of getValue method, of class RunMetric. */ public void testGetValue() throws Exception { System.out.println("getValue"); StringBuffer res = new StringBuffer(); ExecMetric instance = new ExecMetric(MetricParams.createFromString("echo:123")); instance.getValue(res); assertTrue(Double.parseDouble(res.toString()) > 0); } /* public void testGetValue2() throws Exception { System.out.println("getValue"); StringBuffer res = new StringBuffer(); ExecMetric instance = new ExecMetric(MetricParams.createFromString("/usr/bin/perl:-e:\"print 100*rand(1);\"")); instance.getValue(res); assertTrue(Double.parseDouble(res.toString()) > 0); } */ }
make test windows compatible
agent/test/kg/apc/perfmon/metrics/ExecMetricTest.java
make test windows compatible
<ide><path>gent/test/kg/apc/perfmon/metrics/ExecMetricTest.java <ide> public void testGetValue() throws Exception { <ide> System.out.println("getValue"); <ide> StringBuffer res = new StringBuffer(); <del> ExecMetric instance = new ExecMetric(MetricParams.createFromString("echo:123")); <add> //default is linux os <add> String cmd = "echo:123"; <add> if(System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { <add> cmd = "cmd:/C:echo:123"; <add> } <add> ExecMetric instance = new ExecMetric(MetricParams.createFromString(cmd)); <ide> instance.getValue(res); <del> assertTrue(Double.parseDouble(res.toString()) > 0); <add> assertTrue(Double.parseDouble(res.toString()) == 123); <ide> } <ide> <ide> /*
Java
apache-2.0
def6fbba89864ee1d8d654f4b2ba2a2d3d14a73e
0
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
/* * Copyright 2002-2018 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.springframework.beans.factory.support; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.Iterator; 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.concurrent.ConcurrentHashMap; import java.util.stream.Stream; import javax.inject.Provider; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.beans.factory.CannotLoadBeanClassException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InjectionPoint; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartFactoryBean; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.config.NamedBeanHolder; import org.springframework.core.OrderComparator; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CompositeIterator; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Spring's default implementation of the {@link ConfigurableListableBeanFactory} * and {@link BeanDefinitionRegistry} interfaces: a full-fledged bean factory * based on bean definition metadata, extensible through post-processors. * * <p>Typical usage is registering all bean definitions first (possibly read * from a bean definition file), before accessing beans. Bean lookup by name * is therefore an inexpensive operation in a local bean definition table, * operating on pre-resolved bean definition metadata objects. * * <p>Note that readers for specific bean definition formats are typically * implemented separately rather than as bean factory subclasses: * see for example {@link PropertiesBeanDefinitionReader} and * {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}. * * <p>For an alternative implementation of the * {@link org.springframework.beans.factory.ListableBeanFactory} interface, * have a look at {@link StaticListableBeanFactory}, which manages existing * bean instances rather than creating new ones based on bean definitions. * * @author Rod Johnson * @author Juergen Hoeller * @author Sam Brannen * @author Costin Leau * @author Chris Beams * @author Phillip Webb * @author Stephane Nicoll * @since 16 April 2001 * @see #registerBeanDefinition * @see #addBeanPostProcessor * @see #getBean * @see #resolveDependency */ @SuppressWarnings("serial") public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable { @Nullable private static Class<?> javaxInjectProviderClass; static { try { javaxInjectProviderClass = ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader()); } catch (ClassNotFoundException ex) { // JSR-330 API not available - Provider interface simply not supported then. javaxInjectProviderClass = null; } } /** Map from serialized id to factory instance. */ private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories = new ConcurrentHashMap<>(8); /** Optional id for this factory, for serialization purposes. */ @Nullable private String serializationId; /** Whether to allow re-registration of a different definition with the same name. */ private boolean allowBeanDefinitionOverriding = true; /** Whether to allow eager class loading even for lazy-init beans. */ private boolean allowEagerClassLoading = true; /** Optional OrderComparator for dependency Lists and arrays. */ @Nullable private Comparator<Object> dependencyComparator; /** Resolver to use for checking if a bean definition is an autowire candidate. */ private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver(); /** Map from dependency type to corresponding autowired value. */ private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16); /** Map of bean definition objects, keyed by bean name. */ private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256); /** Map of singleton and non-singleton bean names, keyed by dependency type. */ private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64); /** Map of singleton-only bean names, keyed by dependency type. */ private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64); /** List of bean definition names, in registration order. */ private volatile List<String> beanDefinitionNames = new ArrayList<>(256); /** List of names of manually registered singletons, in registration order. */ private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16); /** Cached array of bean definition names in case of frozen configuration. */ @Nullable private volatile String[] frozenBeanDefinitionNames; /** Whether bean definition metadata may be cached for all beans. */ private volatile boolean configurationFrozen = false; /** * Create a new DefaultListableBeanFactory. */ public DefaultListableBeanFactory() { super(); } /** * Create a new DefaultListableBeanFactory with the given parent. * @param parentBeanFactory the parent BeanFactory */ public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) { super(parentBeanFactory); } /** * Specify an id for serialization purposes, allowing this BeanFactory to be * deserialized from this id back into the BeanFactory object, if needed. */ public void setSerializationId(@Nullable String serializationId) { if (serializationId != null) { serializableFactories.put(serializationId, new WeakReference<>(this)); } else if (this.serializationId != null) { serializableFactories.remove(this.serializationId); } this.serializationId = serializationId; } /** * Return an id for serialization purposes, if specified, allowing this BeanFactory * to be deserialized from this id back into the BeanFactory object, if needed. * @since 4.1.2 */ @Nullable public String getSerializationId() { return this.serializationId; } /** * Set whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * If not, an exception will be thrown. This also applies to overriding aliases. * <p>Default is "true". * @see #registerBeanDefinition */ public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } /** * Return whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * @since 4.1.2 */ public boolean isAllowBeanDefinitionOverriding() { return this.allowBeanDefinitionOverriding; } /** * Set whether the factory is allowed to eagerly load bean classes * even for bean definitions that are marked as "lazy-init". * <p>Default is "true". Turn this flag off to suppress class loading * for lazy-init beans unless such a bean is explicitly requested. * In particular, by-type lookups will then simply ignore bean definitions * without resolved class name, instead of loading the bean classes on * demand just to perform a type check. * @see AbstractBeanDefinition#setLazyInit */ public void setAllowEagerClassLoading(boolean allowEagerClassLoading) { this.allowEagerClassLoading = allowEagerClassLoading; } /** * Return whether the factory is allowed to eagerly load bean classes * even for bean definitions that are marked as "lazy-init". * @since 4.1.2 */ public boolean isAllowEagerClassLoading() { return this.allowEagerClassLoading; } /** * Set a {@link java.util.Comparator} for dependency Lists and arrays. * @since 4.0 * @see org.springframework.core.OrderComparator * @see org.springframework.core.annotation.AnnotationAwareOrderComparator */ public void setDependencyComparator(@Nullable Comparator<Object> dependencyComparator) { this.dependencyComparator = dependencyComparator; } /** * Return the dependency comparator for this BeanFactory (may be {@code null}. * @since 4.0 */ @Nullable public Comparator<Object> getDependencyComparator() { return this.dependencyComparator; } /** * Set a custom autowire candidate resolver for this BeanFactory to use * when deciding whether a bean definition should be considered as a * candidate for autowiring. */ public void setAutowireCandidateResolver(final AutowireCandidateResolver autowireCandidateResolver) { Assert.notNull(autowireCandidateResolver, "AutowireCandidateResolver must not be null"); if (autowireCandidateResolver instanceof BeanFactoryAware) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(DefaultListableBeanFactory.this); return null; }, getAccessControlContext()); } else { ((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(this); } } this.autowireCandidateResolver = autowireCandidateResolver; } /** * Return the autowire candidate resolver for this BeanFactory (never {@code null}). */ public AutowireCandidateResolver getAutowireCandidateResolver() { return this.autowireCandidateResolver; } @Override public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { super.copyConfigurationFrom(otherFactory); if (otherFactory instanceof DefaultListableBeanFactory) { DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory; this.allowBeanDefinitionOverriding = otherListableFactory.allowBeanDefinitionOverriding; this.allowEagerClassLoading = otherListableFactory.allowEagerClassLoading; this.dependencyComparator = otherListableFactory.dependencyComparator; // A clone of the AutowireCandidateResolver since it is potentially BeanFactoryAware... setAutowireCandidateResolver(BeanUtils.instantiateClass(getAutowireCandidateResolver().getClass())); // Make resolvable dependencies (e.g. ResourceLoader) available here as well... this.resolvableDependencies.putAll(otherListableFactory.resolvableDependencies); } } //--------------------------------------------------------------------- // Implementation of remaining BeanFactory methods //--------------------------------------------------------------------- @Override public <T> T getBean(Class<T> requiredType) throws BeansException { return getBean(requiredType, (Object[]) null); } @SuppressWarnings("unchecked") @Override public <T> T getBean(Class<T> requiredType, @Nullable Object... args) throws BeansException { Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return (T) resolved; } @Override public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) throws BeansException { return getBeanProvider(ResolvableType.forRawClass(requiredType)); } @SuppressWarnings("unchecked") @Override public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) { return new BeanObjectProvider<T>() { @Override public T getObject() throws BeansException { T resolved = resolveBean(requiredType, null, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return resolved; } @Override public T getObject(Object... args) throws BeansException { T resolved = resolveBean(requiredType, args, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return resolved; } @Override @Nullable public T getIfAvailable() throws BeansException { return resolveBean(requiredType, null, false); } @Override @Nullable public T getIfUnique() throws BeansException { return resolveBean(requiredType, null, true); } @Override public Stream<T> stream() { return Arrays.stream(getBeanNamesForType(requiredType)) .map(name -> (T) getBean(name)) .filter(bean -> !(bean instanceof NullBean)); } }; } @Nullable private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) { NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull); if (namedBean != null) { return namedBean.getBeanInstance(); } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull); } else if (parent != null) { ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType); if (args != null) { return parentProvider.getObject(args); } else { return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable()); } } return null; } //--------------------------------------------------------------------- // Implementation of ListableBeanFactory interface //--------------------------------------------------------------------- @Override public boolean containsBeanDefinition(String beanName) { Assert.notNull(beanName, "Bean name must not be null"); return this.beanDefinitionMap.containsKey(beanName); } @Override public int getBeanDefinitionCount() { return this.beanDefinitionMap.size(); } @Override public String[] getBeanDefinitionNames() { String[] frozenNames = this.frozenBeanDefinitionNames; if (frozenNames != null) { return frozenNames.clone(); } else { return StringUtils.toStringArray(this.beanDefinitionNames); } } @Override public String[] getBeanNamesForType(ResolvableType type) { return doGetBeanNamesForType(type, true, true); } @Override public String[] getBeanNamesForType(@Nullable Class<?> type) { return getBeanNamesForType(type, true, true); } @Override public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { if (!isConfigurationFrozen() || type == null || !allowEagerInit) { return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); } Map<Class<?>, String[]> cache = (includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType); String[] resolvedBeanNames = cache.get(type); if (resolvedBeanNames != null) { return resolvedBeanNames; } resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true); if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) { cache.put(type, resolvedBeanNames); } return resolvedBeanNames; } private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { List<String> result = new ArrayList<>(); // Check all bean definitions. for (String beanName : this.beanDefinitionNames) { // Only consider bean as eligible if the bean name // is not defined as alias for some other bean. if (!isAlias(beanName)) { try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Only check bean definition if it is complete. if (!mbd.isAbstract() && (allowEagerInit || (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) { // In case of FactoryBean, match object created by FactoryBean. boolean isFactoryBean = isFactoryBean(beanName, mbd); BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); boolean matchFound = (allowEagerInit || !isFactoryBean || (dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) && (includeNonSingletons || (dbd != null ? mbd.isSingleton() : isSingleton(beanName))) && isTypeMatch(beanName, type); if (!matchFound && isFactoryBean) { // In case of FactoryBean, try to match FactoryBean instance itself next. beanName = FACTORY_BEAN_PREFIX + beanName; matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type); } if (matchFound) { result.add(beanName); } } } catch (CannotLoadBeanClassException ex) { if (allowEagerInit) { throw ex; } // Probably a class name with a placeholder: let's ignore it for type matching purposes. if (logger.isTraceEnabled()) { logger.trace("Ignoring bean class loading failure for bean '" + beanName + "'", ex); } onSuppressedException(ex); } catch (BeanDefinitionStoreException ex) { if (allowEagerInit) { throw ex; } // Probably some metadata with a placeholder: let's ignore it for type matching purposes. if (logger.isTraceEnabled()) { logger.trace("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex); } onSuppressedException(ex); } } } // Check manually registered singletons too. for (String beanName : this.manualSingletonNames) { try { // In case of FactoryBean, match object created by FactoryBean. if (isFactoryBean(beanName)) { if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) { result.add(beanName); // Match found for this bean: do not match FactoryBean itself anymore. continue; } // In case of FactoryBean, try to match FactoryBean itself next. beanName = FACTORY_BEAN_PREFIX + beanName; } // Match raw bean instance (might be raw FactoryBean). if (isTypeMatch(beanName, type)) { result.add(beanName); } } catch (NoSuchBeanDefinitionException ex) { // Shouldn't happen - probably a result of circular reference resolution... if (logger.isTraceEnabled()) { logger.trace("Failed to check manually registered singleton with name '" + beanName + "'", ex); } } } return StringUtils.toStringArray(result); } /** * Check whether the specified bean would need to be eagerly initialized * in order to determine its type. * @param factoryBeanName a factory-bean reference that the bean definition * defines a factory method for * @return whether eager initialization is necessary */ private boolean requiresEagerInitForType(@Nullable String factoryBeanName) { return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName)); } @Override public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException { return getBeansOfType(type, true, true); } @Override @SuppressWarnings("unchecked") public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit); Map<String, T> result = new LinkedHashMap<>(beanNames.length); for (String beanName : beanNames) { try { Object beanInstance = getBean(beanName); if (!(beanInstance instanceof NullBean)) { result.put(beanName, (T) beanInstance); } } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationException bce = (BeanCreationException) rootCause; String exBeanName = bce.getBeanName(); if (exBeanName != null && isCurrentlyInCreation(exBeanName)) { if (logger.isTraceEnabled()) { logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " + ex.getMessage()); } onSuppressedException(ex); // Ignore: indicates a circular reference when autowiring constructors. // We want to find matches other than the currently created bean itself. continue; } } throw ex; } } return result; } @Override public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) { List<String> result = new ArrayList<>(); for (String beanName : this.beanDefinitionNames) { BeanDefinition beanDefinition = getBeanDefinition(beanName); if (!beanDefinition.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) { result.add(beanName); } } for (String beanName : this.manualSingletonNames) { if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) { result.add(beanName); } } return StringUtils.toStringArray(result); } @Override public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) { String[] beanNames = getBeanNamesForAnnotation(annotationType); Map<String, Object> result = new LinkedHashMap<>(beanNames.length); for (String beanName : beanNames) { Object beanInstance = getBean(beanName); if (!(beanInstance instanceof NullBean)) { result.put(beanName, beanInstance); } } return result; } /** * Find a {@link Annotation} of {@code annotationType} on the specified * bean, traversing its interfaces and super classes if no annotation can be * found on the given class itself, as well as checking its raw bean class * if not found on the exposed bean reference (e.g. in case of a proxy). */ @Override @Nullable public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException{ A ann = null; Class<?> beanType = getType(beanName); if (beanType != null) { ann = AnnotationUtils.findAnnotation(beanType, annotationType); } if (ann == null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; if (abd.hasBeanClass()) { ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType); } } } return ann; } //--------------------------------------------------------------------- // Implementation of ConfigurableListableBeanFactory interface //--------------------------------------------------------------------- @Override public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) { Assert.notNull(dependencyType, "Dependency type must not be null"); if (autowiredValue != null) { if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) { throw new IllegalArgumentException("Value [" + autowiredValue + "] does not implement specified dependency type [" + dependencyType.getName() + "]"); } this.resolvableDependencies.put(dependencyType, autowiredValue); } } @Override public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) throws NoSuchBeanDefinitionException { return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver()); } /** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) throws NoSuchBeanDefinitionException { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); if (containsBeanDefinition(beanDefinitionName)) { return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver); } else if (containsSingleton(beanName)) { return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver); } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver); } else if (parent instanceof ConfigurableListableBeanFactory) { // If no DefaultListableBeanFactory, can't pass the resolver along. return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor); } else { return true; } } /** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param mbd the merged bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); resolveBeanClass(mbd, beanDefinitionName); if (mbd.isFactoryMethodUnique) { boolean resolve; synchronized (mbd.constructorArgumentLock) { resolve = (mbd.resolvedConstructorOrFactoryMethod == null); } if (resolve) { new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd); } } return resolver.isAutowireCandidate( new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor); } @Override public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { BeanDefinition bd = this.beanDefinitionMap.get(beanName); if (bd == null) { if (logger.isTraceEnabled()) { logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } return bd; } @Override public Iterator<String> getBeanNamesIterator() { CompositeIterator<String> iterator = new CompositeIterator<>(); iterator.add(this.beanDefinitionNames.iterator()); iterator.add(this.manualSingletonNames.iterator()); return iterator; } @Override public void clearMetadataCache() { super.clearMetadataCache(); clearByTypeCache(); } @Override public void freezeConfiguration() { this.configurationFrozen = true; this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames); } @Override public boolean isConfigurationFrozen() { return this.configurationFrozen; } /** * Considers all beans as eligible for metadata caching * if the factory's configuration has been marked as frozen. * @see #freezeConfiguration() */ @Override protected boolean isBeanEligibleForMetadataCaching(String beanName) { return (this.configurationFrozen || super.isBeanEligibleForMetadataCaching(beanName)); } @Override public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } // Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... for (String beanName : beanNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { final FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } } else { getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { smartSingleton.afterSingletonsInstantiated(); return null; }, getAccessControlContext()); } else { smartSingleton.afterSingletonsInstantiated(); } } } } //--------------------------------------------------------------------- // Implementation of BeanDefinitionRegistry interface //--------------------------------------------------------------------- @Override public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { Assert.hasText(beanName, "Bean name must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); if (beanDefinition instanceof AbstractBeanDefinition) { try { ((AbstractBeanDefinition) beanDefinition).validate(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", ex); } } BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); if (existingDefinition != null) { if (!isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition); } else if (existingDefinition.getRole() < beanDefinition.getRole()) { // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE if (logger.isInfoEnabled()) { logger.info("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } else if (!beanDefinition.equals(existingDefinition)) { if (logger.isDebugEnabled()) { logger.debug("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } else { if (logger.isTraceEnabled()) { logger.trace("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } this.beanDefinitionMap.put(beanName, beanDefinition); } else { if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { this.beanDefinitionMap.put(beanName, beanDefinition); List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1); updatedDefinitions.addAll(this.beanDefinitionNames); updatedDefinitions.add(beanName); this.beanDefinitionNames = updatedDefinitions; if (this.manualSingletonNames.contains(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames); updatedSingletons.remove(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } this.frozenBeanDefinitionNames = null; } if (existingDefinition != null || containsSingleton(beanName)) { resetBeanDefinition(beanName); } } @Override public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { Assert.hasText(beanName, "'beanName' must not be empty"); BeanDefinition bd = this.beanDefinitionMap.remove(beanName); if (bd == null) { if (logger.isTraceEnabled()) { logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames); updatedDefinitions.remove(beanName); this.beanDefinitionNames = updatedDefinitions; } } else { // Still in startup registration phase this.beanDefinitionNames.remove(beanName); } this.frozenBeanDefinitionNames = null; resetBeanDefinition(beanName); } /** * Reset all bean definition caches for the given bean, * including the caches of beans that are derived from it. * <p>Called after an existing bean definition has been replaced or removed, * triggering {@link #clearMergedBeanDefinition}, {@link #destroySingleton} * and {@link MergedBeanDefinitionPostProcessor#resetBeanDefinition} on the * given bean and on all bean definitions that have the given bean as parent. * @param beanName the name of the bean to reset * @see #registerBeanDefinition * @see #removeBeanDefinition */ protected void resetBeanDefinition(String beanName) { // Remove the merged bean definition for the given bean, if already created. clearMergedBeanDefinition(beanName); // Remove corresponding bean from singleton cache, if any. Shouldn't usually // be necessary, rather just meant for overriding a context's default beans // (e.g. the default StaticMessageSource in a StaticApplicationContext). destroySingleton(beanName); // Notify all post-processors that the specified bean definition has been reset. for (BeanPostProcessor processor : getBeanPostProcessors()) { if (processor instanceof MergedBeanDefinitionPostProcessor) { ((MergedBeanDefinitionPostProcessor) processor).resetBeanDefinition(beanName); } } // Reset all bean definitions that have the given bean as parent (recursively). for (String bdName : this.beanDefinitionNames) { if (!beanName.equals(bdName)) { BeanDefinition bd = this.beanDefinitionMap.get(bdName); if (beanName.equals(bd.getParentName())) { resetBeanDefinition(bdName); } } } } /** * Only allows alias overriding if bean definition overriding is allowed. */ @Override protected boolean allowAliasOverriding() { return isAllowBeanDefinitionOverriding(); } @Override public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { super.registerSingleton(beanName, singletonObject); if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { if (!this.beanDefinitionMap.containsKey(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1); updatedSingletons.addAll(this.manualSingletonNames); updatedSingletons.add(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase if (!this.beanDefinitionMap.containsKey(beanName)) { this.manualSingletonNames.add(beanName); } } clearByTypeCache(); } @Override public void destroySingleton(String beanName) { super.destroySingleton(beanName); this.manualSingletonNames.remove(beanName); clearByTypeCache(); } @Override public void destroySingletons() { super.destroySingletons(); this.manualSingletonNames.clear(); clearByTypeCache(); } /** * Remove any assumptions about by-type mappings. */ private void clearByTypeCache() { this.allBeanNamesByType.clear(); this.singletonBeanNamesByType.clear(); } //--------------------------------------------------------------------- // Dependency resolution functionality //--------------------------------------------------------------------- @Override public <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException { NamedBeanHolder<T> namedBean = resolveNamedBean(ResolvableType.forRawClass(requiredType), null, false); if (namedBean != null) { return namedBean; } BeanFactory parent = getParentBeanFactory(); if (parent instanceof AutowireCapableBeanFactory) { return ((AutowireCapableBeanFactory) parent).resolveNamedBean(requiredType); } throw new NoSuchBeanDefinitionException(requiredType); } @SuppressWarnings("unchecked") @Nullable private <T> NamedBeanHolder<T> resolveNamedBean( ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) throws BeansException { Assert.notNull(requiredType, "Required type must not be null"); Class<?> clazz = requiredType.getRawClass(); Assert.notNull(clazz, "Required type must have a raw Class"); String[] candidateNames = getBeanNamesForType(requiredType); if (candidateNames.length > 1) { List<String> autowireCandidates = new ArrayList<>(candidateNames.length); for (String beanName : candidateNames) { if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) { autowireCandidates.add(beanName); } } if (!autowireCandidates.isEmpty()) { candidateNames = StringUtils.toStringArray(autowireCandidates); } } if (candidateNames.length == 1) { String beanName = candidateNames[0]; return new NamedBeanHolder<>(beanName, (T) getBean(beanName, clazz, args)); } else if (candidateNames.length > 1) { Map<String, Object> candidates = new LinkedHashMap<>(candidateNames.length); for (String beanName : candidateNames) { if (containsSingleton(beanName) && args == null) { Object beanInstance = getBean(beanName); candidates.put(beanName, (beanInstance instanceof NullBean ? null : beanInstance)); } else { candidates.put(beanName, getType(beanName)); } } String candidateName = determinePrimaryCandidate(candidates, clazz); if (candidateName == null) { candidateName = determineHighestPriorityCandidate(candidates, clazz); } if (candidateName != null) { Object beanInstance = candidates.get(candidateName); if (beanInstance == null || beanInstance instanceof Class) { beanInstance = getBean(candidateName, clazz, args); } return new NamedBeanHolder<>(candidateName, (T) beanInstance); } if (!nonUniqueAsNull) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet()); } } return null; } @Override @Nullable public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { return new DependencyObjectProvider(descriptor, requestingBeanName); } else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); } else { Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } } @Nullable public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } Class<?> type = descriptor.getDependencyType(); Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); } else { // In case of an optional Collection/Map, silently ignore a non-unique case: // possibly it was meant to be an empty collection of multiple regular beans // (before 4.3 in particular when we didn't even look for collection beans). return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { // We have exactly one match. Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } if (autowiredBeanNames != null) { autowiredBeanNames.add(autowiredBeanName); } if (instanceCandidate instanceof Class) { instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; if (result instanceof NullBean) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } result = null; } if (!ClassUtils.isAssignableValue(type, result)) { throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); } return result; } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } } @Nullable private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) { Class<?> type = descriptor.getDependencyType(); if (descriptor.isStreamAccess()) { Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, new MultiElementDescriptor(descriptor, false)); if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans.values().stream(); } else if (type.isArray()) { Class<?> componentType = type.getComponentType(); ResolvableType resolvableType = descriptor.getResolvableType(); Class<?> resolvedArrayType = resolvableType.resolve(); if (resolvedArrayType != null && resolvedArrayType != type) { type = resolvedArrayType; componentType = resolvableType.getComponentType().resolve(); } if (componentType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, new MultiElementDescriptor(descriptor, true)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof Object[]) { Arrays.sort((Object[]) result, adaptDependencyComparator(matchingBeans)); } return result; } else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric(); if (elementType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, new MultiElementDescriptor(descriptor, true)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof List) { ((List<?>) result).sort(adaptDependencyComparator(matchingBeans)); } return result; } else if (Map.class == type) { ResolvableType mapType = descriptor.getResolvableType().asMap(); Class<?> keyType = mapType.resolveGeneric(0); if (String.class != keyType) { return null; } Class<?> valueType = mapType.resolveGeneric(1); if (valueType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, new MultiElementDescriptor(descriptor, true)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans; } else { return null; } } private boolean isRequired(DependencyDescriptor descriptor) { return getAutowireCandidateResolver().isRequired(descriptor); } private boolean indicatesMultipleBeans(Class<?> type) { return (type.isArray() || (type.isInterface() && (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)))); } @Nullable private Comparator<Object> adaptDependencyComparator(Map<String, Object> matchingBeans) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).withSourceProvider( createFactoryAwareOrderSourceProvider(matchingBeans)); } else { return comparator; } } private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, Object> beans) { IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>(); beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName)); return new FactoryAwareOrderSourceProvider(instancesToBeanNames); } /** * Find bean instances that match the required type. * Called during autowiring for the specified bean. * @param beanName the name of the bean that is about to be wired * @param requiredType the actual type of bean to look for * (may be an array component type or collection element type) * @param descriptor the descriptor of the dependency to resolve * @return a Map of candidate names and candidate instances that match * the required type (never {@code null}) * @throws BeansException in case of errors * @see #autowireByType * @see #autowireConstructor */ protected Map<String, Object> findAutowireCandidates( @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) { String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this, requiredType, true, descriptor.isEager()); Map<String, Object> result = new LinkedHashMap<>(candidateNames.length); for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) { Class<?> autowiringType = classObjectEntry.getKey(); if (autowiringType.isAssignableFrom(requiredType)) { Object autowiringValue = classObjectEntry.getValue(); autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); if (requiredType.isInstance(autowiringValue)) { result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); break; } } } for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty() && !indicatesMultipleBeans(requiredType)) { // Consider fallback matches if the first pass failed to find anything... DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty()) { // Consider self references as a final pass... // but in the case of a dependency collection, not the very same bean itself. for (String candidate : candidateNames) { if (isSelfReference(beanName, candidate) && (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } } } return result; } /** * Add an entry to the candidate map: a bean instance if available or just the resolved * type, preventing early bean initialization ahead of primary candidate selection. */ private void addCandidateEntry(Map<String, Object> candidates, String candidateName, DependencyDescriptor descriptor, Class<?> requiredType) { if (descriptor instanceof MultiElementDescriptor) { Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); if (!(beanInstance instanceof NullBean)) { candidates.put(candidateName, beanInstance); } } else if (containsSingleton(candidateName)) { Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance)); } else { candidates.put(candidateName, getType(candidateName)); } } /** * Determine the autowire candidate in the given set of beans. * <p>Looks for {@code @Primary} and {@code @Priority} (in that order). * @param candidates a Map of candidate names and candidate instances * that match the required type, as returned by {@link #findAutowireCandidates} * @param descriptor the target dependency to match against * @return the name of the autowire candidate, or {@code null} if none found */ @Nullable protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) { Class<?> requiredType = descriptor.getDependencyType(); String primaryCandidate = determinePrimaryCandidate(candidates, requiredType); if (primaryCandidate != null) { return primaryCandidate; } String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType); if (priorityCandidate != null) { return priorityCandidate; } // Fallback for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateName = entry.getKey(); Object beanInstance = entry.getValue(); if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) || matchesBeanName(candidateName, descriptor.getDependencyName())) { return candidateName; } } return null; } /** * Determine the primary candidate in the given set of beans. * @param candidates a Map of candidate names and candidate instances * (or candidate classes if not created yet) that match the required type * @param requiredType the target dependency type to match against * @return the name of the primary candidate, or {@code null} if none found * @see #isPrimary(String, Object) */ @Nullable protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) { String primaryBeanName = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); if (isPrimary(candidateBeanName, beanInstance)) { if (primaryBeanName != null) { boolean candidateLocal = containsBeanDefinition(candidateBeanName); boolean primaryLocal = containsBeanDefinition(primaryBeanName); if (candidateLocal && primaryLocal) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "more than one 'primary' bean found among candidates: " + candidates.keySet()); } else if (candidateLocal) { primaryBeanName = candidateBeanName; } } else { primaryBeanName = candidateBeanName; } } } return primaryBeanName; } /** * Determine the candidate with the highest priority in the given set of beans. * <p>Based on {@code @javax.annotation.Priority}. As defined by the related * {@link org.springframework.core.Ordered} interface, the lowest value has * the highest priority. * @param candidates a Map of candidate names and candidate instances * (or candidate classes if not created yet) that match the required type * @param requiredType the target dependency type to match against * @return the name of the candidate with the highest priority, * or {@code null} if none found * @see #getPriority(Object) */ @Nullable protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) { String highestPriorityBeanName = null; Integer highestPriority = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); if (beanInstance != null) { Integer candidatePriority = getPriority(beanInstance); if (candidatePriority != null) { if (highestPriorityBeanName != null) { if (candidatePriority.equals(highestPriority)) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "Multiple beans found with the same priority ('" + highestPriority + "') among candidates: " + candidates.keySet()); } else if (candidatePriority < highestPriority) { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } else { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } } } return highestPriorityBeanName; } /** * Return whether the bean definition for the given bean name has been * marked as a primary bean. * @param beanName the name of the bean * @param beanInstance the corresponding bean instance (can be null) * @return whether the given bean qualifies as primary */ protected boolean isPrimary(String beanName, Object beanInstance) { if (containsBeanDefinition(beanName)) { return getMergedLocalBeanDefinition(beanName).isPrimary(); } BeanFactory parent = getParentBeanFactory(); return (parent instanceof DefaultListableBeanFactory && ((DefaultListableBeanFactory) parent).isPrimary(beanName, beanInstance)); } /** * Return the priority assigned for the given bean instance by * the {@code javax.annotation.Priority} annotation. * <p>The default implementation delegates to the specified * {@link #setDependencyComparator dependency comparator}, checking its * {@link OrderComparator#getPriority method} if it is an extension of * Spring's common {@link OrderComparator} - typically, an * {@link org.springframework.core.annotation.AnnotationAwareOrderComparator}. * If no such comparator is present, this implementation returns {@code null}. * @param beanInstance the bean instance to check (can be {@code null}) * @return the priority assigned to that bean or {@code null} if none is set */ @Nullable protected Integer getPriority(Object beanInstance) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).getPriority(beanInstance); } return null; } /** * Determine whether the given candidate name matches the bean name or the aliases * stored in this bean definition. */ protected boolean matchesBeanName(String beanName, @Nullable String candidateName) { return (candidateName != null && (candidateName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), candidateName))); } /** * Determine whether the given beanName/candidateName pair indicates a self reference, * i.e. whether the candidate points back to the original bean or to a factory method * on the original bean. */ private boolean isSelfReference(@Nullable String beanName, @Nullable String candidateName) { return (beanName != null && candidateName != null && (beanName.equals(candidateName) || (containsBeanDefinition(candidateName) && beanName.equals(getMergedLocalBeanDefinition(candidateName).getFactoryBeanName())))); } /** * Raise a NoSuchBeanDefinitionException or BeanNotOfRequiredTypeException * for an unresolvable dependency. */ private void raiseNoMatchingBeanFound( Class<?> type, ResolvableType resolvableType, DependencyDescriptor descriptor) throws BeansException { checkBeanNotOfRequiredType(type, descriptor); throw new NoSuchBeanDefinitionException(resolvableType, "expected at least 1 bean which qualifies as autowire candidate. " + "Dependency annotations: " + ObjectUtils.nullSafeToString(descriptor.getAnnotations())); } /** * Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable, * i.e. if the target type of the bean would match but an exposed proxy doesn't. */ private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) { for (String beanName : this.beanDefinitionNames) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class<?> targetType = mbd.getTargetType(); if (targetType != null && type.isAssignableFrom(targetType) && isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) { // Probably a proxy interfering with target type match -> throw meaningful exception. Object beanInstance = getSingleton(beanName, false); Class<?> beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class ? beanInstance.getClass() : predictBeanType(beanName, mbd)); if (beanType != null && !type.isAssignableFrom(beanType)) { throw new BeanNotOfRequiredTypeException(beanName, type, beanType); } } } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor); } } /** * Create an {@link Optional} wrapper for the specified dependency. */ private Optional<?> createOptionalDependency( DependencyDescriptor descriptor, @Nullable String beanName, final Object... args) { DependencyDescriptor descriptorToUse = new NestedDependencyDescriptor(descriptor) { @Override public boolean isRequired() { return false; } @Override public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return (!ObjectUtils.isEmpty(args) ? beanFactory.getBean(beanName, args) : super.resolveCandidate(beanName, requiredType, beanFactory)); } }; return Optional.ofNullable(doResolveDependency(descriptorToUse, beanName, null, null)); } @Override public String toString() { StringBuilder sb = new StringBuilder(ObjectUtils.identityToString(this)); sb.append(": defining beans ["); sb.append(StringUtils.collectionToCommaDelimitedString(this.beanDefinitionNames)); sb.append("]; "); BeanFactory parent = getParentBeanFactory(); if (parent == null) { sb.append("root of factory hierarchy"); } else { sb.append("parent: ").append(ObjectUtils.identityToString(parent)); } return sb.toString(); } //--------------------------------------------------------------------- // Serialization support //--------------------------------------------------------------------- private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { throw new NotSerializableException("DefaultListableBeanFactory itself is not deserializable - " + "just a SerializedBeanFactoryReference is"); } protected Object writeReplace() throws ObjectStreamException { if (this.serializationId != null) { return new SerializedBeanFactoryReference(this.serializationId); } else { throw new NotSerializableException("DefaultListableBeanFactory has no serialization id"); } } /** * Minimal id reference to the factory. * Resolved to the actual factory instance on deserialization. */ private static class SerializedBeanFactoryReference implements Serializable { private final String id; public SerializedBeanFactoryReference(String id) { this.id = id; } private Object readResolve() { Reference<?> ref = serializableFactories.get(this.id); if (ref != null) { Object result = ref.get(); if (result != null) { return result; } } // Lenient fallback: dummy factory in case of original factory not found... return new DefaultListableBeanFactory(); } } /** * A dependency descriptor marker for nested elements. */ private static class NestedDependencyDescriptor extends DependencyDescriptor { public NestedDependencyDescriptor(DependencyDescriptor original) { super(original); increaseNestingLevel(); } } /** * A dependency descriptor marker for multiple elements. */ private static class MultiElementDescriptor extends DependencyDescriptor { public MultiElementDescriptor(DependencyDescriptor original, boolean nested) { super(original); if (nested) { increaseNestingLevel(); } } } private interface BeanObjectProvider<T> extends ObjectProvider<T>, Serializable { } /** * Serializable ObjectFactory/ObjectProvider for lazy resolution of a dependency. */ private class DependencyObjectProvider implements BeanObjectProvider<Object> { private final DependencyDescriptor descriptor; private final boolean optional; @Nullable private final String beanName; public DependencyObjectProvider(DependencyDescriptor descriptor, @Nullable String beanName) { this.descriptor = new NestedDependencyDescriptor(descriptor); this.optional = (this.descriptor.getDependencyType() == Optional.class); this.beanName = beanName; } @Override public Object getObject() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { Object result = doResolveDependency(this.descriptor, this.beanName, null, null); if (result == null) { throw new NoSuchBeanDefinitionException(this.descriptor.getResolvableType()); } return result; } } @Override public Object getObject(final Object... args) throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName, args); } else { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return beanFactory.getBean(beanName, args); } }; Object result = doResolveDependency(descriptorToUse, this.beanName, null, null); if (result == null) { throw new NoSuchBeanDefinitionException(this.descriptor.getResolvableType()); } return result; } } @Override @Nullable public Object getIfAvailable() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public boolean isRequired() { return false; } }; return doResolveDependency(descriptorToUse, this.beanName, null, null); } } @Override @Nullable public Object getIfUnique() throws BeansException { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public boolean isRequired() { return false; } @Override @Nullable public Object resolveNotUnique(ResolvableType type, Map<String, Object> matchingBeans) { return null; } }; if (this.optional) { return createOptionalDependency(descriptorToUse, this.beanName); } else { return doResolveDependency(descriptorToUse, this.beanName, null, null); } } @Nullable protected Object getValue() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { return doResolveDependency(this.descriptor, this.beanName, null, null); } } @SuppressWarnings("unchecked") @Override public Stream<Object> stream() { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public boolean isStreamAccess() { return true; } }; Object result = doResolveDependency(descriptorToUse, this.beanName, null, null); if (result instanceof Stream) { return (Stream<Object>) result; } else if (result instanceof Collection) { return ((Collection<Object>) result).stream(); } else { return (result != null ? Stream.of(result) : Stream.empty()); } } } /** * Separate inner class for avoiding a hard dependency on the {@code javax.inject} API. * Actual {@code javax.inject.Provider} implementation is nested here in order to make it * invisible for Graal's introspection of DefaultListableBeanFactory's nested classes. */ private class Jsr330Factory implements Serializable { public Object createDependencyProvider(DependencyDescriptor descriptor, @Nullable String beanName) { return new Jsr330Provider(descriptor, beanName); } private class Jsr330Provider extends DependencyObjectProvider implements Provider<Object> { public Jsr330Provider(DependencyDescriptor descriptor, @Nullable String beanName) { super(descriptor, beanName); } @Override @Nullable public Object get() throws BeansException { return getValue(); } } } /** * An {@link org.springframework.core.OrderComparator.OrderSourceProvider} implementation * that is aware of the bean metadata of the instances to sort. * <p>Lookup for the method factory of an instance to sort, if any, and let the * comparator retrieve the {@link org.springframework.core.annotation.Order} * value defined on it. This essentially allows for the following construct: */ private class FactoryAwareOrderSourceProvider implements OrderComparator.OrderSourceProvider { private final Map<Object, String> instancesToBeanNames; public FactoryAwareOrderSourceProvider(Map<Object, String> instancesToBeanNames) { this.instancesToBeanNames = instancesToBeanNames; } @Override @Nullable public Object getOrderSource(Object obj) { RootBeanDefinition beanDefinition = getRootBeanDefinition(this.instancesToBeanNames.get(obj)); if (beanDefinition == null) { return null; } List<Object> sources = new ArrayList<>(2); Method factoryMethod = beanDefinition.getResolvedFactoryMethod(); if (factoryMethod != null) { sources.add(factoryMethod); } Class<?> targetType = beanDefinition.getTargetType(); if (targetType != null && targetType != obj.getClass()) { sources.add(targetType); } return sources.toArray(); } @Nullable private RootBeanDefinition getRootBeanDefinition(@Nullable String beanName) { if (beanName != null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof RootBeanDefinition) { return (RootBeanDefinition) bd; } } return null; } } }
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
/* * Copyright 2002-2018 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.springframework.beans.factory.support; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.Iterator; 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.concurrent.ConcurrentHashMap; import java.util.stream.Stream; import javax.inject.Provider; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.beans.factory.CannotLoadBeanClassException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InjectionPoint; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartFactoryBean; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.config.NamedBeanHolder; import org.springframework.core.OrderComparator; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CompositeIterator; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Spring's default implementation of the {@link ConfigurableListableBeanFactory} * and {@link BeanDefinitionRegistry} interfaces: a full-fledged bean factory * based on bean definition metadata, extensible through post-processors. * * <p>Typical usage is registering all bean definitions first (possibly read * from a bean definition file), before accessing beans. Bean lookup by name * is therefore an inexpensive operation in a local bean definition table, * operating on pre-resolved bean definition metadata objects. * * <p>Note that readers for specific bean definition formats are typically * implemented separately rather than as bean factory subclasses: * see for example {@link PropertiesBeanDefinitionReader} and * {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}. * * <p>For an alternative implementation of the * {@link org.springframework.beans.factory.ListableBeanFactory} interface, * have a look at {@link StaticListableBeanFactory}, which manages existing * bean instances rather than creating new ones based on bean definitions. * * @author Rod Johnson * @author Juergen Hoeller * @author Sam Brannen * @author Costin Leau * @author Chris Beams * @author Phillip Webb * @author Stephane Nicoll * @since 16 April 2001 * @see #registerBeanDefinition * @see #addBeanPostProcessor * @see #getBean * @see #resolveDependency */ @SuppressWarnings("serial") public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable { @Nullable private static Class<?> javaxInjectProviderClass; static { try { javaxInjectProviderClass = ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader()); } catch (ClassNotFoundException ex) { // JSR-330 API not available - Provider interface simply not supported then. javaxInjectProviderClass = null; } } /** Map from serialized id to factory instance. */ private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories = new ConcurrentHashMap<>(8); /** Optional id for this factory, for serialization purposes. */ @Nullable private String serializationId; /** Whether to allow re-registration of a different definition with the same name. */ private boolean allowBeanDefinitionOverriding = true; /** Whether to allow eager class loading even for lazy-init beans. */ private boolean allowEagerClassLoading = true; /** Optional OrderComparator for dependency Lists and arrays. */ @Nullable private Comparator<Object> dependencyComparator; /** Resolver to use for checking if a bean definition is an autowire candidate. */ private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver(); /** Map from dependency type to corresponding autowired value. */ private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16); /** Map of bean definition objects, keyed by bean name. */ private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256); /** Map of singleton and non-singleton bean names, keyed by dependency type. */ private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64); /** Map of singleton-only bean names, keyed by dependency type. */ private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64); /** List of bean definition names, in registration order. */ private volatile List<String> beanDefinitionNames = new ArrayList<>(256); /** List of names of manually registered singletons, in registration order. */ private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16); /** Cached array of bean definition names in case of frozen configuration. */ @Nullable private volatile String[] frozenBeanDefinitionNames; /** Whether bean definition metadata may be cached for all beans. */ private volatile boolean configurationFrozen = false; /** * Create a new DefaultListableBeanFactory. */ public DefaultListableBeanFactory() { super(); } /** * Create a new DefaultListableBeanFactory with the given parent. * @param parentBeanFactory the parent BeanFactory */ public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) { super(parentBeanFactory); } /** * Specify an id for serialization purposes, allowing this BeanFactory to be * deserialized from this id back into the BeanFactory object, if needed. */ public void setSerializationId(@Nullable String serializationId) { if (serializationId != null) { serializableFactories.put(serializationId, new WeakReference<>(this)); } else if (this.serializationId != null) { serializableFactories.remove(this.serializationId); } this.serializationId = serializationId; } /** * Return an id for serialization purposes, if specified, allowing this BeanFactory * to be deserialized from this id back into the BeanFactory object, if needed. * @since 4.1.2 */ @Nullable public String getSerializationId() { return this.serializationId; } /** * Set whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * If not, an exception will be thrown. This also applies to overriding aliases. * <p>Default is "true". * @see #registerBeanDefinition */ public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } /** * Return whether it should be allowed to override bean definitions by registering * a different definition with the same name, automatically replacing the former. * @since 4.1.2 */ public boolean isAllowBeanDefinitionOverriding() { return this.allowBeanDefinitionOverriding; } /** * Set whether the factory is allowed to eagerly load bean classes * even for bean definitions that are marked as "lazy-init". * <p>Default is "true". Turn this flag off to suppress class loading * for lazy-init beans unless such a bean is explicitly requested. * In particular, by-type lookups will then simply ignore bean definitions * without resolved class name, instead of loading the bean classes on * demand just to perform a type check. * @see AbstractBeanDefinition#setLazyInit */ public void setAllowEagerClassLoading(boolean allowEagerClassLoading) { this.allowEagerClassLoading = allowEagerClassLoading; } /** * Return whether the factory is allowed to eagerly load bean classes * even for bean definitions that are marked as "lazy-init". * @since 4.1.2 */ public boolean isAllowEagerClassLoading() { return this.allowEagerClassLoading; } /** * Set a {@link java.util.Comparator} for dependency Lists and arrays. * @since 4.0 * @see org.springframework.core.OrderComparator * @see org.springframework.core.annotation.AnnotationAwareOrderComparator */ public void setDependencyComparator(@Nullable Comparator<Object> dependencyComparator) { this.dependencyComparator = dependencyComparator; } /** * Return the dependency comparator for this BeanFactory (may be {@code null}. * @since 4.0 */ @Nullable public Comparator<Object> getDependencyComparator() { return this.dependencyComparator; } /** * Set a custom autowire candidate resolver for this BeanFactory to use * when deciding whether a bean definition should be considered as a * candidate for autowiring. */ public void setAutowireCandidateResolver(final AutowireCandidateResolver autowireCandidateResolver) { Assert.notNull(autowireCandidateResolver, "AutowireCandidateResolver must not be null"); if (autowireCandidateResolver instanceof BeanFactoryAware) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(DefaultListableBeanFactory.this); return null; }, getAccessControlContext()); } else { ((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(this); } } this.autowireCandidateResolver = autowireCandidateResolver; } /** * Return the autowire candidate resolver for this BeanFactory (never {@code null}). */ public AutowireCandidateResolver getAutowireCandidateResolver() { return this.autowireCandidateResolver; } @Override public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { super.copyConfigurationFrom(otherFactory); if (otherFactory instanceof DefaultListableBeanFactory) { DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory; this.allowBeanDefinitionOverriding = otherListableFactory.allowBeanDefinitionOverriding; this.allowEagerClassLoading = otherListableFactory.allowEagerClassLoading; this.dependencyComparator = otherListableFactory.dependencyComparator; // A clone of the AutowireCandidateResolver since it is potentially BeanFactoryAware... setAutowireCandidateResolver(BeanUtils.instantiateClass(getAutowireCandidateResolver().getClass())); // Make resolvable dependencies (e.g. ResourceLoader) available here as well... this.resolvableDependencies.putAll(otherListableFactory.resolvableDependencies); } } //--------------------------------------------------------------------- // Implementation of remaining BeanFactory methods //--------------------------------------------------------------------- @Override public <T> T getBean(Class<T> requiredType) throws BeansException { return getBean(requiredType, (Object[]) null); } @SuppressWarnings("unchecked") @Override public <T> T getBean(Class<T> requiredType, @Nullable Object... args) throws BeansException { Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return (T) resolved; } @Override public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) throws BeansException { return getBeanProvider(ResolvableType.forRawClass(requiredType)); } @SuppressWarnings("unchecked") @Override public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) { return new BeanObjectProvider<T>() { @Override public T getObject() throws BeansException { T resolved = resolveBean(requiredType, null, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return resolved; } @Override public T getObject(Object... args) throws BeansException { T resolved = resolveBean(requiredType, args, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return resolved; } @Override @Nullable public T getIfAvailable() throws BeansException { return resolveBean(requiredType, null, false); } @Override @Nullable public T getIfUnique() throws BeansException { return resolveBean(requiredType, null, true); } @Override public Stream<T> stream() { return Arrays.stream(getBeanNamesForType(requiredType)) .map(name -> (T) getBean(name)) .filter(bean -> !(bean instanceof NullBean)); } }; } @Nullable private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) { NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull); if (namedBean != null) { return namedBean.getBeanInstance(); } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull); } else if (parent != null) { ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType); if (args != null) { return parentProvider.getObject(args); } else { return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable()); } } return null; } //--------------------------------------------------------------------- // Implementation of ListableBeanFactory interface //--------------------------------------------------------------------- @Override public boolean containsBeanDefinition(String beanName) { Assert.notNull(beanName, "Bean name must not be null"); return this.beanDefinitionMap.containsKey(beanName); } @Override public int getBeanDefinitionCount() { return this.beanDefinitionMap.size(); } @Override public String[] getBeanDefinitionNames() { String[] frozenNames = this.frozenBeanDefinitionNames; if (frozenNames != null) { return frozenNames.clone(); } else { return StringUtils.toStringArray(this.beanDefinitionNames); } } @Override public String[] getBeanNamesForType(ResolvableType type) { return doGetBeanNamesForType(type, true, true); } @Override public String[] getBeanNamesForType(@Nullable Class<?> type) { return getBeanNamesForType(type, true, true); } @Override public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { if (!isConfigurationFrozen() || type == null || !allowEagerInit) { return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); } Map<Class<?>, String[]> cache = (includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType); String[] resolvedBeanNames = cache.get(type); if (resolvedBeanNames != null) { return resolvedBeanNames; } resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true); if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) { cache.put(type, resolvedBeanNames); } return resolvedBeanNames; } private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { List<String> result = new ArrayList<>(); // Check all bean definitions. for (String beanName : this.beanDefinitionNames) { // Only consider bean as eligible if the bean name // is not defined as alias for some other bean. if (!isAlias(beanName)) { try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Only check bean definition if it is complete. if (!mbd.isAbstract() && (allowEagerInit || (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) { // In case of FactoryBean, match object created by FactoryBean. boolean isFactoryBean = isFactoryBean(beanName, mbd); BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); boolean matchFound = (allowEagerInit || !isFactoryBean || (dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) && (includeNonSingletons || (dbd != null ? mbd.isSingleton() : isSingleton(beanName))) && isTypeMatch(beanName, type); if (!matchFound && isFactoryBean) { // In case of FactoryBean, try to match FactoryBean instance itself next. beanName = FACTORY_BEAN_PREFIX + beanName; matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type); } if (matchFound) { result.add(beanName); } } } catch (CannotLoadBeanClassException ex) { if (allowEagerInit) { throw ex; } // Probably a class name with a placeholder: let's ignore it for type matching purposes. if (logger.isTraceEnabled()) { logger.trace("Ignoring bean class loading failure for bean '" + beanName + "'", ex); } onSuppressedException(ex); } catch (BeanDefinitionStoreException ex) { if (allowEagerInit) { throw ex; } // Probably some metadata with a placeholder: let's ignore it for type matching purposes. if (logger.isTraceEnabled()) { logger.trace("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex); } onSuppressedException(ex); } } } // Check manually registered singletons too. for (String beanName : this.manualSingletonNames) { try { // In case of FactoryBean, match object created by FactoryBean. if (isFactoryBean(beanName)) { if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) { result.add(beanName); // Match found for this bean: do not match FactoryBean itself anymore. continue; } // In case of FactoryBean, try to match FactoryBean itself next. beanName = FACTORY_BEAN_PREFIX + beanName; } // Match raw bean instance (might be raw FactoryBean). if (isTypeMatch(beanName, type)) { result.add(beanName); } } catch (NoSuchBeanDefinitionException ex) { // Shouldn't happen - probably a result of circular reference resolution... if (logger.isTraceEnabled()) { logger.trace("Failed to check manually registered singleton with name '" + beanName + "'", ex); } } } return StringUtils.toStringArray(result); } /** * Check whether the specified bean would need to be eagerly initialized * in order to determine its type. * @param factoryBeanName a factory-bean reference that the bean definition * defines a factory method for * @return whether eager initialization is necessary */ private boolean requiresEagerInitForType(@Nullable String factoryBeanName) { return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName)); } @Override public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException { return getBeansOfType(type, true, true); } @Override @SuppressWarnings("unchecked") public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit); Map<String, T> result = new LinkedHashMap<>(beanNames.length); for (String beanName : beanNames) { try { Object beanInstance = getBean(beanName); if (!(beanInstance instanceof NullBean)) { result.put(beanName, (T) beanInstance); } } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationException bce = (BeanCreationException) rootCause; String exBeanName = bce.getBeanName(); if (exBeanName != null && isCurrentlyInCreation(exBeanName)) { if (logger.isTraceEnabled()) { logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " + ex.getMessage()); } onSuppressedException(ex); // Ignore: indicates a circular reference when autowiring constructors. // We want to find matches other than the currently created bean itself. continue; } } throw ex; } } return result; } @Override public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) { List<String> results = new ArrayList<>(); for (String beanName : this.beanDefinitionNames) { BeanDefinition beanDefinition = getBeanDefinition(beanName); if (!beanDefinition.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) { results.add(beanName); } } for (String beanName : this.manualSingletonNames) { if (!results.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) { results.add(beanName); } } return StringUtils.toStringArray(results); } @Override public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) { String[] beanNames = getBeanNamesForAnnotation(annotationType); Map<String, Object> results = new LinkedHashMap<>(beanNames.length); for (String beanName : beanNames) { results.put(beanName, getBean(beanName)); } return results; } /** * Find a {@link Annotation} of {@code annotationType} on the specified * bean, traversing its interfaces and super classes if no annotation can be * found on the given class itself, as well as checking its raw bean class * if not found on the exposed bean reference (e.g. in case of a proxy). */ @Override @Nullable public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException{ A ann = null; Class<?> beanType = getType(beanName); if (beanType != null) { ann = AnnotationUtils.findAnnotation(beanType, annotationType); } if (ann == null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; if (abd.hasBeanClass()) { ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType); } } } return ann; } //--------------------------------------------------------------------- // Implementation of ConfigurableListableBeanFactory interface //--------------------------------------------------------------------- @Override public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) { Assert.notNull(dependencyType, "Dependency type must not be null"); if (autowiredValue != null) { if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) { throw new IllegalArgumentException("Value [" + autowiredValue + "] does not implement specified dependency type [" + dependencyType.getName() + "]"); } this.resolvableDependencies.put(dependencyType, autowiredValue); } } @Override public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) throws NoSuchBeanDefinitionException { return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver()); } /** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) throws NoSuchBeanDefinitionException { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); if (containsBeanDefinition(beanDefinitionName)) { return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver); } else if (containsSingleton(beanName)) { return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver); } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver); } else if (parent instanceof ConfigurableListableBeanFactory) { // If no DefaultListableBeanFactory, can't pass the resolver along. return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor); } else { return true; } } /** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param mbd the merged bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); resolveBeanClass(mbd, beanDefinitionName); if (mbd.isFactoryMethodUnique) { boolean resolve; synchronized (mbd.constructorArgumentLock) { resolve = (mbd.resolvedConstructorOrFactoryMethod == null); } if (resolve) { new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd); } } return resolver.isAutowireCandidate( new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor); } @Override public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { BeanDefinition bd = this.beanDefinitionMap.get(beanName); if (bd == null) { if (logger.isTraceEnabled()) { logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } return bd; } @Override public Iterator<String> getBeanNamesIterator() { CompositeIterator<String> iterator = new CompositeIterator<>(); iterator.add(this.beanDefinitionNames.iterator()); iterator.add(this.manualSingletonNames.iterator()); return iterator; } @Override public void clearMetadataCache() { super.clearMetadataCache(); clearByTypeCache(); } @Override public void freezeConfiguration() { this.configurationFrozen = true; this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames); } @Override public boolean isConfigurationFrozen() { return this.configurationFrozen; } /** * Considers all beans as eligible for metadata caching * if the factory's configuration has been marked as frozen. * @see #freezeConfiguration() */ @Override protected boolean isBeanEligibleForMetadataCaching(String beanName) { return (this.configurationFrozen || super.isBeanEligibleForMetadataCaching(beanName)); } @Override public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } // Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... for (String beanName : beanNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { final FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } } else { getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { smartSingleton.afterSingletonsInstantiated(); return null; }, getAccessControlContext()); } else { smartSingleton.afterSingletonsInstantiated(); } } } } //--------------------------------------------------------------------- // Implementation of BeanDefinitionRegistry interface //--------------------------------------------------------------------- @Override public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { Assert.hasText(beanName, "Bean name must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); if (beanDefinition instanceof AbstractBeanDefinition) { try { ((AbstractBeanDefinition) beanDefinition).validate(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", ex); } } BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); if (existingDefinition != null) { if (!isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition); } else if (existingDefinition.getRole() < beanDefinition.getRole()) { // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE if (logger.isInfoEnabled()) { logger.info("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } else if (!beanDefinition.equals(existingDefinition)) { if (logger.isDebugEnabled()) { logger.debug("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } else { if (logger.isTraceEnabled()) { logger.trace("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } this.beanDefinitionMap.put(beanName, beanDefinition); } else { if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { this.beanDefinitionMap.put(beanName, beanDefinition); List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1); updatedDefinitions.addAll(this.beanDefinitionNames); updatedDefinitions.add(beanName); this.beanDefinitionNames = updatedDefinitions; if (this.manualSingletonNames.contains(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames); updatedSingletons.remove(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } this.frozenBeanDefinitionNames = null; } if (existingDefinition != null || containsSingleton(beanName)) { resetBeanDefinition(beanName); } } @Override public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { Assert.hasText(beanName, "'beanName' must not be empty"); BeanDefinition bd = this.beanDefinitionMap.remove(beanName); if (bd == null) { if (logger.isTraceEnabled()) { logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames); updatedDefinitions.remove(beanName); this.beanDefinitionNames = updatedDefinitions; } } else { // Still in startup registration phase this.beanDefinitionNames.remove(beanName); } this.frozenBeanDefinitionNames = null; resetBeanDefinition(beanName); } /** * Reset all bean definition caches for the given bean, * including the caches of beans that are derived from it. * <p>Called after an existing bean definition has been replaced or removed, * triggering {@link #clearMergedBeanDefinition}, {@link #destroySingleton} * and {@link MergedBeanDefinitionPostProcessor#resetBeanDefinition} on the * given bean and on all bean definitions that have the given bean as parent. * @param beanName the name of the bean to reset * @see #registerBeanDefinition * @see #removeBeanDefinition */ protected void resetBeanDefinition(String beanName) { // Remove the merged bean definition for the given bean, if already created. clearMergedBeanDefinition(beanName); // Remove corresponding bean from singleton cache, if any. Shouldn't usually // be necessary, rather just meant for overriding a context's default beans // (e.g. the default StaticMessageSource in a StaticApplicationContext). destroySingleton(beanName); // Notify all post-processors that the specified bean definition has been reset. for (BeanPostProcessor processor : getBeanPostProcessors()) { if (processor instanceof MergedBeanDefinitionPostProcessor) { ((MergedBeanDefinitionPostProcessor) processor).resetBeanDefinition(beanName); } } // Reset all bean definitions that have the given bean as parent (recursively). for (String bdName : this.beanDefinitionNames) { if (!beanName.equals(bdName)) { BeanDefinition bd = this.beanDefinitionMap.get(bdName); if (beanName.equals(bd.getParentName())) { resetBeanDefinition(bdName); } } } } /** * Only allows alias overriding if bean definition overriding is allowed. */ @Override protected boolean allowAliasOverriding() { return isAllowBeanDefinitionOverriding(); } @Override public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { super.registerSingleton(beanName, singletonObject); if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { if (!this.beanDefinitionMap.containsKey(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1); updatedSingletons.addAll(this.manualSingletonNames); updatedSingletons.add(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase if (!this.beanDefinitionMap.containsKey(beanName)) { this.manualSingletonNames.add(beanName); } } clearByTypeCache(); } @Override public void destroySingleton(String beanName) { super.destroySingleton(beanName); this.manualSingletonNames.remove(beanName); clearByTypeCache(); } @Override public void destroySingletons() { super.destroySingletons(); this.manualSingletonNames.clear(); clearByTypeCache(); } /** * Remove any assumptions about by-type mappings. */ private void clearByTypeCache() { this.allBeanNamesByType.clear(); this.singletonBeanNamesByType.clear(); } //--------------------------------------------------------------------- // Dependency resolution functionality //--------------------------------------------------------------------- @Override public <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException { NamedBeanHolder<T> namedBean = resolveNamedBean(ResolvableType.forRawClass(requiredType), null, false); if (namedBean != null) { return namedBean; } BeanFactory parent = getParentBeanFactory(); if (parent instanceof AutowireCapableBeanFactory) { return ((AutowireCapableBeanFactory) parent).resolveNamedBean(requiredType); } throw new NoSuchBeanDefinitionException(requiredType); } @SuppressWarnings("unchecked") @Nullable private <T> NamedBeanHolder<T> resolveNamedBean( ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) throws BeansException { Assert.notNull(requiredType, "Required type must not be null"); Class<?> clazz = requiredType.getRawClass(); Assert.notNull(clazz, "Required type must have a raw Class"); String[] candidateNames = getBeanNamesForType(requiredType); if (candidateNames.length > 1) { List<String> autowireCandidates = new ArrayList<>(candidateNames.length); for (String beanName : candidateNames) { if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) { autowireCandidates.add(beanName); } } if (!autowireCandidates.isEmpty()) { candidateNames = StringUtils.toStringArray(autowireCandidates); } } if (candidateNames.length == 1) { String beanName = candidateNames[0]; return new NamedBeanHolder<>(beanName, (T) getBean(beanName, clazz, args)); } else if (candidateNames.length > 1) { Map<String, Object> candidates = new LinkedHashMap<>(candidateNames.length); for (String beanName : candidateNames) { if (containsSingleton(beanName) && args == null) { Object beanInstance = getBean(beanName); candidates.put(beanName, (beanInstance instanceof NullBean ? null : beanInstance)); } else { candidates.put(beanName, getType(beanName)); } } String candidateName = determinePrimaryCandidate(candidates, clazz); if (candidateName == null) { candidateName = determineHighestPriorityCandidate(candidates, clazz); } if (candidateName != null) { Object beanInstance = candidates.get(candidateName); if (beanInstance == null || beanInstance instanceof Class) { beanInstance = getBean(candidateName, clazz, args); } return new NamedBeanHolder<>(candidateName, (T) beanInstance); } if (!nonUniqueAsNull) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet()); } } return null; } @Override @Nullable public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { return new DependencyObjectProvider(descriptor, requestingBeanName); } else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); } else { Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } } @Nullable public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } Class<?> type = descriptor.getDependencyType(); Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); } else { // In case of an optional Collection/Map, silently ignore a non-unique case: // possibly it was meant to be an empty collection of multiple regular beans // (before 4.3 in particular when we didn't even look for collection beans). return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { // We have exactly one match. Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } if (autowiredBeanNames != null) { autowiredBeanNames.add(autowiredBeanName); } if (instanceCandidate instanceof Class) { instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; if (result instanceof NullBean) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } result = null; } if (!ClassUtils.isAssignableValue(type, result)) { throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); } return result; } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } } @Nullable private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) { Class<?> type = descriptor.getDependencyType(); if (descriptor.isStreamAccess()) { Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, new MultiElementDescriptor(descriptor, false)); if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans.values().stream(); } else if (type.isArray()) { Class<?> componentType = type.getComponentType(); ResolvableType resolvableType = descriptor.getResolvableType(); Class<?> resolvedArrayType = resolvableType.resolve(); if (resolvedArrayType != null && resolvedArrayType != type) { type = resolvedArrayType; componentType = resolvableType.getComponentType().resolve(); } if (componentType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, new MultiElementDescriptor(descriptor, true)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof Object[]) { Arrays.sort((Object[]) result, adaptDependencyComparator(matchingBeans)); } return result; } else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric(); if (elementType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, new MultiElementDescriptor(descriptor, true)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (getDependencyComparator() != null && result instanceof List) { ((List<?>) result).sort(adaptDependencyComparator(matchingBeans)); } return result; } else if (Map.class == type) { ResolvableType mapType = descriptor.getResolvableType().asMap(); Class<?> keyType = mapType.resolveGeneric(0); if (String.class != keyType) { return null; } Class<?> valueType = mapType.resolveGeneric(1); if (valueType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, new MultiElementDescriptor(descriptor, true)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans; } else { return null; } } private boolean isRequired(DependencyDescriptor descriptor) { return getAutowireCandidateResolver().isRequired(descriptor); } private boolean indicatesMultipleBeans(Class<?> type) { return (type.isArray() || (type.isInterface() && (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)))); } @Nullable private Comparator<Object> adaptDependencyComparator(Map<String, Object> matchingBeans) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).withSourceProvider( createFactoryAwareOrderSourceProvider(matchingBeans)); } else { return comparator; } } private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, Object> beans) { IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>(); beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName)); return new FactoryAwareOrderSourceProvider(instancesToBeanNames); } /** * Find bean instances that match the required type. * Called during autowiring for the specified bean. * @param beanName the name of the bean that is about to be wired * @param requiredType the actual type of bean to look for * (may be an array component type or collection element type) * @param descriptor the descriptor of the dependency to resolve * @return a Map of candidate names and candidate instances that match * the required type (never {@code null}) * @throws BeansException in case of errors * @see #autowireByType * @see #autowireConstructor */ protected Map<String, Object> findAutowireCandidates( @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) { String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this, requiredType, true, descriptor.isEager()); Map<String, Object> result = new LinkedHashMap<>(candidateNames.length); for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) { Class<?> autowiringType = classObjectEntry.getKey(); if (autowiringType.isAssignableFrom(requiredType)) { Object autowiringValue = classObjectEntry.getValue(); autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); if (requiredType.isInstance(autowiringValue)) { result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); break; } } } for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty() && !indicatesMultipleBeans(requiredType)) { // Consider fallback matches if the first pass failed to find anything... DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty()) { // Consider self references as a final pass... // but in the case of a dependency collection, not the very same bean itself. for (String candidate : candidateNames) { if (isSelfReference(beanName, candidate) && (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } } } return result; } /** * Add an entry to the candidate map: a bean instance if available or just the resolved * type, preventing early bean initialization ahead of primary candidate selection. */ private void addCandidateEntry(Map<String, Object> candidates, String candidateName, DependencyDescriptor descriptor, Class<?> requiredType) { if (descriptor instanceof MultiElementDescriptor) { Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); if (!(beanInstance instanceof NullBean)) { candidates.put(candidateName, beanInstance); } } else if (containsSingleton(candidateName)) { Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance)); } else { candidates.put(candidateName, getType(candidateName)); } } /** * Determine the autowire candidate in the given set of beans. * <p>Looks for {@code @Primary} and {@code @Priority} (in that order). * @param candidates a Map of candidate names and candidate instances * that match the required type, as returned by {@link #findAutowireCandidates} * @param descriptor the target dependency to match against * @return the name of the autowire candidate, or {@code null} if none found */ @Nullable protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) { Class<?> requiredType = descriptor.getDependencyType(); String primaryCandidate = determinePrimaryCandidate(candidates, requiredType); if (primaryCandidate != null) { return primaryCandidate; } String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType); if (priorityCandidate != null) { return priorityCandidate; } // Fallback for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateName = entry.getKey(); Object beanInstance = entry.getValue(); if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) || matchesBeanName(candidateName, descriptor.getDependencyName())) { return candidateName; } } return null; } /** * Determine the primary candidate in the given set of beans. * @param candidates a Map of candidate names and candidate instances * (or candidate classes if not created yet) that match the required type * @param requiredType the target dependency type to match against * @return the name of the primary candidate, or {@code null} if none found * @see #isPrimary(String, Object) */ @Nullable protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) { String primaryBeanName = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); if (isPrimary(candidateBeanName, beanInstance)) { if (primaryBeanName != null) { boolean candidateLocal = containsBeanDefinition(candidateBeanName); boolean primaryLocal = containsBeanDefinition(primaryBeanName); if (candidateLocal && primaryLocal) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "more than one 'primary' bean found among candidates: " + candidates.keySet()); } else if (candidateLocal) { primaryBeanName = candidateBeanName; } } else { primaryBeanName = candidateBeanName; } } } return primaryBeanName; } /** * Determine the candidate with the highest priority in the given set of beans. * <p>Based on {@code @javax.annotation.Priority}. As defined by the related * {@link org.springframework.core.Ordered} interface, the lowest value has * the highest priority. * @param candidates a Map of candidate names and candidate instances * (or candidate classes if not created yet) that match the required type * @param requiredType the target dependency type to match against * @return the name of the candidate with the highest priority, * or {@code null} if none found * @see #getPriority(Object) */ @Nullable protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) { String highestPriorityBeanName = null; Integer highestPriority = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); if (beanInstance != null) { Integer candidatePriority = getPriority(beanInstance); if (candidatePriority != null) { if (highestPriorityBeanName != null) { if (candidatePriority.equals(highestPriority)) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "Multiple beans found with the same priority ('" + highestPriority + "') among candidates: " + candidates.keySet()); } else if (candidatePriority < highestPriority) { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } else { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } } } return highestPriorityBeanName; } /** * Return whether the bean definition for the given bean name has been * marked as a primary bean. * @param beanName the name of the bean * @param beanInstance the corresponding bean instance (can be null) * @return whether the given bean qualifies as primary */ protected boolean isPrimary(String beanName, Object beanInstance) { if (containsBeanDefinition(beanName)) { return getMergedLocalBeanDefinition(beanName).isPrimary(); } BeanFactory parent = getParentBeanFactory(); return (parent instanceof DefaultListableBeanFactory && ((DefaultListableBeanFactory) parent).isPrimary(beanName, beanInstance)); } /** * Return the priority assigned for the given bean instance by * the {@code javax.annotation.Priority} annotation. * <p>The default implementation delegates to the specified * {@link #setDependencyComparator dependency comparator}, checking its * {@link OrderComparator#getPriority method} if it is an extension of * Spring's common {@link OrderComparator} - typically, an * {@link org.springframework.core.annotation.AnnotationAwareOrderComparator}. * If no such comparator is present, this implementation returns {@code null}. * @param beanInstance the bean instance to check (can be {@code null}) * @return the priority assigned to that bean or {@code null} if none is set */ @Nullable protected Integer getPriority(Object beanInstance) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).getPriority(beanInstance); } return null; } /** * Determine whether the given candidate name matches the bean name or the aliases * stored in this bean definition. */ protected boolean matchesBeanName(String beanName, @Nullable String candidateName) { return (candidateName != null && (candidateName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), candidateName))); } /** * Determine whether the given beanName/candidateName pair indicates a self reference, * i.e. whether the candidate points back to the original bean or to a factory method * on the original bean. */ private boolean isSelfReference(@Nullable String beanName, @Nullable String candidateName) { return (beanName != null && candidateName != null && (beanName.equals(candidateName) || (containsBeanDefinition(candidateName) && beanName.equals(getMergedLocalBeanDefinition(candidateName).getFactoryBeanName())))); } /** * Raise a NoSuchBeanDefinitionException or BeanNotOfRequiredTypeException * for an unresolvable dependency. */ private void raiseNoMatchingBeanFound( Class<?> type, ResolvableType resolvableType, DependencyDescriptor descriptor) throws BeansException { checkBeanNotOfRequiredType(type, descriptor); throw new NoSuchBeanDefinitionException(resolvableType, "expected at least 1 bean which qualifies as autowire candidate. " + "Dependency annotations: " + ObjectUtils.nullSafeToString(descriptor.getAnnotations())); } /** * Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable, * i.e. if the target type of the bean would match but an exposed proxy doesn't. */ private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) { for (String beanName : this.beanDefinitionNames) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class<?> targetType = mbd.getTargetType(); if (targetType != null && type.isAssignableFrom(targetType) && isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) { // Probably a proxy interfering with target type match -> throw meaningful exception. Object beanInstance = getSingleton(beanName, false); Class<?> beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class ? beanInstance.getClass() : predictBeanType(beanName, mbd)); if (beanType != null && !type.isAssignableFrom(beanType)) { throw new BeanNotOfRequiredTypeException(beanName, type, beanType); } } } BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor); } } /** * Create an {@link Optional} wrapper for the specified dependency. */ private Optional<?> createOptionalDependency( DependencyDescriptor descriptor, @Nullable String beanName, final Object... args) { DependencyDescriptor descriptorToUse = new NestedDependencyDescriptor(descriptor) { @Override public boolean isRequired() { return false; } @Override public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return (!ObjectUtils.isEmpty(args) ? beanFactory.getBean(beanName, args) : super.resolveCandidate(beanName, requiredType, beanFactory)); } }; return Optional.ofNullable(doResolveDependency(descriptorToUse, beanName, null, null)); } @Override public String toString() { StringBuilder sb = new StringBuilder(ObjectUtils.identityToString(this)); sb.append(": defining beans ["); sb.append(StringUtils.collectionToCommaDelimitedString(this.beanDefinitionNames)); sb.append("]; "); BeanFactory parent = getParentBeanFactory(); if (parent == null) { sb.append("root of factory hierarchy"); } else { sb.append("parent: ").append(ObjectUtils.identityToString(parent)); } return sb.toString(); } //--------------------------------------------------------------------- // Serialization support //--------------------------------------------------------------------- private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { throw new NotSerializableException("DefaultListableBeanFactory itself is not deserializable - " + "just a SerializedBeanFactoryReference is"); } protected Object writeReplace() throws ObjectStreamException { if (this.serializationId != null) { return new SerializedBeanFactoryReference(this.serializationId); } else { throw new NotSerializableException("DefaultListableBeanFactory has no serialization id"); } } /** * Minimal id reference to the factory. * Resolved to the actual factory instance on deserialization. */ private static class SerializedBeanFactoryReference implements Serializable { private final String id; public SerializedBeanFactoryReference(String id) { this.id = id; } private Object readResolve() { Reference<?> ref = serializableFactories.get(this.id); if (ref != null) { Object result = ref.get(); if (result != null) { return result; } } // Lenient fallback: dummy factory in case of original factory not found... return new DefaultListableBeanFactory(); } } /** * A dependency descriptor marker for nested elements. */ private static class NestedDependencyDescriptor extends DependencyDescriptor { public NestedDependencyDescriptor(DependencyDescriptor original) { super(original); increaseNestingLevel(); } } /** * A dependency descriptor marker for multiple elements. */ private static class MultiElementDescriptor extends DependencyDescriptor { public MultiElementDescriptor(DependencyDescriptor original, boolean nested) { super(original); if (nested) { increaseNestingLevel(); } } } private interface BeanObjectProvider<T> extends ObjectProvider<T>, Serializable { } /** * Serializable ObjectFactory/ObjectProvider for lazy resolution of a dependency. */ private class DependencyObjectProvider implements BeanObjectProvider<Object> { private final DependencyDescriptor descriptor; private final boolean optional; @Nullable private final String beanName; public DependencyObjectProvider(DependencyDescriptor descriptor, @Nullable String beanName) { this.descriptor = new NestedDependencyDescriptor(descriptor); this.optional = (this.descriptor.getDependencyType() == Optional.class); this.beanName = beanName; } @Override public Object getObject() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { Object result = doResolveDependency(this.descriptor, this.beanName, null, null); if (result == null) { throw new NoSuchBeanDefinitionException(this.descriptor.getResolvableType()); } return result; } } @Override public Object getObject(final Object... args) throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName, args); } else { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return beanFactory.getBean(beanName, args); } }; Object result = doResolveDependency(descriptorToUse, this.beanName, null, null); if (result == null) { throw new NoSuchBeanDefinitionException(this.descriptor.getResolvableType()); } return result; } } @Override @Nullable public Object getIfAvailable() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public boolean isRequired() { return false; } }; return doResolveDependency(descriptorToUse, this.beanName, null, null); } } @Override @Nullable public Object getIfUnique() throws BeansException { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public boolean isRequired() { return false; } @Override @Nullable public Object resolveNotUnique(ResolvableType type, Map<String, Object> matchingBeans) { return null; } }; if (this.optional) { return createOptionalDependency(descriptorToUse, this.beanName); } else { return doResolveDependency(descriptorToUse, this.beanName, null, null); } } @Nullable protected Object getValue() throws BeansException { if (this.optional) { return createOptionalDependency(this.descriptor, this.beanName); } else { return doResolveDependency(this.descriptor, this.beanName, null, null); } } @SuppressWarnings("unchecked") @Override public Stream<Object> stream() { DependencyDescriptor descriptorToUse = new DependencyDescriptor(this.descriptor) { @Override public boolean isStreamAccess() { return true; } }; Object result = doResolveDependency(descriptorToUse, this.beanName, null, null); if (result instanceof Stream) { return (Stream<Object>) result; } else if (result instanceof Collection) { return ((Collection<Object>) result).stream(); } else { return (result != null ? Stream.of(result) : Stream.empty()); } } } /** * Separate inner class for avoiding a hard dependency on the {@code javax.inject} API. * Actual {@code javax.inject.Provider} implementation is nested here in order to make it * invisible for Graal's introspection of DefaultListableBeanFactory's nested classes. */ private class Jsr330Factory implements Serializable { public Object createDependencyProvider(DependencyDescriptor descriptor, @Nullable String beanName) { return new Jsr330Provider(descriptor, beanName); } private class Jsr330Provider extends DependencyObjectProvider implements Provider<Object> { public Jsr330Provider(DependencyDescriptor descriptor, @Nullable String beanName) { super(descriptor, beanName); } @Override @Nullable public Object get() throws BeansException { return getValue(); } } } /** * An {@link org.springframework.core.OrderComparator.OrderSourceProvider} implementation * that is aware of the bean metadata of the instances to sort. * <p>Lookup for the method factory of an instance to sort, if any, and let the * comparator retrieve the {@link org.springframework.core.annotation.Order} * value defined on it. This essentially allows for the following construct: */ private class FactoryAwareOrderSourceProvider implements OrderComparator.OrderSourceProvider { private final Map<Object, String> instancesToBeanNames; public FactoryAwareOrderSourceProvider(Map<Object, String> instancesToBeanNames) { this.instancesToBeanNames = instancesToBeanNames; } @Override @Nullable public Object getOrderSource(Object obj) { RootBeanDefinition beanDefinition = getRootBeanDefinition(this.instancesToBeanNames.get(obj)); if (beanDefinition == null) { return null; } List<Object> sources = new ArrayList<>(2); Method factoryMethod = beanDefinition.getResolvedFactoryMethod(); if (factoryMethod != null) { sources.add(factoryMethod); } Class<?> targetType = beanDefinition.getTargetType(); if (targetType != null && targetType != obj.getClass()) { sources.add(targetType); } return sources.toArray(); } @Nullable private RootBeanDefinition getRootBeanDefinition(@Nullable String beanName) { if (beanName != null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof RootBeanDefinition) { return (RootBeanDefinition) bd; } } return null; } } }
ListableBeanFactory.getBeansWithAnnotation does not include null beans Issue: SPR-17034
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
ListableBeanFactory.getBeansWithAnnotation does not include null beans
<ide><path>pring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java <ide> <ide> @Override <ide> public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) { <del> List<String> results = new ArrayList<>(); <add> List<String> result = new ArrayList<>(); <ide> for (String beanName : this.beanDefinitionNames) { <ide> BeanDefinition beanDefinition = getBeanDefinition(beanName); <ide> if (!beanDefinition.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) { <del> results.add(beanName); <add> result.add(beanName); <ide> } <ide> } <ide> for (String beanName : this.manualSingletonNames) { <del> if (!results.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) { <del> results.add(beanName); <del> } <del> } <del> return StringUtils.toStringArray(results); <add> if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) { <add> result.add(beanName); <add> } <add> } <add> return StringUtils.toStringArray(result); <ide> } <ide> <ide> @Override <ide> public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) { <ide> String[] beanNames = getBeanNamesForAnnotation(annotationType); <del> Map<String, Object> results = new LinkedHashMap<>(beanNames.length); <add> Map<String, Object> result = new LinkedHashMap<>(beanNames.length); <ide> for (String beanName : beanNames) { <del> results.put(beanName, getBean(beanName)); <del> } <del> return results; <add> Object beanInstance = getBean(beanName); <add> if (!(beanInstance instanceof NullBean)) { <add> result.put(beanName, beanInstance); <add> } <add> } <add> return result; <ide> } <ide> <ide> /**
Java
mit
e3ced41fb9b339609f2a9c54f1ada500a520fe20
0
stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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 hudson.model; import hudson.XmlFile; import hudson.BulkChange; import hudson.Util; import static hudson.Util.singleQuote; import hudson.diagnosis.OldDataMonitor; import hudson.model.listeners.SaveableListener; import hudson.util.ReflectionUtils; import hudson.util.ReflectionUtils.Parameter; import hudson.views.ListViewColumn; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.*; import org.springframework.util.StringUtils; import org.jvnet.tiger_types.Types; import org.apache.commons.io.IOUtils; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Locale; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.beans.Introspector; /** * Metadata about a configurable instance. * * <p> * {@link Descriptor} is an object that has metadata about a {@link Describable} * object, and also serves as a factory (in a way this relationship is similar * to {@link Object}/{@link Class} relationship. * * A {@link Descriptor}/{@link Describable} * combination is used throughout in Hudson to implement a * configuration/extensibility mechanism. * * <p> * Take the list view support as an example, which is implemented * in {@link ListView} class. Whenever a new view is created, a new * {@link ListView} instance is created with the configuration * information. This instance gets serialized to XML, and this instance * will be called to render the view page. This is the job * of {@link Describable} &mdash; each instance represents a specific * configuration of a view (what projects are in it, regular expression, etc.) * * <p> * For Hudson to create such configured {@link ListView} instance, Hudson * needs another object that captures the metadata of {@link ListView}, * and that is what a {@link Descriptor} is for. {@link ListView} class * has a singleton descriptor, and this descriptor helps render * the configuration form, remember system-wide configuration, and works as a factory. * * <p> * {@link Descriptor} also usually have its associated views. * * * <h2>Persistence</h2> * <p> * {@link Descriptor} can persist data just by storing them in fields. * However, it is the responsibility of the derived type to properly * invoke {@link #save()} and {@link #load()}. * * <h2>Reflection Enhancement</h2> * {@link Descriptor} defines addition to the standard Java reflection * and provides reflective information about its corresponding {@link Describable}. * These are primarily used by tag libraries to * keep the Jelly scripts concise. * * @author Kohsuke Kawaguchi * @see Describable */ public abstract class Descriptor<T extends Describable<T>> implements Saveable { /** * Up to Hudson 1.61 this was used as the primary persistence mechanism. * Going forward Hudson simply persists all the non-transient fields * of {@link Descriptor}, just like others, so this is pointless. * * @deprecated since 2006-11-16 */ @Deprecated private transient Map<String,Object> properties; /** * The class being described by this descriptor. */ public transient final Class<? extends T> clazz; private transient final Map<String,String> checkMethods = new ConcurrentHashMap<String,String>(); /** * Lazily computed list of properties on {@link #clazz}. */ private transient volatile Map<String, PropertyType> propertyTypes; /** * Represents a readable property on {@link Describable}. */ public static final class PropertyType { public final Class clazz; public final Type type; private volatile Class itemType; PropertyType(Class clazz, Type type) { this.clazz = clazz; this.type = type; } PropertyType(Field f) { this(f.getType(),f.getGenericType()); } PropertyType(Method getter) { this(getter.getReturnType(),getter.getGenericReturnType()); } public Enum[] getEnumConstants() { return (Enum[])clazz.getEnumConstants(); } /** * If the property is a collection/array type, what is an item type? */ public Class getItemType() { if(itemType==null) itemType = computeItemType(); return itemType; } private Class computeItemType() { if(clazz.isArray()) { return clazz.getComponentType(); } if(Collection.class.isAssignableFrom(clazz)) { Type col = Types.getBaseClass(type, Collection.class); if (col instanceof ParameterizedType) return Types.erasure(Types.getTypeArgument(col,0)); else return Object.class; } return null; } /** * Returns {@link Descriptor} whose 'clazz' is the same as {@link #getItemType() the item type}. */ public Descriptor getItemTypeDescriptor() { return Hudson.getInstance().getDescriptor(getItemType()); } public Descriptor getItemTypeDescriptorOrDie() { return Hudson.getInstance().getDescriptorOrDie(getItemType()); } } protected Descriptor(Class<? extends T> clazz) { this.clazz = clazz; // doing this turns out to be very error prone, // as field initializers in derived types will override values. // load(); } /** * Infers the type of the corresponding {@link Describable} from the outer class. * This version works when you follow the common convention, where a descriptor * is written as the static nested class of the describable class. * * @since 1.278 */ protected Descriptor() { this.clazz = (Class<T>)getClass().getEnclosingClass(); if(clazz==null) throw new AssertionError(getClass()+" doesn't have an outer class. Use the constructor that takes the Class object explicitly."); // detect an type error Type bt = Types.getBaseClass(getClass(), Descriptor.class); if (bt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) bt; // this 't' is the closest approximation of T of Descriptor<T>. Class t = Types.erasure(pt.getActualTypeArguments()[0]); if(!t.isAssignableFrom(clazz)) throw new AssertionError("Outer class "+clazz+" of "+getClass()+" is not assignable to "+t+". Perhaps wrong outer class?"); } // detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up. // this prevents a bug like http://www.nabble.com/Creating-a-new-parameter-Type-%3A-Masked-Parameter-td24786554.html try { Method getd = clazz.getMethod("getDescriptor"); if(!getd.getReturnType().isAssignableFrom(getClass())) { throw new AssertionError(getClass()+" must be assignable to "+getd.getReturnType()); } } catch (NoSuchMethodException e) { throw new AssertionError(getClass()+" is missing getDescriptor method."); } } /** * Human readable name of this kind of configurable object. */ public abstract String getDisplayName(); /** * Gets the URL that this Descriptor is bound to, relative to the nearest {@link DescriptorByNameOwner}. * Since {@link Hudson} is a {@link DescriptorByNameOwner}, there's always one such ancestor to any request. */ public String getDescriptorUrl() { return "descriptorByName/"+clazz.getName(); } private String getCurrentDescriptorByNameUrl() { StaplerRequest req = Stapler.getCurrentRequest(); Ancestor a = req.findAncestor(DescriptorByNameOwner.class); return a.getUrl(); } /** * If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method, * return the form-field validation string. Otherwise null. * <p> * This method is used to hook up the form validation method to the corresponding HTML input element. */ public String getCheckUrl(String fieldName) { String method = checkMethods.get(fieldName); if(method==null) { method = calcCheckUrl(fieldName); checkMethods.put(fieldName,method); } if (method.equals(NONE)) // == would do, but it makes IDE flag a warning return null; // put this under the right contextual umbrella. // a is always non-null because we already have Hudson as the sentinel return singleQuote(getCurrentDescriptorByNameUrl()+'/')+'+'+method; } private String calcCheckUrl(String fieldName) { String capitalizedFieldName = StringUtils.capitalize(fieldName); Method method = ReflectionUtils.getPublicMethodNamed(getClass(),"doCheck"+ capitalizedFieldName); if(method==null) return NONE; return singleQuote(getDescriptorUrl() +"/check"+capitalizedFieldName) + buildParameterList(method, new StringBuilder()).append(".toString()"); } /** * Builds query parameter line by figuring out what should be submitted */ private StringBuilder buildParameterList(Method method, StringBuilder query) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp!=null) { String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. if (query.length()==0) query.append("+qs(this)"); if (name.equals("value")) { // The special 'value' parameter binds to the the current field query.append(".addThis()"); } else { query.append(".nearBy('"+name+"')"); } continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); if (m!=null) buildParameterList(m,query); } return query; } /** * Computes the list of other form fields that the given field depends on, via the doFillXyzItems method, * and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and * sets that as the 'fillUrl' attribute. */ public void calcFillSettings(String field, Map<String,Object> attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doFill" + capitalizedFieldName + "Items"; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); if(method==null) throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName)); // build query parameter line by figuring out what should be submitted List<String> depends = buildFillDependencies(method, new ArrayList<String>()); if (!depends.isEmpty()) attributes.put("fillDependsOn",Util.join(depends," ")); attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); } private List<String> buildFillDependencies(Method method, List<String> depends) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp!=null) { String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. depends.add(name); continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); if (m!=null) buildFillDependencies(m,depends); } return depends; } /** * Obtains the property type of the given field of {@link #clazz} */ public PropertyType getPropertyType(String field) { if(propertyTypes ==null) { Map<String, PropertyType> r = new HashMap<String, PropertyType>(); for (Field f : clazz.getFields()) r.put(f.getName(),new PropertyType(f)); for (Method m : clazz.getMethods()) if(m.getName().startsWith("get")) r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m)); propertyTypes = r; } return propertyTypes.get(field); } /** * Gets the class name nicely escaped to be usable as a key in the structured form submission. */ public final String getJsonSafeClassName() { return clazz.getName().replace('.','-'); } /** * @deprecated * Implement {@link #newInstance(StaplerRequest, JSONObject)} method instead. * Deprecated as of 1.145. */ public T newInstance(StaplerRequest req) throws FormException { throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)"); } /** * Creates a configured instance from the submitted form. * * <p> * Hudson only invokes this method when the user wants an instance of <tt>T</tt>. * So there's no need to check that in the implementation. * * <p> * Starting 1.206, the default implementation of this method does the following: * <pre> * req.bindJSON(clazz,formData); * </pre> * <p> * ... which performs the databinding on the constructor of {@link #clazz}. * * <p> * For some types of {@link Describable}, such as {@link ListViewColumn}, this method * can be invoked with null request object for historical reason. Such design is considered * broken, but due to the compatibility reasons we cannot fix it. Because of this, the * default implementation gracefully handles null request, but the contract of the method * still is "request is always non-null." Extension points that need to define the "default instance" * semantics should define a descriptor subtype and add the no-arg newInstance method. * * @param req * Always non-null (see note above.) This object includes represents the entire submission. * @param formData * The JSON object that captures the configuration data for this {@link Descriptor}. * See http://hudson.gotdns.com/wiki/display/HUDSON/Structured+Form+Submission * Always non-null. * * @throws FormException * Signals a problem in the submitted form. * @since 1.145 */ public T newInstance(StaplerRequest req, JSONObject formData) throws FormException { try { Method m = getClass().getMethod("newInstance", StaplerRequest.class); if(!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) { // this class overrides newInstance(StaplerRequest). // maintain the backward compatible behavior return newInstance(req); } else { if (req==null) { // yes, req is supposed to be always non-null, but see the note above return clazz.newInstance(); } // new behavior as of 1.206 return req.bindJSON(clazz,formData); } } catch (NoSuchMethodException e) { throw new AssertionError(e); // impossible } catch (InstantiationException e) { throw new Error(e); } catch (IllegalAccessException e) { throw new Error(e); } } /** * Returns the resource path to the help screen HTML, if any. * * <p> * Starting 1.282, this method uses "convention over configuration" &mdash; you should * just put the "help.html" (and its localized versions, if any) in the same directory * you put your Jelly view files, and this method will automatically does the right thing. * * <p> * This value is relative to the context root of Hudson, so normally * the values are something like <tt>"/plugin/emma/help.html"</tt> to * refer to static resource files in a plugin, or <tt>"/publisher/EmmaPublisher/abc"</tt> * to refer to Jelly script <tt>abc.jelly</tt> or a method <tt>EmmaPublisher.doAbc()</tt>. * * @return * null to indicate that there's no help. */ public String getHelpFile() { return getHelpFile(null); } /** * Returns the path to the help screen HTML for the given field. * * <p> * The help files are assumed to be at "help/FIELDNAME.html" with possible * locale variations. */ public String getHelpFile(final String fieldName) { for(Class c=clazz; c!=null; c=c.getSuperclass()) { String page = "/descriptor/" + clazz.getName() + "/help"; String suffix; if(fieldName==null) { suffix=""; } else { page += '/'+fieldName; suffix='-'+fieldName; } try { if(Stapler.getCurrentRequest().getView(c,"help"+suffix)!=null) return page; } catch (IOException e) { throw new Error(e); } InputStream in = getHelpStream(c,suffix); IOUtils.closeQuietly(in); if(in!=null) return page; } return null; } /** * Checks if the given object is created from this {@link Descriptor}. */ public final boolean isInstance( T instance ) { return clazz.isInstance(instance); } /** * Checks if the type represented by this descriptor is a subtype of the given type. */ public final boolean isSubTypeOf(Class type) { return type.isAssignableFrom(clazz); } /** * @deprecated * As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}. */ public boolean configure( StaplerRequest req ) throws FormException { return true; } /** * Invoked when the global configuration page is submitted. * * Can be overriden to store descriptor-specific information. * * @param json * The JSON object that captures the configuration data for this {@link Descriptor}. * See http://hudson.gotdns.com/wiki/display/HUDSON/Structured+Form+Submission * @return false * to keep the client in the same config page. */ public boolean configure( StaplerRequest req, JSONObject json ) throws FormException { // compatibility return configure(req); } public String getConfigPage() { return getViewPage(clazz, "config.jelly"); } public String getGlobalConfigPage() { return getViewPage(clazz, "global.jelly"); } protected final String getViewPage(Class<?> clazz, String pageName) { while(clazz!=Object.class) { String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName; if(clazz.getClassLoader().getResource(name)!=null) return '/'+name; clazz = clazz.getSuperclass(); } // We didn't find the configuration page. // Either this is non-fatal, in which case it doesn't matter what string we return so long as // it doesn't exist. // Or this error is fatal, in which case we want the developer to see what page he's missing. // so we put the page name. return pageName; } /** * Saves the configuration info to the disk. */ public synchronized void save() { if(BulkChange.contains(this)) return; try { getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e); } } /** * Loads the data from the disk into this object. * * <p> * The constructor of the derived class must call this method. * (If we do that in the base class, the derived class won't * get a chance to set default values.) */ public synchronized void load() { XmlFile file = getConfigFile(); if(!file.exists()) return; try { file.unmarshal(this); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+file, e); } } private XmlFile getConfigFile() { return new XmlFile(new File(Hudson.getInstance().getRootDir(),clazz.getName()+".xml")); } /** * Serves <tt>help.html</tt> from the resource of {@link #clazz}. */ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); if(path.contains("..")) throw new ServletException("Illegal path: "+path); path = path.replace('/','-'); for (Class c=clazz; c!=null; c=c.getSuperclass()) { RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help"+path); if(rd!=null) {// Jelly-generated help page rd.forward(req,rsp); return; } InputStream in = getHelpStream(c,path); if(in!=null) { // TODO: generalize macro expansion and perhaps even support JEXL rsp.setContentType("text/html;charset=UTF-8"); String literal = IOUtils.toString(in,"UTF-8"); rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath()))); in.close(); return; } } rsp.sendError(SC_NOT_FOUND); } private InputStream getHelpStream(Class c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); String base = c.getName().replace('.', '/').replace('$','/') + "/help"+suffix; ClassLoader cl = c.getClassLoader(); if(cl==null) return null; InputStream in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); if(in!=null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); if(in!=null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + ".html"); if(in!=null) return in; // default return cl.getResourceAsStream(base+".html"); } // // static methods // // to work around warning when creating a generic array type public static <T> T[] toArray( T... values ) { return values; } public static <T> List<T> toList( T... values ) { return new ArrayList<T>(Arrays.asList(values)); } public static <T extends Describable<T>> Map<Descriptor<T>,T> toMap(Iterable<T> describables) { Map<Descriptor<T>,T> m = new LinkedHashMap<Descriptor<T>,T>(); for (T d : describables) { m.put(d.getDescriptor(),d); } return m; } /** * Used to build {@link Describable} instance list from &lt;f:hetero-list> tag. * * @param req * Request that represents the form submission. * @param formData * Structured form data that represents the contains data for the list of describables. * @param key * The JSON property name for 'formData' that represents the data for the list of describables. * @param descriptors * List of descriptors to create instances from. * @return * Can be empty but never null. */ public static <T extends Describable<T>> List<T> newInstancesFromHeteroList(StaplerRequest req, JSONObject formData, String key, Collection<? extends Descriptor<T>> descriptors) throws FormException { List<T> items = new ArrayList<T>(); if(!formData.has(key)) return items; JSONArray a = JSONArray.fromObject(formData.get(key)); for (Object o : a) { JSONObject jo = (JSONObject)o; String kind = jo.getString("kind"); items.add(find(descriptors,kind).newInstance(req,jo)); } return items; } /** * Finds a descriptor from a collection by its class name. */ public static <T extends Descriptor> T find(Collection<? extends T> list, String className) { for (T d : list) { if(d.getClass().getName().equals(className)) return d; } return null; } public static Descriptor find(String className) { return find(Hudson.getInstance().getExtensionList(Descriptor.class),className); } public static final class FormException extends Exception implements HttpResponse { private final String formField; public FormException(String message, String formField) { super(message); this.formField = formField; } public FormException(String message, Throwable cause, String formField) { super(message, cause); this.formField = formField; } public FormException(Throwable cause, String formField) { super(cause); this.formField = formField; } /** * Which form field contained an error? */ public String getFormField() { return formField; } public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { // for now, we can't really use the field name that caused the problem. new Failure(getMessage()).generateResponse(req,rsp,node); } } private static final Logger LOGGER = Logger.getLogger(Descriptor.class.getName()); /** * Used in {@link #checkMethods} to indicate that there's no check method. */ private static final String NONE = "\u0000"; private Object readResolve() { if (properties!=null) OldDataMonitor.report(this, "1.62"); return this; } }
core/src/main/java/hudson/model/Descriptor.java
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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 hudson.model; import hudson.XmlFile; import hudson.BulkChange; import hudson.Util; import static hudson.Util.singleQuote; import hudson.diagnosis.OldDataMonitor; import hudson.model.listeners.SaveableListener; import hudson.util.ReflectionUtils; import hudson.util.ReflectionUtils.Parameter; import hudson.views.ListViewColumn; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.*; import org.springframework.util.StringUtils; import org.jvnet.tiger_types.Types; import org.apache.commons.io.IOUtils; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Locale; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.beans.Introspector; /** * Metadata about a configurable instance. * * <p> * {@link Descriptor} is an object that has metadata about a {@link Describable} * object, and also serves as a factory (in a way this relationship is similar * to {@link Object}/{@link Class} relationship. * * A {@link Descriptor}/{@link Describable} * combination is used throughout in Hudson to implement a * configuration/extensibility mechanism. * * <p> * Take the list view support as an example, which is implemented * in {@link ListView} class. Whenever a new view is created, a new * {@link ListView} instance is created with the configuration * information. This instance gets serialized to XML, and this instance * will be called to render the view page. This is the job * of {@link Describable} &mdash; each instance represents a specific * configuration of a view (what projects are in it, regular expression, etc.) * * <p> * For Hudson to create such configured {@link ListView} instance, Hudson * needs another object that captures the metadata of {@link ListView}, * and that is what a {@link Descriptor} is for. {@link ListView} class * has a singleton descriptor, and this descriptor helps render * the configuration form, remember system-wide configuration, and works as a factory. * * <p> * {@link Descriptor} also usually have its associated views. * * * <h2>Persistence</h2> * <p> * {@link Descriptor} can persist data just by storing them in fields. * However, it is the responsibility of the derived type to properly * invoke {@link #save()} and {@link #load()}. * * <h2>Reflection Enhancement</h2> * {@link Descriptor} defines addition to the standard Java reflection * and provides reflective information about its corresponding {@link Describable}. * These are primarily used by tag libraries to * keep the Jelly scripts concise. * * @author Kohsuke Kawaguchi * @see Describable */ public abstract class Descriptor<T extends Describable<T>> implements Saveable { /** * Up to Hudson 1.61 this was used as the primary persistence mechanism. * Going forward Hudson simply persists all the non-transient fields * of {@link Descriptor}, just like others, so this is pointless. * * @deprecated since 2006-11-16 */ @Deprecated private transient Map<String,Object> properties; /** * The class being described by this descriptor. */ public transient final Class<? extends T> clazz; private transient final Map<String,String> checkMethods = new ConcurrentHashMap<String,String>(); /** * Lazily computed list of properties on {@link #clazz}. */ private transient volatile Map<String, PropertyType> propertyTypes; /** * Represents a readable property on {@link Describable}. */ public static final class PropertyType { public final Class clazz; public final Type type; private volatile Class itemType; PropertyType(Class clazz, Type type) { this.clazz = clazz; this.type = type; } PropertyType(Field f) { this(f.getType(),f.getGenericType()); } PropertyType(Method getter) { this(getter.getReturnType(),getter.getGenericReturnType()); } public Enum[] getEnumConstants() { return (Enum[])clazz.getEnumConstants(); } /** * If the property is a collection/array type, what is an item type? */ public Class getItemType() { if(itemType==null) itemType = computeItemType(); return itemType; } private Class computeItemType() { if(clazz.isArray()) { return clazz.getComponentType(); } if(Collection.class.isAssignableFrom(clazz)) { Type col = Types.getBaseClass(type, Collection.class); if (col instanceof ParameterizedType) return Types.erasure(Types.getTypeArgument(col,0)); else return Object.class; } return null; } /** * Returns {@link Descriptor} whose 'clazz' is the same as {@link #getItemType() the item type}. */ public Descriptor getItemTypeDescriptor() { return Hudson.getInstance().getDescriptor(getItemType()); } public Descriptor getItemTypeDescriptorOrDie() { return Hudson.getInstance().getDescriptorOrDie(getItemType()); } } protected Descriptor(Class<? extends T> clazz) { this.clazz = clazz; // doing this turns out to be very error prone, // as field initializers in derived types will override values. // load(); } /** * Infers the type of the corresponding {@link Describable} from the outer class. * This version works when you follow the common convention, where a descriptor * is written as the static nested class of the describable class. * * @since 1.278 */ protected Descriptor() { this.clazz = (Class<T>)getClass().getEnclosingClass(); if(clazz==null) throw new AssertionError(getClass()+" doesn't have an outer class. Use the constructor that takes the Class object explicitly."); // detect an type error Type bt = Types.getBaseClass(getClass(), Descriptor.class); if (bt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) bt; // this 't' is the closest approximation of T of Descriptor<T>. Class t = Types.erasure(pt.getActualTypeArguments()[0]); if(!t.isAssignableFrom(clazz)) throw new AssertionError("Outer class "+clazz+" of "+getClass()+" is not assignable to "+t+". Perhaps wrong outer class?"); } // detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up. // this prevents a bug like http://www.nabble.com/Creating-a-new-parameter-Type-%3A-Masked-Parameter-td24786554.html try { Method getd = clazz.getMethod("getDescriptor"); if(!getd.getReturnType().isAssignableFrom(getClass())) { throw new AssertionError(getClass()+" must be assignable to "+getd.getReturnType()); } } catch (NoSuchMethodException e) { throw new AssertionError(getClass()+" is missing getDescriptor method."); } } /** * Human readable name of this kind of configurable object. */ public abstract String getDisplayName(); /** * Gets the URL that this Descriptor is bound to, relative to the nearest {@link DescriptorByNameOwner}. * Since {@link Hudson} is a {@link DescriptorByNameOwner}, there's always one such ancestor to any request. */ public String getDescriptorUrl() { return "descriptorByName/"+clazz.getName(); } private String getCurrentDescriptorByNameUrl() { StaplerRequest req = Stapler.getCurrentRequest(); Ancestor a = req.findAncestor(DescriptorByNameOwner.class); return a.getUrl(); } /** * If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method, * return the form-field validation string. Otherwise null. * <p> * This method is used to hook up the form validation method to the corresponding HTML input element. */ public String getCheckUrl(String fieldName) { String method = checkMethods.get(fieldName); if(method==null) { method = calcCheckUrl(fieldName); checkMethods.put(fieldName,method); } if (method.equals(NONE)) // == would do, but it makes IDE flag a warning return null; // put this under the right contextual umbrella. // a is always non-null because we already have Hudson as the sentinel return singleQuote(getCurrentDescriptorByNameUrl()+'/')+'+'+method; } private String calcCheckUrl(String fieldName) { String capitalizedFieldName = StringUtils.capitalize(fieldName); Method method = ReflectionUtils.getPublicMethodNamed(getClass(),"doCheck"+ capitalizedFieldName); if(method==null) return NONE; return singleQuote(getDescriptorUrl() +"/check"+capitalizedFieldName) + buildParameterList(method, new StringBuilder()).append(".toString()"); } /** * Builds query parameter line by figuring out what should be submitted */ private StringBuilder buildParameterList(Method method, StringBuilder query) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp!=null) { String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. if (query.length()==0) query.append("+qs(this)"); if (name.equals("value")) { // The special 'value' parameter binds to the the current field query.append(".addThis()"); } else { query.append(".nearBy('"+name+"')"); } continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); if (m!=null) buildParameterList(m,query); } return query; } /** * Computes the list of other form fields that the given field depends on, via the doFillXyzItems method, * and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and * sets that as the 'fillUrl' attribute. */ public void calcFillSettings(String field, Map<String,Object> attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doFill" + capitalizedFieldName + "Items"; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); if(method==null) throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName)); // build query parameter line by figuring out what should be submitted List<String> depends = new ArrayList<String>(); for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); if (qp==null) continue; String name = qp.value(); if (name.length()==0) name = p.name(); if (name==null || name.length()==0) continue; // unknown parameter name. we'll report the error when the form is submitted. depends.add(name); } if (!depends.isEmpty()) attributes.put("fillDependsOn",Util.join(depends," ")); attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); } /** * Obtains the property type of the given field of {@link #clazz} */ public PropertyType getPropertyType(String field) { if(propertyTypes ==null) { Map<String, PropertyType> r = new HashMap<String, PropertyType>(); for (Field f : clazz.getFields()) r.put(f.getName(),new PropertyType(f)); for (Method m : clazz.getMethods()) if(m.getName().startsWith("get")) r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m)); propertyTypes = r; } return propertyTypes.get(field); } /** * Gets the class name nicely escaped to be usable as a key in the structured form submission. */ public final String getJsonSafeClassName() { return clazz.getName().replace('.','-'); } /** * @deprecated * Implement {@link #newInstance(StaplerRequest, JSONObject)} method instead. * Deprecated as of 1.145. */ public T newInstance(StaplerRequest req) throws FormException { throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)"); } /** * Creates a configured instance from the submitted form. * * <p> * Hudson only invokes this method when the user wants an instance of <tt>T</tt>. * So there's no need to check that in the implementation. * * <p> * Starting 1.206, the default implementation of this method does the following: * <pre> * req.bindJSON(clazz,formData); * </pre> * <p> * ... which performs the databinding on the constructor of {@link #clazz}. * * <p> * For some types of {@link Describable}, such as {@link ListViewColumn}, this method * can be invoked with null request object for historical reason. Such design is considered * broken, but due to the compatibility reasons we cannot fix it. Because of this, the * default implementation gracefully handles null request, but the contract of the method * still is "request is always non-null." Extension points that need to define the "default instance" * semantics should define a descriptor subtype and add the no-arg newInstance method. * * @param req * Always non-null (see note above.) This object includes represents the entire submission. * @param formData * The JSON object that captures the configuration data for this {@link Descriptor}. * See http://hudson.gotdns.com/wiki/display/HUDSON/Structured+Form+Submission * Always non-null. * * @throws FormException * Signals a problem in the submitted form. * @since 1.145 */ public T newInstance(StaplerRequest req, JSONObject formData) throws FormException { try { Method m = getClass().getMethod("newInstance", StaplerRequest.class); if(!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) { // this class overrides newInstance(StaplerRequest). // maintain the backward compatible behavior return newInstance(req); } else { if (req==null) { // yes, req is supposed to be always non-null, but see the note above return clazz.newInstance(); } // new behavior as of 1.206 return req.bindJSON(clazz,formData); } } catch (NoSuchMethodException e) { throw new AssertionError(e); // impossible } catch (InstantiationException e) { throw new Error(e); } catch (IllegalAccessException e) { throw new Error(e); } } /** * Returns the resource path to the help screen HTML, if any. * * <p> * Starting 1.282, this method uses "convention over configuration" &mdash; you should * just put the "help.html" (and its localized versions, if any) in the same directory * you put your Jelly view files, and this method will automatically does the right thing. * * <p> * This value is relative to the context root of Hudson, so normally * the values are something like <tt>"/plugin/emma/help.html"</tt> to * refer to static resource files in a plugin, or <tt>"/publisher/EmmaPublisher/abc"</tt> * to refer to Jelly script <tt>abc.jelly</tt> or a method <tt>EmmaPublisher.doAbc()</tt>. * * @return * null to indicate that there's no help. */ public String getHelpFile() { return getHelpFile(null); } /** * Returns the path to the help screen HTML for the given field. * * <p> * The help files are assumed to be at "help/FIELDNAME.html" with possible * locale variations. */ public String getHelpFile(final String fieldName) { for(Class c=clazz; c!=null; c=c.getSuperclass()) { String page = "/descriptor/" + clazz.getName() + "/help"; String suffix; if(fieldName==null) { suffix=""; } else { page += '/'+fieldName; suffix='-'+fieldName; } try { if(Stapler.getCurrentRequest().getView(c,"help"+suffix)!=null) return page; } catch (IOException e) { throw new Error(e); } InputStream in = getHelpStream(c,suffix); IOUtils.closeQuietly(in); if(in!=null) return page; } return null; } /** * Checks if the given object is created from this {@link Descriptor}. */ public final boolean isInstance( T instance ) { return clazz.isInstance(instance); } /** * Checks if the type represented by this descriptor is a subtype of the given type. */ public final boolean isSubTypeOf(Class type) { return type.isAssignableFrom(clazz); } /** * @deprecated * As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}. */ public boolean configure( StaplerRequest req ) throws FormException { return true; } /** * Invoked when the global configuration page is submitted. * * Can be overriden to store descriptor-specific information. * * @param json * The JSON object that captures the configuration data for this {@link Descriptor}. * See http://hudson.gotdns.com/wiki/display/HUDSON/Structured+Form+Submission * @return false * to keep the client in the same config page. */ public boolean configure( StaplerRequest req, JSONObject json ) throws FormException { // compatibility return configure(req); } public String getConfigPage() { return getViewPage(clazz, "config.jelly"); } public String getGlobalConfigPage() { return getViewPage(clazz, "global.jelly"); } protected final String getViewPage(Class<?> clazz, String pageName) { while(clazz!=Object.class) { String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName; if(clazz.getClassLoader().getResource(name)!=null) return '/'+name; clazz = clazz.getSuperclass(); } // We didn't find the configuration page. // Either this is non-fatal, in which case it doesn't matter what string we return so long as // it doesn't exist. // Or this error is fatal, in which case we want the developer to see what page he's missing. // so we put the page name. return pageName; } /** * Saves the configuration info to the disk. */ public synchronized void save() { if(BulkChange.contains(this)) return; try { getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e); } } /** * Loads the data from the disk into this object. * * <p> * The constructor of the derived class must call this method. * (If we do that in the base class, the derived class won't * get a chance to set default values.) */ public synchronized void load() { XmlFile file = getConfigFile(); if(!file.exists()) return; try { file.unmarshal(this); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+file, e); } } private XmlFile getConfigFile() { return new XmlFile(new File(Hudson.getInstance().getRootDir(),clazz.getName()+".xml")); } /** * Serves <tt>help.html</tt> from the resource of {@link #clazz}. */ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); if(path.contains("..")) throw new ServletException("Illegal path: "+path); path = path.replace('/','-'); for (Class c=clazz; c!=null; c=c.getSuperclass()) { RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help"+path); if(rd!=null) {// Jelly-generated help page rd.forward(req,rsp); return; } InputStream in = getHelpStream(c,path); if(in!=null) { // TODO: generalize macro expansion and perhaps even support JEXL rsp.setContentType("text/html;charset=UTF-8"); String literal = IOUtils.toString(in,"UTF-8"); rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath()))); in.close(); return; } } rsp.sendError(SC_NOT_FOUND); } private InputStream getHelpStream(Class c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); String base = c.getName().replace('.', '/').replace('$','/') + "/help"+suffix; ClassLoader cl = c.getClassLoader(); if(cl==null) return null; InputStream in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); if(in!=null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); if(in!=null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + ".html"); if(in!=null) return in; // default return cl.getResourceAsStream(base+".html"); } // // static methods // // to work around warning when creating a generic array type public static <T> T[] toArray( T... values ) { return values; } public static <T> List<T> toList( T... values ) { return new ArrayList<T>(Arrays.asList(values)); } public static <T extends Describable<T>> Map<Descriptor<T>,T> toMap(Iterable<T> describables) { Map<Descriptor<T>,T> m = new LinkedHashMap<Descriptor<T>,T>(); for (T d : describables) { m.put(d.getDescriptor(),d); } return m; } /** * Used to build {@link Describable} instance list from &lt;f:hetero-list> tag. * * @param req * Request that represents the form submission. * @param formData * Structured form data that represents the contains data for the list of describables. * @param key * The JSON property name for 'formData' that represents the data for the list of describables. * @param descriptors * List of descriptors to create instances from. * @return * Can be empty but never null. */ public static <T extends Describable<T>> List<T> newInstancesFromHeteroList(StaplerRequest req, JSONObject formData, String key, Collection<? extends Descriptor<T>> descriptors) throws FormException { List<T> items = new ArrayList<T>(); if(!formData.has(key)) return items; JSONArray a = JSONArray.fromObject(formData.get(key)); for (Object o : a) { JSONObject jo = (JSONObject)o; String kind = jo.getString("kind"); items.add(find(descriptors,kind).newInstance(req,jo)); } return items; } /** * Finds a descriptor from a collection by its class name. */ public static <T extends Descriptor> T find(Collection<? extends T> list, String className) { for (T d : list) { if(d.getClass().getName().equals(className)) return d; } return null; } public static Descriptor find(String className) { return find(Hudson.getInstance().getExtensionList(Descriptor.class),className); } public static final class FormException extends Exception implements HttpResponse { private final String formField; public FormException(String message, String formField) { super(message); this.formField = formField; } public FormException(String message, Throwable cause, String formField) { super(message, cause); this.formField = formField; } public FormException(Throwable cause, String formField) { super(cause); this.formField = formField; } /** * Which form field contained an error? */ public String getFormField() { return formField; } public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { // for now, we can't really use the field name that caused the problem. new Failure(getMessage()).generateResponse(req,rsp,node); } } private static final Logger LOGGER = Logger.getLogger(Descriptor.class.getName()); /** * Used in {@link #checkMethods} to indicate that there's no check method. */ private static final String NONE = "\u0000"; private Object readResolve() { if (properties!=null) OldDataMonitor.report(this, "1.62"); return this; } }
@fillUrl should take the public static fromStapler method into account. git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@30448 71c3de6d-444a-0410-be80-ed276b4c234a
core/src/main/java/hudson/model/Descriptor.java
@fillUrl should take the public static fromStapler method into account.
<ide><path>ore/src/main/java/hudson/model/Descriptor.java <ide> throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName)); <ide> <ide> // build query parameter line by figuring out what should be submitted <del> List<String> depends = new ArrayList<String>(); <del> <del> for (Parameter p : ReflectionUtils.getParameters(method)) { <del> QueryParameter qp = p.annotation(QueryParameter.class); <del> if (qp==null) continue; <del> <del> String name = qp.value(); <del> if (name.length()==0) name = p.name(); <del> if (name==null || name.length()==0) <del> continue; // unknown parameter name. we'll report the error when the form is submitted. <del> <del> depends.add(name); <del> } <add> List<String> depends = buildFillDependencies(method, new ArrayList<String>()); <ide> <ide> if (!depends.isEmpty()) <ide> attributes.put("fillDependsOn",Util.join(depends," ")); <ide> attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); <add> } <add> <add> private List<String> buildFillDependencies(Method method, List<String> depends) { <add> for (Parameter p : ReflectionUtils.getParameters(method)) { <add> QueryParameter qp = p.annotation(QueryParameter.class); <add> if (qp!=null) { <add> String name = qp.value(); <add> if (name.length()==0) name = p.name(); <add> if (name==null || name.length()==0) <add> continue; // unknown parameter name. we'll report the error when the form is submitted. <add> <add> depends.add(name); <add> continue; <add> } <add> <add> Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); <add> if (m!=null) <add> buildFillDependencies(m,depends); <add> } <add> return depends; <ide> } <ide> <ide> /**
Java
apache-2.0
f729ab6c36e4dd5614abc64bf8880ced5edbf63a
0
fkeglevich/Raw-Dumper,fkeglevich/Raw-Dumper,fkeglevich/Raw-Dumper
/* * Copyright 2017, Flávio Keglevich * * 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.fkeglevich.rawdumper.io.async.function; import android.util.Log; import com.fkeglevich.rawdumper.async.function.ThrowingAsyncFunction; import com.fkeglevich.rawdumper.raw.info.DeviceInfo; import com.fkeglevich.rawdumper.raw.info.DeviceInfoLoader; import com.fkeglevich.rawdumper.util.exception.MessageException; /** * Created by Flávio Keglevich on 03/09/2017. * TODO: Add a class header comment! */ public class LoadDeviceInfoFunction extends ThrowingAsyncFunction<Void, DeviceInfo, MessageException> { @Override protected DeviceInfo call(Void argument) throws MessageException { try { return new DeviceInfoLoader().loadDeviceInfo(); } catch (RuntimeException re) { re.printStackTrace(); Log.e("LoadDeviceInfoFunction", "RuntimeException: " + re.getMessage()); throw re; } } }
app/src/main/java/com/fkeglevich/rawdumper/io/async/function/LoadDeviceInfoFunction.java
/* * Copyright 2017, Flávio Keglevich * * 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.fkeglevich.rawdumper.io.async.function; import android.util.Log; import com.fkeglevich.rawdumper.async.function.ThrowingAsyncFunction; import com.fkeglevich.rawdumper.raw.info.DeviceInfo; import com.fkeglevich.rawdumper.raw.info.DeviceInfoLoader; import com.fkeglevich.rawdumper.util.exception.MessageException; /** * Created by Flávio Keglevich on 03/09/2017. * TODO: Add a class header comment! */ public class LoadDeviceInfoFunction extends ThrowingAsyncFunction<Void, DeviceInfo, MessageException> { @Override protected DeviceInfo call(Void argument) throws MessageException { try { return new DeviceInfoLoader().loadDeviceInfo(); } catch (RuntimeException re) { Log.e("LoadDeviceInfoFunction", "RuntimeException: " + re.getMessage()); throw re; } } }
Easier debugging
app/src/main/java/com/fkeglevich/rawdumper/io/async/function/LoadDeviceInfoFunction.java
Easier debugging
<ide><path>pp/src/main/java/com/fkeglevich/rawdumper/io/async/function/LoadDeviceInfoFunction.java <ide> } <ide> catch (RuntimeException re) <ide> { <add> re.printStackTrace(); <ide> Log.e("LoadDeviceInfoFunction", "RuntimeException: " + re.getMessage()); <ide> throw re; <ide> }
Java
apache-2.0
0bb0b6e704d4aeb87415dd9c315dfee3053edfe1
0
appNG/appng,appNG/appng,appNG/appng
/* * Copyright 2011-2018 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.appng.core.controller; import static org.apache.commons.lang3.time.DateFormatUtils.format; import java.util.ArrayList; import java.util.Enumeration; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.apache.commons.collections.list.UnmodifiableList; import org.appng.api.Environment; import org.appng.api.Platform; import org.appng.api.RequestUtil; import org.appng.api.Scope; import org.appng.api.model.Properties; import org.appng.api.model.Site; import org.appng.api.support.environment.DefaultEnvironment; import org.appng.core.domain.PlatformEvent.Type; import org.appng.core.service.CoreService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.context.ApplicationContext; /** * A (ServletContext/HttpSession/ServletRequest) listener that keeps track of creation/destruction and usage of * {@link HttpSession}s. * * @author Matthias Herlitzius * @author Matthias Müller */ @WebListener public class SessionListener implements ServletContextListener, HttpSessionListener, ServletRequestListener { private static Logger LOGGER = LoggerFactory.getLogger(SessionListener.class); private static final Class<org.apache.catalina.connector.Request> CATALINA_REQUEST = org.apache.catalina.connector.Request.class; private static final String HTTPS = "https"; public static final String SESSIONS = "sessions"; public static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; private static final ConcurrentMap<String, Session> SESSION_MAP = new ConcurrentHashMap<String, Session>(); public void contextInitialized(ServletContextEvent sce) { DefaultEnvironment env = DefaultEnvironment.get(sce.getServletContext()); saveSessions(env); } public void contextDestroyed(ServletContextEvent sce) { DefaultEnvironment env = DefaultEnvironment.get(sce.getServletContext()); SESSION_MAP.clear(); env.removeAttribute(Scope.PLATFORM, SESSIONS); } public void sessionCreated(HttpSessionEvent event) { createSession(event.getSession()); } private Session createSession(HttpSession httpSession) { DefaultEnvironment env = DefaultEnvironment.get(httpSession); Properties platformConfig = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); Integer sessionTimeout = platformConfig.getInteger(Platform.Property.SESSION_TIMEOUT); httpSession.setMaxInactiveInterval(sessionTimeout); Session session = new Session(httpSession.getId()); session.update(httpSession.getCreationTime(), httpSession.getLastAccessedTime(), httpSession.getMaxInactiveInterval()); SESSION_MAP.put(session.getId(), session); saveSessions(env); env.setAttribute(Scope.SESSION, org.appng.api.Session.Environment.SID, httpSession.getId()); env.setAttribute(Scope.SESSION, org.appng.api.Session.Environment.TIMEOUT, httpSession.getMaxInactiveInterval()); env.setAttribute(Scope.SESSION, org.appng.api.Session.Environment.STARTTIME, httpSession.getCreationTime() / 1000L); LOGGER.info("Session created: {} (created: {})", session.getId(), format(session.getCreationTime(), DATE_PATTERN)); return session; } public void sessionDestroyed(HttpSessionEvent event) { HttpSession httpSession = event.getSession(); Environment env = DefaultEnvironment.get(httpSession); if (env.isSubjectAuthenticated()) { ApplicationContext ctx = env.getAttribute(Scope.PLATFORM, Platform.Environment.CORE_PLATFORM_CONTEXT); ctx.getBean(CoreService.class).createEvent(Type.INFO, "session expired", httpSession); } if (!destroySession(httpSession.getId(), env)) { LOGGER.info("Session destroyed: {} (created: {}, accessed: {})", httpSession.getId(), format(httpSession.getCreationTime(), DATE_PATTERN), format(httpSession.getLastAccessedTime(), DATE_PATTERN)); } } protected static boolean destroySession(String sessionId, Environment env) { Session session = SESSION_MAP.remove(sessionId); if (null != session) { saveSessions(env); LOGGER.info("Session destroyed: {} (created: {}, accessed: {}, requests: {}, domain: {}, user-agent: {})", session.getId(), format(session.getCreationTime(), DATE_PATTERN), format(session.getLastAccessedTime(), DATE_PATTERN), session.getRequests(), session.getDomain(), session.getUserAgent()); return true; } return false; } public void requestInitialized(ServletRequestEvent sre) { ServletRequest request = sre.getServletRequest(); DefaultEnvironment env = DefaultEnvironment.get(sre.getServletContext(), request); HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpSession httpSession = httpServletRequest.getSession(); Site site = RequestUtil.getSite(env, request); setSecureFlag(httpServletRequest, site); setDiagnosticContext(env, httpServletRequest, site); Session session = SESSION_MAP.get(httpSession.getId()); if (null == session) { session = createSession(httpSession); } session.update(httpSession.getCreationTime(), httpSession.getLastAccessedTime(), httpSession.getMaxInactiveInterval()); session.setSite(null == site ? null : site.getName()); session.setDomain(site == null ? null : site.getDomain()); session.setUser(env.getSubject() == null ? null : env.getSubject().getAuthName()); session.setIp(request.getRemoteAddr()); session.setUserAgent(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)); session.addRequest(); if (LOGGER.isTraceEnabled()) { String referer = httpServletRequest.getHeader(HttpHeaders.REFERER); LOGGER.trace( "Session updated: {} (created: {}, accessed: {}, requests: {}, domain: {}, user-agent: {}, path: {}, referer: {})", session.getId(), format(session.getCreationTime(), DATE_PATTERN), format(session.getLastAccessedTime(), DATE_PATTERN), session.getRequests(), session.getDomain(), session.getUserAgent(), httpServletRequest.getServletPath(), referer); } } protected void setDiagnosticContext(Environment env, HttpServletRequest httpServletRequest, Site site) { Properties platformConfig = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); if (platformConfig.getBoolean(Platform.Property.MDC_ENABLED)) { MDC.put("path", httpServletRequest.getServletPath()); String queryString = httpServletRequest.getQueryString(); if (null != queryString) { MDC.put("query", queryString); } MDC.put("sessionID", httpServletRequest.getSession().getId()); if (null != site) { MDC.put("site", site.getName()); } MDC.put("locale", env.getLocale().toString()); MDC.put("method", httpServletRequest.getMethod()); MDC.put("timezone", env.getTimeZone().getID()); MDC.put("ip", httpServletRequest.getRemoteAddr()); if (null != env.getSubject() && null != env.getSubject().getAuthName()) { MDC.put("user", env.getSubject().getAuthName()); } else { MDC.put("user", "-unknown-"); } Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); MDC.put("h." + name.toLowerCase(), httpServletRequest.getHeader(name)); } } } protected void setSecureFlag(HttpServletRequest httpServletRequest, Site site) { if (!httpServletRequest.isSecure() && ((null != site && site.getDomain().startsWith(HTTPS)) || HttpHeaders.isRequestSecure(httpServletRequest)) && CATALINA_REQUEST.isAssignableFrom(httpServletRequest.getClass())) { CATALINA_REQUEST.cast(httpServletRequest).setSecure(true); } } public void requestDestroyed(ServletRequestEvent sre) { MDC.clear(); } private static void saveSessions(Environment env) { env.setAttribute(Scope.PLATFORM, SESSIONS, UnmodifiableList.decorate(new ArrayList<Session>(SESSION_MAP.values()))); } }
appng-core/src/main/java/org/appng/core/controller/SessionListener.java
/* * Copyright 2011-2018 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.appng.core.controller; import static org.apache.commons.lang3.time.DateFormatUtils.format; import java.util.ArrayList; import java.util.Enumeration; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.apache.commons.collections.list.UnmodifiableList; import org.appng.api.Environment; import org.appng.api.Platform; import org.appng.api.RequestUtil; import org.appng.api.Scope; import org.appng.api.model.Properties; import org.appng.api.model.Site; import org.appng.api.support.environment.DefaultEnvironment; import org.appng.core.domain.PlatformEvent.Type; import org.appng.core.service.CoreService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.context.ApplicationContext; /** * A (ServletContext/HttpSession/ServletRequest) listener that keeps track of creation/destruction and usage of * {@link HttpSession}s. * * @author Matthias Herlitzius * @author Matthias Müller */ @WebListener public class SessionListener implements ServletContextListener, HttpSessionListener, ServletRequestListener { private static Logger LOGGER = LoggerFactory.getLogger(SessionListener.class); private static final Class<org.apache.catalina.connector.Request> CATALINA_REQUEST = org.apache.catalina.connector.Request.class; private static final String HTTPS = "https"; public static final String SESSIONS = "sessions"; public static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; private static final ConcurrentMap<String, Session> SESSION_MAP = new ConcurrentHashMap<String, Session>(); public void contextInitialized(ServletContextEvent sce) { DefaultEnvironment env = DefaultEnvironment.get(sce.getServletContext()); saveSessions(env); } public void contextDestroyed(ServletContextEvent sce) { DefaultEnvironment env = DefaultEnvironment.get(sce.getServletContext()); SESSION_MAP.clear(); env.removeAttribute(Scope.PLATFORM, SESSIONS); } public void sessionCreated(HttpSessionEvent event) { createSession(event.getSession()); } private Session createSession(HttpSession httpSession) { DefaultEnvironment env = DefaultEnvironment.get(httpSession); Properties platformConfig = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); Integer sessionTimeout = platformConfig.getInteger(Platform.Property.SESSION_TIMEOUT); httpSession.setMaxInactiveInterval(sessionTimeout); Session session = new Session(httpSession.getId()); session.update(httpSession.getCreationTime(), httpSession.getLastAccessedTime(), httpSession.getMaxInactiveInterval()); SESSION_MAP.put(session.getId(), session); saveSessions(env); env.setAttribute(Scope.SESSION, org.appng.api.Session.Environment.SID, httpSession.getId()); env.setAttribute(Scope.SESSION, org.appng.api.Session.Environment.TIMEOUT, httpSession.getMaxInactiveInterval()); env.setAttribute(Scope.SESSION, org.appng.api.Session.Environment.STARTTIME, httpSession.getCreationTime() / 1000L); LOGGER.info("Session created: {} (created: {})", session.getId(), format(session.getCreationTime(), DATE_PATTERN)); return session; } public void sessionDestroyed(HttpSessionEvent event) { HttpSession httpSession = event.getSession(); Environment env = DefaultEnvironment.get(httpSession); if (env.isSubjectAuthenticated()) { ApplicationContext ctx = env.getAttribute(Scope.PLATFORM, Platform.Environment.CORE_PLATFORM_CONTEXT); ctx.getBean(CoreService.class).createEvent(Type.INFO, "session expired", httpSession); } if (!destroySession(httpSession.getId(), env)) { LOGGER.info("Session destroyed: {} (created: {}, accessed: {})", httpSession.getId(), format(httpSession.getCreationTime(), DATE_PATTERN), format(httpSession.getLastAccessedTime(), DATE_PATTERN)); } } protected static boolean destroySession(String sessionId, Environment env) { Session session = SESSION_MAP.remove(sessionId); if (null != session) { saveSessions(env); LOGGER.info("Session destroyed: {} (created: {}, accessed: {}, requests: {}, domain: {}, user-agent: {})", session.getId(), format(session.getCreationTime(), DATE_PATTERN), format(session.getLastAccessedTime(), DATE_PATTERN), session.getRequests(), session.getDomain(), session.getUserAgent()); return true; } return false; } public void requestInitialized(ServletRequestEvent sre) { ServletRequest request = sre.getServletRequest(); DefaultEnvironment env = DefaultEnvironment.get(sre.getServletContext(), request); HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpSession httpSession = httpServletRequest.getSession(); Site site = RequestUtil.getSite(env, request); setSecureFlag(httpServletRequest, site); setDiagnosticContext(env, httpServletRequest, site); Session session = SESSION_MAP.get(httpSession.getId()); if (null == session) { session = createSession(httpSession); } session.update(httpSession.getCreationTime(), httpSession.getLastAccessedTime(), httpSession.getMaxInactiveInterval()); session.setSite(null == site ? null : site.getName()); session.setDomain(site == null ? null : site.getDomain()); session.setUser(env.getSubject() == null ? null : env.getSubject().getAuthName()); session.setIp(request.getRemoteAddr()); session.setUserAgent(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)); session.addRequest(); if (LOGGER.isTraceEnabled()) { String referer = httpServletRequest.getHeader(HttpHeaders.REFERER); LOGGER.trace( "Session updated: {} (created: {}, accessed: {}, requests: {}, domain: {}, user-agent: {}, path: {}, referer: {})", session.getId(), format(session.getCreationTime(), DATE_PATTERN), format(session.getLastAccessedTime(), DATE_PATTERN), session.getRequests(), session.getDomain(), session.getUserAgent(), httpServletRequest.getServletPath(), referer); } } protected void setDiagnosticContext(Environment env, HttpServletRequest httpServletRequest, Site site) { Properties platformConfig = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); if (platformConfig.getBoolean(Platform.Property.MDC_ENABLED)) { MDC.put("path", httpServletRequest.getServletPath()); String queryString = httpServletRequest.getQueryString(); if (null != queryString) { MDC.put("query", queryString); } MDC.put("sessionID", httpServletRequest.getSession().getId()); if (null != site) { MDC.put("site", site.getName()); } MDC.put("locale", env.getLocale().toString()); MDC.put("timezone", env.getTimeZone().getID()); MDC.put("ip", httpServletRequest.getRemoteAddr()); if (null != env.getSubject() && null != env.getSubject().getAuthName()) { MDC.put("user", env.getSubject().getAuthName()); } else { MDC.put("user", "-unknown-"); } Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); MDC.put("h." + name.toLowerCase(), httpServletRequest.getHeader(name)); } } } protected void setSecureFlag(HttpServletRequest httpServletRequest, Site site) { if (!httpServletRequest.isSecure() && ((null != site && site.getDomain().startsWith(HTTPS)) || HttpHeaders.isRequestSecure(httpServletRequest)) && CATALINA_REQUEST.isAssignableFrom(httpServletRequest.getClass())) { CATALINA_REQUEST.cast(httpServletRequest).setSecure(true); } } public void requestDestroyed(ServletRequestEvent sre) { MDC.clear(); } private static void saveSessions(Environment env) { env.setAttribute(Scope.PLATFORM, SESSIONS, UnmodifiableList.decorate(new ArrayList<Session>(SESSION_MAP.values()))); } }
APPNG-2193 support http method in MDC
appng-core/src/main/java/org/appng/core/controller/SessionListener.java
APPNG-2193 support http method in MDC
<ide><path>ppng-core/src/main/java/org/appng/core/controller/SessionListener.java <ide> MDC.put("site", site.getName()); <ide> } <ide> MDC.put("locale", env.getLocale().toString()); <add> MDC.put("method", httpServletRequest.getMethod()); <ide> MDC.put("timezone", env.getTimeZone().getID()); <ide> MDC.put("ip", httpServletRequest.getRemoteAddr()); <ide> if (null != env.getSubject() && null != env.getSubject().getAuthName()) {
JavaScript
bsd-3-clause
69a84151a733cbca303b835a923bf897aea1cd32
0
stevenliuit/echarts,gastrodia/echarts,JudeRosario/echarts,logchi/echarts,gspandy/echarts,ecomfe/echarts,lyhiving/echarts,starlkj/echarts,zhaosichao/echarts,kener/echarts,upeng/echarts,xiaoqqchen/echarts,mortonfox/echarts,gaorongchao/echarts,cnbin/echarts,howepeng/echarts,wziyong/echarts,Snister/echarts,ymero/echarts,gastrodia/echarts,kimyongyeon/echarts,PanPanda/echarts,oceanjack/echarts,gregoriusxu/echarts,likaiwalkman/echarts,wxt2005/echarts,krahman/echarts,kakuhiroshi/echarts,laomu1988/echarts,XiaoqingWang/echarts,flashbuckets/echarts,studycwq/echarts,trigrass2/echarts,zhaosichao/echarts,ssxxue/echarts,wells-chen/echarts,liu006006/echarts,westsource/echarts,fiona23/echarts,jokerCode/echarts,dyx/echarts,Ovilia/echarts,darongE/echarts,Snister/echarts,apache/incubator-echarts,amosworker/echarts,echarts/echarts,mlc0202/echarts,niaoren/echarts,tianzhihen/echarts,antoniodesouza/echarts,benjaminbecktg/echarts,zhangbg/echarts,ZHANGJIE982/echarts,ChaosPower/echarts,kingfengji/echarts,echarts/echarts,wwwcs59/echarts,willseeyou/echarts,mubassirhayat/echarts,gaopeng8911/echarts,leisurelicht/echarts,flashbuckets/echarts,faustinoloeza/echarts,jessiejea/echarts,ibollen/echarts,jianjian0dandan/echarts,jianjian0dandan/echarts,jjviscomi/echarts,Ovilia/echarts,queenqueen/echarts,amosworker/echarts,darongE/echarts,wangshijun/echarts,wskplho/echarts,hexj/echarts,guazipi/echarts,jokerCode/echarts,Second-J-L/echarts,jessiejea/echarts,cnbin/echarts,favors-xue/echarts,ycaihua/echarts,kirahan/echarts,globalways/echarts,kirahan/echarts,wangjun/echarts,zhouchao3/echarts,chinakids/echarts,tianzhihen/echarts,ChaosPower/echarts,xfstudio/echarts,benjaminbecktg/echarts,evilemon/echarts,fiona23/echarts,xiayz/echarts,dieface/echarts,zhiyishou/echarts,gaorongchao/echarts,globalways/echarts,kakuhiroshi/echarts,Second-J-L/echarts,jack-Lee-2015/echarts,niaoren/echarts,codeaudit/echarts,hujianfei1989/echarts,jkdcdlly/echarts,jkdcdlly/echarts,NightmareLee888/echarts,wziyong/echarts,dbabox/echarts,linvan/echarts,kingfengji/echarts,kimyongyeon/echarts,100star/echarts,CoffeeCool/echarts,hexj/echarts,HelloYu/echarts,ShefronYudy/echarts,dbabox/echarts,leisurelicht/echarts,willseeyou/echarts,gbk/echarts,zhoulijie/echarts,allenaware/echarts,lunyang/echarts,FutureElement/echarts,mlc0202/echarts,CoffeeCool/echarts,zhiyishou/echarts,xfstudio/echarts,starlkj/echarts,wxt2005/echarts,jueqingsizhe66/echarts,ecomfe/echarts,faustinoloeza/echarts,yubin-huang/echarts,nagyistoce/dato-code-echarts,kingzou/echarts,oceanjack/echarts,wangjun/echarts,yubin-huang/echarts,gitmefive/echarts,heyhawaii/echarts,wangshijun/echarts,JimmyBenKlieve/echarts,hexj/echarts,gxcnupt08/echarts,Ju5Fly/echarts,dieface/echarts,OrcaAnewOne/echarts,cloudsharl/echarts,favors-xue/echarts,kevinc0825/echarts,likaiwalkman/echarts,apache/incubator-echarts,stevenliuit/echarts,linvan/echarts,izhoujie/echarts,xialiangtime/echarts,kevinc0825/echarts,xhuljp/echarts,willseeyou/echarts,loutongbing/echarts,xiaomy001/echarts,westsource/echarts,starlkj/echarts,adminers/echarts,opui/echarts,gbk/echarts,jl9n/echarts,Powww/echarts,guazipi/echarts,kingzou/echarts,allenaware/echarts,vivovip/echarts,yuanrui/echarts,wells-chen/echarts,stanleyxu2005/echarts,benjaminbecktg/echarts,berserkertdl/echarts,laomu1988/echarts,dato-code/echarts,yuanrui/echarts,michaeljunlove/echarts,tanghaohao/echarts,zhangbg/echarts,heyhawaii/echarts,ilovezy/echarts,studycwq/echarts,XiaoqingWang/echarts,NightmareLee888/echarts,Ju5Fly/echarts,adminers/echarts,ibollen/echarts,rainrain/echarts,xuanxinpl/echarts,nagyistoce/dato-code-echarts,uooo/echarts,opui/echarts,xuanxinpl/echarts,justinleoye/echarts,jjviscomi/echarts,tanghaohao/echarts,chenfwind/echarts,berserkertdl/echarts,howepeng/echarts,gitmefive/echarts,ShefronYudy/echarts,zhoulijie/echarts,liubao19860416/amaze-echarts,codeaudit/echarts,dato-code/echarts,jack-Lee-2015/echarts,liu006006/echarts,timmyz/echarts,spetpet/echarts,vivovip/echarts,evilemon/echarts,mortonfox/echarts,zhouchao3/echarts,wskplho/echarts,upeng/echarts,jl9n/echarts,gregoriusxu/echarts,liubao19860416/amaze-echarts,zctea/echarts,xialiangtime/echarts,fanmingjun/echarts,ymero/echarts,PanPanda/echarts,JudeRosario/echarts,HelloYu/echarts,queenqueen/echarts,spetpet/echarts,rainrain/echarts,ilovezy/echarts,gaopeng8911/echarts,timmyz/echarts,xhuljp/echarts,jueqingsizhe66/echarts,FutureElement/echarts,logchi/echarts,antoniodesouza/echarts,OrcaAnewOne/echarts,chenfwind/echarts,michaeljunlove/echarts,JimmyBenKlieve/echarts,lunyang/echarts,xiayz/echarts,hujianfei1989/echarts,xiaomy001/echarts,wwwcs59/echarts,qss2012/echarts,stanleyxu2005/echarts,cloudsharl/echarts,gxcnupt08/echarts,gspandy/echarts,izhoujie/echarts,qss2012/echarts,Powww/echarts,xiaoqqchen/echarts,kener/echarts,loutongbing/echarts,100star/echarts,fanmingjun/echarts,justinleoye/echarts,trigrass2/echarts,uooo/echarts,zctea/echarts,lyhiving/echarts,dyx/echarts,ssxxue/echarts,ZHANGJIE982/echarts
/** * echarts组件:提示框 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author Kener (@Kener-林峰, [email protected]) * */ define(function (require) { var Base = require('./base'); // 图形依赖 var LineShape = require('zrender/shape/Line'); var RectangleShape = require('zrender/shape/Rectangle'); var rectangleInstance = new RectangleShape({}); var ecConfig = require('../config'); var ecData = require('../util/ecData'); var zrConfig = require('zrender/config'); var zrEvent = require('zrender/tool/event'); var zrArea = require('zrender/tool/area'); var zrColor = require('zrender/tool/color'); var zrUtil = require('zrender/tool/util'); var zrShapeBase = require('zrender/shape/Base'); /** * 构造函数 * @param {Object} messageCenter echart消息中心 * @param {ZRender} zr zrender实例 * @param {Object} option 提示框参数 * @param {HtmlElement} dom 目标对象 * @param {ECharts} myChart 当前图表实例 */ function Tooltip(ecTheme, messageCenter, zr, option, dom, myChart) { Base.call(this, ecTheme, zr, option); this.messageCenter = messageCenter; this.dom = dom; this.myChart = myChart; this._tDom = document.createElement('div'); this._axisLineShape = new LineShape({ zlevel: this._zlevelBase, invisible : true, hoverable: false, style : { // lineWidth : 2, // strokeColor : ecConfig.categoryAxis.axisLine.lineStyle.color } }); this._axisShadowShape = new LineShape({ zlevel: 1, // grid上,chart下 invisible : true, hoverable: false, style : { // lineWidth : 10, // strokeColor : ecConfig.categoryAxis.axisLine.lineStyle.color } }); this.zr.addShape(this._axisLineShape); this.zr.addShape(this._axisShadowShape); var self = this; self._onmousemove = function (param) { return self.__onmousemove.call(self, param); }; self._onglobalout = function (param) { return self.__onglobalout.call(self, param); }; this.zr.on(zrConfig.EVENT.MOUSEMOVE, self._onmousemove); this.zr.on(zrConfig.EVENT.GLOBALOUT, self._onglobalout); self._hide = function (param) { return self.__hide.call(self, param); }; self._tryShow = function(param) { return self.__tryShow.call(self, param); } self._refixed = function(param) { return self.__refixed.call(self, param); } this.init(option, dom); } Tooltip.prototype = { type : ecConfig.COMPONENT_TYPE_TOOLTIP, // 通用样式 _gCssText : 'position:absolute;' + 'display:block;' + 'border-style:solid;' + 'white-space:nowrap;', /** * 根据配置设置dom样式 */ _style : function (opt) { if (!opt) { return ''; } var cssText = []; if (opt.transitionDuration) { var transitionText = 'left ' + opt.transitionDuration + 's,' + 'top ' + opt.transitionDuration + 's'; cssText.push( 'transition:' + transitionText ); cssText.push( '-moz-transition:' + transitionText ); cssText.push( '-webkit-transition:' + transitionText ); cssText.push( '-o-transition:' + transitionText ); } if (opt.backgroundColor) { // for sb ie~ cssText.push( 'background-Color:' + zrColor.toHex( opt.backgroundColor ) ); cssText.push('filter:alpha(opacity=70)'); cssText.push('background-Color:' + opt.backgroundColor); } if (typeof opt.borderWidth != 'undefined') { cssText.push('border-width:' + opt.borderWidth + 'px'); } if (typeof opt.borderColor != 'undefined') { cssText.push('border-color:' + opt.borderColor); } if (typeof opt.borderRadius != 'undefined') { cssText.push( 'border-radius:' + opt.borderRadius + 'px' ); cssText.push( '-moz-border-radius:' + opt.borderRadius + 'px' ); cssText.push( '-webkit-border-radius:' + opt.borderRadius + 'px' ); cssText.push( '-o-border-radius:' + opt.borderRadius + 'px' ); } var textStyle = opt.textStyle; if (textStyle) { textStyle.color && cssText.push('color:' + textStyle.color); textStyle.decoration && cssText.push( 'text-decoration:' + textStyle.decoration ); textStyle.align && cssText.push( 'text-align:' + textStyle.align ); textStyle.fontFamily && cssText.push( 'font-family:' + textStyle.fontFamily ); textStyle.fontSize && cssText.push( 'font-size:' + textStyle.fontSize + 'px' ); textStyle.fontSize && cssText.push( 'line-height:' + Math.round(textStyle.fontSize*3/2) + 'px' ); textStyle.fontStyle && cssText.push( 'font-style:' + textStyle.fontStyle ); textStyle.fontWeight && cssText.push( 'font-weight:' + textStyle.fontWeight ); } var padding = opt.padding; if (typeof padding != 'undefined') { padding = this.reformCssArray(padding); cssText.push( 'padding:' + padding[0] + 'px ' + padding[1] + 'px ' + padding[2] + 'px ' + padding[3] + 'px' ); } cssText = cssText.join(';') + ';'; return cssText; }, __hide : function () { if (this._tDom) { this._tDom.style.display = 'none'; } var needRefresh = false; if (!this._axisLineShape.invisible) { this._axisLineShape.invisible = true; this.zr.modShape(this._axisLineShape.id, this._axisLineShape); needRefresh = true; } if (!this._axisShadowShape.invisible) { this._axisShadowShape.invisible = true; this.zr.modShape(this._axisShadowShape.id, this._axisShadowShape); needRefresh = true; } if (this._lastTipShape && this._lastTipShape.tipShape.length > 0) { this.zr.delShape(this._lastTipShape.tipShape); this._lastTipShape = false; } needRefresh && this.zr.refresh(); }, _show : function (x, y, specialCssText) { var domHeight = this._tDom.offsetHeight; var domWidth = this._tDom.offsetWidth; if (x + domWidth > this._zrWidth) { // 太靠右 //x = this._zrWidth - domWidth; x -= (domWidth + 40); } if (y + domHeight > this._zrHeight) { // 太靠下 //y = this._zrHeight - domHeight; y -= (domHeight - 20); } if (y < 20) { y = 0; } this._tDom.style.cssText = this._gCssText + this._defaultCssText + (specialCssText ? specialCssText : '') + 'left:' + x + 'px;top:' + y + 'px;'; if (domHeight < 10 || domWidth < 10) { // this._zrWidth - x < 100 || this._zrHeight - y < 100 setTimeout(this._refixed, 20); } }, __refixed : function () { if (this._tDom) { var cssText = ''; var domHeight = this._tDom.offsetHeight; var domWidth = this._tDom.offsetWidth; if (this._tDom.offsetLeft + domWidth > this._zrWidth) { cssText += 'left:' + (this._zrWidth - domWidth - 20) + 'px;'; } if (this._tDom.offsetTop + domHeight > this._zrHeight) { cssText += 'top:' + (this._zrHeight - domHeight - 10) + 'px;'; } if (cssText !== '') { this._tDom.style.cssText += cssText; } } }, __tryShow : function () { var needShow; var trigger; if (!this._curTarget) { // 坐标轴事件 this._findPolarTrigger() || this._findAxisTrigger(); } else { // 数据项事件 if (this._curTarget._type == 'island' && option.tooltip.show) { this._showItemTrigger(); return; } var serie = ecData.get(this._curTarget, 'series'); var data = ecData.get(this._curTarget, 'data'); needShow = this.deepQuery( [data, serie, option], 'tooltip.show' ); if (typeof serie == 'undefined' || typeof data == 'undefined' || needShow === false ) { // 不响应tooltip的数据对象延时隐藏 clearTimeout(this._hidingTicket); clearTimeout(this._showingTicket); this._hidingTicket = setTimeout(this._hide, this._hideDelay); } else { trigger = this.deepQuery( [data, serie, option], 'tooltip.trigger' ); trigger == 'axis' ? this._showAxisTrigger( serie.xAxisIndex, serie.yAxisIndex, ecData.get(this._curTarget, 'dataIndex') ) : this._showItemTrigger(); } } }, /** * 直角系 */ _findAxisTrigger : function () { if (!this.xAxis || !this.yAxis) { this._hidingTicket = setTimeout(this._hide, this._hideDelay); return; } var series = this.option.series; var xAxisIndex; var yAxisIndex; for (var i = 0, l = series.length; i < l; i++) { // 找到第一个axis触发tooltip的系列 if (this.deepQuery( [series[i], this.option], 'tooltip.trigger' ) == 'axis' ) { xAxisIndex = series[i].xAxisIndex || 0; yAxisIndex = series[i].yAxisIndex || 0; if (this.xAxis.getAxis(xAxisIndex) && this.xAxis.getAxis(xAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 横轴为类目轴 this._showAxisTrigger(xAxisIndex, yAxisIndex, this._getNearestDataIndex('x', this.xAxis.getAxis(xAxisIndex)) ); return; } else if (this.yAxis.getAxis(yAxisIndex) && this.yAxis.getAxis(yAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 纵轴为类目轴 this._showAxisTrigger(xAxisIndex, yAxisIndex, this._getNearestDataIndex('y', this.yAxis.getAxis(yAxisIndex)) ); return; } } } }, /** * 极坐标 */ _findPolarTrigger : function () { if (!this.polar) { return false; } var x = zrEvent.getX(this._event); var y = zrEvent.getY(this._event); var polarIndex = this.polar.getNearestIndex([x, y]); var valueIndex; if (polarIndex) { valueIndex = polarIndex.valueIndex; polarIndex = polarIndex.polarIndex; } else { polarIndex = -1; } if (polarIndex != -1) { return _showPolarTrigger(polarIndex, valueIndex); } return false; }, /** * 根据坐标轴事件带的属性获取最近的axisDataIndex */ _getNearestDataIndex : function (direction, categoryAxis) { var dataIndex = -1; var x = zrEvent.getX(this._event); var y = zrEvent.getY(this._event); if (direction == 'x') { // 横轴为类目轴 var left; var right; var xEnd = this.grid.getXend(); var curCoord = categoryAxis.getCoordByIndex(dataIndex); while (curCoord < xEnd) { if (curCoord <= x) { left = curCoord; } if (curCoord >= x) { break; } curCoord = categoryAxis.getCoordByIndex(++dataIndex); right = curCoord; } if (x - left < right - x) { dataIndex -= dataIndex !== 0 ? 1 : 0; } else { // 离右边近,看是否为最后一个 if (typeof categoryAxis.getNameByIndex(dataIndex) == 'undefined' ) { dataIndex -= 1; } } return dataIndex; } else { // 纵轴为类目轴 var top; var bottom; var yStart = this.grid.getY(); var curCoord = categoryAxis.getCoordByIndex(dataIndex); while (curCoord > yStart) { if (curCoord >= y) { bottom = curCoord; } if (curCoord <= y) { break; } curCoord = categoryAxis.getCoordByIndex(++dataIndex); top = curCoord; } if (y - top > bottom - y) { dataIndex -= dataIndex !== 0 ? 1 : 0; } else { // 离上方边近,看是否为最后一个 if (typeof categoryAxis.getNameByIndex(dataIndex) == 'undefined' ) { dataIndex -= 1; } } return dataIndex; } return -1; }, /** * 直角系 */ _showAxisTrigger : function (xAxisIndex, yAxisIndex, dataIndex) { !this._event.connectTrigger && this.messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_IN_GRID, this._event ); if (typeof this.xAxis == 'undefined' || typeof this.yAxis == 'undefined' || typeof xAxisIndex == 'undefined' || typeof yAxisIndex == 'undefined' || dataIndex < 0 ) { // 不响应tooltip的数据对象延时隐藏 clearTimeout(this._hidingTicket); clearTimeout(this._showingTicket); this._hidingTicket = setTimeout(this._hide, this._hideDelay); return; } var series = this.option.series; var seriesArray = []; var seriesIndex = []; var categoryAxis; var x; var y; var formatter; var showContent; var specialCssText = ''; if (this.option.tooltip.trigger == 'axis') { if (this.option.tooltip.show === false) { return; } formatter = this.option.tooltip.formatter; } if (xAxisIndex != -1 && this.xAxis.getAxis(xAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 横轴为类目轴,找到所有用这条横轴并且axis触发的系列数据 categoryAxis = this.xAxis.getAxis(xAxisIndex); for (var i = 0, l = series.length; i < l; i++) { if (!this._isSelected(series[i].name)) { continue; } if (series[i].xAxisIndex == xAxisIndex && this.deepQuery( [series[i], this.option], 'tooltip.trigger' ) == 'axis' ) { showContent = this.query( series[i], 'tooltip.showContent' ) || showContent; formatter = this.query( series[i], 'tooltip.formatter' ) || formatter; specialCssText += this._style(this.query( series[i], 'tooltip' )); seriesArray.push(series[i]); seriesIndex.push(i); } } // 寻找高亮元素 this.messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_HOVER, this._event, { seriesIndex : seriesIndex, dataIndex : this.component.dataZoom ? this.component.dataZoom.getRealDataIndex( seriesIndex, dataIndex ) : dataIndex } ); y = zrEvent.getY(this._event) + 10; x = this.subPixelOptimize( categoryAxis.getCoordByIndex(dataIndex), this._axisLineWidth ); this._styleAxisPointer( seriesArray, x, this.grid.getY(), x, this.grid.getYend(), categoryAxis.getGap() ); x += 10; } else if (yAxisIndex != -1 && this.yAxis.getAxis(yAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 纵轴为类目轴,找到所有用这条纵轴并且axis触发的系列数据 categoryAxis = this.yAxis.getAxis(yAxisIndex); for (var i = 0, l = series.length; i < l; i++) { if (!this._isSelected(series[i].name)) { continue; } if (series[i].yAxisIndex == yAxisIndex && this.deepQuery( [series[i], this.option], 'tooltip.trigger' ) == 'axis' ) { showContent = this.query( series[i], 'tooltip.showContent' ) || showContent; formatter = this.query( series[i], 'tooltip.formatter' ) || formatter; specialCssText += this._style(this.query( series[i], 'tooltip' )); seriesArray.push(series[i]); seriesIndex.push(i); } } // 寻找高亮元素 this.messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_HOVER, this._event, { seriesIndex : seriesIndex, dataIndex : this.component.dataZoom ? this.component.dataZoom.getRealDataIndex( seriesIndex, dataIndex ) : dataIndex } ); x = zrEvent.getX(this._event) + 10; y = this.subPixelOptimize( categoryAxis.getCoordByIndex(dataIndex), this._axisLineWidth ); this._styleAxisPointer( seriesArray, this.grid.getX(), y, this.grid.getXend(), y, categoryAxis.getGap() ); y += 10; } if (seriesArray.length > 0) { var data; if (typeof formatter == 'function') { var params = []; for (var i = 0, l = seriesArray.length; i < l; i++) { data = seriesArray[i].data[dataIndex]; data = typeof data != 'undefined' ? (typeof data.value != 'undefined' ? data.value : data) : '-'; params.push([ seriesArray[i].name || '', categoryAxis.getNameByIndex(dataIndex), data ]); } this._curTicket = 'axis:' + dataIndex; this._tDom.innerHTML = formatter( params, this._curTicket, this._setContent ); } else if (typeof formatter == 'string') { this._curTicket = NaN; formatter = formatter.replace('{a}','{a0}') .replace('{b}','{b0}') .replace('{c}','{c0}'); for (var i = 0, l = seriesArray.length; i < l; i++) { formatter = formatter.replace( '{a' + i + '}', this._encodeHTML(seriesArray[i].name || '') ); formatter = formatter.replace( '{b' + i + '}', this._encodeHTML(categoryAxis.getNameByIndex(dataIndex)) ); data = seriesArray[i].data[dataIndex]; data = typeof data != 'undefined' ? (typeof data.value != 'undefined' ? data.value : data) : '-'; formatter = formatter.replace( '{c' + i + '}', data instanceof Array ? data : this.numAddCommas(data) ); } this._tDom.innerHTML = formatter; } else { this._curTicket = NaN; formatter = this._encodeHTML( categoryAxis.getNameByIndex(dataIndex) ); for (var i = 0, l = seriesArray.length; i < l; i++) { formatter += '<br/>' + this._encodeHTML(seriesArray[i].name || '') + ' : '; data = seriesArray[i].data[dataIndex]; data = typeof data != 'undefined' ? (typeof data.value != 'undefined' ? data.value : data) : '-'; formatter += data instanceof Array ? data : this.numAddCommas(data); } this._tDom.innerHTML = formatter; } if (showContent === false || !this.option.tooltip.showContent) { // 只用tooltip的行为,不显示主体 return; } if (!this.hasAppend) { this._tDom.style.left = this._zrWidth / 2 + 'px'; this._tDom.style.top = this._zrHeight / 2 + 'px'; this.dom.firstChild.appendChild(this._tDom); this.hasAppend = true; } this._show(x, y, specialCssText); } }, /** * 极坐标 */ _showPolarTrigger : function (polarIndex, dataIndex) { if (typeof this.polar == 'undefined' || typeof polarIndex == 'undefined' || typeof dataIndex == 'undefined' || dataIndex < 0 ) { return false; } var series = this.option.series; var seriesArray = []; var formatter; var showContent; var specialCssText = ''; if (this.option.tooltip.trigger == 'axis') { if (this.option.tooltip.show === false) { return false; } formatter = this.option.tooltip.formatter; } var indicatorName = this.option.polar[polarIndex].indicator[dataIndex].text; // 找到所有用这个极坐标并且axis触发的系列数据 for (var i = 0, l = series.length; i < l; i++) { if (!this._isSelected(series[i].name)) { continue; } if (series[i].polarIndex == polarIndex && this.deepQuery( [series[i], this.option], 'tooltip.trigger' ) == 'axis' ) { showContent = this.query( series[i], 'tooltip.showContent' ) || showContent; formatter = this.query( series[i], 'tooltip.formatter' ) || formatter; specialCssText += this._style(this.query( series[i], 'tooltip' )); seriesArray.push(series[i]); } } if (seriesArray.length > 0) { var polarData; var data; var params = []; for (var i = 0, l = seriesArray.length; i < l; i++) { polarData = seriesArray[i].data; for (var j = 0, k = polarData.length; j < k; j++) { data = polarData[j]; if (!this._isSelected(data.name)) { continue; } data = typeof data != 'undefined' ? data : {name:'', value: {dataIndex:'-'}}; params.push([ seriesArray[i].name || '', data.name, data.value[dataIndex], indicatorName ]); } } if (params.length <= 0) { return; } if (typeof formatter == 'function') { this._curTicket = 'axis:' + dataIndex; this._tDom.innerHTML = formatter( params, this._curTicket, this._setContent ); } else if (typeof formatter == 'string') { formatter = formatter.replace('{a}','{a0}') .replace('{b}','{b0}') .replace('{c}','{c0}') .replace('{d}','{d0}'); for (var i = 0, l = params.length; i < l; i++) { formatter = formatter.replace( '{a' + i + '}', this._encodeHTML(params[i][0]) ); formatter = formatter.replace( '{b' + i + '}', this._encodeHTML(params[i][1]) ); formatter = formatter.replace( '{c' + i + '}', this.numAddCommas(params[i][2]) ); formatter = formatter.replace( '{d' + i + '}', this._encodeHTML(params[i][3]) ); } this._tDom.innerHTML = formatter; } else { formatter = this._encodeHTML(params[0][1]) + '<br/>' + this._encodeHTML(params[0][3]) + ' : ' + this.numAddCommas(params[0][2]); for (var i = 1, l = params.length; i < l; i++) { formatter += '<br/>' + this._encodeHTML(params[i][1]) + '<br/>'; formatter += this._encodeHTML(params[i][3]) + ' : ' + this.numAddCommas(params[i][2]); } this._tDom.innerHTML = formatter; } if (showContent === false || !this.option.tooltip.showContent) { // 只用tooltip的行为,不显示主体 return; } if (!this.hasAppend) { this._tDom.style.left = this._zrWidth / 2 + 'px'; this._tDom.style.top = this._zrHeight / 2 + 'px'; this.dom.firstChild.appendChild(this._tDom); this.hasAppend = true; } this._show( zrEvent.getX(this._event), zrEvent.getY(this._event), specialCssText ); return true; } }, _showItemTrigger : function () { var serie = ecData.get(this._curTarget, 'series'); var data = ecData.get(this._curTarget, 'data'); var name = ecData.get(this._curTarget, 'name'); var value = ecData.get(this._curTarget, 'value'); var special = ecData.get(this._curTarget, 'special'); var special2 = ecData.get(this._curTarget, 'special2'); // 从低优先级往上找到trigger为item的formatter和样式 var formatter; var showContent; var specialCssText = ''; var indicator; var html = ''; if (this._curTarget._type != 'island') { // 全局 if (this.option.tooltip.trigger == 'item') { formatter = this.option.tooltip.formatter; } // 系列 if (this.query(serie, 'tooltip.trigger') == 'item') { showContent = this.query( serie, 'tooltip.showContent' ) || showContent; formatter = this.query( serie, 'tooltip.formatter' ) || formatter; specialCssText += this._style(this.query( serie, 'tooltip' )); } // 数据项 showContent = this.query( data, 'tooltip.showContent' ) || showContent; formatter = this.query( data, 'tooltip.formatter' ) || formatter; specialCssText += this._style(this.query(data, 'tooltip')); } else { showContent = this.deepQuery( [data, serie, this.option], 'tooltip.showContent' ); formatter = this.deepQuery( [data, serie, this.option], 'tooltip.islandFormatter' ); } if (typeof formatter == 'function') { this._curTicket = (serie.name || '') + ':' + ecData.get(this._curTarget, 'dataIndex'); this._tDom.innerHTML = formatter( [ serie.name || '', name, value, special, special2 ], this._curTicket, this._setContent ); } else if (typeof formatter == 'string') { this._curTicket = NaN; formatter = formatter.replace('{a}','{a0}') .replace('{b}','{b0}') .replace('{c}','{c0}'); formatter = formatter.replace( '{a0}', this._encodeHTML(serie.name || '') ) .replace('{b0}', this._encodeHTML(name)) .replace( '{c0}', value instanceof Array ? value : this.numAddCommas(value) ); formatter = formatter.replace('{d}','{d0}') .replace('{d0}', special || ''); formatter = formatter.replace('{e}','{e0}') .replace('{e0}', ecData.get(this._curTarget, 'special2') || ''); this._tDom.innerHTML = formatter; } else { this._curTicket = NaN; if (serie.type == ecConfig.CHART_TYPE_SCATTER) { this._tDom.innerHTML = (typeof serie.name != 'undefined' ? (this._encodeHTML(serie.name) + '<br/>') : '' ) + (name === '' ? '' : (this._encodeHTML(name) + ' : ') ) + value + (typeof special == 'undefined' ? '' : (' (' + special + ')')); } else if (serie.type == ecConfig.CHART_TYPE_RADAR && special) { indicator = special; html += this._encodeHTML( name === '' ? (serie.name || '') : name ); html += html === '' ? '' : '<br />'; for (var i = 0 ; i < indicator.length; i ++) { html += this._encodeHTML(indicator[i].text) + ' : ' + this.numAddCommas(value[i]) + '<br />'; } this._tDom.innerHTML = html; } else if (serie.type == ecConfig.CHART_TYPE_CHORD) { if (typeof special2 == 'undefined') { // 外环上 this._tDom.innerHTML = this._encodeHTML(name) + ' (' + this.numAddCommas(value) + ')'; } else { var name1 = this._encodeHTML(name); var name2 = this._encodeHTML(special); // 内部弦上 this._tDom.innerHTML = (typeof serie.name != 'undefined' ? (this._encodeHTML(serie.name) + '<br/>') : '') + name1 + ' -> ' + name2 + ' (' + this.numAddCommas(value) + ')' + '<br />' + name2 + ' -> ' + name1 + ' (' + this.numAddCommas(special2) + ')'; } } else { this._tDom.innerHTML = (typeof serie.name != 'undefined' ? (this._encodeHTML(serie.name) + '<br/>') : '') + this._encodeHTML(name) + ' : ' + this.numAddCommas(value) + (typeof special == 'undefined' ? '' : (' ('+ this.numAddCommas(special) +')') ); } } if (!this._axisLineShape.invisible) { this._axisLineShape.invisible = true; this.zr.modShape(this._axisLineShape.id, this._axisLineShape); this.zr.refresh(); } if (showContent === false || !this.option.tooltip.showContent) { // 只用tooltip的行为,不显示主体 return; } if (!this.hasAppend) { this._tDom.style.left = this._zrWidth / 2 + 'px'; this._tDom.style.top = this._zrHeight / 2 + 'px'; this.dom.firstChild.appendChild(this._tDom); this.hasAppend = true; } this._show( zrEvent.getX(this._event) + 20, zrEvent.getY(this._event) - 20, specialCssText ); }, /** * 设置坐标轴指示器样式 */ _styleAxisPointer : function (seriesArray, xStart, yStart, xEnd, yEnd, gap) { if (seriesArray.length > 0) { var queryTarget; var curType; var axisPointer = this.option.tooltip.axisPointer; var pointType = axisPointer.type; var lineColor = axisPointer.lineStyle.color; var lineWidth = axisPointer.lineStyle.width; var lineType = axisPointer.lineStyle.type; var areaSize = axisPointer.areaStyle.size; var areaColor = axisPointer.areaStyle.color; for (var i = 0, l = seriesArray.length; i < l; i++) { if (this.deepQuery( [seriesArray[i], this.option], 'tooltip.trigger' ) == 'axis' ) { queryTarget = seriesArray[i]; curType = this.query( queryTarget, 'tooltip.axisPointer.type' ); pointType = curType || pointType; if (curType == 'line') { lineColor = this.query( queryTarget, 'tooltip.axisPointer.lineStyle.color' ) || lineColor; lineWidth = this.query( queryTarget, 'tooltip.axisPointer.lineStyle.width' ) || lineWidth; lineType = this.query( queryTarget, 'tooltip.axisPointer.lineStyle.type' ) || lineType; } else if (curType == 'shadow') { areaSize = this.query( queryTarget, 'tooltip.axisPointer.areaStyle.size' ) || areaSize; areaColor = this.query( queryTarget, 'tooltip.axisPointer.areaStyle.color' ) || areaColor; } } } if (pointType == 'line') { this._axisLineShape.style = { xStart : xStart, yStart : yStart, xEnd : xEnd, yEnd : yEnd, strokeColor : lineColor, lineWidth : lineWidth, lineType : lineType }; this._axisLineShape.invisible = false; this.zr.modShape(this._axisLineShape.id, this._axisLineShape); } else if (pointType == 'shadow') { if (typeof areaSize == 'undefined' || areaSize == 'auto' || isNaN(areaSize) ) { lineWidth = gap; } else { lineWidth = areaSize; } if (xStart == xEnd) { // 纵向 if (Math.abs(this.grid.getX() - xStart) < 2) { // 最左边 lineWidth /= 2; xStart = xEnd = xEnd + lineWidth / 2; } else if (Math.abs(this.grid.getXend() - xStart) < 2) { // 最右边 lineWidth /= 2; xStart = xEnd = xEnd - lineWidth / 2; } } else if (yStart == yEnd) { // 横向 if (Math.abs(this.grid.getY() - yStart) < 2) { // 最上边 lineWidth /= 2; yStart = yEnd = yEnd + lineWidth / 2; } else if (Math.abs(this.grid.getYend() - yStart) < 2) { // 最右边 lineWidth /= 2; yStart = yEnd = yEnd - lineWidth / 2; } } this._axisShadowShape.style = { xStart : xStart, yStart : yStart, xEnd : xEnd, yEnd : yEnd, strokeColor : areaColor, lineWidth : lineWidth }; this._axisShadowShape.invisible = false; this.zr.modShape(this._axisShadowShape.id, this._axisShadowShape); } this.zr.refresh(); } }, __onmousemove : function (param) { clearTimeout(this._hidingTicket); clearTimeout(this._showingTicket); var target = param.target; var mx = zrEvent.getX(param.event); var my = zrEvent.getY(param.event); if (!target) { // 判断是否落到直角系里,axis触发的tooltip this._curTarget = false; this._event = param.event; this._event._target = this._event.target || this._event.toElement; this._event.zrenderX = mx; this._event.zrenderY = my; if (this._needAxisTrigger && this.grid && zrArea.isInside( rectangleInstance, this.grid.getArea(), mx, my ) ) { this._showingTicket = setTimeout(this._tryShow, this._showDelay); } else if (this._needAxisTrigger && this.polar && this.polar.isInside([mx, my]) != -1 ) { this._showingTicket = setTimeout(this._tryShow, this._showDelay); } else { !this._event.connectTrigger && this.messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_OUT_GRID, this._event ); this._hidingTicket = setTimeout(this._hide, this._hideDelay); } } else { this._curTarget = target; this._event = param.event; this._event._target = this._event.target || this._event.toElement; this._event.zrenderX = mx; this._event.zrenderY = my; var polarIndex; if (this._needAxisTrigger && this.polar && (polarIndex = this.polar.isInside([mx, my])) != -1 ) { // 看用这个polar的系列数据是否是axis触发,如果是设置_curTarget为nul var series = this.option.series; for (var i = 0, l = series.length; i < l; i++) { if (series[i].polarIndex == polarIndex && this.deepQuery( [series[i], this.option], 'tooltip.trigger' ) == 'axis' ) { this._curTarget = null; break; } } } this._showingTicket = setTimeout(this._tryShow, this._showDelay); } }, /** * zrender事件响应:鼠标离开绘图区域 */ __onglobalout : function () { clearTimeout(this._hidingTicket); clearTimeout(this._showingTicket); this._hidingTicket = setTimeout(this._hide, this._hideDelay); }, /** * 异步回调填充内容 */ _setContent : function (ticket, content) { if (!this._tDom) { return; } if (ticket == this._curTicket) { this._tDom.innerHTML = content; } setTimeout(this._refixed, 20); }, setComponent : function () { this.component = this.myChart.component; this.grid = this.component.grid; this.xAxis = this.component.xAxis; this.yAxis = this.component.yAxis; this.polar = this.component.polar; }, ontooltipHover : function (param, tipShape) { if (!this._lastTipShape // 不存在或者存在但dataIndex发生变化才需要重绘 || (this._lastTipShape && this._lastTipShape.dataIndex != param.dataIndex) ) { if (this._lastTipShape && this._lastTipShape.tipShape.length > 0) { this.zr.delShape(this._lastTipShape.tipShape); } for (var i = 0, l = tipShape.length; i < l; i++) { tipShape[i].zlevel = this._zlevelBase; tipShape[i].style = zrShapeBase.prototype.getHighlightStyle( tipShape[i].style, tipShape[i].highlightStyle ); tipShape[i].draggable = false; tipShape[i].hoverable = false; tipShape[i].clickable = false; tipShape[i].ondragend = null; tipShape[i].ondragover = null; tipShape[i].ondrop = null; this.zr.addShape(tipShape[i]); } this._lastTipShape = { dataIndex : param.dataIndex, tipShape : tipShape }; } }, ondragend : function () { this._hide(); }, /** * 图例选择 */ onlegendSelected : function (param) { this._selectedMap = param.selected; }, _setSelectedMap : function () { if (this.option.legend && this.option.legend.selected) { this._selectedMap = this.option.legend.selected; } else { this._selectedMap = {}; } }, _isSelected : function (itemName) { if (typeof this._selectedMap[itemName] != 'undefined') { return this._selectedMap[itemName]; } else { return true; // 没在legend里定义的都为true啊~ } }, /** * 模拟tooltip hover方法 * {object} params 参数 * {seriesIndex: 0, seriesName:'', dataInex:0} line、bar、scatter、k、radar * {seriesIndex: 0, seriesName:'', name:''} map、pie、chord */ showTip : function (params) { if (!params) { return; } var seriesIndex; var series = this.option.series; if (typeof params.seriesIndex != 'undefined') { seriesIndex = params.seriesIndex; } else { var seriesName = params.seriesName; for (var i = 0, l = series.length; i < l; i++) { if (series[i].name == seriesName) { seriesIndex = i; break; } } } var serie = series[seriesIndex]; if (typeof serie == 'undefined') { return; } var chart = myChart.chart[serie.type]; var isAxisTrigger = this.deepQuery( [serie, this.option], 'tooltip.trigger' ) == 'axis'; if (!chart) { return; } if (isAxisTrigger) { // axis trigger var dataIndex = params.dataIndex; switch (chart.type) { case ecConfig.CHART_TYPE_LINE : case ecConfig.CHART_TYPE_BAR : case ecConfig.CHART_TYPE_K : if (typeof this.xAxis == 'undefined' || typeof this.yAxis == 'undefined' || serie.data.length <= dataIndex ) { return; } var xAxisIndex = serie.xAxisIndex || 0; var yAxisIndex = serie.yAxisIndex || 0; if (this.xAxis.getAxis(xAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 横轴是类目 this._event = { zrenderX : this.xAxis.getAxis(xAxisIndex).getCoordByIndex(dataIndex), zrenderY : this.grid.getY() + (this.grid.getYend() - this.grid.getY()) / 4 }; } else { // 纵轴是类目 this._event = { zrenderX : this.grid.getX() + (this.grid.getXend() - this.grid.getX()) / 4, zrenderY : this.yAxis.getAxis(yAxisIndex).getCoordByIndex(dataIndex) }; } this._showAxisTrigger( xAxisIndex, yAxisIndex, dataIndex ); break; case ecConfig.CHART_TYPE_RADAR : if (typeof this.polar == 'undefined' || serie.data[0].value.length <= dataIndex ) { return; } var polarIndex = serie.polarIndex || 0; var vector = this.polar.getVector(polarIndex, dataIndex, 'max'); this._event = { zrenderX : vector[0], zrenderY : vector[1] }; _showPolarTrigger( polarIndex, dataIndex ); break; } } else { // item trigger var shapeList = chart.shapeList; var x; var y; switch (chart.type) { case ecConfig.CHART_TYPE_LINE : case ecConfig.CHART_TYPE_BAR : case ecConfig.CHART_TYPE_K : case ecConfig.CHART_TYPE_SCATTER : var dataIndex = params.dataIndex; for (var i = 0, l = shapeList.length; i < l; i++) { if (ecData.get(shapeList[i], 'seriesIndex') == seriesIndex && ecData.get(shapeList[i], 'dataIndex') == dataIndex ) { this._curTarget = shapeList[i]; x = shapeList[i].style.x; y = chart.type != ecConfig.CHART_TYPE_K ? shapeList[i].style.y : shapeList[i].style.y[0]; break; } } break; case ecConfig.CHART_TYPE_RADAR : var dataIndex = params.dataIndex; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'polygon' && ecData.get(shapeList[i], 'seriesIndex') == seriesIndex && ecData.get(shapeList[i], 'dataIndex') == dataIndex ) { this._curTarget = shapeList[i]; var vector = this.polar.getCenter(serie.polarIndex || 0); x = vector[0]; y = vector[1]; break; } } break; case ecConfig.CHART_TYPE_PIE : var name = params.name; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'sector' && ecData.get(shapeList[i], 'seriesIndex') == seriesIndex && ecData.get(shapeList[i], 'name') == name ) { this._curTarget = shapeList[i]; var style = this._curTarget.style; var midAngle = (style.startAngle + style.endAngle) / 2 * Math.PI / 180; x = this._curTarget.style.x + Math.cos(midAngle) * style.r / 1.5; y = this._curTarget.style.y - Math.sin(midAngle) * style.r / 1.5; break; } } break; case ecConfig.CHART_TYPE_MAP : var name = params.name; var mapType = serie.mapType; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'text' && shapeList[i]._mapType == mapType && shapeList[i].style._text == name ) { this._curTarget = shapeList[i]; x = this._curTarget.style.x + this._curTarget.position[0]; y = this._curTarget.style.y + this._curTarget.position[1]; break; } } break; case ecConfig.CHART_TYPE_CHORD: var name = params.name; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'sector' && ecData.get(shapeList[i], 'name') == name ) { this._curTarget = shapeList[i]; var style = this._curTarget.style; var midAngle = (style.startAngle + style.endAngle) / 2 * Math.PI / 180; x = this._curTarget.style.x + Math.cos(midAngle) * (style.r - 2); y = this._curTarget.style.y - Math.sin(midAngle) * (style.r - 2); this.zr.trigger( zrConfig.EVENT.MOUSEMOVE, { zrenderX : x, zrenderY : y } ); return; } } break; case ecConfig.CHART_TYPE_FORCE: var name = params.name; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'circle' && ecData.get(shapeList[i], 'name') == name ) { this._curTarget = shapeList[i]; x = this._curTarget.position[0]; y = this._curTarget.position[1]; break; } } break; } if (typeof x != 'undefined' && typeof y != 'undefined') { this._event = { zrenderX : x, zrenderY : y }; this.zr.addHoverShape(this._curTarget); this.zr.refreshHover(); this._showItemTrigger(); } } }, /** * 关闭,公开接口 */ hideTip : function () { this._hide(); }, init : function (newOption, newDom) { // this.component; // this.grid; // this.xAxis; // this.yAxis; // this.polar; this._selectedMap = {}; // 默认样式 // this._defaultCssText; // css样式缓存 // this._needAxisTrigger; // 坐标轴触发 // this._curTarget; // this._event; // this._curTicket; // 异步回调标识,用来区分多个请求 // 缓存一些高宽数据 this._zrHeight = this.zr.getHeight(); this._zrWidth = this.zr.getWidth(); this._lastTipShape = false; this._axisLineWidth = 0; this.option = newOption; this.dom = newDom; this.option.tooltip = this.reformOption(this.option.tooltip); this.option.tooltip.textStyle = zrUtil.merge( this.option.tooltip.textStyle, this.ecTheme.textStyle ); // 补全padding属性 this.option.tooltip.padding = this.reformCssArray( this.option.tooltip.padding ); this._needAxisTrigger = false; if (this.option.tooltip.trigger == 'axis') { this._needAxisTrigger = true; } var series = this.option.series; for (var i = 0, l = series.length; i < l; i++) { if (this.query(series[i], 'tooltip.trigger') == 'axis') { this._needAxisTrigger = true; break; } } // this._hidingTicket; // this._showingTicket; this._showDelay = this.option.tooltip.showDelay; // 显示延迟 this._hideDelay = this.option.tooltip.hideDelay; // 隐藏延迟 this._defaultCssText = this._style(this.option.tooltip); this._tDom.style.position = 'absolute'; // 不是多余的,别删! this.hasAppend = false; this._setSelectedMap(); this._axisLineWidth = this.option.tooltip.axisPointer.lineStyle.width; }, /** * 刷新 */ refresh : function (newOption) { if (newOption) { this.option = newOption; this.option.tooltip = this.reformOption(this.option.tooltip); this.option.tooltip.textStyle = zrUtil.merge( this.option.tooltip.textStyle, this.ecTheme.textStyle ); // 补全padding属性 this.option.tooltip.padding = this.reformCssArray( this.option.tooltip.padding ); this._setSelectedMap(); this._axisLineWidth = this.option.tooltip.axisPointer.lineStyle.width; } }, /** * zrender事件响应:窗口大小改变 */ resize : function () { this._zrHeight = this.zr.getHeight(); this._zrWidth = this.zr.getWidth(); }, /** * 释放后实例不可用,重载基类方法 */ dispose : function () { clearTimeout(this._hidingTicket); clearTimeout(this._showingTicket); this.zr.un(zrConfig.EVENT.MOUSEMOVE, self._onmousemove); this.zr.un(zrConfig.EVENT.GLOBALOUT, self._onglobalout); if (this.hasAppend) { this.dom.firstChild.removeChild(this._tDom); } this._tDom = null; // this.clear(); this.shapeList = null; }, /** * html转码的方法 */ _encodeHTML : function (source) { return String(source) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } }; zrUtil.inherits(Tooltip, Base); require('../component').define('tooltip', Tooltip); return Tooltip; });
src/component/tooltip.js
/** * echarts组件:提示框 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author Kener (@Kener-林峰, [email protected]) * */ define(function (require) { var LineShape = require('zrender/shape/Line'); var RectangleShape = require('zrender/shape/Rectangle'); var rectangleInstance = new RectangleShape({}); /** * 构造函数 * @param {Object} messageCenter echart消息中心 * @param {ZRender} zr zrender实例 * @param {Object} option 提示框参数 * @param {HtmlElement} dom 目标对象 * @param {ECharts} myChart 当前图表实例 */ function Tooltip(ecConfig, messageCenter, zr, option, dom, myChart) { var Base = require('./base'); Base.call(this, ecConfig, zr); var ecData = require('../util/ecData'); var zrConfig = require('zrender/config'); var zrEvent = require('zrender/tool/event'); var zrArea = require('zrender/tool/area'); var zrColor = require('zrender/tool/color'); var zrUtil = require('zrender/tool/util'); var zrShapeBase = require('zrender/shape/Base'); var self = this; self.type = ecConfig.COMPONENT_TYPE_TOOLTIP; var _zlevelBase = self.getZlevelBase(); var component = {}; // 组件索引 var grid; var xAxis; var yAxis; var polar; var _selectedMap = {}; // tooltip dom & css var _tDom = document.createElement('div'); // 通用样式 var _gCssText = 'position:absolute;' + 'display:block;' + 'border-style:solid;' + 'white-space:nowrap;'; // 默认样式 var _defaultCssText; // css样式缓存 var _needAxisTrigger; // 坐标轴触发 var _hidingTicket; var _hideDelay; // 隐藏延迟 var _showingTicket; var _showDelay; // 显示延迟 var _curTarget; var _event; var _curTicket; // 异步回调标识,用来区分多个请求 // 缓存一些高宽数据 var _zrHeight = zr.getHeight(); var _zrWidth = zr.getWidth(); var _lastTipShape = false; var _axisLineWidth = 0; var _axisLineShape = new LineShape({ zlevel: _zlevelBase, invisible : true, hoverable: false, style : { // lineWidth : 2, // strokeColor : ecConfig.categoryAxis.axisLine.lineStyle.color } }); var _axisShadowShape = new LineShape({ zlevel: 1, // grid上,chart下 invisible : true, hoverable: false, style : { // lineWidth : 10, // strokeColor : ecConfig.categoryAxis.axisLine.lineStyle.color } }); zr.addShape(_axisLineShape); zr.addShape(_axisShadowShape); /** * 根据配置设置dom样式 */ function _style(opt) { if (!opt) { return ''; } var cssText = []; if (opt.transitionDuration) { var transitionText = 'left ' + opt.transitionDuration + 's,' + 'top ' + opt.transitionDuration + 's'; cssText.push( 'transition:' + transitionText ); cssText.push( '-moz-transition:' + transitionText ); cssText.push( '-webkit-transition:' + transitionText ); cssText.push( '-o-transition:' + transitionText ); } if (opt.backgroundColor) { // for sb ie~ cssText.push( 'background-Color:' + zrColor.toHex( opt.backgroundColor ) ); cssText.push('filter:alpha(opacity=70)'); cssText.push('background-Color:' + opt.backgroundColor); } if (typeof opt.borderWidth != 'undefined') { cssText.push('border-width:' + opt.borderWidth + 'px'); } if (typeof opt.borderColor != 'undefined') { cssText.push('border-color:' + opt.borderColor); } if (typeof opt.borderRadius != 'undefined') { cssText.push( 'border-radius:' + opt.borderRadius + 'px' ); cssText.push( '-moz-border-radius:' + opt.borderRadius + 'px' ); cssText.push( '-webkit-border-radius:' + opt.borderRadius + 'px' ); cssText.push( '-o-border-radius:' + opt.borderRadius + 'px' ); } var textStyle = opt.textStyle; if (textStyle) { textStyle.color && cssText.push('color:' + textStyle.color); textStyle.decoration && cssText.push( 'text-decoration:' + textStyle.decoration ); textStyle.align && cssText.push( 'text-align:' + textStyle.align ); textStyle.fontFamily && cssText.push( 'font-family:' + textStyle.fontFamily ); textStyle.fontSize && cssText.push( 'font-size:' + textStyle.fontSize + 'px' ); textStyle.fontSize && cssText.push( 'line-height:' + Math.round(textStyle.fontSize*3/2) + 'px' ); textStyle.fontStyle && cssText.push( 'font-style:' + textStyle.fontStyle ); textStyle.fontWeight && cssText.push( 'font-weight:' + textStyle.fontWeight ); } var padding = opt.padding; if (typeof padding != 'undefined') { padding = self.reformCssArray(padding); cssText.push( 'padding:' + padding[0] + 'px ' + padding[1] + 'px ' + padding[2] + 'px ' + padding[3] + 'px' ); } cssText = cssText.join(';') + ';'; return cssText; } function _hide() { if (_tDom) { _tDom.style.display = 'none'; } var needRefresh = false; if (!_axisLineShape.invisible) { _axisLineShape.invisible = true; zr.modShape(_axisLineShape.id, _axisLineShape); needRefresh = true; } if (!_axisShadowShape.invisible) { _axisShadowShape.invisible = true; zr.modShape(_axisShadowShape.id, _axisShadowShape); needRefresh = true; } if (_lastTipShape && _lastTipShape.tipShape.length > 0) { zr.delShape(_lastTipShape.tipShape); _lastTipShape = false; } needRefresh && zr.refresh(); } function _show(x, y, specialCssText) { var domHeight = _tDom.offsetHeight; var domWidth = _tDom.offsetWidth; if (x + domWidth > _zrWidth) { // 太靠右 //x = _zrWidth - domWidth; x -= (domWidth + 40); } if (y + domHeight > _zrHeight) { // 太靠下 //y = _zrHeight - domHeight; y -= (domHeight - 20); } if (y < 20) { y = 0; } _tDom.style.cssText = _gCssText + _defaultCssText + (specialCssText ? specialCssText : '') + 'left:' + x + 'px;top:' + y + 'px;'; if (domHeight < 10 || domWidth < 10) { // _zrWidth - x < 100 || _zrHeight - y < 100 setTimeout(_refixed, 20); } } function _refixed() { if (_tDom) { var cssText = ''; var domHeight = _tDom.offsetHeight; var domWidth = _tDom.offsetWidth; if (_tDom.offsetLeft + domWidth > _zrWidth) { cssText += 'left:' + (_zrWidth - domWidth - 20) + 'px;'; } if (_tDom.offsetTop + domHeight > _zrHeight) { cssText += 'top:' + (_zrHeight - domHeight - 10) + 'px;'; } if (cssText !== '') { _tDom.style.cssText += cssText; } } } function _tryShow() { var needShow; var trigger; if (!_curTarget) { // 坐标轴事件 _findPolarTrigger() || _findAxisTrigger(); } else { // 数据项事件 if (_curTarget._type == 'island' && option.tooltip.show) { _showItemTrigger(); return; } var serie = ecData.get(_curTarget, 'series'); var data = ecData.get(_curTarget, 'data'); needShow = self.deepQuery( [data, serie, option], 'tooltip.show' ); if (typeof serie == 'undefined' || typeof data == 'undefined' || needShow === false ) { // 不响应tooltip的数据对象延时隐藏 clearTimeout(_hidingTicket); clearTimeout(_showingTicket); _hidingTicket = setTimeout(_hide, _hideDelay); } else { trigger = self.deepQuery( [data, serie, option], 'tooltip.trigger' ); trigger == 'axis' ? _showAxisTrigger( serie.xAxisIndex, serie.yAxisIndex, ecData.get(_curTarget, 'dataIndex') ) : _showItemTrigger(); } } } /** * 直角系 */ function _findAxisTrigger() { if (!xAxis || !yAxis) { _hidingTicket = setTimeout(_hide, _hideDelay); return; } var series = option.series; var xAxisIndex; var yAxisIndex; for (var i = 0, l = series.length; i < l; i++) { // 找到第一个axis触发tooltip的系列 if (self.deepQuery( [series[i], option], 'tooltip.trigger' ) == 'axis' ) { xAxisIndex = series[i].xAxisIndex || 0; yAxisIndex = series[i].yAxisIndex || 0; if (xAxis.getAxis(xAxisIndex) && xAxis.getAxis(xAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 横轴为类目轴 _showAxisTrigger(xAxisIndex, yAxisIndex, _getNearestDataIndex('x', xAxis.getAxis(xAxisIndex)) ); return; } else if (yAxis.getAxis(yAxisIndex) && yAxis.getAxis(yAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 纵轴为类目轴 _showAxisTrigger(xAxisIndex, yAxisIndex, _getNearestDataIndex('y', yAxis.getAxis(yAxisIndex)) ); return; } } } } /** * 极坐标 */ function _findPolarTrigger() { if (!polar) { return false; } var x = zrEvent.getX(_event); var y = zrEvent.getY(_event); var polarIndex = polar.getNearestIndex([x, y]); var valueIndex; if (polarIndex) { valueIndex = polarIndex.valueIndex; polarIndex = polarIndex.polarIndex; } else { polarIndex = -1; } if (polarIndex != -1) { return _showPolarTrigger(polarIndex, valueIndex); } return false; } /** * 根据坐标轴事件带的属性获取最近的axisDataIndex */ function _getNearestDataIndex(direction, categoryAxis) { var dataIndex = -1; var x = zrEvent.getX(_event); var y = zrEvent.getY(_event); if (direction == 'x') { // 横轴为类目轴 var left; var right; var xEnd = grid.getXend(); var curCoord = categoryAxis.getCoordByIndex(dataIndex); while (curCoord < xEnd) { if (curCoord <= x) { left = curCoord; } if (curCoord >= x) { break; } curCoord = categoryAxis.getCoordByIndex(++dataIndex); right = curCoord; } if (x - left < right - x) { dataIndex -= dataIndex !== 0 ? 1 : 0; } else { // 离右边近,看是否为最后一个 if (typeof categoryAxis.getNameByIndex(dataIndex) == 'undefined' ) { dataIndex -= 1; } } return dataIndex; } else { // 纵轴为类目轴 var top; var bottom; var yStart = grid.getY(); var curCoord = categoryAxis.getCoordByIndex(dataIndex); while (curCoord > yStart) { if (curCoord >= y) { bottom = curCoord; } if (curCoord <= y) { break; } curCoord = categoryAxis.getCoordByIndex(++dataIndex); top = curCoord; } if (y - top > bottom - y) { dataIndex -= dataIndex !== 0 ? 1 : 0; } else { // 离上方边近,看是否为最后一个 if (typeof categoryAxis.getNameByIndex(dataIndex) == 'undefined' ) { dataIndex -= 1; } } return dataIndex; } return -1; } /** * 直角系 */ function _showAxisTrigger(xAxisIndex, yAxisIndex, dataIndex) { !_event.connectTrigger && messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_IN_GRID, _event ); if (typeof xAxis == 'undefined' || typeof yAxis == 'undefined' || typeof xAxisIndex == 'undefined' || typeof yAxisIndex == 'undefined' || dataIndex < 0 ) { // 不响应tooltip的数据对象延时隐藏 clearTimeout(_hidingTicket); clearTimeout(_showingTicket); _hidingTicket = setTimeout(_hide, _hideDelay); return; } var series = option.series; var seriesArray = []; var seriesIndex = []; var categoryAxis; var x; var y; var formatter; var showContent; var specialCssText = ''; if (option.tooltip.trigger == 'axis') { if (option.tooltip.show === false) { return; } formatter = option.tooltip.formatter; } if (xAxisIndex != -1 && xAxis.getAxis(xAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 横轴为类目轴,找到所有用这条横轴并且axis触发的系列数据 categoryAxis = xAxis.getAxis(xAxisIndex); for (var i = 0, l = series.length; i < l; i++) { if (!_isSelected(series[i].name)) { continue; } if (series[i].xAxisIndex == xAxisIndex && self.deepQuery( [series[i], option], 'tooltip.trigger' ) == 'axis' ) { showContent = self.query( series[i], 'tooltip.showContent' ) || showContent; formatter = self.query( series[i], 'tooltip.formatter' ) || formatter; specialCssText += _style(self.query( series[i], 'tooltip' )); seriesArray.push(series[i]); seriesIndex.push(i); } } // 寻找高亮元素 messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_HOVER, _event, { seriesIndex : seriesIndex, dataIndex : component.dataZoom ? component.dataZoom.getRealDataIndex( seriesIndex, dataIndex ) : dataIndex } ); y = zrEvent.getY(_event) + 10; x = self.subPixelOptimize( categoryAxis.getCoordByIndex(dataIndex), _axisLineWidth ); _styleAxisPointer( seriesArray, x, grid.getY(), x, grid.getYend(), categoryAxis.getGap() ); x += 10; } else if (yAxisIndex != -1 && yAxis.getAxis(yAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 纵轴为类目轴,找到所有用这条纵轴并且axis触发的系列数据 categoryAxis = yAxis.getAxis(yAxisIndex); for (var i = 0, l = series.length; i < l; i++) { if (!_isSelected(series[i].name)) { continue; } if (series[i].yAxisIndex == yAxisIndex && self.deepQuery( [series[i], option], 'tooltip.trigger' ) == 'axis' ) { showContent = self.query( series[i], 'tooltip.showContent' ) || showContent; formatter = self.query( series[i], 'tooltip.formatter' ) || formatter; specialCssText += _style(self.query( series[i], 'tooltip' )); seriesArray.push(series[i]); seriesIndex.push(i); } } // 寻找高亮元素 messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_HOVER, _event, { seriesIndex : seriesIndex, dataIndex : component.dataZoom ? component.dataZoom.getRealDataIndex( seriesIndex, dataIndex ) : dataIndex } ); x = zrEvent.getX(_event) + 10; y = self.subPixelOptimize( categoryAxis.getCoordByIndex(dataIndex), _axisLineWidth ); _styleAxisPointer( seriesArray, grid.getX(), y, grid.getXend(), y, categoryAxis.getGap() ); y += 10; } if (seriesArray.length > 0) { var data; if (typeof formatter == 'function') { var params = []; for (var i = 0, l = seriesArray.length; i < l; i++) { data = seriesArray[i].data[dataIndex]; data = typeof data != 'undefined' ? (typeof data.value != 'undefined' ? data.value : data) : '-'; params.push([ seriesArray[i].name || '', categoryAxis.getNameByIndex(dataIndex), data ]); } _curTicket = 'axis:' + dataIndex; _tDom.innerHTML = formatter( params, _curTicket, _setContent ); } else if (typeof formatter == 'string') { _curTicket = NaN; formatter = formatter.replace('{a}','{a0}') .replace('{b}','{b0}') .replace('{c}','{c0}'); for (var i = 0, l = seriesArray.length; i < l; i++) { formatter = formatter.replace( '{a' + i + '}', _encodeHTML(seriesArray[i].name || '') ); formatter = formatter.replace( '{b' + i + '}', _encodeHTML(categoryAxis.getNameByIndex(dataIndex)) ); data = seriesArray[i].data[dataIndex]; data = typeof data != 'undefined' ? (typeof data.value != 'undefined' ? data.value : data) : '-'; formatter = formatter.replace( '{c' + i + '}', data instanceof Array ? data : self.numAddCommas(data) ); } _tDom.innerHTML = formatter; } else { _curTicket = NaN; formatter = _encodeHTML( categoryAxis.getNameByIndex(dataIndex) ); for (var i = 0, l = seriesArray.length; i < l; i++) { formatter += '<br/>' + _encodeHTML(seriesArray[i].name || '') + ' : '; data = seriesArray[i].data[dataIndex]; data = typeof data != 'undefined' ? (typeof data.value != 'undefined' ? data.value : data) : '-'; formatter += data instanceof Array ? data : self.numAddCommas(data); } _tDom.innerHTML = formatter; } if (showContent === false || !option.tooltip.showContent) { // 只用tooltip的行为,不显示主体 return; } if (!self.hasAppend) { _tDom.style.left = _zrWidth / 2 + 'px'; _tDom.style.top = _zrHeight / 2 + 'px'; dom.firstChild.appendChild(_tDom); self.hasAppend = true; } _show(x, y, specialCssText); } } /** * 极坐标 */ function _showPolarTrigger(polarIndex, dataIndex) { if (typeof polar == 'undefined' || typeof polarIndex == 'undefined' || typeof dataIndex == 'undefined' || dataIndex < 0 ) { return false; } var series = option.series; var seriesArray = []; var formatter; var showContent; var specialCssText = ''; if (option.tooltip.trigger == 'axis') { if (option.tooltip.show === false) { return false; } formatter = option.tooltip.formatter; } var indicatorName = option.polar[polarIndex].indicator[dataIndex].text; // 找到所有用这个极坐标并且axis触发的系列数据 for (var i = 0, l = series.length; i < l; i++) { if (!_isSelected(series[i].name)) { continue; } if (series[i].polarIndex == polarIndex && self.deepQuery( [series[i], option], 'tooltip.trigger' ) == 'axis' ) { showContent = self.query( series[i], 'tooltip.showContent' ) || showContent; formatter = self.query( series[i], 'tooltip.formatter' ) || formatter; specialCssText += _style(self.query( series[i], 'tooltip' )); seriesArray.push(series[i]); } } if (seriesArray.length > 0) { var polarData; var data; var params = []; for (var i = 0, l = seriesArray.length; i < l; i++) { polarData = seriesArray[i].data; for (var j = 0, k = polarData.length; j < k; j++) { data = polarData[j]; if (!_isSelected(data.name)) { continue; } data = typeof data != 'undefined' ? data : {name:'', value: {dataIndex:'-'}}; params.push([ seriesArray[i].name || '', data.name, data.value[dataIndex], indicatorName ]); } } if (params.length <= 0) { return; } if (typeof formatter == 'function') { _curTicket = 'axis:' + dataIndex; _tDom.innerHTML = formatter( params, _curTicket, _setContent ); } else if (typeof formatter == 'string') { formatter = formatter.replace('{a}','{a0}') .replace('{b}','{b0}') .replace('{c}','{c0}') .replace('{d}','{d0}'); for (var i = 0, l = params.length; i < l; i++) { formatter = formatter.replace( '{a' + i + '}', _encodeHTML(params[i][0]) ); formatter = formatter.replace( '{b' + i + '}', _encodeHTML(params[i][1]) ); formatter = formatter.replace( '{c' + i + '}', self.numAddCommas(params[i][2]) ); formatter = formatter.replace( '{d' + i + '}', _encodeHTML(params[i][3]) ); } _tDom.innerHTML = formatter; } else { formatter = _encodeHTML(params[0][1]) + '<br/>' + _encodeHTML(params[0][3]) + ' : ' + self.numAddCommas(params[0][2]); for (var i = 1, l = params.length; i < l; i++) { formatter += '<br/>' + _encodeHTML(params[i][1]) + '<br/>'; formatter += _encodeHTML(params[i][3]) + ' : ' + self.numAddCommas(params[i][2]); } _tDom.innerHTML = formatter; } if (showContent === false || !option.tooltip.showContent) { // 只用tooltip的行为,不显示主体 return; } if (!self.hasAppend) { _tDom.style.left = _zrWidth / 2 + 'px'; _tDom.style.top = _zrHeight / 2 + 'px'; dom.firstChild.appendChild(_tDom); self.hasAppend = true; } _show( zrEvent.getX(_event), zrEvent.getY(_event), specialCssText ); return true; } } function _showItemTrigger() { var serie = ecData.get(_curTarget, 'series'); var data = ecData.get(_curTarget, 'data'); var name = ecData.get(_curTarget, 'name'); var value = ecData.get(_curTarget, 'value'); var special = ecData.get(_curTarget, 'special'); var special2 = ecData.get(_curTarget, 'special2'); // 从低优先级往上找到trigger为item的formatter和样式 var formatter; var showContent; var specialCssText = ''; var indicator; var html = ''; if (_curTarget._type != 'island') { // 全局 if (option.tooltip.trigger == 'item') { formatter = option.tooltip.formatter; } // 系列 if (self.query(serie, 'tooltip.trigger') == 'item') { showContent = self.query( serie, 'tooltip.showContent' ) || showContent; formatter = self.query( serie, 'tooltip.formatter' ) || formatter; specialCssText += _style(self.query( serie, 'tooltip' )); } // 数据项 showContent = self.query( data, 'tooltip.showContent' ) || showContent; formatter = self.query( data, 'tooltip.formatter' ) || formatter; specialCssText += _style(self.query(data, 'tooltip')); } else { showContent = self.deepQuery( [data, serie, option], 'tooltip.showContent' ); formatter = self.deepQuery( [data, serie, option], 'tooltip.islandFormatter' ); } if (typeof formatter == 'function') { _curTicket = (serie.name || '') + ':' + ecData.get(_curTarget, 'dataIndex'); _tDom.innerHTML = formatter( [ serie.name || '', name, value, special, special2 ], _curTicket, _setContent ); } else if (typeof formatter == 'string') { _curTicket = NaN; formatter = formatter.replace('{a}','{a0}') .replace('{b}','{b0}') .replace('{c}','{c0}'); formatter = formatter.replace( '{a0}', _encodeHTML(serie.name || '') ) .replace('{b0}', _encodeHTML(name)) .replace( '{c0}', value instanceof Array ? value : self.numAddCommas(value) ); formatter = formatter.replace('{d}','{d0}') .replace('{d0}', special || ''); formatter = formatter.replace('{e}','{e0}') .replace('{e0}', ecData.get(_curTarget, 'special2') || ''); _tDom.innerHTML = formatter; } else { _curTicket = NaN; if (serie.type == ecConfig.CHART_TYPE_SCATTER) { _tDom.innerHTML = (typeof serie.name != 'undefined' ? (_encodeHTML(serie.name) + '<br/>') : '' ) + (name === '' ? '' : (_encodeHTML(name) + ' : ') ) + value + (typeof special == 'undefined' ? '' : (' (' + special + ')')); } else if (serie.type == ecConfig.CHART_TYPE_RADAR && special) { indicator = special; html += _encodeHTML( name === '' ? (serie.name || '') : name ); html += html === '' ? '' : '<br />'; for (var i = 0 ; i < indicator.length; i ++) { html += _encodeHTML(indicator[i].text) + ' : ' + self.numAddCommas(value[i]) + '<br />'; } _tDom.innerHTML = html; } else if (serie.type == ecConfig.CHART_TYPE_CHORD) { if (typeof special2 == 'undefined') { // 外环上 _tDom.innerHTML = _encodeHTML(name) + ' (' + self.numAddCommas(value) + ')'; } else { var name1 = _encodeHTML(name); var name2 = _encodeHTML(special); // 内部弦上 _tDom.innerHTML = (typeof serie.name != 'undefined' ? (_encodeHTML(serie.name) + '<br/>') : '') + name1 + ' -> ' + name2 + ' (' + self.numAddCommas(value) + ')' + '<br />' + name2 + ' -> ' + name1 + ' (' + self.numAddCommas(special2) + ')'; } } else { _tDom.innerHTML = (typeof serie.name != 'undefined' ? (_encodeHTML(serie.name) + '<br/>') : '') + _encodeHTML(name) + ' : ' + self.numAddCommas(value) + (typeof special == 'undefined' ? '' : (' ('+ self.numAddCommas(special) +')') ); } } if (!_axisLineShape.invisible) { _axisLineShape.invisible = true; zr.modShape(_axisLineShape.id, _axisLineShape); zr.refresh(); } if (showContent === false || !option.tooltip.showContent) { // 只用tooltip的行为,不显示主体 return; } if (!self.hasAppend) { _tDom.style.left = _zrWidth / 2 + 'px'; _tDom.style.top = _zrHeight / 2 + 'px'; dom.firstChild.appendChild(_tDom); self.hasAppend = true; } _show( zrEvent.getX(_event) + 20, zrEvent.getY(_event) - 20, specialCssText ); } /** * 设置坐标轴指示器样式 */ function _styleAxisPointer( seriesArray, xStart, yStart, xEnd, yEnd, gap ) { if (seriesArray.length > 0) { var queryTarget; var curType; var axisPointer = option.tooltip.axisPointer; var pointType = axisPointer.type; var lineColor = axisPointer.lineStyle.color; var lineWidth = axisPointer.lineStyle.width; var lineType = axisPointer.lineStyle.type; var areaSize = axisPointer.areaStyle.size; var areaColor = axisPointer.areaStyle.color; for (var i = 0, l = seriesArray.length; i < l; i++) { if (self.deepQuery( [seriesArray[i], option], 'tooltip.trigger' ) == 'axis' ) { queryTarget = seriesArray[i]; curType = self.query( queryTarget, 'tooltip.axisPointer.type' ); pointType = curType || pointType; if (curType == 'line') { lineColor = self.query( queryTarget, 'tooltip.axisPointer.lineStyle.color' ) || lineColor; lineWidth = self.query( queryTarget, 'tooltip.axisPointer.lineStyle.width' ) || lineWidth; lineType = self.query( queryTarget, 'tooltip.axisPointer.lineStyle.type' ) || lineType; } else if (curType == 'shadow') { areaSize = self.query( queryTarget, 'tooltip.axisPointer.areaStyle.size' ) || areaSize; areaColor = self.query( queryTarget, 'tooltip.axisPointer.areaStyle.color' ) || areaColor; } } } if (pointType == 'line') { _axisLineShape.style = { xStart : xStart, yStart : yStart, xEnd : xEnd, yEnd : yEnd, strokeColor : lineColor, lineWidth : lineWidth, lineType : lineType }; _axisLineShape.invisible = false; zr.modShape(_axisLineShape.id, _axisLineShape); } else if (pointType == 'shadow') { if (typeof areaSize == 'undefined' || areaSize == 'auto' || isNaN(areaSize) ) { lineWidth = gap; } else { lineWidth = areaSize; } if (xStart == xEnd) { // 纵向 if (Math.abs(grid.getX() - xStart) < 2) { // 最左边 lineWidth /= 2; xStart = xEnd = xEnd + lineWidth / 2; } else if (Math.abs(grid.getXend() - xStart) < 2) { // 最右边 lineWidth /= 2; xStart = xEnd = xEnd - lineWidth / 2; } } else if (yStart == yEnd) { // 横向 if (Math.abs(grid.getY() - yStart) < 2) { // 最上边 lineWidth /= 2; yStart = yEnd = yEnd + lineWidth / 2; } else if (Math.abs(grid.getYend() - yStart) < 2) { // 最右边 lineWidth /= 2; yStart = yEnd = yEnd - lineWidth / 2; } } _axisShadowShape.style = { xStart : xStart, yStart : yStart, xEnd : xEnd, yEnd : yEnd, strokeColor : areaColor, lineWidth : lineWidth }; _axisShadowShape.invisible = false; zr.modShape(_axisShadowShape.id, _axisShadowShape); } zr.refresh(); } } /** * zrender事件响应:鼠标移动 */ function _onmousemove(param) { clearTimeout(_hidingTicket); clearTimeout(_showingTicket); var target = param.target; var mx = zrEvent.getX(param.event); var my = zrEvent.getY(param.event); if (!target) { // 判断是否落到直角系里,axis触发的tooltip _curTarget = false; _event = param.event; _event._target = _event.target || _event.toElement; _event.zrenderX = mx; _event.zrenderY = my; if (_needAxisTrigger && grid && zrArea.isInside( rectangleInstance, grid.getArea(), mx, my ) ) { _showingTicket = setTimeout(_tryShow, _showDelay); } else if (_needAxisTrigger && polar && polar.isInside([mx, my]) != -1 ) { _showingTicket = setTimeout(_tryShow, _showDelay); } else { !_event.connectTrigger && messageCenter.dispatch( ecConfig.EVENT.TOOLTIP_OUT_GRID, _event ); _hidingTicket = setTimeout(_hide, _hideDelay); } } else { _curTarget = target; _event = param.event; _event._target = _event.target || _event.toElement; _event.zrenderX = mx; _event.zrenderY = my; var polarIndex; if (_needAxisTrigger && polar && (polarIndex = polar.isInside([mx, my])) != -1 ) { // 看用这个polar的系列数据是否是axis触发,如果是设置_curTarget为nul var series = option.series; for (var i = 0, l = series.length; i < l; i++) { if (series[i].polarIndex == polarIndex && self.deepQuery( [series[i], option], 'tooltip.trigger' ) == 'axis' ) { _curTarget = null; break; } } } _showingTicket = setTimeout(_tryShow, _showDelay); } } /** * zrender事件响应:鼠标离开绘图区域 */ function _onglobalout() { clearTimeout(_hidingTicket); clearTimeout(_showingTicket); _hidingTicket = setTimeout(_hide, _hideDelay); } /** * 异步回调填充内容 */ function _setContent(ticket, content) { if (!_tDom) { return; } if (ticket == _curTicket) { _tDom.innerHTML = content; } setTimeout(_refixed, 20); } function setComponent() { component = myChart.component; grid = component.grid; xAxis = component.xAxis; yAxis = component.yAxis; polar = component.polar; } function ontooltipHover(param, tipShape) { if (!_lastTipShape // 不存在或者存在但dataIndex发生变化才需要重绘 || (_lastTipShape && _lastTipShape.dataIndex != param.dataIndex) ) { if (_lastTipShape && _lastTipShape.tipShape.length > 0) { zr.delShape(_lastTipShape.tipShape); } for (var i = 0, l = tipShape.length; i < l; i++) { tipShape[i].zlevel = _zlevelBase; tipShape[i].style = zrShapeBase.prototype.getHighlightStyle( tipShape[i].style, tipShape[i].highlightStyle ); tipShape[i].draggable = false; tipShape[i].hoverable = false; tipShape[i].clickable = false; tipShape[i].ondragend = null; tipShape[i].ondragover = null; tipShape[i].ondrop = null; zr.addShape(tipShape[i]); } _lastTipShape = { dataIndex : param.dataIndex, tipShape : tipShape }; } } function ondragend() { _hide(); } /** * 图例选择 */ function onlegendSelected(param) { _selectedMap = param.selected; } function _setSelectedMap() { if (option.legend && option.legend.selected) { _selectedMap = option.legend.selected; } else { _selectedMap = {}; } } function _isSelected(itemName) { if (typeof _selectedMap[itemName] != 'undefined') { return _selectedMap[itemName]; } else { return true; // 没在legend里定义的都为true啊~ } } /** * 模拟tooltip hover方法 * {object} params 参数 * {seriesIndex: 0, seriesName:'', dataInex:0} line、bar、scatter、k、radar * {seriesIndex: 0, seriesName:'', name:''} map、pie、chord */ function showTip(params) { if (!params) { return; } var seriesIndex; var series = option.series; if (typeof params.seriesIndex != 'undefined') { seriesIndex = params.seriesIndex; } else { var seriesName = params.seriesName; for (var i = 0, l = series.length; i < l; i++) { if (series[i].name == seriesName) { seriesIndex = i; break; } } } var serie = series[seriesIndex]; if (typeof serie == 'undefined') { return; } var chart = myChart.chart[serie.type]; var isAxisTrigger = self.deepQuery( [serie, option], 'tooltip.trigger' ) == 'axis'; if (!chart) { return; } if (isAxisTrigger) { // axis trigger var dataIndex = params.dataIndex; switch (chart.type) { case ecConfig.CHART_TYPE_LINE : case ecConfig.CHART_TYPE_BAR : case ecConfig.CHART_TYPE_K : if (typeof xAxis == 'undefined' || typeof yAxis == 'undefined' || serie.data.length <= dataIndex ) { return; } var xAxisIndex = serie.xAxisIndex || 0; var yAxisIndex = serie.yAxisIndex || 0; if (xAxis.getAxis(xAxisIndex).type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { // 横轴是类目 _event = { zrenderX : xAxis.getAxis(xAxisIndex).getCoordByIndex(dataIndex), zrenderY : grid.getY() + (grid.getYend() - grid.getY()) / 4 }; } else { // 纵轴是类目 _event = { zrenderX : grid.getX() + (grid.getXend() - grid.getX()) / 4, zrenderY : yAxis.getAxis(yAxisIndex).getCoordByIndex(dataIndex) }; } _showAxisTrigger( xAxisIndex, yAxisIndex, dataIndex ); break; case ecConfig.CHART_TYPE_RADAR : if (typeof polar == 'undefined' || serie.data[0].value.length <= dataIndex ) { return; } var polarIndex = serie.polarIndex || 0; var vector = polar.getVector(polarIndex, dataIndex, 'max'); _event = { zrenderX : vector[0], zrenderY : vector[1] }; _showPolarTrigger( polarIndex, dataIndex ); break; } } else { // item trigger var shapeList = chart.shapeList; var x; var y; switch (chart.type) { case ecConfig.CHART_TYPE_LINE : case ecConfig.CHART_TYPE_BAR : case ecConfig.CHART_TYPE_K : case ecConfig.CHART_TYPE_SCATTER : var dataIndex = params.dataIndex; for (var i = 0, l = shapeList.length; i < l; i++) { if (ecData.get(shapeList[i], 'seriesIndex') == seriesIndex && ecData.get(shapeList[i], 'dataIndex') == dataIndex ) { _curTarget = shapeList[i]; x = shapeList[i].style.x; y = chart.type != ecConfig.CHART_TYPE_K ? shapeList[i].style.y : shapeList[i].style.y[0]; break; } } break; case ecConfig.CHART_TYPE_RADAR : var dataIndex = params.dataIndex; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'polygon' && ecData.get(shapeList[i], 'seriesIndex') == seriesIndex && ecData.get(shapeList[i], 'dataIndex') == dataIndex ) { _curTarget = shapeList[i]; var vector = polar.getCenter(serie.polarIndex || 0); x = vector[0]; y = vector[1]; break; } } break; case ecConfig.CHART_TYPE_PIE : var name = params.name; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'sector' && ecData.get(shapeList[i], 'seriesIndex') == seriesIndex && ecData.get(shapeList[i], 'name') == name ) { _curTarget = shapeList[i]; var style = _curTarget.style; var midAngle = (style.startAngle + style.endAngle) / 2 * Math.PI / 180; x = _curTarget.style.x + Math.cos(midAngle) * style.r / 1.5; y = _curTarget.style.y - Math.sin(midAngle) * style.r / 1.5; break; } } break; case ecConfig.CHART_TYPE_MAP : var name = params.name; var mapType = serie.mapType; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'text' && shapeList[i]._mapType == mapType && shapeList[i].style._text == name ) { _curTarget = shapeList[i]; x = _curTarget.style.x + _curTarget.position[0]; y = _curTarget.style.y + _curTarget.position[1]; break; } } break; case ecConfig.CHART_TYPE_CHORD: var name = params.name; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'sector' && ecData.get(shapeList[i], 'name') == name ) { _curTarget = shapeList[i]; var style = _curTarget.style; var midAngle = (style.startAngle + style.endAngle) / 2 * Math.PI / 180; x = _curTarget.style.x + Math.cos(midAngle) * (style.r - 2); y = _curTarget.style.y - Math.sin(midAngle) * (style.r - 2); zr.trigger( zrConfig.EVENT.MOUSEMOVE, { zrenderX : x, zrenderY : y } ); return; } } break; case ecConfig.CHART_TYPE_FORCE: var name = params.name; for (var i = 0, l = shapeList.length; i < l; i++) { if (shapeList[i].type == 'circle' && ecData.get(shapeList[i], 'name') == name ) { _curTarget = shapeList[i]; x = _curTarget.position[0]; y = _curTarget.position[1]; break; } } break; } if (typeof x != 'undefined' && typeof y != 'undefined') { _event = { zrenderX : x, zrenderY : y }; zr.addHoverShape(_curTarget); zr.refreshHover(); _showItemTrigger(); } } } /** * 关闭,公开接口 */ function hideTip() { _hide(); } function init(newOption, newDom) { option = newOption; dom = newDom; option.tooltip = self.reformOption(option.tooltip); option.tooltip.textStyle = zrUtil.merge( option.tooltip.textStyle, ecConfig.textStyle ); // 补全padding属性 option.tooltip.padding = self.reformCssArray( option.tooltip.padding ); _needAxisTrigger = false; if (option.tooltip.trigger == 'axis') { _needAxisTrigger = true; } var series = option.series; for (var i = 0, l = series.length; i < l; i++) { if (self.query(series[i], 'tooltip.trigger') == 'axis') { _needAxisTrigger = true; break; } } _showDelay = option.tooltip.showDelay; _hideDelay = option.tooltip.hideDelay; _defaultCssText = _style(option.tooltip); _tDom.style.position = 'absolute'; // 不是多余的,别删! self.hasAppend = false; _setSelectedMap(); _axisLineWidth = option.tooltip.axisPointer.lineStyle.width; } /** * 刷新 */ function refresh(newOption) { if (newOption) { option = newOption; option.tooltip = self.reformOption(option.tooltip); option.tooltip.textStyle = zrUtil.merge( option.tooltip.textStyle, ecConfig.textStyle ); // 补全padding属性 option.tooltip.padding = self.reformCssArray( option.tooltip.padding ); _setSelectedMap(); _axisLineWidth = option.tooltip.axisPointer.lineStyle.width; } } /** * zrender事件响应:窗口大小改变 */ function resize() { _zrHeight = zr.getHeight(); _zrWidth = zr.getWidth(); } /** * 释放后实例不可用,重载基类方法 */ function dispose() { clearTimeout(_hidingTicket); clearTimeout(_showingTicket); zr.un(zrConfig.EVENT.MOUSEMOVE, _onmousemove); zr.un(zrConfig.EVENT.GLOBALOUT, _onglobalout); if (self.hasAppend) { dom.firstChild.removeChild(_tDom); } _tDom = null; // self.clear(); self.shapeList = null; self = null; } /** * html转码的方法 */ function _encodeHTML(source) { return String(source) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } zr.on(zrConfig.EVENT.MOUSEMOVE, _onmousemove); zr.on(zrConfig.EVENT.GLOBALOUT, _onglobalout); // 重载基类方法 self.dispose = dispose; self.init = init; self.refresh = refresh; self.resize = resize; self.setComponent = setComponent; self.ontooltipHover = ontooltipHover; self.ondragend = ondragend; self.onlegendSelected = onlegendSelected; self.showTip = showTip; self.hideTip = hideTip; init(option, dom); } require('../component').define('tooltip', Tooltip); return Tooltip; });
组件重构 tooltip
src/component/tooltip.js
组件重构 tooltip
<ide><path>rc/component/tooltip.js <ide> * <ide> */ <ide> define(function (require) { <add> var Base = require('./base'); <add> <add> // 图形依赖 <ide> var LineShape = require('zrender/shape/Line'); <ide> var RectangleShape = require('zrender/shape/Rectangle'); <ide> var rectangleInstance = new RectangleShape({}); <ide> <add> var ecConfig = require('../config'); <add> var ecData = require('../util/ecData'); <add> var zrConfig = require('zrender/config'); <add> var zrEvent = require('zrender/tool/event'); <add> var zrArea = require('zrender/tool/area'); <add> var zrColor = require('zrender/tool/color'); <add> var zrUtil = require('zrender/tool/util'); <add> var zrShapeBase = require('zrender/shape/Base'); <add> <ide> /** <ide> * 构造函数 <ide> * @param {Object} messageCenter echart消息中心 <ide> * @param {HtmlElement} dom 目标对象 <ide> * @param {ECharts} myChart 当前图表实例 <ide> */ <del> function Tooltip(ecConfig, messageCenter, zr, option, dom, myChart) { <del> var Base = require('./base'); <del> Base.call(this, ecConfig, zr); <del> <del> var ecData = require('../util/ecData'); <del> <del> var zrConfig = require('zrender/config'); <del> var zrEvent = require('zrender/tool/event'); <del> var zrArea = require('zrender/tool/area'); <del> var zrColor = require('zrender/tool/color'); <del> var zrUtil = require('zrender/tool/util'); <del> var zrShapeBase = require('zrender/shape/Base'); <del> <del> var self = this; <del> self.type = ecConfig.COMPONENT_TYPE_TOOLTIP; <del> <del> var _zlevelBase = self.getZlevelBase(); <del> <del> var component = {}; // 组件索引 <del> var grid; <del> var xAxis; <del> var yAxis; <del> var polar; <del> <del> var _selectedMap = {}; <del> // tooltip dom & css <del> var _tDom = document.createElement('div'); <del> // 通用样式 <del> var _gCssText = 'position:absolute;' <del> + 'display:block;' <del> + 'border-style:solid;' <del> + 'white-space:nowrap;'; <del> // 默认样式 <del> var _defaultCssText; // css样式缓存 <del> <del> var _needAxisTrigger; // 坐标轴触发 <del> var _hidingTicket; <del> var _hideDelay; // 隐藏延迟 <del> var _showingTicket; <del> var _showDelay; // 显示延迟 <del> var _curTarget; <del> var _event; <del> <del> var _curTicket; // 异步回调标识,用来区分多个请求 <del> <del> // 缓存一些高宽数据 <del> var _zrHeight = zr.getHeight(); <del> var _zrWidth = zr.getWidth(); <del> <del> var _lastTipShape = false; <del> var _axisLineWidth = 0; <del> var _axisLineShape = new LineShape({ <del> zlevel: _zlevelBase, <add> function Tooltip(ecTheme, messageCenter, zr, option, dom, myChart) { <add> Base.call(this, ecTheme, zr, option); <add> <add> this.messageCenter = messageCenter; <add> this.dom = dom; <add> this.myChart = myChart; <add> <add> this._tDom = document.createElement('div'); <add> <add> this._axisLineShape = new LineShape({ <add> zlevel: this._zlevelBase, <ide> invisible : true, <ide> hoverable: false, <ide> style : { <ide> // strokeColor : ecConfig.categoryAxis.axisLine.lineStyle.color <ide> } <ide> }); <del> var _axisShadowShape = new LineShape({ <add> this._axisShadowShape = new LineShape({ <ide> zlevel: 1, // grid上,chart下 <ide> invisible : true, <ide> hoverable: false, <ide> // strokeColor : ecConfig.categoryAxis.axisLine.lineStyle.color <ide> } <ide> }); <del> zr.addShape(_axisLineShape); <del> zr.addShape(_axisShadowShape); <del> <add> this.zr.addShape(this._axisLineShape); <add> this.zr.addShape(this._axisShadowShape); <add> <add> var self = this; <add> self._onmousemove = function (param) { <add> return self.__onmousemove.call(self, param); <add> }; <add> self._onglobalout = function (param) { <add> return self.__onglobalout.call(self, param); <add> }; <add> <add> this.zr.on(zrConfig.EVENT.MOUSEMOVE, self._onmousemove); <add> this.zr.on(zrConfig.EVENT.GLOBALOUT, self._onglobalout); <add> <add> self._hide = function (param) { <add> return self.__hide.call(self, param); <add> }; <add> self._tryShow = function(param) { <add> return self.__tryShow.call(self, param); <add> } <add> self._refixed = function(param) { <add> return self.__refixed.call(self, param); <add> } <add> <add> this.init(option, dom); <add> } <add> <add> Tooltip.prototype = { <add> type : ecConfig.COMPONENT_TYPE_TOOLTIP, <add> // 通用样式 <add> _gCssText : 'position:absolute;' <add> + 'display:block;' <add> + 'border-style:solid;' <add> + 'white-space:nowrap;', <ide> /** <ide> * 根据配置设置dom样式 <ide> */ <del> function _style(opt) { <add> _style : function (opt) { <ide> if (!opt) { <ide> return ''; <ide> } <ide> <ide> var padding = opt.padding; <ide> if (typeof padding != 'undefined') { <del> padding = self.reformCssArray(padding); <add> padding = this.reformCssArray(padding); <ide> cssText.push( <ide> 'padding:' + padding[0] + 'px ' <ide> + padding[1] + 'px ' <ide> cssText = cssText.join(';') + ';'; <ide> <ide> return cssText; <del> } <del> <del> function _hide() { <del> if (_tDom) { <del> _tDom.style.display = 'none'; <add> }, <add> <add> __hide : function () { <add> if (this._tDom) { <add> this._tDom.style.display = 'none'; <ide> } <ide> var needRefresh = false; <del> if (!_axisLineShape.invisible) { <del> _axisLineShape.invisible = true; <del> zr.modShape(_axisLineShape.id, _axisLineShape); <add> if (!this._axisLineShape.invisible) { <add> this._axisLineShape.invisible = true; <add> this.zr.modShape(this._axisLineShape.id, this._axisLineShape); <ide> needRefresh = true; <ide> } <del> if (!_axisShadowShape.invisible) { <del> _axisShadowShape.invisible = true; <del> zr.modShape(_axisShadowShape.id, _axisShadowShape); <add> if (!this._axisShadowShape.invisible) { <add> this._axisShadowShape.invisible = true; <add> this.zr.modShape(this._axisShadowShape.id, this._axisShadowShape); <ide> needRefresh = true; <ide> } <del> if (_lastTipShape && _lastTipShape.tipShape.length > 0) { <del> zr.delShape(_lastTipShape.tipShape); <del> _lastTipShape = false; <del> } <del> needRefresh && zr.refresh(); <del> } <del> <del> function _show(x, y, specialCssText) { <del> var domHeight = _tDom.offsetHeight; <del> var domWidth = _tDom.offsetWidth; <del> if (x + domWidth > _zrWidth) { <add> if (this._lastTipShape && this._lastTipShape.tipShape.length > 0) { <add> this.zr.delShape(this._lastTipShape.tipShape); <add> this._lastTipShape = false; <add> } <add> needRefresh && this.zr.refresh(); <add> }, <add> <add> _show : function (x, y, specialCssText) { <add> var domHeight = this._tDom.offsetHeight; <add> var domWidth = this._tDom.offsetWidth; <add> if (x + domWidth > this._zrWidth) { <ide> // 太靠右 <del> //x = _zrWidth - domWidth; <add> //x = this._zrWidth - domWidth; <ide> x -= (domWidth + 40); <ide> } <del> if (y + domHeight > _zrHeight) { <add> if (y + domHeight > this._zrHeight) { <ide> // 太靠下 <del> //y = _zrHeight - domHeight; <add> //y = this._zrHeight - domHeight; <ide> y -= (domHeight - 20); <ide> } <ide> if (y < 20) { <ide> y = 0; <ide> } <del> _tDom.style.cssText = _gCssText <del> + _defaultCssText <add> this._tDom.style.cssText = this._gCssText <add> + this._defaultCssText <ide> + (specialCssText ? specialCssText : '') <ide> + 'left:' + x + 'px;top:' + y + 'px;'; <ide> <ide> if (domHeight < 10 || domWidth < 10) { <del> // _zrWidth - x < 100 || _zrHeight - y < 100 <del> setTimeout(_refixed, 20); <del> } <del> } <del> <del> function _refixed() { <del> if (_tDom) { <add> // this._zrWidth - x < 100 || this._zrHeight - y < 100 <add> setTimeout(this._refixed, 20); <add> } <add> }, <add> <add> __refixed : function () { <add> if (this._tDom) { <ide> var cssText = ''; <del> var domHeight = _tDom.offsetHeight; <del> var domWidth = _tDom.offsetWidth; <del> if (_tDom.offsetLeft + domWidth > _zrWidth) { <del> cssText += 'left:' + (_zrWidth - domWidth - 20) + 'px;'; <del> } <del> if (_tDom.offsetTop + domHeight > _zrHeight) { <del> cssText += 'top:' + (_zrHeight - domHeight - 10) + 'px;'; <add> var domHeight = this._tDom.offsetHeight; <add> var domWidth = this._tDom.offsetWidth; <add> if (this._tDom.offsetLeft + domWidth > this._zrWidth) { <add> cssText += 'left:' + (this._zrWidth - domWidth - 20) + 'px;'; <add> } <add> if (this._tDom.offsetTop + domHeight > this._zrHeight) { <add> cssText += 'top:' + (this._zrHeight - domHeight - 10) + 'px;'; <ide> } <ide> if (cssText !== '') { <del> _tDom.style.cssText += cssText; <del> } <del> } <del> } <del> <del> function _tryShow() { <add> this._tDom.style.cssText += cssText; <add> } <add> } <add> }, <add> <add> __tryShow : function () { <ide> var needShow; <ide> var trigger; <del> if (!_curTarget) { <add> if (!this._curTarget) { <ide> // 坐标轴事件 <del> _findPolarTrigger() || _findAxisTrigger(); <add> this._findPolarTrigger() || this._findAxisTrigger(); <ide> } <ide> else { <ide> // 数据项事件 <del> if (_curTarget._type == 'island' && option.tooltip.show) { <del> _showItemTrigger(); <add> if (this._curTarget._type == 'island' && option.tooltip.show) { <add> this._showItemTrigger(); <ide> return; <ide> } <del> var serie = ecData.get(_curTarget, 'series'); <del> var data = ecData.get(_curTarget, 'data'); <del> needShow = self.deepQuery( <add> var serie = ecData.get(this._curTarget, 'series'); <add> var data = ecData.get(this._curTarget, 'data'); <add> needShow = this.deepQuery( <ide> [data, serie, option], <ide> 'tooltip.show' <ide> ); <ide> || needShow === false <ide> ) { <ide> // 不响应tooltip的数据对象延时隐藏 <del> clearTimeout(_hidingTicket); <del> clearTimeout(_showingTicket); <del> _hidingTicket = setTimeout(_hide, _hideDelay); <add> clearTimeout(this._hidingTicket); <add> clearTimeout(this._showingTicket); <add> this._hidingTicket = setTimeout(this._hide, this._hideDelay); <ide> } <ide> else { <del> trigger = self.deepQuery( <add> trigger = this.deepQuery( <ide> [data, serie, option], <ide> 'tooltip.trigger' <ide> ); <ide> trigger == 'axis' <del> ? _showAxisTrigger( <add> ? this._showAxisTrigger( <ide> serie.xAxisIndex, serie.yAxisIndex, <del> ecData.get(_curTarget, 'dataIndex') <add> ecData.get(this._curTarget, 'dataIndex') <ide> ) <del> : _showItemTrigger(); <del> } <del> } <del> } <add> : this._showItemTrigger(); <add> } <add> } <add> }, <ide> <ide> /** <ide> * 直角系 <ide> */ <del> function _findAxisTrigger() { <del> if (!xAxis || !yAxis) { <del> _hidingTicket = setTimeout(_hide, _hideDelay); <add> _findAxisTrigger : function () { <add> if (!this.xAxis || !this.yAxis) { <add> this._hidingTicket = setTimeout(this._hide, this._hideDelay); <ide> return; <ide> } <del> var series = option.series; <add> var series = this.option.series; <ide> var xAxisIndex; <ide> var yAxisIndex; <ide> for (var i = 0, l = series.length; i < l; i++) { <ide> // 找到第一个axis触发tooltip的系列 <del> if (self.deepQuery( <del> [series[i], option], 'tooltip.trigger' <add> if (this.deepQuery( <add> [series[i], this.option], 'tooltip.trigger' <ide> ) == 'axis' <ide> ) { <ide> xAxisIndex = series[i].xAxisIndex || 0; <ide> yAxisIndex = series[i].yAxisIndex || 0; <del> if (xAxis.getAxis(xAxisIndex) <del> && xAxis.getAxis(xAxisIndex).type <add> if (this.xAxis.getAxis(xAxisIndex) <add> && this.xAxis.getAxis(xAxisIndex).type <ide> == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY <ide> ) { <ide> // 横轴为类目轴 <del> _showAxisTrigger(xAxisIndex, yAxisIndex, <del> _getNearestDataIndex('x', xAxis.getAxis(xAxisIndex)) <add> this._showAxisTrigger(xAxisIndex, yAxisIndex, <add> this._getNearestDataIndex('x', this.xAxis.getAxis(xAxisIndex)) <ide> ); <ide> return; <ide> } <del> else if (yAxis.getAxis(yAxisIndex) <del> && yAxis.getAxis(yAxisIndex).type <add> else if (this.yAxis.getAxis(yAxisIndex) <add> && this.yAxis.getAxis(yAxisIndex).type <ide> == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY <ide> ) { <ide> // 纵轴为类目轴 <del> _showAxisTrigger(xAxisIndex, yAxisIndex, <del> _getNearestDataIndex('y', yAxis.getAxis(yAxisIndex)) <add> this._showAxisTrigger(xAxisIndex, yAxisIndex, <add> this._getNearestDataIndex('y', this.yAxis.getAxis(yAxisIndex)) <ide> ); <ide> return; <ide> } <ide> } <ide> } <del> } <add> }, <ide> <ide> /** <ide> * 极坐标 <ide> */ <del> function _findPolarTrigger() { <del> if (!polar) { <add> _findPolarTrigger : function () { <add> if (!this.polar) { <ide> return false; <ide> } <del> var x = zrEvent.getX(_event); <del> var y = zrEvent.getY(_event); <del> var polarIndex = polar.getNearestIndex([x, y]); <add> var x = zrEvent.getX(this._event); <add> var y = zrEvent.getY(this._event); <add> var polarIndex = this.polar.getNearestIndex([x, y]); <ide> var valueIndex; <ide> if (polarIndex) { <ide> valueIndex = polarIndex.valueIndex; <ide> } <ide> <ide> return false; <del> } <add> }, <ide> <ide> /** <ide> * 根据坐标轴事件带的属性获取最近的axisDataIndex <ide> */ <del> function _getNearestDataIndex(direction, categoryAxis) { <add> _getNearestDataIndex : function (direction, categoryAxis) { <ide> var dataIndex = -1; <del> var x = zrEvent.getX(_event); <del> var y = zrEvent.getY(_event); <add> var x = zrEvent.getX(this._event); <add> var y = zrEvent.getY(this._event); <ide> if (direction == 'x') { <ide> // 横轴为类目轴 <ide> var left; <ide> var right; <del> var xEnd = grid.getXend(); <add> var xEnd = this.grid.getXend(); <ide> var curCoord = categoryAxis.getCoordByIndex(dataIndex); <ide> while (curCoord < xEnd) { <ide> if (curCoord <= x) { <ide> // 纵轴为类目轴 <ide> var top; <ide> var bottom; <del> var yStart = grid.getY(); <add> var yStart = this.grid.getY(); <ide> var curCoord = categoryAxis.getCoordByIndex(dataIndex); <ide> while (curCoord > yStart) { <ide> if (curCoord >= y) { <ide> return dataIndex; <ide> } <ide> return -1; <del> } <add> }, <ide> <ide> /** <ide> * 直角系 <ide> */ <del> function _showAxisTrigger(xAxisIndex, yAxisIndex, dataIndex) { <del> !_event.connectTrigger && messageCenter.dispatch( <add> _showAxisTrigger : function (xAxisIndex, yAxisIndex, dataIndex) { <add> !this._event.connectTrigger && this.messageCenter.dispatch( <ide> ecConfig.EVENT.TOOLTIP_IN_GRID, <del> _event <add> this._event <ide> ); <del> if (typeof xAxis == 'undefined' <del> || typeof yAxis == 'undefined' <add> if (typeof this.xAxis == 'undefined' <add> || typeof this.yAxis == 'undefined' <ide> || typeof xAxisIndex == 'undefined' <ide> || typeof yAxisIndex == 'undefined' <ide> || dataIndex < 0 <ide> ) { <ide> // 不响应tooltip的数据对象延时隐藏 <del> clearTimeout(_hidingTicket); <del> clearTimeout(_showingTicket); <del> _hidingTicket = setTimeout(_hide, _hideDelay); <add> clearTimeout(this._hidingTicket); <add> clearTimeout(this._showingTicket); <add> this._hidingTicket = setTimeout(this._hide, this._hideDelay); <ide> return; <ide> } <del> var series = option.series; <add> var series = this.option.series; <ide> var seriesArray = []; <ide> var seriesIndex = []; <ide> var categoryAxis; <ide> var formatter; <ide> var showContent; <ide> var specialCssText = ''; <del> if (option.tooltip.trigger == 'axis') { <del> if (option.tooltip.show === false) { <add> if (this.option.tooltip.trigger == 'axis') { <add> if (this.option.tooltip.show === false) { <ide> return; <ide> } <del> formatter = option.tooltip.formatter; <add> formatter = this.option.tooltip.formatter; <ide> } <ide> <ide> if (xAxisIndex != -1 <del> && xAxis.getAxis(xAxisIndex).type <add> && this.xAxis.getAxis(xAxisIndex).type <ide> == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY <ide> ) { <ide> // 横轴为类目轴,找到所有用这条横轴并且axis触发的系列数据 <del> categoryAxis = xAxis.getAxis(xAxisIndex); <add> categoryAxis = this.xAxis.getAxis(xAxisIndex); <ide> for (var i = 0, l = series.length; i < l; i++) { <del> if (!_isSelected(series[i].name)) { <add> if (!this._isSelected(series[i].name)) { <ide> continue; <ide> } <ide> if (series[i].xAxisIndex == xAxisIndex <del> && self.deepQuery( <del> [series[i], option], 'tooltip.trigger' <add> && this.deepQuery( <add> [series[i], this.option], 'tooltip.trigger' <ide> ) == 'axis' <ide> ) { <del> showContent = self.query( <add> showContent = this.query( <ide> series[i], <ide> 'tooltip.showContent' <ide> ) || showContent; <del> formatter = self.query( <add> formatter = this.query( <ide> series[i], <ide> 'tooltip.formatter' <ide> ) || formatter; <del> specialCssText += _style(self.query( <add> specialCssText += this._style(this.query( <ide> series[i], 'tooltip' <ide> )); <ide> seriesArray.push(series[i]); <ide> } <ide> } <ide> // 寻找高亮元素 <del> messageCenter.dispatch( <add> this.messageCenter.dispatch( <ide> ecConfig.EVENT.TOOLTIP_HOVER, <del> _event, <add> this._event, <ide> { <ide> seriesIndex : seriesIndex, <del> dataIndex : component.dataZoom <del> ? component.dataZoom.getRealDataIndex( <add> dataIndex : this.component.dataZoom <add> ? this.component.dataZoom.getRealDataIndex( <ide> seriesIndex, <ide> dataIndex <ide> ) <ide> : dataIndex <ide> } <ide> ); <del> y = zrEvent.getY(_event) + 10; <del> x = self.subPixelOptimize( <add> y = zrEvent.getY(this._event) + 10; <add> x = this.subPixelOptimize( <ide> categoryAxis.getCoordByIndex(dataIndex), <del> _axisLineWidth <del> ); <del> _styleAxisPointer( <add> this._axisLineWidth <add> ); <add> this._styleAxisPointer( <ide> seriesArray, <del> x, grid.getY(), <del> x, grid.getYend(), <add> x, this.grid.getY(), <add> x, this.grid.getYend(), <ide> categoryAxis.getGap() <ide> ); <ide> x += 10; <ide> } <ide> else if (yAxisIndex != -1 <del> && yAxis.getAxis(yAxisIndex).type <add> && this.yAxis.getAxis(yAxisIndex).type <ide> == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY <ide> ) { <ide> // 纵轴为类目轴,找到所有用这条纵轴并且axis触发的系列数据 <del> categoryAxis = yAxis.getAxis(yAxisIndex); <add> categoryAxis = this.yAxis.getAxis(yAxisIndex); <ide> for (var i = 0, l = series.length; i < l; i++) { <del> if (!_isSelected(series[i].name)) { <add> if (!this._isSelected(series[i].name)) { <ide> continue; <ide> } <ide> if (series[i].yAxisIndex == yAxisIndex <del> && self.deepQuery( <del> [series[i], option], 'tooltip.trigger' <add> && this.deepQuery( <add> [series[i], this.option], 'tooltip.trigger' <ide> ) == 'axis' <ide> ) { <del> showContent = self.query( <add> showContent = this.query( <ide> series[i], <ide> 'tooltip.showContent' <ide> ) || showContent; <del> formatter = self.query( <add> formatter = this.query( <ide> series[i], <ide> 'tooltip.formatter' <ide> ) || formatter; <del> specialCssText += _style(self.query( <add> specialCssText += this._style(this.query( <ide> series[i], 'tooltip' <ide> )); <ide> seriesArray.push(series[i]); <ide> } <ide> } <ide> // 寻找高亮元素 <del> messageCenter.dispatch( <add> this.messageCenter.dispatch( <ide> ecConfig.EVENT.TOOLTIP_HOVER, <del> _event, <add> this._event, <ide> { <ide> seriesIndex : seriesIndex, <del> dataIndex : component.dataZoom <del> ? component.dataZoom.getRealDataIndex( <add> dataIndex : this.component.dataZoom <add> ? this.component.dataZoom.getRealDataIndex( <ide> seriesIndex, <ide> dataIndex <ide> ) <ide> : dataIndex <ide> } <ide> ); <del> x = zrEvent.getX(_event) + 10; <del> y = self.subPixelOptimize( <add> x = zrEvent.getX(this._event) + 10; <add> y = this.subPixelOptimize( <ide> categoryAxis.getCoordByIndex(dataIndex), <del> _axisLineWidth <del> ); <del> _styleAxisPointer( <add> this._axisLineWidth <add> ); <add> this._styleAxisPointer( <ide> seriesArray, <del> grid.getX(), y, <del> grid.getXend(), y, <add> this.grid.getX(), y, <add> this.grid.getXend(), y, <ide> categoryAxis.getGap() <ide> ); <ide> y += 10; <ide> data <ide> ]); <ide> } <del> _curTicket = 'axis:' + dataIndex; <del> _tDom.innerHTML = formatter( <del> params, _curTicket, _setContent <add> this._curTicket = 'axis:' + dataIndex; <add> this._tDom.innerHTML = formatter( <add> params, this._curTicket, this._setContent <ide> ); <ide> } <ide> else if (typeof formatter == 'string') { <del> _curTicket = NaN; <add> this._curTicket = NaN; <ide> formatter = formatter.replace('{a}','{a0}') <ide> .replace('{b}','{b0}') <ide> .replace('{c}','{c0}'); <ide> for (var i = 0, l = seriesArray.length; i < l; i++) { <ide> formatter = formatter.replace( <ide> '{a' + i + '}', <del> _encodeHTML(seriesArray[i].name || '') <add> this._encodeHTML(seriesArray[i].name || '') <ide> ); <ide> formatter = formatter.replace( <ide> '{b' + i + '}', <del> _encodeHTML(categoryAxis.getNameByIndex(dataIndex)) <add> this._encodeHTML(categoryAxis.getNameByIndex(dataIndex)) <ide> ); <ide> data = seriesArray[i].data[dataIndex]; <ide> data = typeof data != 'undefined' <ide> formatter = formatter.replace( <ide> '{c' + i + '}', <ide> data instanceof Array <del> ? data : self.numAddCommas(data) <add> ? data : this.numAddCommas(data) <ide> ); <ide> } <del> _tDom.innerHTML = formatter; <add> this._tDom.innerHTML = formatter; <ide> } <ide> else { <del> _curTicket = NaN; <del> formatter = _encodeHTML( <add> this._curTicket = NaN; <add> formatter = this._encodeHTML( <ide> categoryAxis.getNameByIndex(dataIndex) <ide> ); <ide> <ide> for (var i = 0, l = seriesArray.length; i < l; i++) { <ide> formatter += '<br/>' <del> + _encodeHTML(seriesArray[i].name || '') <add> + this._encodeHTML(seriesArray[i].name || '') <ide> + ' : '; <ide> data = seriesArray[i].data[dataIndex]; <ide> data = typeof data != 'undefined' <ide> : data) <ide> : '-'; <ide> formatter += data instanceof Array <del> ? data : self.numAddCommas(data); <del> } <del> _tDom.innerHTML = formatter; <del> } <del> <del> if (showContent === false || !option.tooltip.showContent) { <add> ? data : this.numAddCommas(data); <add> } <add> this._tDom.innerHTML = formatter; <add> } <add> <add> if (showContent === false || !this.option.tooltip.showContent) { <ide> // 只用tooltip的行为,不显示主体 <ide> return; <ide> } <ide> <del> if (!self.hasAppend) { <del> _tDom.style.left = _zrWidth / 2 + 'px'; <del> _tDom.style.top = _zrHeight / 2 + 'px'; <del> dom.firstChild.appendChild(_tDom); <del> self.hasAppend = true; <del> } <del> _show(x, y, specialCssText); <del> } <del> } <add> if (!this.hasAppend) { <add> this._tDom.style.left = this._zrWidth / 2 + 'px'; <add> this._tDom.style.top = this._zrHeight / 2 + 'px'; <add> this.dom.firstChild.appendChild(this._tDom); <add> this.hasAppend = true; <add> } <add> this._show(x, y, specialCssText); <add> } <add> }, <ide> <ide> /** <ide> * 极坐标 <ide> */ <del> function _showPolarTrigger(polarIndex, dataIndex) { <del> if (typeof polar == 'undefined' <add> _showPolarTrigger : function (polarIndex, dataIndex) { <add> if (typeof this.polar == 'undefined' <ide> || typeof polarIndex == 'undefined' <ide> || typeof dataIndex == 'undefined' <ide> || dataIndex < 0 <ide> ) { <ide> return false; <ide> } <del> var series = option.series; <add> var series = this.option.series; <ide> var seriesArray = []; <ide> <ide> var formatter; <ide> var showContent; <ide> var specialCssText = ''; <del> if (option.tooltip.trigger == 'axis') { <del> if (option.tooltip.show === false) { <add> if (this.option.tooltip.trigger == 'axis') { <add> if (this.option.tooltip.show === false) { <ide> return false; <ide> } <del> formatter = option.tooltip.formatter; <add> formatter = this.option.tooltip.formatter; <ide> } <ide> var indicatorName = <del> option.polar[polarIndex].indicator[dataIndex].text; <add> this.option.polar[polarIndex].indicator[dataIndex].text; <ide> <ide> // 找到所有用这个极坐标并且axis触发的系列数据 <ide> for (var i = 0, l = series.length; i < l; i++) { <del> if (!_isSelected(series[i].name)) { <add> if (!this._isSelected(series[i].name)) { <ide> continue; <ide> } <ide> if (series[i].polarIndex == polarIndex <del> && self.deepQuery( <del> [series[i], option], 'tooltip.trigger' <add> && this.deepQuery( <add> [series[i], this.option], 'tooltip.trigger' <ide> ) == 'axis' <ide> ) { <del> showContent = self.query( <add> showContent = this.query( <ide> series[i], <ide> 'tooltip.showContent' <ide> ) || showContent; <del> formatter = self.query( <add> formatter = this.query( <ide> series[i], <ide> 'tooltip.formatter' <ide> ) || formatter; <del> specialCssText += _style(self.query( <add> specialCssText += this._style(this.query( <ide> series[i], 'tooltip' <ide> )); <ide> seriesArray.push(series[i]); <ide> polarData = seriesArray[i].data; <ide> for (var j = 0, k = polarData.length; j < k; j++) { <ide> data = polarData[j]; <del> if (!_isSelected(data.name)) { <add> if (!this._isSelected(data.name)) { <ide> continue; <ide> } <ide> data = typeof data != 'undefined' <ide> return; <ide> } <ide> if (typeof formatter == 'function') { <del> _curTicket = 'axis:' + dataIndex; <del> _tDom.innerHTML = formatter( <del> params, _curTicket, _setContent <add> this._curTicket = 'axis:' + dataIndex; <add> this._tDom.innerHTML = formatter( <add> params, this._curTicket, this._setContent <ide> ); <ide> } <ide> else if (typeof formatter == 'string') { <ide> for (var i = 0, l = params.length; i < l; i++) { <ide> formatter = formatter.replace( <ide> '{a' + i + '}', <del> _encodeHTML(params[i][0]) <add> this._encodeHTML(params[i][0]) <ide> ); <ide> formatter = formatter.replace( <ide> '{b' + i + '}', <del> _encodeHTML(params[i][1]) <add> this._encodeHTML(params[i][1]) <ide> ); <ide> formatter = formatter.replace( <ide> '{c' + i + '}', <del> self.numAddCommas(params[i][2]) <add> this.numAddCommas(params[i][2]) <ide> ); <ide> formatter = formatter.replace( <ide> '{d' + i + '}', <del> _encodeHTML(params[i][3]) <add> this._encodeHTML(params[i][3]) <ide> ); <ide> } <del> _tDom.innerHTML = formatter; <add> this._tDom.innerHTML = formatter; <ide> } <ide> else { <del> formatter = _encodeHTML(params[0][1]) + '<br/>' <del> + _encodeHTML(params[0][3]) + ' : ' <del> + self.numAddCommas(params[0][2]); <add> formatter = this._encodeHTML(params[0][1]) + '<br/>' <add> + this._encodeHTML(params[0][3]) + ' : ' <add> + this.numAddCommas(params[0][2]); <ide> for (var i = 1, l = params.length; i < l; i++) { <del> formatter += '<br/>' + _encodeHTML(params[i][1]) <add> formatter += '<br/>' + this._encodeHTML(params[i][1]) <ide> + '<br/>'; <del> formatter += _encodeHTML(params[i][3]) + ' : ' <del> + self.numAddCommas(params[i][2]); <del> } <del> _tDom.innerHTML = formatter; <del> } <del> <del> if (showContent === false || !option.tooltip.showContent) { <add> formatter += this._encodeHTML(params[i][3]) + ' : ' <add> + this.numAddCommas(params[i][2]); <add> } <add> this._tDom.innerHTML = formatter; <add> } <add> <add> if (showContent === false || !this.option.tooltip.showContent) { <ide> // 只用tooltip的行为,不显示主体 <ide> return; <ide> } <ide> <del> if (!self.hasAppend) { <del> _tDom.style.left = _zrWidth / 2 + 'px'; <del> _tDom.style.top = _zrHeight / 2 + 'px'; <del> dom.firstChild.appendChild(_tDom); <del> self.hasAppend = true; <del> } <del> _show( <del> zrEvent.getX(_event), <del> zrEvent.getY(_event), <add> if (!this.hasAppend) { <add> this._tDom.style.left = this._zrWidth / 2 + 'px'; <add> this._tDom.style.top = this._zrHeight / 2 + 'px'; <add> this.dom.firstChild.appendChild(this._tDom); <add> this.hasAppend = true; <add> } <add> this._show( <add> zrEvent.getX(this._event), <add> zrEvent.getY(this._event), <ide> specialCssText <ide> ); <ide> return true; <ide> } <del> } <del> <del> function _showItemTrigger() { <del> var serie = ecData.get(_curTarget, 'series'); <del> var data = ecData.get(_curTarget, 'data'); <del> var name = ecData.get(_curTarget, 'name'); <del> var value = ecData.get(_curTarget, 'value'); <del> var special = ecData.get(_curTarget, 'special'); <del> var special2 = ecData.get(_curTarget, 'special2'); <add> }, <add> <add> _showItemTrigger : function () { <add> var serie = ecData.get(this._curTarget, 'series'); <add> var data = ecData.get(this._curTarget, 'data'); <add> var name = ecData.get(this._curTarget, 'name'); <add> var value = ecData.get(this._curTarget, 'value'); <add> var special = ecData.get(this._curTarget, 'special'); <add> var special2 = ecData.get(this._curTarget, 'special2'); <ide> // 从低优先级往上找到trigger为item的formatter和样式 <ide> var formatter; <ide> var showContent; <ide> var specialCssText = ''; <ide> var indicator; <ide> var html = ''; <del> if (_curTarget._type != 'island') { <add> if (this._curTarget._type != 'island') { <ide> // 全局 <del> if (option.tooltip.trigger == 'item') { <del> formatter = option.tooltip.formatter; <add> if (this.option.tooltip.trigger == 'item') { <add> formatter = this.option.tooltip.formatter; <ide> } <ide> // 系列 <del> if (self.query(serie, 'tooltip.trigger') == 'item') { <del> showContent = self.query( <add> if (this.query(serie, 'tooltip.trigger') == 'item') { <add> showContent = this.query( <ide> serie, 'tooltip.showContent' <ide> ) || showContent; <del> formatter = self.query( <add> formatter = this.query( <ide> serie, 'tooltip.formatter' <ide> ) || formatter; <del> specialCssText += _style(self.query( <add> specialCssText += this._style(this.query( <ide> serie, 'tooltip' <ide> )); <ide> } <ide> // 数据项 <del> showContent = self.query( <add> showContent = this.query( <ide> data, 'tooltip.showContent' <ide> ) || showContent; <del> formatter = self.query( <add> formatter = this.query( <ide> data, 'tooltip.formatter' <ide> ) || formatter; <del> specialCssText += _style(self.query(data, 'tooltip')); <add> specialCssText += this._style(this.query(data, 'tooltip')); <ide> } <ide> else { <del> showContent = self.deepQuery( <del> [data, serie, option], <add> showContent = this.deepQuery( <add> [data, serie, this.option], <ide> 'tooltip.showContent' <ide> ); <del> formatter = self.deepQuery( <del> [data, serie, option], <add> formatter = this.deepQuery( <add> [data, serie, this.option], <ide> 'tooltip.islandFormatter' <ide> ); <ide> } <ide> <ide> if (typeof formatter == 'function') { <del> _curTicket = (serie.name || '') <add> this._curTicket = (serie.name || '') <ide> + ':' <del> + ecData.get(_curTarget, 'dataIndex'); <del> _tDom.innerHTML = formatter( <add> + ecData.get(this._curTarget, 'dataIndex'); <add> this._tDom.innerHTML = formatter( <ide> [ <ide> serie.name || '', <ide> name, <ide> special, <ide> special2 <ide> ], <del> _curTicket, <del> _setContent <add> this._curTicket, <add> this._setContent <ide> ); <ide> } <ide> else if (typeof formatter == 'string') { <del> _curTicket = NaN; <add> this._curTicket = NaN; <ide> formatter = formatter.replace('{a}','{a0}') <ide> .replace('{b}','{b0}') <ide> .replace('{c}','{c0}'); <ide> formatter = formatter.replace( <del> '{a0}', _encodeHTML(serie.name || '') <add> '{a0}', this._encodeHTML(serie.name || '') <ide> ) <del> .replace('{b0}', _encodeHTML(name)) <add> .replace('{b0}', this._encodeHTML(name)) <ide> .replace( <ide> '{c0}', <ide> value instanceof Array <del> ? value : self.numAddCommas(value) <add> ? value : this.numAddCommas(value) <ide> ); <ide> <ide> formatter = formatter.replace('{d}','{d0}') <ide> .replace('{d0}', special || ''); <ide> formatter = formatter.replace('{e}','{e0}') <del> .replace('{e0}', ecData.get(_curTarget, 'special2') || ''); <del> <del> _tDom.innerHTML = formatter; <add> .replace('{e0}', ecData.get(this._curTarget, 'special2') || ''); <add> <add> this._tDom.innerHTML = formatter; <ide> } <ide> else { <del> _curTicket = NaN; <add> this._curTicket = NaN; <ide> if (serie.type == ecConfig.CHART_TYPE_SCATTER) { <del> _tDom.innerHTML = (typeof serie.name != 'undefined' <del> ? (_encodeHTML(serie.name) + '<br/>') <add> this._tDom.innerHTML = (typeof serie.name != 'undefined' <add> ? (this._encodeHTML(serie.name) + '<br/>') <ide> : '' <ide> ) <ide> + (name === '' <del> ? '' : (_encodeHTML(name) + ' : ') <add> ? '' : (this._encodeHTML(name) + ' : ') <ide> ) <ide> + value <ide> + (typeof special == 'undefined' <ide> } <ide> else if (serie.type == ecConfig.CHART_TYPE_RADAR && special) { <ide> indicator = special; <del> html += _encodeHTML( <add> html += this._encodeHTML( <ide> name === '' ? (serie.name || '') : name <ide> ); <ide> html += html === '' ? '' : '<br />'; <ide> for (var i = 0 ; i < indicator.length; i ++) { <del> html += _encodeHTML(indicator[i].text) + ' : ' <del> + self.numAddCommas(value[i]) + '<br />'; <del> } <del> _tDom.innerHTML = html; <add> html += this._encodeHTML(indicator[i].text) + ' : ' <add> + this.numAddCommas(value[i]) + '<br />'; <add> } <add> this._tDom.innerHTML = html; <ide> } <ide> else if (serie.type == ecConfig.CHART_TYPE_CHORD) { <ide> if (typeof special2 == 'undefined') { <ide> // 外环上 <del> _tDom.innerHTML = _encodeHTML(name) + ' (' <del> + self.numAddCommas(value) + ')'; <add> this._tDom.innerHTML = this._encodeHTML(name) + ' (' <add> + this.numAddCommas(value) + ')'; <ide> } <ide> else { <del> var name1 = _encodeHTML(name); <del> var name2 = _encodeHTML(special); <add> var name1 = this._encodeHTML(name); <add> var name2 = this._encodeHTML(special); <ide> // 内部弦上 <del> _tDom.innerHTML = (typeof serie.name != 'undefined' <del> ? (_encodeHTML(serie.name) + '<br/>') <add> this._tDom.innerHTML = (typeof serie.name != 'undefined' <add> ? (this._encodeHTML(serie.name) + '<br/>') <ide> : '') <ide> + name1 + ' -> ' + name2 <del> + ' (' + self.numAddCommas(value) + ')' <add> + ' (' + this.numAddCommas(value) + ')' <ide> + '<br />' <ide> + name2 + ' -> ' + name1 <del> + ' (' + self.numAddCommas(special2) + ')'; <add> + ' (' + this.numAddCommas(special2) + ')'; <ide> } <ide> } <ide> else { <del> _tDom.innerHTML = (typeof serie.name != 'undefined' <del> ? (_encodeHTML(serie.name) + '<br/>') <add> this._tDom.innerHTML = (typeof serie.name != 'undefined' <add> ? (this._encodeHTML(serie.name) + '<br/>') <ide> : '') <del> + _encodeHTML(name) + ' : ' <del> + self.numAddCommas(value) + <add> + this._encodeHTML(name) + ' : ' <add> + this.numAddCommas(value) + <ide> (typeof special == 'undefined' <ide> ? '' <del> : (' ('+ self.numAddCommas(special) +')') <add> : (' ('+ this.numAddCommas(special) +')') <ide> ); <ide> } <ide> } <ide> <del> if (!_axisLineShape.invisible) { <del> _axisLineShape.invisible = true; <del> zr.modShape(_axisLineShape.id, _axisLineShape); <del> zr.refresh(); <add> if (!this._axisLineShape.invisible) { <add> this._axisLineShape.invisible = true; <add> this.zr.modShape(this._axisLineShape.id, this._axisLineShape); <add> this.zr.refresh(); <ide> } <ide> <del> if (showContent === false || !option.tooltip.showContent) { <add> if (showContent === false || !this.option.tooltip.showContent) { <ide> // 只用tooltip的行为,不显示主体 <ide> return; <ide> } <ide> <del> if (!self.hasAppend) { <del> _tDom.style.left = _zrWidth / 2 + 'px'; <del> _tDom.style.top = _zrHeight / 2 + 'px'; <del> dom.firstChild.appendChild(_tDom); <del> self.hasAppend = true; <del> } <del> <del> _show( <del> zrEvent.getX(_event) + 20, <del> zrEvent.getY(_event) - 20, <add> if (!this.hasAppend) { <add> this._tDom.style.left = this._zrWidth / 2 + 'px'; <add> this._tDom.style.top = this._zrHeight / 2 + 'px'; <add> this.dom.firstChild.appendChild(this._tDom); <add> this.hasAppend = true; <add> } <add> <add> this._show( <add> zrEvent.getX(this._event) + 20, <add> zrEvent.getY(this._event) - 20, <ide> specialCssText <ide> ); <del> } <add> }, <ide> <ide> /** <ide> * 设置坐标轴指示器样式 <ide> */ <del> function _styleAxisPointer( <del> seriesArray, xStart, yStart, xEnd, yEnd, gap <del> ) { <add> _styleAxisPointer : function (seriesArray, xStart, yStart, xEnd, yEnd, gap) { <ide> if (seriesArray.length > 0) { <ide> var queryTarget; <ide> var curType; <del> var axisPointer = option.tooltip.axisPointer; <add> var axisPointer = this.option.tooltip.axisPointer; <ide> var pointType = axisPointer.type; <ide> var lineColor = axisPointer.lineStyle.color; <ide> var lineWidth = axisPointer.lineStyle.width; <ide> var areaColor = axisPointer.areaStyle.color; <ide> <ide> for (var i = 0, l = seriesArray.length; i < l; i++) { <del> if (self.deepQuery( <del> [seriesArray[i], option], 'tooltip.trigger' <add> if (this.deepQuery( <add> [seriesArray[i], this.option], 'tooltip.trigger' <ide> ) == 'axis' <ide> ) { <ide> queryTarget = seriesArray[i]; <del> curType = self.query( <add> curType = this.query( <ide> queryTarget, <ide> 'tooltip.axisPointer.type' <ide> ); <ide> pointType = curType || pointType; <ide> if (curType == 'line') { <del> lineColor = self.query( <add> lineColor = this.query( <ide> queryTarget, <ide> 'tooltip.axisPointer.lineStyle.color' <ide> ) || lineColor; <del> lineWidth = self.query( <add> lineWidth = this.query( <ide> queryTarget, <ide> 'tooltip.axisPointer.lineStyle.width' <ide> ) || lineWidth; <del> lineType = self.query( <add> lineType = this.query( <ide> queryTarget, <ide> 'tooltip.axisPointer.lineStyle.type' <ide> ) || lineType; <ide> } <ide> else if (curType == 'shadow') { <del> areaSize = self.query( <add> areaSize = this.query( <ide> queryTarget, <ide> 'tooltip.axisPointer.areaStyle.size' <ide> ) || areaSize; <del> areaColor = self.query( <add> areaColor = this.query( <ide> queryTarget, <ide> 'tooltip.axisPointer.areaStyle.color' <ide> ) || areaColor; <ide> } <ide> <ide> if (pointType == 'line') { <del> _axisLineShape.style = { <add> this._axisLineShape.style = { <ide> xStart : xStart, <ide> yStart : yStart, <ide> xEnd : xEnd, <ide> lineWidth : lineWidth, <ide> lineType : lineType <ide> }; <del> _axisLineShape.invisible = false; <del> zr.modShape(_axisLineShape.id, _axisLineShape); <add> this._axisLineShape.invisible = false; <add> this.zr.modShape(this._axisLineShape.id, this._axisLineShape); <ide> } <ide> else if (pointType == 'shadow') { <ide> if (typeof areaSize == 'undefined' <ide> } <ide> if (xStart == xEnd) { <ide> // 纵向 <del> if (Math.abs(grid.getX() - xStart) < 2) { <add> if (Math.abs(this.grid.getX() - xStart) < 2) { <ide> // 最左边 <ide> lineWidth /= 2; <ide> xStart = xEnd = xEnd + lineWidth / 2; <ide> } <del> else if (Math.abs(grid.getXend() - xStart) < 2) { <add> else if (Math.abs(this.grid.getXend() - xStart) < 2) { <ide> // 最右边 <ide> lineWidth /= 2; <ide> xStart = xEnd = xEnd - lineWidth / 2; <ide> } <ide> else if (yStart == yEnd) { <ide> // 横向 <del> if (Math.abs(grid.getY() - yStart) < 2) { <add> if (Math.abs(this.grid.getY() - yStart) < 2) { <ide> // 最上边 <ide> lineWidth /= 2; <ide> yStart = yEnd = yEnd + lineWidth / 2; <ide> } <del> else if (Math.abs(grid.getYend() - yStart) < 2) { <add> else if (Math.abs(this.grid.getYend() - yStart) < 2) { <ide> // 最右边 <ide> lineWidth /= 2; <ide> yStart = yEnd = yEnd - lineWidth / 2; <ide> } <ide> } <del> _axisShadowShape.style = { <add> this._axisShadowShape.style = { <ide> xStart : xStart, <ide> yStart : yStart, <ide> xEnd : xEnd, <ide> strokeColor : areaColor, <ide> lineWidth : lineWidth <ide> }; <del> _axisShadowShape.invisible = false; <del> zr.modShape(_axisShadowShape.id, _axisShadowShape); <del> } <del> zr.refresh(); <del> } <del> } <del> <del> /** <del> * zrender事件响应:鼠标移动 <del> */ <del> function _onmousemove(param) { <del> clearTimeout(_hidingTicket); <del> clearTimeout(_showingTicket); <add> this._axisShadowShape.invisible = false; <add> this.zr.modShape(this._axisShadowShape.id, this._axisShadowShape); <add> } <add> this.zr.refresh(); <add> } <add> }, <add> <add> __onmousemove : function (param) { <add> clearTimeout(this._hidingTicket); <add> clearTimeout(this._showingTicket); <ide> var target = param.target; <ide> var mx = zrEvent.getX(param.event); <ide> var my = zrEvent.getY(param.event); <ide> if (!target) { <ide> // 判断是否落到直角系里,axis触发的tooltip <del> _curTarget = false; <del> _event = param.event; <del> _event._target = _event.target || _event.toElement; <del> _event.zrenderX = mx; <del> _event.zrenderY = my; <del> if (_needAxisTrigger <del> && grid <add> this._curTarget = false; <add> this._event = param.event; <add> this._event._target = this._event.target || this._event.toElement; <add> this._event.zrenderX = mx; <add> this._event.zrenderY = my; <add> if (this._needAxisTrigger <add> && this.grid <ide> && zrArea.isInside( <ide> rectangleInstance, <del> grid.getArea(), <add> this.grid.getArea(), <ide> mx, <ide> my <ide> ) <ide> ) { <del> _showingTicket = setTimeout(_tryShow, _showDelay); <del> } <del> else if (_needAxisTrigger <del> && polar <del> && polar.isInside([mx, my]) != -1 <add> this._showingTicket = setTimeout(this._tryShow, this._showDelay); <add> } <add> else if (this._needAxisTrigger <add> && this.polar <add> && this.polar.isInside([mx, my]) != -1 <ide> ) { <del> _showingTicket = setTimeout(_tryShow, _showDelay); <add> this._showingTicket = setTimeout(this._tryShow, this._showDelay); <ide> } <ide> else { <del> !_event.connectTrigger && messageCenter.dispatch( <add> !this._event.connectTrigger && this.messageCenter.dispatch( <ide> ecConfig.EVENT.TOOLTIP_OUT_GRID, <del> _event <add> this._event <ide> ); <del> _hidingTicket = setTimeout(_hide, _hideDelay); <add> this._hidingTicket = setTimeout(this._hide, this._hideDelay); <ide> } <ide> } <ide> else { <del> _curTarget = target; <del> _event = param.event; <del> _event._target = _event.target || _event.toElement; <del> _event.zrenderX = mx; <del> _event.zrenderY = my; <add> this._curTarget = target; <add> this._event = param.event; <add> this._event._target = this._event.target || this._event.toElement; <add> this._event.zrenderX = mx; <add> this._event.zrenderY = my; <ide> var polarIndex; <del> if (_needAxisTrigger <del> && polar <del> && (polarIndex = polar.isInside([mx, my])) != -1 <add> if (this._needAxisTrigger <add> && this.polar <add> && (polarIndex = this.polar.isInside([mx, my])) != -1 <ide> ) { <ide> // 看用这个polar的系列数据是否是axis触发,如果是设置_curTarget为nul <del> var series = option.series; <add> var series = this.option.series; <ide> for (var i = 0, l = series.length; i < l; i++) { <ide> if (series[i].polarIndex == polarIndex <del> && self.deepQuery( <del> [series[i], option], 'tooltip.trigger' <add> && this.deepQuery( <add> [series[i], this.option], 'tooltip.trigger' <ide> ) == 'axis' <ide> ) { <del> _curTarget = null; <add> this._curTarget = null; <ide> break; <ide> } <ide> } <ide> <ide> } <del> _showingTicket = setTimeout(_tryShow, _showDelay); <del> } <del> } <add> this._showingTicket = setTimeout(this._tryShow, this._showDelay); <add> } <add> }, <ide> <ide> /** <ide> * zrender事件响应:鼠标离开绘图区域 <ide> */ <del> function _onglobalout() { <del> clearTimeout(_hidingTicket); <del> clearTimeout(_showingTicket); <del> _hidingTicket = setTimeout(_hide, _hideDelay); <del> } <del> <add> __onglobalout : function () { <add> clearTimeout(this._hidingTicket); <add> clearTimeout(this._showingTicket); <add> this._hidingTicket = setTimeout(this._hide, this._hideDelay); <add> }, <add> <ide> /** <ide> * 异步回调填充内容 <ide> */ <del> function _setContent(ticket, content) { <del> if (!_tDom) { <add> _setContent : function (ticket, content) { <add> if (!this._tDom) { <ide> return; <ide> } <del> if (ticket == _curTicket) { <del> _tDom.innerHTML = content; <add> if (ticket == this._curTicket) { <add> this._tDom.innerHTML = content; <ide> } <ide> <del> setTimeout(_refixed, 20); <del> } <del> <del> function setComponent() { <del> component = myChart.component; <del> grid = component.grid; <del> xAxis = component.xAxis; <del> yAxis = component.yAxis; <del> polar = component.polar; <del> } <del> <del> function ontooltipHover(param, tipShape) { <del> if (!_lastTipShape // 不存在或者存在但dataIndex发生变化才需要重绘 <del> || (_lastTipShape && _lastTipShape.dataIndex != param.dataIndex) <add> setTimeout(this._refixed, 20); <add> }, <add> <add> setComponent : function () { <add> this.component = this.myChart.component; <add> this.grid = this.component.grid; <add> this.xAxis = this.component.xAxis; <add> this.yAxis = this.component.yAxis; <add> this.polar = this.component.polar; <add> }, <add> <add> ontooltipHover : function (param, tipShape) { <add> if (!this._lastTipShape // 不存在或者存在但dataIndex发生变化才需要重绘 <add> || (this._lastTipShape && this._lastTipShape.dataIndex != param.dataIndex) <ide> ) { <del> if (_lastTipShape && _lastTipShape.tipShape.length > 0) { <del> zr.delShape(_lastTipShape.tipShape); <add> if (this._lastTipShape && this._lastTipShape.tipShape.length > 0) { <add> this.zr.delShape(this._lastTipShape.tipShape); <ide> } <ide> for (var i = 0, l = tipShape.length; i < l; i++) { <del> tipShape[i].zlevel = _zlevelBase; <add> tipShape[i].zlevel = this._zlevelBase; <ide> tipShape[i].style = zrShapeBase.prototype.getHighlightStyle( <ide> tipShape[i].style, <ide> tipShape[i].highlightStyle <ide> tipShape[i].ondragend = null; <ide> tipShape[i].ondragover = null; <ide> tipShape[i].ondrop = null; <del> zr.addShape(tipShape[i]); <del> } <del> _lastTipShape = { <add> this.zr.addShape(tipShape[i]); <add> } <add> this._lastTipShape = { <ide> dataIndex : param.dataIndex, <ide> tipShape : tipShape <ide> }; <ide> } <del> } <del> <del> function ondragend() { <del> _hide(); <del> } <add> }, <add> <add> ondragend : function () { <add> this._hide(); <add> }, <ide> <ide> /** <ide> * 图例选择 <ide> */ <del> function onlegendSelected(param) { <del> _selectedMap = param.selected; <del> } <del> <del> function _setSelectedMap() { <del> if (option.legend && option.legend.selected) { <del> _selectedMap = option.legend.selected; <add> onlegendSelected : function (param) { <add> this._selectedMap = param.selected; <add> }, <add> <add> _setSelectedMap : function () { <add> if (this.option.legend && this.option.legend.selected) { <add> this._selectedMap = this.option.legend.selected; <ide> } <ide> else { <del> _selectedMap = {}; <del> } <del> } <del> <del> function _isSelected(itemName) { <del> if (typeof _selectedMap[itemName] != 'undefined') { <del> return _selectedMap[itemName]; <add> this._selectedMap = {}; <add> } <add> }, <add> <add> _isSelected : function (itemName) { <add> if (typeof this._selectedMap[itemName] != 'undefined') { <add> return this._selectedMap[itemName]; <ide> } <ide> else { <ide> return true; // 没在legend里定义的都为true啊~ <ide> } <del> } <add> }, <ide> <ide> /** <ide> * 模拟tooltip hover方法 <ide> * {seriesIndex: 0, seriesName:'', dataInex:0} line、bar、scatter、k、radar <ide> * {seriesIndex: 0, seriesName:'', name:''} map、pie、chord <ide> */ <del> function showTip(params) { <add> showTip : function (params) { <ide> if (!params) { <ide> return; <ide> } <ide> <ide> var seriesIndex; <del> var series = option.series; <add> var series = this.option.series; <ide> if (typeof params.seriesIndex != 'undefined') { <ide> seriesIndex = params.seriesIndex; <ide> } <ide> return; <ide> } <ide> var chart = myChart.chart[serie.type]; <del> var isAxisTrigger = self.deepQuery( <del> [serie, option], 'tooltip.trigger' <add> var isAxisTrigger = this.deepQuery( <add> [serie, this.option], 'tooltip.trigger' <ide> ) == 'axis'; <ide> <ide> if (!chart) { <ide> case ecConfig.CHART_TYPE_LINE : <ide> case ecConfig.CHART_TYPE_BAR : <ide> case ecConfig.CHART_TYPE_K : <del> if (typeof xAxis == 'undefined' <del> || typeof yAxis == 'undefined' <add> if (typeof this.xAxis == 'undefined' <add> || typeof this.yAxis == 'undefined' <ide> || serie.data.length <= dataIndex <ide> ) { <ide> return; <ide> } <ide> var xAxisIndex = serie.xAxisIndex || 0; <ide> var yAxisIndex = serie.yAxisIndex || 0; <del> if (xAxis.getAxis(xAxisIndex).type <add> if (this.xAxis.getAxis(xAxisIndex).type <ide> == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY <ide> ) { <ide> // 横轴是类目 <del> _event = { <del> zrenderX : xAxis.getAxis(xAxisIndex).getCoordByIndex(dataIndex), <del> zrenderY : grid.getY() + (grid.getYend() - grid.getY()) / 4 <add> this._event = { <add> zrenderX : this.xAxis.getAxis(xAxisIndex).getCoordByIndex(dataIndex), <add> zrenderY : this.grid.getY() + (this.grid.getYend() - this.grid.getY()) / 4 <ide> }; <ide> } <ide> else { <ide> // 纵轴是类目 <del> _event = { <del> zrenderX : grid.getX() + (grid.getXend() - grid.getX()) / 4, <del> zrenderY : yAxis.getAxis(yAxisIndex).getCoordByIndex(dataIndex) <add> this._event = { <add> zrenderX : this.grid.getX() + (this.grid.getXend() - this.grid.getX()) / 4, <add> zrenderY : this.yAxis.getAxis(yAxisIndex).getCoordByIndex(dataIndex) <ide> }; <ide> } <del> _showAxisTrigger( <add> this._showAxisTrigger( <ide> xAxisIndex, <ide> yAxisIndex, <ide> dataIndex <ide> ); <ide> break; <ide> case ecConfig.CHART_TYPE_RADAR : <del> if (typeof polar == 'undefined' <add> if (typeof this.polar == 'undefined' <ide> || serie.data[0].value.length <= dataIndex <ide> ) { <ide> return; <ide> } <ide> var polarIndex = serie.polarIndex || 0; <del> var vector = polar.getVector(polarIndex, dataIndex, 'max'); <del> _event = { <add> var vector = this.polar.getVector(polarIndex, dataIndex, 'max'); <add> this._event = { <ide> zrenderX : vector[0], <ide> zrenderY : vector[1] <ide> }; <ide> if (ecData.get(shapeList[i], 'seriesIndex') == seriesIndex <ide> && ecData.get(shapeList[i], 'dataIndex') == dataIndex <ide> ) { <del> _curTarget = shapeList[i]; <add> this._curTarget = shapeList[i]; <ide> x = shapeList[i].style.x; <ide> y = chart.type != ecConfig.CHART_TYPE_K <ide> ? shapeList[i].style.y : shapeList[i].style.y[0]; <ide> && ecData.get(shapeList[i], 'seriesIndex') == seriesIndex <ide> && ecData.get(shapeList[i], 'dataIndex') == dataIndex <ide> ) { <del> _curTarget = shapeList[i]; <del> var vector = polar.getCenter(serie.polarIndex || 0); <add> this._curTarget = shapeList[i]; <add> var vector = this.polar.getCenter(serie.polarIndex || 0); <ide> x = vector[0]; <ide> y = vector[1]; <ide> break; <ide> && ecData.get(shapeList[i], 'seriesIndex') == seriesIndex <ide> && ecData.get(shapeList[i], 'name') == name <ide> ) { <del> _curTarget = shapeList[i]; <del> var style = _curTarget.style; <add> this._curTarget = shapeList[i]; <add> var style = this._curTarget.style; <ide> var midAngle = (style.startAngle + style.endAngle) <ide> / 2 * Math.PI / 180; <del> x = _curTarget.style.x + Math.cos(midAngle) * style.r / 1.5; <del> y = _curTarget.style.y - Math.sin(midAngle) * style.r / 1.5; <add> x = this._curTarget.style.x + Math.cos(midAngle) * style.r / 1.5; <add> y = this._curTarget.style.y - Math.sin(midAngle) * style.r / 1.5; <ide> break; <ide> } <ide> } <ide> && shapeList[i]._mapType == mapType <ide> && shapeList[i].style._text == name <ide> ) { <del> _curTarget = shapeList[i]; <del> x = _curTarget.style.x + _curTarget.position[0]; <del> y = _curTarget.style.y + _curTarget.position[1]; <add> this._curTarget = shapeList[i]; <add> x = this._curTarget.style.x + this._curTarget.position[0]; <add> y = this._curTarget.style.y + this._curTarget.position[1]; <ide> break; <ide> } <ide> } <ide> if (shapeList[i].type == 'sector' <ide> && ecData.get(shapeList[i], 'name') == name <ide> ) { <del> _curTarget = shapeList[i]; <del> var style = _curTarget.style; <add> this._curTarget = shapeList[i]; <add> var style = this._curTarget.style; <ide> var midAngle = (style.startAngle + style.endAngle) <ide> / 2 * Math.PI / 180; <del> x = _curTarget.style.x + Math.cos(midAngle) * (style.r - 2); <del> y = _curTarget.style.y - Math.sin(midAngle) * (style.r - 2); <del> zr.trigger( <add> x = this._curTarget.style.x + Math.cos(midAngle) * (style.r - 2); <add> y = this._curTarget.style.y - Math.sin(midAngle) * (style.r - 2); <add> this.zr.trigger( <ide> zrConfig.EVENT.MOUSEMOVE, <ide> { <ide> zrenderX : x, <ide> if (shapeList[i].type == 'circle' <ide> && ecData.get(shapeList[i], 'name') == name <ide> ) { <del> _curTarget = shapeList[i]; <del> x = _curTarget.position[0]; <del> y = _curTarget.position[1]; <add> this._curTarget = shapeList[i]; <add> x = this._curTarget.position[0]; <add> y = this._curTarget.position[1]; <ide> break; <ide> } <ide> } <ide> break; <ide> } <ide> if (typeof x != 'undefined' && typeof y != 'undefined') { <del> _event = { <add> this._event = { <ide> zrenderX : x, <ide> zrenderY : y <ide> }; <del> zr.addHoverShape(_curTarget); <del> zr.refreshHover(); <del> _showItemTrigger(); <del> } <del> } <del> } <add> this.zr.addHoverShape(this._curTarget); <add> this.zr.refreshHover(); <add> this._showItemTrigger(); <add> } <add> } <add> }, <ide> <ide> /** <ide> * 关闭,公开接口 <ide> */ <del> function hideTip() { <del> _hide(); <del> } <del> <del> function init(newOption, newDom) { <del> option = newOption; <del> dom = newDom; <del> <del> option.tooltip = self.reformOption(option.tooltip); <del> option.tooltip.textStyle = zrUtil.merge( <del> option.tooltip.textStyle, <del> ecConfig.textStyle <add> hideTip : function () { <add> this._hide(); <add> }, <add> <add> init : function (newOption, newDom) { <add> // this.component; <add> // this.grid; <add> // this.xAxis; <add> // this.yAxis; <add> // this.polar; <add> <add> this._selectedMap = {}; <add> <add> // 默认样式 <add> // this._defaultCssText; // css样式缓存 <add> // this._needAxisTrigger; // 坐标轴触发 <add> // this._curTarget; <add> // this._event; <add> // this._curTicket; // 异步回调标识,用来区分多个请求 <add> <add> // 缓存一些高宽数据 <add> this._zrHeight = this.zr.getHeight(); <add> this._zrWidth = this.zr.getWidth(); <add> <add> this._lastTipShape = false; <add> this._axisLineWidth = 0; <add> <add> this.option = newOption; <add> this.dom = newDom; <add> <add> this.option.tooltip = this.reformOption(this.option.tooltip); <add> this.option.tooltip.textStyle = zrUtil.merge( <add> this.option.tooltip.textStyle, <add> this.ecTheme.textStyle <ide> ); <ide> // 补全padding属性 <del> option.tooltip.padding = self.reformCssArray( <del> option.tooltip.padding <add> this.option.tooltip.padding = this.reformCssArray( <add> this.option.tooltip.padding <ide> ); <ide> <del> _needAxisTrigger = false; <del> if (option.tooltip.trigger == 'axis') { <del> _needAxisTrigger = true; <del> } <del> <del> var series = option.series; <add> this._needAxisTrigger = false; <add> if (this.option.tooltip.trigger == 'axis') { <add> this._needAxisTrigger = true; <add> } <add> <add> var series = this.option.series; <ide> for (var i = 0, l = series.length; i < l; i++) { <del> if (self.query(series[i], 'tooltip.trigger') == 'axis') { <del> _needAxisTrigger = true; <add> if (this.query(series[i], 'tooltip.trigger') == 'axis') { <add> this._needAxisTrigger = true; <ide> break; <ide> } <ide> } <del> _showDelay = option.tooltip.showDelay; <del> _hideDelay = option.tooltip.hideDelay; <del> _defaultCssText = _style(option.tooltip); <del> _tDom.style.position = 'absolute'; // 不是多余的,别删! <del> self.hasAppend = false; <del> _setSelectedMap(); <add> // this._hidingTicket; <add> // this._showingTicket; <add> this._showDelay = this.option.tooltip.showDelay; // 显示延迟 <add> this._hideDelay = this.option.tooltip.hideDelay; // 隐藏延迟 <add> this._defaultCssText = this._style(this.option.tooltip); <add> this._tDom.style.position = 'absolute'; // 不是多余的,别删! <add> this.hasAppend = false; <add> this._setSelectedMap(); <ide> <del> _axisLineWidth = option.tooltip.axisPointer.lineStyle.width; <del> } <add> this._axisLineWidth = this.option.tooltip.axisPointer.lineStyle.width; <add> }, <ide> <ide> /** <ide> * 刷新 <ide> */ <del> function refresh(newOption) { <add> refresh : function (newOption) { <ide> if (newOption) { <del> option = newOption; <del> option.tooltip = self.reformOption(option.tooltip); <del> option.tooltip.textStyle = zrUtil.merge( <del> option.tooltip.textStyle, <del> ecConfig.textStyle <add> this.option = newOption; <add> this.option.tooltip = this.reformOption(this.option.tooltip); <add> this.option.tooltip.textStyle = zrUtil.merge( <add> this.option.tooltip.textStyle, <add> this.ecTheme.textStyle <ide> ); <ide> // 补全padding属性 <del> option.tooltip.padding = self.reformCssArray( <del> option.tooltip.padding <del> ); <del> _setSelectedMap(); <del> _axisLineWidth = option.tooltip.axisPointer.lineStyle.width; <del> } <del> } <add> this.option.tooltip.padding = this.reformCssArray( <add> this.option.tooltip.padding <add> ); <add> this._setSelectedMap(); <add> this._axisLineWidth = this.option.tooltip.axisPointer.lineStyle.width; <add> } <add> }, <ide> <ide> /** <ide> * zrender事件响应:窗口大小改变 <ide> */ <del> function resize() { <del> _zrHeight = zr.getHeight(); <del> _zrWidth = zr.getWidth(); <del> } <add> resize : function () { <add> this._zrHeight = this.zr.getHeight(); <add> this._zrWidth = this.zr.getWidth(); <add> }, <ide> <ide> /** <ide> * 释放后实例不可用,重载基类方法 <ide> */ <del> function dispose() { <del> clearTimeout(_hidingTicket); <del> clearTimeout(_showingTicket); <del> zr.un(zrConfig.EVENT.MOUSEMOVE, _onmousemove); <del> zr.un(zrConfig.EVENT.GLOBALOUT, _onglobalout); <del> <del> if (self.hasAppend) { <del> dom.firstChild.removeChild(_tDom); <del> } <del> _tDom = null; <del> <del> // self.clear(); <del> self.shapeList = null; <del> self = null; <del> } <add> dispose : function () { <add> clearTimeout(this._hidingTicket); <add> clearTimeout(this._showingTicket); <add> this.zr.un(zrConfig.EVENT.MOUSEMOVE, self._onmousemove); <add> this.zr.un(zrConfig.EVENT.GLOBALOUT, self._onglobalout); <add> <add> if (this.hasAppend) { <add> this.dom.firstChild.removeChild(this._tDom); <add> } <add> this._tDom = null; <add> <add> // this.clear(); <add> this.shapeList = null; <add> }, <ide> <ide> /** <ide> * html转码的方法 <ide> */ <del> function _encodeHTML(source) { <add> _encodeHTML : function (source) { <ide> return String(source) <ide> .replace(/&/g, '&amp;') <ide> .replace(/</g, '&lt;') <ide> .replace(/"/g, '&quot;') <ide> .replace(/'/g, '&#39;'); <ide> } <del> <del> zr.on(zrConfig.EVENT.MOUSEMOVE, _onmousemove); <del> zr.on(zrConfig.EVENT.GLOBALOUT, _onglobalout); <del> <del> // 重载基类方法 <del> self.dispose = dispose; <del> <del> self.init = init; <del> self.refresh = refresh; <del> self.resize = resize; <del> self.setComponent = setComponent; <del> self.ontooltipHover = ontooltipHover; <del> self.ondragend = ondragend; <del> self.onlegendSelected = onlegendSelected; <del> self.showTip = showTip; <del> self.hideTip = hideTip; <del> init(option, dom); <del> } <del> <add> }; <add> <add> zrUtil.inherits(Tooltip, Base); <add> <ide> require('../component').define('tooltip', Tooltip); <ide> <ide> return Tooltip;
Java
bsd-3-clause
5620569a8c87b4b50c24d6db783f7e4451de7307
0
bobbylight/RSyntaxTextArea,bobbylight/RSyntaxTextArea
/* * 10/08/2011 * * CurlyFoldParser.java - Fold parser for languages with C-style syntax. * * This library is distributed under a modified BSD license. See the included * RSyntaxTextArea.License.txt file for details. */ package org.fife.ui.rsyntaxtextarea.folding; import java.util.ArrayList; import java.util.List; import javax.swing.text.BadLocationException; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenMaker; /** * A basic fold parser that can be used for languages such as C, that use * curly braces to denote code blocks. This parser searches for curly brace * pairs and creates code folds out of them. It can also optionally find * C-style multi-line comments ("<code>/* ... *&#47;</code>") and make them * foldable as well.<p> * * This parser knows nothing about language semantics; it uses * <code>RSyntaxTextArea</code>'s syntax highlighting tokens to identify * curly braces. By default, it looks for single-char tokens of type * {@link Token#SEPARATOR}, with lexemes '<code>{</code>' or '<code>}</code>'. * If your {@link TokenMaker} uses a different token type for curly braces, you * should override the {@link #isLeftCurly(Token)} and * {@link #isRightCurly(Token)} methods with your own definitions. In theory, * you could extend this fold parser to parse languages that use completely * different tokens than curly braces to denote foldable regions by overriding * those two methods.<p> * * Note also that this class may impose somewhat of a performance penalty on * large source files, since it re-parses the entire document each time folds * are reevaluated. * * @author Robert Futrell * @version 1.0 */ public class CurlyFoldParser implements FoldParser { /** * Whether to scan for C-style multi-line comments and make them foldable. */ private boolean foldableMultiLineComments; /** * Whether this parser is folding Java. */ private final boolean java; /** * Used to find import statements when folding Java code. */ private static final char[] KEYWORD_IMPORT = "import".toCharArray(); /** * Ending of a multi-line comment in C, C++, Java, etc. */ protected static final char[] C_MLC_END = "*/".toCharArray(); /** * Creates a fold parser that identifies foldable regions via curly braces * as well as C-style multi-line comments. */ public CurlyFoldParser() { this(true, false); } /** * Constructor. * * @param cStyleMultiLineComments Whether to scan for C-style multi-line * comments and make them foldable. * @param java Whether this parser is folding Java. This adds extra * parsing rules, such as grouping all import statements into a * fold section. */ public CurlyFoldParser(boolean cStyleMultiLineComments, boolean java) { this.foldableMultiLineComments = cStyleMultiLineComments; this.java = java; } /** * Returns whether multi-line comments are foldable with this parser. * * @return Whether multi-line comments are foldable. * @see #setFoldableMultiLineComments(boolean) */ public boolean getFoldableMultiLineComments() { return foldableMultiLineComments; } /** * {@inheritDoc} */ public List<Fold> getFolds(RSyntaxTextArea textArea) { List<Fold> folds = new ArrayList<Fold>(); Fold currentFold = null; int lineCount = textArea.getLineCount(); boolean inMLC = false; int mlcStart = 0; int importStartLine = -1; int lastSeenImportLine = -1; int importGroupStartOffs = -1; int importGroupEndOffs = -1; int lastRightCurlyLine = -1; Fold prevFold = null; try { for (int line=0; line<lineCount; line++) { Token t = textArea.getTokenListForLine(line); while (t!=null && t.isPaintable()) { if (getFoldableMultiLineComments() && t.isComment()) { // Java-specific stuff if (java) { if (importStartLine>-1) { if (lastSeenImportLine>importStartLine) { Fold fold = null; // Any imports found *should* be a top-level fold, // but we're extra lenient here and allow groups // of them anywhere to keep our parser better-behaved // if they have random "imports" throughout code. if (currentFold==null) { fold = new Fold(FoldType.IMPORTS, textArea, importGroupStartOffs); folds.add(fold); } else { fold = currentFold.createChild(FoldType.IMPORTS, importGroupStartOffs); } fold.setEndOffset(importGroupEndOffs); } importStartLine = lastSeenImportLine = importGroupStartOffs = importGroupEndOffs = -1; } } if (inMLC) { // If we found the end of an MLC that started // on a previous line... if (t.endsWith(C_MLC_END)) { int mlcEnd = t.getEndOffset() - 1; if (currentFold==null) { currentFold = new Fold(FoldType.COMMENT, textArea, mlcStart); currentFold.setEndOffset(mlcEnd); folds.add(currentFold); currentFold = null; } else { currentFold = currentFold.createChild(FoldType.COMMENT, mlcStart); currentFold.setEndOffset(mlcEnd); currentFold = currentFold.getParent(); } //System.out.println("Ending MLC at: " + mlcEnd + ", parent==" + currentFold); inMLC = false; mlcStart = 0; } // Otherwise, this MLC is continuing on to yet // another line. } else { // If we're an MLC that ends on a later line... if (t.getType()!=Token.COMMENT_EOL && !t.endsWith(C_MLC_END)) { //System.out.println("Starting MLC at: " + t.offset); inMLC = true; mlcStart = t.getOffset(); } } } else if (isLeftCurly(t)) { // Java-specific stuff if (java) { if (importStartLine>-1) { if (lastSeenImportLine>importStartLine) { Fold fold = null; // Any imports found *should* be a top-level fold, // but we're extra lenient here and allow groups // of them anywhere to keep our parser better-behaved // if they have random "imports" throughout code. if (currentFold==null) { fold = new Fold(FoldType.IMPORTS, textArea, importGroupStartOffs); folds.add(fold); } else { fold = currentFold.createChild(FoldType.IMPORTS, importGroupStartOffs); } fold.setEndOffset(importGroupEndOffs); } importStartLine = lastSeenImportLine = importGroupStartOffs = importGroupEndOffs = -1; } } // If a new fold block starts on the same line as the // previous one ends, we treat it as one big block // (e.g. K&R-style "} else {") if (prevFold != null && line == lastRightCurlyLine) { currentFold = prevFold; // Keep currentFold.endOffset where it was, so that // unclosed folds at end of the file work as well // as possible prevFold = null; lastRightCurlyLine = -1; } else if (currentFold==null) { // A top-level fold currentFold = new Fold(FoldType.CODE, textArea, t.getOffset()); folds.add(currentFold); } else { // A nested fold currentFold = currentFold.createChild(FoldType.CODE, t.getOffset()); } } else if (isRightCurly(t)) { if (currentFold!=null) { currentFold.setEndOffset(t.getOffset()); Fold parentFold = currentFold.getParent(); //System.out.println("... Adding regular fold at " + t.offset + ", parent==" + parentFold); // Don't add fold markers for single-line blocks if (currentFold.isOnSingleLine()) { if (!currentFold.removeFromParent()) { folds.remove(folds.size()-1); } } else { // Remember the end of the last completed fold, // in case it needs to get merged with the next // one (e.g. K&R "} else {" style) lastRightCurlyLine = line; prevFold = currentFold; } currentFold = parentFold; } } // Java-specific folding rules else if (java) { if (t.is(Token.RESERVED_WORD, KEYWORD_IMPORT)) { if (importStartLine==-1) { importStartLine = line; importGroupStartOffs = t.getOffset(); importGroupEndOffs = t.getOffset(); } lastSeenImportLine = line; } else if (importStartLine>-1 && t.isIdentifier() &&//SEPARATOR && t.isSingleChar(';')) { importGroupEndOffs = t.getOffset(); } } t = t.getNextToken(); } } } catch (BadLocationException ble) { // Should never happen ble.printStackTrace(); } return folds; } /** * Returns whether the token is a left curly brace. This method exists * so subclasses can provide their own curly brace definition. * * @param t The token. * @return Whether it is a left curly brace. * @see #isRightCurly(Token) */ public boolean isLeftCurly(Token t) { return t.isLeftCurly(); } /** * Returns whether the token is a right curly brace. This method exists * so subclasses can provide their own curly brace definition. * * @param t The token. * @return Whether it is a right curly brace. * @see #isLeftCurly(Token) */ public boolean isRightCurly(Token t) { return t.isRightCurly(); } /** * Sets whether multi-line comments are foldable with this parser. * * @param foldable Whether multi-line comments are foldable. * @see #getFoldableMultiLineComments() */ public void setFoldableMultiLineComments(boolean foldable) { this.foldableMultiLineComments = foldable; } }
src/main/java/org/fife/ui/rsyntaxtextarea/folding/CurlyFoldParser.java
/* * 10/08/2011 * * CurlyFoldParser.java - Fold parser for languages with C-style syntax. * * This library is distributed under a modified BSD license. See the included * RSyntaxTextArea.License.txt file for details. */ package org.fife.ui.rsyntaxtextarea.folding; import java.util.ArrayList; import java.util.List; import javax.swing.text.BadLocationException; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenMaker; /** * A basic fold parser that can be used for languages such as C, that use * curly braces to denote code blocks. This parser searches for curly brace * pairs and creates code folds out of them. It can also optionally find * C-style multi-line comments ("<code>/* ... *&#47;</code>") and make them * foldable as well.<p> * * This parser knows nothing about language semantics; it uses * <code>RSyntaxTextArea</code>'s syntax highlighting tokens to identify * curly braces. By default, it looks for single-char tokens of type * {@link Token#SEPARATOR}, with lexemes '<code>{</code>' or '<code>}</code>'. * If your {@link TokenMaker} uses a different token type for curly braces, you * should override the {@link #isLeftCurly(Token)} and * {@link #isRightCurly(Token)} methods with your own definitions. In theory, * you could extend this fold parser to parse languages that use completely * different tokens than curly braces to denote foldable regions by overriding * those two methods.<p> * * Note also that this class may impose somewhat of a performance penalty on * large source files, since it re-parses the entire document each time folds * are reevaluated. * * @author Robert Futrell * @version 1.0 */ public class CurlyFoldParser implements FoldParser { /** * Whether to scan for C-style multi-line comments and make them foldable. */ private boolean foldableMultiLineComments; /** * Whether this parser is folding Java. */ private final boolean java; /** * Used to find import statements when folding Java code. */ private static final char[] KEYWORD_IMPORT = "import".toCharArray(); /** * Ending of a multi-line comment in C, C++, Java, etc. */ protected static final char[] C_MLC_END = "*/".toCharArray(); /** * Creates a fold parser that identifies foldable regions via curly braces * as well as C-style multi-line comments. */ public CurlyFoldParser() { this(true, false); } /** * Constructor. * * @param cStyleMultiLineComments Whether to scan for C-style multi-line * comments and make them foldable. * @param java Whether this parser is folding Java. This adds extra * parsing rules, such as grouping all import statements into a * fold section. */ public CurlyFoldParser(boolean cStyleMultiLineComments, boolean java) { this.foldableMultiLineComments = cStyleMultiLineComments; this.java = java; } /** * Returns whether multi-line comments are foldable with this parser. * * @return Whether multi-line comments are foldable. * @see #setFoldableMultiLineComments(boolean) */ public boolean getFoldableMultiLineComments() { return foldableMultiLineComments; } /** * {@inheritDoc} */ public List<Fold> getFolds(RSyntaxTextArea textArea) { List<Fold> folds = new ArrayList<Fold>(); Fold currentFold = null; int lineCount = textArea.getLineCount(); boolean inMLC = false; int mlcStart = 0; int importStartLine = -1; int lastSeenImportLine = -1; int importGroupStartOffs = -1; int importGroupEndOffs = -1; try { for (int line=0; line<lineCount; line++) { Token t = textArea.getTokenListForLine(line); while (t!=null && t.isPaintable()) { if (getFoldableMultiLineComments() && t.isComment()) { // Java-specific stuff if (java) { if (importStartLine>-1) { if (lastSeenImportLine>importStartLine) { Fold fold = null; // Any imports found *should* be a top-level fold, // but we're extra lenient here and allow groups // of them anywhere to keep our parser better-behaved // if they have random "imports" throughout code. if (currentFold==null) { fold = new Fold(FoldType.IMPORTS, textArea, importGroupStartOffs); folds.add(fold); } else { fold = currentFold.createChild(FoldType.IMPORTS, importGroupStartOffs); } fold.setEndOffset(importGroupEndOffs); } importStartLine = lastSeenImportLine = importGroupStartOffs = importGroupEndOffs = -1; } } if (inMLC) { // If we found the end of an MLC that started // on a previous line... if (t.endsWith(C_MLC_END)) { int mlcEnd = t.getEndOffset() - 1; if (currentFold==null) { currentFold = new Fold(FoldType.COMMENT, textArea, mlcStart); currentFold.setEndOffset(mlcEnd); folds.add(currentFold); currentFold = null; } else { currentFold = currentFold.createChild(FoldType.COMMENT, mlcStart); currentFold.setEndOffset(mlcEnd); currentFold = currentFold.getParent(); } //System.out.println("Ending MLC at: " + mlcEnd + ", parent==" + currentFold); inMLC = false; mlcStart = 0; } // Otherwise, this MLC is continuing on to yet // another line. } else { // If we're an MLC that ends on a later line... if (t.getType()!=Token.COMMENT_EOL && !t.endsWith(C_MLC_END)) { //System.out.println("Starting MLC at: " + t.offset); inMLC = true; mlcStart = t.getOffset(); } } } else if (isLeftCurly(t)) { // Java-specific stuff if (java) { if (importStartLine>-1) { if (lastSeenImportLine>importStartLine) { Fold fold = null; // Any imports found *should* be a top-level fold, // but we're extra lenient here and allow groups // of them anywhere to keep our parser better-behaved // if they have random "imports" throughout code. if (currentFold==null) { fold = new Fold(FoldType.IMPORTS, textArea, importGroupStartOffs); folds.add(fold); } else { fold = currentFold.createChild(FoldType.IMPORTS, importGroupStartOffs); } fold.setEndOffset(importGroupEndOffs); } importStartLine = lastSeenImportLine = importGroupStartOffs = importGroupEndOffs = -1; } } if (currentFold==null) { currentFold = new Fold(FoldType.CODE, textArea, t.getOffset()); folds.add(currentFold); } else { currentFold = currentFold.createChild(FoldType.CODE, t.getOffset()); } } else if (isRightCurly(t)) { if (currentFold!=null) { currentFold.setEndOffset(t.getOffset()); Fold parentFold = currentFold.getParent(); //System.out.println("... Adding regular fold at " + t.offset + ", parent==" + parentFold); // Don't add fold markers for single-line blocks if (currentFold.isOnSingleLine()) { if (!currentFold.removeFromParent()) { folds.remove(folds.size()-1); } } currentFold = parentFold; } } // Java-specific folding rules else if (java) { if (t.is(Token.RESERVED_WORD, KEYWORD_IMPORT)) { if (importStartLine==-1) { importStartLine = line; importGroupStartOffs = t.getOffset(); importGroupEndOffs = t.getOffset(); } lastSeenImportLine = line; } else if (importStartLine>-1 && t.isIdentifier() &&//SEPARATOR && t.isSingleChar(';')) { importGroupEndOffs = t.getOffset(); } } t = t.getNextToken(); } } } catch (BadLocationException ble) { // Should never happen ble.printStackTrace(); } return folds; } /** * Returns whether the token is a left curly brace. This method exists * so subclasses can provide their own curly brace definition. * * @param t The token. * @return Whether it is a left curly brace. * @see #isRightCurly(Token) */ public boolean isLeftCurly(Token t) { return t.isLeftCurly(); } /** * Returns whether the token is a right curly brace. This method exists * so subclasses can provide their own curly brace definition. * * @param t The token. * @return Whether it is a right curly brace. * @see #isLeftCurly(Token) */ public boolean isRightCurly(Token t) { return t.isRightCurly(); } /** * Sets whether multi-line comments are foldable with this parser. * * @param foldable Whether multi-line comments are foldable. * @see #getFoldableMultiLineComments() */ public void setFoldableMultiLineComments(boolean foldable) { this.foldableMultiLineComments = foldable; } }
Fix #116: K&R-styled 'if' statements don't fold correctdly
src/main/java/org/fife/ui/rsyntaxtextarea/folding/CurlyFoldParser.java
Fix #116: K&R-styled 'if' statements don't fold correctdly
<ide><path>rc/main/java/org/fife/ui/rsyntaxtextarea/folding/CurlyFoldParser.java <ide> int lastSeenImportLine = -1; <ide> int importGroupStartOffs = -1; <ide> int importGroupEndOffs = -1; <del> <add> int lastRightCurlyLine = -1; <add> Fold prevFold = null; <add> <ide> try { <ide> <ide> for (int line=0; line<lineCount; line++) { <ide> <ide> } <ide> <del> if (currentFold==null) { <add> // If a new fold block starts on the same line as the <add> // previous one ends, we treat it as one big block <add> // (e.g. K&R-style "} else {") <add> if (prevFold != null && line == lastRightCurlyLine) { <add> currentFold = prevFold; <add> // Keep currentFold.endOffset where it was, so that <add> // unclosed folds at end of the file work as well <add> // as possible <add> prevFold = null; <add> lastRightCurlyLine = -1; <add> } <add> else if (currentFold==null) { // A top-level fold <ide> currentFold = new Fold(FoldType.CODE, textArea, t.getOffset()); <ide> folds.add(currentFold); <ide> } <del> else { <add> else { // A nested fold <ide> currentFold = currentFold.createChild(FoldType.CODE, t.getOffset()); <ide> } <ide> <ide> folds.remove(folds.size()-1); <ide> } <ide> } <add> else { <add> // Remember the end of the last completed fold, <add> // in case it needs to get merged with the next <add> // one (e.g. K&R "} else {" style) <add> lastRightCurlyLine = line; <add> prevFold = currentFold; <add> } <ide> currentFold = parentFold; <ide> } <ide>
Java
epl-1.0
error: pathspec 'D0519_Evaluate_max_mutation_sites.java' did not match any file(s) known to git
856bff719f807d0593c5f5fdebf240acf18b56cb
1
breezedu/LossHomozygosity,breezedu/LossHomozygosity,breezedu/LossHomozygosity,breezedu/LossHomozygosity
package coursera_java_duke; /*********** * Off all the mutation sites (829 on TTN gene), some are not 'rare' enough to be considered; * So we set the allele-count threshold at 10, then we got 741 qualify allele-counts * if we set the allele-count threshold at 5, we got 691 qualify allele-counts * if we set the allele-count threshold at 3, we got 629 qualify allele-counts * * Thus, we assume allele-counts less than 5 to be 'rare'. * * * * @author Jeff * 05-18-2016 */ public class D0519_Evaluate_max_mutation_sites { public static void main(String[] args){ //Initial total and threshold for our formula int total = 691; int threshold = 5; //The allele counts over population*2 gives allele frequency double allele_p = (double) 2/(60706 * 2); double log_p = Math.log10(allele_p); double log_p_hat = Math.log10(1 - allele_p); System.out.println("log_p: " + log_p + " log_p_hat: " + log_p_hat); //get all the combination results for Comb(n, x); /********** * This is just a test code for Combinatoin() function * for(int i=0; i<125; i++){ double comb_rest = Combination(700, i); System.out.println("Comb_700_" + i + " = " + comb_rest); } */ //calculate the chance for possible variants an individual might have double sum = 0; for(int i=0; i<total; i++){ double log_y = Math.log10(Combination(total, i)) + i * log_p + (total - i) * log_p_hat; sum += Math.pow(10, log_y); System.out.println( i + " variants, probability: " + Math.pow(10, log_y) + ".\t Combination: " + Combination(total, i) + "\t the probability left: " + (1 -sum)); } }//end of main() /******** * Get the combination of C(n, x) * @param i * @param i2 * @return */ private static double Combination(int n, int x) { // TODO Auto-generated method stub double result = 1; for(int i=1; i<x + 1; i++){ result *= (n + 1 - i); result = result / i; //System.out.print(" \t " + result); } return result; } }//ee
D0519_Evaluate_max_mutation_sites.java
0519 mutation sites sampling java
D0519_Evaluate_max_mutation_sites.java
0519 mutation sites sampling java
<ide><path>0519_Evaluate_max_mutation_sites.java <add>package coursera_java_duke; <add> <add> <add>/*********** <add> * Off all the mutation sites (829 on TTN gene), some are not 'rare' enough to be considered; <add> * So we set the allele-count threshold at 10, then we got 741 qualify allele-counts <add> * if we set the allele-count threshold at 5, we got 691 qualify allele-counts <add> * if we set the allele-count threshold at 3, we got 629 qualify allele-counts <add> * <add> * Thus, we assume allele-counts less than 5 to be 'rare'. <add> * <add> * <add> * <add> * @author Jeff <add> * 05-18-2016 <add> */ <add>public class D0519_Evaluate_max_mutation_sites { <add> <add> <add> public static void main(String[] args){ <add> <add> //Initial total and threshold for our formula <add> int total = 691; <add> int threshold = 5; <add> <add> //The allele counts over population*2 gives allele frequency <add> double allele_p = (double) 2/(60706 * 2); <add> double log_p = Math.log10(allele_p); <add> double log_p_hat = Math.log10(1 - allele_p); <add> <add> System.out.println("log_p: " + log_p + " log_p_hat: " + log_p_hat); <add> <add> //get all the combination results for Comb(n, x); <add> /********** <add> * This is just a test code for Combinatoin() function <add> * <add> for(int i=0; i<125; i++){ <add> double comb_rest = Combination(700, i); <add> System.out.println("Comb_700_" + i + " = " + comb_rest); <add> } <add> */ <add> <add> //calculate the chance for possible variants an individual might have <add> double sum = 0; <add> for(int i=0; i<total; i++){ <add> <add> double log_y = Math.log10(Combination(total, i)) + i * log_p + (total - i) * log_p_hat; <add> <add> sum += Math.pow(10, log_y); <add> <add> System.out.println( i + " variants, probability: " + Math.pow(10, log_y) + ".\t Combination: " + Combination(total, i) + "\t the probability left: " + (1 -sum)); <add> } <add> <add> <add> }//end of main() <add> <add> <add> /******** <add> * Get the combination of C(n, x) <add> * @param i <add> * @param i2 <add> * @return <add> */ <add> private static double Combination(int n, int x) { <add> // TODO Auto-generated method stub <add> <add> double result = 1; <add> <add> for(int i=1; i<x + 1; i++){ <add> <add> <add> result *= (n + 1 - i); <add> result = result / i; <add> <add> //System.out.print(" \t " + result); <add> } <add> <add> return result; <add> } <add> <add> <add> <add>}//ee
Java
apache-2.0
3b2e0f53d5dbbea5ec5278fe88a53c277c74dd22
0
davidmoten/geo,davidmoten/geo
package com.github.davidmoten.geo; import static com.github.davidmoten.grumpy.core.Position.to180; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.github.davidmoten.geo.util.Preconditions; import com.github.davidmoten.grumpy.core.Position; /** * <p> * Utility functions for * <a href="http://en.wikipedia.org/wiki/Geohash">geohashing</a>. * </p> * * @author dave * */ public final class GeoHash { private static final double PRECISION = 0.000000000001; /** * The standard practical maximum length for geohashes. */ public static final int MAX_HASH_LENGTH = 12; /** * Default maximum number of hashes for covering a bounding box. */ public static final int DEFAULT_MAX_HASHES = 12; /** * Powers of 2 from 32 down to 1. */ private static final int[] BITS = new int[] { 16, 8, 4, 2, 1 }; /** * The characters used in base 32 representations. */ private static final String BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"; /** * Utility lookup for neighbouring hashes. */ private static final Map<Direction, Map<Parity, String>> NEIGHBOURS = createNeighbours(); /** * Utility lookup for hash borders. */ private static final Map<Direction, Map<Parity, String>> BORDERS = createBorders(); /** * Private constructor. */ private GeoHash() { // prevent instantiation } /** * Returns a map to be used in hash border calculations. * * @return map of borders */ private static Map<Direction, Map<Parity, String>> createBorders() { Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); m.get(Direction.RIGHT).put(Parity.EVEN, "bcfguvyz"); m.get(Direction.LEFT).put(Parity.EVEN, "0145hjnp"); m.get(Direction.TOP).put(Parity.EVEN, "prxz"); m.get(Direction.BOTTOM).put(Parity.EVEN, "028b"); addOddParityEntries(m); return m; } /** * Returns a map to be used in adjacent hash calculations. * * @return map */ private static Map<Direction, Map<Parity, String>> createNeighbours() { Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); m.get(Direction.RIGHT).put(Parity.EVEN, "bc01fg45238967deuvhjyznpkmstqrwx"); m.get(Direction.LEFT).put(Parity.EVEN, "238967debc01fg45kmstqrwxuvhjyznp"); m.get(Direction.TOP).put(Parity.EVEN, "p0r21436x8zb9dcf5h7kjnmqesgutwvy"); m.get(Direction.BOTTOM).put(Parity.EVEN, "14365h7k9dcfesgujnmqp0r2twvyx8zb"); addOddParityEntries(m); return m; } /** * Create a direction and parity map for use in adjacent hash calculations. * * @return map */ private static Map<Direction, Map<Parity, String>> createDirectionParityMap() { Map<Direction, Map<Parity, String>> m = newHashMap(); m.put(Direction.BOTTOM, GeoHash.<Parity, String> newHashMap()); m.put(Direction.TOP, GeoHash.<Parity, String> newHashMap()); m.put(Direction.LEFT, GeoHash.<Parity, String> newHashMap()); m.put(Direction.RIGHT, GeoHash.<Parity, String> newHashMap()); return m; } private static <T, D> Map<T, D> newHashMap() { return new HashMap<T, D>(); } /** * Puts odd parity entries in the map m based purely on the even entries. * * @param m * map */ private static void addOddParityEntries(Map<Direction, Map<Parity, String>> m) { m.get(Direction.BOTTOM).put(Parity.ODD, m.get(Direction.LEFT).get(Parity.EVEN)); m.get(Direction.TOP).put(Parity.ODD, m.get(Direction.RIGHT).get(Parity.EVEN)); m.get(Direction.LEFT).put(Parity.ODD, m.get(Direction.BOTTOM).get(Parity.EVEN)); m.get(Direction.RIGHT).put(Parity.ODD, m.get(Direction.TOP).get(Parity.EVEN)); } /** * Returns the adjacent hash in given {@link Direction}. Based on * https://github.com/davetroy/geohash-js/blob/master/geohash.js. This * method is an improvement on the original js method because it works at * borders too (at the poles and the -180,180 longitude boundaries). * * @param hash * @param direction * @return hash of adjacent hash */ public static String adjacentHash(String hash, Direction direction) { checkHash(hash); Preconditions.checkArgument(hash.length() > 0, "adjacent has no meaning for a zero length hash that covers the whole world"); String adjacentHashAtBorder = adjacentHashAtBorder(hash, direction); if (adjacentHashAtBorder != null) return adjacentHashAtBorder; String source = hash.toLowerCase(); char lastChar = source.charAt(source.length() - 1); Parity parity = (source.length() % 2 == 0) ? Parity.EVEN : Parity.ODD; String base = source.substring(0, source.length() - 1); if (BORDERS.get(direction).get(parity).indexOf(lastChar) != -1) base = adjacentHash(base, direction); return base + BASE32.charAt(NEIGHBOURS.get(direction).get(parity).indexOf(lastChar)); } private static String adjacentHashAtBorder(String hash, Direction direction) { // check if hash is on edge and direction would push us over the edge // if so, wrap round to the other limit for longitude // or if at latitude boundary (a pole) then spin longitude around 180 // degrees. LatLong centre = decodeHash(hash); // if rightmost hash if (Direction.RIGHT.equals(direction)) { if (Math.abs(centre.getLon() + widthDegrees(hash.length()) / 2 - 180) < PRECISION) { return encodeHash(centre.getLat(), -180, hash.length()); } } // if leftmost hash else if (Direction.LEFT.equals(direction)) { if (Math.abs(centre.getLon() - widthDegrees(hash.length()) / 2 + 180) < PRECISION) { return encodeHash(centre.getLat(), 180, hash.length()); } } // if topmost hash else if (Direction.TOP.equals(direction)) { if (Math.abs(centre.getLat() + widthDegrees(hash.length()) / 2 - 90) < PRECISION) { return encodeHash(centre.getLat(), centre.getLon() + 180, hash.length()); } } // if bottommost hash else { if (Math.abs(centre.getLat() - widthDegrees(hash.length()) / 2 + 90) < PRECISION) { return encodeHash(centre.getLat(), centre.getLon() + 180, hash.length()); } } return null; } /** * Throws an {@link IllegalArgumentException} if and only if the hash is * null or blank. * * @param hash * to check */ private static void checkHash(String hash) { Preconditions.checkArgument(hash != null, "hash must be non-null"); } /** * Returns the adjacent hash to the right (east). * * @param hash * to check * @return hash on right of given hash */ public static String right(String hash) { return adjacentHash(hash, Direction.RIGHT); } /** * Returns the adjacent hash to the left (west). * * @param hash * origin * @return hash on left of origin hash */ public static String left(String hash) { return adjacentHash(hash, Direction.LEFT); } /** * Returns the adjacent hash to the top (north). * * @param hash * origin * @return hash above origin hash */ public static String top(String hash) { return adjacentHash(hash, Direction.TOP); } /** * Returns the adjacent hash to the bottom (south). * * @param hash * origin * @return hash below (south) of origin hash */ public static String bottom(String hash) { return adjacentHash(hash, Direction.BOTTOM); } /** * Returns the adjacent hash N steps in the given {@link Direction}. A * negative N will use the opposite {@link Direction}. * * @param hash * origin hash * @param direction * to desired hash * @param steps * number of hashes distance to desired hash * @return hash at position in direction a number of hashes away (steps) */ public static String adjacentHash(String hash, Direction direction, int steps) { if (steps < 0) return adjacentHash(hash, direction.opposite(), Math.abs(steps)); else { String h = hash; for (int i = 0; i < steps; i++) h = adjacentHash(h, direction); return h; } } /** * Returns a list of the 8 surrounding hashes for a given hash in order * left,right,top,bottom,left-top,left-bottom,right-top,right-bottom. * * @param hash * source * @return a list of neighbour hashes */ public static List<String> neighbours(String hash) { List<String> list = new ArrayList<String>(); String left = adjacentHash(hash, Direction.LEFT); String right = adjacentHash(hash, Direction.RIGHT); list.add(left); list.add(right); list.add(adjacentHash(hash, Direction.TOP)); list.add(adjacentHash(hash, Direction.BOTTOM)); list.add(adjacentHash(left, Direction.TOP)); list.add(adjacentHash(left, Direction.BOTTOM)); list.add(adjacentHash(right, Direction.TOP)); list.add(adjacentHash(right, Direction.BOTTOM)); return list; } /** * Returns a geohash of length {@link GeoHash#MAX_HASH_LENGTH} (12) for the * given WGS84 point (latitude,longitude). * * @param latitude * in decimal degrees (WGS84) * @param longitude * in decimal degrees (WGS84) * @return hash at given point of default length */ public static String encodeHash(double latitude, double longitude) { return encodeHash(latitude, longitude, MAX_HASH_LENGTH); } /** * Returns a geohash of given length for the given WGS84 point. * * @param p * point * @param length * length of hash * @return hash at point of given length */ public static String encodeHash(LatLong p, int length) { return encodeHash(p.getLat(), p.getLon(), length); } /** * Returns a geohash of of length {@link GeoHash#MAX_HASH_LENGTH} (12) for * the given WGS84 point. * * @param p * point * @return hash of default length */ public static String encodeHash(LatLong p) { return encodeHash(p.getLat(), p.getLon(), MAX_HASH_LENGTH); } /** * Returns a geohash of given length for the given WGS84 point * (latitude,longitude). If latitude is not between -90 and 90 throws an * {@link IllegalArgumentException}. * * @param latitude * in decimal degrees (WGS84) * @param longitude * in decimal degrees (WGS84) * @param length * length of desired hash * @return geohash of given length for the given point */ // Translated to java from: // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License public static String encodeHash(double latitude, double longitude, int length) { Preconditions.checkArgument(length > 0, "length must be greater than zero"); Preconditions.checkArgument(latitude >= -90 && latitude <= 90, "latitude must be between -90 and 90 inclusive"); longitude = Position.to180(longitude); return fromLongToString(encodeHashToLong(latitude, longitude, length)); } /** * Takes a hash represented as a long and returns it as a string. * * @param hash * the hash, with the length encoded in the 4 least significant * bits * @return the string encoded geohash */ static String fromLongToString(long hash) { int length = (int) (hash & 0xf); if (length > 12 || length < 1) throw new IllegalArgumentException("invalid long geohash " + hash); char[] geohash = new char[length]; for (int pos = 0; pos < length; pos++) { geohash[pos] = BASE32.charAt(((int) (hash >>> 59))); hash <<= 5; } return new String(geohash); } static long encodeHashToLong(double latitude, double longitude, int length) { boolean isEven = true; double minLat = -90.0, maxLat = 90; double minLon = -180.0, maxLon = 180.0; long bit = 0x8000000000000000L; long g = 0; long target = 0x8000000000000000L >>> (5 * length); while (bit != target) { if (isEven) { double mid = (minLon + maxLon) / 2; if (longitude >= mid) { g |= bit; minLon = mid; } else maxLon = mid; } else { double mid = (minLat + maxLat) / 2; if (latitude >= mid) { g |= bit; minLat = mid; } else maxLat = mid; } isEven = !isEven; bit >>>= 1; } return g |= length; } /** * Returns a latitude,longitude pair as the centre of the given geohash. * Latitude will be between -90 and 90 and longitude between -180 and 180. * * @param geohash * @return lat long point */ // Translated to java from: // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License public static LatLong decodeHash(String geohash) { Preconditions.checkNotNull(geohash, "geohash cannot be null"); boolean isEven = true; double[] lat = new double[2]; double[] lon = new double[2]; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; for (int i = 0; i < geohash.length(); i++) { char c = geohash.charAt(i); int cd = BASE32.indexOf(c); for (int j = 0; j < 5; j++) { int mask = BITS[j]; if (isEven) { refineInterval(lon, cd, mask); } else { refineInterval(lat, cd, mask); } isEven = !isEven; } } double resultLat = (lat[0] + lat[1]) / 2; double resultLon = (lon[0] + lon[1]) / 2; return new LatLong(resultLat, resultLon); } /** * Refines interval by a factor or 2 in either the 0 or 1 ordinate. * * @param interval * two entry array of double values * @param cd * used with mask * @param mask * used with cd */ private static void refineInterval(double[] interval, int cd, int mask) { if ((cd & mask) != 0) interval[0] = (interval[0] + interval[1]) / 2; else interval[1] = (interval[0] + interval[1]) / 2; } /** * Returns the maximum length of hash that covers the bounding box. If no * hash can enclose the bounding box then 0 is returned. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @return */ public static int hashLengthToCoverBoundingBox(double topLeftLat, double topLeftLon, double bottomRightLat, double bottomRightLon) { boolean isEven = true; double minLat = -90.0, maxLat = 90; double minLon = -180.0, maxLon = 180.0; for (int bits = 0; bits < MAX_HASH_LENGTH * 5; bits++) { if (isEven) { double mid = (minLon + maxLon) / 2; if (topLeftLon >= mid) { if (bottomRightLon < mid) return bits / 5; minLon = mid; } else { if (bottomRightLon >= mid) return bits / 5; maxLon = mid; } } else { double mid = (minLat + maxLat) / 2; if (topLeftLat >= mid) { if (bottomRightLat < mid) return bits / 5; minLat = mid; } else { if (bottomRightLat >= mid) return bits / 5; maxLat = mid; } } isEven = !isEven; } return MAX_HASH_LENGTH; } /** * Returns true if and only if the bounding box corresponding to the hash * contains the given lat and long. * * @param hash * @param lat * @param lon * @return */ public static boolean hashContains(String hash, double lat, double lon) { LatLong centre = decodeHash(hash); return Math.abs(centre.getLat() - lat) <= heightDegrees(hash.length()) / 2 && Math.abs(to180(centre.getLon() - lon)) <= widthDegrees(hash.length()) / 2; } /** * Returns the result of coverBoundingBoxMaxHashes with a maxHashes value of * {@link GeoHash}.DEFAULT_MAX_HASHES. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @return */ public static Coverage coverBoundingBox(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon) { return coverBoundingBoxMaxHashes(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, DEFAULT_MAX_HASHES); } /** * Returns the hashes that are required to cover the given bounding box. The * maximum length of hash is selected that satisfies the number of hashes * returned is less than <code>maxHashes</code>. Returns null if hashes * cannot be found satisfying that condition. Maximum hash length returned * will be {@link GeoHash}.MAX_HASH_LENGTH. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @param maxHashes * @return */ public static Coverage coverBoundingBoxMaxHashes(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon, int maxHashes) { CoverageLongs coverage = null; int startLength = hashLengthToCoverBoundingBox(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon); if (startLength == 0) startLength = 1; for (int length = startLength; length <= MAX_HASH_LENGTH; length++) { CoverageLongs c = coverBoundingBoxLongs(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, length); if (c.getCount() > maxHashes) return coverage == null ? null : new Coverage(coverage); else coverage = c; } // note coverage can never be null return new Coverage(coverage); } /** * Returns the hashes of given length that are required to cover the given * bounding box. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @param length * @return */ public static Coverage coverBoundingBox(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon, final int length) { return new Coverage(coverBoundingBoxLongs(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, length)); } private static class LongSet { int count = 0; private int cap = 16; long[] array = new long[cap]; void add(long l) { for (int i = 0; i < count; i++) if (array[i] == l) return; if (count == cap) { long[] newArray = new long[cap *= 2]; System.arraycopy(array, 0, newArray, 0, count); array = newArray; } array[count++] = l; } } static CoverageLongs coverBoundingBoxLongs(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon, final int length) { Preconditions.checkArgument(topLeftLat >= bottomRightLat, "topLeftLat must be >= bottomRighLat"); Preconditions.checkArgument(topLeftLon <= bottomRightLon, "topLeftLon must be <= bottomRighLon"); Preconditions.checkArgument(length > 0, "length must be greater than zero"); final double actualWidthDegreesPerHash = widthDegrees(length); final double actualHeightDegreesPerHash = heightDegrees(length); LongSet hashes = new LongSet(); double diff = Position.longitudeDiff(bottomRightLon, topLeftLon); double maxLon = topLeftLon + diff; for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { hashes.add(encodeHashToLong(lat, lon, length)); } } // ensure have the borders covered for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { hashes.add(encodeHashToLong(lat, maxLon, length)); } for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { hashes.add(encodeHashToLong(topLeftLat, lon, length)); } // ensure that the topRight corner is covered hashes.add(encodeHashToLong(topLeftLat, maxLon, length)); double areaDegrees = diff * (topLeftLat - bottomRightLat); double coverageAreaDegrees = hashes.count * widthDegrees(length) * heightDegrees(length); double ratio = coverageAreaDegrees / areaDegrees; return new CoverageLongs(hashes.array, hashes.count, ratio); } /** * Returns height in degrees of all geohashes of length n. Results are * deterministic and cached to increase performance. * * @param n * @return */ public static double heightDegrees(int n) { if (n > MAX_HASH_LENGTH) return calculateHeightDegrees(n); else return HashHeights.values[n]; } private static final class HashHeights { static final double[] values = createValues(); private static double[] createValues() { double d[] = new double[MAX_HASH_LENGTH + 1]; for (int i = 0; i <= MAX_HASH_LENGTH; i++) { d[i] = calculateHeightDegrees(i); } return d; } } /** * Returns the height in degrees of the region represented by a geohash of * length n. * * @param n * @return */ private static double calculateHeightDegrees(int n) { double a; if (n % 2 == 0) a = 0; else a = -0.5; double result = 180 / Math.pow(2, 2.5 * n + a); return result; } private static final class HashWidths { static final double[] values = createValues(); private static double[] createValues() { double d[] = new double[MAX_HASH_LENGTH + 1]; for (int i = 0; i <= MAX_HASH_LENGTH; i++) { d[i] = calculateWidthDegrees(i); } return d; } } /** * Returns width in degrees of all geohashes of length n. Results are * deterministic and cached to increase performance (might be unnecessary, * have not benchmarked). * * @param n * @return */ public static double widthDegrees(int n) { if (n > MAX_HASH_LENGTH) return calculateWidthDegrees(n); else return HashWidths.values[n]; } /** * Returns the width in degrees of the region represented by a geohash of * length n. * * @param n * @return */ private static double calculateWidthDegrees(int n) { double a; if (n % 2 == 0) a = -1; else a = -0.5; double result = 180 / Math.pow(2, 2.5 * n + a); return result; } /** * <p> * Returns a String of lines of hashes to represent the relative positions * of hashes on a map. The grid is of height and width 2*size centred around * the given hash. Highlighted hashes are displayed in upper case. For * example, gridToString("dr",1,Collections.<String>emptySet()) returns: * </p> * * <pre> * f0 f2 f8 * dp dr dx * dn dq dw * </pre> * * @param hash * @param size * @param highlightThese * @return */ public static String gridAsString(String hash, int size, Set<String> highlightThese) { return gridAsString(hash, -size, -size, size, size, highlightThese); } /** * Returns a String of lines of hashes to represent the relative positions * of hashes on a map. * * @param hash * @param fromRight * top left of the grid in hashes to the right (can be negative). * @param fromBottom * top left of the grid in hashes to the bottom (can be * negative). * @param toRight * bottom righth of the grid in hashes to the bottom (can be * negative). * @param toBottom * bottom right of the grid in hashes to the bottom (can be * negative). * @return */ public static String gridAsString(String hash, int fromRight, int fromBottom, int toRight, int toBottom) { return gridAsString(hash, fromRight, fromBottom, toRight, toBottom, Collections.<String> emptySet()); } /** * Returns a String of lines of hashes to represent the relative positions * of hashes on a map. Highlighted hashes are displayed in upper case. For * example, gridToString("dr",-1,-1,1,1,Sets.newHashSet("f2","f8")) returns: * </p> * * <pre> * f0 F2 F8 * dp dr dx * dn dq dw * </pre> * * @param hash * @param fromRight * top left of the grid in hashes to the right (can be negative). * @param fromBottom * top left of the grid in hashes to the bottom (can be * negative). * @param toRight * bottom righth of the grid in hashes to the bottom (can be * negative). * @param toBottom * bottom right of the grid in hashes to the bottom (can be * negative). * @param highlightThese * @return */ public static String gridAsString(String hash, int fromRight, int fromBottom, int toRight, int toBottom, Set<String> highlightThese) { StringBuilder s = new StringBuilder(); for (int bottom = fromBottom; bottom <= toBottom; bottom++) { for (int right = fromRight; right <= toRight; right++) { String h = adjacentHash(hash, Direction.RIGHT, right); h = adjacentHash(h, Direction.BOTTOM, bottom); if (highlightThese.contains(h)) h = h.toUpperCase(); s.append(h).append(" "); } s.append("\n"); } return s.toString(); } }
src/main/java/com/github/davidmoten/geo/GeoHash.java
package com.github.davidmoten.geo; import static com.github.davidmoten.grumpy.core.Position.to180; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.github.davidmoten.geo.util.Preconditions; import com.github.davidmoten.grumpy.core.Position; /** * <p> * Utility functions for <a * href="http://en.wikipedia.org/wiki/Geohash">geohashing</a>. * </p> * * @author dave * */ public final class GeoHash { private static final double PRECISION = 0.000000000001; /** * The standard practical maximum length for geohashes. */ public static final int MAX_HASH_LENGTH = 12; /** * Default maximum number of hashes for covering a bounding box. */ public static final int DEFAULT_MAX_HASHES = 12; /** * Powers of 2 from 32 down to 1. */ private static final int[] BITS = new int[] { 16, 8, 4, 2, 1 }; /** * The characters used in base 32 representations. */ private static final String BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"; /** * Utility lookup for neighbouring hashes. */ private static final Map<Direction, Map<Parity, String>> NEIGHBOURS = createNeighbours(); /** * Utility lookup for hash borders. */ private static final Map<Direction, Map<Parity, String>> BORDERS = createBorders(); /** * Private constructor. */ private GeoHash() { // prevent instantiation } /** * Returns a map to be used in hash border calculations. * * @return map of borders */ private static Map<Direction, Map<Parity, String>> createBorders() { Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); m.get(Direction.RIGHT).put(Parity.EVEN, "bcfguvyz"); m.get(Direction.LEFT).put(Parity.EVEN, "0145hjnp"); m.get(Direction.TOP).put(Parity.EVEN, "prxz"); m.get(Direction.BOTTOM).put(Parity.EVEN, "028b"); addOddParityEntries(m); return m; } /** * Returns a map to be used in adjacent hash calculations. * * @return map */ private static Map<Direction, Map<Parity, String>> createNeighbours() { Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); m.get(Direction.RIGHT).put(Parity.EVEN, "bc01fg45238967deuvhjyznpkmstqrwx"); m.get(Direction.LEFT).put(Parity.EVEN, "238967debc01fg45kmstqrwxuvhjyznp"); m.get(Direction.TOP).put(Parity.EVEN, "p0r21436x8zb9dcf5h7kjnmqesgutwvy"); m.get(Direction.BOTTOM).put(Parity.EVEN, "14365h7k9dcfesgujnmqp0r2twvyx8zb"); addOddParityEntries(m); return m; } /** * Create a direction and parity map for use in adjacent hash calculations. * * @return map */ private static Map<Direction, Map<Parity, String>> createDirectionParityMap() { Map<Direction, Map<Parity, String>> m = newHashMap(); m.put(Direction.BOTTOM, GeoHash.<Parity, String> newHashMap()); m.put(Direction.TOP, GeoHash.<Parity, String> newHashMap()); m.put(Direction.LEFT, GeoHash.<Parity, String> newHashMap()); m.put(Direction.RIGHT, GeoHash.<Parity, String> newHashMap()); return m; } private static <T, D> Map<T, D> newHashMap() { return new HashMap<T, D>(); } /** * Puts odd parity entries in the map m based purely on the even entries. * * @param m * map */ private static void addOddParityEntries( Map<Direction, Map<Parity, String>> m) { m.get(Direction.BOTTOM).put(Parity.ODD, m.get(Direction.LEFT).get(Parity.EVEN)); m.get(Direction.TOP).put(Parity.ODD, m.get(Direction.RIGHT).get(Parity.EVEN)); m.get(Direction.LEFT).put(Parity.ODD, m.get(Direction.BOTTOM).get(Parity.EVEN)); m.get(Direction.RIGHT).put(Parity.ODD, m.get(Direction.TOP).get(Parity.EVEN)); } /** * Returns the adjacent hash in given {@link Direction}. Based on * https://github.com/davetroy/geohash-js/blob/master/geohash.js. This * method is an improvement on the original js method because it works at * borders too (at the poles and the -180,180 longitude boundaries). * * @param hash * @param direction * @return hash of adjacent hash */ public static String adjacentHash(String hash, Direction direction) { checkHash(hash); Preconditions .checkArgument(hash.length() > 0, "adjacent has no meaning for a zero length hash that covers the whole world"); String adjacentHashAtBorder = adjacentHashAtBorder(hash, direction); if (adjacentHashAtBorder != null) return adjacentHashAtBorder; String source = hash.toLowerCase(); char lastChar = source.charAt(source.length() - 1); Parity parity = (source.length() % 2 == 0) ? Parity.EVEN : Parity.ODD; String base = source.substring(0, source.length() - 1); if (BORDERS.get(direction).get(parity).indexOf(lastChar) != -1) base = adjacentHash(base, direction); return base + BASE32.charAt(NEIGHBOURS.get(direction).get(parity) .indexOf(lastChar)); } private static String adjacentHashAtBorder(String hash, Direction direction) { // check if hash is on edge and direction would push us over the edge // if so, wrap round to the other limit for longitude // or if at latitude boundary (a pole) then spin longitude around 180 // degrees. LatLong centre = decodeHash(hash); // if rightmost hash if (Direction.RIGHT.equals(direction)) { if (Math.abs(centre.getLon() + widthDegrees(hash.length()) / 2 - 180) < PRECISION) { return encodeHash(centre.getLat(), -180, hash.length()); } } // if leftmost hash else if (Direction.LEFT.equals(direction)) { if (Math.abs(centre.getLon() - widthDegrees(hash.length()) / 2 + 180) < PRECISION) { return encodeHash(centre.getLat(), 180, hash.length()); } } // if topmost hash else if (Direction.TOP.equals(direction)) { if (Math.abs(centre.getLat() + widthDegrees(hash.length()) / 2 - 90) < PRECISION) { return encodeHash(centre.getLat(), centre.getLon() + 180, hash.length()); } } // if bottommost hash else { if (Math.abs(centre.getLat() - widthDegrees(hash.length()) / 2 + 90) < PRECISION) { return encodeHash(centre.getLat(), centre.getLon() + 180, hash.length()); } } return null; } /** * Throws an {@link IllegalArgumentException} if and only if the hash is * null or blank. * * @param hash * to check */ private static void checkHash(String hash) { Preconditions.checkArgument(hash != null, "hash must be non-null"); } /** * Returns the adjacent hash to the right (east). * * @param hash * to check * @return hash on right of given hash */ public static String right(String hash) { return adjacentHash(hash, Direction.RIGHT); } /** * Returns the adjacent hash to the left (west). * * @param hash * origin * @return hash on left of origin hash */ public static String left(String hash) { return adjacentHash(hash, Direction.LEFT); } /** * Returns the adjacent hash to the top (north). * * @param hash * origin * @return hash above origin hash */ public static String top(String hash) { return adjacentHash(hash, Direction.TOP); } /** * Returns the adjacent hash to the bottom (south). * * @param hash * origin * @return hash below (south) of origin hash */ public static String bottom(String hash) { return adjacentHash(hash, Direction.BOTTOM); } /** * Returns the adjacent hash N steps in the given {@link Direction}. A * negative N will use the opposite {@link Direction}. * * @param hash * origin hash * @param direction * to desired hash * @param steps * number of hashes distance to desired hash * @return hash at position in direction a number of hashes away (steps) */ public static String adjacentHash(String hash, Direction direction, int steps) { if (steps < 0) return adjacentHash(hash, direction.opposite(), Math.abs(steps)); else { String h = hash; for (int i = 0; i < steps; i++) h = adjacentHash(h, direction); return h; } } /** * Returns a list of the 8 surrounding hashes for a given hash in order * left,right,top,bottom,left-top,left-bottom,right-top,right-bottom. * * @param hash * source * @return a list of neighbour hashes */ public static List<String> neighbours(String hash) { List<String> list = new ArrayList<String>(); String left = adjacentHash(hash, Direction.LEFT); String right = adjacentHash(hash, Direction.RIGHT); list.add(left); list.add(right); list.add(adjacentHash(hash, Direction.TOP)); list.add(adjacentHash(hash, Direction.BOTTOM)); list.add(adjacentHash(left, Direction.TOP)); list.add(adjacentHash(left, Direction.BOTTOM)); list.add(adjacentHash(right, Direction.TOP)); list.add(adjacentHash(right, Direction.BOTTOM)); return list; } /** * Returns a geohash of length {@link GeoHash#MAX_HASH_LENGTH} (12) for the * given WGS84 point (latitude,longitude). * * @param latitude * in decimal degrees (WGS84) * @param longitude * in decimal degrees (WGS84) * @return hash at given point of default length */ public static String encodeHash(double latitude, double longitude) { return encodeHash(latitude, longitude, MAX_HASH_LENGTH); } /** * Returns a geohash of given length for the given WGS84 point. * * @param p * point * @param length * length of hash * @return hash at point of given length */ public static String encodeHash(LatLong p, int length) { return encodeHash(p.getLat(), p.getLon(), length); } /** * Returns a geohash of of length {@link GeoHash#MAX_HASH_LENGTH} (12) for * the given WGS84 point. * * @param p * point * @return hash of default length */ public static String encodeHash(LatLong p) { return encodeHash(p.getLat(), p.getLon(), MAX_HASH_LENGTH); } /** * Returns a geohash of given length for the given WGS84 point * (latitude,longitude). If latitude is not between -90 and 90 throws an * {@link IllegalArgumentException}. * * @param latitude * in decimal degrees (WGS84) * @param longitude * in decimal degrees (WGS84) * @param length * length of desired hash * @return geohash of given length for the given point */ // Translated to java from: // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License public static String encodeHash(double latitude, double longitude, int length) { Preconditions.checkArgument(length > 0, "length must be greater than zero"); Preconditions.checkArgument(latitude >= -90 && latitude <= 90, "latitude must be between -90 and 90 inclusive"); longitude = Position.to180(longitude); return fromLongToString(encodeHashToLong(latitude, longitude, length)); } /** Takes a hash represented as a long and returns it as a string. * * @param hash the hash, with the length encoded in the 4 least significant bits * @return the string encoded geohash */ static String fromLongToString(long hash) { int length = (int)(hash & 0xf); if(length > 12 || length < 1) throw new IllegalArgumentException("invalid long geohash " + hash); char[] geohash = new char[length]; for(int pos = 0 ; pos < length ; pos++) { geohash[pos] = BASE32.charAt(((int)(hash >>> 59))); hash <<= 5; } return new String(geohash); } static long encodeHashToLong(double latitude, double longitude, int length) { boolean isEven = true; double minLat = -90.0, maxLat = 90; double minLon = -180.0, maxLon = 180.0; long bit = 0x8000000000000000L; long g = 0; long target = 0x8000000000000000L >>> (5 * length); while (bit != target) { if (isEven) { double mid = (minLon + maxLon) / 2; if (longitude >= mid) { g |= bit; minLon = mid; } else maxLon = mid; } else { double mid = (minLat + maxLat) / 2; if (latitude >= mid) { g |= bit; minLat = mid; } else maxLat = mid; } isEven = !isEven; bit >>>= 1; } return g |= length; } /** * Returns a latitude,longitude pair as the centre of the given geohash. * Latitude will be between -90 and 90 and longitude between -180 and 180. * * @param geohash * @return lat long point */ // Translated to java from: // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License public static LatLong decodeHash(String geohash) { Preconditions.checkNotNull(geohash, "geohash cannot be null"); boolean isEven = true; double[] lat = new double[2]; double[] lon = new double[2]; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; for (int i = 0; i < geohash.length(); i++) { char c = geohash.charAt(i); int cd = BASE32.indexOf(c); for (int j = 0; j < 5; j++) { int mask = BITS[j]; if (isEven) { refineInterval(lon, cd, mask); } else { refineInterval(lat, cd, mask); } isEven = !isEven; } } double resultLat = (lat[0] + lat[1]) / 2; double resultLon = (lon[0] + lon[1]) / 2; return new LatLong(resultLat, resultLon); } /** * Refines interval by a factor or 2 in either the 0 or 1 ordinate. * * @param interval * two entry array of double values * @param cd * used with mask * @param mask * used with cd */ private static void refineInterval(double[] interval, int cd, int mask) { if ((cd & mask) != 0) interval[0] = (interval[0] + interval[1]) / 2; else interval[1] = (interval[0] + interval[1]) / 2; } /** * Returns the maximum length of hash that covers the bounding box. If no * hash can enclose the bounding box then 0 is returned. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @return */ public static int hashLengthToCoverBoundingBox(double topLeftLat, double topLeftLon, double bottomRightLat, double bottomRightLon) { boolean isEven = true; double minLat = -90.0, maxLat = 90; double minLon = -180.0, maxLon = 180.0; for(int bits = 0 ; bits < MAX_HASH_LENGTH * 5 ; bits++) { if (isEven) { double mid = (minLon + maxLon) / 2; if(topLeftLon >= mid) { if(bottomRightLon < mid) return bits / 5; minLon = mid; } else { if(bottomRightLon >= mid) return bits / 5; maxLon = mid; } } else { double mid = (minLat + maxLat) / 2; if(topLeftLat >= mid) { if(bottomRightLat < mid) return bits / 5; minLat = mid; } else { if(bottomRightLat >= mid) return bits / 5; maxLat = mid; } } isEven = !isEven; } return MAX_HASH_LENGTH; } /** * Returns true if and only if the bounding box corresponding to the hash * contains the given lat and long. * * @param hash * @param lat * @param lon * @return */ public static boolean hashContains(String hash, double lat, double lon) { LatLong centre = decodeHash(hash); return Math.abs(centre.getLat() - lat) <= heightDegrees(hash.length()) / 2 && Math.abs(to180(centre.getLon() - lon)) <= widthDegrees(hash .length()) / 2; } /** * Returns the result of coverBoundingBoxMaxHashes with a maxHashes value of * {@link GeoHash}.DEFAULT_MAX_HASHES. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @return */ public static Coverage coverBoundingBox(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon) { return coverBoundingBoxMaxHashes(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, DEFAULT_MAX_HASHES); } /** * Returns the hashes that are required to cover the given bounding box. The * maximum length of hash is selected that satisfies the number of hashes * returned is less than <code>maxHashes</code>. Returns null if hashes * cannot be found satisfying that condition. Maximum hash length returned * will be {@link GeoHash}.MAX_HASH_LENGTH. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @param maxHashes * @return */ public static Coverage coverBoundingBoxMaxHashes(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon, int maxHashes) { CoverageLongs coverage = null; int startLength = hashLengthToCoverBoundingBox(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon); if (startLength == 0) startLength = 1; for (int length = startLength; length <= MAX_HASH_LENGTH; length++) { CoverageLongs c = coverBoundingBoxLongs(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, length); if (c.getCount() > maxHashes) return coverage == null ? null : new Coverage(coverage); else coverage = c; } //note coverage can never be null return new Coverage(coverage); } /** * Returns the hashes of given length that are required to cover the given * bounding box. * * @param topLeftLat * @param topLeftLon * @param bottomRightLat * @param bottomRightLon * @param length * @return */ public static Coverage coverBoundingBox(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon, final int length) { return new Coverage(coverBoundingBoxLongs(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, length)); } private static class LongSet { int count = 0; private int cap = 16; long[] array = new long[cap]; void add(long l) { for(int i = 0 ; i < count ; i++) if(array[i] == l) return; if(count == cap) { long[] newArray = new long[cap*=2]; System.arraycopy(array, 0, newArray, 0, count); array = newArray; } array[count++] = l; } } static CoverageLongs coverBoundingBoxLongs(double topLeftLat, final double topLeftLon, final double bottomRightLat, final double bottomRightLon, final int length) { Preconditions.checkArgument(topLeftLat>=bottomRightLat,"topLeftLat must be >= bottomRighLat"); Preconditions.checkArgument(topLeftLon<=bottomRightLon,"topLeftLon must be <= bottomRighLon"); Preconditions.checkArgument(length > 0, "length must be greater than zero"); final double actualWidthDegreesPerHash = widthDegrees(length); final double actualHeightDegreesPerHash = heightDegrees(length); LongSet hashes = new LongSet(); double diff = Position.longitudeDiff(bottomRightLon, topLeftLon); double maxLon = topLeftLon + diff; for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { hashes.add(encodeHashToLong(lat, lon, length)); } } // ensure have the borders covered for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { hashes.add(encodeHashToLong(lat, maxLon, length)); } for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { hashes.add(encodeHashToLong(topLeftLat, lon, length)); } // ensure that the topRight corner is covered hashes.add(encodeHashToLong(topLeftLat, maxLon, length)); double areaDegrees = diff * (topLeftLat - bottomRightLat); double coverageAreaDegrees = hashes.count * widthDegrees(length) * heightDegrees(length); double ratio = coverageAreaDegrees / areaDegrees; return new CoverageLongs(hashes.array, hashes.count, ratio); } /** * Array to cache hash height calculations. */ private static Double[] hashHeightCache = new Double[MAX_HASH_LENGTH]; /** * Returns height in degrees of all geohashes of length n. Results are * deterministic and cached to increase performance. * * @param n * @return */ public synchronized static double heightDegrees(int n) { if (n > 0 && n <= MAX_HASH_LENGTH) { if (hashHeightCache[n - 1] == null) hashHeightCache[n - 1] = calculateHeightDegrees(n); return hashHeightCache[n - 1]; } else return calculateHeightDegrees(n); } /** * Returns the height in degrees of the region represented by a geohash of * length n. * * @param n * @return */ private static double calculateHeightDegrees(int n) { double a; if (n % 2 == 0) a = 0; else a = -0.5; double result = 180 / Math.pow(2, 2.5 * n + a); return result; } /** * Array to cache hash width calculations. */ private static Double[] hashWidthCache = new Double[MAX_HASH_LENGTH]; /** * Returns width in degrees of all geohashes of length n. Results are * deterministic and cached to increase performance (might be unnecessary, * have not benchmarked). * * @param n * @return */ public synchronized static double widthDegrees(int n) { if (n > 0 && n <= MAX_HASH_LENGTH) { if (hashWidthCache[n - 1] == null) { hashWidthCache[n - 1] = calculateWidthDegrees(n); } return hashWidthCache[n - 1]; } else return calculateWidthDegrees(n); } /** * Returns the width in degrees of the region represented by a geohash of * length n. * * @param n * @return */ private static double calculateWidthDegrees(int n) { double a; if (n % 2 == 0) a = -1; else a = -0.5; double result = 180 / Math.pow(2, 2.5 * n + a); return result; } /** * <p> * Returns a String of lines of hashes to represent the relative positions * of hashes on a map. The grid is of height and width 2*size centred around * the given hash. Highlighted hashes are displayed in upper case. For * example, gridToString("dr",1,Collections.<String>emptySet()) returns: * </p> * * <pre> * f0 f2 f8 * dp dr dx * dn dq dw * </pre> * * @param hash * @param size * @param highlightThese * @return */ public static String gridAsString(String hash, int size, Set<String> highlightThese) { return gridAsString(hash, -size, -size, size, size, highlightThese); } /** * Returns a String of lines of hashes to represent the relative positions * of hashes on a map. * * @param hash * @param fromRight * top left of the grid in hashes to the right (can be negative). * @param fromBottom * top left of the grid in hashes to the bottom (can be * negative). * @param toRight * bottom righth of the grid in hashes to the bottom (can be * negative). * @param toBottom * bottom right of the grid in hashes to the bottom (can be * negative). * @return */ public static String gridAsString(String hash, int fromRight, int fromBottom, int toRight, int toBottom) { return gridAsString(hash, fromRight, fromBottom, toRight, toBottom, Collections.<String> emptySet()); } /** * Returns a String of lines of hashes to represent the relative positions * of hashes on a map. Highlighted hashes are displayed in upper case. For * example, gridToString("dr",-1,-1,1,1,Sets.newHashSet("f2","f8")) returns: * </p> * * <pre> * f0 F2 F8 * dp dr dx * dn dq dw * </pre> * * @param hash * @param fromRight * top left of the grid in hashes to the right (can be negative). * @param fromBottom * top left of the grid in hashes to the bottom (can be * negative). * @param toRight * bottom righth of the grid in hashes to the bottom (can be * negative). * @param toBottom * bottom right of the grid in hashes to the bottom (can be * negative). * @param highlightThese * @return */ public static String gridAsString(String hash, int fromRight, int fromBottom, int toRight, int toBottom, Set<String> highlightThese) { StringBuilder s = new StringBuilder(); for (int bottom = fromBottom; bottom <= toBottom; bottom++) { for (int right = fromRight; right <= toRight; right++) { String h = adjacentHash(hash, Direction.RIGHT, right); h = adjacentHash(h, Direction.BOTTOM, bottom); if (highlightThese.contains(h)) h = h.toUpperCase(); s.append(h).append(" "); } s.append("\n"); } return s.toString(); } }
issue #19, remove synchronized keyword and use static holder pattern for singleton creation of height and width values
src/main/java/com/github/davidmoten/geo/GeoHash.java
issue #19, remove synchronized keyword and use static holder pattern for singleton creation of height and width values
<ide><path>rc/main/java/com/github/davidmoten/geo/GeoHash.java <ide> <ide> /** <ide> * <p> <del> * Utility functions for <a <del> * href="http://en.wikipedia.org/wiki/Geohash">geohashing</a>. <add> * Utility functions for <add> * <a href="http://en.wikipedia.org/wiki/Geohash">geohashing</a>. <ide> * </p> <ide> * <ide> * @author dave <ide> */ <ide> public final class GeoHash { <ide> <del> private static final double PRECISION = 0.000000000001; <del> <del> /** <del> * The standard practical maximum length for geohashes. <del> */ <del> public static final int MAX_HASH_LENGTH = 12; <del> <del> /** <del> * Default maximum number of hashes for covering a bounding box. <del> */ <del> public static final int DEFAULT_MAX_HASHES = 12; <del> <del> /** <del> * Powers of 2 from 32 down to 1. <del> */ <del> private static final int[] BITS = new int[] { 16, 8, 4, 2, 1 }; <del> <del> /** <del> * The characters used in base 32 representations. <del> */ <del> private static final String BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"; <del> <del> /** <del> * Utility lookup for neighbouring hashes. <del> */ <del> private static final Map<Direction, Map<Parity, String>> NEIGHBOURS = createNeighbours(); <del> <del> /** <del> * Utility lookup for hash borders. <del> */ <del> private static final Map<Direction, Map<Parity, String>> BORDERS = createBorders(); <del> <del> /** <del> * Private constructor. <del> */ <del> private GeoHash() { <del> // prevent instantiation <del> } <del> <del> /** <del> * Returns a map to be used in hash border calculations. <del> * <del> * @return map of borders <del> */ <del> private static Map<Direction, Map<Parity, String>> createBorders() { <del> Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); <del> <del> m.get(Direction.RIGHT).put(Parity.EVEN, "bcfguvyz"); <del> m.get(Direction.LEFT).put(Parity.EVEN, "0145hjnp"); <del> m.get(Direction.TOP).put(Parity.EVEN, "prxz"); <del> m.get(Direction.BOTTOM).put(Parity.EVEN, "028b"); <del> <del> addOddParityEntries(m); <del> return m; <del> } <del> <del> /** <del> * Returns a map to be used in adjacent hash calculations. <del> * <del> * @return map <del> */ <del> private static Map<Direction, Map<Parity, String>> createNeighbours() { <del> Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); <del> <del> m.get(Direction.RIGHT).put(Parity.EVEN, <del> "bc01fg45238967deuvhjyznpkmstqrwx"); <del> m.get(Direction.LEFT).put(Parity.EVEN, <del> "238967debc01fg45kmstqrwxuvhjyznp"); <del> m.get(Direction.TOP).put(Parity.EVEN, <del> "p0r21436x8zb9dcf5h7kjnmqesgutwvy"); <del> m.get(Direction.BOTTOM).put(Parity.EVEN, <del> "14365h7k9dcfesgujnmqp0r2twvyx8zb"); <del> addOddParityEntries(m); <del> <del> return m; <del> } <del> <del> /** <del> * Create a direction and parity map for use in adjacent hash calculations. <del> * <del> * @return map <del> */ <del> private static Map<Direction, Map<Parity, String>> createDirectionParityMap() { <del> Map<Direction, Map<Parity, String>> m = newHashMap(); <del> m.put(Direction.BOTTOM, GeoHash.<Parity, String> newHashMap()); <del> m.put(Direction.TOP, GeoHash.<Parity, String> newHashMap()); <del> m.put(Direction.LEFT, GeoHash.<Parity, String> newHashMap()); <del> m.put(Direction.RIGHT, GeoHash.<Parity, String> newHashMap()); <del> return m; <del> } <del> <del> private static <T, D> Map<T, D> newHashMap() { <del> return new HashMap<T, D>(); <del> } <del> <del> /** <del> * Puts odd parity entries in the map m based purely on the even entries. <del> * <del> * @param m <del> * map <del> */ <del> private static void addOddParityEntries( <del> Map<Direction, Map<Parity, String>> m) { <del> m.get(Direction.BOTTOM).put(Parity.ODD, <del> m.get(Direction.LEFT).get(Parity.EVEN)); <del> m.get(Direction.TOP).put(Parity.ODD, <del> m.get(Direction.RIGHT).get(Parity.EVEN)); <del> m.get(Direction.LEFT).put(Parity.ODD, <del> m.get(Direction.BOTTOM).get(Parity.EVEN)); <del> m.get(Direction.RIGHT).put(Parity.ODD, <del> m.get(Direction.TOP).get(Parity.EVEN)); <del> } <del> <del> /** <del> * Returns the adjacent hash in given {@link Direction}. Based on <del> * https://github.com/davetroy/geohash-js/blob/master/geohash.js. This <del> * method is an improvement on the original js method because it works at <del> * borders too (at the poles and the -180,180 longitude boundaries). <del> * <del> * @param hash <del> * @param direction <del> * @return hash of adjacent hash <del> */ <del> public static String adjacentHash(String hash, Direction direction) { <del> checkHash(hash); <del> Preconditions <del> .checkArgument(hash.length() > 0, <del> "adjacent has no meaning for a zero length hash that covers the whole world"); <del> <del> String adjacentHashAtBorder = adjacentHashAtBorder(hash, direction); <del> if (adjacentHashAtBorder != null) <del> return adjacentHashAtBorder; <del> <del> String source = hash.toLowerCase(); <del> char lastChar = source.charAt(source.length() - 1); <del> Parity parity = (source.length() % 2 == 0) ? Parity.EVEN : Parity.ODD; <del> String base = source.substring(0, source.length() - 1); <del> if (BORDERS.get(direction).get(parity).indexOf(lastChar) != -1) <del> base = adjacentHash(base, direction); <del> return base <del> + BASE32.charAt(NEIGHBOURS.get(direction).get(parity) <del> .indexOf(lastChar)); <del> } <del> <del> private static String adjacentHashAtBorder(String hash, Direction direction) { <del> // check if hash is on edge and direction would push us over the edge <del> // if so, wrap round to the other limit for longitude <del> // or if at latitude boundary (a pole) then spin longitude around 180 <del> // degrees. <del> LatLong centre = decodeHash(hash); <del> <del> // if rightmost hash <del> if (Direction.RIGHT.equals(direction)) { <del> if (Math.abs(centre.getLon() + widthDegrees(hash.length()) / 2 <del> - 180) < PRECISION) { <del> return encodeHash(centre.getLat(), -180, hash.length()); <del> } <del> } <del> // if leftmost hash <del> else if (Direction.LEFT.equals(direction)) { <del> if (Math.abs(centre.getLon() - widthDegrees(hash.length()) / 2 <del> + 180) < PRECISION) { <del> return encodeHash(centre.getLat(), 180, hash.length()); <del> } <del> } <del> // if topmost hash <del> else if (Direction.TOP.equals(direction)) { <del> if (Math.abs(centre.getLat() + widthDegrees(hash.length()) / 2 - 90) < PRECISION) { <del> return encodeHash(centre.getLat(), centre.getLon() + 180, <del> hash.length()); <del> } <del> } <del> // if bottommost hash <del> else { <del> if (Math.abs(centre.getLat() - widthDegrees(hash.length()) / 2 + 90) < PRECISION) { <del> return encodeHash(centre.getLat(), centre.getLon() + 180, <del> hash.length()); <del> } <del> } <del> <del> return null; <del> } <del> <del> /** <del> * Throws an {@link IllegalArgumentException} if and only if the hash is <del> * null or blank. <del> * <del> * @param hash <del> * to check <del> */ <del> private static void checkHash(String hash) { <del> Preconditions.checkArgument(hash != null, "hash must be non-null"); <del> } <del> <del> /** <del> * Returns the adjacent hash to the right (east). <del> * <del> * @param hash <del> * to check <del> * @return hash on right of given hash <del> */ <del> public static String right(String hash) { <del> return adjacentHash(hash, Direction.RIGHT); <del> } <del> <del> /** <del> * Returns the adjacent hash to the left (west). <del> * <del> * @param hash <del> * origin <del> * @return hash on left of origin hash <del> */ <del> public static String left(String hash) { <del> return adjacentHash(hash, Direction.LEFT); <del> } <del> <del> /** <del> * Returns the adjacent hash to the top (north). <del> * <del> * @param hash <del> * origin <del> * @return hash above origin hash <del> */ <del> public static String top(String hash) { <del> return adjacentHash(hash, Direction.TOP); <del> } <del> <del> /** <del> * Returns the adjacent hash to the bottom (south). <del> * <del> * @param hash <del> * origin <del> * @return hash below (south) of origin hash <del> */ <del> public static String bottom(String hash) { <del> return adjacentHash(hash, Direction.BOTTOM); <del> } <del> <del> /** <del> * Returns the adjacent hash N steps in the given {@link Direction}. A <del> * negative N will use the opposite {@link Direction}. <del> * <del> * @param hash <del> * origin hash <del> * @param direction <del> * to desired hash <del> * @param steps <del> * number of hashes distance to desired hash <del> * @return hash at position in direction a number of hashes away (steps) <del> */ <del> public static String adjacentHash(String hash, Direction direction, <del> int steps) { <del> if (steps < 0) <del> return adjacentHash(hash, direction.opposite(), Math.abs(steps)); <del> else { <del> String h = hash; <del> for (int i = 0; i < steps; i++) <del> h = adjacentHash(h, direction); <del> return h; <del> } <del> } <del> <del> /** <del> * Returns a list of the 8 surrounding hashes for a given hash in order <del> * left,right,top,bottom,left-top,left-bottom,right-top,right-bottom. <del> * <del> * @param hash <del> * source <del> * @return a list of neighbour hashes <del> */ <del> public static List<String> neighbours(String hash) { <del> List<String> list = new ArrayList<String>(); <del> String left = adjacentHash(hash, Direction.LEFT); <del> String right = adjacentHash(hash, Direction.RIGHT); <del> list.add(left); <del> list.add(right); <del> list.add(adjacentHash(hash, Direction.TOP)); <del> list.add(adjacentHash(hash, Direction.BOTTOM)); <del> list.add(adjacentHash(left, Direction.TOP)); <del> list.add(adjacentHash(left, Direction.BOTTOM)); <del> list.add(adjacentHash(right, Direction.TOP)); <del> list.add(adjacentHash(right, Direction.BOTTOM)); <del> return list; <del> } <del> <del> /** <del> * Returns a geohash of length {@link GeoHash#MAX_HASH_LENGTH} (12) for the <del> * given WGS84 point (latitude,longitude). <del> * <del> * @param latitude <del> * in decimal degrees (WGS84) <del> * @param longitude <del> * in decimal degrees (WGS84) <del> * @return hash at given point of default length <del> */ <del> public static String encodeHash(double latitude, double longitude) { <del> return encodeHash(latitude, longitude, MAX_HASH_LENGTH); <del> } <del> <del> /** <del> * Returns a geohash of given length for the given WGS84 point. <del> * <del> * @param p <del> * point <del> * @param length <del> * length of hash <del> * @return hash at point of given length <del> */ <del> public static String encodeHash(LatLong p, int length) { <del> return encodeHash(p.getLat(), p.getLon(), length); <del> } <del> <del> /** <del> * Returns a geohash of of length {@link GeoHash#MAX_HASH_LENGTH} (12) for <del> * the given WGS84 point. <del> * <del> * @param p <del> * point <del> * @return hash of default length <del> */ <del> public static String encodeHash(LatLong p) { <del> return encodeHash(p.getLat(), p.getLon(), MAX_HASH_LENGTH); <del> } <del> <del> /** <del> * Returns a geohash of given length for the given WGS84 point <del> * (latitude,longitude). If latitude is not between -90 and 90 throws an <del> * {@link IllegalArgumentException}. <del> * <del> * @param latitude <del> * in decimal degrees (WGS84) <del> * @param longitude <del> * in decimal degrees (WGS84) <del> * @param length <del> * length of desired hash <del> * @return geohash of given length for the given point <del> */ <del> // Translated to java from: <del> // geohash.js <del> // Geohash library for Javascript <del> // (c) 2008 David Troy <del> // Distributed under the MIT License <del> public static String encodeHash(double latitude, double longitude, <del> int length) { <del> Preconditions.checkArgument(length > 0, <del> "length must be greater than zero"); <del> Preconditions.checkArgument(latitude >= -90 && latitude <= 90, <del> "latitude must be between -90 and 90 inclusive"); <del> longitude = Position.to180(longitude); <del> <del> return fromLongToString(encodeHashToLong(latitude, longitude, length)); <del> } <del> <del> /** Takes a hash represented as a long and returns it as a string. <del> * <del> * @param hash the hash, with the length encoded in the 4 least significant bits <del> * @return the string encoded geohash <del> */ <del> static String fromLongToString(long hash) { <del> int length = (int)(hash & 0xf); <del> if(length > 12 || length < 1) <del> throw new IllegalArgumentException("invalid long geohash " + hash); <del> char[] geohash = new char[length]; <del> for(int pos = 0 ; pos < length ; pos++) { <del> geohash[pos] = BASE32.charAt(((int)(hash >>> 59))); <del> hash <<= 5; <del> } <del> return new String(geohash); <del> } <del> <del> static long encodeHashToLong(double latitude, double longitude, int length) { <del> boolean isEven = true; <del> double minLat = -90.0, maxLat = 90; <del> double minLon = -180.0, maxLon = 180.0; <del> long bit = 0x8000000000000000L; <del> long g = 0; <del> <del> long target = 0x8000000000000000L >>> (5 * length); <del> while (bit != target) { <del> if (isEven) { <del> double mid = (minLon + maxLon) / 2; <del> if (longitude >= mid) { <del> g |= bit; <del> minLon = mid; <del> } else <del> maxLon = mid; <del> } else { <del> double mid = (minLat + maxLat) / 2; <del> if (latitude >= mid) { <del> g |= bit; <del> minLat = mid; <del> } else <del> maxLat = mid; <del> } <del> <del> isEven = !isEven; <del> bit >>>= 1; <del> } <del> return g |= length; <del> } <del> <del> /** <del> * Returns a latitude,longitude pair as the centre of the given geohash. <del> * Latitude will be between -90 and 90 and longitude between -180 and 180. <del> * <del> * @param geohash <del> * @return lat long point <del> */ <del> // Translated to java from: <del> // geohash.js <del> // Geohash library for Javascript <del> // (c) 2008 David Troy <del> // Distributed under the MIT License <del> public static LatLong decodeHash(String geohash) { <del> Preconditions.checkNotNull(geohash, "geohash cannot be null"); <del> boolean isEven = true; <del> double[] lat = new double[2]; <del> double[] lon = new double[2]; <del> lat[0] = -90.0; <del> lat[1] = 90.0; <del> lon[0] = -180.0; <del> lon[1] = 180.0; <del> <del> for (int i = 0; i < geohash.length(); i++) { <del> char c = geohash.charAt(i); <del> int cd = BASE32.indexOf(c); <del> for (int j = 0; j < 5; j++) { <del> int mask = BITS[j]; <del> if (isEven) { <del> refineInterval(lon, cd, mask); <del> } else { <del> refineInterval(lat, cd, mask); <del> } <del> isEven = !isEven; <del> } <del> } <del> double resultLat = (lat[0] + lat[1]) / 2; <del> double resultLon = (lon[0] + lon[1]) / 2; <del> <del> return new LatLong(resultLat, resultLon); <del> } <del> <del> /** <del> * Refines interval by a factor or 2 in either the 0 or 1 ordinate. <del> * <del> * @param interval <del> * two entry array of double values <del> * @param cd <del> * used with mask <del> * @param mask <del> * used with cd <del> */ <del> private static void refineInterval(double[] interval, int cd, int mask) { <del> if ((cd & mask) != 0) <del> interval[0] = (interval[0] + interval[1]) / 2; <del> else <del> interval[1] = (interval[0] + interval[1]) / 2; <del> } <del> <del> /** <del> * Returns the maximum length of hash that covers the bounding box. If no <del> * hash can enclose the bounding box then 0 is returned. <del> * <del> * @param topLeftLat <del> * @param topLeftLon <del> * @param bottomRightLat <del> * @param bottomRightLon <del> * @return <del> */ <del> public static int hashLengthToCoverBoundingBox(double topLeftLat, <del> double topLeftLon, double bottomRightLat, double bottomRightLon) { <del> boolean isEven = true; <del> double minLat = -90.0, maxLat = 90; <del> double minLon = -180.0, maxLon = 180.0; <del> <del> for(int bits = 0 ; bits < MAX_HASH_LENGTH * 5 ; bits++) <del> { <del> if (isEven) { <del> double mid = (minLon + maxLon) / 2; <del> if(topLeftLon >= mid) { <del> if(bottomRightLon < mid) <del> return bits / 5; <del> minLon = mid; <del> } else { <del> if(bottomRightLon >= mid) <del> return bits / 5; <del> maxLon = mid; <del> } <del> } else { <del> double mid = (minLat + maxLat) / 2; <del> if(topLeftLat >= mid) { <del> if(bottomRightLat < mid) <del> return bits / 5; <del> minLat = mid; <del> } else { <del> if(bottomRightLat >= mid) <del> return bits / 5; <del> maxLat = mid; <del> } <del> } <del> <del> isEven = !isEven; <del> } <del> return MAX_HASH_LENGTH; <del> } <del> <del> /** <del> * Returns true if and only if the bounding box corresponding to the hash <del> * contains the given lat and long. <del> * <del> * @param hash <del> * @param lat <del> * @param lon <del> * @return <del> */ <del> public static boolean hashContains(String hash, double lat, double lon) { <del> LatLong centre = decodeHash(hash); <del> return Math.abs(centre.getLat() - lat) <= heightDegrees(hash.length()) / 2 <del> && Math.abs(to180(centre.getLon() - lon)) <= widthDegrees(hash <del> .length()) / 2; <del> } <del> <del> /** <del> * Returns the result of coverBoundingBoxMaxHashes with a maxHashes value of <del> * {@link GeoHash}.DEFAULT_MAX_HASHES. <del> * <del> * @param topLeftLat <del> * @param topLeftLon <del> * @param bottomRightLat <del> * @param bottomRightLon <del> * @return <del> */ <del> public static Coverage coverBoundingBox(double topLeftLat, <del> final double topLeftLon, final double bottomRightLat, <del> final double bottomRightLon) { <del> <del> return coverBoundingBoxMaxHashes(topLeftLat, topLeftLon, <del> bottomRightLat, bottomRightLon, DEFAULT_MAX_HASHES); <del> } <del> <del> /** <del> * Returns the hashes that are required to cover the given bounding box. The <del> * maximum length of hash is selected that satisfies the number of hashes <del> * returned is less than <code>maxHashes</code>. Returns null if hashes <del> * cannot be found satisfying that condition. Maximum hash length returned <del> * will be {@link GeoHash}.MAX_HASH_LENGTH. <del> * <del> * @param topLeftLat <del> * @param topLeftLon <del> * @param bottomRightLat <del> * @param bottomRightLon <del> * @param maxHashes <del> * @return <del> */ <del> public static Coverage coverBoundingBoxMaxHashes(double topLeftLat, <del> final double topLeftLon, final double bottomRightLat, <del> final double bottomRightLon, int maxHashes) { <del> CoverageLongs coverage = null; <del> int startLength = hashLengthToCoverBoundingBox(topLeftLat, topLeftLon, <del> bottomRightLat, bottomRightLon); <del> if (startLength == 0) <del> startLength = 1; <del> for (int length = startLength; length <= MAX_HASH_LENGTH; length++) { <del> CoverageLongs c = coverBoundingBoxLongs(topLeftLat, topLeftLon, <del> bottomRightLat, bottomRightLon, length); <del> if (c.getCount() > maxHashes) <del> return coverage == null ? null : new Coverage(coverage); <del> else <del> coverage = c; <del> } <del> //note coverage can never be null <del> return new Coverage(coverage); <del> } <del> <del> /** <del> * Returns the hashes of given length that are required to cover the given <del> * bounding box. <del> * <del> * @param topLeftLat <del> * @param topLeftLon <del> * @param bottomRightLat <del> * @param bottomRightLon <del> * @param length <del> * @return <del> */ <del> public static Coverage coverBoundingBox(double topLeftLat, <del> final double topLeftLon, final double bottomRightLat, <del> final double bottomRightLon, final int length) { <del> return new Coverage(coverBoundingBoxLongs(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, length)); <del> } <del> <del> private static class LongSet <del> { <del> int count = 0; <del> private int cap = 16; <del> long[] array = new long[cap]; <del> <del> void add(long l) <del> { <del> for(int i = 0 ; i < count ; i++) <del> if(array[i] == l) <del> return; <del> if(count == cap) { <del> long[] newArray = new long[cap*=2]; <del> System.arraycopy(array, 0, newArray, 0, count); <del> array = newArray; <del> } <del> array[count++] = l; <del> } <del> } <del> <del> static CoverageLongs coverBoundingBoxLongs(double topLeftLat, final double topLeftLon, <del> final double bottomRightLat, final double bottomRightLon, final int length) <del> { <del> Preconditions.checkArgument(topLeftLat>=bottomRightLat,"topLeftLat must be >= bottomRighLat"); <del> Preconditions.checkArgument(topLeftLon<=bottomRightLon,"topLeftLon must be <= bottomRighLon"); <del> Preconditions.checkArgument(length > 0, <del> "length must be greater than zero"); <del> final double actualWidthDegreesPerHash = widthDegrees(length); <del> final double actualHeightDegreesPerHash = heightDegrees(length); <del> <del> LongSet hashes = new LongSet(); <del> <del> double diff = Position.longitudeDiff(bottomRightLon, topLeftLon); <del> double maxLon = topLeftLon + diff; <del> <del> for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { <del> for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { <del> hashes.add(encodeHashToLong(lat, lon, length)); <del> } <del> } <del> // ensure have the borders covered <del> for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { <del> hashes.add(encodeHashToLong(lat, maxLon, length)); <del> } <del> for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { <del> hashes.add(encodeHashToLong(topLeftLat, lon, length)); <del> } <del> // ensure that the topRight corner is covered <del> hashes.add(encodeHashToLong(topLeftLat, maxLon, length)); <del> <del> double areaDegrees = diff * (topLeftLat - bottomRightLat); <del> double coverageAreaDegrees = hashes.count * widthDegrees(length) <del> * heightDegrees(length); <del> double ratio = coverageAreaDegrees / areaDegrees; <del> return new CoverageLongs(hashes.array, hashes.count, ratio); <del> } <del> <del> /** <del> * Array to cache hash height calculations. <del> */ <del> private static Double[] hashHeightCache = new Double[MAX_HASH_LENGTH]; <del> <del> /** <del> * Returns height in degrees of all geohashes of length n. Results are <del> * deterministic and cached to increase performance. <del> * <del> * @param n <del> * @return <del> */ <del> public synchronized static double heightDegrees(int n) { <del> if (n > 0 && n <= MAX_HASH_LENGTH) { <del> if (hashHeightCache[n - 1] == null) <del> hashHeightCache[n - 1] = calculateHeightDegrees(n); <del> return hashHeightCache[n - 1]; <del> } else <del> return calculateHeightDegrees(n); <del> } <del> <del> /** <del> * Returns the height in degrees of the region represented by a geohash of <del> * length n. <del> * <del> * @param n <del> * @return <del> */ <del> private static double calculateHeightDegrees(int n) { <del> double a; <del> if (n % 2 == 0) <del> a = 0; <del> else <del> a = -0.5; <del> double result = 180 / Math.pow(2, 2.5 * n + a); <del> return result; <del> } <del> <del> /** <del> * Array to cache hash width calculations. <del> */ <del> private static Double[] hashWidthCache = new Double[MAX_HASH_LENGTH]; <del> <del> /** <del> * Returns width in degrees of all geohashes of length n. Results are <del> * deterministic and cached to increase performance (might be unnecessary, <del> * have not benchmarked). <del> * <del> * @param n <del> * @return <del> */ <del> public synchronized static double widthDegrees(int n) { <del> if (n > 0 && n <= MAX_HASH_LENGTH) { <del> if (hashWidthCache[n - 1] == null) { <del> hashWidthCache[n - 1] = calculateWidthDegrees(n); <del> } <del> return hashWidthCache[n - 1]; <del> } else <del> return calculateWidthDegrees(n); <del> } <del> <del> /** <del> * Returns the width in degrees of the region represented by a geohash of <del> * length n. <del> * <del> * @param n <del> * @return <del> */ <del> private static double calculateWidthDegrees(int n) { <del> double a; <del> if (n % 2 == 0) <del> a = -1; <del> else <del> a = -0.5; <del> double result = 180 / Math.pow(2, 2.5 * n + a); <del> return result; <del> } <del> <del> /** <del> * <p> <del> * Returns a String of lines of hashes to represent the relative positions <del> * of hashes on a map. The grid is of height and width 2*size centred around <del> * the given hash. Highlighted hashes are displayed in upper case. For <del> * example, gridToString("dr",1,Collections.<String>emptySet()) returns: <del> * </p> <del> * <del> * <pre> <del> * f0 f2 f8 <del> * dp dr dx <del> * dn dq dw <del> * </pre> <del> * <del> * @param hash <del> * @param size <del> * @param highlightThese <del> * @return <del> */ <del> public static String gridAsString(String hash, int size, <del> Set<String> highlightThese) { <del> return gridAsString(hash, -size, -size, size, size, highlightThese); <del> } <del> <del> /** <del> * Returns a String of lines of hashes to represent the relative positions <del> * of hashes on a map. <del> * <del> * @param hash <del> * @param fromRight <del> * top left of the grid in hashes to the right (can be negative). <del> * @param fromBottom <del> * top left of the grid in hashes to the bottom (can be <del> * negative). <del> * @param toRight <del> * bottom righth of the grid in hashes to the bottom (can be <del> * negative). <del> * @param toBottom <del> * bottom right of the grid in hashes to the bottom (can be <del> * negative). <del> * @return <del> */ <del> public static String gridAsString(String hash, int fromRight, <del> int fromBottom, int toRight, int toBottom) { <del> return gridAsString(hash, fromRight, fromBottom, toRight, toBottom, <del> Collections.<String> emptySet()); <del> } <del> <del> /** <del> * Returns a String of lines of hashes to represent the relative positions <del> * of hashes on a map. Highlighted hashes are displayed in upper case. For <del> * example, gridToString("dr",-1,-1,1,1,Sets.newHashSet("f2","f8")) returns: <del> * </p> <del> * <del> * <pre> <del> * f0 F2 F8 <del> * dp dr dx <del> * dn dq dw <del> * </pre> <del> * <del> * @param hash <del> * @param fromRight <del> * top left of the grid in hashes to the right (can be negative). <del> * @param fromBottom <del> * top left of the grid in hashes to the bottom (can be <del> * negative). <del> * @param toRight <del> * bottom righth of the grid in hashes to the bottom (can be <del> * negative). <del> * @param toBottom <del> * bottom right of the grid in hashes to the bottom (can be <del> * negative). <del> * @param highlightThese <del> * @return <del> */ <del> public static String gridAsString(String hash, int fromRight, <del> int fromBottom, int toRight, int toBottom, <del> Set<String> highlightThese) { <del> StringBuilder s = new StringBuilder(); <del> for (int bottom = fromBottom; bottom <= toBottom; bottom++) { <del> for (int right = fromRight; right <= toRight; right++) { <del> String h = adjacentHash(hash, Direction.RIGHT, right); <del> h = adjacentHash(h, Direction.BOTTOM, bottom); <del> if (highlightThese.contains(h)) <del> h = h.toUpperCase(); <del> s.append(h).append(" "); <del> } <del> s.append("\n"); <del> } <del> return s.toString(); <del> } <add> private static final double PRECISION = 0.000000000001; <add> <add> /** <add> * The standard practical maximum length for geohashes. <add> */ <add> public static final int MAX_HASH_LENGTH = 12; <add> <add> /** <add> * Default maximum number of hashes for covering a bounding box. <add> */ <add> public static final int DEFAULT_MAX_HASHES = 12; <add> <add> /** <add> * Powers of 2 from 32 down to 1. <add> */ <add> private static final int[] BITS = new int[] { 16, 8, 4, 2, 1 }; <add> <add> /** <add> * The characters used in base 32 representations. <add> */ <add> private static final String BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"; <add> <add> /** <add> * Utility lookup for neighbouring hashes. <add> */ <add> private static final Map<Direction, Map<Parity, String>> NEIGHBOURS = createNeighbours(); <add> <add> /** <add> * Utility lookup for hash borders. <add> */ <add> private static final Map<Direction, Map<Parity, String>> BORDERS = createBorders(); <add> <add> /** <add> * Private constructor. <add> */ <add> private GeoHash() { <add> // prevent instantiation <add> } <add> <add> /** <add> * Returns a map to be used in hash border calculations. <add> * <add> * @return map of borders <add> */ <add> private static Map<Direction, Map<Parity, String>> createBorders() { <add> Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); <add> <add> m.get(Direction.RIGHT).put(Parity.EVEN, "bcfguvyz"); <add> m.get(Direction.LEFT).put(Parity.EVEN, "0145hjnp"); <add> m.get(Direction.TOP).put(Parity.EVEN, "prxz"); <add> m.get(Direction.BOTTOM).put(Parity.EVEN, "028b"); <add> <add> addOddParityEntries(m); <add> return m; <add> } <add> <add> /** <add> * Returns a map to be used in adjacent hash calculations. <add> * <add> * @return map <add> */ <add> private static Map<Direction, Map<Parity, String>> createNeighbours() { <add> Map<Direction, Map<Parity, String>> m = createDirectionParityMap(); <add> <add> m.get(Direction.RIGHT).put(Parity.EVEN, "bc01fg45238967deuvhjyznpkmstqrwx"); <add> m.get(Direction.LEFT).put(Parity.EVEN, "238967debc01fg45kmstqrwxuvhjyznp"); <add> m.get(Direction.TOP).put(Parity.EVEN, "p0r21436x8zb9dcf5h7kjnmqesgutwvy"); <add> m.get(Direction.BOTTOM).put(Parity.EVEN, "14365h7k9dcfesgujnmqp0r2twvyx8zb"); <add> addOddParityEntries(m); <add> <add> return m; <add> } <add> <add> /** <add> * Create a direction and parity map for use in adjacent hash calculations. <add> * <add> * @return map <add> */ <add> private static Map<Direction, Map<Parity, String>> createDirectionParityMap() { <add> Map<Direction, Map<Parity, String>> m = newHashMap(); <add> m.put(Direction.BOTTOM, GeoHash.<Parity, String> newHashMap()); <add> m.put(Direction.TOP, GeoHash.<Parity, String> newHashMap()); <add> m.put(Direction.LEFT, GeoHash.<Parity, String> newHashMap()); <add> m.put(Direction.RIGHT, GeoHash.<Parity, String> newHashMap()); <add> return m; <add> } <add> <add> private static <T, D> Map<T, D> newHashMap() { <add> return new HashMap<T, D>(); <add> } <add> <add> /** <add> * Puts odd parity entries in the map m based purely on the even entries. <add> * <add> * @param m <add> * map <add> */ <add> private static void addOddParityEntries(Map<Direction, Map<Parity, String>> m) { <add> m.get(Direction.BOTTOM).put(Parity.ODD, m.get(Direction.LEFT).get(Parity.EVEN)); <add> m.get(Direction.TOP).put(Parity.ODD, m.get(Direction.RIGHT).get(Parity.EVEN)); <add> m.get(Direction.LEFT).put(Parity.ODD, m.get(Direction.BOTTOM).get(Parity.EVEN)); <add> m.get(Direction.RIGHT).put(Parity.ODD, m.get(Direction.TOP).get(Parity.EVEN)); <add> } <add> <add> /** <add> * Returns the adjacent hash in given {@link Direction}. Based on <add> * https://github.com/davetroy/geohash-js/blob/master/geohash.js. This <add> * method is an improvement on the original js method because it works at <add> * borders too (at the poles and the -180,180 longitude boundaries). <add> * <add> * @param hash <add> * @param direction <add> * @return hash of adjacent hash <add> */ <add> public static String adjacentHash(String hash, Direction direction) { <add> checkHash(hash); <add> Preconditions.checkArgument(hash.length() > 0, <add> "adjacent has no meaning for a zero length hash that covers the whole world"); <add> <add> String adjacentHashAtBorder = adjacentHashAtBorder(hash, direction); <add> if (adjacentHashAtBorder != null) <add> return adjacentHashAtBorder; <add> <add> String source = hash.toLowerCase(); <add> char lastChar = source.charAt(source.length() - 1); <add> Parity parity = (source.length() % 2 == 0) ? Parity.EVEN : Parity.ODD; <add> String base = source.substring(0, source.length() - 1); <add> if (BORDERS.get(direction).get(parity).indexOf(lastChar) != -1) <add> base = adjacentHash(base, direction); <add> return base + BASE32.charAt(NEIGHBOURS.get(direction).get(parity).indexOf(lastChar)); <add> } <add> <add> private static String adjacentHashAtBorder(String hash, Direction direction) { <add> // check if hash is on edge and direction would push us over the edge <add> // if so, wrap round to the other limit for longitude <add> // or if at latitude boundary (a pole) then spin longitude around 180 <add> // degrees. <add> LatLong centre = decodeHash(hash); <add> <add> // if rightmost hash <add> if (Direction.RIGHT.equals(direction)) { <add> if (Math.abs(centre.getLon() + widthDegrees(hash.length()) / 2 - 180) < PRECISION) { <add> return encodeHash(centre.getLat(), -180, hash.length()); <add> } <add> } <add> // if leftmost hash <add> else if (Direction.LEFT.equals(direction)) { <add> if (Math.abs(centre.getLon() - widthDegrees(hash.length()) / 2 + 180) < PRECISION) { <add> return encodeHash(centre.getLat(), 180, hash.length()); <add> } <add> } <add> // if topmost hash <add> else if (Direction.TOP.equals(direction)) { <add> if (Math.abs(centre.getLat() + widthDegrees(hash.length()) / 2 - 90) < PRECISION) { <add> return encodeHash(centre.getLat(), centre.getLon() + 180, hash.length()); <add> } <add> } <add> // if bottommost hash <add> else { <add> if (Math.abs(centre.getLat() - widthDegrees(hash.length()) / 2 + 90) < PRECISION) { <add> return encodeHash(centre.getLat(), centre.getLon() + 180, hash.length()); <add> } <add> } <add> <add> return null; <add> } <add> <add> /** <add> * Throws an {@link IllegalArgumentException} if and only if the hash is <add> * null or blank. <add> * <add> * @param hash <add> * to check <add> */ <add> private static void checkHash(String hash) { <add> Preconditions.checkArgument(hash != null, "hash must be non-null"); <add> } <add> <add> /** <add> * Returns the adjacent hash to the right (east). <add> * <add> * @param hash <add> * to check <add> * @return hash on right of given hash <add> */ <add> public static String right(String hash) { <add> return adjacentHash(hash, Direction.RIGHT); <add> } <add> <add> /** <add> * Returns the adjacent hash to the left (west). <add> * <add> * @param hash <add> * origin <add> * @return hash on left of origin hash <add> */ <add> public static String left(String hash) { <add> return adjacentHash(hash, Direction.LEFT); <add> } <add> <add> /** <add> * Returns the adjacent hash to the top (north). <add> * <add> * @param hash <add> * origin <add> * @return hash above origin hash <add> */ <add> public static String top(String hash) { <add> return adjacentHash(hash, Direction.TOP); <add> } <add> <add> /** <add> * Returns the adjacent hash to the bottom (south). <add> * <add> * @param hash <add> * origin <add> * @return hash below (south) of origin hash <add> */ <add> public static String bottom(String hash) { <add> return adjacentHash(hash, Direction.BOTTOM); <add> } <add> <add> /** <add> * Returns the adjacent hash N steps in the given {@link Direction}. A <add> * negative N will use the opposite {@link Direction}. <add> * <add> * @param hash <add> * origin hash <add> * @param direction <add> * to desired hash <add> * @param steps <add> * number of hashes distance to desired hash <add> * @return hash at position in direction a number of hashes away (steps) <add> */ <add> public static String adjacentHash(String hash, Direction direction, int steps) { <add> if (steps < 0) <add> return adjacentHash(hash, direction.opposite(), Math.abs(steps)); <add> else { <add> String h = hash; <add> for (int i = 0; i < steps; i++) <add> h = adjacentHash(h, direction); <add> return h; <add> } <add> } <add> <add> /** <add> * Returns a list of the 8 surrounding hashes for a given hash in order <add> * left,right,top,bottom,left-top,left-bottom,right-top,right-bottom. <add> * <add> * @param hash <add> * source <add> * @return a list of neighbour hashes <add> */ <add> public static List<String> neighbours(String hash) { <add> List<String> list = new ArrayList<String>(); <add> String left = adjacentHash(hash, Direction.LEFT); <add> String right = adjacentHash(hash, Direction.RIGHT); <add> list.add(left); <add> list.add(right); <add> list.add(adjacentHash(hash, Direction.TOP)); <add> list.add(adjacentHash(hash, Direction.BOTTOM)); <add> list.add(adjacentHash(left, Direction.TOP)); <add> list.add(adjacentHash(left, Direction.BOTTOM)); <add> list.add(adjacentHash(right, Direction.TOP)); <add> list.add(adjacentHash(right, Direction.BOTTOM)); <add> return list; <add> } <add> <add> /** <add> * Returns a geohash of length {@link GeoHash#MAX_HASH_LENGTH} (12) for the <add> * given WGS84 point (latitude,longitude). <add> * <add> * @param latitude <add> * in decimal degrees (WGS84) <add> * @param longitude <add> * in decimal degrees (WGS84) <add> * @return hash at given point of default length <add> */ <add> public static String encodeHash(double latitude, double longitude) { <add> return encodeHash(latitude, longitude, MAX_HASH_LENGTH); <add> } <add> <add> /** <add> * Returns a geohash of given length for the given WGS84 point. <add> * <add> * @param p <add> * point <add> * @param length <add> * length of hash <add> * @return hash at point of given length <add> */ <add> public static String encodeHash(LatLong p, int length) { <add> return encodeHash(p.getLat(), p.getLon(), length); <add> } <add> <add> /** <add> * Returns a geohash of of length {@link GeoHash#MAX_HASH_LENGTH} (12) for <add> * the given WGS84 point. <add> * <add> * @param p <add> * point <add> * @return hash of default length <add> */ <add> public static String encodeHash(LatLong p) { <add> return encodeHash(p.getLat(), p.getLon(), MAX_HASH_LENGTH); <add> } <add> <add> /** <add> * Returns a geohash of given length for the given WGS84 point <add> * (latitude,longitude). If latitude is not between -90 and 90 throws an <add> * {@link IllegalArgumentException}. <add> * <add> * @param latitude <add> * in decimal degrees (WGS84) <add> * @param longitude <add> * in decimal degrees (WGS84) <add> * @param length <add> * length of desired hash <add> * @return geohash of given length for the given point <add> */ <add> // Translated to java from: <add> // geohash.js <add> // Geohash library for Javascript <add> // (c) 2008 David Troy <add> // Distributed under the MIT License <add> public static String encodeHash(double latitude, double longitude, int length) { <add> Preconditions.checkArgument(length > 0, "length must be greater than zero"); <add> Preconditions.checkArgument(latitude >= -90 && latitude <= 90, <add> "latitude must be between -90 and 90 inclusive"); <add> longitude = Position.to180(longitude); <add> <add> return fromLongToString(encodeHashToLong(latitude, longitude, length)); <add> } <add> <add> /** <add> * Takes a hash represented as a long and returns it as a string. <add> * <add> * @param hash <add> * the hash, with the length encoded in the 4 least significant <add> * bits <add> * @return the string encoded geohash <add> */ <add> static String fromLongToString(long hash) { <add> int length = (int) (hash & 0xf); <add> if (length > 12 || length < 1) <add> throw new IllegalArgumentException("invalid long geohash " + hash); <add> char[] geohash = new char[length]; <add> for (int pos = 0; pos < length; pos++) { <add> geohash[pos] = BASE32.charAt(((int) (hash >>> 59))); <add> hash <<= 5; <add> } <add> return new String(geohash); <add> } <add> <add> static long encodeHashToLong(double latitude, double longitude, int length) { <add> boolean isEven = true; <add> double minLat = -90.0, maxLat = 90; <add> double minLon = -180.0, maxLon = 180.0; <add> long bit = 0x8000000000000000L; <add> long g = 0; <add> <add> long target = 0x8000000000000000L >>> (5 * length); <add> while (bit != target) { <add> if (isEven) { <add> double mid = (minLon + maxLon) / 2; <add> if (longitude >= mid) { <add> g |= bit; <add> minLon = mid; <add> } else <add> maxLon = mid; <add> } else { <add> double mid = (minLat + maxLat) / 2; <add> if (latitude >= mid) { <add> g |= bit; <add> minLat = mid; <add> } else <add> maxLat = mid; <add> } <add> <add> isEven = !isEven; <add> bit >>>= 1; <add> } <add> return g |= length; <add> } <add> <add> /** <add> * Returns a latitude,longitude pair as the centre of the given geohash. <add> * Latitude will be between -90 and 90 and longitude between -180 and 180. <add> * <add> * @param geohash <add> * @return lat long point <add> */ <add> // Translated to java from: <add> // geohash.js <add> // Geohash library for Javascript <add> // (c) 2008 David Troy <add> // Distributed under the MIT License <add> public static LatLong decodeHash(String geohash) { <add> Preconditions.checkNotNull(geohash, "geohash cannot be null"); <add> boolean isEven = true; <add> double[] lat = new double[2]; <add> double[] lon = new double[2]; <add> lat[0] = -90.0; <add> lat[1] = 90.0; <add> lon[0] = -180.0; <add> lon[1] = 180.0; <add> <add> for (int i = 0; i < geohash.length(); i++) { <add> char c = geohash.charAt(i); <add> int cd = BASE32.indexOf(c); <add> for (int j = 0; j < 5; j++) { <add> int mask = BITS[j]; <add> if (isEven) { <add> refineInterval(lon, cd, mask); <add> } else { <add> refineInterval(lat, cd, mask); <add> } <add> isEven = !isEven; <add> } <add> } <add> double resultLat = (lat[0] + lat[1]) / 2; <add> double resultLon = (lon[0] + lon[1]) / 2; <add> <add> return new LatLong(resultLat, resultLon); <add> } <add> <add> /** <add> * Refines interval by a factor or 2 in either the 0 or 1 ordinate. <add> * <add> * @param interval <add> * two entry array of double values <add> * @param cd <add> * used with mask <add> * @param mask <add> * used with cd <add> */ <add> private static void refineInterval(double[] interval, int cd, int mask) { <add> if ((cd & mask) != 0) <add> interval[0] = (interval[0] + interval[1]) / 2; <add> else <add> interval[1] = (interval[0] + interval[1]) / 2; <add> } <add> <add> /** <add> * Returns the maximum length of hash that covers the bounding box. If no <add> * hash can enclose the bounding box then 0 is returned. <add> * <add> * @param topLeftLat <add> * @param topLeftLon <add> * @param bottomRightLat <add> * @param bottomRightLon <add> * @return <add> */ <add> public static int hashLengthToCoverBoundingBox(double topLeftLat, double topLeftLon, <add> double bottomRightLat, double bottomRightLon) { <add> boolean isEven = true; <add> double minLat = -90.0, maxLat = 90; <add> double minLon = -180.0, maxLon = 180.0; <add> <add> for (int bits = 0; bits < MAX_HASH_LENGTH * 5; bits++) { <add> if (isEven) { <add> double mid = (minLon + maxLon) / 2; <add> if (topLeftLon >= mid) { <add> if (bottomRightLon < mid) <add> return bits / 5; <add> minLon = mid; <add> } else { <add> if (bottomRightLon >= mid) <add> return bits / 5; <add> maxLon = mid; <add> } <add> } else { <add> double mid = (minLat + maxLat) / 2; <add> if (topLeftLat >= mid) { <add> if (bottomRightLat < mid) <add> return bits / 5; <add> minLat = mid; <add> } else { <add> if (bottomRightLat >= mid) <add> return bits / 5; <add> maxLat = mid; <add> } <add> } <add> <add> isEven = !isEven; <add> } <add> return MAX_HASH_LENGTH; <add> } <add> <add> /** <add> * Returns true if and only if the bounding box corresponding to the hash <add> * contains the given lat and long. <add> * <add> * @param hash <add> * @param lat <add> * @param lon <add> * @return <add> */ <add> public static boolean hashContains(String hash, double lat, double lon) { <add> LatLong centre = decodeHash(hash); <add> return Math.abs(centre.getLat() - lat) <= heightDegrees(hash.length()) / 2 <add> && Math.abs(to180(centre.getLon() - lon)) <= widthDegrees(hash.length()) / 2; <add> } <add> <add> /** <add> * Returns the result of coverBoundingBoxMaxHashes with a maxHashes value of <add> * {@link GeoHash}.DEFAULT_MAX_HASHES. <add> * <add> * @param topLeftLat <add> * @param topLeftLon <add> * @param bottomRightLat <add> * @param bottomRightLon <add> * @return <add> */ <add> public static Coverage coverBoundingBox(double topLeftLat, final double topLeftLon, <add> final double bottomRightLat, final double bottomRightLon) { <add> <add> return coverBoundingBoxMaxHashes(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon, <add> DEFAULT_MAX_HASHES); <add> } <add> <add> /** <add> * Returns the hashes that are required to cover the given bounding box. The <add> * maximum length of hash is selected that satisfies the number of hashes <add> * returned is less than <code>maxHashes</code>. Returns null if hashes <add> * cannot be found satisfying that condition. Maximum hash length returned <add> * will be {@link GeoHash}.MAX_HASH_LENGTH. <add> * <add> * @param topLeftLat <add> * @param topLeftLon <add> * @param bottomRightLat <add> * @param bottomRightLon <add> * @param maxHashes <add> * @return <add> */ <add> public static Coverage coverBoundingBoxMaxHashes(double topLeftLat, final double topLeftLon, <add> final double bottomRightLat, final double bottomRightLon, int maxHashes) { <add> CoverageLongs coverage = null; <add> int startLength = hashLengthToCoverBoundingBox(topLeftLat, topLeftLon, bottomRightLat, <add> bottomRightLon); <add> if (startLength == 0) <add> startLength = 1; <add> for (int length = startLength; length <= MAX_HASH_LENGTH; length++) { <add> CoverageLongs c = coverBoundingBoxLongs(topLeftLat, topLeftLon, bottomRightLat, <add> bottomRightLon, length); <add> if (c.getCount() > maxHashes) <add> return coverage == null ? null : new Coverage(coverage); <add> else <add> coverage = c; <add> } <add> // note coverage can never be null <add> return new Coverage(coverage); <add> } <add> <add> /** <add> * Returns the hashes of given length that are required to cover the given <add> * bounding box. <add> * <add> * @param topLeftLat <add> * @param topLeftLon <add> * @param bottomRightLat <add> * @param bottomRightLon <add> * @param length <add> * @return <add> */ <add> public static Coverage coverBoundingBox(double topLeftLat, final double topLeftLon, <add> final double bottomRightLat, final double bottomRightLon, final int length) { <add> return new Coverage(coverBoundingBoxLongs(topLeftLat, topLeftLon, bottomRightLat, <add> bottomRightLon, length)); <add> } <add> <add> private static class LongSet { <add> int count = 0; <add> private int cap = 16; <add> long[] array = new long[cap]; <add> <add> void add(long l) { <add> for (int i = 0; i < count; i++) <add> if (array[i] == l) <add> return; <add> if (count == cap) { <add> long[] newArray = new long[cap *= 2]; <add> System.arraycopy(array, 0, newArray, 0, count); <add> array = newArray; <add> } <add> array[count++] = l; <add> } <add> } <add> <add> static CoverageLongs coverBoundingBoxLongs(double topLeftLat, final double topLeftLon, <add> final double bottomRightLat, final double bottomRightLon, final int length) { <add> Preconditions.checkArgument(topLeftLat >= bottomRightLat, <add> "topLeftLat must be >= bottomRighLat"); <add> Preconditions.checkArgument(topLeftLon <= bottomRightLon, <add> "topLeftLon must be <= bottomRighLon"); <add> Preconditions.checkArgument(length > 0, "length must be greater than zero"); <add> final double actualWidthDegreesPerHash = widthDegrees(length); <add> final double actualHeightDegreesPerHash = heightDegrees(length); <add> <add> LongSet hashes = new LongSet(); <add> <add> double diff = Position.longitudeDiff(bottomRightLon, topLeftLon); <add> double maxLon = topLeftLon + diff; <add> <add> for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { <add> for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { <add> hashes.add(encodeHashToLong(lat, lon, length)); <add> } <add> } <add> // ensure have the borders covered <add> for (double lat = bottomRightLat; lat <= topLeftLat; lat += actualHeightDegreesPerHash) { <add> hashes.add(encodeHashToLong(lat, maxLon, length)); <add> } <add> for (double lon = topLeftLon; lon <= maxLon; lon += actualWidthDegreesPerHash) { <add> hashes.add(encodeHashToLong(topLeftLat, lon, length)); <add> } <add> // ensure that the topRight corner is covered <add> hashes.add(encodeHashToLong(topLeftLat, maxLon, length)); <add> <add> double areaDegrees = diff * (topLeftLat - bottomRightLat); <add> double coverageAreaDegrees = hashes.count * widthDegrees(length) * heightDegrees(length); <add> double ratio = coverageAreaDegrees / areaDegrees; <add> return new CoverageLongs(hashes.array, hashes.count, ratio); <add> } <add> <add> /** <add> * Returns height in degrees of all geohashes of length n. Results are <add> * deterministic and cached to increase performance. <add> * <add> * @param n <add> * @return <add> */ <add> public static double heightDegrees(int n) { <add> if (n > MAX_HASH_LENGTH) <add> return calculateHeightDegrees(n); <add> else <add> return HashHeights.values[n]; <add> } <add> <add> private static final class HashHeights { <add> <add> static final double[] values = createValues(); <add> <add> private static double[] createValues() { <add> double d[] = new double[MAX_HASH_LENGTH + 1]; <add> for (int i = 0; i <= MAX_HASH_LENGTH; i++) { <add> d[i] = calculateHeightDegrees(i); <add> } <add> return d; <add> } <add> } <add> <add> /** <add> * Returns the height in degrees of the region represented by a geohash of <add> * length n. <add> * <add> * @param n <add> * @return <add> */ <add> private static double calculateHeightDegrees(int n) { <add> double a; <add> if (n % 2 == 0) <add> a = 0; <add> else <add> a = -0.5; <add> double result = 180 / Math.pow(2, 2.5 * n + a); <add> return result; <add> } <add> <add> private static final class HashWidths { <add> <add> static final double[] values = createValues(); <add> <add> private static double[] createValues() { <add> double d[] = new double[MAX_HASH_LENGTH + 1]; <add> for (int i = 0; i <= MAX_HASH_LENGTH; i++) { <add> d[i] = calculateWidthDegrees(i); <add> } <add> return d; <add> } <add> } <add> <add> /** <add> * Returns width in degrees of all geohashes of length n. Results are <add> * deterministic and cached to increase performance (might be unnecessary, <add> * have not benchmarked). <add> * <add> * @param n <add> * @return <add> */ <add> public static double widthDegrees(int n) { <add> if (n > MAX_HASH_LENGTH) <add> return calculateWidthDegrees(n); <add> else <add> return HashWidths.values[n]; <add> } <add> <add> /** <add> * Returns the width in degrees of the region represented by a geohash of <add> * length n. <add> * <add> * @param n <add> * @return <add> */ <add> private static double calculateWidthDegrees(int n) { <add> double a; <add> if (n % 2 == 0) <add> a = -1; <add> else <add> a = -0.5; <add> double result = 180 / Math.pow(2, 2.5 * n + a); <add> return result; <add> } <add> <add> /** <add> * <p> <add> * Returns a String of lines of hashes to represent the relative positions <add> * of hashes on a map. The grid is of height and width 2*size centred around <add> * the given hash. Highlighted hashes are displayed in upper case. For <add> * example, gridToString("dr",1,Collections.<String>emptySet()) returns: <add> * </p> <add> * <add> * <pre> <add> * f0 f2 f8 <add> * dp dr dx <add> * dn dq dw <add> * </pre> <add> * <add> * @param hash <add> * @param size <add> * @param highlightThese <add> * @return <add> */ <add> public static String gridAsString(String hash, int size, Set<String> highlightThese) { <add> return gridAsString(hash, -size, -size, size, size, highlightThese); <add> } <add> <add> /** <add> * Returns a String of lines of hashes to represent the relative positions <add> * of hashes on a map. <add> * <add> * @param hash <add> * @param fromRight <add> * top left of the grid in hashes to the right (can be negative). <add> * @param fromBottom <add> * top left of the grid in hashes to the bottom (can be <add> * negative). <add> * @param toRight <add> * bottom righth of the grid in hashes to the bottom (can be <add> * negative). <add> * @param toBottom <add> * bottom right of the grid in hashes to the bottom (can be <add> * negative). <add> * @return <add> */ <add> public static String gridAsString(String hash, int fromRight, int fromBottom, int toRight, <add> int toBottom) { <add> return gridAsString(hash, fromRight, fromBottom, toRight, toBottom, <add> Collections.<String> emptySet()); <add> } <add> <add> /** <add> * Returns a String of lines of hashes to represent the relative positions <add> * of hashes on a map. Highlighted hashes are displayed in upper case. For <add> * example, gridToString("dr",-1,-1,1,1,Sets.newHashSet("f2","f8")) returns: <add> * </p> <add> * <add> * <pre> <add> * f0 F2 F8 <add> * dp dr dx <add> * dn dq dw <add> * </pre> <add> * <add> * @param hash <add> * @param fromRight <add> * top left of the grid in hashes to the right (can be negative). <add> * @param fromBottom <add> * top left of the grid in hashes to the bottom (can be <add> * negative). <add> * @param toRight <add> * bottom righth of the grid in hashes to the bottom (can be <add> * negative). <add> * @param toBottom <add> * bottom right of the grid in hashes to the bottom (can be <add> * negative). <add> * @param highlightThese <add> * @return <add> */ <add> public static String gridAsString(String hash, int fromRight, int fromBottom, int toRight, <add> int toBottom, Set<String> highlightThese) { <add> StringBuilder s = new StringBuilder(); <add> for (int bottom = fromBottom; bottom <= toBottom; bottom++) { <add> for (int right = fromRight; right <= toRight; right++) { <add> String h = adjacentHash(hash, Direction.RIGHT, right); <add> h = adjacentHash(h, Direction.BOTTOM, bottom); <add> if (highlightThese.contains(h)) <add> h = h.toUpperCase(); <add> s.append(h).append(" "); <add> } <add> s.append("\n"); <add> } <add> return s.toString(); <add> } <ide> <ide> }
Java
mit
d6e23de77d639ab33ffc591dd67a6353083ccc92
0
gmessner/gitlab4j-api
package org.gitlab4j.api; import java.util.Date; import java.util.List; import javax.ws.rs.core.Form; import javax.ws.rs.core.MultivaluedHashMap; import org.gitlab4j.api.models.AccessLevel; import org.gitlab4j.api.utils.ISO8601; /** * This class extends the standard JAX-RS Form class to make it fluent. */ public class GitLabApiForm extends Form { public GitLabApiForm() { super(); } public GitLabApiForm(MultivaluedHashMap<String, String> map) { super(map); } /** * Create a GitLabApiForm instance with the "page", and "per_page" parameters preset. * * @param page the value for the "page" parameter * @param perPage the value for the "per_page" parameter */ public GitLabApiForm(int page, int perPage) { super(); withParam(AbstractApi.PAGE_PARAM, page); withParam(AbstractApi.PER_PAGE_PARAM, (Integer)perPage); } /** * Fluent method for adding query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param value the value of the field/attribute to add * @return this GitLabAPiForm instance */ public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException { return (withParam(name, value, false)); } /** * Fluent method for adding Date query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param date the value of the field/attribute to add * @return this GitLabAPiForm instance */ public GitLabApiForm withParam(String name, Date date) throws IllegalArgumentException { return (withParam(name, date, false)); } /** * Fluent method for adding Date query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param date the value of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public GitLabApiForm withParam(String name, Date date, boolean required) throws IllegalArgumentException { return (withParam(name, (date == null ? null : ISO8601.toString(date)), required)); } /** * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param level the value of the field/attribute to add * @return this GitLabAPiForm instance */ public GitLabApiForm withParam(String name, AccessLevel level) throws IllegalArgumentException { return (withParam(name, level, false)); } /** * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param level the value of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public GitLabApiForm withParam(String name, AccessLevel level, boolean required) throws IllegalArgumentException { return (withParam(name, (level == null ? null : level.toValue()), required)); } /** * Fluent method for adding a List type query and form parameters to a get() or post() call. * * @param <T> the type contained by the List * @param name the name of the field/attribute to add * @param values a List containing the values of the field/attribute to add * @return this GitLabAPiForm instance */ public <T> GitLabApiForm withParam(String name, List<T> values) { return (withParam(name, values, false)); } /** * Fluent method for adding a List type query and form parameters to a get() or post() call. * * @param <T> the type contained by the List * @param name the name of the field/attribute to add * @param values a List containing the values of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public <T> GitLabApiForm withParam(String name, List<T> values, boolean required) throws IllegalArgumentException { if (values == null || values.isEmpty()) { if (required) { throw new IllegalArgumentException(name + " cannot be empty or null"); } return (this); } for (T value : values) { if (value != null) { this.param(name + "[]", value.toString()); } } return (this); } /** * Fluent method for adding query and form parameters to a get() or post() call. * If required is true and value is null, will throw an IllegalArgumentException. * * @param name the name of the field/attribute to add * @param value the value of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public GitLabApiForm withParam(String name, Object value, boolean required) throws IllegalArgumentException { if (value == null) { if (required) { throw new IllegalArgumentException(name + " cannot be empty or null"); } return (this); } String stringValue = value.toString(); if (required && stringValue.trim().length() == 0) { throw new IllegalArgumentException(name + " cannot be empty or null"); } this.param(name, stringValue); return (this); } }
src/main/java/org/gitlab4j/api/GitLabApiForm.java
package org.gitlab4j.api; import java.util.Date; import java.util.List; import javax.ws.rs.core.Form; import javax.ws.rs.core.MultivaluedHashMap; import org.gitlab4j.api.models.AccessLevel; import org.gitlab4j.api.utils.ISO8601; /** * This class extends the standard JAX-RS Form class to make it fluent. */ public class GitLabApiForm extends Form { public GitLabApiForm() { super(); } public GitLabApiForm(MultivaluedHashMap<String, String> map) { super(map); } /** * Create a GitLabApiForm instance with the "page", and "per_page" parameters preset. * * @param page the value for the "page" parameter * @param perPage the value for the "per_page" parameter */ public GitLabApiForm(int page, int perPage) { super(); withParam(AbstractApi.PAGE_PARAM, page); withParam(AbstractApi.PER_PAGE_PARAM, (Integer)perPage); } /** * Fluent method for adding query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param value the value of the field/attribute to add * @return this GitLabAPiForm instance */ public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException { return (withParam(name, value, false)); } /** * Fluent method for adding Date query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param date the value of the field/attribute to add * @return this GitLabAPiForm instance */ public GitLabApiForm withParam(String name, Date date) throws IllegalArgumentException { return (withParam(name, date, false)); } /** * Fluent method for adding Date query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param date the value of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public GitLabApiForm withParam(String name, Date date, boolean required) throws IllegalArgumentException { return (withParam(name, (date == null ? null : ISO8601.toString(date)), required)); } /** * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param date the value of the field/attribute to add * @return this GitLabAPiForm instance */ public GitLabApiForm withParam(String name, AccessLevel level) throws IllegalArgumentException { return (withParam(name, level, false)); } /** * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. * * @param name the name of the field/attribute to add * @param level the value of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public GitLabApiForm withParam(String name, AccessLevel level, boolean required) throws IllegalArgumentException { return (withParam(name, (level == null ? null : level.toValue()), required)); } /** * Fluent method for adding a List type query and form parameters to a get() or post() call. * * @param <T> the type contained by the List * @param name the name of the field/attribute to add * @param values a List containing the values of the field/attribute to add * @return this GitLabAPiForm instance */ public <T> GitLabApiForm withParam(String name, List<T> values) { return (withParam(name, values, false)); } /** * Fluent method for adding a List type query and form parameters to a get() or post() call. * * @param <T> the type contained by the List * @param name the name of the field/attribute to add * @param values a List containing the values of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public <T> GitLabApiForm withParam(String name, List<T> values, boolean required) throws IllegalArgumentException { if (values == null || values.isEmpty()) { if (required) { throw new IllegalArgumentException(name + " cannot be empty or null"); } return (this); } for (T value : values) { if (value != null) { this.param(name + "[]", value.toString()); } } return (this); } /** * Fluent method for adding query and form parameters to a get() or post() call. * If required is true and value is null, will throw an IllegalArgumentException. * * @param name the name of the field/attribute to add * @param value the value of the field/attribute to add * @param required the field is required flag * @return this GitLabAPiForm instance * @throws IllegalArgumentException if a required parameter is null or empty */ public GitLabApiForm withParam(String name, Object value, boolean required) throws IllegalArgumentException { if (value == null) { if (required) { throw new IllegalArgumentException(name + " cannot be empty or null"); } return (this); } String stringValue = value.toString(); if (required && stringValue.trim().length() == 0) { throw new IllegalArgumentException(name + " cannot be empty or null"); } this.param(name, stringValue); return (this); } }
Fixed javadoc error.
src/main/java/org/gitlab4j/api/GitLabApiForm.java
Fixed javadoc error.
<ide><path>rc/main/java/org/gitlab4j/api/GitLabApiForm.java <ide> * Fluent method for adding AccessLevel query and form parameters to a get() or post() call. <ide> * <ide> * @param name the name of the field/attribute to add <del> * @param date the value of the field/attribute to add <add> * @param level the value of the field/attribute to add <ide> * @return this GitLabAPiForm instance <ide> */ <ide> public GitLabApiForm withParam(String name, AccessLevel level) throws IllegalArgumentException {
Java
apache-2.0
0625e67d46533d83754e77ffb8f8d1b196806074
0
apache/commons-vfs,ecki/commons-vfs,ecki/commons-vfs,apache/commons-vfs
/* * 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.commons.vfs2.provider.local.test; import java.io.File; import java.net.URI; import org.apache.commons.vfs2.FileContent; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemManager; import org.apache.commons.vfs2.VFS; import org.apache.commons.vfs2.impl.DefaultFileSystemManager; import org.apache.commons.vfs2.test.AbstractProviderTestCase; import org.junit.Assert; import org.junit.Test; /** * Additional naming tests for local file system. */ public class FileNameTests extends AbstractProviderTestCase { /** * Tests resolution of an absolute file name. */ @Test public void testAbsoluteFileName() throws Exception { // Locate file by absolute file name final String fileName = new File("testdir").getAbsolutePath(); final DefaultFileSystemManager manager = getManager(); Assert.assertNotNull("Unexpected null manager for test " + this, manager); try (final FileObject absFile = manager.resolveFile(fileName)) { // Locate file by URI final String uri = "file://" + fileName.replace(File.separatorChar, '/'); final FileObject uriFile = manager.resolveFile(uri); assertSame("file object", absFile, uriFile); } } /** * https://issues.apache.org/jira/browse/VFS-790 */ @Test public void testLocalFile() throws Exception { final String prefix = new String("\u0074\u0065\u0074"); final File file = File.createTempFile(prefix + "-", "-" + prefix); assertTrue(file.exists()); final URI uri = file.toURI(); try (final FileSystemManager manager = getManager()) { try (final FileObject fileObject = manager.resolveFile(uri)) { try (final FileContent sourceContent = fileObject.getContent()) { assertEquals(sourceContent.getSize(), file.length()); } } } } }
commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/test/FileNameTests.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.commons.vfs2.provider.local.test; import java.io.File; import java.net.URI; import org.apache.commons.vfs2.FileContent; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemManager; import org.apache.commons.vfs2.VFS; import org.apache.commons.vfs2.impl.DefaultFileSystemManager; import org.apache.commons.vfs2.test.AbstractProviderTestCase; import org.junit.Assert; import org.junit.Test; /** * Additional naming tests for local file system. */ public class FileNameTests extends AbstractProviderTestCase { /** * Tests resolution of an absolute file name. */ @Test public void testAbsoluteFileName() throws Exception { // Locate file by absolute file name final String fileName = new File("testdir").getAbsolutePath(); final DefaultFileSystemManager manager = getManager(); Assert.assertNotNull("Unexpected null manager for test " + this, manager); try (final FileObject absFile = manager.resolveFile(fileName)) { // Locate file by URI final String uri = "file://" + fileName.replace(File.separatorChar, '/'); final FileObject uriFile = manager.resolveFile(uri); assertSame("file object", absFile, uriFile); } } /** * https://issues.apache.org/jira/browse/VFS-790 */ @Test public void testLocalFile() throws Exception { final String prefix = new String(new char[] { '\u0074', '\u0065', '\u0074' }); final File f = File.createTempFile(prefix + "-", "-" + prefix); assertTrue(f.exists()); final URI uri = f.toURI(); try (final FileSystemManager m = VFS.getManager()) { try (final FileObject s = m.resolveFile(uri)) { try (final FileContent sourceContent = s.getContent()) { final long size = sourceContent.getSize(); assertEquals(size, f.length()); } } } } }
Clean up new test method.
commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/test/FileNameTests.java
Clean up new test method.
<ide><path>ommons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/test/FileNameTests.java <ide> */ <ide> @Test <ide> public void testLocalFile() throws Exception { <del> final String prefix = new String(new char[] { '\u0074', '\u0065', '\u0074' }); <del> final File f = File.createTempFile(prefix + "-", "-" + prefix); <del> assertTrue(f.exists()); <del> <del> final URI uri = f.toURI(); <del> <del> try (final FileSystemManager m = VFS.getManager()) { <del> try (final FileObject s = m.resolveFile(uri)) { <del> try (final FileContent sourceContent = s.getContent()) { <del> final long size = sourceContent.getSize(); <del> assertEquals(size, f.length()); <add> final String prefix = new String("\u0074\u0065\u0074"); <add> final File file = File.createTempFile(prefix + "-", "-" + prefix); <add> assertTrue(file.exists()); <add> final URI uri = file.toURI(); <add> try (final FileSystemManager manager = getManager()) { <add> try (final FileObject fileObject = manager.resolveFile(uri)) { <add> try (final FileContent sourceContent = fileObject.getContent()) { <add> assertEquals(sourceContent.getSize(), file.length()); <ide> } <ide> } <ide> }
JavaScript
mit
d8ebde24db4d6e7dccf3d1f87a9d0ea128d8b60f
0
leftiness/angular-gulp-browserify-starter,goodbomb/angular-gulp-browserify-starter,agurha/angular-gulp-browserify-starter,parikmaher534/angular-gulp-browserify-starter,leftiness/angular-gulp-browserify-starter,parikmaher534/angular-gulp-browserify-starter,agurha/angular-gulp-browserify-starter,psimyn/angular-gulp-browserify-starter,psimyn/angular-gulp-browserify-starter,parikmaher534/angular-gulp-browserify-starter,goodbomb/angular-gulp-browserify-starter
// Karma configuration var istanbul = require('browserify-istanbul'); 'use strict'; module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['browserify', 'mocha', 'chai', 'sinon'], // list of files / patterns to load in the browser files: [ './libs/angular/angular.js', './libs/angular-mocks/angular-mocks.js', // for angular.mock.module and inject. './app/**/*.js' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { './app/**/!(*spec)*.js': ['browserify'] }, // karma-browserify configuration browserify: { debug: true, transform: ['debowerify', 'html2js-browserify', istanbul({ 'ignore': ['**/*.spec.js', '**/libs/**'] })], // don't forget to register the extensions extensions: ['.js'] }, // test results reporter to use // possible values: 'dots', 'progress', 'spec' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['spec', 'coverage'], coverageReporter: { type: 'html', dir: './reports/coverage' }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ // 'Chrome', 'PhantomJS' ], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
karma.conf.js
// Karma configuration var istanbul = require('browserify-istanbul'); 'use strict'; module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['browserify', 'mocha', 'chai', 'sinon'], // list of files / patterns to load in the browser files: [ './libs/angular/angular.js', './libs/angular-mocks/angular-mocks.js', // for angular.mock.module and inject. './app/**/*.js' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { './app/**/!(*spec)*.js': ['browserify'] }, // karma-browserify configuration browserify: { debug: true, transform: ['debowerify', 'html2js-browserify', istanbul({ 'ignore': ['**/*.spec.js', '**/libs/**'] })], // don't forget to register the extensions extensions: ['.js'] }, // test results reporter to use // possible values: 'dots', 'progress', 'spec' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['spec', 'coverage'], coverageReporter: { type: 'html', dir: './reports/coverage' }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ // 'Chrome', 'PhantomJS' ], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
Fix 2 spaces -> 4 spaces
karma.conf.js
Fix 2 spaces -> 4 spaces
<ide><path>arma.conf.js <ide> browserify: { <ide> debug: true, <ide> transform: ['debowerify', 'html2js-browserify', istanbul({ <del> 'ignore': ['**/*.spec.js', '**/libs/**'] <add> 'ignore': ['**/*.spec.js', '**/libs/**'] <ide> })], <ide> <ide> // don't forget to register the extensions
Java
apache-2.0
4a26ebaed7975bfcbc4700f43a381f51afdacc06
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
/* * 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.shardingsphere.shardingjdbc.jdbc.core.datasource; import lombok.Getter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.shardingsphere.api.config.encryptor.EncryptRuleConfiguration; import org.apache.shardingsphere.core.metadata.table.ColumnMetaData; import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData; import org.apache.shardingsphere.core.metadata.table.TableMetaData; import org.apache.shardingsphere.core.rule.EncryptRule; import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.metadata.CachedDatabaseMetaData; import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Encrypt data source. * * @author panjuan */ @Getter @Slf4j public class EncryptDataSource extends AbstractUnsupportedOperationDataSource implements AutoCloseable { private final DataSource dataSource; private final DatabaseMetaData cachedDatabaseMetaData; private final EncryptRule encryptRule; private final ShardingTableMetaData encryptTableMetaData; @SneakyThrows public EncryptDataSource(final DataSource dataSource, final EncryptRuleConfiguration encryptRuleConfiguration) { this.dataSource = dataSource; cachedDatabaseMetaData = createCachedDatabaseMetaData(dataSource); encryptRule = new EncryptRule(encryptRuleConfiguration); } private DatabaseMetaData createCachedDatabaseMetaData(final DataSource dataSource) throws SQLException { try (Connection connection = dataSource.getConnection()) { return new CachedDatabaseMetaData(connection.getMetaData()); } } @SneakyThrows private ShardingTableMetaData createEncryptTableMetaData() { Map<String, TableMetaData> tables = new LinkedHashMap<>(); for (String each : encryptRule.getEncryptTableNames()) { try (Connection connection = dataSource.getConnection()) { tables.put(each, new TableMetaData(getColumnMetaDataList(connection, ))) } } } private List<ColumnMetaData> getColumnMetaDataList(final Connection connection, final String tableName) throws SQLException { List<ColumnMetaData> result = new LinkedList<>(); Collection<String> primaryKeys = getPrimaryKeys(connection, tableName); try (ResultSet resultSet = connection.getMetaData().getColumns(connection.getCatalog(), null, tableName, "%")) { while (resultSet.next()) { String columnName = resultSet.getString("COLUMN_NAME"); String columnType = resultSet.getString("TYPE_NAME"); result.add(new ColumnMetaData(columnName, columnType, primaryKeys.contains(columnName))); } } return result; } private Collection<String> getPrimaryKeys(final Connection connection, final String tableName) throws SQLException { Collection<String> result = new HashSet<>(); try (ResultSet resultSet = connection.getMetaData().getPrimaryKeys(connection.getCatalog(), null, tableName)) { while (resultSet.next()) { result.add(resultSet.getString("COLUMN_NAME")); } } return result; } @Override @SneakyThrows public final Connection getConnection() { cachedDatabaseMetaData.getColumns() return dataSource.getConnection(); } }
sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/EncryptDataSource.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.shardingsphere.shardingjdbc.jdbc.core.datasource; import lombok.Getter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.shardingsphere.api.config.encryptor.EncryptRuleConfiguration; import org.apache.shardingsphere.core.metadata.table.ColumnMetaData; import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData; import org.apache.shardingsphere.core.metadata.table.TableMetaData; import org.apache.shardingsphere.core.rule.EncryptRule; import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.metadata.CachedDatabaseMetaData; import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Encrypt data source. * * @author panjuan */ @Getter @Slf4j public class EncryptDataSource extends AbstractUnsupportedOperationDataSource implements AutoCloseable { private final DataSource dataSource; private final DatabaseMetaData cachedDatabaseMetaData; private final EncryptRule encryptRule; private final ShardingTableMetaData encryptTableMetaData; @SneakyThrows public EncryptDataSource(final DataSource dataSource, final EncryptRuleConfiguration encryptRuleConfiguration) { this.dataSource = dataSource; cachedDatabaseMetaData = createCachedDatabaseMetaData(dataSource); encryptRule = new EncryptRule(encryptRuleConfiguration); } private DatabaseMetaData createCachedDatabaseMetaData(final DataSource dataSource) throws SQLException { try (Connection connection = dataSource.getConnection()) { return new CachedDatabaseMetaData(connection.getMetaData()); } } @SneakyThrows private ShardingTableMetaData createEncryptTableMetaData() { Map<String, TableMetaData> tables = new LinkedHashMap<>(); for (String each : encryptRule.getEncryptTableNames()) { try (Connection connection = dataSource.getConnection()) { tables.put(each, new TableMetaData(getColumnMetaDataList(connection, ))) } } } private List<ColumnMetaData> getColumnMetaDataList(final Connection connection, final String tableName) throws SQLException { List<ColumnMetaData> result = new LinkedList<>(); Collection<String> primaryKeys = getPrimaryKeys(connection, tableName); try (ResultSet resultSet = connection.getMetaData().getColumns(connection.getCatalog(), null, tableName, "%")) { while (resultSet.next()) { String columnName = resultSet.getString("COLUMN_NAME"); String columnType = resultSet.getString("TYPE_NAME"); result.add(new ColumnMetaData(columnName, columnType, primaryKeys.contains(columnName))); } } return result; } private Collection<String> getPrimaryKeys(final Connection connection, final String tableName) throws SQLException { Collection<String> result = new HashSet<>(); try (ResultSet resultSet = connection.getMetaData().getPrimaryKeys(catalog, null, tableName)) { while (resultSet.next()) { result.add(resultSet.getString("COLUMN_NAME")); } } return result; } @Override @SneakyThrows public final Connection getConnection() { cachedDatabaseMetaData.getColumns() return dataSource.getConnection(); } }
getPrimaryKeys()
sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/EncryptDataSource.java
getPrimaryKeys()
<ide><path>harding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/EncryptDataSource.java <ide> <ide> private Collection<String> getPrimaryKeys(final Connection connection, final String tableName) throws SQLException { <ide> Collection<String> result = new HashSet<>(); <del> try (ResultSet resultSet = connection.getMetaData().getPrimaryKeys(catalog, null, tableName)) { <add> try (ResultSet resultSet = connection.getMetaData().getPrimaryKeys(connection.getCatalog(), null, tableName)) { <ide> while (resultSet.next()) { <ide> result.add(resultSet.getString("COLUMN_NAME")); <ide> }
Java
apache-2.0
82aa25adb1765c04294971c3905c5cc9e36ef82f
0
krmahadevan/testng,emopers/testng,cbeust/testng,missedone/testng,cbeust/testng,krmahadevan/testng,emopers/testng,emopers/testng,missedone/testng,emopers/testng,krmahadevan/testng,cbeust/testng,krmahadevan/testng,emopers/testng,cbeust/testng,krmahadevan/testng,missedone/testng,missedone/testng,cbeust/testng,missedone/testng
package org.testng.internal; import org.testng.ITestNGMethod; import org.testng.collections.Lists; import org.testng.collections.Maps; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This class wraps access to beforeGroups and afterGroups methods, * since they are passed around the various invokers and potentially * modified in different threads. * * @since 5.3 (Mar 2, 2006) */ public class ConfigurationGroupMethods { /** The list of beforeGroups methods keyed by the name of the group */ private final Map<String, List<ITestNGMethod>> m_beforeGroupsMethods; /** The list of afterGroups methods keyed by the name of the group */ private final Map<String, List<ITestNGMethod>> m_afterGroupsMethods; /** The list of all test methods */ private final ITestNGMethod[] m_allMethods; /**A map that returns the last method belonging to the given group */ private volatile Map<String, List<ITestNGMethod>> m_afterGroupsMap = null; public ConfigurationGroupMethods(ITestNGMethod[] allMethods, Map<String, List<ITestNGMethod>> beforeGroupsMethods, Map<String, List<ITestNGMethod>> afterGroupsMethods) { m_allMethods = allMethods; m_beforeGroupsMethods = new ConcurrentHashMap<>(beforeGroupsMethods); m_afterGroupsMethods = new ConcurrentHashMap<>(afterGroupsMethods); } public ITestNGMethod[] getAllTestMethods() { return this.m_allMethods; } public Map<String, List<ITestNGMethod>> getBeforeGroupsMethods() { return m_beforeGroupsMethods; } public Map<String, List<ITestNGMethod>> getAfterGroupsMethods() { return m_afterGroupsMethods; } /** * @return true if the passed method is the last to run for the group. * This method is used to figure out when is the right time to invoke * afterGroups methods. */ public boolean isLastMethodForGroup(String group, ITestNGMethod method) { // If we have more invocation to do, this is not the last one yet if(method.hasMoreInvocation()) { return false; } // Lazy initialization since we might never be called if(m_afterGroupsMap == null) { synchronized (this) { if (m_afterGroupsMap == null) { m_afterGroupsMap = initializeAfterGroupsMap(); } } } List<ITestNGMethod> methodsInGroup= m_afterGroupsMap.get(group); if(null == methodsInGroup || methodsInGroup.isEmpty()) { return false; } methodsInGroup.remove(method); // Note: == is not good enough here as we may work with ITestNGMethod clones return methodsInGroup.isEmpty(); } private Map<String, List<ITestNGMethod>> initializeAfterGroupsMap() { Map<String, List<ITestNGMethod>> result= Maps.newConcurrentMap(); for(ITestNGMethod m : m_allMethods) { String[] groups= m.getGroups(); for(String g : groups) { List<ITestNGMethod> methodsInGroup= result.get(g); if(null == methodsInGroup) { methodsInGroup= Lists.newArrayList(); result.put(g, methodsInGroup); } methodsInGroup.add(m); } } return result; } public void removeBeforeMethod(String group, ITestNGMethod method) { List<ITestNGMethod> methods= m_beforeGroupsMethods.get(group); if(methods != null) { Object success= methods.remove(method); if(success == null) { log("Couldn't remove beforeGroups method " + method + " for group " + group); } } else { log("Couldn't find any beforeGroups method for group " + group); } } private void log(String string) { Utils.log("ConfigurationGroupMethods", 2, string); } public Map<String, List<ITestNGMethod>> getBeforeGroupsMap() { return m_beforeGroupsMethods; } public Map<String, List<ITestNGMethod>> getAfterGroupsMap() { return m_afterGroupsMethods; } public void removeBeforeGroups(String[] groups) { for(String group : groups) { // log("Removing before group " + group); m_beforeGroupsMethods.remove(group); } } public void removeAfterGroups(Collection<String> groups) { for(String group : groups) { // log("Removing before group " + group); m_afterGroupsMethods.remove(group); } } }
src/main/java/org/testng/internal/ConfigurationGroupMethods.java
package org.testng.internal; import org.testng.ITestNGMethod; import org.testng.collections.Lists; import org.testng.collections.Maps; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This class wraps access to beforeGroups and afterGroups methods, * since they are passed around the various invokers and potentially * modified in different threads. * * @since 5.3 (Mar 2, 2006) */ public class ConfigurationGroupMethods { /** The list of beforeGroups methods keyed by the name of the group */ private final Map<String, List<ITestNGMethod>> m_beforeGroupsMethods; /** The list of afterGroups methods keyed by the name of the group */ private final Map<String, List<ITestNGMethod>> m_afterGroupsMethods; /** The list of all test methods */ private final ITestNGMethod[] m_allMethods; /**A map that returns the last method belonging to the given group */ private Map<String, List<ITestNGMethod>> m_afterGroupsMap = null; public ConfigurationGroupMethods(ITestNGMethod[] allMethods, Map<String, List<ITestNGMethod>> beforeGroupsMethods, Map<String, List<ITestNGMethod>> afterGroupsMethods) { m_allMethods = allMethods; m_beforeGroupsMethods = new ConcurrentHashMap<>(beforeGroupsMethods); m_afterGroupsMethods = new ConcurrentHashMap<>(afterGroupsMethods); } public ITestNGMethod[] getAllTestMethods() { return this.m_allMethods; } public Map<String, List<ITestNGMethod>> getBeforeGroupsMethods() { return m_beforeGroupsMethods; } public Map<String, List<ITestNGMethod>> getAfterGroupsMethods() { return m_afterGroupsMethods; } /** * @return true if the passed method is the last to run for the group. * This method is used to figure out when is the right time to invoke * afterGroups methods. */ public boolean isLastMethodForGroup(String group, ITestNGMethod method) { // If we have more invocation to do, this is not the last one yet if(method.hasMoreInvocation()) { return false; } // Lazy initialization since we might never be called if(m_afterGroupsMap == null) { synchronized (this) { if (m_afterGroupsMap == null) { m_afterGroupsMap = initializeAfterGroupsMap(); } } } List<ITestNGMethod> methodsInGroup= m_afterGroupsMap.get(group); if(null == methodsInGroup || methodsInGroup.isEmpty()) { return false; } methodsInGroup.remove(method); // Note: == is not good enough here as we may work with ITestNGMethod clones return methodsInGroup.isEmpty(); } private Map<String, List<ITestNGMethod>> initializeAfterGroupsMap() { Map<String, List<ITestNGMethod>> result= Maps.newConcurrentMap(); for(ITestNGMethod m : m_allMethods) { String[] groups= m.getGroups(); for(String g : groups) { List<ITestNGMethod> methodsInGroup= result.get(g); if(null == methodsInGroup) { methodsInGroup= Lists.newArrayList(); result.put(g, methodsInGroup); } methodsInGroup.add(m); } } return result; } public void removeBeforeMethod(String group, ITestNGMethod method) { List<ITestNGMethod> methods= m_beforeGroupsMethods.get(group); if(methods != null) { Object success= methods.remove(method); if(success == null) { log("Couldn't remove beforeGroups method " + method + " for group " + group); } } else { log("Couldn't find any beforeGroups method for group " + group); } } private void log(String string) { Utils.log("ConfigurationGroupMethods", 2, string); } public Map<String, List<ITestNGMethod>> getBeforeGroupsMap() { return m_beforeGroupsMethods; } public Map<String, List<ITestNGMethod>> getAfterGroupsMap() { return m_afterGroupsMethods; } public void removeBeforeGroups(String[] groups) { for(String group : groups) { // log("Removing before group " + group); m_beforeGroupsMethods.remove(group); } } public void removeAfterGroups(Collection<String> groups) { for(String group : groups) { // log("Removing before group " + group); m_afterGroupsMethods.remove(group); } } }
Implement the DCL locking properly.
src/main/java/org/testng/internal/ConfigurationGroupMethods.java
Implement the DCL locking properly.
<ide><path>rc/main/java/org/testng/internal/ConfigurationGroupMethods.java <ide> private final ITestNGMethod[] m_allMethods; <ide> <ide> /**A map that returns the last method belonging to the given group */ <del> private Map<String, List<ITestNGMethod>> m_afterGroupsMap = null; <add> private volatile Map<String, List<ITestNGMethod>> m_afterGroupsMap = null; <ide> <ide> public ConfigurationGroupMethods(ITestNGMethod[] allMethods, <ide> Map<String, List<ITestNGMethod>> beforeGroupsMethods,
JavaScript
mit
a93fee98561a8f553fbcb4952a2ab533afc26f71
0
u-wave/api-v1
import Promise from 'bluebird'; import { createCommand } from '../sockets'; import { NotFoundError, PermissionError } from '../errors'; export async function isEmpty(uw) { return !(await uw.redis.get('booth:historyID')); } export async function getBooth(uw) { const History = uw.model('History'); const historyID = await uw.redis.get('booth:historyID'); const historyEntry = await History.findById(historyID) .populate('media.media'); if (!historyEntry || !historyEntry.user) { return null; } const stats = await Promise.props({ upvotes: uw.redis.smembers('booth:upvotes'), downvotes: uw.redis.smembers('booth:downvotes'), favorites: uw.redis.smembers('booth:favorites'), }); return { historyID, playlistID: `${historyEntry.playlist}`, playedAt: Date.parse(historyEntry.playedAt), userID: `${historyEntry.user}`, media: historyEntry.media, stats, }; } export function getCurrentDJ(uw) { return uw.redis.get('booth:currentDJ'); } export function skipBooth(uw, moderatorID, userID, reason, opts = {}) { uw.redis.publish('v1', createCommand('skip', { moderatorID, userID, reason })); uw.advance({ remove: opts.remove === true }); return Promise.resolve(true); } export async function skipIfCurrentDJ(uw, userID) { const currentDJ = await getCurrentDJ(uw); if (userID === currentDJ) { await uw.advance({ remove: true }); } } export async function replaceBooth(uw, moderatorID, id) { let waitlist = await uw.redis.lrange('waitlist', 0, -1); if (!waitlist.length) throw new NotFoundError('Waitlist is empty.'); if (waitlist.some(userID => userID === id)) { uw.redis.lrem('waitlist', 1, id); await uw.redis.lpush('waitlist', id); waitlist = await uw.redis.lrange('waitlist', 0, -1); } uw.redis.publish('v1', createCommand('boothReplace', { moderatorID, userID: id, })); uw.advance(); return waitlist; } async function addVote(uw, userID, direction) { await Promise.all([ uw.redis.srem('booth:upvotes', userID), uw.redis.srem('booth:downvotes', userID), ]); await uw.redis.sadd( direction > 0 ? 'booth:upvotes' : 'booth:downvotes', userID, ); uw.publish('booth:vote', { userID, direction, }); } export async function vote(uw, userID, direction) { const currentDJ = await uw.redis.get('booth:currentDJ'); if (currentDJ !== null && currentDJ !== userID) { const historyID = await uw.redis.get('booth:historyID'); if (historyID === null) return; if (direction > 0) { const upvoted = await uw.redis.sismember('booth:upvotes', userID); if (!upvoted) { await addVote(uw, userID, 1); } } else { const downvoted = await uw.redis.sismember('booth:downvotes', userID); if (!downvoted) { await addVote(uw, userID, -1); } } } } export async function favorite(uw, id, playlistID, historyID) { const Playlist = uw.model('Playlist'); const PlaylistItem = uw.model('PlaylistItem'); const History = uw.model('History'); const historyEntry = await History.findById(historyID) .populate('media.media'); if (!historyEntry) { throw new NotFoundError('History entry not found.'); } if (`${historyEntry.user}` === id) { throw new PermissionError('You can\'t favorite your own plays.'); } const playlist = await Playlist.findById(playlistID); if (!playlist) throw new NotFoundError('Playlist not found.'); if (`${playlist.author}` !== id) { throw new PermissionError('You can\'t edit another user\'s playlist.'); } // `.media` has the same shape as `.item`, but is guaranteed to exist and have // the same properties as when the playlist item was actually played. const playlistItem = new PlaylistItem(historyEntry.media.toJSON()); await playlistItem.save(); playlist.media.push(playlistItem.id); await uw.redis.sadd('booth:favorites', id); uw.redis.publish('v1', createCommand('favorite', { userID: id, playlistID, })); await playlist.save(); return { playlistSize: playlist.media.length, added: [playlistItem], }; } export function getHistory(uw, pagination) { return uw.getHistory(pagination); }
src/controllers/booth.js
import Promise from 'bluebird'; import { createCommand } from '../sockets'; import { NotFoundError, PermissionError } from '../errors'; export async function isEmpty(uw) { return !(await uw.redis.get('booth:historyID')); } export async function getBooth(uw) { const History = uw.model('History'); const historyID = await uw.redis.get('booth:historyID'); const historyEntry = await History.findById(historyID) .populate('media.media'); if (!historyEntry || !historyEntry.user) { return null; } const stats = await Promise.props({ upvotes: uw.redis.lrange('booth:upvotes', 0, -1), downvotes: uw.redis.lrange('booth:downvotes', 0, -1), favorites: uw.redis.lrange('booth:favorites', 0, -1), }); return { historyID, playlistID: `${historyEntry.playlist}`, playedAt: Date.parse(historyEntry.playedAt), userID: `${historyEntry.user}`, media: historyEntry.media, stats, }; } export function getCurrentDJ(uw) { return uw.redis.get('booth:currentDJ'); } export function skipBooth(uw, moderatorID, userID, reason, opts = {}) { uw.redis.publish('v1', createCommand('skip', { moderatorID, userID, reason })); uw.advance({ remove: opts.remove === true }); return Promise.resolve(true); } export async function skipIfCurrentDJ(uw, userID) { const currentDJ = await getCurrentDJ(uw); if (userID === currentDJ) { await uw.advance({ remove: true }); } } export async function replaceBooth(uw, moderatorID, id) { let waitlist = await uw.redis.lrange('waitlist', 0, -1); if (!waitlist.length) throw new NotFoundError('Waitlist is empty.'); if (waitlist.some(userID => userID === id)) { uw.redis.lrem('waitlist', 1, id); await uw.redis.lpush('waitlist', id); waitlist = await uw.redis.lrange('waitlist', 0, -1); } uw.redis.publish('v1', createCommand('boothReplace', { moderatorID, userID: id, })); uw.advance(); return waitlist; } async function addVote(uw, userID, direction) { await Promise.all([ uw.redis.lrem('booth:upvotes', 0, userID), uw.redis.lrem('booth:downvotes', 0, userID), ]); await uw.redis.lpush( direction > 0 ? 'booth:upvotes' : 'booth:downvotes', userID, ); uw.publish('booth:vote', { userID, direction, }); } export async function vote(uw, userID, direction) { const currentDJ = await uw.redis.get('booth:currentDJ'); if (currentDJ !== null && currentDJ !== userID) { const historyID = await uw.redis.get('booth:historyID'); if (historyID === null) return; if (direction > 0) { const upvoted = await uw.redis.lrange('booth:upvotes', 0, -1); if (upvoted.indexOf(userID) === -1) { await addVote(uw, userID, 1); } } else { const downvoted = await uw.redis.lrange('booth:downvotes', 0, -1); if (downvoted.indexOf(userID) === -1) { await addVote(uw, userID, -1); } } } } export async function favorite(uw, id, playlistID, historyID) { const Playlist = uw.model('Playlist'); const PlaylistItem = uw.model('PlaylistItem'); const History = uw.model('History'); const historyEntry = await History.findById(historyID) .populate('media.media'); if (!historyEntry) { throw new NotFoundError('History entry not found.'); } if (`${historyEntry.user}` === id) { throw new PermissionError('You can\'t favorite your own plays.'); } const playlist = await Playlist.findById(playlistID); if (!playlist) throw new NotFoundError('Playlist not found.'); if (`${playlist.author}` !== id) { throw new PermissionError('You can\'t edit another user\'s playlist.'); } // `.media` has the same shape as `.item`, but is guaranteed to exist and have // the same properties as when the playlist item was actually played. const playlistItem = new PlaylistItem(historyEntry.media.toJSON()); await playlistItem.save(); playlist.media.push(playlistItem.id); uw.redis.lrem('booth:favorites', 0, id); uw.redis.lpush('booth:favorites', id); uw.redis.publish('v1', createCommand('favorite', { userID: id, playlistID, })); await playlist.save(); return { playlistSize: playlist.media.length, added: [playlistItem], }; } export function getHistory(uw, pagination) { return uw.getHistory(pagination); }
booth: Use a Set to store votes, fix occasional duplicates (#159)
src/controllers/booth.js
booth: Use a Set to store votes, fix occasional duplicates (#159)
<ide><path>rc/controllers/booth.js <ide> } <ide> <ide> const stats = await Promise.props({ <del> upvotes: uw.redis.lrange('booth:upvotes', 0, -1), <del> downvotes: uw.redis.lrange('booth:downvotes', 0, -1), <del> favorites: uw.redis.lrange('booth:favorites', 0, -1), <add> upvotes: uw.redis.smembers('booth:upvotes'), <add> downvotes: uw.redis.smembers('booth:downvotes'), <add> favorites: uw.redis.smembers('booth:favorites'), <ide> }); <ide> <ide> return { <ide> <ide> async function addVote(uw, userID, direction) { <ide> await Promise.all([ <del> uw.redis.lrem('booth:upvotes', 0, userID), <del> uw.redis.lrem('booth:downvotes', 0, userID), <add> uw.redis.srem('booth:upvotes', userID), <add> uw.redis.srem('booth:downvotes', userID), <ide> ]); <del> await uw.redis.lpush( <add> await uw.redis.sadd( <ide> direction > 0 ? 'booth:upvotes' : 'booth:downvotes', <ide> userID, <ide> ); <ide> const historyID = await uw.redis.get('booth:historyID'); <ide> if (historyID === null) return; <ide> if (direction > 0) { <del> const upvoted = await uw.redis.lrange('booth:upvotes', 0, -1); <del> if (upvoted.indexOf(userID) === -1) { <add> const upvoted = await uw.redis.sismember('booth:upvotes', userID); <add> if (!upvoted) { <ide> await addVote(uw, userID, 1); <ide> } <ide> } else { <del> const downvoted = await uw.redis.lrange('booth:downvotes', 0, -1); <del> if (downvoted.indexOf(userID) === -1) { <add> const downvoted = await uw.redis.sismember('booth:downvotes', userID); <add> if (!downvoted) { <ide> await addVote(uw, userID, -1); <ide> } <ide> } <ide> <ide> playlist.media.push(playlistItem.id); <ide> <del> uw.redis.lrem('booth:favorites', 0, id); <del> uw.redis.lpush('booth:favorites', id); <add> await uw.redis.sadd('booth:favorites', id); <ide> uw.redis.publish('v1', createCommand('favorite', { <ide> userID: id, <ide> playlistID,
JavaScript
mit
2bc73cb64cbafb0ca746260f7e1a1a44aaac43a7
0
OpenCollective/opencollective-api,OpenCollective/opencollective-api,OpenCollective/opencollective-api
import { expect } from 'chai'; import { Given, When, Then } from 'cucumber'; import * as libtransactions from '../../../../server/lib/transactions'; import * as store from '../stores'; import * as utils from '../../../utils'; Given('a User {string}', async function (name) { const { user, userCollective } = await store.newUser(name); this.addValue(name, userCollective); this.addValue(`${name}-user`, user); }); Given('a User {string} as an {string} to {string}', async function (userName, role, collectiveName) { const { user, userCollective } = await store.newUser(userName); this.addValue(userName, userCollective); this.addValue(`${userName}-user`, user); const collective = this.getValue(collectiveName); collective.addUserWithRole(user, role); }); Given('a Host {string} in {string} and charges {string} of fee', async function (name, currency, fee) { const { hostCollective, hostAdmin } = await store.newHost(name, currency, fee); this.addValue(name, hostCollective); this.addValue(`${name}-admin`, hostAdmin); }); Given('an Organization {string} in {string} administered by {string}', async function (orgName, currency, userName) { const orgAdmin = this.getValue(`${userName}-user`); const organization = await store.newOrganization({ name: orgName, currency }, orgAdmin); this.addValue(orgName, organization); }); Given('a Collective {string} in {string} hosted by {string}', async function (name, currency, hostName) { const hostCollective = this.getValue(hostName); const hostAdmin = this.getValue(`${hostName}-admin`); const { collective } = await store.newCollectiveInHost(name, currency, hostCollective); this.addValue(name, collective); this.addValue(`${name}-host-collective`, hostCollective); this.addValue(`${name}-host-admin`, hostAdmin); }); Given('{string} is hosted by {string}', async function (collectiveName, hostName) { const hostCollective = this.getValue(hostName); const collective = this.getValue(collectiveName); collective.addHost(hostCollective); }); Given('{string} connects a {string} account', async function (hostName, connectedAccountName) { const host = this.getValue(hostName); const hostAdmin = this.getValue(`${hostName}-admin`); const method = { stripe: store.stripeConnectedAccount, }[connectedAccountName.toLowerCase()]; await method(host.id, hostAdmin.id); }); Given('{string} payment processor fee is {string}', async function (ppName, feeStr) { this.addValue(`${ppName.toLowerCase()}-payment-provider-fee`, feeStr); }); Given('platform fee is {string}', async function (feeStr) { this.addValue(`platform-fee`, feeStr); }); async function handleDonation (fromName, value, toName, paymentMethod, userName=null) { const [ amountStr, currency ] = value.split(' '); const amount = parseInt(amountStr); const user = !userName ? this.getValue(`${userName ? userName : fromName}-user`) : this.getValue(`${fromName}-user`); const userCollective = this.getValue(fromName); const collective = this.getValue(toName); /* Retrieve fees that may or may not have been set */ const paymentMethodName = paymentMethod.toLowerCase(); const ppFee = utils.readFee(amount, this.getValue(`${paymentMethodName}-payment-provider-fee`)); const appFee = utils.readFee(amount, this.getValue('platform-fee')); /* Use the appropriate stub to execute the order */ const method = { stripe: store.stripeOneTimeDonation, }[paymentMethodName]; if (!method) throw new Error(`Payment Method ${paymentMethod} doesn't exist`); return method({ user, userCollective, collective, currency, amount, appFee, ppFee, }); } When('{string} donates {string} to {string} via {string}', handleDonation); When('{string} donates {string} to {string} via {string} as {string}', handleDonation); Then('{string} should have contributed {string} to {string}', async function(userName, value, collectiveName) { const [ amount, currency ] = value.split(' '); const userCollective = this.getValue(userName); const collective = this.getValue(collectiveName); /* Doesn't ever sum up different currencies */ const userToCollectiveAmount = await libtransactions.sum({ FromCollectiveId: userCollective.id, CollectiveId: collective.id, currency, type: 'CREDIT', }); expect(userToCollectiveAmount).to.equal(parseInt(amount)); }); Then('{string} should have {string} in their balance', async function(collectiveName, value) { const [ amount, currency ] = value.split(' '); const collective = this.getValue(collectiveName); /* Doesn't ever sum up different currencies */ const userToCollectiveAmount = await libtransactions.sum({ CollectiveId: collective.id, currency, }); expect(userToCollectiveAmount).to.equal(parseInt(amount)); });
test/features/support/steps/users-and-collectives.js
import { expect } from 'chai'; import { Given, When, Then } from 'cucumber'; import * as libtransactions from '../../../../server/lib/transactions'; import * as store from '../stores'; import * as utils from '../../../utils'; Given('a User {string}', async function (name) { const { user, userCollective } = await store.newUser(name); this.addValue(name, userCollective); this.addValue(`${name}-user`, user); }); Given('a User {string} as an {string} to {string}', async function (userName, role, collectiveName) { const { user, userCollective } = await store.newUser(userName); this.addValue(userName, userCollective); this.addValue(`${userName}-user`, user); const collective = this.getValue(collectiveName); collective.addUserWithRole(user, role); }); Given('a Host {string} in {string} and charges {string} of fee', async function (name, currency, fee) { const { hostCollective, hostAdmin } = await store.newHost(name, currency, fee); this.addValue(name, hostCollective); this.addValue(`${name}-admin`, hostAdmin); }); Given('an Organization {string} in {string} administered by {string}', async function (orgName, currency, userName) { const orgAdmin = this.getValue(`${userName}-user`); const organization = await store.newOrganization({ name: orgName, currency }, orgAdmin); this.addValue(orgName, organization); }); Given('a Collective {string} in {string} hosted by {string}', async function (name, currency, hostName) { const hostCollective = this.getValue(hostName); const hostAdmin = this.getValue(`${hostName}-admin`); const { collective } = await store.newCollectiveInHost(name, currency, hostCollective); this.addValue(name, collective); this.addValue(`${name}-host-collective`, hostCollective); this.addValue(`${name}-host-admin`, hostAdmin); }); Given('{string} is hosted by {string}', async function (collectiveName, hostName) { const hostCollective = this.getValue(hostName); const collective = this.getValue(collectiveName); collective.addHost(hostCollective); }); Given('{string} connects a {string} account', async function (hostName, connectedAccountName) { const host = this.getValue(hostName); const hostAdmin = this.getValue(`${hostName}-admin`); const method = { stripe: store.stripeConnectedAccount, }[connectedAccountName.toLowerCase()]; await method(host.id, hostAdmin.id); }); Given('{string} payment processor fee is {string}', async function (ppName, feeStr) { this.addValue(`${ppName.toLowerCase()}-payment-provider-fee`, feeStr); }); Given('platform fee is {string}', async function (feeStr) { this.addValue(`platform-fee`, feeStr); }); async function handleDonation (fromName, value, toName, paymentMethod, userName) { const [ amountStr, currency ] = value.split(' '); const amount = parseInt(amountStr); const user = this.getValue(`${userName ? userName : fromName}-user`); const userCollective = this.getValue(fromName); const collective = this.getValue(toName); /* Retrieve fees that may or may not have been set */ const paymentMethodName = paymentMethod.toLowerCase(); const ppFee = utils.readFee(amount, this.getValue(`${paymentMethodName}-payment-provider-fee`)); const appFee = utils.readFee(amount, this.getValue('platform-fee')); /* Use the appropriate stub to execute the order */ const method = { stripe: store.stripeOneTimeDonation, }[paymentMethodName]; if (!method) throw new Error(`Payment Method ${paymentMethod} doesn't exist`); return method({ user, userCollective, collective, currency, amount, appFee, ppFee, }); } When('{string} donates {string} to {string} via {string}', handleDonation); When('{string} donates {string} to {string} via {string} as {string}', handleDonation); Then('{string} should have contributed {string} to {string}', async function(userName, value, collectiveName) { const [ amount, currency ] = value.split(' '); const userCollective = this.getValue(userName); const collective = this.getValue(collectiveName); /* Doesn't ever sum up different currencies */ const userToCollectiveAmount = await libtransactions.sum({ FromCollectiveId: userCollective.id, CollectiveId: collective.id, currency, type: 'CREDIT', }); expect(userToCollectiveAmount).to.equal(parseInt(amount)); }); Then('{string} should have {string} in their balance', async function(collectiveName, value) { const [ amount, currency ] = value.split(' '); const collective = this.getValue(collectiveName); /* Doesn't ever sum up different currencies */ const userToCollectiveAmount = await libtransactions.sum({ CollectiveId: collective.id, currency, }); expect(userToCollectiveAmount).to.equal(parseInt(amount)); });
chore(bdd): User is optional for handleDonation step handler
test/features/support/steps/users-and-collectives.js
chore(bdd): User is optional for handleDonation step handler
<ide><path>est/features/support/steps/users-and-collectives.js <ide> this.addValue(`platform-fee`, feeStr); <ide> }); <ide> <del>async function handleDonation (fromName, value, toName, paymentMethod, userName) { <add>async function handleDonation (fromName, value, toName, paymentMethod, userName=null) { <ide> const [ amountStr, currency ] = value.split(' '); <ide> const amount = parseInt(amountStr); <del> const user = this.getValue(`${userName ? userName : fromName}-user`); <add> const user = !userName <add> ? this.getValue(`${userName ? userName : fromName}-user`) <add> : this.getValue(`${fromName}-user`); <ide> const userCollective = this.getValue(fromName); <ide> const collective = this.getValue(toName); <ide> /* Retrieve fees that may or may not have been set */
Java
apache-2.0
a4c49ddb6f172819e80a4e2a96b734eeac66758b
0
solomonronald/SalesforceMobileSDK-Android,solomonronald/SalesforceMobileSDK-Android,kchitalia/SalesforceMobileSDK-Android,solomonronald/SalesforceMobileSDK-Android,kchitalia/SalesforceMobileSDK-Android,huminzhi/SalesforceMobileSDK-Android,huminzhi/SalesforceMobileSDK-Android,huminzhi/SalesforceMobileSDK-Android,kchitalia/SalesforceMobileSDK-Android
/* * Copyright (c) 2014-2015, salesforce.com, inc. * All rights reserved. * Redistribution and use of this software 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 name of salesforce.com, inc. nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission of salesforce.com, inc. * 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 OWNER 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 com.salesforce.androidsdk.smartstore.store; import java.io.File; import java.io.FilenameFilter; import java.util.HashMap; import java.util.Map; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteDatabaseHook; import net.sqlcipher.database.SQLiteOpenHelper; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.salesforce.androidsdk.accounts.UserAccount; /** * Helper class to manage SmartStore's database creation and version management. */ public class DBOpenHelper extends SQLiteOpenHelper { // 1 --> up until 2.3 // 2 --> starting at 2.3 (new meta data table long_operations_status) public static final int DB_VERSION = 2; public static final String DEFAULT_DB_NAME = "smartstore"; private static final String DB_NAME_SUFFIX = ".db"; private static final String ORG_KEY_PREFIX = "00D"; /* * Cache for the helper instances */ private static Map<String, DBOpenHelper> openHelpers = new HashMap<String, DBOpenHelper>(); /** * Returns a map of all DBOpenHelper instances created. The key is the * database name and the value is the instance itself. * * @return Map of DBOpenHelper instances. */ public static synchronized Map<String, DBOpenHelper> getOpenHelpers() { return openHelpers; } /** * Returns the DBOpenHelper instance associated with this user account. * * @param ctx Context. * @param account User account. * @return DBOpenHelper instance. */ public static synchronized DBOpenHelper getOpenHelper(Context ctx, UserAccount account) { return getOpenHelper(ctx, account, null); } /** * Returns the DBOpenHelper instance associated with this user and community. * * @param ctx Context. * @param account User account. * @param communityId Community ID. * @return DBOpenHelper instance. */ public static synchronized DBOpenHelper getOpenHelper(Context ctx, UserAccount account, String communityId) { return getOpenHelper(ctx, DEFAULT_DB_NAME, account, communityId); } /** * Returns the DBOpenHelper instance for the given database name. * * @param ctx Context. * @param dbNamePrefix The database name. This must be a valid file name without a * filename extension such as ".db". * @param account User account. If this method is called before authentication, * we will simply return the smart store DB, which is not associated * with any user account. Otherwise, we will return a unique * database at the community level. * @param communityId Community ID. * @return DBOpenHelper instance. */ public static DBOpenHelper getOpenHelper(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { final StringBuffer dbName = new StringBuffer(dbNamePrefix); // If we have account information, we will use it to create a database suffix for the user. if (account != null) { // Default user path for a user is 'internal', if community ID is null. final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); DBOpenHelper helper = openHelpers.get(fullDBName); if (helper == null) { helper = new DBOpenHelper(ctx, fullDBName); openHelpers.put(fullDBName, helper); } return helper; } protected DBOpenHelper(Context context, String dbName) { super(context, dbName, null, DB_VERSION, new DBHook()); SQLiteDatabase.loadLibs(context); } @Override public void onCreate(SQLiteDatabase db) { /* * SQLCipher manages locking on the DB at a low level. However, * we explicitly lock on the DB as well, for all SmartStore * operations. This can lead to deadlocks or ReentrantLock * exceptions where a thread is waiting for itself. Hence, we * set the default SQLCipher locking to 'false', since we * manage locking at our level anyway. */ db.setLockingEnabled(false); SmartStore.createMetaTables(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /* * SQLCipher manages locking on the DB at a low level. However, * we explicitly lock on the DB as well, for all SmartStore * operations. This can lead to deadlocks or ReentrantLock * exceptions where a thread is waiting for itself. Hence, we * set the default SQLCipher locking to 'false', since we * manage locking at our level anyway. */ db.setLockingEnabled(false); if (oldVersion == 1) { SmartStore.createLongOperationsStatusTable(db); } } @Override @SuppressWarnings("deprecation") public void onOpen(SQLiteDatabase db) { (new SmartStore(db)).resumeLongOperations(); } /** * Deletes the underlying database for the specified user account. * * @param ctx Context. * @param account User account. */ public static synchronized void deleteDatabase(Context ctx, UserAccount account) { deleteDatabase(ctx, account, null); } /** * Deletes the underlying database for the specified user and community. * * @param ctx Context. * @param account User account. * @param communityId Community ID. */ public static synchronized void deleteDatabase(Context ctx, UserAccount account, String communityId) { deleteDatabase(ctx, DEFAULT_DB_NAME, account, communityId); } /** * Deletes the underlying database for the specified user and community. * * @param ctx Context. * @param dbNamePrefix The database name. This must be a valid file name without a * filename extension such as ".db". * @param account User account. * @param communityId Community ID. */ public static synchronized void deleteDatabase(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { try { final StringBuffer dbName = new StringBuffer(dbNamePrefix); // If we have account information, we will use it to create a database suffix for the user. if (account != null) { // Default user path for a user is 'internal', if community ID is null. final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); // Close and remove the helper from the cache if it exists. final DBOpenHelper helper = openHelpers.get(fullDBName); if (helper != null) { helper.close(); openHelpers.remove(fullDBName); } // Physically delete the database from disk. ctx.deleteDatabase(fullDBName); // If community id was not passed in, then we remove ALL databases for the account. if (account != null && TextUtils.isEmpty(communityId)) { StringBuffer communityDBNamePrefix = new StringBuffer(dbNamePrefix); String accountSuffix = account.getUserLevelFilenameSuffix(); communityDBNamePrefix.append(accountSuffix); deleteFiles(ctx, communityDBNamePrefix.toString()); } } catch (Exception e) { Log.e("DBOpenHelper:deleteDatabase", "Exception occurred while attempting to delete database.", e); } } /** * Deletes all remaining authenticated databases. We pass in the key prefix * for an organization here, because all authenticated DBs will have to * go against an org, which means the org ID will be a part of the DB name. * This prevents the global DBs from being removed. * * @param ctx Context. */ public static synchronized void deleteAllUserDatabases(Context ctx) { deleteFiles(ctx, ORG_KEY_PREFIX); } /** * Determines if a smart store currently exists for the given account and/or community id. * * @param ctx Context. * @param account User account. * @param communityId Community ID. * @return boolean indicating if a smartstore already exists. */ public static boolean smartStoreExists(Context ctx, UserAccount account, String communityId) { return smartStoreExists(ctx, DEFAULT_DB_NAME, account, communityId); } /** * Determines if a smart store currently exists for the given database name, account * and/or community id. * * @param ctx Context. * @param dbNamePrefix The database name. This must be a valid file name without a * filename extension such as ".db". * @param account User account. * @param communityId Community ID. * @return boolean indicating if a smartstore already exists. */ public static boolean smartStoreExists(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { final StringBuffer dbName = new StringBuffer(dbNamePrefix); if (account != null) { final String dbSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(dbSuffix); } dbName.append(DB_NAME_SUFFIX); return ctx.getDatabasePath(dbName.toString()).exists(); } static class DBHook implements SQLiteDatabaseHook { public void preKey(SQLiteDatabase database) { database.execSQL("PRAGMA cipher_default_kdf_iter = '4000'"); // the new default for sqlcipher 3.x (64000) is too slow // also that way we can open 2.x databases without any migration } public void postKey(SQLiteDatabase database) { } }; private static void deleteFiles(Context ctx, String prefix) { final String dbPath = ctx.getApplicationInfo().dataDir + "/databases"; final File dir = new File(dbPath); if (dir != null) { final SmartStoreFileFilter fileFilter = new SmartStoreFileFilter(prefix); final File[] fileList = dir.listFiles(); if (fileList != null) { for (final File file : fileList) { if (file != null && fileFilter.accept(dir, file.getName())) { file.delete(); openHelpers.remove(file.getName()); } } } } } /** * This class acts as a filter to identify only the relevant SmartStore files. * * @author bhariharan */ private static class SmartStoreFileFilter implements FilenameFilter { private String dbNamePrefix; /** * Parameterized constructor. * * @param dbNamePrefix Database name prefix pattern. */ public SmartStoreFileFilter(String dbNamePrefix) { this.dbNamePrefix = dbNamePrefix; } @Override public boolean accept(File dir, String filename) { if (filename != null && filename.contains(dbNamePrefix)) { return true; } return false; } } }
libs/SmartStore/src/com/salesforce/androidsdk/smartstore/store/DBOpenHelper.java
/* * Copyright (c) 2014-2015, salesforce.com, inc. * All rights reserved. * Redistribution and use of this software 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 name of salesforce.com, inc. nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission of salesforce.com, inc. * 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 OWNER 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 com.salesforce.androidsdk.smartstore.store; import java.io.File; import java.io.FilenameFilter; import java.util.HashMap; import java.util.Map; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteDatabaseHook; import net.sqlcipher.database.SQLiteOpenHelper; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.salesforce.androidsdk.accounts.UserAccount; /** * Helper class to manage SmartStore's database creation and version management. */ public class DBOpenHelper extends SQLiteOpenHelper { // 1 --> up until 2.3 // 2 --> starting at 2.3 (new meta data table long_operations_status) public static final int DB_VERSION = 2; public static final String DEFAULT_DB_NAME = "smartstore"; private static final String DB_NAME_SUFFIX = ".db"; private static final String ORG_KEY_PREFIX = "00D"; /* * Cache for the helper instances */ private static Map<String, DBOpenHelper> openHelpers = new HashMap<String, DBOpenHelper>(); /** * Returns a map of all DBOpenHelper instances created. The key is the * database name and the value is the instance itself. * * @return Map of DBOpenHelper instances. */ public static synchronized Map<String, DBOpenHelper> getOpenHelpers() { return openHelpers; } /** * Returns the DBOpenHelper instance associated with this user account. * * @param ctx Context. * @param account User account. * @return DBOpenHelper instance. */ public static synchronized DBOpenHelper getOpenHelper(Context ctx, UserAccount account) { return getOpenHelper(ctx, account, null); } /** * Returns the DBOpenHelper instance associated with this user and community. * * @param ctx Context. * @param account User account. * @param communityId Community ID. * @return DBOpenHelper instance. */ public static synchronized DBOpenHelper getOpenHelper(Context ctx, UserAccount account, String communityId) { return getOpenHelper(ctx, DEFAULT_DB_NAME, account, communityId); } /** * Returns the DBOpenHelper instance for the given database name. * * @param ctx Context. * @param dbNamePrefix The database name. This must be a valid file name without a * filename extension such as ".db". * @param account User account. If this method is called before authentication, * we will simply return the smart store DB, which is not associated * with any user account. Otherwise, we will return a unique * database at the community level. * @param communityId Community ID. * @return DBOpenHelper instance. */ public static DBOpenHelper getOpenHelper(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { final StringBuffer dbName = new StringBuffer(dbNamePrefix); // If we have account information, we will use it to create a database suffix for the user. if (account != null) { // Default user path for a user is 'internal', if community ID is null. final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); DBOpenHelper helper = openHelpers.get(fullDBName); if (helper == null) { helper = new DBOpenHelper(ctx, fullDBName); openHelpers.put(fullDBName, helper); } return helper; } private DBOpenHelper(Context context, String dbName) { super(context, dbName, null, DB_VERSION, new DBHook()); SQLiteDatabase.loadLibs(context); } @Override public void onCreate(SQLiteDatabase db) { /* * SQLCipher manages locking on the DB at a low level. However, * we explicitly lock on the DB as well, for all SmartStore * operations. This can lead to deadlocks or ReentrantLock * exceptions where a thread is waiting for itself. Hence, we * set the default SQLCipher locking to 'false', since we * manage locking at our level anyway. */ db.setLockingEnabled(false); SmartStore.createMetaTables(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /* * SQLCipher manages locking on the DB at a low level. However, * we explicitly lock on the DB as well, for all SmartStore * operations. This can lead to deadlocks or ReentrantLock * exceptions where a thread is waiting for itself. Hence, we * set the default SQLCipher locking to 'false', since we * manage locking at our level anyway. */ db.setLockingEnabled(false); if (oldVersion == 1) { SmartStore.createLongOperationsStatusTable(db); } } @Override @SuppressWarnings("deprecation") public void onOpen(SQLiteDatabase db) { (new SmartStore(db)).resumeLongOperations(); } /** * Deletes the underlying database for the specified user account. * * @param ctx Context. * @param account User account. */ public static synchronized void deleteDatabase(Context ctx, UserAccount account) { deleteDatabase(ctx, account, null); } /** * Deletes the underlying database for the specified user and community. * * @param ctx Context. * @param account User account. * @param communityId Community ID. */ public static synchronized void deleteDatabase(Context ctx, UserAccount account, String communityId) { deleteDatabase(ctx, DEFAULT_DB_NAME, account, communityId); } /** * Deletes the underlying database for the specified user and community. * * @param ctx Context. * @param dbNamePrefix The database name. This must be a valid file name without a * filename extension such as ".db". * @param account User account. * @param communityId Community ID. */ public static synchronized void deleteDatabase(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { try { final StringBuffer dbName = new StringBuffer(dbNamePrefix); // If we have account information, we will use it to create a database suffix for the user. if (account != null) { // Default user path for a user is 'internal', if community ID is null. final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); // Close and remove the helper from the cache if it exists. final DBOpenHelper helper = openHelpers.get(fullDBName); if (helper != null) { helper.close(); openHelpers.remove(fullDBName); } // Physically delete the database from disk. ctx.deleteDatabase(fullDBName); // If community id was not passed in, then we remove ALL databases for the account. if (account != null && TextUtils.isEmpty(communityId)) { StringBuffer communityDBNamePrefix = new StringBuffer(dbNamePrefix); String accountSuffix = account.getUserLevelFilenameSuffix(); communityDBNamePrefix.append(accountSuffix); deleteFiles(ctx, communityDBNamePrefix.toString()); } } catch (Exception e) { Log.e("DBOpenHelper:deleteDatabase", "Exception occurred while attempting to delete database.", e); } } /** * Deletes all remaining authenticated databases. We pass in the key prefix * for an organization here, because all authenticated DBs will have to * go against an org, which means the org ID will be a part of the DB name. * This prevents the global DBs from being removed. * * @param ctx Context. */ public static synchronized void deleteAllUserDatabases(Context ctx) { deleteFiles(ctx, ORG_KEY_PREFIX); } /** * Determines if a smart store currently exists for the given account and/or community id. * * @param ctx Context. * @param account User account. * @param communityId Community ID. * @return boolean indicating if a smartstore already exists. */ public static boolean smartStoreExists(Context ctx, UserAccount account, String communityId) { return smartStoreExists(ctx, DEFAULT_DB_NAME, account, communityId); } /** * Determines if a smart store currently exists for the given database name, account * and/or community id. * * @param ctx Context. * @param dbNamePrefix The database name. This must be a valid file name without a * filename extension such as ".db". * @param account User account. * @param communityId Community ID. * @return boolean indicating if a smartstore already exists. */ public static boolean smartStoreExists(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { final StringBuffer dbName = new StringBuffer(dbNamePrefix); if (account != null) { final String dbSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(dbSuffix); } dbName.append(DB_NAME_SUFFIX); return ctx.getDatabasePath(dbName.toString()).exists(); } static class DBHook implements SQLiteDatabaseHook { public void preKey(SQLiteDatabase database) { database.execSQL("PRAGMA cipher_default_kdf_iter = '4000'"); // the new default for sqlcipher 3.x (64000) is too slow // also that way we can open 2.x databases without any migration } public void postKey(SQLiteDatabase database) { } }; private static void deleteFiles(Context ctx, String prefix) { final String dbPath = ctx.getApplicationInfo().dataDir + "/databases"; final File dir = new File(dbPath); if (dir != null) { final SmartStoreFileFilter fileFilter = new SmartStoreFileFilter(prefix); final File[] fileList = dir.listFiles(); if (fileList != null) { for (final File file : fileList) { if (file != null && fileFilter.accept(dir, file.getName())) { file.delete(); openHelpers.remove(file.getName()); } } } } } /** * This class acts as a filter to identify only the relevant SmartStore files. * * @author bhariharan */ private static class SmartStoreFileFilter implements FilenameFilter { private String dbNamePrefix; /** * Parameterized constructor. * * @param dbNamePrefix Database name prefix pattern. */ public SmartStoreFileFilter(String dbNamePrefix) { this.dbNamePrefix = dbNamePrefix; } @Override public boolean accept(File dir, String filename) { if (filename != null && filename.contains(dbNamePrefix)) { return true; } return false; } } }
Making constructor protected, so application can override DBOpenHelper. This is useful if the application is packing databases with the apk
libs/SmartStore/src/com/salesforce/androidsdk/smartstore/store/DBOpenHelper.java
Making constructor protected, so application can override DBOpenHelper. This is useful if the application is packing databases with the apk
<ide><path>ibs/SmartStore/src/com/salesforce/androidsdk/smartstore/store/DBOpenHelper.java <ide> return helper; <ide> } <ide> <del> private DBOpenHelper(Context context, String dbName) { <add> protected DBOpenHelper(Context context, String dbName) { <ide> super(context, dbName, null, DB_VERSION, new DBHook()); <ide> SQLiteDatabase.loadLibs(context); <ide> }
JavaScript
mit
20d032a5ed14569f9bb2f91ed33eb5713c47358b
0
kolllor33/secure-json-database
"use strict"; var _ = require("lodash"), fh = require("./Filehandler"), EventEmitter = require('events') module.exports = class DB extends EventEmitter { constructor(args) { super() this.db = {} this.path = args.path this.key = args.key this.updateCalls = 0 this.previousCallTime = undefined this.canCall = true this.canCallTreshold = undefined this.fileHandler = new fh({ path: this.path, key: this.key }) var data = this.fileHandler.init() if (data != null) { this.db = data } } addTable(name) { if (this.db[name] === undefined) { this.db[name] = [] this.update() } } getAllTableNames() { return Object.keys(this.db) } getTable(name) { if (this.db[name] == undefined) { return } return this.db[name] } insert(tablename, data) { try { if (data != undefined) { if (this.db[tablename] != undefined) { data.id = this.genUUID() this.db[tablename].push(data) this.update() //event emiter this.emit("insert", tablename, data) } else { throw new Error("Table wasn't created") } } else { console.error("Error: Data was null or undefined!") return } } catch (err) { console.log(err) } } removeAllBy(tablename, args) { if (this.db[tablename] != undefined) { var removed = this.findAll(tablename, args) _.pullAllBy(this.db[tablename], removed) this.update() //event emiter this.emit("remove", tablename, removed) } else { throw new Error("Table wasn't created") } } updateByID(tablename, id, data) { if (data != undefined) { if (this.db[tablename] != undefined) { var updated = _.filter(this.db[tablename], { id: id }) if (updated[0] === undefined) { return } const index = _.sortedIndexBy(this.db[tablename], updated[0]) Object.assign(this.db[tablename][index], data) this.update() //event emiter this.emit("updated", tablename, this.db[tablename][index]) } else { throw new Error("Table wasn't created") } } else { console.error("Error: Data was null or undefined!") return } } find(tablename, args) { if (this.db[tablename] != undefined) { return _.find(this.getTable(tablename), args) } else { throw new Error("Table wasn't created") } } findLast(tablename, args) { if (this.db[name] != undefined) { return _.findLast(this.getTable(tablename), args) } else { throw new Error("Table wasn't created") } } findAll(tablename, args) { if (this.db[tablename] != undefined) { return _.filter(this.getTable(tablename), args) } else { throw new Error("Table wasn't created") } } genUUID() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } update() { this.updateCalls++ if (this.canCall) { this.previousCallTime = new Date() this.fileHandler.write(this.db) this.emit("write") } if (this.updateCalls == this.canCallTreshold) { this.canCall = true } else if ((new Date() - this.previousCallTime) < 65) { this.canCallTreshold = this.updateCalls + 10 this.canCall = false } } }
index.js
"use strict"; var _ = require("lodash"), fh = require("./Filehandler"), EventEmitter = require('events') module.exports = class DB extends EventEmitter { constructor(args) { super() this.db = {} this.path = args.path this.key = args.key this.fileHandler = new fh({ path: this.path, key: this.key }) var data = this.fileHandler.init() if (data != null) { this.db = data } } addTable(name) { if (this.db[name] === undefined) { this.db[name] = [] this.update() } } getAllTableNames() { return Object.keys(this.db) } getTable(name) { if (this.db[name] == undefined) { return } return this.db[name] } insert(tablename, data) { try { if (data != undefined) { if (this.db[tablename] != undefined) { data.id = this.genUUID() this.db[tablename].push(data) //event emiter this.emit("insert", tablename, data) this.update() } else { throw new Error("Table wasn't created") } } else { console.error("Error: Data was null or undefined!") return } } catch (err) { console.log(err) } } removeAllBy(tablename, args) { if (this.db[tablename] != undefined) { var removed = this.findAll(tablename, args) _.pullAllBy(this.db[tablename], removed) //event emiter this.emit("delete", tablename, removed) this.update() } else { throw new Error("Table wasn't created") } } updateByID(tablename, id, data) { if (data != undefined) { if (this.db[tablename] != undefined) { var updated = _.filter(this.db[tablename], { id: id }) if (updated[0] === undefined) { return } const index = _.sortedIndexBy(this.db[tablename], updated[0]) Object.assign(this.db[tablename][index], data) //event emiter this.emit("updated", tablename, this.db[tablename][index]) this.update() } else { throw new Error("Table wasn't created") } } else { console.error("Error: Data was null or undefined!") return } } find(tablename, args) { if (this.db[tablename] != undefined) { return _.find(this.getTable(tablename), args) } else { throw new Error("Table wasn't created") } } findLast(tablename, args) { if (this.db[name] != undefined) { return _.findLast(this.getTable(tablename), args) } else { throw new Error("Table wasn't created") } } findAll(tablename, args) { if (this.db[tablename] != undefined) { return _.filter(this.getTable(tablename), args) } else { throw new Error("Table wasn't created") } } genUUID() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } update() { this.fileHandler.write(this.db) this.emit("write") } }
Performance enhancing Performance enhancing for large amounts of data putted in the database at once + set event handelers after data has been writen to the file
index.js
Performance enhancing
<ide><path>ndex.js <ide> this.db = {} <ide> this.path = args.path <ide> this.key = args.key <add> this.updateCalls = 0 <add> this.previousCallTime = undefined <add> this.canCall = true <add> this.canCallTreshold = undefined <ide> this.fileHandler = new fh({ <ide> path: this.path, <ide> key: this.key <ide> if (this.db[tablename] != undefined) { <ide> data.id = this.genUUID() <ide> this.db[tablename].push(data) <add> this.update() <ide> //event emiter <ide> this.emit("insert", tablename, data) <del> this.update() <ide> } else { <ide> throw new Error("Table wasn't created") <ide> } <ide> if (this.db[tablename] != undefined) { <ide> var removed = this.findAll(tablename, args) <ide> _.pullAllBy(this.db[tablename], removed) <add> this.update() <ide> //event emiter <del> this.emit("delete", tablename, removed) <del> this.update() <add> this.emit("remove", tablename, removed) <ide> } else { <ide> throw new Error("Table wasn't created") <ide> } <ide> } <ide> const index = _.sortedIndexBy(this.db[tablename], updated[0]) <ide> Object.assign(this.db[tablename][index], data) <add> this.update() <ide> //event emiter <ide> this.emit("updated", tablename, this.db[tablename][index]) <del> this.update() <ide> } else { <ide> throw new Error("Table wasn't created") <ide> } <ide> } <ide> <ide> update() { <del> this.fileHandler.write(this.db) <del> this.emit("write") <add> this.updateCalls++ <add> if (this.canCall) { <add> this.previousCallTime = new Date() <add> this.fileHandler.write(this.db) <add> this.emit("write") <add> } <add> if (this.updateCalls == this.canCallTreshold) { <add> this.canCall = true <add> } else if ((new Date() - this.previousCallTime) < 65) { <add> this.canCallTreshold = this.updateCalls + 10 <add> this.canCall = false <add> } <ide> } <ide> }
JavaScript
mit
3b1541d85d9e17b8ddd76ad19ff34103d3b38de2
0
concord-consortium/codap,concord-consortium/codap,concord-consortium/codap,concord-consortium/codap,concord-consortium/codap
// ========================================================================== // DG.Debug // // Debugging utilities for use in the DG application. // // Author: Kirk Swenson // // Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved. // // 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. // ========================================================================== /** Constant used to indicate logging of user actions. Analogous to SC.LOGGER_LEVEL_INFO, which as also the SC.Logger level at which it is such user log events are processed by SC.Logger. */ DG.LOGGER_LEVEL_USER = 'user'; /** Global function used to reload the current page. Called by the assert code when user presses the Reload button. */ DG.debugForceReload = function() { window.location.reload(); }; /** Global function used to drop into the JavaScript debugger, if one is running. */ DG.debugLaunchDebugger = function() { /* jslint evil:true */ eval('debugger'); }; /** @class DG.Debug provides debugging utilities for use during development. These debugging utilities are synchronized with the SproutCore facilities. (1) Expanded logging support (enhances SC.Logger) -- Log messages can be logged to the DG server via DG.logToServer(). -- Addition of the DG.LOGGER_LEVEL_USER for logging of user actions Clients control the level of server logging via the 'logServerLevel' property of DG.Debug. Clients should use the global convenience functions for their logging needs: DG.log(), DG.logRaw(), DG.logGroupBegin(), DG.logGroupEnd() DG.logInfo(), DG.logInfoRaw(), DG.logUser(), DG.logUserRaw(), DG.logWarn(), DG.logWarnRaw(), DG.logError(), DG.logErrorRaw() Note that the "standard" functions support printf-style formatting to simplify formatting of log strings. See SC.Logger for details. The "raw" functions skip the printf-style formatting for clients that would prefer to do the formatting themselves. (2) Assert functions Assert functions test a condition and put up an alert if it fails. As currently configured, the alert provides "Reload" and "Ignore" buttons and for developer builds (i.e. when running from sc-server during development), a "Debugger" button which drops into the debugger. In addition, for developer builds (i.e. when running from sc-server), the assert functions will drop into the debugger at a point at which the stack is meaningful, as it will contain the function which called the assert function. The following functions are defined at this point: DG.assert( iCondition, iMessage, iDescription) DG.check( iObject, iMessage, iDescription) -- Equivalent to assert( !SC.none( iObject)) The assert functions as they exist now are designed to return the condition being tested. Thus, it is possible to handle the failure as well as being notified about it, e.g. if( DG.check( iObject)) iObject.doSomething(); Thus, even if the alert and dropping into the debugger features of the assert functions are eliminated in a production build, clients may still use the assertion functions to bypass code that would otherwise fail Note that currently the assert function will bring up the assertion failure dialog in production builds as well as during development. If we decide at some point that this is not what we want, at least there will be a single place in which to make the change. (3) Unhandled exception handling The SproutCore White Screen of Death (WSOD) is the built-in SproutCore handler of last resort for otherwise unhandled exceptions. We intercept this mechanism to log it (using DG.logError()) and to stop in the debugger in developer builds (i.e. when running from sc-server) to allow the developer to look around and perhaps set a breakpoint before calling the SproutCore White Screen of Death handler. @author Kirk Swenson @extends SC.Object */ SC.Logger.logOutputLevel = SC.LOGGER_LEVEL_WARN; // @if (debug) SC.Logger.logOutputLevel = SC.LOGGER_LEVEL_DEBUG; // @endif DG.Debug = SC.Object.create( (function() { /** @scope DG.GlobalsController.prototype */ return { /** Controls the logging level to the DG server. Analogous to SC.Logger.logOutputLevel and SC.Logger.logRecordingLevel. @property: {Constant} */ logServerLevel: SC.LOGGER_LEVEL_INFO, /** Previous message logging function Called from our intervening message log handler. */ _prevHandleLogMessage: null, /** Previous exception handler Called from our intervening exception handler. */ _prevExceptionHandler: null, /** the time in milliseconds when init() or logDebugTimer(true) was last called. */ _debugStartTime: 0, /** Install our overrides/interventions. */ init: function() { this._debugStartTime = Date.now(); // record current time in milliseconds "since the epoch" // Install our message-logging intervention this._prevHandleLogMessage = SC.Logger._handleMessage; SC.Logger._handleMessage = this._prevHandleLogMessage; // Install our exception-handling intervention this._prevExceptionHandler = SC.ExceptionHandler.handleException; SC.ExceptionHandler.handleException = this._prevExceptionHandler; }, /** Issue a log warning if the specified value is not finite (NaN, infinite, etc.) */ logIfNotFinite: function(iValue, iOptString) { if( !isFinite( iValue)) this.logWarn("DG.Debug.logIfNotFinite: String: %@, Value: %@", iOptString, iValue); }, /** DG.Debug logging methods. Clients will generally use the global convenience functions defined later. */ logDebug: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_DEBUG, YES, iMessage, arguments); }, logDebugRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_DEBUG, NO, null, arguments); }, /** DG.Debug logging method with '[TIME=0.1234]' timing message (in seconds). */ logDebugTimer: function( iResetTimer, iMessage, iOptFormatArgs ) { var tTimeMS = Date.now(); // time in milliseconds if( iResetTimer ) { // reset the timer to zero DG.Debug._debugStartTime = tTimeMS; tTimeMS = 0; } else { // else relative to last start tTimeMS -= DG.Debug._debugStartTime; } // log with '[TIME=seconds.milliseconds] {message}' DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_DEBUG, YES, "[TIME="+(tTimeMS/1000)+"] "+iMessage, arguments); }, logDebugGroupBegin: function( iMessage, iOptFormatArgs) { SC.Logger._handleGroup(SC.LOGGER_LEVEL_DEBUG, iMessage, arguments); }, logDebugGroupEnd: function() { SC.Logger._handleGroupEnd(SC.LOGGER_LEVEL_DEBUG); }, logInfo: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_INFO, YES, iMessage, arguments); }, logInfoRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_INFO, NO, null, arguments); }, logUser: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(DG.LOGGER_LEVEL_USER, YES, iMessage, arguments); }, logUserRaw: function( iRawArgs) { DG.Debug._handleLogMessage(DG.LOGGER_LEVEL_USER, NO, null, arguments); }, logWarn: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_WARN, YES, iMessage, arguments); }, logWarnRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_WARN, NO, null, arguments); }, logError: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_ERROR, YES, iMessage, arguments); }, logErrorRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_ERROR, NO, null, arguments); }, /** Asserts that its condition is true. Puts up an alert message when its condition is not true, and automatically drops into the debugger in debug builds. Alert dialog has options for "Reload" and "Ignore" (and "Debug" for developer builds). @param {Boolean} iCondition The condition to test @param {String} iMessage A primary message @param {String} iDescription A secondary message @returns {Boolean} The condition that was tested */ assert: function( iCondition, iMessage, iDescription) { if( !iCondition) { var showAlert = true, stopInDebugger = true; // Log assertion failures automatically DG.Debug.logErrorRaw( "Assertion Failed: " + iMessage + ": " + iDescription); // Stop in debugger in debug builds if( stopInDebugger ) { //@if(debug) /* jslint evil:true */ eval('debugger'); //@endif } // Show the assertion failure alert if( showAlert) { SC.AlertPane.error({ message: iMessage || "", description: iDescription || "", buttons: [ { title: "Reload", action: DG.debugForceReload }, //@if(debug) { title: "Debug", action: DG.debugLaunchDebugger }, //@endif { title: "Ignore" } ] }); } } // Give clients a chance to handle the failure, e.g. // if( !DG.assert(myObj)) // myObj.doSomething(); return iCondition; }, /** Asserts that the specified object is defined and non-null. Equivalent to DG.assert( !SC.none( iObject, iMessage, iDescription)) @param {Object} iObject The object to test @param {String} iMessage A primary message @param {String} iDescription A secondary message @returns {Boolean} The condition that was tested */ check: function( iObject, iMessage, iDescription) { return this.assert( !SC.none( iObject), iMessage, iDescription); }, /** @private Private function used to decide when to log to the DG server. Analogous to SC.Logger._shouldOutputType and SC.Logger._shouldRecordType. @param {String} iType The name of the type in question from among standard Sproutcore log types. @returns {Boolean} */ _shouldLogTypeToServer: function( iType) { var logLevelMapping = SC.Logger._LOG_LEVEL_MAPPING, level = logLevelMapping[iType] || 0, currentLevel = logLevelMapping[this.get('logServerLevel')] || 0; return (level <= currentLevel); }, /** @private Outputs to the console and/or records the specified message and/or logs it to the DG server if the respective current log levels allows for it. Assuming 'automaticallyFormat' is specified, then String.fmt() will be called automatically on the message, but only if at least one of the log levels is such that the result will be used. @param {String} iType Expected to be SC.LOGGER_LEVEL_DEBUG, etc. @param {Boolean} iAutoFormat Whether or not to treat 'message' as a format string if there are additional arguments @param {String} iMessage Expected to a string format (for String.fmt()) if there are other arguments @param {Object} iOriginalArgs (optional) All arguments passed into debug(), etc. (which includes 'message'; for efficiency, we don’t copy it) */ _handleLogMessage: function( iType, iAutoFormat, iMessage, iOriginalArgs) { // Map DG-specific types to standard SC.Logger types var scType = (iType === DG.LOGGER_LEVEL_USER ? SC.LOGGER_LEVEL_INFO : iType); // Let SC.Logger log the message normally this._prevHandleLogMessage.call( SC.Logger, scType, iAutoFormat, iMessage, iOriginalArgs); // Log the message to the server as well, if appropriate if( DG.Debug._shouldLogTypeToServer( scType)) { try { // Pass along any properties that were passed in the last argument as // metaArgs var lastArg = (iOriginalArgs && (iOriginalArgs.length > 0)) ? iOriginalArgs[ iOriginalArgs.length - 1] : undefined, metaArgs = typeof lastArg === 'object' ? lastArg : {}, messageParts = DG.Debug._currentMessage? DG.Debug._currentMessage.split(":"): [], activity = DG.gameSelectionController.get('currentGame'), activityName = activity? activity.get('name') : undefined, messageType = messageParts.shift(), messageArgs = messageParts.join(':').trim(); DG.logToServer( messageType, { type: iType, args: messageArgs, activity: activityName, application: 'CODAP' }, metaArgs); } catch(ex) { if (console && console.log) { console.log('Log to server failed: ' + ex); } } } }, /** @private Our exception handler override which logs the exception and stops in the debugger before calling the SproutCore exception handler. */ _handleException: function( iException) { var shouldCallSystemHandler = !SC.none( this._prevExceptionHandler); DG.Debug.logErrorRaw( "Exception: " + iException.message); //@if(debug) /* jslint evil:true */ eval('debugger'); //@endif if( shouldCallSystemHandler) this._prevExceptionHandler.call( SC.ExceptionHandler, iException); } }; // return from function closure }())); // function closure /** @private Replace SC.Logger._shouldOutputType function with our own implementation which always returns true, thus guaranteeing that we have a chance to capture the formatted message. Stash the original SC.Logger._shouldOutputType function so we can call it later. */ DG.Debug._prevShouldOutputType = SC.Logger._shouldOutputType; SC.Logger._shouldOutputType = function(type) { return true; }; /** @private Replace SC.Logger._outputMessage function with our own implementation which captures the formatted message. We then call the original SC.Logger._shouldOutputType method to determine whether or not to call the original SC.Logger._outputMessage method. */ DG.Debug._prevOutputMessage = SC.Logger._outputMessage; SC.Logger._outputMessage = function(type, timestampStr, indentation, message, originalArguments) { DG.Debug._currentMessage = message; if( DG.Debug._prevShouldOutputType.call( SC.Logger, type)) DG.Debug._prevOutputMessage.call( SC.Logger, type, timestampStr, indentation, message, originalArguments); }; /** Returns the unique SproutCore-generated ID for a SproutCore object. Returns "{none}" if there is not SproutCore ID associated with the object. This can be useful when logging to help identify objects. */ DG.Debug.scObjectID = function( iObject) { var scIDKey, scIDValue = ""; DG.ObjectMap.findKey( iObject, function( iKey, iValue) { if( iKey.substr(0,10) === 'SproutCore') { scIDKey = iKey; scIDValue = iValue; return true; } return false; }); return !SC.empty(scIDValue) ? scIDValue : "{none}"; }; /** Convenience functions for DG.Debug functions. */ DG.log = DG.Debug.logDebug; DG.logRaw = DG.Debug.logDebugRaw; DG.logTimer = DG.Debug.logDebugTimer; DG.logGroupBegin = DG.Debug.logDebugGroupBegin; DG.logGroupEnd = DG.Debug.logDebugGroupEnd; DG.logInfo = DG.Debug.logInfo; DG.logInfoRaw = DG.Debug.logInfoRaw; DG.logUser = DG.Debug.logUser; DG.logUserRaw = DG.Debug.logUserRaw; DG.logWarn = DG.Debug.logWarn; DG.logWarnRaw = DG.Debug.logWarnRaw; DG.logError = DG.Debug.logError; DG.logErrorRaw = DG.Debug.logErrorRaw; DG.assert = DG.Debug.assert; DG.check = DG.Debug.check;
apps/dg/alpha/debug.js
// ========================================================================== // DG.Debug // // Debugging utilities for use in the DG application. // // Author: Kirk Swenson // // Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved. // // 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. // ========================================================================== /** Constant used to indicate logging of user actions. Analogous to SC.LOGGER_LEVEL_INFO, which as also the SC.Logger level at which it is such user log events are processed by SC.Logger. */ DG.LOGGER_LEVEL_USER = 'user'; /** Global function used to reload the current page. Called by the assert code when user presses the Reload button. */ DG.debugForceReload = function() { window.location.reload(); }; /** Global function used to drop into the JavaScript debugger, if one is running. */ DG.debugLaunchDebugger = function() { /* jslint evil:true */ eval('debugger'); }; /** @class DG.Debug provides debugging utilities for use during development. These debugging utilities are synchronized with the SproutCore facilities. (1) Expanded logging support (enhances SC.Logger) -- Log messages can be logged to the DG server via DG.logToServer(). -- Addition of the DG.LOGGER_LEVEL_USER for logging of user actions Clients control the level of server logging via the 'logServerLevel' property of DG.Debug. Clients should use the global convenience functions for their logging needs: DG.log(), DG.logRaw(), DG.logGroupBegin(), DG.logGroupEnd() DG.logInfo(), DG.logInfoRaw(), DG.logUser(), DG.logUserRaw(), DG.logWarn(), DG.logWarnRaw(), DG.logError(), DG.logErrorRaw() Note that the "standard" functions support printf-style formatting to simplify formatting of log strings. See SC.Logger for details. The "raw" functions skip the printf-style formatting for clients that would prefer to do the formatting themselves. (2) Assert functions Assert functions test a condition and put up an alert if it fails. As currently configured, the alert provides "Reload" and "Ignore" buttons and for developer builds (i.e. when running from sc-server during development), a "Debugger" button which drops into the debugger. In addition, for developer builds (i.e. when running from sc-server), the assert functions will drop into the debugger at a point at which the stack is meaningful, as it will contain the function which called the assert function. The following functions are defined at this point: DG.assert( iCondition, iMessage, iDescription) DG.check( iObject, iMessage, iDescription) -- Equivalent to assert( !SC.none( iObject)) The assert functions as they exist now are designed to return the condition being tested. Thus, it is possible to handle the failure as well as being notified about it, e.g. if( DG.check( iObject)) iObject.doSomething(); Thus, even if the alert and dropping into the debugger features of the assert functions are eliminated in a production build, clients may still use the assertion functions to bypass code that would otherwise fail Note that currently the assert function will bring up the assertion failure dialog in production builds as well as during development. If we decide at some point that this is not what we want, at least there will be a single place in which to make the change. (3) Unhandled exception handling The SproutCore White Screen of Death (WSOD) is the built-in SproutCore handler of last resort for otherwise unhandled exceptions. We intercept this mechanism to log it (using DG.logError()) and to stop in the debugger in developer builds (i.e. when running from sc-server) to allow the developer to look around and perhaps set a breakpoint before calling the SproutCore White Screen of Death handler. @author Kirk Swenson @extends SC.Object */ SC.Logger.logOutputLevel = SC.LOGGER_LEVEL_WARN; // @if (debug) SC.Logger.logOutputLevel = SC.LOGGER_LEVEL_DEBUG; // @endif DG.Debug = SC.Object.create( (function() { /** @scope DG.GlobalsController.prototype */ return { /** Controls the logging level to the DG server. Analogous to SC.Logger.logOutputLevel and SC.Logger.logRecordingLevel. @property: {Constant} */ logServerLevel: SC.LOGGER_LEVEL_INFO, /** Previous message logging function Called from our intervening message log handler. */ _prevHandleLogMessage: null, /** Previous exception handler Called from our intervening exception handler. */ _prevExceptionHandler: null, /** the time in milliseconds when init() or logDebugTimer(true) was last called. */ _debugStartTime: 0, /** Install our overrides/interventions. */ init: function() { this._debugStartTime = Date.now(); // record current time in milliseconds "since the epoch" // Install our message-logging intervention this._prevHandleLogMessage = SC.Logger._handleMessage; SC.Logger._handleMessage = this._prevHandleLogMessage; // Install our exception-handling intervention this._prevExceptionHandler = SC.ExceptionHandler.handleException; SC.ExceptionHandler.handleException = this._prevExceptionHandler; }, /** Issue a log warning if the specified value is not finite (NaN, infinite, etc.) */ logIfNotFinite: function(iValue, iOptString) { if( !isFinite( iValue)) this.logWarn("DG.Debug.logIfNotFinite: String: %@, Value: %@", iOptString, iValue); }, /** DG.Debug logging methods. Clients will generally use the global convenience functions defined later. */ logDebug: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_DEBUG, YES, iMessage, arguments); }, logDebugRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_DEBUG, NO, null, arguments); }, /** DG.Debug logging method with '[TIME=0.1234]' timing message (in seconds). */ logDebugTimer: function( iResetTimer, iMessage, iOptFormatArgs ) { var tTimeMS = Date.now(); // time in milliseconds if( iResetTimer ) { // reset the timer to zero DG.Debug._debugStartTime = tTimeMS; tTimeMS = 0; } else { // else relative to last start tTimeMS -= DG.Debug._debugStartTime; } // log with '[TIME=seconds.milliseconds] {message}' DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_DEBUG, YES, "[TIME="+(tTimeMS/1000)+"] "+iMessage, arguments); }, logDebugGroupBegin: function( iMessage, iOptFormatArgs) { SC.Logger._handleGroup(SC.LOGGER_LEVEL_DEBUG, iMessage, arguments); }, logDebugGroupEnd: function() { SC.Logger._handleGroupEnd(SC.LOGGER_LEVEL_DEBUG); }, logInfo: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_INFO, YES, iMessage, arguments); }, logInfoRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_INFO, NO, null, arguments); }, logUser: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(DG.LOGGER_LEVEL_USER, YES, iMessage, arguments); }, logUserRaw: function( iRawArgs) { DG.Debug._handleLogMessage(DG.LOGGER_LEVEL_USER, NO, null, arguments); }, logWarn: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_WARN, YES, iMessage, arguments); }, logWarnRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_WARN, NO, null, arguments); }, logError: function( iMessage, iOptFormatArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_ERROR, YES, iMessage, arguments); }, logErrorRaw: function( iRawArgs) { DG.Debug._handleLogMessage(SC.LOGGER_LEVEL_ERROR, NO, null, arguments); }, /** Asserts that its condition is true. Puts up an alert message when its condition is not true, and automatically drops into the debugger in debug builds. Alert dialog has options for "Reload" and "Ignore" (and "Debug" for developer builds). @param {Boolean} iCondition The condition to test @param {String} iMessage A primary message @param {String} iDescription A secondary message @returns {Boolean} The condition that was tested */ assert: function( iCondition, iMessage, iDescription) { if( !iCondition) { var showAlert = true, stopInDebugger = true; // Log assertion failures automatically DG.Debug.logErrorRaw( "Assertion Failed: " + iMessage + ": " + iDescription); // Stop in debugger in debug builds if( stopInDebugger ) { //@if(debug) /* jslint evil:true */ eval('debugger'); //@endif } // Show the assertion failure alert if( showAlert) { SC.AlertPane.error({ message: iMessage || "", description: iDescription || "", buttons: [ { title: "Reload", action: DG.debugForceReload }, //@if(debug) { title: "Debug", action: DG.debugLaunchDebugger }, //@endif { title: "Ignore" } ] }); } } // Give clients a chance to handle the failure, e.g. // if( !DG.assert(myObj)) // myObj.doSomething(); return iCondition; }, /** Asserts that the specified object is defined and non-null. Equivalent to DG.assert( !SC.none( iObject, iMessage, iDescription)) @param {Object} iObject The object to test @param {String} iMessage A primary message @param {String} iDescription A secondary message @returns {Boolean} The condition that was tested */ check: function( iObject, iMessage, iDescription) { return this.assert( !SC.none( iObject), iMessage, iDescription); }, /** @private Private function used to decide when to log to the DG server. Analogous to SC.Logger._shouldOutputType and SC.Logger._shouldRecordType. @param {String} iType The name of the type in question from among standard Sproutcore log types. @returns {Boolean} */ _shouldLogTypeToServer: function( iType) { var logLevelMapping = SC.Logger._LOG_LEVEL_MAPPING, level = logLevelMapping[iType] || 0, currentLevel = logLevelMapping[this.get('logServerLevel')] || 0; return (level <= currentLevel); }, /** @private Outputs to the console and/or records the specified message and/or logs it to the DG server if the respective current log levels allows for it. Assuming 'automaticallyFormat' is specified, then String.fmt() will be called automatically on the message, but only if at least one of the log levels is such that the result will be used. @param {String} iType Expected to be SC.LOGGER_LEVEL_DEBUG, etc. @param {Boolean} iAutoFormat Whether or not to treat 'message' as a format string if there are additional arguments @param {String} iMessage Expected to a string format (for String.fmt()) if there are other arguments @param {Object} iOriginalArgs (optional) All arguments passed into debug(), etc. (which includes 'message'; for efficiency, we don’t copy it) */ _handleLogMessage: function( iType, iAutoFormat, iMessage, iOriginalArgs) { // Map DG-specific types to standard SC.Logger types var scType = (iType === DG.LOGGER_LEVEL_USER ? SC.LOGGER_LEVEL_INFO : iType); // Let SC.Logger log the message normally this._prevHandleLogMessage.call( SC.Logger, scType, iAutoFormat, iMessage, iOriginalArgs); // Log the message to the server as well, if appropriate if( DG.Debug._shouldLogTypeToServer( scType)) { try { // Pass along any properties that were passed in the last argument as // metaArgs var lastArg = (iOriginalArgs && (iOriginalArgs.length > 0)) ? iOriginalArgs[ iOriginalArgs.length - 1] : undefined, metaArgs = typeof lastArg === 'object' ? lastArg : {}, messageParts = DG.Debug._currentMessage? DG.Debug._currentMessage.split(":"): [], activity = DG.gameSelectionController.get('currentGame'), activityName = activity? activity.get('name') : undefined, messageType = messageParts.shift(), messageArgs = messageParts.join(':').trim(); DG.logToServer( messageType, { type: iType, args: messageArgs, activity: activityName, application: 'CODAP' }, metaArgs); } catch(ex) { console && console.log && console.log('Log to server failed: ' + ex); } } }, /** @private Our exception handler override which logs the exception and stops in the debugger before calling the SproutCore exception handler. */ _handleException: function( iException) { var shouldCallSystemHandler = !SC.none( this._prevExceptionHandler); DG.Debug.logErrorRaw( "Exception: " + iException.message); //@if(debug) /* jslint evil:true */ eval('debugger'); //@endif if( shouldCallSystemHandler) this._prevExceptionHandler.call( SC.ExceptionHandler, iException); } }; // return from function closure }())); // function closure /** @private Replace SC.Logger._shouldOutputType function with our own implementation which always returns true, thus guaranteeing that we have a chance to capture the formatted message. Stash the original SC.Logger._shouldOutputType function so we can call it later. */ DG.Debug._prevShouldOutputType = SC.Logger._shouldOutputType; SC.Logger._shouldOutputType = function(type) { return true; }; /** @private Replace SC.Logger._outputMessage function with our own implementation which captures the formatted message. We then call the original SC.Logger._shouldOutputType method to determine whether or not to call the original SC.Logger._outputMessage method. */ DG.Debug._prevOutputMessage = SC.Logger._outputMessage; SC.Logger._outputMessage = function(type, timestampStr, indentation, message, originalArguments) { DG.Debug._currentMessage = message; if( DG.Debug._prevShouldOutputType.call( SC.Logger, type)) DG.Debug._prevOutputMessage.call( SC.Logger, type, timestampStr, indentation, message, originalArguments); }; /** Returns the unique SproutCore-generated ID for a SproutCore object. Returns "{none}" if there is not SproutCore ID associated with the object. This can be useful when logging to help identify objects. */ DG.Debug.scObjectID = function( iObject) { var scIDKey, scIDValue = ""; DG.ObjectMap.findKey( iObject, function( iKey, iValue) { if( iKey.substr(0,10) === 'SproutCore') { scIDKey = iKey; scIDValue = iValue; return true; } return false; }); return !SC.empty(scIDValue) ? scIDValue : "{none}"; }; /** Convenience functions for DG.Debug functions. */ DG.log = DG.Debug.logDebug; DG.logRaw = DG.Debug.logDebugRaw; DG.logTimer = DG.Debug.logDebugTimer; DG.logGroupBegin = DG.Debug.logDebugGroupBegin; DG.logGroupEnd = DG.Debug.logDebugGroupEnd; DG.logInfo = DG.Debug.logInfo; DG.logInfoRaw = DG.Debug.logInfoRaw; DG.logUser = DG.Debug.logUser; DG.logUserRaw = DG.Debug.logUserRaw; DG.logWarn = DG.Debug.logWarn; DG.logWarnRaw = DG.Debug.logWarnRaw; DG.logError = DG.Debug.logError; DG.logErrorRaw = DG.Debug.logErrorRaw; DG.assert = DG.Debug.assert; DG.check = DG.Debug.check;
Convert unconventional use of expressions.
apps/dg/alpha/debug.js
Convert unconventional use of expressions.
<ide><path>pps/dg/alpha/debug.js <ide> application: 'CODAP' <ide> }, metaArgs); <ide> } catch(ex) { <del> console && console.log && console.log('Log to server failed: ' + ex); <add> if (console && console.log) { <add> console.log('Log to server failed: ' + ex); <add> } <ide> } <ide> } <ide>
Java
agpl-3.0
error: pathspec 'src/test/java/com/imcode/imcms/TransactionalWebAppSpringTestConfig.java' did not match any file(s) known to git
7d4a91aa16c9a4a6fe0f6e5da5dfbe80e9fbd6bd
1
imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms
package com.imcode.imcms; import com.imcode.imcms.config.TestConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; /** * Merge of all frequently used annotations */ @Transactional @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestConfig.class}) public class TransactionalWebAppSpringTestConfig { @Test public void empty() { // to prevent "no runnable tests" error } }
src/test/java/com/imcode/imcms/TransactionalWebAppSpringTestConfig.java
IMCMS-300 - New design to superadmin-pages: - Created class with all frequently used annotations for tests.
src/test/java/com/imcode/imcms/TransactionalWebAppSpringTestConfig.java
IMCMS-300 - New design to superadmin-pages: - Created class with all frequently used annotations for tests.
<ide><path>rc/test/java/com/imcode/imcms/TransactionalWebAppSpringTestConfig.java <add>package com.imcode.imcms; <add> <add>import com.imcode.imcms.config.TestConfig; <add>import org.junit.Test; <add>import org.junit.runner.RunWith; <add>import org.springframework.test.context.ContextConfiguration; <add>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <add>import org.springframework.test.context.web.WebAppConfiguration; <add>import org.springframework.transaction.annotation.Transactional; <add> <add>/** <add> * Merge of all frequently used annotations <add> */ <add>@Transactional <add>@WebAppConfiguration <add>@RunWith(SpringJUnit4ClassRunner.class) <add>@ContextConfiguration(classes = {TestConfig.class}) <add>public class TransactionalWebAppSpringTestConfig { <add> <add> @Test <add> public void empty() { <add> // to prevent "no runnable tests" error <add> } <add>}
Java
mit
3d758f508610a82a242bb95bc1eb3fdb9ee73303
0
raeleus/skin-composer
/******************************************************************************* * MIT License * * Copyright (c) 2022 Raymond Buckley * * 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 com.ray3k.skincomposer; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Net; import com.badlogic.gdx.Net.HttpMethods; import com.badlogic.gdx.Net.HttpRequest; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; import com.badlogic.gdx.net.HttpRequestBuilder; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle; import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle; import com.badlogic.gdx.scenes.scene2d.ui.SplitPane.SplitPaneStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip.TextTooltipStyle; import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle; import com.badlogic.gdx.scenes.scene2d.ui.Tree.TreeStyle; import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle; import com.badlogic.gdx.utils.Null; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.esotericsoftware.spine.AnimationStateData; import com.esotericsoftware.spine.SkeletonData; import com.esotericsoftware.spine.SkeletonJson; import com.esotericsoftware.spine.SkeletonRenderer; import com.ray3k.skincomposer.data.AtlasData; import com.ray3k.skincomposer.data.JsonData; import com.ray3k.skincomposer.data.ProjectData; import com.ray3k.skincomposer.dialog.DialogFactory; import com.ray3k.skincomposer.dialog.DialogListener; import com.ray3k.skincomposer.utils.Utils; import com.ray3k.stripe.FreeTypeSkin; import com.ray3k.stripe.PopColorPicker.PopColorPickerStyle; import com.ray3k.stripe.ScrollFocusListener; import com.ray3k.tenpatch.TenPatchDrawable; import dev.lyze.gdxtinyvg.TinyVGAssetLoader; import dev.lyze.gdxtinyvg.drawers.TinyVGShapeDrawer; import dev.lyze.gdxtinyvg.scene2d.TinyVGDrawable; import space.earlygrey.shapedrawer.GraphDrawer; public class Main extends ApplicationAdapter { public final static String VERSION = "51"; public static String newVersion; public static final Class[] BASIC_CLASSES = {Button.class, CheckBox.class, ImageButton.class, ImageTextButton.class, Label.class, List.class, ProgressBar.class, ScrollPane.class, SelectBox.class, Slider.class, SplitPane.class, TextButton.class, TextField.class, TextTooltip.class, Touchpad.class, Tree.class, Window.class}; public static final Class[] STYLE_CLASSES = {ButtonStyle.class, CheckBoxStyle.class, ImageButtonStyle.class, ImageTextButtonStyle.class, LabelStyle.class, ListStyle.class, ProgressBarStyle.class, ScrollPaneStyle.class, SelectBoxStyle.class, SliderStyle.class, SplitPaneStyle.class, TextButtonStyle.class, TextFieldStyle.class, TextTooltipStyle.class, TouchpadStyle.class, TreeStyle.class, WindowStyle.class}; public static Stage stage; public static Skin skin; public static ScreenViewport viewport; public static TinyVGShapeDrawer shapeDrawer; public static GraphDrawer graphDrawer; public static DialogFactory dialogFactory; public static DesktopWorker desktopWorker; public static TenPatchDrawable loadingAnimation; public static TenPatchDrawable loadingAnimation2; public static UndoableManager undoableManager; public static ProjectData projectData; public static JsonData jsonData; public static AtlasData atlasData; public static RootTable rootTable; public static IbeamListener ibeamListener; public static MainListener mainListener; public static HandListener handListener; public static ScrollFocusListener scrollFocusListener; public static ResizeArrowListener verticalResizeArrowListener; public static ResizeArrowListener horizontalResizeArrowListener; public static TooltipManager tooltipManager; public static FileHandle appFolder; private String[] args; public static Main main; public static SkeletonRenderer skeletonRenderer; public static SkeletonData floppySkeletonData; public static AnimationStateData floppyAnimationStateData; public static SkeletonData uiScaleSkeletonData; public static AnimationStateData uiScaleAnimationStateData; public static SkeletonData textraTypistLogoSkeletonData; public static AnimationStateData textraTypistLogoAnimationStateData; public static SkeletonData arrowSkeletonData; public static AnimationStateData arrowAnimationStateData; public static TinyVGAssetLoader tinyVGAssetLoader; private static final int SPINE_MAX_VERTS = 32767; private static TinyVGDrawable drawable; public static PopColorPickerStyle popColorPickerStyle; public Main (String[] args) { this.args = args; main = this; } @Override public void create() { appFolder = Gdx.files.external(".skincomposer/"); skin = new FreeTypeSkin(Gdx.files.internal("skin-composer-ui/skin-composer-ui.json")); viewport = new ScreenViewport(); // viewport.setUnitsPerPixel(.5f); var batch = new PolygonSpriteBatch(SPINE_MAX_VERTS); stage = new Stage(viewport, batch); Gdx.input.setInputProcessor(stage); shapeDrawer = new TinyVGShapeDrawer(stage.getBatch(), skin.getRegion("white")); graphDrawer = new GraphDrawer(shapeDrawer); tinyVGAssetLoader = new TinyVGAssetLoader(); skeletonRenderer = new SkeletonRenderer(); var skeletonJson = new SkeletonJson(Main.skin.getAtlas()); floppySkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/floppy.json")); floppyAnimationStateData = new AnimationStateData(floppySkeletonData); uiScaleSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/uiscale.json")); uiScaleAnimationStateData = new AnimationStateData(uiScaleSkeletonData); textraTypistLogoSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/TextraTypist Logo.json")); textraTypistLogoAnimationStateData = new AnimationStateData(textraTypistLogoSkeletonData); arrowSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/arrow-animation.json")); arrowAnimationStateData = new AnimationStateData(arrowSkeletonData); popColorPickerStyle = new PopColorPickerStyle(); popColorPickerStyle.background = skin.getDrawable("cp-bg-10"); popColorPickerStyle.stageBackground = skin.getDrawable("stage-background"); popColorPickerStyle.titleBarBackground = skin.getDrawable("cp-title-bar-10"); popColorPickerStyle.labelStyle = skin.get("tt", LabelStyle.class); popColorPickerStyle.fileTextButtonStyle = skin.get("cp-file", TextButtonStyle.class); popColorPickerStyle.scrollPaneStyle = skin.get("tt", ScrollPaneStyle.class); popColorPickerStyle.colorSwatch = skin.getDrawable("tt-color-swatch"); popColorPickerStyle.colorSwatchNew = skin.getDrawable("tt-color-swatch-new"); popColorPickerStyle.colorSwatchPopBackground = skin.getDrawable("tt-panel-10"); popColorPickerStyle.colorSwatchPopPreview = skin.getDrawable("tt-color-swatch-10"); popColorPickerStyle.previewSwatchBackground = skin.getDrawable("tt-swatch"); popColorPickerStyle.previewSwatchOld = skin.getDrawable("tt-swatch-old"); popColorPickerStyle.previewSwatchNew = skin.getDrawable("tt-swatch-new"); popColorPickerStyle.previewSwatchSingleBackground = skin.getDrawable("tt-swatch-null"); popColorPickerStyle.previewSwatchSingle = skin.getDrawable("tt-swatch-new-null"); popColorPickerStyle.textFieldStyle = skin.get("cp", TextFieldStyle.class); popColorPickerStyle.hexTextFieldStyle = skin.get("cp-hexfield", TextFieldStyle.class); popColorPickerStyle.textButtonStyle = skin.get("cp", TextButtonStyle.class); popColorPickerStyle.colorSliderBackground = skin.getDrawable("tt-slider-10"); popColorPickerStyle.colorKnobCircleBackground = skin.getDrawable("tt-color-ball"); popColorPickerStyle.colorKnobCircleForeground = skin.getDrawable("tt-color-ball-interior"); popColorPickerStyle.colorSliderKnobHorizontal = skin.getDrawable("tt-slider-knob"); popColorPickerStyle.colorSliderKnobVertical = skin.getDrawable("tt-slider-knob-vertical"); popColorPickerStyle.radioButtonStyle = skin.get("cp-radio", ImageButtonStyle.class); popColorPickerStyle.increaseButtonStyle = skin.get("cp-increase", ImageButtonStyle.class); popColorPickerStyle.decreaseButtonStyle = skin.get("cp-decrease", ImageButtonStyle.class); popColorPickerStyle.checkerBackground = skin.getDrawable("tt-checker-10"); initDefaults(); populate(); resizeUiScale(projectData.getUiScale()); } private void initDefaults() { if (Utils.isMac()) System.setProperty("java.awt.headless", "true"); skin.getFont("font").getData().markupEnabled = true; //copy defaults.json to temp folder if it doesn't exist var fileHandle = appFolder.child("texturepacker/atlas-export-settings.json"); if (!fileHandle.exists()) { Gdx.files.internal("atlas-export-settings.json").copyTo(fileHandle); } //copy atlas settings for preview to temp folder if it doesn't exist fileHandle = appFolder.child("texturepacker/atlas-internal-settings.json"); if (!fileHandle.exists()) { Gdx.files.internal("atlas-internal-settings.json").copyTo(fileHandle); } //copy white-pixel.png for pixel drawables fileHandle = appFolder.child("texturepacker/white-pixel.png"); if (!fileHandle.exists()) { Gdx.files.internal("white-pixel.png").copyTo(fileHandle); } //copy preview fonts to preview fonts folder if they do not exist fileHandle = appFolder.child("preview fonts/IBMPlexSerif-Medium.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/IBMPlexSerif-Medium.ttf").copyTo(fileHandle); } fileHandle = appFolder.child("preview fonts/Pacifico-Regular.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/Pacifico-Regular.ttf").copyTo(fileHandle); } fileHandle = appFolder.child("preview fonts/PressStart2P-Regular.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/PressStart2P-Regular.ttf").copyTo(fileHandle); } fileHandle = appFolder.child("preview fonts/SourceSansPro-Regular.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/SourceSansPro-Regular.ttf").copyTo(fileHandle); } ibeamListener = new IbeamListener(); dialogFactory = new DialogFactory(); projectData = new ProjectData(); projectData.randomizeId(); projectData.setMaxUndos(30); atlasData = projectData.getAtlasData(); jsonData = projectData.getJsonData(); newVersion = VERSION; if (projectData.isCheckingForUpdates()) { checkForUpdates(this); } undoableManager = new UndoableManager(this); desktopWorker.attachLogListener(); desktopWorker.setCloseListener(() -> { dialogFactory.showCloseDialog(new DialogListener() { @Override public void opened() { desktopWorker.removeFilesDroppedListener(rootTable.getFilesDroppedListener()); } @Override public void closed() { desktopWorker.addFilesDroppedListener(rootTable.getFilesDroppedListener()); } }); return false; }); loadingAnimation = skin.get("loading-animation", TenPatchDrawable.class); loadingAnimation2 = skin.get("loading-animation2", TenPatchDrawable.class); projectData.getAtlasData().clearTempData(); handListener = new HandListener(); scrollFocusListener = new ScrollFocusListener(stage); verticalResizeArrowListener = new ResizeArrowListener(true); horizontalResizeArrowListener = new ResizeArrowListener(false); tooltipManager = new TooltipManager(); tooltipManager.animations = false; tooltipManager.initialTime = .4f; tooltipManager.resetTime = 0.0f; tooltipManager.subsequentTime = 0.0f; tooltipManager.maxWidth = 400f; tooltipManager.hideAll(); tooltipManager.instant(); } private void populate() { stage.clear(); rootTable = new RootTable(); rootTable.setFillParent(true); mainListener = new MainListener(); rootTable.addListener(mainListener); rootTable.populate(); stage.addActor(rootTable); rootTable.updateRecentFiles(); //pass arguments if (!mainListener.argumentsPassed(args)) { //show welcome screen if there are no valid arguments mainListener.createWelcomeListener(); } } @Override public void render() { Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); for (var tenPatch : skin.getAll(TenPatchDrawable.class)) { tenPatch.value.update(Gdx.graphics.getDeltaTime()); } stage.draw(); } @Override public void resize(int width, int height) { if (width != 0 && height != 0) { stage.getViewport().update(width, height, true); rootTable.fire(new StageResizeEvent(width, height)); } } @Override public void dispose() { stage.dispose(); skin.dispose(); } public void resizeUiScale(int scale) { resizeUiScale(scale, scale > 1); } public void resizeUiScale(int scale, boolean large) { if (large) { desktopWorker.sizeWindowToFit(1440, 1440, 50, Gdx.graphics); } else { desktopWorker.sizeWindowToFit(800, 800, 50, Gdx.graphics); } desktopWorker.centerWindow(Gdx.graphics); viewport.setUnitsPerPixel(1f / scale); viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true); } public static Class basicToStyleClass(Class clazz) { int i = 0; for (Class basicClass : BASIC_CLASSES) { if (clazz.equals(basicClass)) { break; } else { i++; } } return i < STYLE_CLASSES.length ? STYLE_CLASSES[i] : null; } public static Class styleToBasicClass(Class clazz) { int i = 0; for (Class styleClass : STYLE_CLASSES) { if (clazz.equals(styleClass)) { break; } else { i++; } } return BASIC_CLASSES[i]; } public static void checkForUpdates(Main main) { Thread thread = new Thread(new Runnable() { @Override public void run() { HttpRequestBuilder requestBuilder = new HttpRequestBuilder(); HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://raw.githubusercontent.com/raeleus/skin-composer/master/version").build(); Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() { @Override public void handleHttpResponse(Net.HttpResponse httpResponse) { newVersion = httpResponse.getResultAsString(); Gdx.app.postRunnable(new Runnable() { @Override public void run() { main.rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.CHECK_FOR_UPDATES_COMPLETE)); } }); } @Override public void failed(Throwable t) { newVersion = VERSION; } @Override public void cancelled() { newVersion = VERSION; } }); } }); thread.start(); } public static TextTooltip fixTooltip(TextTooltip toolTip) { toolTip.getContainer().width(new Value() { public float get (@Null Actor context) { return Math.min(toolTip.getManager().maxWidth, toolTip.getActor().getGlyphLayout().width); } }); return toolTip; } }
core/src/com/ray3k/skincomposer/Main.java
/******************************************************************************* * MIT License * * Copyright (c) 2022 Raymond Buckley * * 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 com.ray3k.skincomposer; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Net; import com.badlogic.gdx.Net.HttpMethods; import com.badlogic.gdx.Net.HttpRequest; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; import com.badlogic.gdx.net.HttpRequestBuilder; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle; import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle; import com.badlogic.gdx.scenes.scene2d.ui.SplitPane.SplitPaneStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip.TextTooltipStyle; import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle; import com.badlogic.gdx.scenes.scene2d.ui.Tree.TreeStyle; import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle; import com.badlogic.gdx.utils.Null; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.esotericsoftware.spine.AnimationStateData; import com.esotericsoftware.spine.SkeletonData; import com.esotericsoftware.spine.SkeletonJson; import com.esotericsoftware.spine.SkeletonRenderer; import com.ray3k.skincomposer.data.AtlasData; import com.ray3k.skincomposer.data.JsonData; import com.ray3k.skincomposer.data.ProjectData; import com.ray3k.skincomposer.dialog.DialogFactory; import com.ray3k.skincomposer.dialog.DialogListener; import com.ray3k.skincomposer.utils.Utils; import com.ray3k.stripe.FreeTypeSkin; import com.ray3k.stripe.PopColorPicker.PopColorPickerStyle; import com.ray3k.stripe.ScrollFocusListener; import com.ray3k.tenpatch.TenPatchDrawable; import dev.lyze.gdxtinyvg.TinyVGAssetLoader; import dev.lyze.gdxtinyvg.drawers.TinyVGShapeDrawer; import dev.lyze.gdxtinyvg.scene2d.TinyVGDrawable; import space.earlygrey.shapedrawer.GraphDrawer; public class Main extends ApplicationAdapter { public final static String VERSION = "51"; public static String newVersion; public static final Class[] BASIC_CLASSES = {Button.class, CheckBox.class, ImageButton.class, ImageTextButton.class, Label.class, List.class, ProgressBar.class, ScrollPane.class, SelectBox.class, Slider.class, SplitPane.class, TextButton.class, TextField.class, TextTooltip.class, Touchpad.class, Tree.class, Window.class}; public static final Class[] STYLE_CLASSES = {ButtonStyle.class, CheckBoxStyle.class, ImageButtonStyle.class, ImageTextButtonStyle.class, LabelStyle.class, ListStyle.class, ProgressBarStyle.class, ScrollPaneStyle.class, SelectBoxStyle.class, SliderStyle.class, SplitPaneStyle.class, TextButtonStyle.class, TextFieldStyle.class, TextTooltipStyle.class, TouchpadStyle.class, TreeStyle.class, WindowStyle.class}; public static Stage stage; public static Skin skin; public static ScreenViewport viewport; public static TinyVGShapeDrawer shapeDrawer; public static GraphDrawer graphDrawer; public static DialogFactory dialogFactory; public static DesktopWorker desktopWorker; public static TenPatchDrawable loadingAnimation; public static TenPatchDrawable loadingAnimation2; public static UndoableManager undoableManager; public static ProjectData projectData; public static JsonData jsonData; public static AtlasData atlasData; public static RootTable rootTable; public static IbeamListener ibeamListener; public static MainListener mainListener; public static HandListener handListener; public static ScrollFocusListener scrollFocusListener; public static ResizeArrowListener verticalResizeArrowListener; public static ResizeArrowListener horizontalResizeArrowListener; public static TooltipManager tooltipManager; public static FileHandle appFolder; private String[] args; public static Main main; public static SkeletonRenderer skeletonRenderer; public static SkeletonData floppySkeletonData; public static AnimationStateData floppyAnimationStateData; public static SkeletonData uiScaleSkeletonData; public static AnimationStateData uiScaleAnimationStateData; public static SkeletonData textraTypistLogoSkeletonData; public static AnimationStateData textraTypistLogoAnimationStateData; public static SkeletonData arrowSkeletonData; public static AnimationStateData arrowAnimationStateData; public static TinyVGAssetLoader tinyVGAssetLoader; private static final int SPINE_MAX_VERTS = 32767; private static TinyVGDrawable drawable; public static PopColorPickerStyle popColorPickerStyle; public Main (String[] args) { this.args = args; main = this; } @Override public void create() { appFolder = Gdx.files.external(".skincomposer/"); skin = new FreeTypeSkin(Gdx.files.internal("skin-composer-ui/skin-composer-ui.json")); viewport = new ScreenViewport(); // viewport.setUnitsPerPixel(.5f); var batch = new PolygonSpriteBatch(SPINE_MAX_VERTS); stage = new Stage(viewport, batch); Gdx.input.setInputProcessor(stage); shapeDrawer = new TinyVGShapeDrawer(stage.getBatch(), skin.getRegion("white")); graphDrawer = new GraphDrawer(shapeDrawer); tinyVGAssetLoader = new TinyVGAssetLoader(); skeletonRenderer = new SkeletonRenderer(); var skeletonJson = new SkeletonJson(Main.skin.getAtlas()); floppySkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/floppy.json")); floppyAnimationStateData = new AnimationStateData(floppySkeletonData); uiScaleSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/uiscale.json")); uiScaleAnimationStateData = new AnimationStateData(uiScaleSkeletonData); textraTypistLogoSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/TextraTypist Logo.json")); textraTypistLogoAnimationStateData = new AnimationStateData(textraTypistLogoSkeletonData); arrowSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/arrow-animation.json")); arrowAnimationStateData = new AnimationStateData(arrowSkeletonData); popColorPickerStyle = new PopColorPickerStyle(); popColorPickerStyle.background = skin.getDrawable("cp-bg-10"); popColorPickerStyle.stageBackground = skin.getDrawable("stage-background"); popColorPickerStyle.titleBarBackground = skin.getDrawable("cp-title-bar-10"); popColorPickerStyle.labelStyle = skin.get("tt", LabelStyle.class); popColorPickerStyle.fileTextButtonStyle = skin.get("cp-file", TextButtonStyle.class); popColorPickerStyle.scrollPaneStyle = skin.get("tt", ScrollPaneStyle.class); popColorPickerStyle.colorSwatch = skin.getDrawable("tt-color-swatch"); popColorPickerStyle.colorSwatchNew = skin.getDrawable("tt-color-swatch-new"); popColorPickerStyle.colorSwatchPopBackground = skin.getDrawable("tt-panel-10"); popColorPickerStyle.colorSwatchPopPreview = skin.getDrawable("tt-color-swatch-10"); popColorPickerStyle.previewSwatchBackground = skin.getDrawable("tt-swatch"); popColorPickerStyle.previewSwatchOld = skin.getDrawable("tt-swatch-old"); popColorPickerStyle.previewSwatchNew = skin.getDrawable("tt-swatch-new"); popColorPickerStyle.previewSwatchSingleBackground = skin.getDrawable("tt-swatch-null"); popColorPickerStyle.previewSwatchSingle = skin.getDrawable("tt-swatch-new-null"); popColorPickerStyle.textFieldStyle = skin.get("cp", TextFieldStyle.class); popColorPickerStyle.hexTextFieldStyle = skin.get("cp-hexfield", TextFieldStyle.class); popColorPickerStyle.textButtonStyle = skin.get("cp", TextButtonStyle.class); popColorPickerStyle.colorSliderBackground = skin.getDrawable("tt-slider-10"); popColorPickerStyle.colorKnobCircleBackground = skin.getDrawable("tt-color-ball"); popColorPickerStyle.colorKnobCircleForeground = skin.getDrawable("tt-color-ball-interior"); popColorPickerStyle.colorSliderKnobHorizontal = skin.getDrawable("tt-slider-knob"); popColorPickerStyle.colorSliderKnobVertical = skin.getDrawable("tt-slider-knob-vertical"); popColorPickerStyle.radioButtonStyle = skin.get("cp-radio", ImageButtonStyle.class); popColorPickerStyle.increaseButtonStyle = skin.get("cp-increase", ImageButtonStyle.class); popColorPickerStyle.decreaseButtonStyle = skin.get("cp-decrease", ImageButtonStyle.class); popColorPickerStyle.checkerBackground = skin.getDrawable("tt-checker-10"); initDefaults(); populate(); resizeUiScale(projectData.getUiScale()); } private void initDefaults() { if (Utils.isMac()) System.setProperty("java.awt.headless", "true"); skin.getFont("font").getData().markupEnabled = true; //copy defaults.json to temp folder if it doesn't exist var fileHandle = appFolder.child("texturepacker/atlas-export-settings.json"); if (!fileHandle.exists()) { Gdx.files.internal("atlas-export-settings.json").copyTo(fileHandle); } //copy atlas settings for preview to temp folder if it doesn't exist fileHandle = appFolder.child("texturepacker/atlas-internal-settings.json"); if (!fileHandle.exists()) { Gdx.files.internal("atlas-internal-settings.json").copyTo(fileHandle); } //copy white-pixel.png for pixel drawables fileHandle = appFolder.child("texturepacker/white-pixel.png"); if (!fileHandle.exists()) { Gdx.files.internal("white-pixel.png").copyTo(fileHandle); } //copy preview fonts to preview fonts folder if they do not exist fileHandle = appFolder.child("preview fonts/IBMPlexSerif-Medium.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/IBMPlexSerif-Medium.ttf").copyTo(fileHandle); } fileHandle = appFolder.child("preview fonts/Pacifico-Regular.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/Pacifico-Regular.ttf").copyTo(fileHandle); } fileHandle = appFolder.child("preview fonts/PressStart2P-Regular.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/PressStart2P-Regular.ttf").copyTo(fileHandle); } fileHandle = appFolder.child("preview fonts/SourceSansPro-Regular.ttf"); if (!fileHandle.exists()) { Gdx.files.internal("preview fonts/SourceSansPro-Regular.ttf").copyTo(fileHandle); } ibeamListener = new IbeamListener(); dialogFactory = new DialogFactory(); projectData = new ProjectData(); projectData.randomizeId(); projectData.setMaxUndos(30); atlasData = projectData.getAtlasData(); jsonData = projectData.getJsonData(); newVersion = VERSION; if (projectData.isCheckingForUpdates()) { checkForUpdates(this); } undoableManager = new UndoableManager(this); desktopWorker.attachLogListener(); desktopWorker.setCloseListener(() -> { dialogFactory.showCloseDialog(new DialogListener() { @Override public void opened() { desktopWorker.removeFilesDroppedListener(rootTable.getFilesDroppedListener()); } @Override public void closed() { desktopWorker.addFilesDroppedListener(rootTable.getFilesDroppedListener()); } }); return false; }); loadingAnimation = skin.get("loading-animation", TenPatchDrawable.class); loadingAnimation2 = skin.get("loading-animation2", TenPatchDrawable.class); projectData.getAtlasData().clearTempData(); handListener = new HandListener(); scrollFocusListener = new ScrollFocusListener(stage); verticalResizeArrowListener = new ResizeArrowListener(true); horizontalResizeArrowListener = new ResizeArrowListener(false); tooltipManager = new TooltipManager(); tooltipManager.animations = false; tooltipManager.initialTime = .4f; tooltipManager.resetTime = 0.0f; tooltipManager.subsequentTime = 0.0f; tooltipManager.maxWidth = 400f; tooltipManager.hideAll(); tooltipManager.instant(); } private void populate() { stage.clear(); rootTable = new RootTable(); rootTable.setFillParent(true); mainListener = new MainListener(); rootTable.addListener(mainListener); rootTable.populate(); stage.addActor(rootTable); rootTable.updateRecentFiles(); //pass arguments if (!mainListener.argumentsPassed(args)) { //show welcome screen if there are no valid arguments mainListener.createWelcomeListener(); } } @Override public void render() { Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); for (var tenPatch : skin.getAll(TenPatchDrawable.class)) { tenPatch.value.update(Gdx.graphics.getDeltaTime()); } stage.draw(); } @Override public void resize(int width, int height) { if (width != 0 && height != 0) { stage.getViewport().update(width, height, true); rootTable.fire(new StageResizeEvent(width, height)); } } @Override public void dispose() { stage.dispose(); skin.dispose(); } public void resizeUiScale(int scale) { resizeUiScale(scale, scale > 1); } public void resizeUiScale(int scale, boolean large) { if (large) { desktopWorker.sizeWindowToFit(1440, 1440, 50, Gdx.graphics); } else { desktopWorker.sizeWindowToFit(800, 800, 50, Gdx.graphics); } desktopWorker.centerWindow(Gdx.graphics); viewport.setUnitsPerPixel(1f / scale); viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true); } public static Class basicToStyleClass(Class clazz) { int i = 0; for (Class basicClass : BASIC_CLASSES) { if (clazz.equals(basicClass)) { break; } else { i++; } } return i < STYLE_CLASSES.length ? STYLE_CLASSES[i] : null; } public static Class styleToBasicClass(Class clazz) { int i = 0; for (Class styleClass : STYLE_CLASSES) { if (clazz.equals(styleClass)) { break; } else { i++; } } return BASIC_CLASSES[i]; } public static void checkForUpdates(Main main) { Thread thread = new Thread(new Runnable() { @Override public void run() { HttpRequestBuilder requestBuilder = new HttpRequestBuilder(); HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://raw.githubusercontent.com/raeleus/skin-composer/master/version").build(); Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() { @Override public void handleHttpResponse(Net.HttpResponse httpResponse) { newVersion = httpResponse.getResultAsString(); Gdx.app.postRunnable(new Runnable() { @Override public void run() { main.rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.CHECK_FOR_UPDATES_COMPLETE)); } }); } @Override public void failed(Throwable t) { newVersion = VERSION; } @Override public void cancelled() { newVersion = VERSION; } }); } }); thread.start(); } public static TextTooltip fixTooltip(TextTooltip toolTip) { toolTip.getContainer().width(new Value() { public float get (@Null Actor context) { return Math.min(toolTip.getManager().maxWidth, toolTip.getActor().getGlyphLayout().width); } }); return toolTip; } }
Clean up imports.
core/src/com/ray3k/skincomposer/Main.java
Clean up imports.
<ide><path>ore/src/com/ray3k/skincomposer/Main.java <ide> import com.badlogic.gdx.Net.HttpMethods; <ide> import com.badlogic.gdx.Net.HttpRequest; <ide> import com.badlogic.gdx.files.FileHandle; <del>import com.badlogic.gdx.graphics.Cursor; <ide> import com.badlogic.gdx.graphics.GL20; <ide> import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; <ide> import com.badlogic.gdx.net.HttpRequestBuilder;
Java
mit
b4208c8e5b33da680ff09ed60ce6c6928271f164
0
Mitsugaru/KarmicJail
package com.mitsugaru.karmicjail; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import lib.Mitsugaru.SQLibrary.Database.Query; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import com.mitsugaru.karmicjail.DBHandler.Field; import com.mitsugaru.karmicjail.DBHandler.Table; import com.mitsugaru.karmicjail.KarmicJail.JailStatus; import com.mitsugaru.karmicjail.KarmicJail.PrisonerInfo; import com.mitsugaru.karmicjail.events.JailEvent; import com.platymuus.bukkit.permissions.Group; import com.platymuus.bukkit.permissions.PermissionsPlugin; public class JailLogic { private static KarmicJail plugin; private static Config config; private static PermCheck perm; private static DBHandler database; private final static DateFormat dateFormat = new SimpleDateFormat( "MM-dd-yyyy 'at' HH:mm z"); public static void init(KarmicJail plugin) { JailLogic.plugin = plugin; JailLogic.perm = plugin.getPermissions(); JailLogic.config = plugin.getPluginConfig(); JailLogic.database = plugin.getDatabaseHandler(); } /** * Jails a player * * @param sender * of command * @param name * of player to be jailed * @param reason * for being jailed * @param minutes * for how long they're in jail * @param boolean to determine of player has a timed release */ public static void jailPlayer(CommandSender sender, String inName, String reason, int minutes, boolean timedCom) { // Check if player is already jailed: if (playerIsJailed(inName) || playerIsPendingJail(inName)) { sender.sendMessage(ChatColor.RED + "That player is already in jail!"); } else { // Check if player is in database String name = getPlayerInDatabase(inName); if (name == null) { sender.sendMessage(ChatColor.YELLOW + " Player '" + ChatColor.GREEN + inName + ChatColor.YELLOW + "' has never been on server! Adding to database..."); // Player has never been on server, adding to list addPlayerToDatabase(inName); name = inName; } if (config.removeGroups) { // Save groups savePlayerGroups(name); // Remove all groups removePlayerGroups(name); } // Add to jail group perm.playerAddGroup(config.jailLoc.getWorld().getName(), name, config.jailGroup); // Grab duration long duration = 0; boolean timed = timedCom; if (config.timePerm) { if (!perm.has(sender, "KarmicJail.timed")) { timed = false; sender.sendMessage(ChatColor.RED + "Cannot put time on jailed player. Lack Permission: KarmicJail.timed"); } } if (timed) { duration = minutes * KarmicJail.minutesToTicks; } updatePlayerTime(name, duration); // Grab player from server if they are online final Player player = plugin.getServer().getPlayer(name); if (player != null) { if (player.isOnline()) { // Set previous location setPlayerLastLocation(name, player.getLocation()); // Move to jail if (config.jailTeleport) { player.teleport(config.jailLoc); } // Set inventory setPlayerInventory(name, player.getInventory(), config.clearInventory); // Set status to jailed setPlayerStatus(JailStatus.JAILED, name); // Notify player if (reason.equals("")) { player.sendMessage(ChatColor.RED + "Jailed by " + ChatColor.AQUA + sender.getName() + ChatColor.RED); } else { player.sendMessage(ChatColor.RED + "Jailed by " + ChatColor.AQUA + sender.getName() + ChatColor.RED + " for: " + ChatColor.GRAY + plugin.colorizeText(reason)); } if (timed) { player.sendMessage(ChatColor.AQUA + "Time in jail: " + ChatColor.GOLD + plugin.prettifyMinutes(minutes)); // Create thread to release player KarmicJail.getJailThreads().put(name, new JailTask(plugin, name, duration)); } } else { // Set player status to pending setPlayerStatus(JailStatus.PENDINGJAIL, name); } } else { // Set player status to pending setPlayerStatus(JailStatus.PENDINGJAIL, name); } try { final String date = dateFormat.format(new Date()); final PreparedStatement statement = database.prepare("UPDATE " + Table.JAILED.getName() + " SET " + Field.JAILER.getColumnName() + "=?," + Field.DATE.getColumnName() + "=?," + Field.REASON.getColumnName() + "=?, " + Field.MUTE.getColumnName() + "=? WHERE " + Field.PLAYERNAME.getColumnName() + "=?;"); statement.setString(1, sender.getName()); statement.setString(2, date); statement.setString(3, reason); statement.setInt(4, 0); statement.setString(5, name); statement.executeUpdate(); statement.close(); // Add to history with same information StringBuilder sb = new StringBuilder(); sb.append(ChatColor.AQUA + name + ChatColor.RED + " was jailed on " + ChatColor.GREEN + date + ChatColor.RED + " by " + ChatColor.GOLD + sender.getName()); if (!reason.equals("")) { sb.append(ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(reason)); } database.addToHistory(name, sb.toString()); // Notify sender.sendMessage(ChatColor.RED + name + ChatColor.AQUA + " sent to jail."); final PrisonerInfo pi = new PrisonerInfo(name, sender.getName(), date, reason, duration, false); plugin.getCommander().addToCache(name, pi); // Throw jail event plugin.getServer().getPluginManager() .callEvent(new JailEvent("JailEvent", pi)); // Broadcast if necessary if (config.broadcastJail) { // Setup broadcast string sb = new StringBuilder(); sb.append(ChatColor.AQUA + pi.name + ChatColor.RED + " was jailed on " + ChatColor.GREEN + pi.date + ChatColor.RED + " by " + ChatColor.GOLD + pi.jailer); if (!pi.reason.equals("")) { sb.append(ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(pi.reason)); } if (pi.mute) { sb.append(ChatColor.GRAY + " - " + ChatColor.DARK_RED + "MUTED"); } // Broadcast if (config.broadcastPerms) { plugin.getServer().broadcast(sb.toString(), "KarmicJail.broadcast"); } else { plugin.getServer().broadcastMessage(sb.toString()); } } } catch (SQLException e) { plugin.getLogger().warning("SQL Exception on jail command"); e.printStackTrace(); } } } /** * Unjails a player * * @param sender * of command * @param name * of jailed player * @param fromTempJail * , if the jailed player's time ran out */ public static void unjailPlayer(CommandSender sender, String inName, boolean fromTempJail) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } // Check if player is in jail: final JailStatus currentStatus = getPlayerStatus(name); if (currentStatus == JailStatus.FREED || currentStatus == JailStatus.PENDINGFREE) { sender.sendMessage(ChatColor.RED + "That player is not in jail!"); return; } // Grab player if on server Player player = plugin.getServer().getPlayer(name); // Remove jail group perm.playerRemoveGroup(config.jailLoc.getWorld(), name, config.jailGroup); if (config.removeGroups) { // Return previous groups returnGroups(name); } // Remove viewers final Set<String> viewList = new HashSet<String>(); for (Map.Entry<String, JailInventoryHolder> entry : Commander.inv .entrySet()) { if (entry.getValue().getTarget().equals(name)) { final Player viewer = plugin.getServer().getPlayer( entry.getKey()); if (viewer != null) { viewer.closeInventory(); } viewList.add(entry.getKey()); } } for (String viewer : viewList) { Commander.inv.remove(viewer); } plugin.getCommander().removeFromCache(name); // Check if player is offline: if (player == null) { setPlayerStatus(JailStatus.PENDINGFREE, name); sender.sendMessage(ChatColor.GOLD + name + ChatColor.AQUA + " will be released from jail on login."); return; } freePlayer(sender, inName, fromTempJail); } public static void unjailPlayer(CommandSender sender, String name) { unjailPlayer(sender, name, false); } public static void freePlayer(CommandSender sender, String name) { freePlayer(sender, name, false); } public static void freePlayer(CommandSender sender, String inName, boolean fromTempJail) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } // Grab player if on server Player player = plugin.getServer().getPlayer(name); if (player != null) { // Return items if any if (config.returnInventory) { Map<Integer, ItemStack> items = database.getPlayerItems(name); for (Map.Entry<Integer, ItemStack> item : items.entrySet()) { try { player.getInventory().setItem(item.getKey().intValue(), item.getValue()); } catch (ArrayIndexOutOfBoundsException e) { // Ignore } } } // Clear other columns database.resetPlayer(name); // Move player out of jail if (config.unjailTeleport) { player.teleport(config.unjailLoc); } // Change status setPlayerStatus(JailStatus.FREED, name); // Remove task if (KarmicJail.getJailThreads().containsKey(name)) { int id = KarmicJail.getJailThreads().get(name).getId(); if (id != -1) { plugin.getServer().getScheduler().cancelTask(id); } KarmicJail.removeTask(name); } player.sendMessage(ChatColor.AQUA + "You have been released from jail!"); if (fromTempJail) { // Also notify jailer if they're online Player jailer = plugin.getServer().getPlayer(getJailer(name)); if (jailer != null) { jailer.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.AQUA + " auto-unjailed."); } // Notify sender sender.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.AQUA + " auto-unjailed."); } else { sender.sendMessage(ChatColor.GOLD + name + ChatColor.AQUA + " removed from jail."); } // Broadcast if necessary if (config.broadcastUnjail) { // Setup broadcast string final StringBuilder sb = new StringBuilder(); sb.append(ChatColor.AQUA + name); if (fromTempJail) { sb.append(ChatColor.RED + " was auto-unjailed by "); } else { sb.append(ChatColor.RED + " was unjailed by "); } sb.append(ChatColor.GOLD + sender.getName()); // Broadcast if (config.broadcastPerms) { plugin.getServer().broadcast(sb.toString(), "KarmicJail.broadcast"); } else { plugin.getServer().broadcastMessage(sb.toString()); } } } } /** * Checks if the player was jailed while offline * * @param Name * of player * @return True if pending jailed, else false */ public static boolean playerIsPendingJail(String player) { boolean jailed = false; String name = getPlayerInDatabase(player); if (name == null) { name = player; } switch (getPlayerStatus(name)) { case PENDINGJAIL: { jailed = true; break; } default: break; } return jailed; } /** * Checks if the player is in jail * * @param Name * of player * @return true if jailed, else false */ public static boolean playerIsJailed(String player) { boolean jailed = false; String name = getPlayerInDatabase(player); if (name == null) { name = player; } switch (getPlayerStatus(name)) { case JAILED: { jailed = true; break; } default: break; } return jailed; } /** * Grabs player's time left in jail * * @param name * of player * @return long of time left to serve */ public static long getPlayerTime(String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } return (long) database.getDoubleField(Field.TIME, name); } /** * Sets a player's time * * @param name * of player * @param duration * of time */ public static void updatePlayerTime(String player, long duration) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } database.standardQuery("UPDATE " + config.tablePrefix + "jailed SET time='" + duration + "' WHERE playername='" + name + "';"); } /** * Check if player exists in master database * * @param name * of player * @return Name of player in database, else null */ public static String getPlayerInDatabase(String name) { String has = null; try { Query rs = database.select("SELECT * FROM " + Table.JAILED.getName() + ";"); if (rs.getResult().next()) { do { if (name.equalsIgnoreCase(rs.getResult().getString( Field.PLAYERNAME.getColumnName()))) { has = rs.getResult().getString("playername"); break; } } while (rs.getResult().next()); } rs.closeQuery(); } catch (SQLException e) { plugin.getLogger().warning(KarmicJail.prefix + " SQL Exception"); e.printStackTrace(); } return has; } /** * Adds a player to the database if they do not exist * * @param name * of player */ public static void addPlayerToDatabase(String name) { try { boolean has = false; Query rs = database.select("SELECT COUNT(*) FROM " + config.tablePrefix + "jailed WHERE playername='" + name + "';"); if (rs.getResult().next()) { final int count = rs.getResult().getInt(1); if (!rs.getResult().wasNull()) { if (count > 0) { has = true; } } } rs.closeQuery(); if (!has) { // Add to database database.standardQuery("INSERT INTO " + config.tablePrefix + "jailed (playername,status,time) VALUES ('" + name + "', '" + JailStatus.FREED + "', '-1');"); } } catch (SQLException e) { plugin.getLogger().warning(KarmicJail.prefix + " SQL Exception"); e.printStackTrace(); } } /** * Checks to see if the player has a time associated with their jail * sentence * * @param Name * of player * @return true if player has a valid time, else false */ public static boolean playerIsTempJailed(String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } double time = database.getDoubleField(Field.TIME, name); if (time > 0) { return true; } return false; } public static void setJailTime(CommandSender sender, String name, int minutes) { // Check if player is in jail: if (!playerIsJailed(name) && !playerIsPendingJail(name)) { sender.sendMessage(ChatColor.RED + "That player is not in jail!"); return; } // Grab player if on server Player player = plugin.getServer().getPlayer(name); // Remove task if (KarmicJail.getJailThreads().containsKey(name)) { int id = KarmicJail.getJailThreads().get(name).getId(); if (id != -1) { plugin.getServer().getScheduler().cancelTask(id); } KarmicJail.removeTask(name); } // Jail indefinitely if 0 or negative if (minutes <= 0) { updatePlayerTime(name, minutes); sender.sendMessage(ChatColor.RED + name + ChatColor.AQUA + " is jailed forever."); if (player != null) { player.sendMessage(ChatColor.AQUA + "Jailed forever."); } } else { // Calculate time long duration = 0; duration = minutes * KarmicJail.minutesToTicks; updatePlayerTime(name, duration); if (player != null) { // Create thread to release player KarmicJail.getJailThreads().put(name, new JailTask(plugin, name, duration)); } sender.sendMessage(ChatColor.AQUA + "Time set to " + ChatColor.GOLD + minutes + ChatColor.AQUA + " for " + ChatColor.RED + name + ChatColor.AQUA + "."); if (player != null) { player.sendMessage(ChatColor.AQUA + "Time set to " + ChatColor.GOLD + minutes + ChatColor.AQUA + "."); } } } public static void setPlayerReason(String inName, String reason) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } database.setField(Field.REASON, name, reason, 0, 0); // Add to history if (!reason.equals("")) { database.addToHistory(name, ChatColor.GOLD + "Reason changed for " + ChatColor.AQUA + name + ChatColor.RED + " to " + ChatColor.GRAY + plugin.colorizeText(reason)); } // broadcast if (config.broadcastReason) { final String out = ChatColor.AQUA + name + ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(reason); if (config.broadcastPerms) { plugin.getServer().broadcast(out, "KarmicJail.broadcast"); } else { plugin.getServer().broadcastMessage(out); } } } /** * Grabs the reason for being in jail * * @param name * of player * @return String of jailer's reason */ public static String getJailReason(String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } String reason = database.getStringField(Field.REASON, name); if (reason.equals("")) { reason = "UNKOWN"; } return reason; } public static boolean playerIsMuted(String player) { boolean mute = false; String name = getPlayerInDatabase(player); if (name == null) { name = player; } int muteint = database.getIntField(Field.MUTE, name); if (muteint == 1) { mute = true; } return mute; } public static void mutePlayer(CommandSender sender, String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } // Check if player is in jail: if (!playerIsJailed(name) && !playerIsPendingJail(name)) { sender.sendMessage(ChatColor.RED + "That player is not in jail!"); return; } if (playerIsMuted(name)) { database.setField(Field.MUTE, name, null, 0, 0); sender.sendMessage(ChatColor.GOLD + name + ChatColor.GREEN + " unmuted"); } else { database.setField(Field.MUTE, name, null, 1, 0); sender.sendMessage(ChatColor.GOLD + name + ChatColor.RED + " muted"); } } /** * Returns the player's current status * * @param name * of player * @return String of the player's JailStatus */ public static JailStatus getPlayerStatus(String inName) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } String status = database.getStringField(Field.STATUS, name); if (status.equals(JailStatus.JAILED.name())) { return JailStatus.JAILED; } else if (status.equals(JailStatus.PENDINGFREE.name())) { return JailStatus.PENDINGFREE; } else if (status.equals(JailStatus.PENDINGJAIL.name())) { return JailStatus.PENDINGJAIL; } else { return JailStatus.FREED; } } /** * Sets a player's status * * @param JailStatus * to set to * @param name * of player */ public static void setPlayerStatus(JailStatus status, String inName) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } database.setField(Field.STATUS, name, status.name(), 0, 0); } /** * Saves the player's groups into database * * @param name * of player */ private static void savePlayerGroups(String name) { StringBuilder sb = new StringBuilder(); boolean append = false; for (String s : getGroups(name)) { sb.append(s + "&"); append = true; } if (append) { sb.deleteCharAt(sb.length() - 1); } database.setField(Field.GROUPS, name, sb.toString(), 0, 0); } /** * Removes all groups of a player * * @param name * of player */ private static void removePlayerGroups(String name) { if (perm.getName().equals("PermissionsBukkit")) { final PermissionsPlugin permission = (PermissionsPlugin) plugin .getServer().getPluginManager() .getPlugin("PermissionsBukkit"); for (Group group : permission.getGroups(name)) { perm.playerRemoveGroup(plugin.getServer().getWorlds().get(0), name, group.getName()); } } else { for (World w : plugin.getServer().getWorlds()) { String[] groups = perm.getPlayerGroups(w, name); for (String group : groups) { perm.playerRemoveGroup(w, name, group); } } } } /** * Returns a list of all the groups a player has * * @param name * of player * @return List of groups with associated world */ public static List<String> getGroups(String player) { List<String> list = new ArrayList<String>(); if (perm.getName().equals("PermissionsBukkit")) { final PermissionsPlugin permission = (PermissionsPlugin) plugin .getServer().getPluginManager() .getPlugin("PermissionsBukkit"); for (Group group : permission.getGroups(player)) { final String s = group.getName() + "!" + plugin.getServer().getWorlds().get(0).getName(); list.add(s); } } else { for (World w : plugin.getServer().getWorlds()) { String[] groups = perm.getPlayerGroups(w, player); for (String group : groups) { String s = group + "!" + w.getName(); if (!list.contains(s)) { list.add(s); } } } } return list; } /** * Restores the players groups from database storage * * @param name * of player */ private static void returnGroups(String name) { String groups = database.getStringField(Field.GROUPS, name); if (!groups.equals("")) { try { if (groups.contains("&")) { String[] cut = groups.split("&"); for (String group : cut) { String[] split = group.split("!"); perm.playerAddGroup(split[1], name, split[0]); } } else { String[] split = groups.split("!"); perm.playerAddGroup(split[1], name, split[0]); } } catch (ArrayIndexOutOfBoundsException a) { plugin.getLogger().warning( "Could not return groups for " + name); } } } /** * Gets the status of a player * * @param sender * of command * @param arguments * of command */ public static void jailStatus(CommandSender sender, String[] args) { if (!(sender instanceof Player) && args.length == 0) { sender.sendMessage(ChatColor.RED + "Must specify a player."); return; } final Player player = (args.length == 0) ? (Player) sender : plugin .getServer().getPlayer(args[0]); String temp = ""; if (player == null) { temp = args[0]; } else { temp = player.getName(); } String name = getPlayerInDatabase(temp); if (name == null) { name = temp; } if (!playerIsJailed(name) && !playerIsPendingJail(name)) { if (args.length == 0) sender.sendMessage(ChatColor.RED + "You are not jailed."); else sender.sendMessage(ChatColor.AQUA + name + ChatColor.RED + " is not jailed."); return; } final StringBuilder sb = new StringBuilder(); final String date = getJailDate(name); final String jailer = getJailer(name); final String reason = getJailReason(name); final boolean muted = playerIsMuted(name); if (args.length == 0) { sb.append(ChatColor.RED + "Jailed on " + ChatColor.GREEN + date + ChatColor.RED + " by " + ChatColor.GOLD + jailer); } else { sb.append(ChatColor.AQUA + name + ChatColor.RED + " was jailed on " + ChatColor.GREEN + date + ChatColor.RED + " by " + ChatColor.GOLD + jailer); } if (!reason.equals("UNKOWN")) { sb.append(ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(reason)); } if (muted) { sb.append(ChatColor.GRAY + " - " + ChatColor.DARK_RED + "MUTED"); } sender.sendMessage(sb.toString()); if (playerIsTempJailed(name)) { int minutes = (int) ((getPlayerTime(name) / KarmicJail.minutesToTicks)); if (player == null) { sender.sendMessage(ChatColor.AQUA + "Remaining jail time: " + ChatColor.GOLD + plugin.prettifyMinutes(minutes)); } else { // Player is online, check the thread for their remaining time if (KarmicJail.getJailThreads().containsKey(name)) { minutes = (int) (KarmicJail.getJailThreads().get(name) .remainingTime() / KarmicJail.minutesToTicks); sender.sendMessage(ChatColor.AQUA + "Remaining jail time: " + plugin.prettifyMinutes(minutes)); } } } } /** * Gets name of the jailer * * @param name * of person in jail * @return name of jailer */ private static String getJailer(String name) { String jailer = database.getStringField(Field.JAILER, name); if (jailer.equals("")) { jailer = "UNKOWN"; } return jailer; } /** * Grabs date of when player was originally jailed * * @param name * of person jailed * @return String of the date when player was jailed */ private static String getJailDate(String name) { String date = database.getStringField(Field.DATE, name); if (date.equals("")) { date = "UNKOWN"; } return date; } /** * Sets the jail location * * @param sender * of command * @param arguments * of command */ public static void setJail(CommandSender sender, String[] args) { if (!(sender instanceof Player) && args.length != 4) { sender.sendMessage(ChatColor.RED + "Only players can use that."); return; } if (args.length == 0) { Player player = (Player) sender; config.jailLoc = player.getLocation(); } else { if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) { sender.sendMessage(ChatColor.RED + "Invalid coordinate."); return; } config.jailLoc = new Location(plugin.getServer().getWorld(args[3]), Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2])); } config.set("jail.x", (int) config.jailLoc.getX()); config.set("jail.y", (int) config.jailLoc.getY()); config.set("jail.z", (int) config.jailLoc.getZ()); config.set("jail.world", config.jailLoc.getWorld().getName()); plugin.saveConfig(); sender.sendMessage(ChatColor.AQUA + "Jail point saved."); } /** * Sets the unjail location * * @param sender * of command * @param arguments * of command */ public static void setUnjail(CommandSender sender, String[] args) { if (!(sender instanceof Player) && args.length != 4) { sender.sendMessage(ChatColor.RED + "Only players can use that."); return; } if (args.length == 0) { Player player = (Player) sender; config.unjailLoc = player.getLocation(); } else { if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) { sender.sendMessage(ChatColor.RED + "Invalid coordinate."); return; } config.unjailLoc = new Location(plugin.getServer() .getWorld(args[3]), Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2])); } config.set("unjail.x", (int) config.unjailLoc.getX()); config.set("unjail.y", (int) config.unjailLoc.getY()); config.set("unjail.z", (int) config.unjailLoc.getZ()); config.set("unjail.world", config.unjailLoc.getWorld().getName()); plugin.saveConfig(); sender.sendMessage(ChatColor.AQUA + "Unjail point saved."); } /** * * @return location of jail */ public static Location getJailLocation() { return config.jailLoc; } /** * * @return location of unjail */ public static Location getUnjailLocation() { return config.unjailLoc; } /** * Teleports a player to unjail locaiton * * @param name * of player to be teleported */ public static void teleportOut(String name) { final Player player = plugin.getServer().getPlayer(name); if (player != null) { player.teleport(config.unjailLoc); } } public static void setPlayerLastLocation(String playername, Location location) { String name = getPlayerInDatabase(playername); if (name == null) { name = playername; } final String entry = location.getWorld().getName() + " " + location.getX() + " " + location.getY() + " " + location.getZ() + " " + location.getYaw() + " " + location.getPitch(); database.setField(Field.LAST_POSITION, name, entry, 0, 0); } public static Location getPlayerLastLocation(String playername) { Location location = null; String name = getPlayerInDatabase(playername); if (name == null) { name = playername; } final String entry = database.getStringField(Field.LAST_POSITION, name); if (!entry.equals("") && entry.contains(" ")) { try { final String[] split = entry.split(" "); final World world = plugin.getServer().getWorld(split[0]); if (world != null) { location = new Location(world, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]), Float.parseFloat(split[4]), Float.parseFloat(split[5])); } } catch (ArrayIndexOutOfBoundsException a) { plugin.getLogger().warning("Bad last location for: " + name); } catch (NumberFormatException n) { plugin.getLogger().warning("Bad last location for: " + name); } } return location; } public static void setPlayerInventory(String playername, Inventory inventory, boolean clear) { Map<Integer, ItemStack> items = new HashMap<Integer, ItemStack>(); if (inventory instanceof PlayerInventory) { PlayerInventory inv = (PlayerInventory) inventory; // Get normal inventory for (int i = 0; i < inventory.getSize(); i++) { try { final ItemStack item = inventory.getItem(i); if (item != null) { if (!item.getType().equals(Material.AIR)) { /* * plugin.getLogger().info( item.toString() + " at " * + i); */ items.put(new Integer(i), item); } } } catch (ArrayIndexOutOfBoundsException a) { // Ignore } catch (NullPointerException n) { // Ignore } } // TODO implement /* * ItemStack[] armor = inv.getArmorContents(); for (int i = 0; i < * armor.length; i++) { try { final ItemStack item = armor[i]; if * (item != null) { if (!item.getType().equals(Material.AIR)) { * plugin.getLogger().info( item.toString() + " at " + i); * items.put(new Integer(i + inv.getSize()), item); } } } catch * (ArrayIndexOutOfBoundsException a) { // Ignore } catch * (NullPointerException n) { // Ignore } } */ if (database.setPlayerItems(playername, items) && clear) { // clear inventory try { inv.clear(); final ItemStack[] cleared = new ItemStack[] { null, null, null, null }; inv.setArmorContents(cleared); } catch (ArrayIndexOutOfBoundsException e) { // ignore again } } } } }
KarmicJail/src/com/mitsugaru/karmicjail/JailLogic.java
package com.mitsugaru.karmicjail; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import lib.Mitsugaru.SQLibrary.Database.Query; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import com.mitsugaru.karmicjail.DBHandler.Field; import com.mitsugaru.karmicjail.DBHandler.Table; import com.mitsugaru.karmicjail.KarmicJail.JailStatus; import com.mitsugaru.karmicjail.KarmicJail.PrisonerInfo; import com.mitsugaru.karmicjail.events.JailEvent; import com.platymuus.bukkit.permissions.Group; import com.platymuus.bukkit.permissions.PermissionsPlugin; public class JailLogic { private static KarmicJail plugin; private static Config config; private static PermCheck perm; private static DBHandler database; private final static DateFormat dateFormat = new SimpleDateFormat( "MM-dd-yyyy 'at' HH:mm z"); public static void init(KarmicJail plugin) { JailLogic.plugin = plugin; JailLogic.perm = plugin.getPermissions(); JailLogic.config = plugin.getPluginConfig(); JailLogic.database = plugin.getDatabaseHandler(); } /** * Jails a player * * @param sender * of command * @param name * of player to be jailed * @param reason * for being jailed * @param minutes * for how long they're in jail * @param boolean to determine of player has a timed release */ public static void jailPlayer(CommandSender sender, String inName, String reason, int minutes, boolean timedCom) { // Check if player is already jailed: if (playerIsJailed(inName) || playerIsPendingJail(inName)) { sender.sendMessage(ChatColor.RED + "That player is already in jail!"); } else { // Check if player is in database String name = getPlayerInDatabase(inName); if (name == null) { sender.sendMessage(ChatColor.YELLOW + " Player '" + ChatColor.GREEN + inName + ChatColor.YELLOW + "' has never been on server! Adding to database..."); // Player has never been on server, adding to list addPlayerToDatabase(inName); name = inName; } if (config.removeGroups) { // Save groups savePlayerGroups(name); // Remove all groups removePlayerGroups(name); } // Add to jail group perm.playerAddGroup(config.jailLoc.getWorld().getName(), name, config.jailGroup); // Grab duration long duration = 0; boolean timed = timedCom; if (config.timePerm) { if (!perm.has(sender, "KarmicJail.timed")) { timed = false; sender.sendMessage(ChatColor.RED + "Cannot put time on jailed player. Lack Permission: KarmicJail.timed"); } } if (timed) { duration = minutes * KarmicJail.minutesToTicks; } updatePlayerTime(name, duration); // Grab player from server if they are online final Player player = plugin.getServer().getPlayer(name); if (player != null) { if (player.isOnline()) { // Set previous location setPlayerLastLocation(name, player.getLocation()); // Move to jail if (config.jailTeleport) { player.teleport(config.jailLoc); } // Set inventory setPlayerInventory(name, player.getInventory(), config.clearInventory); // Set status to jailed setPlayerStatus(JailStatus.JAILED, name); // Notify player if (reason.equals("")) { player.sendMessage(ChatColor.RED + "Jailed by " + ChatColor.AQUA + sender.getName() + ChatColor.RED); } else { player.sendMessage(ChatColor.RED + "Jailed by " + ChatColor.AQUA + sender.getName() + ChatColor.RED + " for: " + ChatColor.GRAY + plugin.colorizeText(reason)); } if (timed) { player.sendMessage(ChatColor.AQUA + "Time in jail: " + ChatColor.GOLD + plugin.prettifyMinutes(minutes)); // Create thread to release player KarmicJail.getJailThreads().put(name, new JailTask(plugin, name, duration)); } } else { // Set player status to pending setPlayerStatus(JailStatus.PENDINGJAIL, name); } } else { // Set player status to pending setPlayerStatus(JailStatus.PENDINGJAIL, name); } try { final String date = dateFormat.format(new Date()); final PreparedStatement statement = database.prepare("UPDATE " + Table.JAILED.getName() + " SET " + Field.JAILER.getColumnName() + "=?," + Field.DATE.getColumnName() + "=?," + Field.REASON.getColumnName() + "=?, " + Field.MUTE.getColumnName() + "=? WHERE " + Field.PLAYERNAME.getColumnName() + "=?;"); statement.setString(1, sender.getName()); statement.setString(2, date); statement.setString(3, reason); statement.setInt(4, 0); statement.setString(5, name); statement.executeUpdate(); statement.close(); // Add to history with same information StringBuilder sb = new StringBuilder(); sb.append(ChatColor.AQUA + name + ChatColor.RED + " was jailed on " + ChatColor.GREEN + date + ChatColor.RED + " by " + ChatColor.GOLD + sender.getName()); if (!reason.equals("")) { sb.append(ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(reason)); } database.addToHistory(name, sb.toString()); // Notify sender.sendMessage(ChatColor.RED + name + ChatColor.AQUA + " sent to jail."); final PrisonerInfo pi = new PrisonerInfo(name, sender.getName(), date, reason, duration, false); plugin.getCommander().addToCache(name, pi); // Throw jail event plugin.getServer().getPluginManager() .callEvent(new JailEvent("JailEvent", pi)); // Broadcast if necessary if (config.broadcastJail) { // Setup broadcast string sb = new StringBuilder(); sb.append(ChatColor.AQUA + pi.name + ChatColor.RED + " was jailed on " + ChatColor.GREEN + pi.date + ChatColor.RED + " by " + ChatColor.GOLD + pi.jailer); if (!pi.reason.equals("")) { sb.append(ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(pi.reason)); } if (pi.mute) { sb.append(ChatColor.GRAY + " - " + ChatColor.DARK_RED + "MUTED"); } // Broadcast if (config.broadcastPerms) { plugin.getServer().broadcast(sb.toString(), "KarmicJail.broadcast"); } else { plugin.getServer().broadcastMessage(sb.toString()); } } } catch (SQLException e) { plugin.getLogger().warning("SQL Exception on jail command"); e.printStackTrace(); } } } /** * Unjails a player * * @param sender * of command * @param name * of jailed player * @param fromTempJail * , if the jailed player's time ran out */ public static void unjailPlayer(CommandSender sender, String inName, boolean fromTempJail) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } // Check if player is in jail: final JailStatus currentStatus = getPlayerStatus(name); if (currentStatus == JailStatus.FREED || currentStatus == JailStatus.PENDINGFREE) { sender.sendMessage(ChatColor.RED + "That player is not in jail!"); return; } // Grab player if on server Player player = plugin.getServer().getPlayer(name); // Remove jail group perm.playerRemoveGroup(config.jailLoc.getWorld(), name, config.jailGroup); if (config.removeGroups) { // Return previous groups returnGroups(name); } // Remove viewers final Set<String> viewList = new HashSet<String>(); for (Map.Entry<String, JailInventoryHolder> entry : Commander.inv .entrySet()) { if (entry.getValue().getTarget().equals(name)) { final Player viewer = plugin.getServer().getPlayer( entry.getKey()); if (viewer != null) { viewer.closeInventory(); } viewList.add(entry.getKey()); } } for (String viewer : viewList) { Commander.inv.remove(viewer); } plugin.getCommander().removeFromCache(name); // Check if player is offline: if (player == null) { setPlayerStatus(JailStatus.PENDINGFREE, name); sender.sendMessage(ChatColor.GOLD + name + ChatColor.AQUA + " will be released from jail on login."); return; } freePlayer(sender, inName, fromTempJail); } public static void unjailPlayer(CommandSender sender, String name) { unjailPlayer(sender, name, false); } public static void freePlayer(CommandSender sender, String name) { freePlayer(sender, name, false); } public static void freePlayer(CommandSender sender, String inName, boolean fromTempJail) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } // Grab player if on server Player player = plugin.getServer().getPlayer(name); if (player != null) { //Return items if any Map<Integer, ItemStack> items = database.getPlayerItems(name); for (Map.Entry<Integer, ItemStack> item : items.entrySet()) { try { player.getInventory().setItem(item.getKey().intValue(), item.getValue()); } catch (ArrayIndexOutOfBoundsException e) { // Ignore } } // Clear other columns database.resetPlayer(name); // Move player out of jail if (config.unjailTeleport) { player.teleport(config.unjailLoc); } // Change status setPlayerStatus(JailStatus.FREED, name); // Remove task if (KarmicJail.getJailThreads().containsKey(name)) { int id = KarmicJail.getJailThreads().get(name).getId(); if (id != -1) { plugin.getServer().getScheduler().cancelTask(id); } KarmicJail.removeTask(name); } player.sendMessage(ChatColor.AQUA + "You have been released from jail!"); if (fromTempJail) { // Also notify jailer if they're online Player jailer = plugin.getServer().getPlayer(getJailer(name)); if (jailer != null) { jailer.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.AQUA + " auto-unjailed."); } // Notify sender sender.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.AQUA + " auto-unjailed."); } else { sender.sendMessage(ChatColor.GOLD + name + ChatColor.AQUA + " removed from jail."); } // Broadcast if necessary if (config.broadcastUnjail) { // Setup broadcast string final StringBuilder sb = new StringBuilder(); sb.append(ChatColor.AQUA + name); if (fromTempJail) { sb.append(ChatColor.RED + " was auto-unjailed by "); } else { sb.append(ChatColor.RED + " was unjailed by "); } sb.append(ChatColor.GOLD + sender.getName()); // Broadcast if (config.broadcastPerms) { plugin.getServer().broadcast(sb.toString(), "KarmicJail.broadcast"); } else { plugin.getServer().broadcastMessage(sb.toString()); } } } } /** * Checks if the player was jailed while offline * * @param Name * of player * @return True if pending jailed, else false */ public static boolean playerIsPendingJail(String player) { boolean jailed = false; String name = getPlayerInDatabase(player); if (name == null) { name = player; } switch (getPlayerStatus(name)) { case PENDINGJAIL: { jailed = true; break; } default: break; } return jailed; } /** * Checks if the player is in jail * * @param Name * of player * @return true if jailed, else false */ public static boolean playerIsJailed(String player) { boolean jailed = false; String name = getPlayerInDatabase(player); if (name == null) { name = player; } switch (getPlayerStatus(name)) { case JAILED: { jailed = true; break; } default: break; } return jailed; } /** * Grabs player's time left in jail * * @param name * of player * @return long of time left to serve */ public static long getPlayerTime(String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } return (long) database.getDoubleField(Field.TIME, name); } /** * Sets a player's time * * @param name * of player * @param duration * of time */ public static void updatePlayerTime(String player, long duration) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } database.standardQuery("UPDATE " + config.tablePrefix + "jailed SET time='" + duration + "' WHERE playername='" + name + "';"); } /** * Check if player exists in master database * * @param name * of player * @return Name of player in database, else null */ public static String getPlayerInDatabase(String name) { String has = null; try { Query rs = database.select("SELECT * FROM " + Table.JAILED.getName() + ";"); if (rs.getResult().next()) { do { if (name.equalsIgnoreCase(rs.getResult().getString( Field.PLAYERNAME.getColumnName()))) { has = rs.getResult().getString("playername"); break; } } while (rs.getResult().next()); } rs.closeQuery(); } catch (SQLException e) { plugin.getLogger().warning(KarmicJail.prefix + " SQL Exception"); e.printStackTrace(); } return has; } /** * Adds a player to the database if they do not exist * * @param name * of player */ public static void addPlayerToDatabase(String name) { try { boolean has = false; Query rs = database.select("SELECT COUNT(*) FROM " + config.tablePrefix + "jailed WHERE playername='" + name + "';"); if (rs.getResult().next()) { final int count = rs.getResult().getInt(1); if (!rs.getResult().wasNull()) { if (count > 0) { has = true; } } } rs.closeQuery(); if (!has) { // Add to database database.standardQuery("INSERT INTO " + config.tablePrefix + "jailed (playername,status,time) VALUES ('" + name + "', '" + JailStatus.FREED + "', '-1');"); } } catch (SQLException e) { plugin.getLogger().warning(KarmicJail.prefix + " SQL Exception"); e.printStackTrace(); } } /** * Checks to see if the player has a time associated with their jail * sentence * * @param Name * of player * @return true if player has a valid time, else false */ public static boolean playerIsTempJailed(String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } double time = database.getDoubleField(Field.TIME, name); if (time > 0) { return true; } return false; } public static void setJailTime(CommandSender sender, String name, int minutes) { // Check if player is in jail: if (!playerIsJailed(name) && !playerIsPendingJail(name)) { sender.sendMessage(ChatColor.RED + "That player is not in jail!"); return; } // Grab player if on server Player player = plugin.getServer().getPlayer(name); // Remove task if (KarmicJail.getJailThreads().containsKey(name)) { int id = KarmicJail.getJailThreads().get(name).getId(); if (id != -1) { plugin.getServer().getScheduler().cancelTask(id); } KarmicJail.removeTask(name); } // Jail indefinitely if 0 or negative if (minutes <= 0) { updatePlayerTime(name, minutes); sender.sendMessage(ChatColor.RED + name + ChatColor.AQUA + " is jailed forever."); if (player != null) { player.sendMessage(ChatColor.AQUA + "Jailed forever."); } } else { // Calculate time long duration = 0; duration = minutes * KarmicJail.minutesToTicks; updatePlayerTime(name, duration); if (player != null) { // Create thread to release player KarmicJail.getJailThreads().put(name, new JailTask(plugin, name, duration)); } sender.sendMessage(ChatColor.AQUA + "Time set to " + ChatColor.GOLD + minutes + ChatColor.AQUA + " for " + ChatColor.RED + name + ChatColor.AQUA + "."); if (player != null) { player.sendMessage(ChatColor.AQUA + "Time set to " + ChatColor.GOLD + minutes + ChatColor.AQUA + "."); } } } public static void setPlayerReason(String inName, String reason) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } database.setField(Field.REASON, name, reason, 0, 0); // Add to history if (!reason.equals("")) { database.addToHistory(name, ChatColor.GOLD + "Reason changed for " + ChatColor.AQUA + name + ChatColor.RED + " to " + ChatColor.GRAY + plugin.colorizeText(reason)); } // broadcast if (config.broadcastReason) { final String out = ChatColor.AQUA + name + ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(reason); if (config.broadcastPerms) { plugin.getServer().broadcast(out, "KarmicJail.broadcast"); } else { plugin.getServer().broadcastMessage(out); } } } /** * Grabs the reason for being in jail * * @param name * of player * @return String of jailer's reason */ public static String getJailReason(String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } String reason = database.getStringField(Field.REASON, name); if (reason.equals("")) { reason = "UNKOWN"; } return reason; } public static boolean playerIsMuted(String player) { boolean mute = false; String name = getPlayerInDatabase(player); if (name == null) { name = player; } int muteint = database.getIntField(Field.MUTE, name); if (muteint == 1) { mute = true; } return mute; } public static void mutePlayer(CommandSender sender, String player) { String name = getPlayerInDatabase(player); if (name == null) { name = player; } // Check if player is in jail: if (!playerIsJailed(name) && !playerIsPendingJail(name)) { sender.sendMessage(ChatColor.RED + "That player is not in jail!"); return; } if (playerIsMuted(name)) { database.setField(Field.MUTE, name, null, 0, 0); sender.sendMessage(ChatColor.GOLD + name + ChatColor.GREEN + " unmuted"); } else { database.setField(Field.MUTE, name, null, 1, 0); sender.sendMessage(ChatColor.GOLD + name + ChatColor.RED + " muted"); } } /** * Returns the player's current status * * @param name * of player * @return String of the player's JailStatus */ public static JailStatus getPlayerStatus(String inName) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } String status = database.getStringField(Field.STATUS, name); if (status.equals(JailStatus.JAILED.name())) { return JailStatus.JAILED; } else if (status.equals(JailStatus.PENDINGFREE.name())) { return JailStatus.PENDINGFREE; } else if (status.equals(JailStatus.PENDINGJAIL.name())) { return JailStatus.PENDINGJAIL; } else { return JailStatus.FREED; } } /** * Sets a player's status * * @param JailStatus * to set to * @param name * of player */ public static void setPlayerStatus(JailStatus status, String inName) { String name = getPlayerInDatabase(inName); if (name == null) { name = inName; } database.setField(Field.STATUS, name, status.name(), 0, 0); } /** * Saves the player's groups into database * * @param name * of player */ private static void savePlayerGroups(String name) { StringBuilder sb = new StringBuilder(); boolean append = false; for (String s : getGroups(name)) { sb.append(s + "&"); append = true; } if (append) { sb.deleteCharAt(sb.length() - 1); } database.setField(Field.GROUPS, name, sb.toString(), 0, 0); } /** * Removes all groups of a player * * @param name * of player */ private static void removePlayerGroups(String name) { if (perm.getName().equals("PermissionsBukkit")) { final PermissionsPlugin permission = (PermissionsPlugin) plugin .getServer().getPluginManager() .getPlugin("PermissionsBukkit"); for (Group group : permission.getGroups(name)) { perm.playerRemoveGroup(plugin.getServer().getWorlds().get(0), name, group.getName()); } } else { for (World w : plugin.getServer().getWorlds()) { String[] groups = perm.getPlayerGroups(w, name); for (String group : groups) { perm.playerRemoveGroup(w, name, group); } } } } /** * Returns a list of all the groups a player has * * @param name * of player * @return List of groups with associated world */ public static List<String> getGroups(String player) { List<String> list = new ArrayList<String>(); if (perm.getName().equals("PermissionsBukkit")) { final PermissionsPlugin permission = (PermissionsPlugin) plugin .getServer().getPluginManager() .getPlugin("PermissionsBukkit"); for (Group group : permission.getGroups(player)) { final String s = group.getName() + "!" + plugin.getServer().getWorlds().get(0).getName(); list.add(s); } } else { for (World w : plugin.getServer().getWorlds()) { String[] groups = perm.getPlayerGroups(w, player); for (String group : groups) { String s = group + "!" + w.getName(); if (!list.contains(s)) { list.add(s); } } } } return list; } /** * Restores the players groups from database storage * * @param name * of player */ private static void returnGroups(String name) { String groups = database.getStringField(Field.GROUPS, name); if (!groups.equals("")) { try { if (groups.contains("&")) { String[] cut = groups.split("&"); for (String group : cut) { String[] split = group.split("!"); perm.playerAddGroup(split[1], name, split[0]); } } else { String[] split = groups.split("!"); perm.playerAddGroup(split[1], name, split[0]); } } catch (ArrayIndexOutOfBoundsException a) { plugin.getLogger().warning( "Could not return groups for " + name); } } } /** * Gets the status of a player * * @param sender * of command * @param arguments * of command */ public static void jailStatus(CommandSender sender, String[] args) { if (!(sender instanceof Player) && args.length == 0) { sender.sendMessage(ChatColor.RED + "Must specify a player."); return; } final Player player = (args.length == 0) ? (Player) sender : plugin .getServer().getPlayer(args[0]); String temp = ""; if (player == null) { temp = args[0]; } else { temp = player.getName(); } String name = getPlayerInDatabase(temp); if (name == null) { name = temp; } if (!playerIsJailed(name) && !playerIsPendingJail(name)) { if (args.length == 0) sender.sendMessage(ChatColor.RED + "You are not jailed."); else sender.sendMessage(ChatColor.AQUA + name + ChatColor.RED + " is not jailed."); return; } final StringBuilder sb = new StringBuilder(); final String date = getJailDate(name); final String jailer = getJailer(name); final String reason = getJailReason(name); final boolean muted = playerIsMuted(name); if (args.length == 0) { sb.append(ChatColor.RED + "Jailed on " + ChatColor.GREEN + date + ChatColor.RED + " by " + ChatColor.GOLD + jailer); } else { sb.append(ChatColor.AQUA + name + ChatColor.RED + " was jailed on " + ChatColor.GREEN + date + ChatColor.RED + " by " + ChatColor.GOLD + jailer); } if (!reason.equals("UNKOWN")) { sb.append(ChatColor.RED + " for " + ChatColor.GRAY + plugin.colorizeText(reason)); } if (muted) { sb.append(ChatColor.GRAY + " - " + ChatColor.DARK_RED + "MUTED"); } sender.sendMessage(sb.toString()); if (playerIsTempJailed(name)) { int minutes = (int) ((getPlayerTime(name) / KarmicJail.minutesToTicks)); if (player == null) { sender.sendMessage(ChatColor.AQUA + "Remaining jail time: " + ChatColor.GOLD + plugin.prettifyMinutes(minutes)); } else { // Player is online, check the thread for their remaining time if (KarmicJail.getJailThreads().containsKey(name)) { minutes = (int) (KarmicJail.getJailThreads().get(name) .remainingTime() / KarmicJail.minutesToTicks); sender.sendMessage(ChatColor.AQUA + "Remaining jail time: " + plugin.prettifyMinutes(minutes)); } } } } /** * Gets name of the jailer * * @param name * of person in jail * @return name of jailer */ private static String getJailer(String name) { String jailer = database.getStringField(Field.JAILER, name); if (jailer.equals("")) { jailer = "UNKOWN"; } return jailer; } /** * Grabs date of when player was originally jailed * * @param name * of person jailed * @return String of the date when player was jailed */ private static String getJailDate(String name) { String date = database.getStringField(Field.DATE, name); if (date.equals("")) { date = "UNKOWN"; } return date; } /** * Sets the jail location * * @param sender * of command * @param arguments * of command */ public static void setJail(CommandSender sender, String[] args) { if (!(sender instanceof Player) && args.length != 4) { sender.sendMessage(ChatColor.RED + "Only players can use that."); return; } if (args.length == 0) { Player player = (Player) sender; config.jailLoc = player.getLocation(); } else { if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) { sender.sendMessage(ChatColor.RED + "Invalid coordinate."); return; } config.jailLoc = new Location(plugin.getServer().getWorld(args[3]), Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2])); } config.set("jail.x", (int) config.jailLoc.getX()); config.set("jail.y", (int) config.jailLoc.getY()); config.set("jail.z", (int) config.jailLoc.getZ()); config.set("jail.world", config.jailLoc.getWorld().getName()); plugin.saveConfig(); sender.sendMessage(ChatColor.AQUA + "Jail point saved."); } /** * Sets the unjail location * * @param sender * of command * @param arguments * of command */ public static void setUnjail(CommandSender sender, String[] args) { if (!(sender instanceof Player) && args.length != 4) { sender.sendMessage(ChatColor.RED + "Only players can use that."); return; } if (args.length == 0) { Player player = (Player) sender; config.unjailLoc = player.getLocation(); } else { if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) { sender.sendMessage(ChatColor.RED + "Invalid coordinate."); return; } config.unjailLoc = new Location(plugin.getServer() .getWorld(args[3]), Integer.parseInt(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2])); } config.set("unjail.x", (int) config.unjailLoc.getX()); config.set("unjail.y", (int) config.unjailLoc.getY()); config.set("unjail.z", (int) config.unjailLoc.getZ()); config.set("unjail.world", config.unjailLoc.getWorld().getName()); plugin.saveConfig(); sender.sendMessage(ChatColor.AQUA + "Unjail point saved."); } /** * * @return location of jail */ public static Location getJailLocation() { return config.jailLoc; } /** * * @return location of unjail */ public static Location getUnjailLocation() { return config.unjailLoc; } /** * Teleports a player to unjail locaiton * * @param name * of player to be teleported */ public static void teleportOut(String name) { final Player player = plugin.getServer().getPlayer(name); if (player != null) { player.teleport(config.unjailLoc); } } public static void setPlayerLastLocation(String playername, Location location) { String name = getPlayerInDatabase(playername); if (name == null) { name = playername; } final String entry = location.getWorld().getName() + " " + location.getX() + " " + location.getY() + " " + location.getZ() + " " + location.getYaw() + " " + location.getPitch(); database.setField(Field.LAST_POSITION, name, entry, 0, 0); } public static Location getPlayerLastLocation(String playername) { Location location = null; String name = getPlayerInDatabase(playername); if (name == null) { name = playername; } final String entry = database.getStringField(Field.LAST_POSITION, name); if (!entry.equals("") && entry.contains(" ")) { try { final String[] split = entry.split(" "); final World world = plugin.getServer().getWorld(split[0]); if (world != null) { location = new Location(world, Double.parseDouble(split[1]), Double.parseDouble(split[2]), Double.parseDouble(split[3]), Float.parseFloat(split[4]), Float.parseFloat(split[5])); } } catch (ArrayIndexOutOfBoundsException a) { plugin.getLogger().warning("Bad last location for: " + name); } catch (NumberFormatException n) { plugin.getLogger().warning("Bad last location for: " + name); } } return location; } public static void setPlayerInventory(String playername, Inventory inventory, boolean clear) { Map<Integer, ItemStack> items = new HashMap<Integer, ItemStack>(); if (inventory instanceof PlayerInventory) { PlayerInventory inv = (PlayerInventory) inventory; // Get normal inventory for (int i = 0; i < inventory.getSize(); i++) { try { final ItemStack item = inventory.getItem(i); if (item != null) { if (!item.getType().equals(Material.AIR)) { /* * plugin.getLogger().info( item.toString() + " at " * + i); */ items.put(new Integer(i), item); } } } catch (ArrayIndexOutOfBoundsException a) { // Ignore } catch (NullPointerException n) { // Ignore } } // TODO implement /* * ItemStack[] armor = inv.getArmorContents(); for (int i = 0; i < * armor.length; i++) { try { final ItemStack item = armor[i]; if * (item != null) { if (!item.getType().equals(Material.AIR)) { * plugin.getLogger().info( item.toString() + " at " + i); * items.put(new Integer(i + inv.getSize()), item); } } } catch * (ArrayIndexOutOfBoundsException a) { // Ignore } catch * (NullPointerException n) { // Ignore } } */ if (database.setPlayerItems(playername, items) && clear) { // clear inventory try { inv.clear(); final ItemStack[] cleared = new ItemStack[] { null, null, null, null }; inv.setArmorContents(cleared); } catch (ArrayIndexOutOfBoundsException e) { // ignore again } } } } }
Check config node on whether to return inventory or not.
KarmicJail/src/com/mitsugaru/karmicjail/JailLogic.java
Check config node on whether to return inventory or not.
<ide><path>armicJail/src/com/mitsugaru/karmicjail/JailLogic.java <ide> Player player = plugin.getServer().getPlayer(name); <ide> if (player != null) <ide> { <del> //Return items if any <del> Map<Integer, ItemStack> items = database.getPlayerItems(name); <del> for (Map.Entry<Integer, ItemStack> item : items.entrySet()) <del> { <del> try <del> { <del> player.getInventory().setItem(item.getKey().intValue(), <del> item.getValue()); <del> } <del> catch (ArrayIndexOutOfBoundsException e) <del> { <del> // Ignore <add> // Return items if any <add> if (config.returnInventory) <add> { <add> Map<Integer, ItemStack> items = database.getPlayerItems(name); <add> for (Map.Entry<Integer, ItemStack> item : items.entrySet()) <add> { <add> try <add> { <add> player.getInventory().setItem(item.getKey().intValue(), <add> item.getValue()); <add> } <add> catch (ArrayIndexOutOfBoundsException e) <add> { <add> // Ignore <add> } <ide> } <ide> } <ide> // Clear other columns
Java
mit
1b48e03b2c4f2cec278c4c906f450905a301407c
0
urbanairship/pushy,relayrides/pushy,relayrides/pushy,relayrides/pushy,urbanairship/pushy,urbanairship/pushy
/* Copyright (c) 2013-2016 RelayRides * * 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 com.relayrides.pushy.apns; import java.io.File; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.UnrecoverableEntryException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http2.Http2SecurityUtil; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior; import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.SupportedCipherSuiteFilter; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.FailedFuture; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.SucceededFuture; /** * <p>An APNs client sends push notifications to the APNs gateway. An APNs client connects to the APNs server and, as * part of a TLS handshake, presents a certificate that identifies the client and the "topics" to which it can send * push notifications. Please see Apple's * <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/">Local * and Remote Notification Programming Guide</a> for detailed discussion of * <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW9">topics</a> * and <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ProvisioningDevelopment.html#//apple_ref/doc/uid/TP40008194-CH104-SW1">certificate * provisioning</a>.</p> * * <p>To construct a client, callers will need to provide the certificate provisioned by Apple and its accompanying * private key. The certificate and key will be used to authenticate the client and identify the topics to which it can * send notifications. Callers may optionally specify an {@link NioEventLoopGroup} when constructing a new client. If no * event loop group is specified, clients will create and manage their own single-thread event loop group. If many * clients are operating in parallel, specifying a shared event loop group serves as a mechanism to keep the total * number of threads in check.</p> * * <p>Once a client has been constructed, it must connect to an APNs server before it can begin sending push * notifications. Apple provides a production and development gateway; see {@link ApnsClient#PRODUCTION_APNS_HOST} and * {@link ApnsClient#DEVELOPMENT_APNS_HOST}. See the * <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html#//apple_ref/doc/uid/TP40008194-CH101-SW1">APNs * Provider API</a> documentation for additional details.</p> * * <p>Once a connection has been established, an APNs client will attempt to restore that connection automatically if * the connection closes unexpectedly. APNs clients employ an exponential back-off strategy to manage the rate of * reconnection attempts. Clients will stop trying to reconnect automatically if disconnected via the * {@link ApnsClient#disconnect()} method.</p> * * <p>Notifications sent by a client to an APNs server are sent asynchronously. A * {@link io.netty.util.concurrent.Future io.netty.util.concurrent.Future} is returned immediately when a notification * is sent, but will not complete until the attempt to send the notification has failed, the notification has been * accepted by the APNs server, or the notification has been rejected by the APNs server. Please note that the * {@code Future} returned is a {@code io.netty.util.concurrent.Future}, which is an extension of the * {@link java.util.concurrent.Future java.util.concurrent.Future} interface that allows callers to attach listeners * that will be notified when the {@code Future} completes.</p> * * <p>APNs clients are intended to be long-lived, persistent resources. Callers should shut them down when they are no * longer needed (i.e. when shutting down the entire application). If an event loop group was specified at construction * time, callers should shut down that event loop group when all clients using that group have been disconnected.</p> * * @author <a href="https://github.com/jchambers">Jon Chambers</a> * * @param <T> the type of notification handled by the client */ public class ApnsClient<T extends ApnsPushNotification> { private final Bootstrap bootstrap; private final boolean shouldShutDownEventLoopGroup; private Long gracefulShutdownTimeoutMillis; private volatile ChannelPromise connectionReadyPromise; private volatile ChannelPromise reconnectionPromise; private long reconnectDelay = INITIAL_RECONNECT_DELAY; private final Map<T, Promise<PushNotificationResponse<T>>> responsePromises = new IdentityHashMap<T, Promise<PushNotificationResponse<T>>>(); /** * The hostname for the production APNs gateway. */ public static final String PRODUCTION_APNS_HOST = "api.push.apple.com"; /** * The hostname for the development APNs gateway. */ public static final String DEVELOPMENT_APNS_HOST = "api.development.push.apple.com"; /** * The default (HTTPS) port for communication with the APNs gateway. */ public static final int DEFAULT_APNS_PORT = 443; /** * <p>An alternative port for communication with the APNs gateway. According to Apple's documentation:</p> * * <blockquote>You can alternatively use port 2197 when communicating with APNs. You might do this, for example, to * allow APNs traffic through your firewall but to block other HTTPS traffic.</blockquote> * * @see <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html#//apple_ref/doc/uid/TP40008194-CH101-SW12">APNs * Provider API, Connections</a> */ public static final int ALTERNATE_APNS_PORT = 2197; private static final ClientNotConnectedException NOT_CONNECTED_EXCEPTION = new ClientNotConnectedException(); private static final long INITIAL_RECONNECT_DELAY = 1; // second private static final long MAX_RECONNECT_DELAY = 60; // seconds private static final Logger log = LoggerFactory.getLogger(ApnsClient.class); /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the certificate and key from the * given PKCS#12 file. The PKCS#12 file <em>must</em> contain a single certificate/private key pair.</p> * * <p>Clients created using this method will use a default, internally-managed event loop group. Once the client * has been disconnected via the {@link ApnsClient#disconnect()} method, its event loop will be shut down and the * client cannot be reconnected.</p> * * @param p12File a PKCS#12-formatted file containing a the certificate and private key to be used to identify the * client to the APNs server * @param password the password to be used to decrypt the contents of the given PKCS#12 file * * @throws SSLException if the given PKCS#12 file could not be loaded or if any other SSL-related problem arises * when constructing the context */ public ApnsClient(final File p12File, final String password) throws SSLException { this(p12File, password, null); } /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the certificate and key from the * given PKCS#12 file. The PKCS#12 file <em>must</em> contain a single certificate/private key pair.</p> * * <p>Clients created using this method will use the provided event loop group, which may be useful in cases where * multiple clients are running in parallel. If a client is created using this method, it is the responsibility of * the caller to shut down the event loop group. Clients created with an externally-provided event loop group may be * reconnected after being shut down via the {@link ApnsClient#disconnect()} method.</p> * * @param p12File a PKCS#12-formatted file containing a the certificate and private key to be used to identify the * client to the APNs server * @param password the password to be used to decrypt the contents of the given PKCS#12 file * @param eventLoopGroup the event loop group to be used to handle I/O events for this client * * @throws SSLException if the given PKCS#12 file could not be loaded or if any other SSL-related problem arises * when constructing the context */ public ApnsClient(final File p12File, final String password, final NioEventLoopGroup eventLoopGroup) throws SSLException { this(ApnsClient.getSslContextWithP12File(p12File, password), eventLoopGroup); } /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the given certificate and * key.</p> * * <p>Clients created using this method will use a default, internally-managed event loop group. Once the client * has been disconnected via the {@link ApnsClient#disconnect()} method, its event loop will be shut down and the * client cannot be reconnected.</p> * * @param certificate the certificate to be used to identify the client to the APNs server * @param privateKey the private key for the client certificate * @param privateKeyPassword the password to be used to decrypt the private key; may be {@code null} if the private * key does not require a password * * @throws SSLException if the given key or certificate could not be loaded or if any other SSL-related problem * arises when constructing the context */ public ApnsClient(final X509Certificate certificate, final PrivateKey privateKey, final String privateKeyPassword) throws SSLException { this(certificate, privateKey, privateKeyPassword, null); } /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the given certificate and * key.</p> * * <p>Clients created using this method will use the provided event loop group, which may be useful in cases where * multiple clients are running in parallel. If a client is created using this method, it is the responsibility of * the caller to shut down the event loop group. Clients created with an externally-provided event loop group may be * reconnected after being shut down via the {@link ApnsClient#disconnect()} method.</p> * * @param certificate the certificate to be used to identify the client to the APNs server * @param privateKey the private key for the client certificate * @param privateKeyPassword the password to be used to decrypt the private key; may be {@code null} if the private * key does not require a password * @param eventLoopGroup the event loop group to be used to handle I/O events for this client * * @throws SSLException if the given key or certificate could not be loaded or if any other SSL-related problem * arises when constructing the context */ public ApnsClient(final X509Certificate certificate, final PrivateKey privateKey, final String privateKeyPassword, final NioEventLoopGroup eventLoopGroup) throws SSLException { this(ApnsClient.getSslContextWithCertificateAndPrivateKey(certificate, privateKey, privateKeyPassword), eventLoopGroup); } private static SslContext getSslContextWithP12File(final File p12File, final String password) throws SSLException { final X509Certificate x509Certificate; final PrivateKey privateKey; try { final KeyStore.PasswordProtection keyStorePassword = new KeyStore.PasswordProtection(password != null ? password.toCharArray() : null); final KeyStore keyStore = KeyStore.Builder.newInstance("PKCS12", null, p12File, keyStorePassword).getKeyStore(); if (keyStore.size() != 1) { throw new KeyStoreException("Key store must contain exactly one entry, and that entry must be a private key entry."); } final String alias = keyStore.aliases().nextElement(); final KeyStore.Entry entry = keyStore.getEntry(alias, keyStorePassword); if (!(entry instanceof KeyStore.PrivateKeyEntry)) { throw new KeyStoreException("Key store must contain exactly one entry, and that entry must be a private key entry."); } final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry; final Certificate certificate = privateKeyEntry.getCertificate(); if (!(certificate instanceof X509Certificate)) { throw new KeyStoreException("Found a certificate in the provided PKCS#12 file, but it was not an X.509 certificate."); } x509Certificate = (X509Certificate) certificate; privateKey = privateKeyEntry.getPrivateKey(); } catch (final KeyStoreException e) { throw new SSLException(e); } catch (final NoSuchAlgorithmException e) { throw new SSLException(e); } catch (final UnrecoverableEntryException e) { throw new SSLException(e); } return ApnsClient.getSslContextWithCertificateAndPrivateKey(x509Certificate, privateKey, password); } private static SslContext getSslContextWithCertificateAndPrivateKey(final X509Certificate certificate, final PrivateKey privateKey, final String privateKeyPassword) throws SSLException { return ApnsClient.getBaseSslContextBuilder() .keyManager(privateKey, privateKeyPassword, certificate) .build(); } private static SslContextBuilder getBaseSslContextBuilder() { return SslContextBuilder.forClient() .sslProvider(OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig( new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)); } protected ApnsClient(final SslContext sslContext, final NioEventLoopGroup eventLoopGroup) { this.bootstrap = new Bootstrap(); if (eventLoopGroup != null) { this.bootstrap.group(eventLoopGroup); this.shouldShutDownEventLoopGroup = false; } else { this.bootstrap.group(new NioEventLoopGroup(1)); this.shouldShutDownEventLoopGroup = true; } this.bootstrap.channel(NioSocketChannel.class); this.bootstrap.option(ChannelOption.TCP_NODELAY, true); this.bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(sslContext.newHandler(channel.alloc())); pipeline.addLast(new ApplicationProtocolNegotiationHandler("") { @Override protected void configurePipeline(final ChannelHandlerContext context, final String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { final ApnsClientHandler<T> apnsClientHandler = new ApnsClientHandler.Builder<T>() .server(false) .apnsClient(ApnsClient.this) .encoderEnforceMaxConcurrentStreams(true) .build(); synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.gracefulShutdownTimeoutMillis != null) { apnsClientHandler.gracefulShutdownTimeoutMillis(ApnsClient.this.gracefulShutdownTimeoutMillis); } } context.pipeline().addLast(apnsClientHandler); // Add this to the end of the queue so any events enqueued by the client handler happen // before we declare victory. context.channel().eventLoop().submit(new Runnable() { @Override public void run() { final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise; if (connectionReadyPromise != null) { connectionReadyPromise.trySuccess(); } } }); } else { log.error("Unexpected protocol: {}", protocol); context.close(); } } @Override protected void handshakeFailure(final ChannelHandlerContext context, final Throwable cause) throws Exception { super.handshakeFailure(context, cause); final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise; if (connectionReadyPromise != null) { connectionReadyPromise.tryFailure(cause); } } }); } }); } /** * Sets the maximum amount of time, in milliseconds, that a client will wait to establish a connection with the * APNs server before the connection attempt is considered a failure. * * @param timeoutMillis the maximum amount of time in milliseconds to wait for a connection attempt to complete */ public void setConnectionTimeout(final int timeoutMillis) { synchronized (this.bootstrap) { this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis); } } /** * <p>Connects to the given APNs gateway on the default (HTTPS) port ({@value DEFAULT_APNS_PORT}).</p> * * <p>Once an initial connection has been established and until the client has been explicitly disconnected via the * {@link ApnsClient#disconnect()} method, the client will attempt to reconnect automatically if the connection * closes unexpectedly. If the connection closes unexpectedly, callers may monitor the status of the reconnection * attempt with the {@code Future} returned by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param host the APNs gateway to which to connect * * @return a {@code Future} that will succeed when the client has connected to the gateway and is ready to send * push notifications * * @see ApnsClient#PRODUCTION_APNS_HOST * @see ApnsClient#DEVELOPMENT_APNS_HOST */ public Future<Void> connect(final String host) { return this.connect(host, DEFAULT_APNS_PORT); } /** * <p>Connects to the given APNs gateway on the given port.</p> * * <p>Once an initial connection has been established and until the client has been explicitly disconnected via the * {@link ApnsClient#disconnect()} method, the client will attempt to reconnect automatically if the connection * closes unexpectedly. If the connection closes unexpectedly, callers may monitor the status of the reconnection * attempt with the {@code Future} returned by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param host the APNs gateway to which to connect * @param port the port on which to connect to the APNs gateway * * @return a {@code Future} that will succeed when the client has connected to the gateway and is ready to send * push notifications * * @see ApnsClient#PRODUCTION_APNS_HOST * @see ApnsClient#DEVELOPMENT_APNS_HOST * @see ApnsClient#DEFAULT_APNS_PORT * @see ApnsClient#ALTERNATE_APNS_PORT */ public Future<Void> connect(final String host, final int port) { final Future<Void> connectionReadyFuture; if (this.bootstrap.group().isShuttingDown() || this.bootstrap.group().isShutdown()) { connectionReadyFuture = new FailedFuture<Void>(GlobalEventExecutor.INSTANCE, new IllegalStateException("Client's event loop group has been shut down and cannot be restarted.")); } else { synchronized (this.bootstrap) { // We only want to begin a connection attempt if one is not already in progress or complete; if we already // have a connection future, just return the existing promise. if (this.connectionReadyPromise == null) { final ChannelFuture connectFuture = this.bootstrap.connect(host, port); this.connectionReadyPromise = connectFuture.channel().newPromise(); connectFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.debug("Failed to connect.", future.cause()); ApnsClient.this.connectionReadyPromise.tryFailure(future.cause()); } } }); connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture> () { @Override public void operationComplete(final ChannelFuture future) throws Exception { // We always want to try to fail the "connection ready" promise if the connection closes; if // it has already succeeded, this will have no effect. ApnsClient.this.connectionReadyPromise.tryFailure( new IllegalStateException("Channel closed before HTTP/2 preface completed.")); synchronized (ApnsClient.this.bootstrap) { ApnsClient.this.connectionReadyPromise = null; if (ApnsClient.this.reconnectionPromise != null) { log.debug("Disconnected. Next automatic reconnection attempt in {} seconds.", ApnsClient.this.reconnectDelay); future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { log.debug("Attempting to reconnect."); ApnsClient.this.connect(host, port); } }, ApnsClient.this.reconnectDelay, TimeUnit.SECONDS); ApnsClient.this.reconnectDelay = Math.min(ApnsClient.this.reconnectDelay, MAX_RECONNECT_DELAY); } } } }); this.connectionReadyPromise.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.reconnectionPromise != null) { log.info("Connection to {} restored.", future.channel().remoteAddress()); ApnsClient.this.reconnectionPromise.trySuccess(); } else { log.info("Connected to {}.", future.channel().remoteAddress()); } ApnsClient.this.reconnectDelay = INITIAL_RECONNECT_DELAY; ApnsClient.this.reconnectionPromise = future.channel().newPromise(); } } else { log.info("Failed to connect.", future.cause()); } }}); } connectionReadyFuture = this.connectionReadyPromise; } } return connectionReadyFuture; } /** * Indicates whether this client is connected to the APNs gateway and ready to send push notifications. * * @return {@code true} if this client is connected and ready to send notifications or {@code false} otherwise */ public boolean isConnected() { final ChannelPromise connectionReadyPromise = this.connectionReadyPromise; return (connectionReadyPromise != null && connectionReadyPromise.isSuccess()); } /** * <p>Returns a {@code Future} that will succeed when the client has re-established a connection to the APNs gateway. * Callers may use this method to determine when it is safe to resume sending notifications after a send attempt * fails with a {@link ClientNotConnectedException}.</p> * * <p>If the client is already connected, the {@code Future} returned by this method will succeed immediately. If * the client was not previously connected (either because it has never been connected or because it was explicitly * disconnected via the {@link ApnsClient#disconnect()} method), the {@code Future} returned by this method will * fail immediately with an {@link IllegalStateException}.</p> * * @return a {@code Future} that will succeed when the client has established a connection to the APNs gateway */ public Future<Void> getReconnectionFuture() { final Future<Void> reconnectionFuture; synchronized (this.bootstrap) { if (this.isConnected()) { reconnectionFuture = this.connectionReadyPromise.channel().newSucceededFuture(); } else if (this.reconnectionPromise != null) { // If we're not connected, but have a reconnection promise, we're in the middle of a reconnection // attempt. reconnectionFuture = this.reconnectionPromise; } else { // We're not connected and have no reconnection future, which means we've either never connected or have // explicitly disconnected. reconnectionFuture = new FailedFuture<Void>(GlobalEventExecutor.INSTANCE, new IllegalStateException("Client was not previously connected.")); } } return reconnectionFuture; } /** * <p>Sends a push notification to the APNs gateway.</p> * * <p>This method returns a {@code Future} that indicates whether the notification was accepted or rejected by the * gateway. If the notification was accepted, it may be delivered to its destination device at some time in the * future, but final delivery is not guaranteed. Rejections should be considered permanent failures, and callers * should <em>not</em> attempt to re-send the notification.</p> * * <p>The returned {@code Future} may fail with an exception if the notification could not be sent. Failures to * <em>send</em> a notification to the gateway—i.e. those that fail with exceptions—should generally be considered * non-permanent, and callers should attempt to re-send the notification when the underlying problem has been * resolved.</p> * * <p>In particular, attempts to send a notification when the client is not connected will fail with a * {@link ClientNotConnectedException}. If the client was previously connected and has not been explicitly * disconnected (via the {@link ApnsClient#disconnect()} method), the client will attempt to reconnect * automatically. Callers may wait for a reconnection attempt to complete by waiting for the {@code Future} returned * by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param notification the notification to send to the APNs gateway * * @return a {@code Future} that will complete when the notification has been either accepted or rejected by the * APNs gateway */ public Future<PushNotificationResponse<T>> sendNotification(final T notification) { final Future<PushNotificationResponse<T>> responseFuture; // Instead of synchronizing here, we keep a final reference to the connection ready promise. We can get away // with this because we're not changing the state of the connection or its promises. Keeping a reference ensures // we won't suddenly "lose" the channel and get a NullPointerException, but risks sending a notification after // things have shut down. In that case, though, the returned futures should fail quickly, and the benefit of // not synchronizing for every write seems worth it. final ChannelPromise connectionReadyPromise = this.connectionReadyPromise; if (connectionReadyPromise != null && connectionReadyPromise.isSuccess() && connectionReadyPromise.channel().isActive()) { final DefaultPromise<PushNotificationResponse<T>> responsePromise = new DefaultPromise<PushNotificationResponse<T>>(connectionReadyPromise.channel().eventLoop()); connectionReadyPromise.channel().eventLoop().submit(new Runnable() { @Override public void run() { // We want to do this inside the channel's event loop so we can be sure that only one thread is // modifying responsePromises. ApnsClient.this.responsePromises.put(notification, responsePromise); } }); connectionReadyPromise.channel().writeAndFlush(notification).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.debug("Failed to write push notification: {}", notification, future.cause()); // This will always be called from inside the channel's event loop, so we don't have to worry // about synchronization. ApnsClient.this.responsePromises.remove(notification); responsePromise.setFailure(future.cause()); } } }); responseFuture = responsePromise; } else { log.debug("Failed to send push notification because client is not connected: {}", notification); responseFuture = new FailedFuture<PushNotificationResponse<T>>( GlobalEventExecutor.INSTANCE, NOT_CONNECTED_EXCEPTION); } return responseFuture; } protected void handlePushNotificationResponse(final PushNotificationResponse<T> response) { log.debug("Received response from APNs gateway: {}", response); // This will always be called from inside the channel's event loop, so we don't have to worry about // synchronization. this.responsePromises.remove(response.getPushNotification()).setSuccess(response); } /** * Sets the amount of time (in milliseconds) clients should wait for in-progress requests to complete before closing * a connection during a graceful shutdown. * * @param timeoutMillis the number of milliseconds to wait for in-progress requests to complete before closing a * connection * * @see ApnsClient#disconnect() */ public void setGracefulShutdownTimeout(final long timeoutMillis) { synchronized (this.bootstrap) { this.gracefulShutdownTimeoutMillis = timeoutMillis; if (this.connectionReadyPromise != null) { @SuppressWarnings("rawtypes") final ApnsClientHandler handler = this.connectionReadyPromise.channel().pipeline().get(ApnsClientHandler.class); if (handler != null) { handler.gracefulShutdownTimeoutMillis(timeoutMillis); } } } } /** * <p>Gracefully disconnects from the APNs gateway. The disconnection process will wait until notifications in * flight have been either accepted or rejected by the gateway. The returned {@code Future} will be marked as * complete when the connection has closed completely. If the connection is already closed when this method is * called, the returned {@code Future} will be marked as complete immediately.</p> * * <p>If a non-null {@code EventLoopGroup} was provided at construction time, clients may be reconnected and reused * after they have been disconnected. If no event loop group was provided at construction time, clients may not be * restarted after they have been disconnected via this method.</p> * * @return a {@code Future} that will be marked as complete when the connection has been closed */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Future<Void> disconnect() { log.info("Disconnecting."); final Future<Void> disconnectFuture; synchronized (this.bootstrap) { this.reconnectionPromise = null; final Future<Void> channelCloseFuture; if (this.connectionReadyPromise != null) { channelCloseFuture = this.connectionReadyPromise.channel().close(); } else { channelCloseFuture = new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null); } if (this.shouldShutDownEventLoopGroup) { // Wait for the channel to close before we try to shut down the event loop group channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(final Future<Void> future) throws Exception { ApnsClient.this.bootstrap.group().shutdownGracefully(); } }); // Since the termination future for the event loop group is a Future<?> instead of a Future<Void>, // we'll need to create our own promise and then notify it when the termination future completes. disconnectFuture = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE); this.bootstrap.group().terminationFuture().addListener(new GenericFutureListener() { @Override public void operationComplete(final Future future) throws Exception { assert disconnectFuture instanceof DefaultPromise; ((DefaultPromise<Void>) disconnectFuture).trySuccess(null); } }); } else { // We're done once we've closed the channel, so we can return the closure future directly. disconnectFuture = channelCloseFuture; } } return disconnectFuture; } }
src/main/java/com/relayrides/pushy/apns/ApnsClient.java
/* Copyright (c) 2013-2016 RelayRides * * 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 com.relayrides.pushy.apns; import java.io.File; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.UnrecoverableEntryException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http2.Http2SecurityUtil; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior; import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior; import io.netty.handler.ssl.ApplicationProtocolNames; import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.SupportedCipherSuiteFilter; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.FailedFuture; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.SucceededFuture; /** * <p>An APNs client sends push notifications to the APNs gateway. An APNs client connects to the APNs server and, as * part of a TLS handshake, presents a certificate that identifies the client and the "topics" to which it can send * push notifications. Please see Apple's * <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/">Local * and Remote Notification Programming Guide</a> for detailed discussion of * <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW9">topics</a> * and <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ProvisioningDevelopment.html#//apple_ref/doc/uid/TP40008194-CH104-SW1">certificate * provisioning</a>.</p> * * <p>To construct a client, callers will need to provide the certificate provisioned by Apple and its accompanying * private key. The certificate and key will be used to authenticate the client and identify the topics to which it can * send notifications. Callers may optionally specify an {@link NioEventLoopGroup} when constructing a new client. If no * event loop group is specified, clients will create and manage their own single-thread event loop group. If many * clients are operating in parallel, specifying a shared event loop group serves as a mechanism to keep the total * number of threads in check.</p> * * <p>Once a client has been constructed, it must connect to an APNs server before it can begin sending push * notifications. Apple provides a production and development gateway; see {@link ApnsClient#PRODUCTION_APNS_HOST} and * {@link ApnsClient#DEVELOPMENT_APNS_HOST}. See the * <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html#//apple_ref/doc/uid/TP40008194-CH101-SW1">APNs * Provider API</a> documentation for additional details.</p> * * <p>Once a connection has been established, an APNs client will attempt to restore that connection automatically if * the connection closes unexpectedly. APNs clients employ an exponential back-off strategy to manage the rate of * reconnection attempts. Clients will stop trying to reconnect automatically if disconnected via the * {@link ApnsClient#disconnect()} method.</p> * * <p>Notifications sent by a client to an APNs server are sent asynchronously. A * {@link io.netty.util.concurrent.Future io.netty.util.concurrent.Future} is returned immediately when a notification * is sent, but will not complete until the attempt to send the notification has failed, the notification has been * accepted by the APNs server, or the notification has been rejected by the APNs server. Please note that the * {@code Future} returned is a {@code io.netty.util.concurrent.Future}, which is an extension of the * {@link java.util.concurrent.Future java.util.concurrent.Future} interface that allows callers to attach listeners * that will be notified when the {@code Future} completes.</p> * * <p>APNs clients are intended to be long-lived, persistent resources. Callers should shut them down when they are no * longer needed (i.e. when shutting down the entire application). If an event loop group was specified at construction * time, callers should shut down that event loop group when all clients using that group have been disconnected.</p> * * @author <a href="https://github.com/jchambers">Jon Chambers</a> * * @param <T> the type of notification handled by the client */ public class ApnsClient<T extends ApnsPushNotification> { private final Bootstrap bootstrap; private final boolean shouldShutDownEventLoopGroup; private Long gracefulShutdownTimeoutMillis; private volatile ChannelPromise connectionReadyPromise; private volatile ChannelPromise reconnectionPromise; private long reconnectDelay = INITIAL_RECONNECT_DELAY; private final Map<T, Promise<PushNotificationResponse<T>>> responsePromises = new IdentityHashMap<T, Promise<PushNotificationResponse<T>>>(); /** * The hostname for the production APNs gateway. */ public static final String PRODUCTION_APNS_HOST = "api.push.apple.com"; /** * The hostname for the development APNs gateway. */ public static final String DEVELOPMENT_APNS_HOST = "api.development.push.apple.com"; /** * The default (HTTPS) port for communication with the APNs gateway. */ public static final int DEFAULT_APNS_PORT = 443; /** * <p>An alternative port for communication with the APNs gateway. According to Apple's documentation:</p> * * <blockquote>You can alternatively use port 2197 when communicating with APNs. You might do this, for example, to * allow APNs traffic through your firewall but to block other HTTPS traffic.</blockquote> * * @see <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html#//apple_ref/doc/uid/TP40008194-CH101-SW12">APNs * Provider API, Connections</a> */ public static final int ALTERNATE_APNS_PORT = 2197; private static final ClientNotConnectedException NOT_CONNECTED_EXCEPTION = new ClientNotConnectedException(); private static final long INITIAL_RECONNECT_DELAY = 1; // second private static final long MAX_RECONNECT_DELAY = 60; // seconds private static final Logger log = LoggerFactory.getLogger(ApnsClient.class); /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the certificate and key from the * given PKCS#12 file. The PKCS#12 file <em>must</em> contain a single certificate/private key pair.</p> * * <p>Clients created using this method will use a default, internally-managed event loop group. Once the client * has been disconnected via the {@link ApnsClient#disconnect()} method, its event loop will be shut down and the * client cannot be reconnected.</p> * * @param p12File a PKCS#12-formatted file containing a the certificate and private key to be used to identify the * client to the APNs server * @param password the password to be used to decrypt the contents of the given PKCS#12 file * * @throws SSLException if the given PKCS#12 file could not be loaded or if any other SSL-related problem arises * when constructing the context */ public ApnsClient(final File p12File, final String password) throws SSLException { this(p12File, password, null); } /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the certificate and key from the * given PKCS#12 file. The PKCS#12 file <em>must</em> contain a single certificate/private key pair.</p> * * <p>Clients created using this method will use the provided event loop group, which may be useful in cases where * multiple clients are running in parallel. If a client is created using this method, it is the responsibility of * the caller to shut down the event loop group. Clients created with an externally-provided event loop group may be * reconnected after being shut down via the {@link ApnsClient#disconnect()} method.</p> * * @param p12File a PKCS#12-formatted file containing a the certificate and private key to be used to identify the * client to the APNs server * @param password the password to be used to decrypt the contents of the given PKCS#12 file * @param eventLoopGroup the event loop group to be used to handle I/O events for this client * * @throws SSLException if the given PKCS#12 file could not be loaded or if any other SSL-related problem arises * when constructing the context */ public ApnsClient(final File p12File, final String password, final NioEventLoopGroup eventLoopGroup) throws SSLException { this(ApnsClient.getSslContextWithP12File(p12File, password), eventLoopGroup); } /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the given certificate and * key.</p> * * <p>Clients created using this method will use a default, internally-managed event loop group. Once the client * has been disconnected via the {@link ApnsClient#disconnect()} method, its event loop will be shut down and the * client cannot be reconnected.</p> * * @param certificate the certificate to be used to identify the client to the APNs server * @param privateKey the private key for the client certificate * @param privateKeyPassword the password to be used to decrypt the private key; may be {@code null} if the private * key does not require a password * * @throws SSLException if the given key or certificate could not be loaded or if any other SSL-related problem * arises when constructing the context */ public ApnsClient(final X509Certificate certificate, final PrivateKey privateKey, final String privateKeyPassword) throws SSLException { this(certificate, privateKey, privateKeyPassword, null); } /** * <p>Creates a new APNs client that will identify itself to the APNs gateway with the given certificate and * key.</p> * * <p>Clients created using this method will use the provided event loop group, which may be useful in cases where * multiple clients are running in parallel. If a client is created using this method, it is the responsibility of * the caller to shut down the event loop group. Clients created with an externally-provided event loop group may be * reconnected after being shut down via the {@link ApnsClient#disconnect()} method.</p> * * @param certificate the certificate to be used to identify the client to the APNs server * @param privateKey the private key for the client certificate * @param privateKeyPassword the password to be used to decrypt the private key; may be {@code null} if the private * key does not require a password * @param eventLoopGroup the event loop group to be used to handle I/O events for this client * * @throws SSLException if the given key or certificate could not be loaded or if any other SSL-related problem * arises when constructing the context */ public ApnsClient(final X509Certificate certificate, final PrivateKey privateKey, final String privateKeyPassword, final NioEventLoopGroup eventLoopGroup) throws SSLException { this(ApnsClient.getSslContextWithCertificateAndPrivateKey(certificate, privateKey, privateKeyPassword), eventLoopGroup); } private static SslContext getSslContextWithP12File(final File p12File, final String password) throws SSLException { final X509Certificate x509Certificate; final PrivateKey privateKey; try { final KeyStore.PasswordProtection keyStorePassword = (password != null) ? new KeyStore.PasswordProtection(password.toCharArray()) : null; final KeyStore keyStore = KeyStore.Builder.newInstance("PKCS12", null, p12File, keyStorePassword).getKeyStore(); if (keyStore.size() != 1) { throw new KeyStoreException("Key store must contain exactly one entry, and that entry must be a private key entry."); } final String alias = keyStore.aliases().nextElement(); final KeyStore.Entry entry = keyStore.getEntry(alias, keyStorePassword); if (!(entry instanceof KeyStore.PrivateKeyEntry)) { throw new KeyStoreException("Key store must contain exactly one entry, and that entry must be a private key entry."); } final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry; final Certificate certificate = privateKeyEntry.getCertificate(); if (!(certificate instanceof X509Certificate)) { throw new KeyStoreException("Found a certificate in the provided PKCS#12 file, but it was not an X.509 certificate."); } x509Certificate = (X509Certificate) certificate; privateKey = privateKeyEntry.getPrivateKey(); } catch (final KeyStoreException e) { throw new SSLException(e); } catch (final NoSuchAlgorithmException e) { throw new SSLException(e); } catch (final UnrecoverableEntryException e) { throw new SSLException(e); } return ApnsClient.getSslContextWithCertificateAndPrivateKey(x509Certificate, privateKey, password); } private static SslContext getSslContextWithCertificateAndPrivateKey(final X509Certificate certificate, final PrivateKey privateKey, final String privateKeyPassword) throws SSLException { return ApnsClient.getBaseSslContextBuilder() .keyManager(privateKey, privateKeyPassword, certificate) .build(); } private static SslContextBuilder getBaseSslContextBuilder() { return SslContextBuilder.forClient() .sslProvider(OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig( new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)); } protected ApnsClient(final SslContext sslContext, final NioEventLoopGroup eventLoopGroup) { this.bootstrap = new Bootstrap(); if (eventLoopGroup != null) { this.bootstrap.group(eventLoopGroup); this.shouldShutDownEventLoopGroup = false; } else { this.bootstrap.group(new NioEventLoopGroup(1)); this.shouldShutDownEventLoopGroup = true; } this.bootstrap.channel(NioSocketChannel.class); this.bootstrap.option(ChannelOption.TCP_NODELAY, true); this.bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(sslContext.newHandler(channel.alloc())); pipeline.addLast(new ApplicationProtocolNegotiationHandler("") { @Override protected void configurePipeline(final ChannelHandlerContext context, final String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { final ApnsClientHandler<T> apnsClientHandler = new ApnsClientHandler.Builder<T>() .server(false) .apnsClient(ApnsClient.this) .encoderEnforceMaxConcurrentStreams(true) .build(); synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.gracefulShutdownTimeoutMillis != null) { apnsClientHandler.gracefulShutdownTimeoutMillis(ApnsClient.this.gracefulShutdownTimeoutMillis); } } context.pipeline().addLast(apnsClientHandler); // Add this to the end of the queue so any events enqueued by the client handler happen // before we declare victory. context.channel().eventLoop().submit(new Runnable() { @Override public void run() { final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise; if (connectionReadyPromise != null) { connectionReadyPromise.trySuccess(); } } }); } else { log.error("Unexpected protocol: {}", protocol); context.close(); } } @Override protected void handshakeFailure(final ChannelHandlerContext context, final Throwable cause) throws Exception { super.handshakeFailure(context, cause); final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise; if (connectionReadyPromise != null) { connectionReadyPromise.tryFailure(cause); } } }); } }); } /** * Sets the maximum amount of time, in milliseconds, that a client will wait to establish a connection with the * APNs server before the connection attempt is considered a failure. * * @param timeoutMillis the maximum amount of time in milliseconds to wait for a connection attempt to complete */ public void setConnectionTimeout(final int timeoutMillis) { synchronized (this.bootstrap) { this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis); } } /** * <p>Connects to the given APNs gateway on the default (HTTPS) port ({@value DEFAULT_APNS_PORT}).</p> * * <p>Once an initial connection has been established and until the client has been explicitly disconnected via the * {@link ApnsClient#disconnect()} method, the client will attempt to reconnect automatically if the connection * closes unexpectedly. If the connection closes unexpectedly, callers may monitor the status of the reconnection * attempt with the {@code Future} returned by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param host the APNs gateway to which to connect * * @return a {@code Future} that will succeed when the client has connected to the gateway and is ready to send * push notifications * * @see ApnsClient#PRODUCTION_APNS_HOST * @see ApnsClient#DEVELOPMENT_APNS_HOST */ public Future<Void> connect(final String host) { return this.connect(host, DEFAULT_APNS_PORT); } /** * <p>Connects to the given APNs gateway on the given port.</p> * * <p>Once an initial connection has been established and until the client has been explicitly disconnected via the * {@link ApnsClient#disconnect()} method, the client will attempt to reconnect automatically if the connection * closes unexpectedly. If the connection closes unexpectedly, callers may monitor the status of the reconnection * attempt with the {@code Future} returned by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param host the APNs gateway to which to connect * @param port the port on which to connect to the APNs gateway * * @return a {@code Future} that will succeed when the client has connected to the gateway and is ready to send * push notifications * * @see ApnsClient#PRODUCTION_APNS_HOST * @see ApnsClient#DEVELOPMENT_APNS_HOST * @see ApnsClient#DEFAULT_APNS_PORT * @see ApnsClient#ALTERNATE_APNS_PORT */ public Future<Void> connect(final String host, final int port) { final Future<Void> connectionReadyFuture; if (this.bootstrap.group().isShuttingDown() || this.bootstrap.group().isShutdown()) { connectionReadyFuture = new FailedFuture<Void>(GlobalEventExecutor.INSTANCE, new IllegalStateException("Client's event loop group has been shut down and cannot be restarted.")); } else { synchronized (this.bootstrap) { // We only want to begin a connection attempt if one is not already in progress or complete; if we already // have a connection future, just return the existing promise. if (this.connectionReadyPromise == null) { final ChannelFuture connectFuture = this.bootstrap.connect(host, port); this.connectionReadyPromise = connectFuture.channel().newPromise(); connectFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.debug("Failed to connect.", future.cause()); ApnsClient.this.connectionReadyPromise.tryFailure(future.cause()); } } }); connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture> () { @Override public void operationComplete(final ChannelFuture future) throws Exception { // We always want to try to fail the "connection ready" promise if the connection closes; if // it has already succeeded, this will have no effect. ApnsClient.this.connectionReadyPromise.tryFailure( new IllegalStateException("Channel closed before HTTP/2 preface completed.")); synchronized (ApnsClient.this.bootstrap) { ApnsClient.this.connectionReadyPromise = null; if (ApnsClient.this.reconnectionPromise != null) { log.debug("Disconnected. Next automatic reconnection attempt in {} seconds.", ApnsClient.this.reconnectDelay); future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { log.debug("Attempting to reconnect."); ApnsClient.this.connect(host, port); } }, ApnsClient.this.reconnectDelay, TimeUnit.SECONDS); ApnsClient.this.reconnectDelay = Math.min(ApnsClient.this.reconnectDelay, MAX_RECONNECT_DELAY); } } } }); this.connectionReadyPromise.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.reconnectionPromise != null) { log.info("Connection to {} restored.", future.channel().remoteAddress()); ApnsClient.this.reconnectionPromise.trySuccess(); } else { log.info("Connected to {}.", future.channel().remoteAddress()); } ApnsClient.this.reconnectDelay = INITIAL_RECONNECT_DELAY; ApnsClient.this.reconnectionPromise = future.channel().newPromise(); } } else { log.info("Failed to connect.", future.cause()); } }}); } connectionReadyFuture = this.connectionReadyPromise; } } return connectionReadyFuture; } /** * Indicates whether this client is connected to the APNs gateway and ready to send push notifications. * * @return {@code true} if this client is connected and ready to send notifications or {@code false} otherwise */ public boolean isConnected() { final ChannelPromise connectionReadyPromise = this.connectionReadyPromise; return (connectionReadyPromise != null && connectionReadyPromise.isSuccess()); } /** * <p>Returns a {@code Future} that will succeed when the client has re-established a connection to the APNs gateway. * Callers may use this method to determine when it is safe to resume sending notifications after a send attempt * fails with a {@link ClientNotConnectedException}.</p> * * <p>If the client is already connected, the {@code Future} returned by this method will succeed immediately. If * the client was not previously connected (either because it has never been connected or because it was explicitly * disconnected via the {@link ApnsClient#disconnect()} method), the {@code Future} returned by this method will * fail immediately with an {@link IllegalStateException}.</p> * * @return a {@code Future} that will succeed when the client has established a connection to the APNs gateway */ public Future<Void> getReconnectionFuture() { final Future<Void> reconnectionFuture; synchronized (this.bootstrap) { if (this.isConnected()) { reconnectionFuture = this.connectionReadyPromise.channel().newSucceededFuture(); } else if (this.reconnectionPromise != null) { // If we're not connected, but have a reconnection promise, we're in the middle of a reconnection // attempt. reconnectionFuture = this.reconnectionPromise; } else { // We're not connected and have no reconnection future, which means we've either never connected or have // explicitly disconnected. reconnectionFuture = new FailedFuture<Void>(GlobalEventExecutor.INSTANCE, new IllegalStateException("Client was not previously connected.")); } } return reconnectionFuture; } /** * <p>Sends a push notification to the APNs gateway.</p> * * <p>This method returns a {@code Future} that indicates whether the notification was accepted or rejected by the * gateway. If the notification was accepted, it may be delivered to its destination device at some time in the * future, but final delivery is not guaranteed. Rejections should be considered permanent failures, and callers * should <em>not</em> attempt to re-send the notification.</p> * * <p>The returned {@code Future} may fail with an exception if the notification could not be sent. Failures to * <em>send</em> a notification to the gateway—i.e. those that fail with exceptions—should generally be considered * non-permanent, and callers should attempt to re-send the notification when the underlying problem has been * resolved.</p> * * <p>In particular, attempts to send a notification when the client is not connected will fail with a * {@link ClientNotConnectedException}. If the client was previously connected and has not been explicitly * disconnected (via the {@link ApnsClient#disconnect()} method), the client will attempt to reconnect * automatically. Callers may wait for a reconnection attempt to complete by waiting for the {@code Future} returned * by the {@link ApnsClient#getReconnectionFuture()} method.</p> * * @param notification the notification to send to the APNs gateway * * @return a {@code Future} that will complete when the notification has been either accepted or rejected by the * APNs gateway */ public Future<PushNotificationResponse<T>> sendNotification(final T notification) { final Future<PushNotificationResponse<T>> responseFuture; // Instead of synchronizing here, we keep a final reference to the connection ready promise. We can get away // with this because we're not changing the state of the connection or its promises. Keeping a reference ensures // we won't suddenly "lose" the channel and get a NullPointerException, but risks sending a notification after // things have shut down. In that case, though, the returned futures should fail quickly, and the benefit of // not synchronizing for every write seems worth it. final ChannelPromise connectionReadyPromise = this.connectionReadyPromise; if (connectionReadyPromise != null && connectionReadyPromise.isSuccess() && connectionReadyPromise.channel().isActive()) { final DefaultPromise<PushNotificationResponse<T>> responsePromise = new DefaultPromise<PushNotificationResponse<T>>(connectionReadyPromise.channel().eventLoop()); connectionReadyPromise.channel().eventLoop().submit(new Runnable() { @Override public void run() { // We want to do this inside the channel's event loop so we can be sure that only one thread is // modifying responsePromises. ApnsClient.this.responsePromises.put(notification, responsePromise); } }); connectionReadyPromise.channel().writeAndFlush(notification).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.debug("Failed to write push notification: {}", notification, future.cause()); // This will always be called from inside the channel's event loop, so we don't have to worry // about synchronization. ApnsClient.this.responsePromises.remove(notification); responsePromise.setFailure(future.cause()); } } }); responseFuture = responsePromise; } else { log.debug("Failed to send push notification because client is not connected: {}", notification); responseFuture = new FailedFuture<PushNotificationResponse<T>>( GlobalEventExecutor.INSTANCE, NOT_CONNECTED_EXCEPTION); } return responseFuture; } protected void handlePushNotificationResponse(final PushNotificationResponse<T> response) { log.debug("Received response from APNs gateway: {}", response); // This will always be called from inside the channel's event loop, so we don't have to worry about // synchronization. this.responsePromises.remove(response.getPushNotification()).setSuccess(response); } /** * Sets the amount of time (in milliseconds) clients should wait for in-progress requests to complete before closing * a connection during a graceful shutdown. * * @param timeoutMillis the number of milliseconds to wait for in-progress requests to complete before closing a * connection * * @see ApnsClient#disconnect() */ public void setGracefulShutdownTimeout(final long timeoutMillis) { synchronized (this.bootstrap) { this.gracefulShutdownTimeoutMillis = timeoutMillis; if (this.connectionReadyPromise != null) { @SuppressWarnings("rawtypes") final ApnsClientHandler handler = this.connectionReadyPromise.channel().pipeline().get(ApnsClientHandler.class); if (handler != null) { handler.gracefulShutdownTimeoutMillis(timeoutMillis); } } } } /** * <p>Gracefully disconnects from the APNs gateway. The disconnection process will wait until notifications in * flight have been either accepted or rejected by the gateway. The returned {@code Future} will be marked as * complete when the connection has closed completely. If the connection is already closed when this method is * called, the returned {@code Future} will be marked as complete immediately.</p> * * <p>If a non-null {@code EventLoopGroup} was provided at construction time, clients may be reconnected and reused * after they have been disconnected. If no event loop group was provided at construction time, clients may not be * restarted after they have been disconnected via this method.</p> * * @return a {@code Future} that will be marked as complete when the connection has been closed */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Future<Void> disconnect() { log.info("Disconnecting."); final Future<Void> disconnectFuture; synchronized (this.bootstrap) { this.reconnectionPromise = null; final Future<Void> channelCloseFuture; if (this.connectionReadyPromise != null) { channelCloseFuture = this.connectionReadyPromise.channel().close(); } else { channelCloseFuture = new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null); } if (this.shouldShutDownEventLoopGroup) { // Wait for the channel to close before we try to shut down the event loop group channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(final Future<Void> future) throws Exception { ApnsClient.this.bootstrap.group().shutdownGracefully(); } }); // Since the termination future for the event loop group is a Future<?> instead of a Future<Void>, // we'll need to create our own promise and then notify it when the termination future completes. disconnectFuture = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE); this.bootstrap.group().terminationFuture().addListener(new GenericFutureListener() { @Override public void operationComplete(final Future future) throws Exception { assert disconnectFuture instanceof DefaultPromise; ((DefaultPromise<Void>) disconnectFuture).trySuccess(null); } }); } else { // We're done once we've closed the channel, so we can return the closure future directly. disconnectFuture = channelCloseFuture; } } return disconnectFuture; } }
Fix passing not specified password for .p12 file KeyStore.PasswordProtection constructor accepts null, but the next KeyStore.Builder.newInstance() call doesn't accept protection as null
src/main/java/com/relayrides/pushy/apns/ApnsClient.java
Fix passing not specified password for .p12 file
<ide><path>rc/main/java/com/relayrides/pushy/apns/ApnsClient.java <ide> final PrivateKey privateKey; <ide> <ide> try { <del> final KeyStore.PasswordProtection keyStorePassword = (password != null) ? new KeyStore.PasswordProtection(password.toCharArray()) : null; <add> final KeyStore.PasswordProtection keyStorePassword = new KeyStore.PasswordProtection(password != null ? password.toCharArray() : null); <ide> <ide> final KeyStore keyStore = KeyStore.Builder.newInstance("PKCS12", null, p12File, keyStorePassword).getKeyStore(); <ide>
JavaScript
mit
cde68500748d1a3dc5c41f76a484cddda6638a59
0
Vrturo/Algo-Gem,Vrturo/Algo-Gem,Vrturo/Algo-Gem
// Given a set of distinct integers, nums, return all possible subsets. // Note: // Elements in a subset must be in non-descending order. // The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,3], a solution is: // [ // [3], // [1], // [2], // [1,2,3], // [1,3], // [2,3], // [1,2], // [] // ] var subsets = function(nums) { var solution = [], result = [], used = []; // nums, each element can only be used once var backTracking = function(k, n) { if( k===n ){ return result.push( solution.slice(0) ); } else { for( var i=0; i<nums.length; i++ ){ if( used[i] ) continue; // when true, express the element(used[i]) has been used if( k>0 && solution[k-1] > nums[i]) continue; // elements have to be in ascending order used[i] = true; solution[k] = nums[i]; backTracking(k+1, n); used[i] = false; } } } for( var i=0; i<=nums.length; i++ ){ backTracking(0, i); // eg. subsets([1, 2, 3]); // backTracking(0, 0); return []; // backTracking(0, 1); return [1], [2], [3]; // backTracking(0, 2); return [1, 2], [1, 3], [2, 3]; // backTracking(0, 3); return [1, 2, 3]; } return result; }; console.log(subsets([1,2,3])) // -------------------------------- // var subsets = function(nums) { // var result = []; // function helper(set, i){ // if (nums.length === i){ // result.push(set); // return; // } // helper(set, Number(i+1)); // helper(set + nums[i], Number(i+1)); // } // helper([],0); // return result; // }; // --------------------------------------------------- // Q: Given an array of characters, print all possible combinations. For example given a, b, c, print // a // b // c // ab // ac // abc // bc var combination = function(array){ var str = array.join(""); function helper(string){ if (set.length === 0){ return [""] } else{ var last = str[string.length-1] var sub = helper(str.slice(0, -1)); var joined = sub.map(function(character){ return character + last; }) return sub.concat(joined) } } return helper(str) }
Algorithms/JS/arrays/subSet.js
// Given a set of distinct integers, nums, return all possible subsets. // Note: // Elements in a subset must be in non-descending order. // The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,3], a solution is: // [ // [3], // [1], // [2], // [1,2,3], // [1,3], // [2,3], // [1,2], // [] // ] var subsets = function(nums) { var result = []; function helper(set, i){ if (nums.length === i){ result.push(set); return; } helper(set, Number(i+1)); helper(set + nums[i], Number(i+1)); } helper([],0); return result; }; // Q: Given an array of characters, print all possible combinations. For example given a, b, c, print // a // b // c // ab // ac // abc // bc var combination = function(array){ var str = array.join(""); function helper(string){ if (set.length === 0){ return [""] } else{ var last = str[string.length-1] var sub = helper(str.slice(0, -1)); var joined = sub.map(function(character){ return character + last; }) return sub.concat(joined) } } return helper(str) }
add solution
Algorithms/JS/arrays/subSet.js
add solution
<ide><path>lgorithms/JS/arrays/subSet.js <ide> <ide> <ide> var subsets = function(nums) { <del> var result = []; <del> function helper(set, i){ <del> if (nums.length === i){ <del> result.push(set); <del> return; <del> } <del> helper(set, Number(i+1)); <del> helper(set + nums[i], Number(i+1)); <add> var solution = [], <add> result = [], <add> used = []; // nums, each element can only be used once <add> <add> var backTracking = function(k, n) { <add> if( k===n ){ <add> return result.push( solution.slice(0) ); <add> } else { <add> for( var i=0; i<nums.length; i++ ){ <add> if( used[i] ) continue; // when true, express the element(used[i]) has been used <add> if( k>0 && solution[k-1] > nums[i]) continue; // elements have to be in ascending order <add> used[i] = true; <add> solution[k] = nums[i]; <add> backTracking(k+1, n); <add> used[i] = false; <add> } <ide> } <del> helper([],0); <del> return result; <add> } <add> <add> for( var i=0; i<=nums.length; i++ ){ <add> backTracking(0, i); <add> // eg. subsets([1, 2, 3]); <add> // backTracking(0, 0); return []; <add> // backTracking(0, 1); return [1], [2], [3]; <add> // backTracking(0, 2); return [1, 2], [1, 3], [2, 3]; <add> // backTracking(0, 3); return [1, 2, 3]; <add> } <add> <add> return result; <ide> }; <ide> <add>console.log(subsets([1,2,3])) <add> <add>// -------------------------------- <add>// var subsets = function(nums) { <add>// var result = []; <add>// function helper(set, i){ <add>// if (nums.length === i){ <add>// result.push(set); <add>// return; <add>// } <add>// helper(set, Number(i+1)); <add>// helper(set + nums[i], Number(i+1)); <add>// } <add>// helper([],0); <add>// return result; <add>// }; <add> <add>// --------------------------------------------------- <ide> <ide> // Q: Given an array of characters, print all possible combinations. For example given a, b, c, print <ide> // a
Java
apache-2.0
722dac58cf5a15e79acc428b6b9978d0b0d6e85b
0
yahoo/pulsar,nkurihar/pulsar,ArvinDevel/incubator-pulsar,merlimat/pulsar,merlimat/pulsar,jai1/pulsar,ArvinDevel/incubator-pulsar,jai1/pulsar,merlimat/pulsar,nkurihar/pulsar,massakam/pulsar,massakam/pulsar,jai1/pulsar,jai1/pulsar,jai1/pulsar,ArvinDevel/incubator-pulsar,jai1/pulsar,nkurihar/pulsar,yahoo/pulsar,nkurihar/pulsar,massakam/pulsar,nkurihar/pulsar,merlimat/pulsar,yahoo/pulsar,jai1/pulsar,nkurihar/pulsar,massakam/pulsar,massakam/pulsar,merlimat/pulsar,yahoo/pulsar,ArvinDevel/incubator-pulsar,nkurihar/pulsar,nkurihar/pulsar,massakam/pulsar,ArvinDevel/incubator-pulsar,ArvinDevel/incubator-pulsar,ArvinDevel/incubator-pulsar,yahoo/pulsar,jai1/pulsar,ArvinDevel/incubator-pulsar,jai1/pulsar,nkurihar/pulsar,merlimat/pulsar,yahoo/pulsar
/** * 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.pulsar.broker.service.nonpersistent; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.bookkeeper.mledger.impl.EntryCacheManager.create; import static org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES; import com.carrotsearch.hppc.ObjectObjectHashMap; import com.google.common.base.MoreObjects; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import io.netty.buffer.ByteBuf; import io.netty.util.concurrent.FastThreadLocal; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.bookkeeper.common.util.OrderedExecutor; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.Position; import org.apache.bookkeeper.mledger.util.SafeRun; import org.apache.pulsar.broker.admin.AdminResource; import org.apache.pulsar.broker.service.BrokerService; import org.apache.pulsar.broker.service.BrokerServiceException; import org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.NamingException; import org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException; import org.apache.pulsar.broker.service.BrokerServiceException.ProducerBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException; import org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.TopicFencedException; import org.apache.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException; import org.apache.pulsar.broker.service.Consumer; import org.apache.pulsar.broker.service.Producer; import org.apache.pulsar.broker.service.Replicator; import org.apache.pulsar.broker.service.ServerCnx; import org.apache.pulsar.broker.service.StreamingStats; import org.apache.pulsar.broker.service.Subscription; import org.apache.pulsar.broker.service.Topic; import org.apache.pulsar.broker.stats.ClusterReplicationMetrics; import org.apache.pulsar.broker.stats.NamespaceStats; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition; import org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.BacklogQuota; import org.apache.pulsar.common.policies.data.ConsumerStats; import org.apache.pulsar.common.policies.data.NonPersistentPublisherStats; import org.apache.pulsar.common.policies.data.NonPersistentReplicatorStats; import org.apache.pulsar.common.policies.data.NonPersistentSubscriptionStats; import org.apache.pulsar.common.policies.data.NonPersistentTopicStats; import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats; import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.CursorStats; import org.apache.pulsar.common.policies.data.Policies; import org.apache.pulsar.common.policies.data.PublisherStats; import org.apache.pulsar.common.schema.SchemaData; import org.apache.pulsar.common.schema.SchemaVersion; import org.apache.pulsar.common.util.FutureUtil; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet; import org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats; import org.apache.pulsar.utils.StatsOutputStream; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NonPersistentTopic implements Topic { private final String topic; // Producers currently connected to this topic private final ConcurrentOpenHashSet<Producer> producers; // Subscriptions to this topic private final ConcurrentOpenHashMap<String, NonPersistentSubscription> subscriptions; private final ConcurrentOpenHashMap<String, NonPersistentReplicator> replicators; private final BrokerService brokerService; private volatile boolean isFenced; // Prefix for replication cursors public final String replicatorPrefix; protected static final AtomicLongFieldUpdater<NonPersistentTopic> USAGE_COUNT_UPDATER = AtomicLongFieldUpdater .newUpdater(NonPersistentTopic.class, "usageCount"); private volatile long usageCount = 0; private final OrderedExecutor executor; private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // Timestamp of when this topic was last seen active private volatile long lastActive; // Flag to signal that producer of this topic has published batch-message so, broker should not allow consumer which // doesn't support batch-message private volatile boolean hasBatchMessagePublished = false; // Ever increasing counter of entries added static final AtomicLongFieldUpdater<NonPersistentTopic> ENTRIES_ADDED_COUNTER_UPDATER = AtomicLongFieldUpdater .newUpdater(NonPersistentTopic.class, "entriesAddedCounter"); private volatile long entriesAddedCounter = 0; private static final long POLICY_UPDATE_FAILURE_RETRY_TIME_SECONDS = 60; private static final FastThreadLocal<TopicStats> threadLocalTopicStats = new FastThreadLocal<TopicStats>() { @Override protected TopicStats initialValue() { return new TopicStats(); } }; // Whether messages published must be encrypted or not in this topic private volatile boolean isEncryptionRequired = false; private static class TopicStats { public double averageMsgSize; public double aggMsgRateIn; public double aggMsgThroughputIn; public double aggMsgRateOut; public double aggMsgThroughputOut; public final ObjectObjectHashMap<String, PublisherStats> remotePublishersStats; public TopicStats() { remotePublishersStats = new ObjectObjectHashMap<String, PublisherStats>(); reset(); } public void reset() { averageMsgSize = 0; aggMsgRateIn = 0; aggMsgThroughputIn = 0; aggMsgRateOut = 0; aggMsgThroughputOut = 0; remotePublishersStats.clear(); } } public NonPersistentTopic(String topic, BrokerService brokerService) { this.topic = topic; this.brokerService = brokerService; this.producers = new ConcurrentOpenHashSet<Producer>(16, 1); this.subscriptions = new ConcurrentOpenHashMap<>(16, 1); this.replicators = new ConcurrentOpenHashMap<>(16, 1); this.isFenced = false; this.replicatorPrefix = brokerService.pulsar().getConfiguration().getReplicatorPrefix(); this.executor = brokerService.getTopicOrderedExecutor(); USAGE_COUNT_UPDATER.set(this, 0); this.lastActive = System.nanoTime(); try { Policies policies = brokerService.pulsar().getConfigurationCache().policiesCache() .get(AdminResource.path(POLICIES, TopicName.get(topic).getNamespace())) .orElseThrow(() -> new KeeperException.NoNodeException()); isEncryptionRequired = policies.encryption_required; } catch (Exception e) { log.warn("[{}] Error getting policies {} and isEncryptionRequired will be set to false", topic, e.getMessage()); isEncryptionRequired = false; } } @Override public void publishMessage(ByteBuf data, PublishContext callback) { callback.completed(null, 0L, 0L); ENTRIES_ADDED_COUNTER_UPDATER.incrementAndGet(this); subscriptions.forEach((name, subscription) -> { ByteBuf duplicateBuffer = data.retainedDuplicate(); Entry entry = create(0L, 0L, duplicateBuffer); // entry internally retains data so, duplicateBuffer should be release here duplicateBuffer.release(); if (subscription.getDispatcher() != null) { subscription.getDispatcher().sendMessages(Collections.singletonList(entry)); } else { // it happens when subscription is created but dispatcher is not created as consumer is not added // yet entry.release(); } }); if (!replicators.isEmpty()) { replicators.forEach((name, replicator) -> { ByteBuf duplicateBuffer = data.retainedDuplicate(); Entry entry = create(0L, 0L, duplicateBuffer); // entry internally retains data so, duplicateBuffer should be release here duplicateBuffer.release(); ((NonPersistentReplicator) replicator).sendMessage(entry); }); } } @Override public void addProducer(Producer producer) throws BrokerServiceException { checkArgument(producer.getTopic() == this); lock.readLock().lock(); try { if (isFenced) { log.warn("[{}] Attempting to add producer to a fenced topic", topic); throw new TopicFencedException("Topic is temporarily unavailable"); } if (isProducersExceeded()) { log.warn("[{}] Attempting to add producer to topic which reached max producers limit", topic); throw new ProducerBusyException("Topic reached max producers limit"); } if (log.isDebugEnabled()) { log.debug("[{}] {} Got request to create producer ", topic, producer.getProducerName()); } if (!producers.add(producer)) { throw new NamingException( "Producer with name '" + producer.getProducerName() + "' is already connected to topic"); } USAGE_COUNT_UPDATER.incrementAndGet(this); if (log.isDebugEnabled()) { log.debug("[{}] [{}] Added producer -- count: {}", topic, producer.getProducerName(), USAGE_COUNT_UPDATER.get(this)); } } finally { lock.readLock().unlock(); } } private boolean isProducersExceeded() { Policies policies; try { policies = brokerService.pulsar().getConfigurationCache().policiesCache() .get(AdminResource.path(POLICIES, TopicName.get(topic).getNamespace())) .orElseGet(() -> new Policies()); } catch (Exception e) { policies = new Policies(); } final int maxProducers = policies.max_producers_per_topic > 0 ? policies.max_producers_per_topic : brokerService.pulsar().getConfiguration().getMaxProducersPerTopic(); if (maxProducers > 0 && maxProducers <= producers.size()) { return true; } return false; } @Override public void checkMessageDeduplicationInfo() { // No-op } private boolean hasLocalProducers() { AtomicBoolean foundLocal = new AtomicBoolean(false); producers.forEach(producer -> { if (!producer.isRemote()) { foundLocal.set(true); } }); return foundLocal.get(); } private boolean hasRemoteProducers() { AtomicBoolean foundRemote = new AtomicBoolean(false); producers.forEach(producer -> { if (producer.isRemote()) { foundRemote.set(true); } }); return foundRemote.get(); } @Override public void removeProducer(Producer producer) { checkArgument(producer.getTopic() == this); if (producers.remove(producer)) { // decrement usage only if this was a valid producer close USAGE_COUNT_UPDATER.decrementAndGet(this); if (log.isDebugEnabled()) { log.debug("[{}] [{}] Removed producer -- count: {}", topic, producer.getProducerName(), USAGE_COUNT_UPDATER.get(this)); } lastActive = System.nanoTime(); } } @Override public CompletableFuture<Consumer> subscribe(final ServerCnx cnx, String subscriptionName, long consumerId, SubType subType, int priorityLevel, String consumerName, boolean isDurable, MessageId startMessageId, Map<String, String> metadata, boolean readCompacted, InitialPosition initialPosition) { final CompletableFuture<Consumer> future = new CompletableFuture<>(); if (hasBatchMessagePublished && !cnx.isBatchMessageCompatibleVersion()) { if (log.isDebugEnabled()) { log.debug("[{}] Consumer doesn't support batch-message {}", topic, subscriptionName); } future.completeExceptionally(new UnsupportedVersionException("Consumer doesn't support batch-message")); return future; } if (subscriptionName.startsWith(replicatorPrefix)) { log.warn("[{}] Failed to create subscription for {}", topic, subscriptionName); future.completeExceptionally(new NamingException("Subscription with reserved subscription name attempted")); return future; } if (readCompacted) { future.completeExceptionally(new NotAllowedException("readCompacted only valid on persistent topics")); return future; } lock.readLock().lock(); try { if (isFenced) { log.warn("[{}] Attempting to subscribe to a fenced topic", topic); future.completeExceptionally(new TopicFencedException("Topic is temporarily unavailable")); return future; } USAGE_COUNT_UPDATER.incrementAndGet(this); if (log.isDebugEnabled()) { log.debug("[{}] [{}] [{}] Added consumer -- count: {}", topic, subscriptionName, consumerName, USAGE_COUNT_UPDATER.get(this)); } } finally { lock.readLock().unlock(); } NonPersistentSubscription subscription = subscriptions.computeIfAbsent(subscriptionName, name -> new NonPersistentSubscription(this, subscriptionName)); try { Consumer consumer = new Consumer(subscription, subType, topic, consumerId, priorityLevel, consumerName, 0, cnx, cnx.getRole(), metadata, readCompacted, initialPosition); subscription.addConsumer(consumer); if (!cnx.isActive()) { consumer.close(); if (log.isDebugEnabled()) { log.debug("[{}] [{}] [{}] Subscribe failed -- count: {}", topic, subscriptionName, consumer.consumerName(), USAGE_COUNT_UPDATER.get(NonPersistentTopic.this)); } future.completeExceptionally( new BrokerServiceException("Connection was closed while the opening the cursor ")); } else { log.info("[{}][{}] Created new subscription for {}", topic, subscriptionName, consumerId); future.complete(consumer); } } catch (BrokerServiceException e) { if (e instanceof ConsumerBusyException) { log.warn("[{}][{}] Consumer {} {} already connected", topic, subscriptionName, consumerId, consumerName); } else if (e instanceof SubscriptionBusyException) { log.warn("[{}][{}] {}", topic, subscriptionName, e.getMessage()); } USAGE_COUNT_UPDATER.decrementAndGet(NonPersistentTopic.this); future.completeExceptionally(e); } return future; } @Override public CompletableFuture<Subscription> createSubscription(String subscriptionName, InitialPosition initialPosition) { return CompletableFuture.completedFuture(new NonPersistentSubscription(this, subscriptionName)); } void removeSubscription(String subscriptionName) { subscriptions.remove(subscriptionName); } @Override public CompletableFuture<Void> delete() { return delete(false, false); } /** * Forcefully close all producers/consumers/replicators and deletes the topic. * * @return */ @Override public CompletableFuture<Void> deleteForcefully() { return delete(false, true); } private CompletableFuture<Void> delete(boolean failIfHasSubscriptions, boolean closeIfClientsConnected) { CompletableFuture<Void> deleteFuture = new CompletableFuture<>(); lock.writeLock().lock(); try { if (isFenced) { log.warn("[{}] Topic is already being closed or deleted", topic); deleteFuture.completeExceptionally(new TopicFencedException("Topic is already fenced")); return deleteFuture; } CompletableFuture<Void> closeClientFuture = new CompletableFuture<>(); if (closeIfClientsConnected) { List<CompletableFuture<Void>> futures = Lists.newArrayList(); replicators.forEach((cluster, replicator) -> futures.add(replicator.disconnect())); producers.forEach(producer -> futures.add(producer.disconnect())); subscriptions.forEach((s, sub) -> futures.add(sub.disconnect())); FutureUtil.waitForAll(futures).thenRun(() -> { closeClientFuture.complete(null); }).exceptionally(ex -> { log.error("[{}] Error closing clients", topic, ex); isFenced = false; closeClientFuture.completeExceptionally(ex); return null; }); } else { closeClientFuture.complete(null); } closeClientFuture.thenAccept(delete -> { if (USAGE_COUNT_UPDATER.get(this) == 0) { isFenced = true; List<CompletableFuture<Void>> futures = Lists.newArrayList(); if (failIfHasSubscriptions) { if (!subscriptions.isEmpty()) { isFenced = false; deleteFuture.completeExceptionally(new TopicBusyException("Topic has subscriptions")); return; } } else { subscriptions.forEach((s, sub) -> futures.add(sub.delete())); } FutureUtil.waitForAll(futures).whenComplete((v, ex) -> { if (ex != null) { log.error("[{}] Error deleting topic", topic, ex); isFenced = false; deleteFuture.completeExceptionally(ex); } else { brokerService.removeTopicFromCache(topic); log.info("[{}] Topic deleted", topic); deleteFuture.complete(null); } }); } else { deleteFuture.completeExceptionally(new TopicBusyException( "Topic has " + USAGE_COUNT_UPDATER.get(this) + " connected producers/consumers")); } }).exceptionally(ex -> { deleteFuture.completeExceptionally( new TopicBusyException("Failed to close clients before deleting topic.")); return null; }); } finally { lock.writeLock().unlock(); } return deleteFuture; } /** * Close this topic - close all producers and subscriptions associated with this topic * * @return Completable future indicating completion of close operation */ @Override public CompletableFuture<Void> close() { CompletableFuture<Void> closeFuture = new CompletableFuture<>(); lock.writeLock().lock(); try { if (!isFenced) { isFenced = true; } else { log.warn("[{}] Topic is already being closed or deleted", topic); closeFuture.completeExceptionally(new TopicFencedException("Topic is already fenced")); return closeFuture; } } finally { lock.writeLock().unlock(); } List<CompletableFuture<Void>> futures = Lists.newArrayList(); replicators.forEach((cluster, replicator) -> futures.add(replicator.disconnect())); producers.forEach(producer -> futures.add(producer.disconnect())); subscriptions.forEach((s, sub) -> futures.add(sub.disconnect())); FutureUtil.waitForAll(futures).thenRun(() -> { log.info("[{}] Topic closed", topic); // unload topic iterates over topics map and removing from the map with the same thread creates deadlock. // so, execute it in different thread brokerService.executor().execute(() -> { brokerService.removeTopicFromCache(topic); closeFuture.complete(null); }); }).exceptionally(exception -> { log.error("[{}] Error closing topic", topic, exception); isFenced = false; closeFuture.completeExceptionally(exception); return null; }); return closeFuture; } public CompletableFuture<Void> stopReplProducers() { List<CompletableFuture<Void>> closeFutures = Lists.newArrayList(); replicators.forEach((region, replicator) -> closeFutures.add(replicator.disconnect())); return FutureUtil.waitForAll(closeFutures); } @Override public CompletableFuture<Void> checkReplication() { TopicName name = TopicName.get(topic); if (!name.isGlobal()) { return CompletableFuture.completedFuture(null); } if (log.isDebugEnabled()) { log.debug("[{}] Checking replication status", name); } Policies policies = null; try { policies = brokerService.pulsar().getConfigurationCache().policiesCache() .get(AdminResource.path(POLICIES, name.getNamespace())) .orElseThrow(() -> new KeeperException.NoNodeException()); } catch (Exception e) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new ServerMetadataException(e)); return future; } Set<String> configuredClusters; if (policies.replication_clusters != null) { configuredClusters = policies.replication_clusters; } else { configuredClusters = Collections.emptySet(); } String localCluster = brokerService.pulsar().getConfiguration().getClusterName(); List<CompletableFuture<Void>> futures = Lists.newArrayList(); // Check for missing replicators for (String cluster : configuredClusters) { if (cluster.equals(localCluster)) { continue; } if (!replicators.containsKey(cluster)) { if (!startReplicator(cluster)) { // it happens when global topic is a partitioned topic and replicator can't start on original // non partitioned-topic (topic without partition prefix) return FutureUtil .failedFuture(new NamingException(topic + " failed to start replicator for " + cluster)); } } } // Check for replicators to be stopped replicators.forEach((cluster, replicator) -> { if (!cluster.equals(localCluster)) { if (!configuredClusters.contains(cluster)) { futures.add(removeReplicator(cluster)); } } }); return FutureUtil.waitForAll(futures); } boolean startReplicator(String remoteCluster) { log.info("[{}] Starting replicator to remote: {}", topic, remoteCluster); String localCluster = brokerService.pulsar().getConfiguration().getClusterName(); return addReplicationCluster(remoteCluster,NonPersistentTopic.this, localCluster); } protected boolean addReplicationCluster(String remoteCluster, NonPersistentTopic nonPersistentTopic, String localCluster) { AtomicBoolean isReplicatorStarted = new AtomicBoolean(true); replicators.computeIfAbsent(remoteCluster, r -> { try { return new NonPersistentReplicator(NonPersistentTopic.this, localCluster, remoteCluster, brokerService); } catch (NamingException e) { isReplicatorStarted.set(false); log.error("[{}] Replicator startup failed due to partitioned-topic {}", topic, remoteCluster); } return null; }); // clean up replicator if startup is failed if (!isReplicatorStarted.get()) { replicators.remove(remoteCluster); } return isReplicatorStarted.get(); } CompletableFuture<Void> removeReplicator(String remoteCluster) { log.info("[{}] Removing replicator to {}", topic, remoteCluster); final CompletableFuture<Void> future = new CompletableFuture<>(); String name = NonPersistentReplicator.getReplicatorName(replicatorPrefix, remoteCluster); replicators.get(remoteCluster).disconnect().thenRun(() -> { log.info("[{}] Successfully removed replicator {}", name, remoteCluster); }).exceptionally(e -> { log.error("[{}] Failed to close replication producer {} {}", topic, name, e.getMessage(), e); future.completeExceptionally(e); return null; }); return future; } private CompletableFuture<Void> checkReplicationAndRetryOnFailure() { CompletableFuture<Void> result = new CompletableFuture<Void>(); checkReplication().thenAccept(res -> { log.info("[{}] Policies updated successfully", topic); result.complete(null); }).exceptionally(th -> { log.error("[{}] Policies update failed {}, scheduled retry in {} seconds", topic, th.getMessage(), POLICY_UPDATE_FAILURE_RETRY_TIME_SECONDS, th); brokerService.executor().schedule(this::checkReplicationAndRetryOnFailure, POLICY_UPDATE_FAILURE_RETRY_TIME_SECONDS, TimeUnit.SECONDS); result.completeExceptionally(th); return null; }); return result; } @Override public void checkMessageExpiry() { // No-op } @Override public String toString() { return MoreObjects.toStringHelper(this).add("topic", topic).toString(); } @Override public ConcurrentOpenHashSet<Producer> getProducers() { return producers; } public int getNumberOfConsumers() { int count = 0; for (NonPersistentSubscription subscription : subscriptions.values()) { count += subscription.getConsumers().size(); } return count; } @Override public ConcurrentOpenHashMap<String, NonPersistentSubscription> getSubscriptions() { return subscriptions; } @Override public ConcurrentOpenHashMap<String, NonPersistentReplicator> getReplicators() { return replicators; } @Override public Subscription getSubscription(String subscription) { return subscriptions.get(subscription); } public Replicator getPersistentReplicator(String remoteCluster) { return replicators.get(remoteCluster); } public BrokerService getBrokerService() { return brokerService; } @Override public String getName() { return topic; } public void updateRates(NamespaceStats nsStats, NamespaceBundleStats bundleStats, StatsOutputStream topicStatsStream, ClusterReplicationMetrics replStats, String namespace, boolean hydratePublishers) { TopicStats topicStats = threadLocalTopicStats.get(); topicStats.reset(); replicators.forEach((region, replicator) -> replicator.updateRates()); nsStats.producerCount += producers.size(); bundleStats.producerCount += producers.size(); topicStatsStream.startObject(topic); topicStatsStream.startList("publishers"); producers.forEach(producer -> { producer.updateRates(); PublisherStats publisherStats = producer.getStats(); topicStats.aggMsgRateIn += publisherStats.msgRateIn; topicStats.aggMsgThroughputIn += publisherStats.msgThroughputIn; if (producer.isRemote()) { topicStats.remotePublishersStats.put(producer.getRemoteCluster(), publisherStats); } if (hydratePublishers) { StreamingStats.writePublisherStats(topicStatsStream, publisherStats); } }); topicStatsStream.endList(); // Start replicator stats topicStatsStream.startObject("replication"); nsStats.replicatorCount += topicStats.remotePublishersStats.size(); // Close replication topicStatsStream.endObject(); // Start subscription stats topicStatsStream.startObject("subscriptions"); nsStats.subsCount += subscriptions.size(); subscriptions.forEach((subscriptionName, subscription) -> { double subMsgRateOut = 0; double subMsgThroughputOut = 0; double subMsgRateRedeliver = 0; // Start subscription name & consumers try { topicStatsStream.startObject(subscriptionName); Object[] consumers = subscription.getConsumers().array(); nsStats.consumerCount += consumers.length; bundleStats.consumerCount += consumers.length; topicStatsStream.startList("consumers"); subscription.getDispatcher().getMesssageDropRate().calculateRate(); for (Object consumerObj : consumers) { Consumer consumer = (Consumer) consumerObj; consumer.updateRates(); ConsumerStats consumerStats = consumer.getStats(); subMsgRateOut += consumerStats.msgRateOut; subMsgThroughputOut += consumerStats.msgThroughputOut; subMsgRateRedeliver += consumerStats.msgRateRedeliver; // Populate consumer specific stats here StreamingStats.writeConsumerStats(topicStatsStream, subscription.getType(), consumerStats); } // Close Consumer stats topicStatsStream.endList(); // Populate subscription specific stats here topicStatsStream.writePair("msgBacklog", subscription.getNumberOfEntriesInBacklog()); topicStatsStream.writePair("msgRateExpired", subscription.getExpiredMessageRate()); topicStatsStream.writePair("msgRateOut", subMsgRateOut); topicStatsStream.writePair("msgThroughputOut", subMsgThroughputOut); topicStatsStream.writePair("msgRateRedeliver", subMsgRateRedeliver); topicStatsStream.writePair("type", subscription.getTypeString()); if (subscription.getDispatcher() != null) { topicStatsStream.writePair("msgDropRate", subscription.getDispatcher().getMesssageDropRate().getRate()); } // Close consumers topicStatsStream.endObject(); topicStats.aggMsgRateOut += subMsgRateOut; topicStats.aggMsgThroughputOut += subMsgThroughputOut; nsStats.msgBacklog += subscription.getNumberOfEntriesInBacklog(); } catch (Exception e) { log.error("Got exception when creating consumer stats for subscription {}: {}", subscriptionName, e.getMessage(), e); } }); // Close subscription topicStatsStream.endObject(); // Remaining dest stats. topicStats.averageMsgSize = topicStats.aggMsgRateIn == 0.0 ? 0.0 : (topicStats.aggMsgThroughputIn / topicStats.aggMsgRateIn); topicStatsStream.writePair("producerCount", producers.size()); topicStatsStream.writePair("averageMsgSize", topicStats.averageMsgSize); topicStatsStream.writePair("msgRateIn", topicStats.aggMsgRateIn); topicStatsStream.writePair("msgRateOut", topicStats.aggMsgRateOut); topicStatsStream.writePair("msgThroughputIn", topicStats.aggMsgThroughputIn); topicStatsStream.writePair("msgThroughputOut", topicStats.aggMsgThroughputOut); nsStats.msgRateIn += topicStats.aggMsgRateIn; nsStats.msgRateOut += topicStats.aggMsgRateOut; nsStats.msgThroughputIn += topicStats.aggMsgThroughputIn; nsStats.msgThroughputOut += topicStats.aggMsgThroughputOut; bundleStats.msgRateIn += topicStats.aggMsgRateIn; bundleStats.msgRateOut += topicStats.aggMsgRateOut; bundleStats.msgThroughputIn += topicStats.aggMsgThroughputIn; bundleStats.msgThroughputOut += topicStats.aggMsgThroughputOut; // Close topic object topicStatsStream.endObject(); } public NonPersistentTopicStats getStats() { NonPersistentTopicStats stats = new NonPersistentTopicStats(); ObjectObjectHashMap<String, PublisherStats> remotePublishersStats = new ObjectObjectHashMap<String, PublisherStats>(); producers.forEach(producer -> { NonPersistentPublisherStats publisherStats = (NonPersistentPublisherStats) producer.getStats(); stats.msgRateIn += publisherStats.msgRateIn; stats.msgThroughputIn += publisherStats.msgThroughputIn; if (producer.isRemote()) { remotePublishersStats.put(producer.getRemoteCluster(), publisherStats); } else { stats.getPublishers().add(publisherStats); } }); stats.averageMsgSize = stats.msgRateIn == 0.0 ? 0.0 : (stats.msgThroughputIn / stats.msgRateIn); subscriptions.forEach((name, subscription) -> { NonPersistentSubscriptionStats subStats = subscription.getStats(); stats.msgRateOut += subStats.msgRateOut; stats.msgThroughputOut += subStats.msgThroughputOut; stats.getSubscriptions().put(name, subStats); }); replicators.forEach((cluster, replicator) -> { NonPersistentReplicatorStats ReplicatorStats = replicator.getStats(); // Add incoming msg rates PublisherStats pubStats = remotePublishersStats.get(replicator.getRemoteCluster()); if (pubStats != null) { ReplicatorStats.msgRateIn = pubStats.msgRateIn; ReplicatorStats.msgThroughputIn = pubStats.msgThroughputIn; ReplicatorStats.inboundConnection = pubStats.getAddress(); ReplicatorStats.inboundConnectedSince = pubStats.getConnectedSince(); } stats.msgRateOut += ReplicatorStats.msgRateOut; stats.msgThroughputOut += ReplicatorStats.msgThroughputOut; stats.getReplication().put(replicator.getRemoteCluster(), ReplicatorStats); }); return stats; } public PersistentTopicInternalStats getInternalStats() { PersistentTopicInternalStats stats = new PersistentTopicInternalStats(); stats.entriesAddedCounter = ENTRIES_ADDED_COUNTER_UPDATER.get(this); stats.cursors = Maps.newTreeMap(); subscriptions.forEach((name, subs) -> stats.cursors.put(name, new CursorStats())); replicators.forEach((name, subs) -> stats.cursors.put(name, new CursorStats())); return stats; } public boolean isActive() { if (TopicName.get(topic).isGlobal()) { // No local consumers and no local producers return !subscriptions.isEmpty() || hasLocalProducers(); } return USAGE_COUNT_UPDATER.get(this) != 0 || !subscriptions.isEmpty(); } @Override public void checkGC(int gcIntervalInSeconds) { if (isActive()) { lastActive = System.nanoTime(); } else { if (System.nanoTime() - lastActive > TimeUnit.SECONDS.toNanos(gcIntervalInSeconds)) { if (TopicName.get(topic).isGlobal()) { // For global namespace, close repl producers first. // Once all repl producers are closed, we can delete the topic, // provided no remote producers connected to the broker. if (log.isDebugEnabled()) { log.debug("[{}] Global topic inactive for {} seconds, closing repl producers.", topic, gcIntervalInSeconds); } stopReplProducers().thenCompose(v -> delete(true, false)) .thenRun(() -> log.info("[{}] Topic deleted successfully due to inactivity", topic)) .exceptionally(e -> { if (e.getCause() instanceof TopicBusyException) { // topic became active again if (log.isDebugEnabled()) { log.debug("[{}] Did not delete busy topic: {}", topic, e.getCause().getMessage()); } replicators.forEach((region, replicator) -> ((NonPersistentReplicator) replicator) .startProducer()); } else { log.warn("[{}] Inactive topic deletion failed", topic, e); } return null; }); } } } } @Override public void checkInactiveSubscriptions() { // no-op } @Override public CompletableFuture<Void> onPoliciesUpdate(Policies data) { if (log.isDebugEnabled()) { log.debug("[{}] isEncryptionRequired changes: {} -> {}", topic, isEncryptionRequired, data.encryption_required); } isEncryptionRequired = data.encryption_required; producers.forEach(producer -> { producer.checkPermissions(); producer.checkEncryption(); }); subscriptions.forEach((subName, sub) -> sub.getConsumers().forEach(Consumer::checkPermissions)); return checkReplicationAndRetryOnFailure(); } /** * * @return Backlog quota for topic */ @Override public BacklogQuota getBacklogQuota() { // No-op throw new UnsupportedOperationException("getBacklogQuota method is not supported on non-persistent topic"); } /** * * @return quota exceeded status for blocking producer creation */ @Override public boolean isBacklogQuotaExceeded(String producerName) { // No-op return false; } @Override public boolean isEncryptionRequired() { return isEncryptionRequired; } @Override public boolean isReplicated() { return replicators.size() > 1; } @Override public CompletableFuture<Void> unsubscribe(String subName) { // No-op return CompletableFuture.completedFuture(null); } @Override public Position getLastMessageId() { throw new UnsupportedOperationException("getLastMessageId is not supported on non-persistent topic"); } public void markBatchMessagePublished() { this.hasBatchMessagePublished = true; } private static final Logger log = LoggerFactory.getLogger(NonPersistentTopic.class); @Override public CompletableFuture<SchemaVersion> addSchema(SchemaData schema) { if (schema == null) { return CompletableFuture.completedFuture(SchemaVersion.Empty); } String base = TopicName.get(getName()).getPartitionedTopicName(); String id = TopicName.get(base).getSchemaName(); return brokerService.pulsar() .getSchemaRegistryService() .putSchemaIfAbsent(id, schema); } @Override public CompletableFuture<Boolean> isSchemaCompatible(SchemaData schema) { String base = TopicName.get(getName()).getPartitionedTopicName(); String id = TopicName.get(base).getSchemaName(); return brokerService.pulsar() .getSchemaRegistryService() .isCompatibleWithLatestVersion(id, schema); } }
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentTopic.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.pulsar.broker.service.nonpersistent; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.bookkeeper.mledger.impl.EntryCacheManager.create; import static org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES; import com.carrotsearch.hppc.ObjectObjectHashMap; import com.google.common.base.MoreObjects; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import io.netty.buffer.ByteBuf; import io.netty.util.concurrent.FastThreadLocal; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.bookkeeper.common.util.OrderedExecutor; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.Position; import org.apache.bookkeeper.mledger.util.SafeRun; import org.apache.pulsar.broker.admin.AdminResource; import org.apache.pulsar.broker.service.BrokerService; import org.apache.pulsar.broker.service.BrokerServiceException; import org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.NamingException; import org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException; import org.apache.pulsar.broker.service.BrokerServiceException.ProducerBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException; import org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException; import org.apache.pulsar.broker.service.BrokerServiceException.TopicFencedException; import org.apache.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException; import org.apache.pulsar.broker.service.Consumer; import org.apache.pulsar.broker.service.Producer; import org.apache.pulsar.broker.service.Replicator; import org.apache.pulsar.broker.service.ServerCnx; import org.apache.pulsar.broker.service.StreamingStats; import org.apache.pulsar.broker.service.Subscription; import org.apache.pulsar.broker.service.Topic; import org.apache.pulsar.broker.stats.ClusterReplicationMetrics; import org.apache.pulsar.broker.stats.NamespaceStats; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition; import org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.BacklogQuota; import org.apache.pulsar.common.policies.data.ConsumerStats; import org.apache.pulsar.common.policies.data.NonPersistentPublisherStats; import org.apache.pulsar.common.policies.data.NonPersistentReplicatorStats; import org.apache.pulsar.common.policies.data.NonPersistentSubscriptionStats; import org.apache.pulsar.common.policies.data.NonPersistentTopicStats; import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats; import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.CursorStats; import org.apache.pulsar.common.policies.data.Policies; import org.apache.pulsar.common.policies.data.PublisherStats; import org.apache.pulsar.common.schema.SchemaData; import org.apache.pulsar.common.schema.SchemaVersion; import org.apache.pulsar.common.util.FutureUtil; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet; import org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats; import org.apache.pulsar.utils.StatsOutputStream; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NonPersistentTopic implements Topic { private final String topic; // Producers currently connected to this topic private final ConcurrentOpenHashSet<Producer> producers; // Subscriptions to this topic private final ConcurrentOpenHashMap<String, NonPersistentSubscription> subscriptions; private final ConcurrentOpenHashMap<String, NonPersistentReplicator> replicators; private final BrokerService brokerService; private volatile boolean isFenced; // Prefix for replication cursors public final String replicatorPrefix; protected static final AtomicLongFieldUpdater<NonPersistentTopic> USAGE_COUNT_UPDATER = AtomicLongFieldUpdater .newUpdater(NonPersistentTopic.class, "usageCount"); private volatile long usageCount = 0; private final OrderedExecutor executor; private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // Timestamp of when this topic was last seen active private volatile long lastActive; // Flag to signal that producer of this topic has published batch-message so, broker should not allow consumer which // doesn't support batch-message private volatile boolean hasBatchMessagePublished = false; // Ever increasing counter of entries added static final AtomicLongFieldUpdater<NonPersistentTopic> ENTRIES_ADDED_COUNTER_UPDATER = AtomicLongFieldUpdater .newUpdater(NonPersistentTopic.class, "entriesAddedCounter"); private volatile long entriesAddedCounter = 0; private static final long POLICY_UPDATE_FAILURE_RETRY_TIME_SECONDS = 60; private static final FastThreadLocal<TopicStats> threadLocalTopicStats = new FastThreadLocal<TopicStats>() { @Override protected TopicStats initialValue() { return new TopicStats(); } }; // Whether messages published must be encrypted or not in this topic private volatile boolean isEncryptionRequired = false; private static class TopicStats { public double averageMsgSize; public double aggMsgRateIn; public double aggMsgThroughputIn; public double aggMsgRateOut; public double aggMsgThroughputOut; public final ObjectObjectHashMap<String, PublisherStats> remotePublishersStats; public TopicStats() { remotePublishersStats = new ObjectObjectHashMap<String, PublisherStats>(); reset(); } public void reset() { averageMsgSize = 0; aggMsgRateIn = 0; aggMsgThroughputIn = 0; aggMsgRateOut = 0; aggMsgThroughputOut = 0; remotePublishersStats.clear(); } } public NonPersistentTopic(String topic, BrokerService brokerService) { this.topic = topic; this.brokerService = brokerService; this.producers = new ConcurrentOpenHashSet<Producer>(16, 1); this.subscriptions = new ConcurrentOpenHashMap<>(16, 1); this.replicators = new ConcurrentOpenHashMap<>(16, 1); this.isFenced = false; this.replicatorPrefix = brokerService.pulsar().getConfiguration().getReplicatorPrefix(); this.executor = brokerService.getTopicOrderedExecutor(); USAGE_COUNT_UPDATER.set(this, 0); this.lastActive = System.nanoTime(); try { Policies policies = brokerService.pulsar().getConfigurationCache().policiesCache() .get(AdminResource.path(POLICIES, TopicName.get(topic).getNamespace())) .orElseThrow(() -> new KeeperException.NoNodeException()); isEncryptionRequired = policies.encryption_required; } catch (Exception e) { log.warn("[{}] Error getting policies {} and isEncryptionRequired will be set to false", topic, e.getMessage()); isEncryptionRequired = false; } } @Override public void publishMessage(ByteBuf data, PublishContext callback) { AtomicInteger msgDeliveryCount = new AtomicInteger(2); ENTRIES_ADDED_COUNTER_UPDATER.incrementAndGet(this); // retain data for sub/replication because io-thread will release actual payload data.retain(2); this.executor.executeOrdered(topic, SafeRun.safeRun(() -> { subscriptions.forEach((name, subscription) -> { ByteBuf duplicateBuffer = data.retainedDuplicate(); Entry entry = create(0L, 0L, duplicateBuffer); // entry internally retains data so, duplicateBuffer should be release here duplicateBuffer.release(); if (subscription.getDispatcher() != null) { subscription.getDispatcher().sendMessages(Lists.newArrayList(entry)); } else { // it happens when subscription is created but dispatcher is not created as consumer is not added // yet entry.release(); } }); data.release(); if (msgDeliveryCount.decrementAndGet() == 0) { callback.completed(null, 0L, 0L); } })); this.executor.executeOrdered(topic, SafeRun.safeRun(() -> { replicators.forEach((name, replicator) -> { ByteBuf duplicateBuffer = data.retainedDuplicate(); Entry entry = create(0L, 0L, duplicateBuffer); // entry internally retains data so, duplicateBuffer should be release here duplicateBuffer.release(); ((NonPersistentReplicator) replicator).sendMessage(entry); }); data.release(); if (msgDeliveryCount.decrementAndGet() == 0) { callback.completed(null, 0L, 0L); } })); } @Override public void addProducer(Producer producer) throws BrokerServiceException { checkArgument(producer.getTopic() == this); lock.readLock().lock(); try { if (isFenced) { log.warn("[{}] Attempting to add producer to a fenced topic", topic); throw new TopicFencedException("Topic is temporarily unavailable"); } if (isProducersExceeded()) { log.warn("[{}] Attempting to add producer to topic which reached max producers limit", topic); throw new ProducerBusyException("Topic reached max producers limit"); } if (log.isDebugEnabled()) { log.debug("[{}] {} Got request to create producer ", topic, producer.getProducerName()); } if (!producers.add(producer)) { throw new NamingException( "Producer with name '" + producer.getProducerName() + "' is already connected to topic"); } USAGE_COUNT_UPDATER.incrementAndGet(this); if (log.isDebugEnabled()) { log.debug("[{}] [{}] Added producer -- count: {}", topic, producer.getProducerName(), USAGE_COUNT_UPDATER.get(this)); } } finally { lock.readLock().unlock(); } } private boolean isProducersExceeded() { Policies policies; try { policies = brokerService.pulsar().getConfigurationCache().policiesCache() .get(AdminResource.path(POLICIES, TopicName.get(topic).getNamespace())) .orElseGet(() -> new Policies()); } catch (Exception e) { policies = new Policies(); } final int maxProducers = policies.max_producers_per_topic > 0 ? policies.max_producers_per_topic : brokerService.pulsar().getConfiguration().getMaxProducersPerTopic(); if (maxProducers > 0 && maxProducers <= producers.size()) { return true; } return false; } @Override public void checkMessageDeduplicationInfo() { // No-op } private boolean hasLocalProducers() { AtomicBoolean foundLocal = new AtomicBoolean(false); producers.forEach(producer -> { if (!producer.isRemote()) { foundLocal.set(true); } }); return foundLocal.get(); } private boolean hasRemoteProducers() { AtomicBoolean foundRemote = new AtomicBoolean(false); producers.forEach(producer -> { if (producer.isRemote()) { foundRemote.set(true); } }); return foundRemote.get(); } @Override public void removeProducer(Producer producer) { checkArgument(producer.getTopic() == this); if (producers.remove(producer)) { // decrement usage only if this was a valid producer close USAGE_COUNT_UPDATER.decrementAndGet(this); if (log.isDebugEnabled()) { log.debug("[{}] [{}] Removed producer -- count: {}", topic, producer.getProducerName(), USAGE_COUNT_UPDATER.get(this)); } lastActive = System.nanoTime(); } } @Override public CompletableFuture<Consumer> subscribe(final ServerCnx cnx, String subscriptionName, long consumerId, SubType subType, int priorityLevel, String consumerName, boolean isDurable, MessageId startMessageId, Map<String, String> metadata, boolean readCompacted, InitialPosition initialPosition) { final CompletableFuture<Consumer> future = new CompletableFuture<>(); if (hasBatchMessagePublished && !cnx.isBatchMessageCompatibleVersion()) { if (log.isDebugEnabled()) { log.debug("[{}] Consumer doesn't support batch-message {}", topic, subscriptionName); } future.completeExceptionally(new UnsupportedVersionException("Consumer doesn't support batch-message")); return future; } if (subscriptionName.startsWith(replicatorPrefix)) { log.warn("[{}] Failed to create subscription for {}", topic, subscriptionName); future.completeExceptionally(new NamingException("Subscription with reserved subscription name attempted")); return future; } if (readCompacted) { future.completeExceptionally(new NotAllowedException("readCompacted only valid on persistent topics")); return future; } lock.readLock().lock(); try { if (isFenced) { log.warn("[{}] Attempting to subscribe to a fenced topic", topic); future.completeExceptionally(new TopicFencedException("Topic is temporarily unavailable")); return future; } USAGE_COUNT_UPDATER.incrementAndGet(this); if (log.isDebugEnabled()) { log.debug("[{}] [{}] [{}] Added consumer -- count: {}", topic, subscriptionName, consumerName, USAGE_COUNT_UPDATER.get(this)); } } finally { lock.readLock().unlock(); } NonPersistentSubscription subscription = subscriptions.computeIfAbsent(subscriptionName, name -> new NonPersistentSubscription(this, subscriptionName)); try { Consumer consumer = new Consumer(subscription, subType, topic, consumerId, priorityLevel, consumerName, 0, cnx, cnx.getRole(), metadata, readCompacted, initialPosition); subscription.addConsumer(consumer); if (!cnx.isActive()) { consumer.close(); if (log.isDebugEnabled()) { log.debug("[{}] [{}] [{}] Subscribe failed -- count: {}", topic, subscriptionName, consumer.consumerName(), USAGE_COUNT_UPDATER.get(NonPersistentTopic.this)); } future.completeExceptionally( new BrokerServiceException("Connection was closed while the opening the cursor ")); } else { log.info("[{}][{}] Created new subscription for {}", topic, subscriptionName, consumerId); future.complete(consumer); } } catch (BrokerServiceException e) { if (e instanceof ConsumerBusyException) { log.warn("[{}][{}] Consumer {} {} already connected", topic, subscriptionName, consumerId, consumerName); } else if (e instanceof SubscriptionBusyException) { log.warn("[{}][{}] {}", topic, subscriptionName, e.getMessage()); } USAGE_COUNT_UPDATER.decrementAndGet(NonPersistentTopic.this); future.completeExceptionally(e); } return future; } @Override public CompletableFuture<Subscription> createSubscription(String subscriptionName, InitialPosition initialPosition) { return CompletableFuture.completedFuture(new NonPersistentSubscription(this, subscriptionName)); } void removeSubscription(String subscriptionName) { subscriptions.remove(subscriptionName); } @Override public CompletableFuture<Void> delete() { return delete(false, false); } /** * Forcefully close all producers/consumers/replicators and deletes the topic. * * @return */ @Override public CompletableFuture<Void> deleteForcefully() { return delete(false, true); } private CompletableFuture<Void> delete(boolean failIfHasSubscriptions, boolean closeIfClientsConnected) { CompletableFuture<Void> deleteFuture = new CompletableFuture<>(); lock.writeLock().lock(); try { if (isFenced) { log.warn("[{}] Topic is already being closed or deleted", topic); deleteFuture.completeExceptionally(new TopicFencedException("Topic is already fenced")); return deleteFuture; } CompletableFuture<Void> closeClientFuture = new CompletableFuture<>(); if (closeIfClientsConnected) { List<CompletableFuture<Void>> futures = Lists.newArrayList(); replicators.forEach((cluster, replicator) -> futures.add(replicator.disconnect())); producers.forEach(producer -> futures.add(producer.disconnect())); subscriptions.forEach((s, sub) -> futures.add(sub.disconnect())); FutureUtil.waitForAll(futures).thenRun(() -> { closeClientFuture.complete(null); }).exceptionally(ex -> { log.error("[{}] Error closing clients", topic, ex); isFenced = false; closeClientFuture.completeExceptionally(ex); return null; }); } else { closeClientFuture.complete(null); } closeClientFuture.thenAccept(delete -> { if (USAGE_COUNT_UPDATER.get(this) == 0) { isFenced = true; List<CompletableFuture<Void>> futures = Lists.newArrayList(); if (failIfHasSubscriptions) { if (!subscriptions.isEmpty()) { isFenced = false; deleteFuture.completeExceptionally(new TopicBusyException("Topic has subscriptions")); return; } } else { subscriptions.forEach((s, sub) -> futures.add(sub.delete())); } FutureUtil.waitForAll(futures).whenComplete((v, ex) -> { if (ex != null) { log.error("[{}] Error deleting topic", topic, ex); isFenced = false; deleteFuture.completeExceptionally(ex); } else { brokerService.removeTopicFromCache(topic); log.info("[{}] Topic deleted", topic); deleteFuture.complete(null); } }); } else { deleteFuture.completeExceptionally(new TopicBusyException( "Topic has " + USAGE_COUNT_UPDATER.get(this) + " connected producers/consumers")); } }).exceptionally(ex -> { deleteFuture.completeExceptionally( new TopicBusyException("Failed to close clients before deleting topic.")); return null; }); } finally { lock.writeLock().unlock(); } return deleteFuture; } /** * Close this topic - close all producers and subscriptions associated with this topic * * @return Completable future indicating completion of close operation */ @Override public CompletableFuture<Void> close() { CompletableFuture<Void> closeFuture = new CompletableFuture<>(); lock.writeLock().lock(); try { if (!isFenced) { isFenced = true; } else { log.warn("[{}] Topic is already being closed or deleted", topic); closeFuture.completeExceptionally(new TopicFencedException("Topic is already fenced")); return closeFuture; } } finally { lock.writeLock().unlock(); } List<CompletableFuture<Void>> futures = Lists.newArrayList(); replicators.forEach((cluster, replicator) -> futures.add(replicator.disconnect())); producers.forEach(producer -> futures.add(producer.disconnect())); subscriptions.forEach((s, sub) -> futures.add(sub.disconnect())); FutureUtil.waitForAll(futures).thenRun(() -> { log.info("[{}] Topic closed", topic); // unload topic iterates over topics map and removing from the map with the same thread creates deadlock. // so, execute it in different thread brokerService.executor().execute(() -> { brokerService.removeTopicFromCache(topic); closeFuture.complete(null); }); }).exceptionally(exception -> { log.error("[{}] Error closing topic", topic, exception); isFenced = false; closeFuture.completeExceptionally(exception); return null; }); return closeFuture; } public CompletableFuture<Void> stopReplProducers() { List<CompletableFuture<Void>> closeFutures = Lists.newArrayList(); replicators.forEach((region, replicator) -> closeFutures.add(replicator.disconnect())); return FutureUtil.waitForAll(closeFutures); } @Override public CompletableFuture<Void> checkReplication() { TopicName name = TopicName.get(topic); if (!name.isGlobal()) { return CompletableFuture.completedFuture(null); } if (log.isDebugEnabled()) { log.debug("[{}] Checking replication status", name); } Policies policies = null; try { policies = brokerService.pulsar().getConfigurationCache().policiesCache() .get(AdminResource.path(POLICIES, name.getNamespace())) .orElseThrow(() -> new KeeperException.NoNodeException()); } catch (Exception e) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new ServerMetadataException(e)); return future; } Set<String> configuredClusters; if (policies.replication_clusters != null) { configuredClusters = policies.replication_clusters; } else { configuredClusters = Collections.emptySet(); } String localCluster = brokerService.pulsar().getConfiguration().getClusterName(); List<CompletableFuture<Void>> futures = Lists.newArrayList(); // Check for missing replicators for (String cluster : configuredClusters) { if (cluster.equals(localCluster)) { continue; } if (!replicators.containsKey(cluster)) { if (!startReplicator(cluster)) { // it happens when global topic is a partitioned topic and replicator can't start on original // non partitioned-topic (topic without partition prefix) return FutureUtil .failedFuture(new NamingException(topic + " failed to start replicator for " + cluster)); } } } // Check for replicators to be stopped replicators.forEach((cluster, replicator) -> { if (!cluster.equals(localCluster)) { if (!configuredClusters.contains(cluster)) { futures.add(removeReplicator(cluster)); } } }); return FutureUtil.waitForAll(futures); } boolean startReplicator(String remoteCluster) { log.info("[{}] Starting replicator to remote: {}", topic, remoteCluster); String localCluster = brokerService.pulsar().getConfiguration().getClusterName(); return addReplicationCluster(remoteCluster,NonPersistentTopic.this, localCluster); } protected boolean addReplicationCluster(String remoteCluster, NonPersistentTopic nonPersistentTopic, String localCluster) { AtomicBoolean isReplicatorStarted = new AtomicBoolean(true); replicators.computeIfAbsent(remoteCluster, r -> { try { return new NonPersistentReplicator(NonPersistentTopic.this, localCluster, remoteCluster, brokerService); } catch (NamingException e) { isReplicatorStarted.set(false); log.error("[{}] Replicator startup failed due to partitioned-topic {}", topic, remoteCluster); } return null; }); // clean up replicator if startup is failed if (!isReplicatorStarted.get()) { replicators.remove(remoteCluster); } return isReplicatorStarted.get(); } CompletableFuture<Void> removeReplicator(String remoteCluster) { log.info("[{}] Removing replicator to {}", topic, remoteCluster); final CompletableFuture<Void> future = new CompletableFuture<>(); String name = NonPersistentReplicator.getReplicatorName(replicatorPrefix, remoteCluster); replicators.get(remoteCluster).disconnect().thenRun(() -> { log.info("[{}] Successfully removed replicator {}", name, remoteCluster); }).exceptionally(e -> { log.error("[{}] Failed to close replication producer {} {}", topic, name, e.getMessage(), e); future.completeExceptionally(e); return null; }); return future; } private CompletableFuture<Void> checkReplicationAndRetryOnFailure() { CompletableFuture<Void> result = new CompletableFuture<Void>(); checkReplication().thenAccept(res -> { log.info("[{}] Policies updated successfully", topic); result.complete(null); }).exceptionally(th -> { log.error("[{}] Policies update failed {}, scheduled retry in {} seconds", topic, th.getMessage(), POLICY_UPDATE_FAILURE_RETRY_TIME_SECONDS, th); brokerService.executor().schedule(this::checkReplicationAndRetryOnFailure, POLICY_UPDATE_FAILURE_RETRY_TIME_SECONDS, TimeUnit.SECONDS); result.completeExceptionally(th); return null; }); return result; } @Override public void checkMessageExpiry() { // No-op } @Override public String toString() { return MoreObjects.toStringHelper(this).add("topic", topic).toString(); } @Override public ConcurrentOpenHashSet<Producer> getProducers() { return producers; } public int getNumberOfConsumers() { int count = 0; for (NonPersistentSubscription subscription : subscriptions.values()) { count += subscription.getConsumers().size(); } return count; } @Override public ConcurrentOpenHashMap<String, NonPersistentSubscription> getSubscriptions() { return subscriptions; } @Override public ConcurrentOpenHashMap<String, NonPersistentReplicator> getReplicators() { return replicators; } @Override public Subscription getSubscription(String subscription) { return subscriptions.get(subscription); } public Replicator getPersistentReplicator(String remoteCluster) { return replicators.get(remoteCluster); } public BrokerService getBrokerService() { return brokerService; } @Override public String getName() { return topic; } public void updateRates(NamespaceStats nsStats, NamespaceBundleStats bundleStats, StatsOutputStream topicStatsStream, ClusterReplicationMetrics replStats, String namespace, boolean hydratePublishers) { TopicStats topicStats = threadLocalTopicStats.get(); topicStats.reset(); replicators.forEach((region, replicator) -> replicator.updateRates()); nsStats.producerCount += producers.size(); bundleStats.producerCount += producers.size(); topicStatsStream.startObject(topic); topicStatsStream.startList("publishers"); producers.forEach(producer -> { producer.updateRates(); PublisherStats publisherStats = producer.getStats(); topicStats.aggMsgRateIn += publisherStats.msgRateIn; topicStats.aggMsgThroughputIn += publisherStats.msgThroughputIn; if (producer.isRemote()) { topicStats.remotePublishersStats.put(producer.getRemoteCluster(), publisherStats); } if (hydratePublishers) { StreamingStats.writePublisherStats(topicStatsStream, publisherStats); } }); topicStatsStream.endList(); // Start replicator stats topicStatsStream.startObject("replication"); nsStats.replicatorCount += topicStats.remotePublishersStats.size(); // Close replication topicStatsStream.endObject(); // Start subscription stats topicStatsStream.startObject("subscriptions"); nsStats.subsCount += subscriptions.size(); subscriptions.forEach((subscriptionName, subscription) -> { double subMsgRateOut = 0; double subMsgThroughputOut = 0; double subMsgRateRedeliver = 0; // Start subscription name & consumers try { topicStatsStream.startObject(subscriptionName); Object[] consumers = subscription.getConsumers().array(); nsStats.consumerCount += consumers.length; bundleStats.consumerCount += consumers.length; topicStatsStream.startList("consumers"); subscription.getDispatcher().getMesssageDropRate().calculateRate(); for (Object consumerObj : consumers) { Consumer consumer = (Consumer) consumerObj; consumer.updateRates(); ConsumerStats consumerStats = consumer.getStats(); subMsgRateOut += consumerStats.msgRateOut; subMsgThroughputOut += consumerStats.msgThroughputOut; subMsgRateRedeliver += consumerStats.msgRateRedeliver; // Populate consumer specific stats here StreamingStats.writeConsumerStats(topicStatsStream, subscription.getType(), consumerStats); } // Close Consumer stats topicStatsStream.endList(); // Populate subscription specific stats here topicStatsStream.writePair("msgBacklog", subscription.getNumberOfEntriesInBacklog()); topicStatsStream.writePair("msgRateExpired", subscription.getExpiredMessageRate()); topicStatsStream.writePair("msgRateOut", subMsgRateOut); topicStatsStream.writePair("msgThroughputOut", subMsgThroughputOut); topicStatsStream.writePair("msgRateRedeliver", subMsgRateRedeliver); topicStatsStream.writePair("type", subscription.getTypeString()); if (subscription.getDispatcher() != null) { topicStatsStream.writePair("msgDropRate", subscription.getDispatcher().getMesssageDropRate().getRate()); } // Close consumers topicStatsStream.endObject(); topicStats.aggMsgRateOut += subMsgRateOut; topicStats.aggMsgThroughputOut += subMsgThroughputOut; nsStats.msgBacklog += subscription.getNumberOfEntriesInBacklog(); } catch (Exception e) { log.error("Got exception when creating consumer stats for subscription {}: {}", subscriptionName, e.getMessage(), e); } }); // Close subscription topicStatsStream.endObject(); // Remaining dest stats. topicStats.averageMsgSize = topicStats.aggMsgRateIn == 0.0 ? 0.0 : (topicStats.aggMsgThroughputIn / topicStats.aggMsgRateIn); topicStatsStream.writePair("producerCount", producers.size()); topicStatsStream.writePair("averageMsgSize", topicStats.averageMsgSize); topicStatsStream.writePair("msgRateIn", topicStats.aggMsgRateIn); topicStatsStream.writePair("msgRateOut", topicStats.aggMsgRateOut); topicStatsStream.writePair("msgThroughputIn", topicStats.aggMsgThroughputIn); topicStatsStream.writePair("msgThroughputOut", topicStats.aggMsgThroughputOut); nsStats.msgRateIn += topicStats.aggMsgRateIn; nsStats.msgRateOut += topicStats.aggMsgRateOut; nsStats.msgThroughputIn += topicStats.aggMsgThroughputIn; nsStats.msgThroughputOut += topicStats.aggMsgThroughputOut; bundleStats.msgRateIn += topicStats.aggMsgRateIn; bundleStats.msgRateOut += topicStats.aggMsgRateOut; bundleStats.msgThroughputIn += topicStats.aggMsgThroughputIn; bundleStats.msgThroughputOut += topicStats.aggMsgThroughputOut; // Close topic object topicStatsStream.endObject(); } public NonPersistentTopicStats getStats() { NonPersistentTopicStats stats = new NonPersistentTopicStats(); ObjectObjectHashMap<String, PublisherStats> remotePublishersStats = new ObjectObjectHashMap<String, PublisherStats>(); producers.forEach(producer -> { NonPersistentPublisherStats publisherStats = (NonPersistentPublisherStats) producer.getStats(); stats.msgRateIn += publisherStats.msgRateIn; stats.msgThroughputIn += publisherStats.msgThroughputIn; if (producer.isRemote()) { remotePublishersStats.put(producer.getRemoteCluster(), publisherStats); } else { stats.getPublishers().add(publisherStats); } }); stats.averageMsgSize = stats.msgRateIn == 0.0 ? 0.0 : (stats.msgThroughputIn / stats.msgRateIn); subscriptions.forEach((name, subscription) -> { NonPersistentSubscriptionStats subStats = subscription.getStats(); stats.msgRateOut += subStats.msgRateOut; stats.msgThroughputOut += subStats.msgThroughputOut; stats.getSubscriptions().put(name, subStats); }); replicators.forEach((cluster, replicator) -> { NonPersistentReplicatorStats ReplicatorStats = replicator.getStats(); // Add incoming msg rates PublisherStats pubStats = remotePublishersStats.get(replicator.getRemoteCluster()); if (pubStats != null) { ReplicatorStats.msgRateIn = pubStats.msgRateIn; ReplicatorStats.msgThroughputIn = pubStats.msgThroughputIn; ReplicatorStats.inboundConnection = pubStats.getAddress(); ReplicatorStats.inboundConnectedSince = pubStats.getConnectedSince(); } stats.msgRateOut += ReplicatorStats.msgRateOut; stats.msgThroughputOut += ReplicatorStats.msgThroughputOut; stats.getReplication().put(replicator.getRemoteCluster(), ReplicatorStats); }); return stats; } public PersistentTopicInternalStats getInternalStats() { PersistentTopicInternalStats stats = new PersistentTopicInternalStats(); stats.entriesAddedCounter = ENTRIES_ADDED_COUNTER_UPDATER.get(this); stats.cursors = Maps.newTreeMap(); subscriptions.forEach((name, subs) -> stats.cursors.put(name, new CursorStats())); replicators.forEach((name, subs) -> stats.cursors.put(name, new CursorStats())); return stats; } public boolean isActive() { if (TopicName.get(topic).isGlobal()) { // No local consumers and no local producers return !subscriptions.isEmpty() || hasLocalProducers(); } return USAGE_COUNT_UPDATER.get(this) != 0 || !subscriptions.isEmpty(); } @Override public void checkGC(int gcIntervalInSeconds) { if (isActive()) { lastActive = System.nanoTime(); } else { if (System.nanoTime() - lastActive > TimeUnit.SECONDS.toNanos(gcIntervalInSeconds)) { if (TopicName.get(topic).isGlobal()) { // For global namespace, close repl producers first. // Once all repl producers are closed, we can delete the topic, // provided no remote producers connected to the broker. if (log.isDebugEnabled()) { log.debug("[{}] Global topic inactive for {} seconds, closing repl producers.", topic, gcIntervalInSeconds); } stopReplProducers().thenCompose(v -> delete(true, false)) .thenRun(() -> log.info("[{}] Topic deleted successfully due to inactivity", topic)) .exceptionally(e -> { if (e.getCause() instanceof TopicBusyException) { // topic became active again if (log.isDebugEnabled()) { log.debug("[{}] Did not delete busy topic: {}", topic, e.getCause().getMessage()); } replicators.forEach((region, replicator) -> ((NonPersistentReplicator) replicator) .startProducer()); } else { log.warn("[{}] Inactive topic deletion failed", topic, e); } return null; }); } } } } @Override public void checkInactiveSubscriptions() { // no-op } @Override public CompletableFuture<Void> onPoliciesUpdate(Policies data) { if (log.isDebugEnabled()) { log.debug("[{}] isEncryptionRequired changes: {} -> {}", topic, isEncryptionRequired, data.encryption_required); } isEncryptionRequired = data.encryption_required; producers.forEach(producer -> { producer.checkPermissions(); producer.checkEncryption(); }); subscriptions.forEach((subName, sub) -> sub.getConsumers().forEach(Consumer::checkPermissions)); return checkReplicationAndRetryOnFailure(); } /** * * @return Backlog quota for topic */ @Override public BacklogQuota getBacklogQuota() { // No-op throw new UnsupportedOperationException("getBacklogQuota method is not supported on non-persistent topic"); } /** * * @return quota exceeded status for blocking producer creation */ @Override public boolean isBacklogQuotaExceeded(String producerName) { // No-op return false; } @Override public boolean isEncryptionRequired() { return isEncryptionRequired; } @Override public boolean isReplicated() { return replicators.size() > 1; } @Override public CompletableFuture<Void> unsubscribe(String subName) { // No-op return CompletableFuture.completedFuture(null); } @Override public Position getLastMessageId() { throw new UnsupportedOperationException("getLastMessageId is not supported on non-persistent topic"); } public void markBatchMessagePublished() { this.hasBatchMessagePublished = true; } private static final Logger log = LoggerFactory.getLogger(NonPersistentTopic.class); @Override public CompletableFuture<SchemaVersion> addSchema(SchemaData schema) { if (schema == null) { return CompletableFuture.completedFuture(SchemaVersion.Empty); } String base = TopicName.get(getName()).getPartitionedTopicName(); String id = TopicName.get(base).getSchemaName(); return brokerService.pulsar() .getSchemaRegistryService() .putSchemaIfAbsent(id, schema); } @Override public CompletableFuture<Boolean> isSchemaCompatible(SchemaData schema) { String base = TopicName.get(getName()).getPartitionedTopicName(); String id = TopicName.get(base).getSchemaName(); return brokerService.pulsar() .getSchemaRegistryService() .isCompatibleWithLatestVersion(id, schema); } }
Avoid double executor on non-persistent topic send operation (#2351)
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentTopic.java
Avoid double executor on non-persistent topic send operation (#2351)
<ide><path>ulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentTopic.java <ide> <ide> @Override <ide> public void publishMessage(ByteBuf data, PublishContext callback) { <del> AtomicInteger msgDeliveryCount = new AtomicInteger(2); <add> callback.completed(null, 0L, 0L); <ide> ENTRIES_ADDED_COUNTER_UPDATER.incrementAndGet(this); <ide> <del> // retain data for sub/replication because io-thread will release actual payload <del> data.retain(2); <del> this.executor.executeOrdered(topic, SafeRun.safeRun(() -> { <del> subscriptions.forEach((name, subscription) -> { <del> ByteBuf duplicateBuffer = data.retainedDuplicate(); <del> Entry entry = create(0L, 0L, duplicateBuffer); <del> // entry internally retains data so, duplicateBuffer should be release here <del> duplicateBuffer.release(); <del> if (subscription.getDispatcher() != null) { <del> subscription.getDispatcher().sendMessages(Lists.newArrayList(entry)); <del> } else { <del> // it happens when subscription is created but dispatcher is not created as consumer is not added <del> // yet <del> entry.release(); <del> } <del> }); <del> data.release(); <del> if (msgDeliveryCount.decrementAndGet() == 0) { <del> callback.completed(null, 0L, 0L); <del> } <del> })); <del> <del> this.executor.executeOrdered(topic, SafeRun.safeRun(() -> { <add> subscriptions.forEach((name, subscription) -> { <add> ByteBuf duplicateBuffer = data.retainedDuplicate(); <add> Entry entry = create(0L, 0L, duplicateBuffer); <add> // entry internally retains data so, duplicateBuffer should be release here <add> duplicateBuffer.release(); <add> if (subscription.getDispatcher() != null) { <add> subscription.getDispatcher().sendMessages(Collections.singletonList(entry)); <add> } else { <add> // it happens when subscription is created but dispatcher is not created as consumer is not added <add> // yet <add> entry.release(); <add> } <add> }); <add> <add> if (!replicators.isEmpty()) { <ide> replicators.forEach((name, replicator) -> { <ide> ByteBuf duplicateBuffer = data.retainedDuplicate(); <ide> Entry entry = create(0L, 0L, duplicateBuffer); <ide> duplicateBuffer.release(); <ide> ((NonPersistentReplicator) replicator).sendMessage(entry); <ide> }); <del> data.release(); <del> if (msgDeliveryCount.decrementAndGet() == 0) { <del> callback.completed(null, 0L, 0L); <del> } <del> })); <add> } <ide> } <ide> <ide> @Override
Java
apache-2.0
97994d6a19cda1e991237e61174b4ea75d0f359f
0
Valkryst/VTerminal
package com.valkryst.AsciiPanel; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Paint; import lombok.Getter; public class AsciiString { /** The characters of the string. */ @Getter private AsciiCharacter[] characters; /** * Constructs a new AsciiString of the specified length with all characters set to ' '. * * @param length * The length to make the string. */ public AsciiString(final int length) { characters = new AsciiCharacter[length]; for (int i = 0; i < characters.length; i++) { characters[i] = new AsciiCharacter(' '); } } /** * Constructs a new AsciiString. * * @param string * The string. */ public AsciiString(final String string) { if (string == null) { characters = new AsciiCharacter[0]; } else { characters = new AsciiCharacter[string.length()]; for (int i = 0; i < characters.length; i++) { characters[i] = new AsciiCharacter(string.charAt(i)); } } } @Override public String toString() { final StringBuilder builder = new StringBuilder(); for (int i = 0 ; i < characters.length ; i++) { builder.append(characters[i].getCharacter()); } return builder.toString(); } @Override public boolean equals(final Object object) { if (object instanceof AsciiString == false) { return false; } final AsciiString otherString = (AsciiString) object; if (characters.length != otherString.getCharacters().length) { return false; } for (int i = 0 ; i < characters.length ; i++) { final AsciiCharacter thisChar = characters[i]; final AsciiCharacter otherChar = otherString.getCharacters()[i]; if (thisChar.equals(otherChar) == false) { return false; } } return true; } /** * Draws the characters of the string onto the specified context. * * @param gc * The context on which to draw. * * @param font * The font to draw with. * * @param rowIndex * The y-axis (row) coordinate where the characters are to be drawn. */ public void draw(final GraphicsContext gc, final AsciiFont font, final int rowIndex) { for (int columnIndex = 0 ; columnIndex < characters.length ; columnIndex++) { characters[columnIndex].draw(gc, font, columnIndex, rowIndex); } } /** * Replaces the character at the specified position with the specified character. * * @param columnIndex * The x-axis (column) coordinate of the character to be replaced. * * @param character * The new character. */ public void replaceCharacter(final int columnIndex, final AsciiCharacter character) { boolean canProceed = columnIndex >= 0; canProceed &= columnIndex < characters.length; canProceed &= character != null; if (canProceed) { characters[columnIndex] = character; } } /** * Sets all characters to either be hidden or visible. * * @param isHidden * Whether or not the characters are to be hidden. */ public void setHidden(final boolean isHidden) { for (final AsciiCharacter c : characters) { c.setHidden(isHidden); } } /** Swaps the background and foreground colors of every character. */ public void invertColors() { for (final AsciiCharacter c : characters) { c.invertColors(); } } /** * Sets the background color of all characters. * * @param color * The new background color. */ public void setBackgroundColor(final Paint color) { for (final AsciiCharacter c : characters) { c.setBackgroundColor(color); } } /** * Sets the foreground color of all characters. * * @param color * The new foreground color. */ public void setForegroundColor(final Paint color) { for (final AsciiCharacter c : characters) { c.setForegroundColor(color); } } }
src/com/valkryst/AsciiPanel/AsciiString.java
package com.valkryst.AsciiPanel; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Paint; import lombok.Getter; public class AsciiString { /** The characters of the string. */ @Getter private AsciiCharacter[] characters; /** * Constructs a new AsciiString of the specified length with all characters set to ' '. * * @param length * The length to make the string. */ public AsciiString(final int length) { characters = new AsciiCharacter[length]; for (int i = 0; i < characters.length; i++) { characters[i] = new AsciiCharacter(' '); } } /** * Constructs a new AsciiString. * * @param string * The string. */ public AsciiString(final String string) { if (string == null) { characters = new AsciiCharacter[0]; } else { characters = new AsciiCharacter[string.length()]; for (int i = 0; i < characters.length; i++) { characters[i] = new AsciiCharacter(string.charAt(i)); } } } @Override public String toString() { final StringBuilder builder = new StringBuilder(); for (int i = 0 ; i < characters.length ; i++) { builder.append(characters[i].getCharacter()); } return builder.toString(); } @Override public boolean equals(final Object object) { if (object instanceof AsciiString == false) { return false; } final AsciiString otherString = (AsciiString) object; if (characters.length != otherString.getCharacters().length) { return false; } for (int i = 0 ; i < characters.length ; i++) { final AsciiCharacter thisChar = characters[i]; final AsciiCharacter otherChar = otherString.getCharacters()[i]; if (thisChar.equals(otherChar) == false) { return false; } } return true; } /** * Draws the characters of the string onto the specified context. * * @param gc * The context on which to draw. * * @param font * The font to draw with. * * @param rowIndex * The y-axis (row) coordinate where the characters are to be drawn. */ public void draw(final GraphicsContext gc, final AsciiFont font, final int rowIndex) { for (int columnIndex = 0 ; columnIndex < characters.length ; columnIndex++) { characters[columnIndex].draw(gc, font, columnIndex, rowIndex); } } /** * Replaces the character at the specified position with the specified character. * * @param columnIndex * The x-axis (column) coordinate of the character to be replaced. * * @param character * The new character. */ public void replaceCharacter(final int columnIndex, final AsciiCharacter character) { boolean canProceed = columnIndex >= 0; canProceed &= columnIndex < characters.length; canProceed &= character != null; if (canProceed) { characters[columnIndex] = character; } } /** * Sets the background color of all characters to the specified color. * * @param color * The new background color. */ public void setBackgroundColor(final Paint color) { for (int i = 0 ; i < characters.length ; i++) { characters[i].setBackgroundColor(color); } } /** * Sets the foreground color of all characters to the specified color. * * @param color * The new foreground color. */ public void setForegroundColor(final Paint color) { for (int i = 0 ; i < characters.length ; i++) { characters[i].setForegroundColor(color); } } }
Added a way to set all characters of a string to visible or hidden.
src/com/valkryst/AsciiPanel/AsciiString.java
Added a way to set all characters of a string to visible or hidden.
<ide><path>rc/com/valkryst/AsciiPanel/AsciiString.java <ide> } <ide> <ide> /** <del> * Sets the background color of all characters to the specified color. <add> * Sets all characters to either be hidden or visible. <add> * <add> * @param isHidden <add> * Whether or not the characters are to be hidden. <add> */ <add> public void setHidden(final boolean isHidden) { <add> for (final AsciiCharacter c : characters) { <add> c.setHidden(isHidden); <add> } <add> } <add> <add> /** Swaps the background and foreground colors of every character. */ <add> public void invertColors() { <add> for (final AsciiCharacter c : characters) { <add> c.invertColors(); <add> } <add> } <add> <add> /** <add> * Sets the background color of all characters. <ide> * <ide> * @param color <ide> * The new background color. <ide> */ <ide> public void setBackgroundColor(final Paint color) { <del> for (int i = 0 ; i < characters.length ; i++) { <del> characters[i].setBackgroundColor(color); <add> for (final AsciiCharacter c : characters) { <add> c.setBackgroundColor(color); <ide> } <ide> } <ide> <ide> /** <del> * Sets the foreground color of all characters to the specified color. <add> * Sets the foreground color of all characters. <ide> * <ide> * @param color <ide> * The new foreground color. <ide> */ <ide> public void setForegroundColor(final Paint color) { <del> for (int i = 0 ; i < characters.length ; i++) { <del> characters[i].setForegroundColor(color); <add> for (final AsciiCharacter c : characters) { <add> c.setForegroundColor(color); <ide> } <ide> } <ide> }
Java
mit
8f9d41c181fadbd44866c9bd825efe9409862892
0
yang/sron,yang/sron,yang/sron,yang/sron
package edu.cmu.neuron2; import java.io.*; import java.net.*; import java.util.*; import java.lang.annotation.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.logging.*; import java.util.logging.Formatter; import java.nio.ByteBuffer; //import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.transport.socket.nio.DatagramAcceptor; import org.apache.mina.transport.socket.nio.DatagramAcceptorConfig; import edu.cmu.neuron2.RonTest.RunMode; class LabelFilter implements Filter { private final HashSet<String> suppressedLabels; private final boolean suppressAll; public LabelFilter(HashSet<String> suppressedLabels) { this.suppressedLabels = suppressedLabels; this.suppressAll = suppressedLabels.contains("all"); } public boolean isLoggable(LogRecord record) { if (suppressAll) return false; String[] parts = record.getLoggerName().split("\\.", 2); return parts.length == 1 || !suppressedLabels.contains(parts[1]); } } public class NeuRonNode extends Thread { private final Reactor scheduler; public short myNid; private final boolean isCoordinator; private final String coordinatorHost; private final int basePort; private final AtomicBoolean doQuit = new AtomicBoolean(); private Logger logger; /** * maps node id's to nodestates. this is the primary container. */ private final Hashtable<Short, NodeState> nodes = new Hashtable<Short, NodeState>(); /** * neighbors = rendesvousServers union rendezvousClients. we send our * routes to all servers in this set. */ /** * maps nid to {the set of rendezvous servers to that nid} */ private final Hashtable<Short, HashSet<NodeState>> rendezvousServers = new Hashtable<Short, HashSet<NodeState>>(); /** * the set of nodes that are relying us to get to someone. * * this is needed during route computation. i need to know who to calculate * routes among, and we want to include rendezvousclients in this set. */ private final SortedSet<NodeState> rendezvousClients = new TreeSet<NodeState>(); // These variables used internally to updateMembers (keep this way, for // abstraction purposes), and are only exposed for printGrid(). private NodeState[][] grid; private short numCols, numRows; // Coord-only: maps addresses to nids private final Hashtable<InetAddress, Short> addr2id = new Hashtable<InetAddress, Short>(); // Specific to this node. Lookup from destination to default rs's to it private final Hashtable<Short, HashSet<NodeState>> defaultRendezvousServers = new Hashtable<Short, HashSet<NodeState>>(); // Lookup from node to a set of its rendezvous servers private final Hashtable<NodeState, HashSet<NodeState>> nodeDefaultRSs = new Hashtable<NodeState, HashSet<NodeState>>(); private short currentStateVersion; public final int neighborBroadcastPeriod; public final int probePeriod; public final int gcPeriod; private final NodeInfo coordNode; private final RunMode mode; private final short numNodesHint; private final Runnable semAllJoined; private final Random rand = new Random(); private final InetAddress myCachedAddr; private ArrayList<Short> cachedMemberNids = new ArrayList<Short>(); // sorted list of members private short cachedMemberNidsVersion; private final boolean blockJoins; private final boolean capJoins; private final int joinRetries; // seconds private final boolean enableSubpings; private final int subpingPeriod; // seconds // number of intervals which we'll split the probing time into private int numProbeIntervals; private Set[] pingTable; private final Hashtable<NodeState, Integer> pingId = new Hashtable<NodeState, Integer>(); private final int dumpPeriod; private final FileHandler fh; private final short origNid; private final short sessionId; private final int linkTimeout; private final int membershipBroadcastPeriod; private static final String defaultLabelSet = "subprobe send.Ping recv.Ping stale.Ping send.Pong recv.Pong send.Subprobe recv.Subprobe stale.Pong send.Measurements send.RoutingRecs subprobe"; private final Hashtable<Short,Long> lastSentMbr = new Hashtable<Short,Long>(); private final double smoothingFactor; private final short resetLatency = Short.MAX_VALUE; private final DatagramAcceptor acceptor; private final Hashtable<Short, NodeInfo> coordNodes = new Hashtable<Short, NodeInfo>(); private final ArrayList<Short> memberNids = new ArrayList<Short>(); private final ArrayList<NodeState> otherNodes = new ArrayList<NodeState>(); private final ArrayList<NodeState> lastRendezvousServers = new ArrayList<NodeState>(); private final double directBonus, hysteresisBonus; private final long startTime = System.currentTimeMillis(); private final int pingDumpPeriod, pingDumpInitialDelay; private final Reactor reactor; private Runnable safeRun(final Runnable r) { return new Runnable() { public void run() { try { r.run(); } catch (Throwable ex) { err(ex); } } }; } private void createLabelFilter(Properties props, String labelSet, Handler handler) { String[] labels = props.getProperty(labelSet, defaultLabelSet).split(" "); final HashSet<String> suppressedLabels = new HashSet<String>(Arrays.asList(labels)); handler.setFilter(new LabelFilter(suppressedLabels)); } private final int joinDelay; public NeuRonNode(short id, Properties props, short numNodes, Runnable semJoined, InetAddress myAddr, String coordinatorHost, NodeInfo coordNode, DatagramAcceptor acceptor, Reactor reactor) { this.reactor = reactor; joinDelay = rand.nextInt(Integer.parseInt(props.getProperty("joinDelayRange", "1"))); if ((coordNode == null) || (coordNode.addr == null)){ throw new RuntimeException("coordNode is null!"); } dumpPeriod = Integer.parseInt(props.getProperty("dumpPeriod", "60")); myNid = id; origNid = id; cachedMemberNidsVersion = (short)-1; joinRetries = Integer.parseInt(props.getProperty("joinRetries", "10")); // wait up to 10 secs by default for coord to be available membershipBroadcastPeriod = Integer.parseInt(props.getProperty("membershipBroadcastPeriod", "0")); // NOTE note that you'll probably want to set this, always! sessionId = Short.parseShort(props.getProperty("sessionId", "0")); blockJoins = Boolean.valueOf(props.getProperty("blockJoins", "true")); capJoins = Boolean.valueOf(props.getProperty("capJoins", "true")); this.coordinatorHost = coordinatorHost; this.coordNode = coordNode; mode = RunMode.valueOf(props.getProperty("mode", "sim").toUpperCase()); basePort = coordNode.port; scheme = RoutingScheme.valueOf(props.getProperty("scheme", "SQRT").toUpperCase()); if (scheme == RoutingScheme.SQRT) { neighborBroadcastPeriod = Integer.parseInt(props.getProperty("neighborBroadcastPeriod", "15")); } else { neighborBroadcastPeriod = Integer.parseInt(props.getProperty("neighborBroadcastPeriod", "30")); } gcPeriod = Integer.parseInt(props.getProperty("gcPeriod", neighborBroadcastPeriod + "")); enableSubpings = Boolean.valueOf(props.getProperty("enableSubpings", "true")); this.acceptor = acceptor; // for simulations we can safely reduce the probing frequency, or even turn it off //if (mode == RunMode.SIM) { //probePeriod = Integer.parseInt(props.getProperty("probePeriod", "60")); //} else { probePeriod = Integer.parseInt(props.getProperty("probePeriod", "30")); //} subpingPeriod = Integer.parseInt(props.getProperty("subpingPeriod", "" + probePeriod)); membershipTimeout = Integer.parseInt(props.getProperty("timeout", "" + 30*60)); linkTimeout = Integer.parseInt(props.getProperty("failoverTimeout", "" + membershipTimeout)); pingDumpInitialDelay = Integer.parseInt(props.getProperty("pingDumpInitialDelay", "60")); pingDumpPeriod = Integer.parseInt(props.getProperty("pingDumpPeriod", "60")); // Events are when simulated latencies change; these are substituted in // for real measured latencies, and can be useful in simulation. These // events must be specified in time order! To remove any sim latency // for a dst, set it to resetLatency. String simEventsSpec = props.getProperty("simEvents", ""); if (!simEventsSpec.equals("")) { String[] events = simEventsSpec.split(";"); for (String e : events) { String[] parts = e.split(" "); int secs = Integer.parseInt(parts[0]); short oid = Short.parseShort(parts[1]); if (oid == myNid) { short dst = Short.parseShort(parts[2]); short lat = Short.parseShort(parts[3]); simEvents.addLast(new SimEvent(secs, oid, dst, lat)); } } } smoothingFactor = Double.parseDouble(props.getProperty("smoothingFactor", "0.1")); directBonus = Double.parseDouble(props.getProperty("directBonus", "1.05")); hysteresisBonus = Double.parseDouble(props.getProperty("hysteresisBonus", "1.05")); Formatter minfmt = new Formatter() { public String format(LogRecord record) { StringBuilder buf = new StringBuilder(); buf.append(record.getMillis()).append(' ')/*.append(new Date(record.getMillis())).append(" ").append( record.getLevel()).append(" ")*/.append( record.getLoggerName()).append(": ").append( record.getMessage()).append("\n"); return buf.toString(); } }; Formatter fmt = new Formatter() { public String format(LogRecord record) { StringBuilder buf = new StringBuilder(); buf.append(record.getMillis()).append(' ').append(new Date(record.getMillis())).append(" ").append( record.getLevel()).append(" ").append( record.getLoggerName()).append(": ").append( record.getMessage()).append("\n"); return buf.toString(); } }; Logger rootLogger = Logger.getLogger(""); rootLogger.getHandlers()[0].setFormatter(fmt); logger = Logger.getLogger("node" + myNid); createLabelFilter(props, "consoleLogFilter", rootLogger.getHandlers()[0]); try { String logFileBase = props.getProperty("logFileBase", "%t/scaleron-log-"); fh = new FileHandler(logFileBase + myNid, true); fh.setFormatter(fmt); createLabelFilter(props, "fileLogFilter", fh); logger.addHandler(fh); } catch (IOException ex) { throw new RuntimeException(ex); } this.scheduler = reactor; grid = null; numCols = numRows = 0; isCoordinator = myNid == 0; currentStateVersion = (short) (isCoordinator ? 0 : -1); numNodesHint = Short.parseShort(props.getProperty("numNodesHint", "" + numNodes)); semAllJoined = semJoined; if (myAddr == null) { try { myCachedAddr = InetAddress.getLocalHost(); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } } else { myCachedAddr = myAddr; } myPort = basePort + myNid; this.myAddr = new InetSocketAddress(myCachedAddr, myPort); clientTimeout = Integer.parseInt(props.getProperty("clientTimeout", "" + 3 * neighborBroadcastPeriod)); } private final int myPort; private final InetSocketAddress myAddr; private void handleInit(Init im) { if (im.id == -1) { throw new PlannedException("network is full; aborting"); } myNid = im.id; logger = Logger.getLogger("node_" + myNid); if (logger.getHandlers().length == 0) { logger.addHandler(fh); } currentStateVersion = im.version; log("got from coord => Init version " + im.version); updateMembers(im.members); } private String bytes2string(byte[] buf) { String s = "[ "; for (byte b : buf) { s += b + " "; } s += "]"; return s; } private void log(String msg) { logger.info(msg); } private void warn(String msg) { logger.warning(msg); } private void err(String msg) { logger.severe(msg); } public void err(Throwable ex) { StringWriter s = new StringWriter(); PrintWriter p = new PrintWriter(s); ex.printStackTrace(p); err(s.toString()); } /** * Used for logging data, such as neighbor lists. * * @param name - the name of the data, e.g.: "neighbors", "info" * @param value */ private void log(String name, Object value) { Logger.getLogger(logger.getName() + "." + name).info(value.toString()); } public static final class SimEvent { public int secs; public short oid, dst, lat; public SimEvent(int secs, short src, short dst, short lat) { this.secs = secs; this.oid = oid; this.dst = dst; this.lat = lat; } } public final ArrayDeque<SimEvent> simEvents = new ArrayDeque<SimEvent>(); public final ShortShortMap simLatencies = new ShortShortMap(resetLatency); public static final class PlannedException extends RuntimeException { public PlannedException(String msg) { super(msg); } } public final AtomicReference<Exception> failure = new AtomicReference<Exception>(); public void run() { try { run3(); } catch (PlannedException ex) { warn(ex.getMessage()); failure.set(ex); if (semAllJoined != null) semAllJoined.run(); } catch (Exception ex) { err(ex); failure.set(ex); if (semAllJoined != null) semAllJoined.run(); } } /** * Similar to fixed-rate scheduling, but doesn't try to make up multiple * overdue items, but rather allows us to skip over them. This should deal * better with PLab's overloaded hosts. * * @param r The runnable task. * @param initialDelay The initial delay in seconds. * @param period The period in seconds. */ private ScheduledFuture<?> safeSchedule(final Runnable r, long initialDelay, final long period) { final long bufferTime = 1000; // TODO parameterize return scheduler.schedule(new Runnable() { private long scheduledTime = -1; public void run() { if (scheduledTime < 0) scheduledTime = System.currentTimeMillis(); r.run(); long now = System.currentTimeMillis(); scheduledTime = Math.max(scheduledTime + period * 1000, now + bufferTime); scheduler.schedule(this, scheduledTime - now, TimeUnit.MILLISECONDS); } }, initialDelay, TimeUnit.SECONDS); } private ScheduledFuture<?> safeScheduleMs(final Callable<Integer> r, final int maxPoints, long initialDelay, final long period) { return scheduler.schedule(new Runnable() { private long scheduledTime = -1; public void run() { if (scheduledTime < 0) scheduledTime = System.currentTimeMillis(); int points = 0; while (true) { try { points += r.call(); } catch (Exception ex) { err(ex); } long now = System.currentTimeMillis(); scheduledTime = Math.max(scheduledTime + period, now); if (scheduledTime > now) { scheduler.schedule(this, scheduledTime - now, TimeUnit.MILLISECONDS); break; } if (points > maxPoints) { scheduler.schedule(this, now + period, TimeUnit.MILLISECONDS); break; } } } }, initialDelay, TimeUnit.MILLISECONDS); } private boolean hasJoined = false; private Session session = null; public void run3() { if (isCoordinator) { try { safeSchedule(safeRun(new Runnable() { public void run() { log("checkpoint: " + coordNodes.size() + " nodes"); printMembers(); //printGrid(); } }), dumpPeriod, dumpPeriod); if (false) { acceptor.bind(new InetSocketAddress(InetAddress .getLocalHost(), basePort), new CoordReceiver()); } else { final CoordHandler handler = new CoordHandler(); session = reactor.register(null, myAddr, handler); } } catch (Exception ex) { throw new RuntimeException(ex); } } else { try { if (false) { final Receiver receiver = new Receiver(); acceptor.bind(new InetSocketAddress(myCachedAddr, myPort), receiver); } else { final NodeHandler handler = new NodeHandler(); session = reactor.register(null, myAddr, handler); } log("server started on " + myCachedAddr + ":" + (basePort + myNid)); // Split up the probing period into many small intervals. In each // interval we will ping a small fraction of the nodes. numProbeIntervals = numNodesHint / 3; pingTable = new HashSet[numProbeIntervals]; for(int i=0; i<numProbeIntervals; i++) pingTable[i] = new HashSet(); int probeSubPeriod = (1000 * probePeriod) / numProbeIntervals; safeScheduleMs(new Callable<Integer>() { int pingIter = 0; public Integer call() { int points = 0; if (hasJoined) { points += pingAll(pingIter); pingIter = (pingIter + 1) % numProbeIntervals; } return 1; } }, 5, 1234, probeSubPeriod); safeSchedule(safeRun(new Runnable() { public void run() { if (hasJoined) { /* * path-finding and rendezvous finding is * interdependent. the fact that we do the path-finding * first before the rendezvous servers is arbitrary. */ // TODO the below can be decoupled. Actually, with the current bug, node.hop isn't // set and findPathsForAllNodes() doesn't actually do anything. Pair<Integer, Integer> p = findPathsForAllNodes(); log(p.first + " live nodes, " + p.second + " avg paths, " + nodes.get(myNid).latencies.keySet() .size() + " direct paths"); // TODO this can also be decoupled. However, we don't want too much time to pass // between calculating rendezvous servers and actually sending to them, since in // the mean time we will have received recommendations which hint at remote failures // etc. Also our notion of isReachable will have changed. For SIMPLE this is easy: // we can remove from the set any nodes that are no longer reachable. An ad-hoc // solution would be to run it just once and then check if the dst is reachable before // broadcasting. This might take longer in certain failure scenarios. // We can, before sending, check whether link is down or we received a more recent // measurement packing showing remote failure. If remote failure, we'd like to wait // anyway since dst might be down. Might be useless, but can still send measurements. // If link is down, just don't send anything. We'll try again in the next iteration. // SUMMARY: after constructing measRecips, put each destination onto the queue, // and if when popped !dst.isReachable, just don't send. ArrayList<NodeState> measRecips = scheme == RoutingScheme.SIMPLE ? getAllReachableNodes() : getAllRendezvousServers(); // TODO this can also be decoupled, and also split up // into intervals. We should keep the probeTable[] // in memory and always up to date. Further optimization // is to keep array of bytes, so no serialization. broadcastMeasurements(measRecips); // TODO this can also be decoupled. Don't use // getAllRendezvousClients(), just work directly with // the list. Order doesn't matter (confirm). // Also split calls to findHops into intervals. if (scheme != RoutingScheme.SIMPLE) { broadcastRecommendations(); } } } }), 7, neighborBroadcastPeriod); if (enableSubpings) { int subpingSubPeriod = (1000 * subpingPeriod) / numProbeIntervals; safeScheduleMs(new Callable<Integer>() { int pingIter = 0; public Integer call() { if(hasJoined) { subping(pingIter); pingIter = (pingIter + 1) % numProbeIntervals; } return 1; } }, 5, 5521, subpingSubPeriod); // TODO should these initial offsets be constants? } scheduler.scheduleWithFixedDelay(safeRun(new Runnable() { public void run() { log("received/sent " + pingpongCount + " pings/pongs " + pingpongBytes + " bytes"); log("received/sent " + subprobeCount + " subprobes " + subprobeBytes + " bytes"); } }), pingDumpInitialDelay, pingDumpPeriod, TimeUnit.SECONDS); final InetAddress coordAddr = InetAddress.getByName(coordinatorHost); scheduler.schedule(safeRun(new Runnable() { private int count = 0; public void run() { if (count > joinRetries) { warn("exceeded max tries!"); System.exit(0); } else if (!hasJoined) { log("sending join to coordinator at " + coordinatorHost + ":" + basePort + " (try " + count++ + ")"); Join msg = new Join(); msg.addr = myCachedAddr; msg.src = myNid; // informs coord of orig id msg.port = myPort; sendObject(msg, coordAddr, basePort, (short)-1); log("waiting for InitMsg"); scheduler.schedule(this, 10, TimeUnit.SECONDS); } } }), joinDelay, TimeUnit.SECONDS); if (semAllJoined != null) semAllJoined.run(); } catch (IOException ex) { throw new RuntimeException(ex); } } } private final HashSet<Short> ignored = new HashSet<Short>(); public synchronized void ignore(short nid) { if (nid != myNid) { log("ignoring " + nid); ignored.add(nid); } } public synchronized void unignore(short nid) { if (nid != myNid) { log("unignoring " + nid); ignored.remove(nid); } } private ArrayList<NodeState> getAllReachableNodes() { ArrayList<NodeState> nbrs = new ArrayList<NodeState>(); for (NodeState n : otherNodes) if (n.isReachable) nbrs.add(n); return nbrs; } private static final byte SUBPING = 0, SUBPING_FWD = 1, SUBPONG = 2, SUBPONG_FWD = 3; private Subprobe subprobe(InetSocketAddress nod, long time, byte type) { Subprobe p = new Subprobe(); p.src = myAddr; p.nod = nod; p.time = time; p.type = type; return p; } private int subping(int pingIter) { // We will only subping a fraction of the nodes at this iteration // Note: this synch. statement is redundant until we remove global lock List<Short> nids = new ArrayList<Short>(); int bytes = 0, initCount = subprobeCount; for (Object obj : pingTable[pingIter]) { NodeState dst = (NodeState) obj; // TODO: dst.hop almost always != 0 (except when dst is new node) if (dst.info.id != myNid && dst.hop != 0) { NodeState hop = nodes.get(dst.hop); long time = System.currentTimeMillis(); InetSocketAddress nod = new InetSocketAddress(dst.info.addr, dst.info.port); InetSocketAddress hopAddr = new InetSocketAddress( hop.info.addr, hop.info.port); bytes += sendObj(subprobe(nod, time, SUBPING), hopAddr); nids.add(dst.info.id); subprobeCount++; } } if (bytes > 0) { log("sent subpings " + bytes + " bytes, to " + nids); subprobeBytes += bytes; } return subprobeCount - initCount; } private final Serialization probeSer = new Serialization(); private int sendObj(Object o, InetSocketAddress dst) { try { // TODO investigate directly writing to ByteBuffer ByteArrayOutputStream baos = new ByteArrayOutputStream(); probeSer.serialize(o, new DataOutputStream(baos)); byte[] buf = baos.toByteArray(); session.send(ByteBuffer.wrap(buf), dst); return buf.length; } catch (Exception ex) { err(ex); return 0; } } private void handleSubping(Subprobe p) { if (myAddr.equals(p.nod)) { sendObj(subprobe(p.nod, p.time, SUBPONG_FWD), p.src); log("subprobe", "direct subpong from/to " + p.src); } else { // we also checked for p.src because eventually we'll need to // forward the subpong back too; if we don't know him, no point in // sending a subping sendObj(subprobe(p.src, p.time, SUBPING_FWD), p.nod); // log("subprobe", "subping fwd from " + p.src + " to " + p.nod); } } private void handleSubpingFwd(Subprobe p) { sendObj(subprobe(p.nod, p.time, SUBPONG), p.src); // log("subprobe", "subpong to " + p.nod + " via " + p.src); } private void handleSubpong(Subprobe p) { sendObj(subprobe(p.src, p.time, SUBPONG_FWD), p.nod); // log("subprobe", "subpong fwd from " + p.src + " to " + p.nod); } private final Hashtable<InetSocketAddress, NodeState> addr2node = new Hashtable<InetSocketAddress, NodeState>(); private int addr2nid(InetSocketAddress a) { return addr2node.get(a).info.id; } private void handleSubpongFwd(Subprobe p, long receiveTime) { long latency = (receiveTime - p.time) / 2; log("subpong from " + addr2nid(p.nod) + " via " + addr2nid(p.src) + ": " + latency + ", time " + p.time); } private int pingAll(int pingIter) { log("pinging"); // We will only ping a fraction of the nodes at this iteration // Note: this synch. statement is redundant until we remove global lock int initCount = pingpongCount; PeerPing ping = new PeerPing(); ping.time = System.currentTimeMillis(); ping.src = myAddr; for (Object node : pingTable[pingIter]) { NodeInfo info = ((NodeState) node).info; if (info.id != myNid) { pingpongCount++; pingpongBytes += sendObj(ping, new InetSocketAddress(info.addr, info.port)); } } /* * send ping to the membership server (co-ord) - this might not be * required if everone makes their own local decision. i.e. each node * notices that no other node can reach a node (say X), then each node * sends the co-ord a msg saying that "i think X is dead". The sending * of this msg can be staggered in time so that the co-ord is not * flooded with mesgs. The co-ordinator can then make a decision on * keeping or removing node Y from the membership. On seeing a * subsequent msg from the co-ord that X has been removed from the * overlay, if a node Y has not sent its "i think X is dead" msg, it can * cancel this event. */ // Only ping the coordinator once per ping interval (not per // subinterval) if (pingIter == 0) { Ping p = new Ping(); p.time = System.currentTimeMillis(); NodeInfo tmp = nodes.get(myNid).info; p.info = new NodeInfo(); p.info.id = origNid; // note that the ping info uses the // original id p.info.addr = tmp.addr; p.info.port = tmp.port; pingpongCount++; pingpongBytes += sendObject(p, (short) 0); } // log("sent pings, " + totalSize + " bytes"); return pingpongCount - initCount; } private Object deserialize(ByteBuffer buf) { byte[] bytes = new byte[buf.limit()]; buf.get(bytes); try { return new Serialization().deserialize(new DataInputStream(new ByteArrayInputStream(bytes))); } catch (Exception ex) { err(ex); return null; } } private Hashtable<Short,Short> id2oid = new Hashtable<Short,Short>(); private Hashtable<Short,String> id2name = new Hashtable<Short,String>(); /** * coordinator's msg handling loop */ public final class CoordHandler implements ReactorHandler { /** * Generates non-repeating random sequence of short IDs, and keeps * track of how many are emitted. */ public final class IdGenerator { private final Iterator<Short> iter; private short counter; public IdGenerator() { List<Short> list = new ArrayList<Short>(); for (short s = 1; s < Short.MAX_VALUE; s++) { list.add(s); } Collections.shuffle(list); iter = list.iterator(); } public short next() { counter++; return iter.next(); } public short count() { return counter; } } private IdGenerator nidGen = new IdGenerator(); private void sendInit(short nid, Join join) { Init im = new Init(); im.id = nid; im.members = getMemberInfos(); sendObject(im, join.addr, join.port, (short)-1); } @Override public void handle(Session session, InetSocketAddress src, java.nio.ByteBuffer buf) { try { Msg msg = (Msg) deserialize(buf); if (msg == null) return; if (msg.session == sessionId) { if (msg instanceof Join) { final Join join = (Join) msg ; if (id2oid.values().contains(msg.src)) { // we already added this guy; just resend him the init msg sendInit(addr2id.get(join.addr), join); } else { // need to add this guy and send him the init msg (if there's space) if (!capJoins || coordNodes.size() < numNodesHint) { short newNid = nidGen.next(); addMember(newNid, join.addr, join.port, join.src); if (blockJoins) { if (coordNodes.size() >= numNodesHint) { // time to broadcast ims to everyone ArrayList<NodeInfo> memberList = getMemberInfos(); for (NodeInfo m : memberList) { Init im = new Init(); im.id = m.id; im.members = memberList; sendObject(im, m); } } } else { sendInit(newNid, join); broadcastMembershipChange(newNid); } if (coordNodes.size() == numNodesHint) { semAllJoined.run(); } } else if (capJoins && coordNodes.size() == numNodesHint) { Init im = new Init(); im.id = -1; im.members = new ArrayList<NodeInfo>(); sendObject(im, join.addr, join.port, (short)-1); } } } else if (coordNodes.containsKey(msg.src)) { log("recv." + msg.getClass().getSimpleName(), "from " + msg.src + " (oid " + id2oid.get(msg.src) + ", " + id2name.get(msg.src) + ")"); resetTimeoutAtCoord(msg.src); if (msg.version < currentStateVersion) { // this includes joins log("updating stale membership"); sendMembership(msg.src); } else if (msg instanceof Ping) { // ignore the ping } else { throw new Exception("can't handle message type here: " + msg.getClass().getName()); } } else { if ((!capJoins || coordNodes.size() < numNodesHint) && msg instanceof Ping) { Ping ping = (Ping) msg; log("dead." + ping.getClass().getSimpleName(), "from '" + ping.src + "' " + ping.info.addr.getHostName()); Short mappedId = addr2id.get(ping.info.addr); short nid; if (mappedId == null) { nid = nidGen.next(); addMember(nid, ping.info.addr, ping.info.port, ping.info.id); broadcastMembershipChange(nid); } else { nid = mappedId; } Init im = new Init(); im.id = nid; im.src = myNid; im.version = currentStateVersion; im.members = getMemberInfos(); sendObject(im, nid); } else { log("dead." + msg.getClass().getSimpleName(), "from '" + msg.src + "'"); } } } } catch (Exception ex) { err(ex); } } } /** * coordinator's msg handling loop */ public final class CoordReceiver extends IoHandlerAdapter { @Override public void messageReceived(IoSession session, Object obj) throws Exception { assert false; } } private int pingpongCount, pingpongBytes, subprobeCount, subprobeBytes; public final class NodeHandler implements ReactorHandler { public short getSimLatency(short nid) { long time = System.currentTimeMillis(); for (SimEvent e : simEvents) { if (time - startTime >= e.secs * 1000) { // make this event happen simLatencies.put(e.dst, e.lat); } } return simLatencies.get(nid); } @Override public void handle(Session session, InetSocketAddress src, ByteBuffer buf) { try { // TODO check SimpleMsg.session Object obj = deserialize(buf); if (obj == null) return; long receiveTime; if (obj instanceof Subprobe) { Subprobe p = (Subprobe) obj; subprobeBytes += buf.limit(); subprobeCount += 2; switch (p.type) { case SUBPING: handleSubping(p); break; case SUBPING_FWD: handleSubpingFwd(p); break; case SUBPONG: handleSubpong(p); break; case SUBPONG_FWD: // TODO move into the new worker thread when it's here receiveTime = System.currentTimeMillis(); handleSubpongFwd(p, receiveTime); break; default: assert false; } return; // TODO early exit is unclean } else if (obj instanceof PeerPing) { PeerPing ping = ((PeerPing) obj); PeerPong pong = new PeerPong(); pong.time = ping.time; pong.src = myAddr; pingpongBytes += sendObj(pong, ping.src) + buf.limit(); pingpongCount += 2; return; // TODO early exit is unclean } else if (obj instanceof PeerPong) { PeerPong pong = (PeerPong) obj; long rawRtt = System.currentTimeMillis() - pong.time; if (mode == RunMode.SIM) { short l = getSimLatency(addr2node.get(pong.src).info.id); if (l < resetLatency) { rawRtt = 2 * l; } } NodeState state = addr2node.get(pong.src); // if the rtt was astronomical, just treat it as a dropped packet if (rawRtt / 2 < Short.MAX_VALUE) { // we define "latency" as rtt/2; this should be // a bigger point near the top of this file short latency = (short) (rawRtt / 2); short nid = state.info.id; if (state != null) { resetTimeoutAtNode(nid); NodeState self = nodes.get(myNid); short oldLatency = self.latencies.get(nid); final short ewma; if (oldLatency == resetLatency) { ewma = latency; } else { ewma = (short) (smoothingFactor * latency + (1 - smoothingFactor) * oldLatency); } log("latency", state + " = " + latency + ", ewma " + ewma + ", time " + pong.time); self.latencies.put(nid, ewma); } else { log("latency", "some " + nid + " = " + latency); } pingpongCount++; pingpongBytes += buf.limit(); } return; // TODO early exit is unclean } Msg msg = (Msg) obj; if ((msg.src == 0 || nodes.containsKey(msg.src) || msg instanceof Ping) && msg.session == sessionId) { NodeState state = nodes.get(msg.src); log("recv." + msg.getClass().getSimpleName(), "from " + msg.src + " len " + ((ByteBuffer) buf).limit()); // for other messages, make sure their state version is // the same as ours if (msg.version > currentStateVersion) { if (msg instanceof Membership && hasJoined) { currentStateVersion = msg.version; Membership m = (Membership) msg; assert myNid == m.yourId; updateMembers(m.members); } else if (msg instanceof Init) { hasJoined = true; if (semAllJoined != null) semAllJoined.run(); if (((Init) msg).id == -1) session.close(); handleInit((Init) msg); } else { // i am out of date - wait until i am updated } } else if (msg.version == currentStateVersion) { // from coordinator if (msg instanceof Membership) { Membership m = (Membership) msg; assert myNid == m.yourId; updateMembers(m.members); } else if (msg instanceof Measurements) { resetTimeoutOnRendezvousClient(msg.src); updateMeasurements((Measurements) msg); } else if (msg instanceof RoutingRecs) { RoutingRecs recs = (RoutingRecs) msg; handleRecommendations(recs); log("got recs " + routesToString(recs.recs)); } else if (msg instanceof Ping || msg instanceof Pong || msg instanceof Init) { // nothing to do, already handled above } else { throw new Exception("can't handle that message type"); } } else { log("stale." + msg.getClass().getSimpleName(), "from " + msg.src + " version " + msg.version + " current " + currentStateVersion); } } else { // log("ignored." + msg.getClass().getSimpleName(), "ignored from " + msg.src + " session " + msg.session); } } catch (Exception ex) { err(ex); } } } /** * receiver's msg handling loop */ public final class Receiver extends IoHandlerAdapter { @Override public void messageReceived(IoSession session, Object buf) throws Exception { assert false; } } /** * If we don't hear from a node for this number of seconds, then consider * them dead. */ private int membershipTimeout; private Hashtable<Short, ScheduledFuture<?>> timeouts = new Hashtable<Short, ScheduledFuture<?>>(); /** * a coord-only method * * @param nid */ private void resetTimeoutAtCoord(final short nid) { if (coordNodes.containsKey(nid)) { ScheduledFuture<?> oldFuture = timeouts.get(nid); if (oldFuture != null) { oldFuture.cancel(false); } ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { removeMember(nid); } }), membershipTimeout, TimeUnit.SECONDS); timeouts.put(nid, future); } } private final int clientTimeout; private final Hashtable<Short, ScheduledFuture<?>> rendezvousClientTimeouts = new Hashtable<Short, ScheduledFuture<?>>(); private void resetTimeoutOnRendezvousClient(final short nid) { final NodeState node = nodes.get(nid); // TODO: wrong semantics for isReachable if (!node.isReachable) return; ScheduledFuture<?> oldFuture = rendezvousClientTimeouts.get(nid); if (oldFuture != null) { oldFuture.cancel(false); } if (rendezvousClients.add(node)) { log("rendezvous client " + node + " added"); } ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { if (rendezvousClients.remove(node)) { log("rendezvous client " + node + " removed"); } } }), clientTimeout, TimeUnit.SECONDS); rendezvousClientTimeouts.put(nid, future); } private void resetTimeoutAtNode(final short nid) { if (nodes.containsKey(nid)) { ScheduledFuture<?> oldFuture = timeouts.get(nid); if (oldFuture != null) { oldFuture.cancel(false); } final NodeState node = nodes.get(nid); if (!node.isReachable) { log(nid + " reachable"); if (node.hop == 0) { node.isHopRecommended = false; node.cameUp = true; node.hop = nid; } } node.isReachable = true; node.isDead = false; ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { if (nodes.containsKey(nid)) { log(nid + " unreachable"); node.isReachable = false; nodes.get(myNid).latencies.remove(nid); // TODO: do we really want this? rendezvousClients.remove(node); findPaths(node, false); } } }), linkTimeout, TimeUnit.SECONDS); timeouts.put(nid, future); } } /** * a coordinator-only method */ private NodeInfo addMember(short newNid, InetAddress addr, int port, short origId) { NodeInfo info = new NodeInfo(); info.id = newNid; info.addr = addr; info.port = port; coordNodes.put(newNid, info); id2oid.put(newNid, origId); id2name.put(newNid, addr.getHostName()); addr2id.put(addr, newNid); log("adding new node: " + newNid + " oid " + origId + " name " + id2name.get(newNid)); currentStateVersion++; resetTimeoutAtCoord(newNid); return info; } private final AtomicBoolean membersChanged = new AtomicBoolean(); /** * a coordinator-only method * * @param exceptNid - if this is 0, then we must have been called by the * periodic membership-broadcast daemon thread, so actually send stuff; * otherwise, we should just signal to the daemon thread a pending change */ private void broadcastMembershipChange(short exceptNid) { if (exceptNid == 0 || membershipBroadcastPeriod == 0) { for (short nid : coordNodes.keySet()) { if (nid != exceptNid) { sendMembership(nid); } } } } ArrayList<NodeInfo> getMemberInfos() { return new ArrayList<NodeInfo>(coordNodes.values()); } /** * a coordinator-only method * * throttles these messages so they're sent at most once per second */ private void sendMembership(short nid) { Membership msg = new Membership(); msg.yourId = nid; msg.members = getMemberInfos(); sendObject(msg, coordNodes.get(nid)); } /** * a coordinator-only method * * NOTE: there is a hack workaround here for sim mode, because addr2id is * not storing unique host:port combos, only unique hosts. * * @param nid */ private void removeMember(short nid) { log("removing dead node " + nid + " oid " + id2oid.get(nid) + " " + id2name.get(nid)); id2oid.remove(nid); NodeInfo info = coordNodes.remove(nid); Short mid = addr2id.remove(info.addr); if (mode != RunMode.SIM) assert mid != null; currentStateVersion++; broadcastMembershipChange(nid); } /** * updates our member state. modifies data structures as necessary to * maintain invariants. * * @param newNodes */ private void updateMembers(List<NodeInfo> newNodes) { HashSet<Short> newNids = new HashSet<Short>(); for (NodeInfo node : newNodes) newNids.add(node.id); // add new nodes for (NodeInfo node : newNodes) if (!nodes.containsKey(node.id)) { NodeState newNode = new NodeState(node); // Choose a subinterval for this node during which we will ping it int loc = rand.nextInt(numProbeIntervals); pingTable[loc].add(newNode); pingId.put(newNode, loc); nodes.put(node.id, newNode); addr2node.put(new InetSocketAddress(node.addr, node.port), newNode); if (node.id != myNid) resetTimeoutAtNode(node.id); } // Remove nodes. We need toRemove to avoid // ConcurrentModificationException on the table that we'd be looping // through. for (NodeInfo node : newNodes) newNids.add(node.id); HashSet<Pair<Short, NodeState>> toRemove = new HashSet<Pair<Short,NodeState>>(); for (Map.Entry<Short, NodeState> entry : nodes.entrySet()) if (!newNids.contains(entry.getKey())) toRemove.add(Pair.of(entry.getKey(), entry.getValue())); for (Pair<Short, NodeState> pair : toRemove) { short nid = pair.first; NodeState node = pair.second; // Remove the node from the subinterval during which it // was pinged. int index = pingId.remove(node); pingTable[index].remove(node); addr2node.remove(new InetSocketAddress(node.info.addr, node.info.port)); NodeState n = nodes.remove(nid); assert n != null; } // consistency cleanups: check that all nid references are still valid nid's for (NodeState state : nodes.values()) { if (state.hop != 0 && !newNids.contains(state.hop)) { state.hop = state.info.id; state.isHopRecommended = false; } for (Iterator<Short> i = state.hopOptions.iterator(); i.hasNext();) if (!newNids.contains(i.next())) i.remove(); HashSet<Short> garbage = new HashSet<Short>(); for (short nid : state.latencies.keySet()) if (!newNids.contains(nid)) garbage.add(nid); for (short nid : garbage) state.latencies.remove(nid); // Clear the remote failures hash, since this node will now have a different // set of default rendezvous nodes. state.remoteFailures.clear(); } // // regenerate alternative views of this data // NodeState self = nodes.get(myNid); assert self != null; memberNids.clear(); memberNids.addAll(newNids); Collections.sort(memberNids); otherNodes.clear(); otherNodes.addAll(nodes.values()); otherNodes.remove(self); // ABOVE IS INDEPENDENT OF GRID // numRows needs to be >= numCols numRows = (short) Math.ceil(Math.sqrt(nodes.size())); numCols = (short) Math.ceil((double) nodes.size() / (double) numCols); grid = new NodeState[numRows][numCols]; // These are used temporarily for setting up the defaults Hashtable<NodeState, Short> gridRow = new Hashtable<NodeState, Short>(); Hashtable<NodeState, Short> gridColumn = new Hashtable<NodeState, Short>(); List<Short> nids = memberNids; short i = 0; // node counter short numberOfNodes = (short) memberNids.size(); short lastColUsed = (short) (numCols - 1); // default is for the full grid gridLoop: for (short r = 0; r < numRows; r++) { for (short c = 0; c < numCols; c++) { // Are there any more nodes to put into the grid? if(i > numberOfNodes - 1) { // Assert: We shouldn't create a grid with an empty last row. assert (r == numRows - 1) && (c > 0); lastColUsed = (short) (c - 1); break gridLoop; } grid[r][c] = nodes.get(nids.get(i++)); gridRow.put(grid[r][c], r); gridColumn.put(grid[r][c], c); } } // Algorithm described in model_choices.tex // Set up hash of each node's default rendezvous servers // Note: a node's default rendezvous servers will include itself. nodeDefaultRSs.clear(); for(NodeState node : nodes.values()) { int rn = gridRow.get(node); int cn = gridColumn.get(node); // We know the number of elements. Should be [1/(default load factor)]*size HashSet<NodeState> nodeDefaults = new HashSet<NodeState>((int) 1.4*(numRows + numCols - 1)); // If this is not the last row if(rn < numRows - 1) { // Add the whole row for (int c1 = 0; c1 < numCols; c1++) nodeDefaults.add(grid[rn][c1]); // If this is before the last col used (on last row) if(cn <= lastColUsed) { // Add whole column for (int r1 = 0; r1 < numRows; r1++) nodeDefaults.add(grid[r1][cn]); } else { // Add column up until last row for (int r1 = 0; r1 < numRows-1; r1++) nodeDefaults.add(grid[r1][cn]); // Add corresponding node from the last row (column rn); // only for the first lastColUsed rows. if(rn <= lastColUsed) { nodeDefaults.add(grid[numRows-1][rn]); } } } else { // This is the last row // Add whole column for (int r1 = 0; r1 < numRows; r1++) nodeDefaults.add(grid[r1][cn]); // Add whole last row up till lastColUsed for (int c1 = 0; c1 <= lastColUsed; c1++) nodeDefaults.add(grid[rn][c1]); // Add row cn for columns > lastColUsed for (int c1 = lastColUsed+1; c1 < numCols; c1++) nodeDefaults.add(grid[cn][c1]); } // Could also make an array of nodeDefaults, for less memory usage/faster nodeDefaultRSs.put(node, nodeDefaults); } // BELOW IS INDEPENDENT OF GRID /* * simply forget about all our neighbors. thus, this forgets all our * failover clients and servers. since the grid is different. if this * somehow disrupts route computation, so be it - it'll only last for a * period. * * one worry is that others who miss this member update will continue to * broadcast to us. this is a non-issue because we ignore stale * messages, and when they do become updated, they'll forget about us * too. */ // Set up rendezvous clients rendezvousClients.clear(); for (NodeState cli : nodeDefaultRSs.get(self)) { // TODO: wrong semantics for isReachable if (cli.isReachable && cli != self) rendezvousClients.add(cli); } // Put timeouts for all new rendezvous clients. If they can never // reach us, we should stop sending them recommendations. for (final NodeState clientNode : rendezvousClients) { ScheduledFuture<?> oldFuture = rendezvousClientTimeouts.get(clientNode.info.id); if (oldFuture != null) { oldFuture.cancel(false); } ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { if (rendezvousClients.remove(clientNode)) { log("rendezvous client " + clientNode + " removed"); } } }), clientTimeout, TimeUnit.SECONDS); rendezvousClientTimeouts.put(clientNode.info.id, future); } // Set up default rendezvous servers to all destinations // Note: In an earlier version of the code, for a destination in // our row/col, we did not add rendezvous nodes which are not // reachable. We no longer do this (but it shouldn't matter). defaultRendezvousServers.clear(); for (NodeState dst : nodes.values()) { // note: including self HashSet<NodeState> rs = new HashSet<NodeState>(); defaultRendezvousServers.put(dst.info.id, rs); // Take intersection of this node's default rendezvous and // the dst's default rendezvous servers, excluding self. // Running time for outer loop is 2n^{1.5} since we are using // a HashSet for quick lookups. Could be optimized further, // but code simplicity is preferred. HashSet<NodeState> dstDefaults = nodeDefaultRSs.get(dst); for (NodeState selfRS : nodeDefaultRSs.get(self)) { // Don't add self because we will never receive routing // recommendation messages from ourselves. if (selfRS != self && dstDefaults.contains(selfRS)) rs.add(selfRS); } } // Create empty set for default rendezvous servers, will be filled in // getAllRendezvousServers() rendezvousServers.clear(); for (Entry<Short, HashSet<NodeState>> entry : defaultRendezvousServers.entrySet()) { rendezvousServers.put(entry.getKey(), new HashSet<NodeState>()); } lastRendezvousServers.clear(); log("state " + currentStateVersion + ", mbrs " + nids); } /** * @param n * @param remoteNid * @return */ private boolean isFailedRendezvous(NodeState n, NodeState remote) { // TODO: isReachable semantics should be fixed (but how?) // NOTE: We may never receive this node's measurements since // it is our rendezvous client, but we don't offer to be // its rendezvous server. This is why we check for // remote in the recommendations response rather than // the measurements. // This assumes that the node's reachability is indicative // of its ability to send us recommendation messages. return !n.isReachable || n.remoteFailures.contains(remote); } /** * @return failoverClients `union` nodes in my row and col (wherever i occur) */ private ArrayList<NodeState> getAllRendezvousClients() { ArrayList<NodeState> list = new ArrayList<NodeState>(rendezvousClients); Collections.sort(list); return list; } private String mkString(HashSet<NodeState> ns, String glue) { String s = ""; for (NodeState n : ns) { s += n.info.id + glue; } return s; } /** * makes one pass over the metaset of all rendezvous servers, removing any * failed rendezvous from the individual sets. * * for the simple routing scheme, this is the full set of nodes. as a * result, measurements are broadcast to everyone, as intended. (note that * there are no routing recommendation messages in this scheme.) * * OLD ALGO * * for dst * if dst is not down * rs = dst's current rendezvous servers * ds = dst's default rendezvous servers * if any of ds are working to dst and rs is not ds * rs = working subset of ds * if rs = [] * rs += random node from dst's row/col * else * rs -= any failed rs * note that this may leave rs empty for the coming round * this is what we want bc it will delay failover-finding till the next round * * NEW ALGO * * // CHANGES START * build a hashtable for all rendezvous nodes currently used * call this F * // CHANGES END * for dst * if dst is not down * rs = dst's current rendezvous servers * ds = dst's default rendezvous servers * if any of ds are working to dst and rs is not ds * rs = working subset of ds * if rs = [] * // CHANGES START * for active failover in dst's default rendezvous nodes (according to F) * if failover works to dst, choose it as failover for dst as well * choose rand node from dst's default rendezvous nodes that is not currently in use * rs += whatever we chose; F += whatever we chose * // CHANGES END * else * rs -= any failed rs * note that this may leave rs empty for the coming round * this is what we want bc it will delay failover-finding till the next round * * @return the union of all the sets of non-failed rendezvous servers. */ private ArrayList<NodeState> getAllRendezvousServers() { NodeState self = nodes.get(myNid); HashSet<NodeState> currentRSs = new HashSet<NodeState>(); HashSet<NodeState> allDefaults = nodeDefaultRSs.get(self); // first, prepare currentRS so that we can share/reuse // rendezvous servers for (NodeState node : otherNodes) { for (NodeState n : rendezvousServers.get(node.info.id)) { // if this is an actual failover if (!allDefaults.contains(n)) currentRSs.add(n); } } // these are the rendezvous servers that we want to sent our // measurements to HashSet<NodeState> servers = new HashSet<NodeState>(); // iterate over all destination nodes that are not us for (NodeState dst : otherNodes) { if (!dst.isDead) { // this is our current (active) set of rendezvous servers HashSet<NodeState> rs = rendezvousServers.get(dst.info.id); // check if any of our default rendezvous servers are once // more available; if so, add them back HashSet<NodeState> defaults = defaultRendezvousServers.get(dst.info.id); // we always want to try talking to our default rendezvous // servers if we think they're reachable for (NodeState r : defaults) if (r.isReachable) servers.add(r); // rs consists of either default rendezvous servers or // non-default rendezvous, but never a mix of both; test // which type it is boolean hasDefaultsOnly = rs.isEmpty() ? true : defaults.contains(rs.iterator().next()); // the following code attempts to add default rendezvous // servers back into rs HashSet<NodeState> old = new HashSet<NodeState>(rs); if (hasDefaultsOnly) { // if any default rendezvous servers are in use, then // don't clear rs; simply add any more default servers // that are working if (!defaults.equals(rs)) for (NodeState r : defaults) if (!isFailedRendezvous(r, dst)) rs.add(r); } else { // if no default rendezvous servers are in use, then // try adding any that are working; if any are working, // we make sure to first clear rs boolean cleared = false; for (NodeState r : defaults) { if (!isFailedRendezvous(r, dst)) { if (!cleared) { rs.clear(); cleared = true; } rs.add(r); } } } if (!old.equals(rs)) { log("restored rendezvous server for " + dst + " from " + old + " to " + rs); } // Note that rs not being empty means that in previous iterations the nodes in // rs were alive, and either we did not ever receive any recommendations from them, // or the last recommendation we received from it did include routing information // for dst (and so there is no hint of a remote failure). In either case, as of // the previous iteration, n.remoteFailures.contains(remote) == false. // if { any node in rs has n.remoteFailures.contains(remote) == true, then we know that we // did receive a routing recommendation from it since the last round, and it is alive. // Remove it from rs and do nothing else this step, as the destination is likely dead. // set skipIteration=true. } // else { // If !n.isReachable for any node n in rs, remove it from rs. We don't expect it to be // helpful for routing ever. // If rs is now empty, choose a failover rendezvous node (in this iteration) // Else, any remaining nodes have n.remoteFailures.contains(remote) == false, which means // either that we did not yet receive a routing message from it, or we did and the dst // is reachable. In either case, do nothing. If this node is still alive, we will // eventually receive a routing recommendation from it. Otherwise, very soon we will find // that !n.isReachable. We add a bit of latency for waiting, but should be okay. // } /* * If we think a remote failure could have occured, don't immediately look * for failovers. The next period, we will have received link states from * our neighbors, from which we can determine whether dst is just down. * * The reason for this is that if a node fails, we don't want the entire network to flood * the row/col of that downed node (no need for failovers period). */ boolean skipIteration = false; // We use the iterator so that we can safely remove from the set for (Iterator<NodeState> i = rs.iterator(); i.hasNext();) { NodeState r = i.next(); if(r.remoteFailures.contains(dst)) { i.remove(); skipIteration = true; } else if(!r.isReachable) { i.remove(); } } if (!skipIteration && rs.isEmpty() && scheme != RoutingScheme.SQRT_NOFAILOVER) { // create debug string String s = "defaults"; for (NodeState r : defaults) { s += " " + r.info.id + ( !r.isReachable ? " unreachable" : " <-/-> " + mkString(r.remoteFailures, ",") ); } final String report = s; // look for failovers HashSet<NodeState> cands = new HashSet<NodeState>(); // first, start by looking at the failovers that are // currently in use which are default rs's for this dst, so // that we can share when possible. that is, if we know that a // failover works for a destination, keep using it. HashSet<NodeState> dstDefault = nodeDefaultRSs.get(dst); // currentRSs may contain rendezvous nodes which are no longer alive // or useful for reaching the destination for(NodeState f : currentRSs) { if (dstDefault.contains(f) && !isFailedRendezvous(f, dst)) { cands.add(f); } } if (cands.isEmpty()) { // only once we have determined that no current // failover works for us do we go ahead and randomly // select a new failover. this is a blind choice; // we don't have these node's routing recommendations, // so we could not hope to do better. // TODO (low priority): one exception is if any of the candidates // are rendezvous clients for us, in which case we // will have received their link state, and we could // smartly decide whether they can reach the destination. // Not obvious if we should (or how) take advantage of this. for(NodeState cand : dstDefault) { if (cand != self && cand.isReachable) cands.add(cand); } } // if any of the candidates are already selected to be in // 'servers', we want to make sure that we only choose from // these choices. HashSet<NodeState> candsInServers = new HashSet<NodeState>(); for (NodeState cand : cands) if (servers.contains(cand)) candsInServers.add(cand); // choose candidate uniformly at random ArrayList<NodeState> candsList = new ArrayList<NodeState>(candsInServers.isEmpty() ? cands : candsInServers); if (candsList.size() == 0) { log("no failover candidates! giving up; " + report); } else { NodeState failover = candsList.get(rand.nextInt(candsList.size())); // TODO (low priority): prev rs = ... is now broken since rs is empty log("new failover for " + dst + ": " + failover + ", prev rs = " + rs + "; " + report); rs.add(failover); // share this failover in this routing iteration too if (!allDefaults.contains(failover)) { currentRSs.add(failover); } } } else if (rs.isEmpty()) { log("all rs to " + dst + " failed"); System.out.println("ALL FAILED!"); } // Add any nodes that are in rs to the servers set for (NodeState r : rs) { servers.add(r); } } // end if dst.hop != 0 (destination is alive) } // end while loop over destinations ArrayList<NodeState> list = new ArrayList<NodeState>(servers); Collections.sort(list); return list; } public static enum RoutingScheme { SIMPLE, SQRT, SQRT_NOFAILOVER, SQRT_RC_FAILOVER, SQRT_SPECIAL }; private final RoutingScheme scheme; private void printMembers() { String s = "members:"; for (NodeInfo info : coordNodes.values()) { s += "\n " + info.id + " oid " + id2oid.get(info.id) + " " + id2name.get(info.id) + " " + info.port; } log(s); } // PERF private void printGrid() { String s = "grid:"; if (grid != null) { for (int i = 0; i < numRows; i++) { s += "\n "; for (int j = 0; j < numCols; j++) { s += "\t" + grid[i][j]; } } } log(s); } /** * in the sqrt routing scheme: for each neighbor, find for him the min-cost * hops to all other neighbors, and send this info to him (the intermediate * node may be one of the endpoints, meaning a direct route is cheapest). * * in the sqrt_special routing scheme, we instead find for each neighbor the * best intermediate other neighbor through which to route to every * destination. this still needs work, see various todos. * * a failed rendezvous wrt some node n is one which we cannot reach * (proximal failure) or which cannot reach n (remote failure). when all * current rendezvous to some node n fail, then we find a failover from node * n's row and col, and include it in our neighbor set. by befault, this * situation occurs when a row-col rendezvous pair fail. it can also occur * with any of our current failovers. */ private void broadcastRecommendations() { ArrayList<NodeState> clients = getAllRendezvousClients(); ArrayList<NodeState> dsts = new ArrayList<NodeState>(clients); dsts.add(nodes.get(myNid)); Collections.sort(dsts); int totalSize = 0; for (NodeState src : clients) { ArrayList<Rec> recs = new ArrayList<Rec>(); // dst <- nbrs, hop <- any findHops(dsts, memberNids, src, recs); /* * TODO: need to additionally send back info about *how good* the * best hop is, so that the receiver can decide which of the many * recommendations to accept */ if (scheme == RoutingScheme.SQRT_SPECIAL) { // dst <- any, hop <- nbrs findHopsAlt(memberNids, dsts, src, recs); } RoutingRecs msg = new RoutingRecs(); msg.recs = recs; totalSize += sendObject(msg, src.info.id); } log("sent recs, " + totalSize + " bytes, to " + clients); } /** * Given the src, find for each dst in dsts the ideal hop from hops, * storing these into recs. This may choose the dst itself as the hop. */ private void findHops(ArrayList<NodeState> dsts, ArrayList<Short> hops, NodeState src, ArrayList<Rec> recs) { for (NodeState dst : dsts) { if (src != dst) { short min = resetLatency; short minhop = -1; for (short hop : hops) { if (hop != src.info.id) { int src2hop = src.latencies.get(hop); int dst2hop = dst.latencies.get(hop); int latency = src2hop + dst2hop; // DEBUG // log(src + "->" + hop + " is " + src2hop + ", " + hop + // "->" + dst + " is " + dst2hop + ", sum " + // latency); if (latency < min) { min = (short) latency; minhop = hop; } } } // it's possible for us to have not found an ideal hop. this // may be counter-intuitive, since even if src<->dst is broken, // the fact that both are our clients means we should be able // to serve as a hop. however it may be that either one of them // was, or we were, recently added as a member to the network, // so they never had a chance to ping us yet (and hence we're // missing from their measurements). (TODO also is it possible // that we're missing their measurement entirely? are all // clients necessarily added on demand by measurement packets?) // what we can do is to try finding our own latency to the hop // (perhaps we've had a chance to ping them), and failing that, // estimating the latency (only if one of us was newly added). // however, these errors are transient anyway - by the next // routing period, several pings will have taken place that // would guarantee (or there was a failure, and eventually one // of {src,dst} will fall out of our client set). if (minhop != -1) { short directLatency = src.latencies.get(dst.info.id); Rec rec = new Rec(); rec.dst = dst.info.id; // We require that a recommended route (if not the direct // route and if direct route is working) yield at least a // 5% reduction in latency. // - if min-cost route is the direct route, just use it // - if direct-cost route is infinite, then no point // comparing to the min-cost hop route // - if min-cost route is not much better than direct // route, use direct route if (minhop == dst.info.id || directLatency == resetLatency || min * directBonus < directLatency) { // TODO (high priority): can you get a short overflow with above? directBonus is a double rec.via = minhop; recs.add(rec); } else { // At this point, // min-cost route is not the direct route && // src->dst is *not* infinite && // min * directBonus >= src->dst // So, recommend the direct route, if that is working. rec.via = dst.info.id; recs.add(rec); } } } } } private void findHopsAlt(ArrayList<Short> dsts, ArrayList<NodeState> hops, NodeState src, ArrayList<Rec> recs) { for (short dst : dsts) { if (src.info.id != dst && nodes.get(dst).isReachable) { short min = resetLatency; short minhop = -1; for (NodeState hop : hops) { if (hop != src) { short src2hop = src.latencies.get(hop.info.id); short dst2hop = hop.latencies.get(dst); short latency = (short) (src2hop + dst2hop); if (latency < min) { min = latency; minhop = hop.info.id; } } } assert minhop != -1; Rec rec = new Rec(); rec.dst = dst; rec.via = minhop; recs.add(rec); } } } private String routesToString(ArrayList<Rec> recs) { String s = ""; for (Rec rec : recs) s += rec.via + "->" + rec.dst + " "; return s; } private Serialization senderSer = new Serialization(); private int sendObject(final Msg o, InetAddress addr, int port, short nid) { o.src = myNid; o.version = currentStateVersion; o.session = sessionId; try { /* * note that it's unsafe to re-use these output streams - at * least, i don't know how (reset() is insufficient) */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); senderSer.serialize(o, new DataOutputStream(baos)); byte[] buf = baos.toByteArray(); String who = nid >= 0 ? "" + nid : (addr + ":" + port); log("send." + o.getClass().getSimpleName(), "to " + who + " len " + buf.length); if (!ignored.contains(nid)) { session.send(ByteBuffer.wrap(buf), new InetSocketAddress(addr, port)); } else { log("droppng packet sent to " + who); } return buf.length; } catch (Exception ex) { throw new RuntimeException(ex); } } private int sendObject(final Msg o, NodeInfo info, short nid) { return sendObject(o, info.addr, info.port, nid); } private int sendObject(final Msg o, NodeInfo info) { return sendObject(o, info, (short)-1); } private int sendObject(final Msg o, short nid) { return nid != myNid ? sendObject(o, nid == 0 ? coordNode : (myNid == 0 ? coordNodes.get(nid) : nodes.get(nid).info), nid) : 0; } private void broadcastMeasurements(ArrayList<NodeState> servers) { ShortShortMap latencies = nodes.get(myNid).latencies; Measurements rm = new Measurements(); rm.probeTable = new short[memberNids.size()]; for (int i = 0; i < rm.probeTable.length; i++) rm.probeTable[i] = latencies.get(memberNids.get(i)); rm.inflation = new byte[rm.probeTable.length]; int totalSize = 0; for (NodeState nbr : servers) { totalSize += sendObject(rm, nbr.info.id); } log("sent measurements, " + totalSize + " bytes, to " + servers); } private void updateMeasurements(Measurements m) { NodeState src = nodes.get(m.src); for (int i = 0; i < m.probeTable.length; i++) src.latencies.put(memberNids.get(i), m.probeTable[i]); // TODO we aren't setting node.{hop,cameUp,isHopRecommended=false}... } private void handleRecommendations(RoutingRecs msg) { ArrayList<Rec> recs = msg.recs; NodeState r = nodes.get(msg.src); r.dstsPresent.clear(); r.remoteFailures.clear(); for (Rec rec : recs) { r.dstsPresent.add(rec.dst); if (nodes.get(rec.via).isReachable) { if (scheme == RoutingScheme.SQRT_SPECIAL) { /* * TODO: add in support for processing sqrt_special * recommendations. first we need to add in the actual cost of * the route to these recommendations (see * broadcastRecommndations), then we need to compare all of * these and see which ones were better. a complication is that * routing recommendation broadcasts are not synchronized, so * while older messages may appear to have better routes, there * must be some threshold in time past which we disregard old * latencies. must keep some history */ } else { // blindly trust the recommendations NodeState node = nodes.get(rec.dst); if (node.hop == 0 || node.isDead) { node.cameUp = true; node.isDead = false; } node.isHopRecommended = true; node.hop = rec.via; } } } if (scheme != RoutingScheme.SQRT_SPECIAL) { /* * get the full set of dsts that we depend on this node for. note * that the set of nodes it's actually serving may be different. */ // TODO (low priority): just use dstsPresent instead of remoteFailures for (NodeState dst : nodeDefaultRSs.get(r)) { if (!r.dstsPresent.contains(dst.info.id)) { /* * there was a comm failure between this rendezvous and the * dst for which this rendezvous did not provide a * recommendation. this a proximal rendezvous failure, so that if * necessary during the next phase, we will find failovers. */ r.remoteFailures.add(dst); } } } } /** * counts the number of nodes that we can reach - either directly, through a * hop, or through any rendezvous client. * * @return */ private int countReachableNodes() { /* * TODO need to fix up hopOptions so that it actually gets updated * correctly, since currently things are *never* removed from it (they * need to expire) */ NodeState myState = nodes.get(myNid); int count = 0; for (NodeState node : otherNodes) { count += node.hop != 0 ? 1 : 0; } return count; } /** * Counts the number of paths to a particular node. * * Note that this does not get run whenever nodes become reachable, only * when they become unreachable (and also in batch periodically). * Furthermore, we do not run this whenever we get a measurement packet. * The reason for these infelicities is one of performance. * * The logic among hop, isHopRecommended, and cameUp is tricky. */ private int findPaths(NodeState node, boolean batch) { ArrayList<NodeState> clients = getAllRendezvousClients(); ArrayList<NodeState> servers = lastRendezvousServers; HashSet<NodeState> options = new HashSet<NodeState>(); short min = resetLatency; short nid = node.info.id; boolean wasDead = node.hop == 0; NodeState self = nodes.get(myNid); // we would like to keep recommended nodes (they should be the best // choice, but also we have no ping data). but if it was not obtained // via recommendation (i.e., a previous findPaths() got this hop), then // we should feel free to update it. if (node.hop == 0) { node.isHopRecommended = false; } else { // we are not adding the hop if (!node.isHopRecommended) { node.hop = 0; } } // Unless node.hop == 0, this code below is useless // We would like to measure this... // keep track of subping. // direct hop if (node.isReachable) { options.add(node); if (!node.isHopRecommended) { node.hop = node.info.id; min = self.latencies.get(node.info.id); } } else { // If it is alive, we will set it to false in the next few lines node.isDead = true; } // find best rendezvous client. (`clients` are all reachable.) for (NodeState client : clients) { int val = client.latencies.get(nid); if (val != resetLatency) { if(!node.isReachable) node.isDead = false; options.add(client); val += self.latencies.get(client.info.id); if (!node.isHopRecommended && val < min) { node.hop = client.info.id; min = (short) val; } } } // see if a rendezvous server can serve as the hop. (can't just iterate // through hopOptions, because that doesn't tell us which server to go // through.) using the heuristic of just our latency to the server for (NodeState server : servers) { if (server.dstsPresent.contains(nid)) { options.add(server); short val = self.latencies.get(server.info.id); if (node.hop == 0 && val < min) { node.hop = server.info.id; min = val; } } } boolean isDead = node.hop == 0; // seems that (!isDead && wasDead) can be true, if a hop is found here // from a measurement (from a rclient). boolean cameUp = !isDead && wasDead || node.cameUp; boolean wentDown = isDead && !wasDead; // reset node.cameUp node.cameUp = false; // we always print something in non-batch mode. we also print stuff if // there was a change in the node's up/down status. if a node is reachable // then findPaths(node,) will only be called during batch processing, and // so wasDead will have been set either by the last unreachable call or by // the previous batch call. thus, the first batch call after a node goes // up, the "up" message will be printed. if (!batch || cameUp || wentDown) { String stateChange = cameUp ? " up" : (wentDown ? " down" : ""); log("node " + node + stateChange + " hop " + node.hop + " total " + options.size()); } return options.size(); } /** * Counts the avg number of one-hop or direct paths available to nodes * Calls findPaths(node) for all other nodes. This code is supposed to * a) find out a node is alive, and b) find the optimal one-hop route to * this destination. * @return */ private Pair<Integer, Integer> findPathsForAllNodes() { NodeState myState = nodes.get(myNid); int count = 0; int numNodesReachable = 0; for (NodeState node : otherNodes) { int d = findPaths(node, true); count += d; numNodesReachable += d > 0 ? 1 : 0; } if (numNodesReachable > 0) count /= numNodesReachable; return Pair.of(numNodesReachable, count); } public void quit() { doQuit.set(true); } private class NodeState implements Comparable<NodeState> { public String toString() { return "" + info.id; } /** * not null */ public final NodeInfo info; /** * updated in resetTimeoutAtNode(). if hop == 0, this must be false; if * hop == the nid, this must be true. * * this should also be made to correspond with the appropriate latencies in myNid */ public boolean isReachable = true; /** * the last known latencies to all other nodes. missing entry implies * resetLatency. this is populated/valid for rendezvous clients. * * invariants: * - keyset is a subset of current members (memberNids); enforced in * updateMembers() * - keyset contains only live nodes; enforced in resetTimeoutAtNode() * - values are not resetLatency * - undefined if not a rendezvous client */ public final ShortShortMap latencies = new ShortShortMap(resetLatency); /** * the recommended intermediate hop for us to get to this node, or 0 if * no way we know of to get to that node, and thus believe the node is * down. * * invariants: * - always refers to a member or 0; enforced in updateMembers() * - never refers to dead node; enforced in resetTimeoutAtNode() * - may be nid (may be dst) * - initially defaults to dst (since we don't know hops to it) * - never refers to the owning neuronnode (never is src) * - cannot be nid if !isReachable */ public short hop; /** * Keeps track of whether any node (including ourself) receives measurements * to the destination. Only consider this if node.isReachable is false. */ public boolean isDead = false; /** * this is set at certain places where we determine that a node is * alive, and reset in the next findPaths(). the only reason we need * this is to help produce the correct logging output for the * effectiveness timing analysis. */ public boolean cameUp; /** * this indicates how we got this hop. this is set in * handleRecommendations(), reset in resetTimeoutAtNode(), and * read/reset from batch-mode findPaths(). if it was recommended to * us, then we will want to keep it; otherwise, it was just something * we found in failover mode, so are free to wipe it out. this var has * no meaning when hop == 0. */ public boolean isHopRecommended; /** * remote failures. applies only if this nodestate is of a rendezvous * node. contains nids of all nodes for which this rendezvous cannot * recommend routes. * * invariants: * - undefined if this is not a rendezvous node * - empty */ public final HashSet<NodeState> remoteFailures = new HashSet<NodeState>(); /** * dstsPresent, the complement of remoteFailures (in defaultClients). */ public final HashSet<Short> dstsPresent = new HashSet<Short>(); /** * this is unused at the moment. still need to re-design. */ public final HashSet<Short> hopOptions = new HashSet<Short>(); public NodeState(NodeInfo info) { this.info = info; this.hop = info.id; latencies.put(info.id, (short) 0); } public int compareTo(NodeState o) { return new Short(info.id).compareTo(o.info.id); } } } class ShortShortMap { private final Hashtable<Short,Short> table = new Hashtable<Short, Short>(); private final short defaultValue; public ShortShortMap(short defaultValue) { this.defaultValue = defaultValue; } public Set<Short> keySet() { return table.keySet(); } public boolean containsKey(short key) { return table.containsKey(key); } public void remove(short key) { table.remove(key); } public short get(short key) { Short value = table.get(key); return value != null ? value : defaultValue; } public void put(short key, short value) { if (value == defaultValue) table.remove(key); else table.put(key, value); } } /////////////////////////////////////// // // // // // // welcome to my // DEATH MACHINE, // interloper!!!!!!!11 // // // // // // ///////////////////////////////////// class NodeInfo { short id; int port; InetAddress addr; } class Rec { short dst; short via; } class Subprobe { long time; InetSocketAddress src; InetSocketAddress nod; byte type; } class PeerPing { long time; InetSocketAddress src; } class PeerPong { long time; InetSocketAddress src; } class Msg { short src; short version; short session; } class Join extends Msg { InetAddress addr; int port; } class Init extends Msg { short id; ArrayList<NodeInfo> members; } class Membership extends Msg { ArrayList<NodeInfo> members; short numNodes; short yourId; } class RoutingRecs extends Msg { ArrayList<Rec> recs; } class Ping extends Msg { long time; NodeInfo info; } class Pong extends Msg { long time; } class Measurements extends Msg { short[] probeTable; byte[] inflation; } class Serialization { public void serialize(Object obj, DataOutputStream out) throws IOException { if (false) {} else if (obj.getClass() == NodeInfo.class) { NodeInfo casted = (NodeInfo) obj; out.writeInt(((int) serVersion) << 8 | 0); out.writeShort(casted.id); out.writeInt(casted.port); { byte[] buf = casted.addr.getAddress(); out.writeInt(buf.length); out.write(buf); } } else if (obj.getClass() == Rec.class) { Rec casted = (Rec) obj; out.writeInt(((int) serVersion) << 8 | 1); out.writeShort(casted.dst); out.writeShort(casted.via); } else if (obj.getClass() == Subprobe.class) { Subprobe casted = (Subprobe) obj; out.writeInt(((int) serVersion) << 8 | 2); out.writeLong(casted.time); { byte[] buf = casted.src.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.src.getPort()); { byte[] buf = casted.nod.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.nod.getPort()); out.writeByte(casted.type); } else if (obj.getClass() == PeerPing.class) { PeerPing casted = (PeerPing) obj; out.writeInt(((int) serVersion) << 8 | 3); out.writeLong(casted.time); { byte[] buf = casted.src.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.src.getPort()); } else if (obj.getClass() == PeerPong.class) { PeerPong casted = (PeerPong) obj; out.writeInt(((int) serVersion) << 8 | 4); out.writeLong(casted.time); { byte[] buf = casted.src.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.src.getPort()); } else if (obj.getClass() == Msg.class) { Msg casted = (Msg) obj; out.writeInt(((int) serVersion) << 8 | 5); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Join.class) { Join casted = (Join) obj; out.writeInt(((int) serVersion) << 8 | 6); { byte[] buf = casted.addr.getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.port); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Init.class) { Init casted = (Init) obj; out.writeInt(((int) serVersion) << 8 | 7); out.writeShort(casted.id); out.writeInt(casted.members.size()); for (int i = 0; i < casted.members.size(); i++) { out.writeShort(casted.members.get(i).id); out.writeInt(casted.members.get(i).port); { byte[] buf = casted.members.get(i).addr.getAddress(); out.writeInt(buf.length); out.write(buf); } } out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Membership.class) { Membership casted = (Membership) obj; out.writeInt(((int) serVersion) << 8 | 8); out.writeInt(casted.members.size()); for (int i = 0; i < casted.members.size(); i++) { out.writeShort(casted.members.get(i).id); out.writeInt(casted.members.get(i).port); { byte[] buf = casted.members.get(i).addr.getAddress(); out.writeInt(buf.length); out.write(buf); } } out.writeShort(casted.numNodes); out.writeShort(casted.yourId); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == RoutingRecs.class) { RoutingRecs casted = (RoutingRecs) obj; out.writeInt(((int) serVersion) << 8 | 9); out.writeInt(casted.recs.size()); for (int i = 0; i < casted.recs.size(); i++) { out.writeShort(casted.recs.get(i).dst); out.writeShort(casted.recs.get(i).via); } out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Ping.class) { Ping casted = (Ping) obj; out.writeInt(((int) serVersion) << 8 | 10); out.writeLong(casted.time); out.writeShort(casted.info.id); out.writeInt(casted.info.port); { byte[] buf = casted.info.addr.getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Pong.class) { Pong casted = (Pong) obj; out.writeInt(((int) serVersion) << 8 | 11); out.writeLong(casted.time); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Measurements.class) { Measurements casted = (Measurements) obj; out.writeInt(((int) serVersion) << 8 | 12); out.writeInt(casted.probeTable.length); for (int i = 0; i < casted.probeTable.length; i++) { out.writeShort(casted.probeTable[i]); } out.writeInt(casted.inflation.length); out.write(casted.inflation); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } } public static byte serVersion = 2; public Object deserialize(DataInputStream in) throws IOException { int header = readInt(in); if ((header & 0xff00) != ((int) serVersion) << 8) return null; int msgtype = header & 0xff; switch (msgtype) { case 0: { // NodeInfo NodeInfo obj; { obj = new NodeInfo(); { obj.id = in.readShort(); } { obj.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } obj.addr = InetAddress.getByAddress(buf); } } return obj; } case 1: { // Rec Rec obj; { obj = new Rec(); { obj.dst = in.readShort(); } { obj.via = in.readShort(); } } return obj; } case 2: { // Subprobe Subprobe obj; { obj = new Subprobe(); { obj.time = in.readLong(); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.src = new InetSocketAddress(addr, port); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.nod = new InetSocketAddress(addr, port); } { obj.type = in.readByte(); } } return obj; } case 3: { // PeerPing PeerPing obj; { obj = new PeerPing(); { obj.time = in.readLong(); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.src = new InetSocketAddress(addr, port); } } return obj; } case 4: { // PeerPong PeerPong obj; { obj = new PeerPong(); { obj.time = in.readLong(); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.src = new InetSocketAddress(addr, port); } } return obj; } case 5: { // Msg Msg obj; { obj = new Msg(); { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } return obj; } case 6: { // Join Join obj; { obj = new Join(); { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } obj.addr = InetAddress.getByAddress(buf); } { obj.port = readInt(in); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 7: { // Init Init obj; { obj = new Init(); { obj.id = in.readShort(); } { obj.members = new ArrayList<NodeInfo>(); for (int i = 0, len = readInt(in); i < len; i++) { NodeInfo x; { x = new NodeInfo(); { x.id = in.readShort(); } { x.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } x.addr = InetAddress.getByAddress(buf); } } obj.members.add(x); } } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 8: { // Membership Membership obj; { obj = new Membership(); { obj.members = new ArrayList<NodeInfo>(); for (int i = 0, len = readInt(in); i < len; i++) { NodeInfo x; { x = new NodeInfo(); { x.id = in.readShort(); } { x.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } x.addr = InetAddress.getByAddress(buf); } } obj.members.add(x); } } { obj.numNodes = in.readShort(); } { obj.yourId = in.readShort(); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 9: { // RoutingRecs RoutingRecs obj; { obj = new RoutingRecs(); { obj.recs = new ArrayList<Rec>(); for (int i = 0, len = readInt(in); i < len; i++) { Rec x; { x = new Rec(); { x.dst = in.readShort(); } { x.via = in.readShort(); } } obj.recs.add(x); } } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 10: { // Ping Ping obj; { obj = new Ping(); { obj.time = in.readLong(); } { obj.info = new NodeInfo(); { obj.info.id = in.readShort(); } { obj.info.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } obj.info.addr = InetAddress.getByAddress(buf); } } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 11: { // Pong Pong obj; { obj = new Pong(); { obj.time = in.readLong(); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 12: { // Measurements Measurements obj; { obj = new Measurements(); { obj.probeTable = new short[readInt(in)]; for (int i = 0; i < obj.probeTable.length; i++) { { obj.probeTable[i] = in.readShort(); } } } { obj.inflation = new byte[readInt(in)]; in.read(obj.inflation); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } default: throw new RuntimeException("unknown obj type"); } } private byte[] readBuffer = new byte[4]; // read in a big-endian 4-byte integer public int readInt(DataInputStream dis) throws IOException { dis.readFully(readBuffer, 0, 4); return ( ((int)(readBuffer[0] & 255) << 24) + ((readBuffer[1] & 255) << 16) + ((readBuffer[2] & 255) << 8) + ((readBuffer[3] & 255) << 0)); } /* public static void main(String[] args) throws IOException { { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); Pong pong = new Pong(); pong.src = 2; pong.version = 3; pong.time = 4; serialize(pong, out); byte[] buf = baos.toByteArray(); System.out.println(buf.length); Object obj = deserialize(new DataInputStream(new ByteArrayInputStream(buf))); System.out.println(obj); } { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); Measurements m = new Measurements(); m.src = 2; m.version = 3; m.membershipList = new ArrayList<Integer>(); m.membershipList.add(4); m.membershipList.add(5); m.membershipList.add(6); m.ProbeTable = new long[5]; m.ProbeTable[1] = 7; m.ProbeTable[2] = 8; m.ProbeTable[3] = 9; serialize(m, out); byte[] buf = baos.toByteArray(); System.out.println(buf.length); Object obj = deserialize(new DataInputStream(new ByteArrayInputStream(buf))); System.out.println(obj); } { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); Membership m = new Membership(); m.src = 2; m.version = 3; m.members = new ArrayList<NodeInfo>(); NodeInfo n1 = new NodeInfo(); n1.addr = InetAddress.getLocalHost(); n1.port = 4; n1.id = 5; m.members.add(n1); NodeInfo n2 = new NodeInfo(); n2.addr = InetAddress.getByName("google.com"); n2.port = 6; n2.id = 7; m.members.add(n2); m.numNodes = 8; serialize(m, out); byte[] buf = baos.toByteArray(); System.out.println(buf.length); Object obj = deserialize(new DataInputStream( new ByteArrayInputStream(buf))); System.out.println(obj); } }*/ }
edu/cmu/neuron2/NeuRonNode.java
package edu.cmu.neuron2; import java.io.*; import java.net.*; import java.util.*; import java.lang.annotation.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.logging.*; import java.util.logging.Formatter; import java.nio.ByteBuffer; //import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.transport.socket.nio.DatagramAcceptor; import org.apache.mina.transport.socket.nio.DatagramAcceptorConfig; import edu.cmu.neuron2.RonTest.RunMode; class LabelFilter implements Filter { private final HashSet<String> suppressedLabels; private final boolean suppressAll; public LabelFilter(HashSet<String> suppressedLabels) { this.suppressedLabels = suppressedLabels; this.suppressAll = suppressedLabels.contains("all"); } public boolean isLoggable(LogRecord record) { if (suppressAll) return false; String[] parts = record.getLoggerName().split("\\.", 2); return parts.length == 1 || !suppressedLabels.contains(parts[1]); } } public class NeuRonNode extends Thread { private final Reactor scheduler; public short myNid; private final boolean isCoordinator; private final String coordinatorHost; private final int basePort; private final AtomicBoolean doQuit = new AtomicBoolean(); private Logger logger; /** * maps node id's to nodestates. this is the primary container. */ private final Hashtable<Short, NodeState> nodes = new Hashtable<Short, NodeState>(); /** * neighbors = rendesvousServers union rendezvousClients. we send our * routes to all servers in this set. */ /** * maps nid to {the set of rendezvous servers to that nid} */ private final Hashtable<Short, HashSet<NodeState>> rendezvousServers = new Hashtable<Short, HashSet<NodeState>>(); /** * the set of nodes that are relying us to get to someone. * * this is needed during route computation. i need to know who to calculate * routes among, and we want to include rendezvousclients in this set. */ private final SortedSet<NodeState> rendezvousClients = new TreeSet<NodeState>(); // These variables used internally to updateMembers (keep this way, for // abstraction purposes), and are only exposed for printGrid(). private NodeState[][] grid; private short numCols, numRows; // Coord-only: maps addresses to nids private final Hashtable<InetAddress, Short> addr2id = new Hashtable<InetAddress, Short>(); // Specific to this node. Lookup from destination to default rs's to it private final Hashtable<Short, HashSet<NodeState>> defaultRendezvousServers = new Hashtable<Short, HashSet<NodeState>>(); // Lookup from node to a set of its rendezvous servers private final Hashtable<NodeState, HashSet<NodeState>> nodeDefaultRSs = new Hashtable<NodeState, HashSet<NodeState>>(); private short currentStateVersion; public final int neighborBroadcastPeriod; public final int probePeriod; public final int gcPeriod; private final NodeInfo coordNode; private final RunMode mode; private final short numNodesHint; private final Runnable semAllJoined; private final Random rand = new Random(); private final InetAddress myCachedAddr; private ArrayList<Short> cachedMemberNids = new ArrayList<Short>(); // sorted list of members private short cachedMemberNidsVersion; private final boolean blockJoins; private final boolean capJoins; private final int joinRetries; // seconds private final boolean enableSubpings; private final int subpingPeriod; // seconds // number of intervals which we'll split the probing time into private int numProbeIntervals; private Set[] pingTable; private final Hashtable<NodeState, Integer> pingId = new Hashtable<NodeState, Integer>(); private final int dumpPeriod; private final FileHandler fh; private final short origNid; private final short sessionId; private final int linkTimeout; private final int membershipBroadcastPeriod; private static final String defaultLabelSet = "subprobe send.Ping recv.Ping stale.Ping send.Pong recv.Pong send.Subprobe recv.Subprobe stale.Pong send.Measurements send.RoutingRecs subprobe"; private final Hashtable<Short,Long> lastSentMbr = new Hashtable<Short,Long>(); private final double smoothingFactor; private final short resetLatency = Short.MAX_VALUE; private final DatagramAcceptor acceptor; private final Hashtable<Short, NodeInfo> coordNodes = new Hashtable<Short, NodeInfo>(); private final ArrayList<Short> memberNids = new ArrayList<Short>(); private final ArrayList<NodeState> otherNodes = new ArrayList<NodeState>(); private final ArrayList<NodeState> lastRendezvousServers = new ArrayList<NodeState>(); private final double directBonus, hysteresisBonus; private final long startTime = System.currentTimeMillis(); private final int pingDumpPeriod, pingDumpInitialDelay; private final Reactor reactor; private Runnable safeRun(final Runnable r) { return new Runnable() { public void run() { try { r.run(); } catch (Throwable ex) { err(ex); } } }; } private void createLabelFilter(Properties props, String labelSet, Handler handler) { String[] labels = props.getProperty(labelSet, defaultLabelSet).split(" "); final HashSet<String> suppressedLabels = new HashSet<String>(Arrays.asList(labels)); handler.setFilter(new LabelFilter(suppressedLabels)); } private final int joinDelay; public NeuRonNode(short id, Properties props, short numNodes, Runnable semJoined, InetAddress myAddr, String coordinatorHost, NodeInfo coordNode, DatagramAcceptor acceptor, Reactor reactor) { this.reactor = reactor; joinDelay = rand.nextInt(Integer.parseInt(props.getProperty("joinDelayRange", "1"))); if ((coordNode == null) || (coordNode.addr == null)){ throw new RuntimeException("coordNode is null!"); } dumpPeriod = Integer.parseInt(props.getProperty("dumpPeriod", "60")); myNid = id; origNid = id; cachedMemberNidsVersion = (short)-1; joinRetries = Integer.parseInt(props.getProperty("joinRetries", "10")); // wait up to 10 secs by default for coord to be available membershipBroadcastPeriod = Integer.parseInt(props.getProperty("membershipBroadcastPeriod", "0")); // NOTE note that you'll probably want to set this, always! sessionId = Short.parseShort(props.getProperty("sessionId", "0")); blockJoins = Boolean.valueOf(props.getProperty("blockJoins", "true")); capJoins = Boolean.valueOf(props.getProperty("capJoins", "true")); this.coordinatorHost = coordinatorHost; this.coordNode = coordNode; mode = RunMode.valueOf(props.getProperty("mode", "sim").toUpperCase()); basePort = coordNode.port; scheme = RoutingScheme.valueOf(props.getProperty("scheme", "SQRT").toUpperCase()); if (scheme == RoutingScheme.SQRT) { neighborBroadcastPeriod = Integer.parseInt(props.getProperty("neighborBroadcastPeriod", "15")); } else { neighborBroadcastPeriod = Integer.parseInt(props.getProperty("neighborBroadcastPeriod", "30")); } gcPeriod = Integer.parseInt(props.getProperty("gcPeriod", neighborBroadcastPeriod + "")); enableSubpings = Boolean.valueOf(props.getProperty("enableSubpings", "true")); this.acceptor = acceptor; // for simulations we can safely reduce the probing frequency, or even turn it off //if (mode == RunMode.SIM) { //probePeriod = Integer.parseInt(props.getProperty("probePeriod", "60")); //} else { probePeriod = Integer.parseInt(props.getProperty("probePeriod", "30")); //} subpingPeriod = Integer.parseInt(props.getProperty("subpingPeriod", "" + probePeriod)); membershipTimeout = Integer.parseInt(props.getProperty("timeout", "" + 30*60)); linkTimeout = Integer.parseInt(props.getProperty("failoverTimeout", "" + membershipTimeout)); pingDumpInitialDelay = Integer.parseInt(props.getProperty("pingDumpInitialDelay", "60")); pingDumpPeriod = Integer.parseInt(props.getProperty("pingDumpPeriod", "60")); // Events are when simulated latencies change; these are substituted in // for real measured latencies, and can be useful in simulation. These // events must be specified in time order! To remove any sim latency // for a dst, set it to resetLatency. String simEventsSpec = props.getProperty("simEvents", ""); if (!simEventsSpec.equals("")) { String[] events = simEventsSpec.split(";"); for (String e : events) { String[] parts = e.split(" "); int secs = Integer.parseInt(parts[0]); short oid = Short.parseShort(parts[1]); if (oid == myNid) { short dst = Short.parseShort(parts[2]); short lat = Short.parseShort(parts[3]); simEvents.addLast(new SimEvent(secs, oid, dst, lat)); } } } smoothingFactor = Double.parseDouble(props.getProperty("smoothingFactor", "0.1")); directBonus = Double.parseDouble(props.getProperty("directBonus", "1.05")); hysteresisBonus = Double.parseDouble(props.getProperty("hysteresisBonus", "1.05")); Formatter minfmt = new Formatter() { public String format(LogRecord record) { StringBuilder buf = new StringBuilder(); buf.append(record.getMillis()).append(' ')/*.append(new Date(record.getMillis())).append(" ").append( record.getLevel()).append(" ")*/.append( record.getLoggerName()).append(": ").append( record.getMessage()).append("\n"); return buf.toString(); } }; Formatter fmt = new Formatter() { public String format(LogRecord record) { StringBuilder buf = new StringBuilder(); buf.append(record.getMillis()).append(' ').append(new Date(record.getMillis())).append(" ").append( record.getLevel()).append(" ").append( record.getLoggerName()).append(": ").append( record.getMessage()).append("\n"); return buf.toString(); } }; Logger rootLogger = Logger.getLogger(""); rootLogger.getHandlers()[0].setFormatter(fmt); logger = Logger.getLogger("node" + myNid); createLabelFilter(props, "consoleLogFilter", rootLogger.getHandlers()[0]); try { String logFileBase = props.getProperty("logFileBase", "%t/scaleron-log-"); fh = new FileHandler(logFileBase + myNid, true); fh.setFormatter(fmt); createLabelFilter(props, "fileLogFilter", fh); logger.addHandler(fh); } catch (IOException ex) { throw new RuntimeException(ex); } this.scheduler = reactor; grid = null; numCols = numRows = 0; isCoordinator = myNid == 0; currentStateVersion = (short) (isCoordinator ? 0 : -1); numNodesHint = Short.parseShort(props.getProperty("numNodesHint", "" + numNodes)); semAllJoined = semJoined; if (myAddr == null) { try { myCachedAddr = InetAddress.getLocalHost(); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } } else { myCachedAddr = myAddr; } myPort = basePort + myNid; this.myAddr = new InetSocketAddress(myCachedAddr, myPort); clientTimeout = Integer.parseInt(props.getProperty("clientTimeout", "" + 3 * neighborBroadcastPeriod)); } private final int myPort; private final InetSocketAddress myAddr; private void handleInit(Init im) { if (im.id == -1) { throw new PlannedException("network is full; aborting"); } myNid = im.id; logger = Logger.getLogger("node_" + myNid); if (logger.getHandlers().length == 0) { logger.addHandler(fh); } currentStateVersion = im.version; log("got from coord => Init version " + im.version); updateMembers(im.members); } private String bytes2string(byte[] buf) { String s = "[ "; for (byte b : buf) { s += b + " "; } s += "]"; return s; } private void log(String msg) { logger.info(msg); } private void warn(String msg) { logger.warning(msg); } private void err(String msg) { logger.severe(msg); } public void err(Throwable ex) { StringWriter s = new StringWriter(); PrintWriter p = new PrintWriter(s); ex.printStackTrace(p); err(s.toString()); } /** * Used for logging data, such as neighbor lists. * * @param name - the name of the data, e.g.: "neighbors", "info" * @param value */ private void log(String name, Object value) { Logger.getLogger(logger.getName() + "." + name).info(value.toString()); } public static final class SimEvent { public int secs; public short oid, dst, lat; public SimEvent(int secs, short src, short dst, short lat) { this.secs = secs; this.oid = oid; this.dst = dst; this.lat = lat; } } public final ArrayDeque<SimEvent> simEvents = new ArrayDeque<SimEvent>(); public final ShortShortMap simLatencies = new ShortShortMap(resetLatency); public static final class PlannedException extends RuntimeException { public PlannedException(String msg) { super(msg); } } public final AtomicReference<Exception> failure = new AtomicReference<Exception>(); public void run() { try { run3(); } catch (PlannedException ex) { warn(ex.getMessage()); failure.set(ex); if (semAllJoined != null) semAllJoined.run(); } catch (Exception ex) { err(ex); failure.set(ex); if (semAllJoined != null) semAllJoined.run(); } } /** * Similar to fixed-rate scheduling, but doesn't try to make up multiple * overdue items, but rather allows us to skip over them. This should deal * better with PLab's overloaded hosts. * * @param r The runnable task. * @param initialDelay The initial delay in seconds. * @param period The period in seconds. */ private ScheduledFuture<?> safeSchedule(final Runnable r, long initialDelay, final long period) { final long bufferTime = 1000; // TODO parameterize return scheduler.schedule(new Runnable() { private long scheduledTime = -1; public void run() { if (scheduledTime < 0) scheduledTime = System.currentTimeMillis(); r.run(); long now = System.currentTimeMillis(); scheduledTime = Math.max(scheduledTime + period * 1000, now + bufferTime); scheduler.schedule(this, scheduledTime - now, TimeUnit.MILLISECONDS); } }, initialDelay, TimeUnit.SECONDS); } private ScheduledFuture<?> safeScheduleMs(final Callable<Integer> r, final int maxPoints, long initialDelay, final long period) { return scheduler.schedule(new Runnable() { private long scheduledTime = -1; public void run() { if (scheduledTime < 0) scheduledTime = System.currentTimeMillis(); int points = 0; while (true) { try { points += r.call(); } catch (Exception ex) { err(ex); } long now = System.currentTimeMillis(); scheduledTime = Math.max(scheduledTime + period, now); if (scheduledTime > now) { scheduler.schedule(this, scheduledTime - now, TimeUnit.MILLISECONDS); break; } if (points > maxPoints) { scheduler.schedule(this, now + period, TimeUnit.MILLISECONDS); break; } } } }, initialDelay, TimeUnit.MILLISECONDS); } private boolean hasJoined = false; private Session session = null; public void run3() { if (isCoordinator) { try { safeSchedule(safeRun(new Runnable() { public void run() { log("checkpoint: " + coordNodes.size() + " nodes"); printMembers(); //printGrid(); } }), dumpPeriod, dumpPeriod); if (false) { acceptor.bind(new InetSocketAddress(InetAddress .getLocalHost(), basePort), new CoordReceiver()); } else { final CoordHandler handler = new CoordHandler(); session = reactor.register(null, myAddr, handler); } } catch (Exception ex) { throw new RuntimeException(ex); } } else { try { if (false) { final Receiver receiver = new Receiver(); acceptor.bind(new InetSocketAddress(myCachedAddr, myPort), receiver); } else { final NodeHandler handler = new NodeHandler(); session = reactor.register(null, myAddr, handler); } log("server started on " + myCachedAddr + ":" + (basePort + myNid)); // Split up the probing period into many small intervals. In each // interval we will ping a small fraction of the nodes. numProbeIntervals = numNodesHint / 3; pingTable = new HashSet[numProbeIntervals]; for(int i=0; i<numProbeIntervals; i++) pingTable[i] = new HashSet(); int probeSubPeriod = (1000 * probePeriod) / numProbeIntervals; safeScheduleMs(new Callable<Integer>() { int pingIter = 0; public Integer call() { int points = 0; if (hasJoined) { points += pingAll(pingIter); pingIter = (pingIter + 1) % numProbeIntervals; } return 1; } }, 5, 1234, probeSubPeriod); safeSchedule(safeRun(new Runnable() { public void run() { if (hasJoined) { /* * path-finding and rendezvous finding is * interdependent. the fact that we do the path-finding * first before the rendezvous servers is arbitrary. */ // TODO the below can be decoupled. Actually, with the current bug, node.hop isn't // set and findPathsForAllNodes() doesn't actually do anything. Pair<Integer, Integer> p = findPathsForAllNodes(); log(p.first + " live nodes, " + p.second + " avg paths, " + nodes.get(myNid).latencies.keySet() .size() + " direct paths"); // TODO this can also be decoupled. However, we don't want too much time to pass // between calculating rendezvous servers and actually sending to them, since in // the mean time we will have received recommendations which hint at remote failures // etc. Also our notion of isReachable will have changed. For SIMPLE this is easy: // we can remove from the set any nodes that are no longer reachable. An ad-hoc // solution would be to run it just once and then check if the dst is reachable before // broadcasting. This might take longer in certain failure scenarios. // We can, before sending, check whether link is down or we received a more recent // measurement packing showing remote failure. If remote failure, we'd like to wait // anyway since dst might be down. Might be useless, but can still send measurements. // If link is down, just don't send anything. We'll try again in the next iteration. // SUMMARY: after constructing measRecips, put each destination onto the queue, // and if when popped !dst.isReachable, just don't send. ArrayList<NodeState> measRecips = scheme == RoutingScheme.SIMPLE ? getAllReachableNodes() : getAllRendezvousServers(); // TODO this can also be decoupled, and also split up // into intervals. We should keep the probeTable[] // in memory and always up to date. Further optimization // is to keep array of bytes, so no serialization. broadcastMeasurements(measRecips); // TODO this can also be decoupled. Don't use // getAllRendezvousClients(), just work directly with // the list. Order doesn't matter (confirm). // Also split calls to findHops into intervals. if (scheme != RoutingScheme.SIMPLE) { broadcastRecommendations(); } } } }), 7, neighborBroadcastPeriod); if (enableSubpings) { int subpingSubPeriod = (1000 * subpingPeriod) / numProbeIntervals; safeScheduleMs(new Callable<Integer>() { int pingIter = 0; public Integer call() { if(hasJoined) { subping(pingIter); pingIter = (pingIter + 1) % numProbeIntervals; } return 1; } }, 5, 5521, subpingSubPeriod); // TODO should these initial offsets be constants? } scheduler.scheduleWithFixedDelay(safeRun(new Runnable() { public void run() { log("received/sent " + pingpongCount + " pings/pongs " + pingpongBytes + " bytes"); log("received/sent " + subprobeCount + " subprobes " + subprobeBytes + " bytes"); } }), pingDumpInitialDelay, pingDumpPeriod, TimeUnit.SECONDS); final InetAddress coordAddr = InetAddress.getByName(coordinatorHost); scheduler.schedule(safeRun(new Runnable() { private int count = 0; public void run() { if (count > joinRetries) { warn("exceeded max tries!"); System.exit(0); } else if (!hasJoined) { log("sending join to coordinator at " + coordinatorHost + ":" + basePort + " (try " + count++ + ")"); Join msg = new Join(); msg.addr = myCachedAddr; msg.src = myNid; // informs coord of orig id msg.port = myPort; sendObject(msg, coordAddr, basePort, (short)-1); log("waiting for InitMsg"); scheduler.schedule(this, 10, TimeUnit.SECONDS); } } }), joinDelay, TimeUnit.SECONDS); if (semAllJoined != null) semAllJoined.run(); } catch (IOException ex) { throw new RuntimeException(ex); } } } private final HashSet<Short> ignored = new HashSet<Short>(); public synchronized void ignore(short nid) { if (nid != myNid) { log("ignoring " + nid); ignored.add(nid); } } public synchronized void unignore(short nid) { if (nid != myNid) { log("unignoring " + nid); ignored.remove(nid); } } private ArrayList<NodeState> getAllReachableNodes() { ArrayList<NodeState> nbrs = new ArrayList<NodeState>(); for (NodeState n : otherNodes) if (n.isReachable) nbrs.add(n); return nbrs; } private static final byte SUBPING = 0, SUBPING_FWD = 1, SUBPONG = 2, SUBPONG_FWD = 3; private Subprobe subprobe(InetSocketAddress nod, long time, byte type) { Subprobe p = new Subprobe(); p.src = myAddr; p.nod = nod; p.time = time; p.type = type; return p; } private int subping(int pingIter) { // We will only subping a fraction of the nodes at this iteration // Note: this synch. statement is redundant until we remove global lock List<Short> nids = new ArrayList<Short>(); int bytes = 0, initCount = subprobeCount; for (Object obj : pingTable[pingIter]) { NodeState dst = (NodeState) obj; // TODO: dst.hop almost always != 0 (except when dst is new node) if (dst.info.id != myNid && dst.hop != 0) { NodeState hop = nodes.get(dst.hop); long time = System.currentTimeMillis(); InetSocketAddress nod = new InetSocketAddress(dst.info.addr, dst.info.port); InetSocketAddress hopAddr = new InetSocketAddress( hop.info.addr, hop.info.port); bytes += sendObj(subprobe(nod, time, SUBPING), hopAddr); nids.add(dst.info.id); subprobeCount++; } } if (bytes > 0) { log("sent subpings " + bytes + " bytes, to " + nids); subprobeBytes += bytes; } return subprobeCount - initCount; } private final Serialization probeSer = new Serialization(); private int sendObj(Object o, InetSocketAddress dst) { try { // TODO investigate directly writing to ByteBuffer ByteArrayOutputStream baos = new ByteArrayOutputStream(); probeSer.serialize(o, new DataOutputStream(baos)); byte[] buf = baos.toByteArray(); session.send(ByteBuffer.wrap(buf), dst); return buf.length; } catch (Exception ex) { err(ex); return 0; } } private void handleSubping(Subprobe p) { if (myAddr.equals(p.nod)) { sendObj(subprobe(p.nod, p.time, SUBPONG_FWD), p.src); log("subprobe", "direct subpong from/to " + p.src); } else { // we also checked for p.src because eventually we'll need to // forward the subpong back too; if we don't know him, no point in // sending a subping sendObj(subprobe(p.src, p.time, SUBPING_FWD), p.nod); // log("subprobe", "subping fwd from " + p.src + " to " + p.nod); } } private void handleSubpingFwd(Subprobe p) { sendObj(subprobe(p.nod, p.time, SUBPONG), p.src); // log("subprobe", "subpong to " + p.nod + " via " + p.src); } private void handleSubpong(Subprobe p) { sendObj(subprobe(p.src, p.time, SUBPONG_FWD), p.nod); // log("subprobe", "subpong fwd from " + p.src + " to " + p.nod); } private final Hashtable<InetSocketAddress, NodeState> addr2node = new Hashtable<InetSocketAddress, NodeState>(); private int addr2nid(InetSocketAddress a) { return addr2node.get(a).info.id; } private void handleSubpongFwd(Subprobe p, long receiveTime) { long latency = (receiveTime - p.time) / 2; log("subpong from " + addr2nid(p.nod) + " via " + addr2nid(p.src) + ": " + latency + ", time " + p.time); } private int pingAll(int pingIter) { log("pinging"); // We will only ping a fraction of the nodes at this iteration // Note: this synch. statement is redundant until we remove global lock int initCount = pingpongCount; PeerPing ping = new PeerPing(); ping.time = System.currentTimeMillis(); ping.src = myAddr; for (Object node : pingTable[pingIter]) { NodeInfo info = ((NodeState) node).info; if (info.id != myNid) { pingpongCount++; pingpongBytes += sendObj(ping, new InetSocketAddress(info.addr, info.port)); } } /* * send ping to the membership server (co-ord) - this might not be * required if everone makes their own local decision. i.e. each node * notices that no other node can reach a node (say X), then each node * sends the co-ord a msg saying that "i think X is dead". The sending * of this msg can be staggered in time so that the co-ord is not * flooded with mesgs. The co-ordinator can then make a decision on * keeping or removing node Y from the membership. On seeing a * subsequent msg from the co-ord that X has been removed from the * overlay, if a node Y has not sent its "i think X is dead" msg, it can * cancel this event. */ // Only ping the coordinator once per ping interval (not per // subinterval) if (pingIter == 0) { Ping p = new Ping(); p.time = System.currentTimeMillis(); NodeInfo tmp = nodes.get(myNid).info; p.info = new NodeInfo(); p.info.id = origNid; // note that the ping info uses the // original id p.info.addr = tmp.addr; p.info.port = tmp.port; pingpongCount++; pingpongBytes += sendObject(p, (short) 0); } // log("sent pings, " + totalSize + " bytes"); return pingpongCount - initCount; } private Object deserialize(ByteBuffer buf) { byte[] bytes = new byte[buf.limit()]; buf.get(bytes); try { return new Serialization().deserialize(new DataInputStream(new ByteArrayInputStream(bytes))); } catch (Exception ex) { err(ex); return null; } } private Hashtable<Short,Short> id2oid = new Hashtable<Short,Short>(); private Hashtable<Short,String> id2name = new Hashtable<Short,String>(); /** * coordinator's msg handling loop */ public final class CoordHandler implements ReactorHandler { /** * Generates non-repeating random sequence of short IDs, and keeps * track of how many are emitted. */ public final class IdGenerator { private final Iterator<Short> iter; private short counter; public IdGenerator() { List<Short> list = new ArrayList<Short>(); for (short s = 1; s < Short.MAX_VALUE; s++) { list.add(s); } Collections.shuffle(list); iter = list.iterator(); } public short next() { counter++; return iter.next(); } public short count() { return counter; } } private IdGenerator nidGen = new IdGenerator(); private void sendInit(short nid, Join join) { Init im = new Init(); im.id = nid; im.members = getMemberInfos(); sendObject(im, join.addr, join.port, (short)-1); } @Override public void handle(Session session, InetSocketAddress src, java.nio.ByteBuffer buf) { try { Msg msg = (Msg) deserialize(buf); if (msg == null) return; if (msg.session == sessionId) { if (msg instanceof Join) { final Join join = (Join) msg ; if (id2oid.values().contains(msg.src)) { // we already added this guy; just resend him the init msg sendInit(addr2id.get(join.addr), join); } else { // need to add this guy and send him the init msg (if there's space) if (!capJoins || coordNodes.size() < numNodesHint) { short newNid = nidGen.next(); addMember(newNid, join.addr, join.port, join.src); if (blockJoins) { if (coordNodes.size() >= numNodesHint) { // time to broadcast ims to everyone ArrayList<NodeInfo> memberList = getMemberInfos(); for (NodeInfo m : memberList) { Init im = new Init(); im.id = m.id; im.members = memberList; sendObject(im, m); } } } else { sendInit(newNid, join); broadcastMembershipChange(newNid); } if (coordNodes.size() == numNodesHint) { semAllJoined.run(); } } else if (capJoins && coordNodes.size() == numNodesHint) { Init im = new Init(); im.id = -1; im.members = new ArrayList<NodeInfo>(); sendObject(im, join.addr, join.port, (short)-1); } } } else if (coordNodes.containsKey(msg.src)) { log("recv." + msg.getClass().getSimpleName(), "from " + msg.src + " (oid " + id2oid.get(msg.src) + ", " + id2name.get(msg.src) + ")"); resetTimeoutAtCoord(msg.src); if (msg.version < currentStateVersion) { // this includes joins log("updating stale membership"); sendMembership(msg.src); } else if (msg instanceof Ping) { // ignore the ping } else { throw new Exception("can't handle message type here: " + msg.getClass().getName()); } } else { if ((!capJoins || coordNodes.size() < numNodesHint) && msg instanceof Ping) { Ping ping = (Ping) msg; log("dead." + ping.getClass().getSimpleName(), "from '" + ping.src + "' " + ping.info.addr.getHostName()); Short mappedId = addr2id.get(ping.info.addr); short nid; if (mappedId == null) { nid = nidGen.next(); addMember(nid, ping.info.addr, ping.info.port, ping.info.id); broadcastMembershipChange(nid); } else { nid = mappedId; } Init im = new Init(); im.id = nid; im.src = myNid; im.version = currentStateVersion; im.members = getMemberInfos(); sendObject(im, nid); } else { log("dead." + msg.getClass().getSimpleName(), "from '" + msg.src + "'"); } } } } catch (Exception ex) { err(ex); } } } /** * coordinator's msg handling loop */ public final class CoordReceiver extends IoHandlerAdapter { @Override public void messageReceived(IoSession session, Object obj) throws Exception { assert false; } } private int pingpongCount, pingpongBytes, subprobeCount, subprobeBytes; public final class NodeHandler implements ReactorHandler { public short getSimLatency(short nid) { long time = System.currentTimeMillis(); for (SimEvent e : simEvents) { if (time - startTime >= e.secs * 1000) { // make this event happen simLatencies.put(e.dst, e.lat); } } return simLatencies.get(nid); } @Override public void handle(Session session, InetSocketAddress src, ByteBuffer buf) { try { // TODO check SimpleMsg.session Object obj = deserialize(buf); if (obj == null) return; long receiveTime; if (obj instanceof Subprobe) { Subprobe p = (Subprobe) obj; subprobeBytes += buf.limit(); subprobeCount += 2; switch (p.type) { case SUBPING: handleSubping(p); break; case SUBPING_FWD: handleSubpingFwd(p); break; case SUBPONG: handleSubpong(p); break; case SUBPONG_FWD: // TODO move into the new worker thread when it's here receiveTime = System.currentTimeMillis(); handleSubpongFwd(p, receiveTime); break; default: assert false; } return; // TODO early exit is unclean } else if (obj instanceof PeerPing) { PeerPing ping = ((PeerPing) obj); PeerPong pong = new PeerPong(); pong.time = ping.time; pong.src = myAddr; pingpongBytes += sendObj(pong, ping.src) + buf.limit(); pingpongCount += 2; return; // TODO early exit is unclean } else if (obj instanceof PeerPong) { PeerPong pong = (PeerPong) obj; long rawRtt = System.currentTimeMillis() - pong.time; if (mode == RunMode.SIM) { short l = getSimLatency(addr2node.get(pong.src).info.id); if (l < resetLatency) { rawRtt = 2 * l; } } NodeState state = addr2node.get(pong.src); // if the rtt was astronomical, just treat it as a dropped packet if (rawRtt / 2 < Short.MAX_VALUE) { // we define "latency" as rtt/2; this should be // a bigger point near the top of this file short latency = (short) (rawRtt / 2); short nid = state.info.id; if (state != null) { resetTimeoutAtNode(nid); NodeState self = nodes.get(myNid); short oldLatency = self.latencies.get(nid); final short ewma; if (oldLatency == resetLatency) { ewma = latency; } else { ewma = (short) (smoothingFactor * latency + (1 - smoothingFactor) * oldLatency); } log("latency", state + " = " + latency + ", ewma " + ewma + ", time " + pong.time); self.latencies.put(nid, ewma); } else { log("latency", "some " + nid + " = " + latency); } pingpongCount++; pingpongBytes += buf.limit(); } return; // TODO early exit is unclean } Msg msg = (Msg) obj; if ((msg.src == 0 || nodes.containsKey(msg.src) || msg instanceof Ping) && msg.session == sessionId) { NodeState state = nodes.get(msg.src); log("recv." + msg.getClass().getSimpleName(), "from " + msg.src + " len " + ((ByteBuffer) buf).limit()); // for other messages, make sure their state version is // the same as ours if (msg.version > currentStateVersion) { if (msg instanceof Membership && hasJoined) { currentStateVersion = msg.version; Membership m = (Membership) msg; assert myNid == m.yourId; updateMembers(m.members); } else if (msg instanceof Init) { hasJoined = true; if (semAllJoined != null) semAllJoined.run(); if (((Init) msg).id == -1) session.close(); handleInit((Init) msg); } else { // i am out of date - wait until i am updated } } else if (msg.version == currentStateVersion) { // from coordinator if (msg instanceof Membership) { Membership m = (Membership) msg; assert myNid == m.yourId; updateMembers(m.members); } else if (msg instanceof Measurements) { resetTimeoutOnRendezvousClient(msg.src); updateMeasurements((Measurements) msg); } else if (msg instanceof RoutingRecs) { RoutingRecs recs = (RoutingRecs) msg; handleRecommendations(recs); log("got recs " + routesToString(recs.recs)); } else if (msg instanceof Ping || msg instanceof Pong || msg instanceof Init) { // nothing to do, already handled above } else { throw new Exception("can't handle that message type"); } } else { log("stale." + msg.getClass().getSimpleName(), "from " + msg.src + " version " + msg.version + " current " + currentStateVersion); } } else { // log("ignored." + msg.getClass().getSimpleName(), "ignored from " + msg.src + " session " + msg.session); } } catch (Exception ex) { err(ex); } } } /** * receiver's msg handling loop */ public final class Receiver extends IoHandlerAdapter { @Override public void messageReceived(IoSession session, Object buf) throws Exception { assert false; } } /** * If we don't hear from a node for this number of seconds, then consider * them dead. */ private int membershipTimeout; private Hashtable<Short, ScheduledFuture<?>> timeouts = new Hashtable<Short, ScheduledFuture<?>>(); /** * a coord-only method * * @param nid */ private void resetTimeoutAtCoord(final short nid) { if (coordNodes.containsKey(nid)) { ScheduledFuture<?> oldFuture = timeouts.get(nid); if (oldFuture != null) { oldFuture.cancel(false); } ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { removeMember(nid); } }), membershipTimeout, TimeUnit.SECONDS); timeouts.put(nid, future); } } private final int clientTimeout; private final Hashtable<Short, ScheduledFuture<?>> rendezvousClientTimeouts = new Hashtable<Short, ScheduledFuture<?>>(); private void resetTimeoutOnRendezvousClient(final short nid) { final NodeState node = nodes.get(nid); // TODO: wrong semantics for isReachable if (!node.isReachable) return; ScheduledFuture<?> oldFuture = rendezvousClientTimeouts.get(nid); if (oldFuture != null) { oldFuture.cancel(false); } if (rendezvousClients.add(node)) { log("rendezvous client " + node + " added"); } ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { if (rendezvousClients.remove(node)) { log("rendezvous client " + node + " removed"); } } }), clientTimeout, TimeUnit.SECONDS); rendezvousClientTimeouts.put(nid, future); } private void resetTimeoutAtNode(final short nid) { if (nodes.containsKey(nid)) { ScheduledFuture<?> oldFuture = timeouts.get(nid); if (oldFuture != null) { oldFuture.cancel(false); } final NodeState node = nodes.get(nid); if (!node.isReachable) { log(nid + " reachable"); if (node.hop == 0) { node.isHopRecommended = false; node.cameUp = true; node.hop = nid; } } node.isReachable = true; ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { if (nodes.containsKey(nid)) { log(nid + " unreachable"); node.isReachable = false; nodes.get(myNid).latencies.remove(nid); // TODO: do we really want this? rendezvousClients.remove(node); findPaths(node, false); } } }), linkTimeout, TimeUnit.SECONDS); timeouts.put(nid, future); } } /** * a coordinator-only method */ private NodeInfo addMember(short newNid, InetAddress addr, int port, short origId) { NodeInfo info = new NodeInfo(); info.id = newNid; info.addr = addr; info.port = port; coordNodes.put(newNid, info); id2oid.put(newNid, origId); id2name.put(newNid, addr.getHostName()); addr2id.put(addr, newNid); log("adding new node: " + newNid + " oid " + origId + " name " + id2name.get(newNid)); currentStateVersion++; resetTimeoutAtCoord(newNid); return info; } private final AtomicBoolean membersChanged = new AtomicBoolean(); /** * a coordinator-only method * * @param exceptNid - if this is 0, then we must have been called by the * periodic membership-broadcast daemon thread, so actually send stuff; * otherwise, we should just signal to the daemon thread a pending change */ private void broadcastMembershipChange(short exceptNid) { if (exceptNid == 0 || membershipBroadcastPeriod == 0) { for (short nid : coordNodes.keySet()) { if (nid != exceptNid) { sendMembership(nid); } } } } ArrayList<NodeInfo> getMemberInfos() { return new ArrayList<NodeInfo>(coordNodes.values()); } /** * a coordinator-only method * * throttles these messages so they're sent at most once per second */ private void sendMembership(short nid) { Membership msg = new Membership(); msg.yourId = nid; msg.members = getMemberInfos(); sendObject(msg, coordNodes.get(nid)); } /** * a coordinator-only method * * NOTE: there is a hack workaround here for sim mode, because addr2id is * not storing unique host:port combos, only unique hosts. * * @param nid */ private void removeMember(short nid) { log("removing dead node " + nid + " oid " + id2oid.get(nid) + " " + id2name.get(nid)); id2oid.remove(nid); NodeInfo info = coordNodes.remove(nid); Short mid = addr2id.remove(info.addr); if (mode != RunMode.SIM) assert mid != null; currentStateVersion++; broadcastMembershipChange(nid); } /** * updates our member state. modifies data structures as necessary to * maintain invariants. * * @param newNodes */ private void updateMembers(List<NodeInfo> newNodes) { HashSet<Short> newNids = new HashSet<Short>(); for (NodeInfo node : newNodes) newNids.add(node.id); // add new nodes for (NodeInfo node : newNodes) if (!nodes.containsKey(node.id)) { NodeState newNode = new NodeState(node); // Choose a subinterval for this node during which we will ping it int loc = rand.nextInt(numProbeIntervals); pingTable[loc].add(newNode); pingId.put(newNode, loc); nodes.put(node.id, newNode); addr2node.put(new InetSocketAddress(node.addr, node.port), newNode); if (node.id != myNid) resetTimeoutAtNode(node.id); } // Remove nodes. We need toRemove to avoid // ConcurrentModificationException on the table that we'd be looping // through. for (NodeInfo node : newNodes) newNids.add(node.id); HashSet<Pair<Short, NodeState>> toRemove = new HashSet<Pair<Short,NodeState>>(); for (Map.Entry<Short, NodeState> entry : nodes.entrySet()) if (!newNids.contains(entry.getKey())) toRemove.add(Pair.of(entry.getKey(), entry.getValue())); for (Pair<Short, NodeState> pair : toRemove) { short nid = pair.first; NodeState node = pair.second; // Remove the node from the subinterval during which it // was pinged. int index = pingId.remove(node); pingTable[index].remove(node); addr2node.remove(new InetSocketAddress(node.info.addr, node.info.port)); NodeState n = nodes.remove(nid); assert n != null; } // consistency cleanups: check that all nid references are still valid nid's for (NodeState state : nodes.values()) { if (state.hop != 0 && !newNids.contains(state.hop)) { state.hop = state.info.id; state.isHopRecommended = false; } for (Iterator<Short> i = state.hopOptions.iterator(); i.hasNext();) if (!newNids.contains(i.next())) i.remove(); HashSet<Short> garbage = new HashSet<Short>(); for (short nid : state.latencies.keySet()) if (!newNids.contains(nid)) garbage.add(nid); for (short nid : garbage) state.latencies.remove(nid); // Clear the remote failures hash, since this node will now have a different // set of default rendezvous nodes. state.remoteFailures.clear(); } // // regenerate alternative views of this data // NodeState self = nodes.get(myNid); assert self != null; memberNids.clear(); memberNids.addAll(newNids); Collections.sort(memberNids); otherNodes.clear(); otherNodes.addAll(nodes.values()); otherNodes.remove(self); // ABOVE IS INDEPENDENT OF GRID // numRows needs to be >= numCols numRows = (short) Math.ceil(Math.sqrt(nodes.size())); numCols = (short) Math.ceil((double) nodes.size() / (double) numCols); grid = new NodeState[numRows][numCols]; // These are used temporarily for setting up the defaults Hashtable<NodeState, Short> gridRow = new Hashtable<NodeState, Short>(); Hashtable<NodeState, Short> gridColumn = new Hashtable<NodeState, Short>(); List<Short> nids = memberNids; short i = 0; // node counter short numberOfNodes = (short) memberNids.size(); short lastColUsed = (short) (numCols - 1); // default is for the full grid gridLoop: for (short r = 0; r < numRows; r++) { for (short c = 0; c < numCols; c++) { // Are there any more nodes to put into the grid? if(i > numberOfNodes - 1) { // Assert: We shouldn't create a grid with an empty last row. assert (r == numRows - 1) && (c > 0); lastColUsed = (short) (c - 1); break gridLoop; } grid[r][c] = nodes.get(nids.get(i++)); gridRow.put(grid[r][c], r); gridColumn.put(grid[r][c], c); } } // Algorithm described in model_choices.tex // Set up hash of each node's default rendezvous servers // Note: a node's default rendezvous servers will include itself. nodeDefaultRSs.clear(); for(NodeState node : nodes.values()) { int rn = gridRow.get(node); int cn = gridColumn.get(node); // We know the number of elements. Should be [1/(default load factor)]*size HashSet<NodeState> nodeDefaults = new HashSet<NodeState>((int) 1.4*(numRows + numCols - 1)); // If this is not the last row if(rn < numRows - 1) { // Add the whole row for (int c1 = 0; c1 < numCols; c1++) nodeDefaults.add(grid[rn][c1]); // If this is before the last col used (on last row) if(cn <= lastColUsed) { // Add whole column for (int r1 = 0; r1 < numRows; r1++) nodeDefaults.add(grid[r1][cn]); } else { // Add column up until last row for (int r1 = 0; r1 < numRows-1; r1++) nodeDefaults.add(grid[r1][cn]); // Add corresponding node from the last row (column rn); // only for the first lastColUsed rows. if(rn <= lastColUsed) { nodeDefaults.add(grid[numRows-1][rn]); } } } else { // This is the last row // Add whole column for (int r1 = 0; r1 < numRows; r1++) nodeDefaults.add(grid[r1][cn]); // Add whole last row up till lastColUsed for (int c1 = 0; c1 <= lastColUsed; c1++) nodeDefaults.add(grid[rn][c1]); // Add row cn for columns > lastColUsed for (int c1 = lastColUsed+1; c1 < numCols; c1++) nodeDefaults.add(grid[cn][c1]); } // Could also make an array of nodeDefaults, for less memory usage/faster nodeDefaultRSs.put(node, nodeDefaults); } // BELOW IS INDEPENDENT OF GRID /* * simply forget about all our neighbors. thus, this forgets all our * failover clients and servers. since the grid is different. if this * somehow disrupts route computation, so be it - it'll only last for a * period. * * one worry is that others who miss this member update will continue to * broadcast to us. this is a non-issue because we ignore stale * messages, and when they do become updated, they'll forget about us * too. */ // Set up rendezvous clients rendezvousClients.clear(); for (NodeState cli : nodeDefaultRSs.get(self)) { // TODO: wrong semantics for isReachable if (cli.isReachable && cli != self) rendezvousClients.add(cli); } // Put timeouts for all new rendezvous clients. If they can never // reach us, we should stop sending them recommendations. for (final NodeState clientNode : rendezvousClients) { ScheduledFuture<?> oldFuture = rendezvousClientTimeouts.get(clientNode.info.id); if (oldFuture != null) { oldFuture.cancel(false); } ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { public void run() { if (rendezvousClients.remove(clientNode)) { log("rendezvous client " + clientNode + " removed"); } } }), clientTimeout, TimeUnit.SECONDS); rendezvousClientTimeouts.put(clientNode.info.id, future); } // Set up default rendezvous servers to all destinations // Note: In an earlier version of the code, for a destination in // our row/col, we did not add rendezvous nodes which are not // reachable. We no longer do this (but it shouldn't matter). defaultRendezvousServers.clear(); for (NodeState dst : nodes.values()) { // note: including self HashSet<NodeState> rs = new HashSet<NodeState>(); defaultRendezvousServers.put(dst.info.id, rs); // Take intersection of this node's default rendezvous and // the dst's default rendezvous servers, excluding self. // Running time for outer loop is 2n^{1.5} since we are using // a HashSet for quick lookups. Could be optimized further, // but code simplicity is preferred. HashSet<NodeState> dstDefaults = nodeDefaultRSs.get(dst); for (NodeState selfRS : nodeDefaultRSs.get(self)) { // Don't add self because we will never receive routing // recommendation messages from ourselves. if (selfRS != self && dstDefaults.contains(selfRS)) rs.add(selfRS); } } // Create empty set for default rendezvous servers, will be filled in // getAllRendezvousServers() rendezvousServers.clear(); for (Entry<Short, HashSet<NodeState>> entry : defaultRendezvousServers.entrySet()) { rendezvousServers.put(entry.getKey(), new HashSet<NodeState>()); } lastRendezvousServers.clear(); log("state " + currentStateVersion + ", mbrs " + nids); } /** * @param n * @param remoteNid * @return */ private boolean isFailedRendezvous(NodeState n, NodeState remote) { // TODO: isReachable semantics should be fixed (but how?) // NOTE: We may never receive this node's measurements since // it is our rendezvous client, but we don't offer to be // its rendezvous server. This is why we check for // remote in the recommendations response rather than // the measurements. // This assumes that the node's reachability is indicative // of its ability to send us recommendation messages. return !n.isReachable || n.remoteFailures.contains(remote); } /** * @return failoverClients `union` nodes in my row and col (wherever i occur) */ private ArrayList<NodeState> getAllRendezvousClients() { ArrayList<NodeState> list = new ArrayList<NodeState>(rendezvousClients); Collections.sort(list); return list; } private String mkString(HashSet<NodeState> ns, String glue) { String s = ""; for (NodeState n : ns) { s += n.info.id + glue; } return s; } /** * makes one pass over the metaset of all rendezvous servers, removing any * failed rendezvous from the individual sets. * * for the simple routing scheme, this is the full set of nodes. as a * result, measurements are broadcast to everyone, as intended. (note that * there are no routing recommendation messages in this scheme.) * * OLD ALGO * * for dst * if dst is not down * rs = dst's current rendezvous servers * ds = dst's default rendezvous servers * if any of ds are working to dst and rs is not ds * rs = working subset of ds * if rs = [] * rs += random node from dst's row/col * else * rs -= any failed rs * note that this may leave rs empty for the coming round * this is what we want bc it will delay failover-finding till the next round * * NEW ALGO * * // CHANGES START * build a hashtable for all rendezvous nodes currently used * call this F * // CHANGES END * for dst * if dst is not down * rs = dst's current rendezvous servers * ds = dst's default rendezvous servers * if any of ds are working to dst and rs is not ds * rs = working subset of ds * if rs = [] * // CHANGES START * for active failover in dst's default rendezvous nodes (according to F) * if failover works to dst, choose it as failover for dst as well * choose rand node from dst's default rendezvous nodes that is not currently in use * rs += whatever we chose; F += whatever we chose * // CHANGES END * else * rs -= any failed rs * note that this may leave rs empty for the coming round * this is what we want bc it will delay failover-finding till the next round * * @return the union of all the sets of non-failed rendezvous servers. */ private ArrayList<NodeState> getAllRendezvousServers() { NodeState self = nodes.get(myNid); HashSet<NodeState> currentRSs = new HashSet<NodeState>(); HashSet<NodeState> allDefaults = nodeDefaultRSs.get(self); // first, prepare currentRS so that we can share/reuse // rendezvous servers for (NodeState node : otherNodes) { for (NodeState n : rendezvousServers.get(node.info.id)) { // if this is an actual failover if (!allDefaults.contains(n)) currentRSs.add(n); } } // these are the rendezvous servers that we want to sent our // measurements to HashSet<NodeState> servers = new HashSet<NodeState>(); // iterate over all destination nodes that are not us for (NodeState dst : otherNodes) { // if we believe that the node is not down // TODO (high priority): since dst.hop is never set to 0, this will always // be called, and we will always attempt to find a route to the // destination, even if there is a node failure. if (dst.hop != 0) { // this is our current (active) set of rendezvous servers HashSet<NodeState> rs = rendezvousServers.get(dst.info.id); // check if any of our default rendezvous servers are once // more available; if so, add them back HashSet<NodeState> defaults = defaultRendezvousServers.get(dst.info.id); // we always want to try talking to our default rendezvous // servers if we think they're reachable for (NodeState r : defaults) if (r.isReachable) servers.add(r); // rs consists of either default rendezvous servers or // non-default rendezvous, but never a mix of both; test // which type it is boolean hasDefaultsOnly = rs.isEmpty() ? true : defaults.contains(rs.iterator().next()); // the following code attempts to add default rendezvous // servers back into rs HashSet<NodeState> old = new HashSet<NodeState>(rs); if (hasDefaultsOnly) { // if any default rendezvous servers are in use, then // don't clear rs; simply add any more default servers // that are working if (!defaults.equals(rs)) for (NodeState r : defaults) if (!isFailedRendezvous(r, dst)) rs.add(r); } else { // if no default rendezvous servers are in use, then // try adding any that are working; if any are working, // we make sure to first clear rs boolean cleared = false; for (NodeState r : defaults) { if (!isFailedRendezvous(r, dst)) { if (!cleared) { rs.clear(); cleared = true; } rs.add(r); } } } if (!old.equals(rs)) { log("restored rendezvous server for " + dst + " from " + old + " to " + rs); } // Note that rs not being empty means that in previous iterations the nodes in // rs were alive, and either we did not ever receive any recommendations from them, // or the last recommendation we received from it did include routing information // for dst (and so there is no hint of a remote failure). In either case, as of // the previous iteration, n.remoteFailures.contains(remote) == false. // if { any node in rs has n.remoteFailures.contains(remote) == true, then we know that we // did receive a routing recommendation from it since the last round, and it is alive. // Remove it from rs and do nothing else this step, as the destination is likely dead. // set skipIteration=true. } // else { // If !n.isReachable for any node n in rs, remove it from rs. We don't expect it to be // helpful for routing ever. // If rs is now empty, choose a failover rendezvous node (in this iteration) // Else, any remaining nodes have n.remoteFailures.contains(remote) == false, which means // either that we did not yet receive a routing message from it, or we did and the dst // is reachable. In either case, do nothing. If this node is still alive, we will // eventually receive a routing recommendation from it. Otherwise, very soon we will find // that !n.isReachable. We add a bit of latency for waiting, but should be okay. // } /* * If we think a remote failure could have occured, don't immediately look * for failovers. The next period, we will have received link states from * our neighbors, from which we can determine whether dst is just down. * * The reason for this is that if a node fails, we don't want the entire network to flood * the row/col of that downed node (no need for failovers period). */ boolean skipIteration = false; // We use the iterator so that we can safely remove from the set for (Iterator<NodeState> i = rs.iterator(); i.hasNext();) { NodeState r = i.next(); if(r.remoteFailures.contains(dst)) { i.remove(); skipIteration = true; } else if(!r.isReachable) { i.remove(); } } if (!skipIteration && rs.isEmpty() && scheme != RoutingScheme.SQRT_NOFAILOVER) { // create debug string String s = "defaults"; for (NodeState r : defaults) { s += " " + r.info.id + ( !r.isReachable ? " unreachable" : " <-/-> " + mkString(r.remoteFailures, ",") ); } final String report = s; // look for failovers HashSet<NodeState> cands = new HashSet<NodeState>(); // first, start by looking at the failovers that are // currently in use which are default rs's for this dst, so // that we can share when possible. that is, if we know that a // failover works for a destination, keep using it. HashSet<NodeState> dstDefault = nodeDefaultRSs.get(dst); // currentRSs may contain rendezvous nodes which are no longer alive // or useful for reaching the destination for(NodeState f : currentRSs) { if (dstDefault.contains(f) && !isFailedRendezvous(f, dst)) { cands.add(f); } } if (cands.isEmpty()) { // only once we have determined that no current // failover works for us do we go ahead and randomly // select a new failover. this is a blind choice; // we don't have these node's routing recommendations, // so we could not hope to do better. // TODO (low priority): one exception is if any of the candidates // are rendezvous clients for us, in which case we // will have received their link state, and we could // smartly decide whether they can reach the destination. // Not obvious if we should (or how) take advantage of this. for(NodeState cand : dstDefault) { if (cand != self && cand.isReachable) cands.add(cand); } } // if any of the candidates are already selected to be in // 'servers', we want to make sure that we only choose from // these choices. HashSet<NodeState> candsInServers = new HashSet<NodeState>(); for (NodeState cand : cands) if (servers.contains(cand)) candsInServers.add(cand); // choose candidate uniformly at random ArrayList<NodeState> candsList = new ArrayList<NodeState>(candsInServers.isEmpty() ? cands : candsInServers); if (candsList.size() == 0) { log("no failover candidates! giving up; " + report); } else { NodeState failover = candsList.get(rand.nextInt(candsList.size())); // TODO (low priority): prev rs = ... is now broken since rs is empty log("new failover for " + dst + ": " + failover + ", prev rs = " + rs + "; " + report); rs.add(failover); // share this failover in this routing iteration too if (!allDefaults.contains(failover)) { currentRSs.add(failover); } } } else if (rs.isEmpty()) { log("all rs to " + dst + " failed"); System.out.println("ALL FAILED!"); } // Add any nodes that are in rs to the servers set for (NodeState r : rs) { servers.add(r); } } // end if dst.hop != 0 (destination is alive) } // end while loop over destinations ArrayList<NodeState> list = new ArrayList<NodeState>(servers); Collections.sort(list); return list; } public static enum RoutingScheme { SIMPLE, SQRT, SQRT_NOFAILOVER, SQRT_RC_FAILOVER, SQRT_SPECIAL }; private final RoutingScheme scheme; private void printMembers() { String s = "members:"; for (NodeInfo info : coordNodes.values()) { s += "\n " + info.id + " oid " + id2oid.get(info.id) + " " + id2name.get(info.id) + " " + info.port; } log(s); } // PERF private void printGrid() { String s = "grid:"; if (grid != null) { for (int i = 0; i < numRows; i++) { s += "\n "; for (int j = 0; j < numCols; j++) { s += "\t" + grid[i][j]; } } } log(s); } /** * in the sqrt routing scheme: for each neighbor, find for him the min-cost * hops to all other neighbors, and send this info to him (the intermediate * node may be one of the endpoints, meaning a direct route is cheapest). * * in the sqrt_special routing scheme, we instead find for each neighbor the * best intermediate other neighbor through which to route to every * destination. this still needs work, see various todos. * * a failed rendezvous wrt some node n is one which we cannot reach * (proximal failure) or which cannot reach n (remote failure). when all * current rendezvous to some node n fail, then we find a failover from node * n's row and col, and include it in our neighbor set. by befault, this * situation occurs when a row-col rendezvous pair fail. it can also occur * with any of our current failovers. */ private void broadcastRecommendations() { ArrayList<NodeState> clients = getAllRendezvousClients(); ArrayList<NodeState> dsts = new ArrayList<NodeState>(clients); dsts.add(nodes.get(myNid)); Collections.sort(dsts); int totalSize = 0; for (NodeState src : clients) { ArrayList<Rec> recs = new ArrayList<Rec>(); // dst <- nbrs, hop <- any findHops(dsts, memberNids, src, recs); /* * TODO: need to additionally send back info about *how good* the * best hop is, so that the receiver can decide which of the many * recommendations to accept */ if (scheme == RoutingScheme.SQRT_SPECIAL) { // dst <- any, hop <- nbrs findHopsAlt(memberNids, dsts, src, recs); } RoutingRecs msg = new RoutingRecs(); msg.recs = recs; totalSize += sendObject(msg, src.info.id); } log("sent recs, " + totalSize + " bytes, to " + clients); } /** * Given the src, find for each dst in dsts the ideal hop from hops, * storing these into recs. This may choose the dst itself as the hop. */ private void findHops(ArrayList<NodeState> dsts, ArrayList<Short> hops, NodeState src, ArrayList<Rec> recs) { for (NodeState dst : dsts) { if (src != dst) { short min = resetLatency; short minhop = -1; for (short hop : hops) { if (hop != src.info.id) { int src2hop = src.latencies.get(hop); int dst2hop = dst.latencies.get(hop); int latency = src2hop + dst2hop; // DEBUG // log(src + "->" + hop + " is " + src2hop + ", " + hop + // "->" + dst + " is " + dst2hop + ", sum " + // latency); if (latency < min) { min = (short) latency; minhop = hop; } } } // it's possible for us to have not found an ideal hop. this // may be counter-intuitive, since even if src<->dst is broken, // the fact that both are our clients means we should be able // to serve as a hop. however it may be that either one of them // was, or we were, recently added as a member to the network, // so they never had a chance to ping us yet (and hence we're // missing from their measurements). (TODO also is it possible // that we're missing their measurement entirely? are all // clients necessarily added on demand by measurement packets?) // what we can do is to try finding our own latency to the hop // (perhaps we've had a chance to ping them), and failing that, // estimating the latency (only if one of us was newly added). // however, these errors are transient anyway - by the next // routing period, several pings will have taken place that // would guarantee (or there was a failure, and eventually one // of {src,dst} will fall out of our client set). if (minhop != -1) { short directLatency = src.latencies.get(dst.info.id); Rec rec = new Rec(); rec.dst = dst.info.id; // We require that a recommended route (if not the direct // route and if direct route is working) yield at least a // 5% reduction in latency. // - if min-cost route is the direct route, just use it // - if direct-cost route is infinite, then no point // comparing to the min-cost hop route // - if min-cost route is not much better than direct // route, use direct route if (minhop == dst.info.id || directLatency == resetLatency || min * directBonus < directLatency) { // TODO (high priority): can you get a short overflow with above? directBonus is a double rec.via = minhop; recs.add(rec); } else { // At this point, // min-cost route is not the direct route && // src->dst is *not* infinite && // min * directBonus >= src->dst // So, recommend the direct route, if that is working. rec.via = dst.info.id; recs.add(rec); } } } } } private void findHopsAlt(ArrayList<Short> dsts, ArrayList<NodeState> hops, NodeState src, ArrayList<Rec> recs) { for (short dst : dsts) { if (src.info.id != dst && nodes.get(dst).isReachable) { short min = resetLatency; short minhop = -1; for (NodeState hop : hops) { if (hop != src) { short src2hop = src.latencies.get(hop.info.id); short dst2hop = hop.latencies.get(dst); short latency = (short) (src2hop + dst2hop); if (latency < min) { min = latency; minhop = hop.info.id; } } } assert minhop != -1; Rec rec = new Rec(); rec.dst = dst; rec.via = minhop; recs.add(rec); } } } private String routesToString(ArrayList<Rec> recs) { String s = ""; for (Rec rec : recs) s += rec.via + "->" + rec.dst + " "; return s; } private Serialization senderSer = new Serialization(); private int sendObject(final Msg o, InetAddress addr, int port, short nid) { o.src = myNid; o.version = currentStateVersion; o.session = sessionId; try { /* * note that it's unsafe to re-use these output streams - at * least, i don't know how (reset() is insufficient) */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); senderSer.serialize(o, new DataOutputStream(baos)); byte[] buf = baos.toByteArray(); String who = nid >= 0 ? "" + nid : (addr + ":" + port); log("send." + o.getClass().getSimpleName(), "to " + who + " len " + buf.length); if (!ignored.contains(nid)) { session.send(ByteBuffer.wrap(buf), new InetSocketAddress(addr, port)); } else { log("droppng packet sent to " + who); } return buf.length; } catch (Exception ex) { throw new RuntimeException(ex); } } private int sendObject(final Msg o, NodeInfo info, short nid) { return sendObject(o, info.addr, info.port, nid); } private int sendObject(final Msg o, NodeInfo info) { return sendObject(o, info, (short)-1); } private int sendObject(final Msg o, short nid) { return nid != myNid ? sendObject(o, nid == 0 ? coordNode : (myNid == 0 ? coordNodes.get(nid) : nodes.get(nid).info), nid) : 0; } private void broadcastMeasurements(ArrayList<NodeState> servers) { ShortShortMap latencies = nodes.get(myNid).latencies; Measurements rm = new Measurements(); rm.probeTable = new short[memberNids.size()]; for (int i = 0; i < rm.probeTable.length; i++) rm.probeTable[i] = latencies.get(memberNids.get(i)); rm.inflation = new byte[rm.probeTable.length]; int totalSize = 0; for (NodeState nbr : servers) { totalSize += sendObject(rm, nbr.info.id); } log("sent measurements, " + totalSize + " bytes, to " + servers); } private void updateMeasurements(Measurements m) { NodeState src = nodes.get(m.src); for (int i = 0; i < m.probeTable.length; i++) src.latencies.put(memberNids.get(i), m.probeTable[i]); // TODO we aren't setting node.{hop,cameUp,isHopRecommended=false}... } private void handleRecommendations(RoutingRecs msg) { ArrayList<Rec> recs = msg.recs; NodeState r = nodes.get(msg.src); r.dstsPresent.clear(); r.remoteFailures.clear(); for (Rec rec : recs) { r.dstsPresent.add(rec.dst); if (nodes.get(rec.via).isReachable) { if (scheme == RoutingScheme.SQRT_SPECIAL) { /* * TODO: add in support for processing sqrt_special * recommendations. first we need to add in the actual cost of * the route to these recommendations (see * broadcastRecommndations), then we need to compare all of * these and see which ones were better. a complication is that * routing recommendation broadcasts are not synchronized, so * while older messages may appear to have better routes, there * must be some threshold in time past which we disregard old * latencies. must keep some history */ } else { // blindly trust the recommendations NodeState node = nodes.get(rec.dst); if (node.hop == 0) node.cameUp = true; node.isHopRecommended = true; node.hop = rec.via; } } } if (scheme != RoutingScheme.SQRT_SPECIAL) { /* * get the full set of dsts that we depend on this node for. note * that the set of nodes it's actually serving may be different. */ // TODO (low priority): just use dstsPresent instead of remoteFailures for (NodeState dst : nodeDefaultRSs.get(r)) { if (!r.dstsPresent.contains(dst.info.id)) { /* * there was a comm failure between this rendezvous and the * dst for which this rendezvous did not provide a * recommendation. this a proximal rendezvous failure, so that if * necessary during the next phase, we will find failovers. */ r.remoteFailures.add(dst); } } } } /** * counts the number of nodes that we can reach - either directly, through a * hop, or through any rendezvous client. * * @return */ private int countReachableNodes() { /* * TODO need to fix up hopOptions so that it actually gets updated * correctly, since currently things are *never* removed from it (they * need to expire) */ NodeState myState = nodes.get(myNid); int count = 0; for (NodeState node : otherNodes) { count += node.hop != 0 ? 1 : 0; } return count; } /** * Counts the number of paths to a particular node. * * Note that this does not get run whenever nodes become reachable, only * when they become unreachable (and also in batch periodically). * Furthermore, we do not run this whenever we get a measurement packet. * The reason for these infelicities is one of performance. * * The logic among hop, isHopRecommended, and cameUp is tricky. */ private int findPaths(NodeState node, boolean batch) { ArrayList<NodeState> clients = getAllRendezvousClients(); ArrayList<NodeState> servers = lastRendezvousServers; HashSet<NodeState> options = new HashSet<NodeState>(); short min = resetLatency; short nid = node.info.id; boolean wasDead = node.hop == 0; NodeState self = nodes.get(myNid); // we would like to keep recommended nodes (they should be the best // choice, but also we have no ping data). but if it was not obtained // via recommendation (i.e., a previous findPaths() got this hop), then // we should feel free to update it. if (node.hop == 0) { node.isHopRecommended = false; } else { // we are not adding the hop if (!node.isHopRecommended) { node.hop = 0; } } // Unless node.hop == 0, this code below is useless // We would like to measure this... // keep track of subping. // direct hop if (node.isReachable) { options.add(node); if (!node.isHopRecommended) { node.hop = node.info.id; min = self.latencies.get(node.info.id); } } // find best rendezvous client. (`clients` are all reachable.) for (NodeState client : clients) { int val = client.latencies.get(nid); if (val != resetLatency) { options.add(client); val += self.latencies.get(client.info.id); if (!node.isHopRecommended && val < min) { node.hop = client.info.id; min = (short) val; } } } // see if a rendezvous server can serve as the hop. (can't just iterate // through hopOptions, because that doesn't tell us which server to go // through.) using the heuristic of just our latency to the server for (NodeState server : servers) { if (server.dstsPresent.contains(nid)) { options.add(server); short val = self.latencies.get(server.info.id); if (node.hop == 0 && val < min) { node.hop = server.info.id; min = val; } } } boolean isDead = node.hop == 0; // seems that (!isDead && wasDead) can be true, if a hop is found here // from a measurement (from a rclient). boolean cameUp = !isDead && wasDead || node.cameUp; boolean wentDown = isDead && !wasDead; // reset node.cameUp node.cameUp = false; // we always print something in non-batch mode. we also print stuff if // there was a change in the node's up/down status. if a node is reachable // then findPaths(node,) will only be called during batch processing, and // so wasDead will have been set either by the last unreachable call or by // the previous batch call. thus, the first batch call after a node goes // up, the "up" message will be printed. if (!batch || cameUp || wentDown) { String stateChange = cameUp ? " up" : (wentDown ? " down" : ""); log("node " + node + stateChange + " hop " + node.hop + " total " + options.size()); } return options.size(); } /** * Counts the avg number of one-hop or direct paths available to nodes * Calls findPaths(node) for all other nodes. This code is supposed to * a) find out a node is alive, and b) find the optimal one-hop route to * this destination. * @return */ private Pair<Integer, Integer> findPathsForAllNodes() { NodeState myState = nodes.get(myNid); int count = 0; int numNodesReachable = 0; for (NodeState node : otherNodes) { int d = findPaths(node, true); count += d; numNodesReachable += d > 0 ? 1 : 0; } if (numNodesReachable > 0) count /= numNodesReachable; return Pair.of(numNodesReachable, count); } public void quit() { doQuit.set(true); } private class NodeState implements Comparable<NodeState> { public String toString() { return "" + info.id; } /** * not null */ public final NodeInfo info; /** * updated in resetTimeoutAtNode(). if hop == 0, this must be false; if * hop == the nid, this must be true. * * this should also be made to correspond with the appropriate latencies in myNid */ public boolean isReachable = true; /** * the last known latencies to all other nodes. missing entry implies * resetLatency. this is populated/valid for rendezvous clients. * * invariants: * - keyset is a subset of current members (memberNids); enforced in * updateMembers() * - keyset contains only live nodes; enforced in resetTimeoutAtNode() * - values are not resetLatency * - undefined if not a rendezvous client */ public final ShortShortMap latencies = new ShortShortMap(resetLatency); /** * the recommended intermediate hop for us to get to this node, or 0 if * no way we know of to get to that node, and thus believe the node is * down. * * invariants: * - always refers to a member or 0; enforced in updateMembers() * - never refers to dead node; enforced in resetTimeoutAtNode() * - may be nid (may be dst) * - initially defaults to dst (since we don't know hops to it) * - never refers to the owning neuronnode (never is src) * - cannot be nid if !isReachable */ public short hop; /** * this is set at certain places where we determine that a node is * alive, and reset in the next findPaths(). the only reason we need * this is to help produce the correct logging output for the * effectiveness timing analysis. */ public boolean cameUp; /** * this indicates how we got this hop. this is set in * handleRecommendations(), reset in resetTimeoutAtNode(), and * read/reset from batch-mode findPaths(). if it was recommended to * us, then we will want to keep it; otherwise, it was just something * we found in failover mode, so are free to wipe it out. this var has * no meaning when hop == 0. */ public boolean isHopRecommended; /** * remote failures. applies only if this nodestate is of a rendezvous * node. contains nids of all nodes for which this rendezvous cannot * recommend routes. * * invariants: * - undefined if this is not a rendezvous node * - empty */ public final HashSet<NodeState> remoteFailures = new HashSet<NodeState>(); /** * dstsPresent, the complement of remoteFailures (in defaultClients). */ public final HashSet<Short> dstsPresent = new HashSet<Short>(); /** * this is unused at the moment. still need to re-design. */ public final HashSet<Short> hopOptions = new HashSet<Short>(); public NodeState(NodeInfo info) { this.info = info; this.hop = info.id; latencies.put(info.id, (short) 0); } public int compareTo(NodeState o) { return new Short(info.id).compareTo(o.info.id); } } } class ShortShortMap { private final Hashtable<Short,Short> table = new Hashtable<Short, Short>(); private final short defaultValue; public ShortShortMap(short defaultValue) { this.defaultValue = defaultValue; } public Set<Short> keySet() { return table.keySet(); } public boolean containsKey(short key) { return table.containsKey(key); } public void remove(short key) { table.remove(key); } public short get(short key) { Short value = table.get(key); return value != null ? value : defaultValue; } public void put(short key, short value) { if (value == defaultValue) table.remove(key); else table.put(key, value); } } /////////////////////////////////////// // // // // // // welcome to my // DEATH MACHINE, // interloper!!!!!!!11 // // // // // // ///////////////////////////////////// class NodeInfo { short id; int port; InetAddress addr; } class Rec { short dst; short via; } class Subprobe { long time; InetSocketAddress src; InetSocketAddress nod; byte type; } class PeerPing { long time; InetSocketAddress src; } class PeerPong { long time; InetSocketAddress src; } class Msg { short src; short version; short session; } class Join extends Msg { InetAddress addr; int port; } class Init extends Msg { short id; ArrayList<NodeInfo> members; } class Membership extends Msg { ArrayList<NodeInfo> members; short numNodes; short yourId; } class RoutingRecs extends Msg { ArrayList<Rec> recs; } class Ping extends Msg { long time; NodeInfo info; } class Pong extends Msg { long time; } class Measurements extends Msg { short[] probeTable; byte[] inflation; } class Serialization { public void serialize(Object obj, DataOutputStream out) throws IOException { if (false) {} else if (obj.getClass() == NodeInfo.class) { NodeInfo casted = (NodeInfo) obj; out.writeInt(((int) serVersion) << 8 | 0); out.writeShort(casted.id); out.writeInt(casted.port); { byte[] buf = casted.addr.getAddress(); out.writeInt(buf.length); out.write(buf); } } else if (obj.getClass() == Rec.class) { Rec casted = (Rec) obj; out.writeInt(((int) serVersion) << 8 | 1); out.writeShort(casted.dst); out.writeShort(casted.via); } else if (obj.getClass() == Subprobe.class) { Subprobe casted = (Subprobe) obj; out.writeInt(((int) serVersion) << 8 | 2); out.writeLong(casted.time); { byte[] buf = casted.src.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.src.getPort()); { byte[] buf = casted.nod.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.nod.getPort()); out.writeByte(casted.type); } else if (obj.getClass() == PeerPing.class) { PeerPing casted = (PeerPing) obj; out.writeInt(((int) serVersion) << 8 | 3); out.writeLong(casted.time); { byte[] buf = casted.src.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.src.getPort()); } else if (obj.getClass() == PeerPong.class) { PeerPong casted = (PeerPong) obj; out.writeInt(((int) serVersion) << 8 | 4); out.writeLong(casted.time); { byte[] buf = casted.src.getAddress().getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.src.getPort()); } else if (obj.getClass() == Msg.class) { Msg casted = (Msg) obj; out.writeInt(((int) serVersion) << 8 | 5); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Join.class) { Join casted = (Join) obj; out.writeInt(((int) serVersion) << 8 | 6); { byte[] buf = casted.addr.getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeInt(casted.port); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Init.class) { Init casted = (Init) obj; out.writeInt(((int) serVersion) << 8 | 7); out.writeShort(casted.id); out.writeInt(casted.members.size()); for (int i = 0; i < casted.members.size(); i++) { out.writeShort(casted.members.get(i).id); out.writeInt(casted.members.get(i).port); { byte[] buf = casted.members.get(i).addr.getAddress(); out.writeInt(buf.length); out.write(buf); } } out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Membership.class) { Membership casted = (Membership) obj; out.writeInt(((int) serVersion) << 8 | 8); out.writeInt(casted.members.size()); for (int i = 0; i < casted.members.size(); i++) { out.writeShort(casted.members.get(i).id); out.writeInt(casted.members.get(i).port); { byte[] buf = casted.members.get(i).addr.getAddress(); out.writeInt(buf.length); out.write(buf); } } out.writeShort(casted.numNodes); out.writeShort(casted.yourId); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == RoutingRecs.class) { RoutingRecs casted = (RoutingRecs) obj; out.writeInt(((int) serVersion) << 8 | 9); out.writeInt(casted.recs.size()); for (int i = 0; i < casted.recs.size(); i++) { out.writeShort(casted.recs.get(i).dst); out.writeShort(casted.recs.get(i).via); } out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Ping.class) { Ping casted = (Ping) obj; out.writeInt(((int) serVersion) << 8 | 10); out.writeLong(casted.time); out.writeShort(casted.info.id); out.writeInt(casted.info.port); { byte[] buf = casted.info.addr.getAddress(); out.writeInt(buf.length); out.write(buf); } out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Pong.class) { Pong casted = (Pong) obj; out.writeInt(((int) serVersion) << 8 | 11); out.writeLong(casted.time); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } else if (obj.getClass() == Measurements.class) { Measurements casted = (Measurements) obj; out.writeInt(((int) serVersion) << 8 | 12); out.writeInt(casted.probeTable.length); for (int i = 0; i < casted.probeTable.length; i++) { out.writeShort(casted.probeTable[i]); } out.writeInt(casted.inflation.length); out.write(casted.inflation); out.writeShort(casted.src); out.writeShort(casted.version); out.writeShort(casted.session); } } public static byte serVersion = 2; public Object deserialize(DataInputStream in) throws IOException { int header = readInt(in); if ((header & 0xff00) != ((int) serVersion) << 8) return null; int msgtype = header & 0xff; switch (msgtype) { case 0: { // NodeInfo NodeInfo obj; { obj = new NodeInfo(); { obj.id = in.readShort(); } { obj.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } obj.addr = InetAddress.getByAddress(buf); } } return obj; } case 1: { // Rec Rec obj; { obj = new Rec(); { obj.dst = in.readShort(); } { obj.via = in.readShort(); } } return obj; } case 2: { // Subprobe Subprobe obj; { obj = new Subprobe(); { obj.time = in.readLong(); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.src = new InetSocketAddress(addr, port); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.nod = new InetSocketAddress(addr, port); } { obj.type = in.readByte(); } } return obj; } case 3: { // PeerPing PeerPing obj; { obj = new PeerPing(); { obj.time = in.readLong(); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.src = new InetSocketAddress(addr, port); } } return obj; } case 4: { // PeerPong PeerPong obj; { obj = new PeerPong(); { obj.time = in.readLong(); } { InetAddress addr; { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } addr = InetAddress.getByAddress(buf); } int port; { port = readInt(in); } obj.src = new InetSocketAddress(addr, port); } } return obj; } case 5: { // Msg Msg obj; { obj = new Msg(); { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } return obj; } case 6: { // Join Join obj; { obj = new Join(); { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } obj.addr = InetAddress.getByAddress(buf); } { obj.port = readInt(in); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 7: { // Init Init obj; { obj = new Init(); { obj.id = in.readShort(); } { obj.members = new ArrayList<NodeInfo>(); for (int i = 0, len = readInt(in); i < len; i++) { NodeInfo x; { x = new NodeInfo(); { x.id = in.readShort(); } { x.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } x.addr = InetAddress.getByAddress(buf); } } obj.members.add(x); } } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 8: { // Membership Membership obj; { obj = new Membership(); { obj.members = new ArrayList<NodeInfo>(); for (int i = 0, len = readInt(in); i < len; i++) { NodeInfo x; { x = new NodeInfo(); { x.id = in.readShort(); } { x.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } x.addr = InetAddress.getByAddress(buf); } } obj.members.add(x); } } { obj.numNodes = in.readShort(); } { obj.yourId = in.readShort(); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 9: { // RoutingRecs RoutingRecs obj; { obj = new RoutingRecs(); { obj.recs = new ArrayList<Rec>(); for (int i = 0, len = readInt(in); i < len; i++) { Rec x; { x = new Rec(); { x.dst = in.readShort(); } { x.via = in.readShort(); } } obj.recs.add(x); } } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 10: { // Ping Ping obj; { obj = new Ping(); { obj.time = in.readLong(); } { obj.info = new NodeInfo(); { obj.info.id = in.readShort(); } { obj.info.port = readInt(in); } { byte[] buf; { buf = new byte[readInt(in)]; in.read(buf); } obj.info.addr = InetAddress.getByAddress(buf); } } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 11: { // Pong Pong obj; { obj = new Pong(); { obj.time = in.readLong(); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } case 12: { // Measurements Measurements obj; { obj = new Measurements(); { obj.probeTable = new short[readInt(in)]; for (int i = 0; i < obj.probeTable.length; i++) { { obj.probeTable[i] = in.readShort(); } } } { obj.inflation = new byte[readInt(in)]; in.read(obj.inflation); } { { obj.src = in.readShort(); } { obj.version = in.readShort(); } { obj.session = in.readShort(); } } } return obj; } default: throw new RuntimeException("unknown obj type"); } } private byte[] readBuffer = new byte[4]; // read in a big-endian 4-byte integer public int readInt(DataInputStream dis) throws IOException { dis.readFully(readBuffer, 0, 4); return ( ((int)(readBuffer[0] & 255) << 24) + ((readBuffer[1] & 255) << 16) + ((readBuffer[2] & 255) << 8) + ((readBuffer[3] & 255) << 0)); } /* public static void main(String[] args) throws IOException { { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); Pong pong = new Pong(); pong.src = 2; pong.version = 3; pong.time = 4; serialize(pong, out); byte[] buf = baos.toByteArray(); System.out.println(buf.length); Object obj = deserialize(new DataInputStream(new ByteArrayInputStream(buf))); System.out.println(obj); } { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); Measurements m = new Measurements(); m.src = 2; m.version = 3; m.membershipList = new ArrayList<Integer>(); m.membershipList.add(4); m.membershipList.add(5); m.membershipList.add(6); m.ProbeTable = new long[5]; m.ProbeTable[1] = 7; m.ProbeTable[2] = 8; m.ProbeTable[3] = 9; serialize(m, out); byte[] buf = baos.toByteArray(); System.out.println(buf.length); Object obj = deserialize(new DataInputStream(new ByteArrayInputStream(buf))); System.out.println(obj); } { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); Membership m = new Membership(); m.src = 2; m.version = 3; m.members = new ArrayList<NodeInfo>(); NodeInfo n1 = new NodeInfo(); n1.addr = InetAddress.getLocalHost(); n1.port = 4; n1.id = 5; m.members.add(n1); NodeInfo n2 = new NodeInfo(); n2.addr = InetAddress.getByName("google.com"); n2.port = 6; n2.id = 7; m.members.add(n2); m.numNodes = 8; serialize(m, out); byte[] buf = baos.toByteArray(); System.out.println(buf.length); Object obj = deserialize(new DataInputStream( new ByteArrayInputStream(buf))); System.out.println(obj); } }*/ }
Added logic to see if a node failure has occured Let's hope this works!! git-svn-id: 1701df1deb063346cd8c76dc2a7d96d8dbeff991@649 0bd769cf-3f23-0410-95ed-bb08bbc236b7
edu/cmu/neuron2/NeuRonNode.java
Added logic to see if a node failure has occured
<ide><path>du/cmu/neuron2/NeuRonNode.java <ide> } <ide> } <ide> node.isReachable = true; <add> node.isDead = false; <ide> <ide> ScheduledFuture<?> future = scheduler.schedule(safeRun(new Runnable() { <ide> public void run() { <ide> // iterate over all destination nodes that are not us <ide> for (NodeState dst : otherNodes) { <ide> <del> // if we believe that the node is not down <del> // TODO (high priority): since dst.hop is never set to 0, this will always <del> // be called, and we will always attempt to find a route to the <del> // destination, even if there is a node failure. <del> if (dst.hop != 0) { <add> if (!dst.isDead) { <ide> // this is our current (active) set of rendezvous servers <ide> HashSet<NodeState> rs = rendezvousServers.get(dst.info.id); <ide> <ide> } else { <ide> // blindly trust the recommendations <ide> NodeState node = nodes.get(rec.dst); <del> if (node.hop == 0) <add> if (node.hop == 0 || node.isDead) { <ide> node.cameUp = true; <add> node.isDead = false; <add> } <ide> node.isHopRecommended = true; <ide> node.hop = rec.via; <ide> } <ide> min = self.latencies.get(node.info.id); <ide> } <ide> } <add> else { <add> // If it is alive, we will set it to false in the next few lines <add> node.isDead = true; <add> } <ide> <ide> // find best rendezvous client. (`clients` are all reachable.) <ide> for (NodeState client : clients) { <ide> int val = client.latencies.get(nid); <ide> if (val != resetLatency) { <add> if(!node.isReachable) <add> node.isDead = false; <add> <ide> options.add(client); <ide> val += self.latencies.get(client.info.id); <ide> if (!node.isHopRecommended && val < min) { <ide> * - cannot be nid if !isReachable <ide> */ <ide> public short hop; <add> <add> <add> /** <add> * Keeps track of whether any node (including ourself) receives measurements <add> * to the destination. Only consider this if node.isReachable is false. <add> */ <add> public boolean isDead = false; <add> <ide> <ide> /** <ide> * this is set at certain places where we determine that a node is
Java
apache-2.0
9a7b91bdc22e4e75a1ca0a12cb4355f4a1d16964
0
ssilvert/keycloak,jpkrohling/keycloak,mhajas/keycloak,ssilvert/keycloak,mposolda/keycloak,srose/keycloak,reneploetz/keycloak,darranl/keycloak,mposolda/keycloak,ahus1/keycloak,mhajas/keycloak,vmuzikar/keycloak,abstractj/keycloak,thomasdarimont/keycloak,thomasdarimont/keycloak,srose/keycloak,pedroigor/keycloak,stianst/keycloak,hmlnarik/keycloak,abstractj/keycloak,keycloak/keycloak,hmlnarik/keycloak,raehalme/keycloak,raehalme/keycloak,mhajas/keycloak,pedroigor/keycloak,mposolda/keycloak,vmuzikar/keycloak,ssilvert/keycloak,keycloak/keycloak,pedroigor/keycloak,ssilvert/keycloak,pedroigor/keycloak,reneploetz/keycloak,darranl/keycloak,srose/keycloak,thomasdarimont/keycloak,raehalme/keycloak,abstractj/keycloak,thomasdarimont/keycloak,mhajas/keycloak,srose/keycloak,darranl/keycloak,reneploetz/keycloak,stianst/keycloak,pedroigor/keycloak,reneploetz/keycloak,stianst/keycloak,mhajas/keycloak,thomasdarimont/keycloak,hmlnarik/keycloak,ahus1/keycloak,ahus1/keycloak,mposolda/keycloak,abstractj/keycloak,abstractj/keycloak,pedroigor/keycloak,thomasdarimont/keycloak,hmlnarik/keycloak,jpkrohling/keycloak,hmlnarik/keycloak,vmuzikar/keycloak,stianst/keycloak,jpkrohling/keycloak,darranl/keycloak,hmlnarik/keycloak,mposolda/keycloak,keycloak/keycloak,vmuzikar/keycloak,jpkrohling/keycloak,stianst/keycloak,ahus1/keycloak,reneploetz/keycloak,keycloak/keycloak,ahus1/keycloak,raehalme/keycloak,raehalme/keycloak,vmuzikar/keycloak,srose/keycloak,mposolda/keycloak,ahus1/keycloak,jpkrohling/keycloak,raehalme/keycloak,keycloak/keycloak,vmuzikar/keycloak,ssilvert/keycloak
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.broker.provider.util; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.keycloak.common.util.Base64; import org.keycloak.connections.httpclient.HttpClientProvider; import org.keycloak.models.KeycloakSession; import org.keycloak.util.JsonSerialization; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; /** * @author <a href="mailto:[email protected]">Stian Thorgersen</a> * @author Vlastimil Elias (velias at redhat dot com) * @author David Klassen ([email protected]) */ public class SimpleHttp { private static final ObjectMapper mapper = new ObjectMapper(); private HttpClient client; private String url; private String method; private Map<String, String> headers; private Map<String, String> params; private Object entity; protected SimpleHttp(String url, String method, HttpClient client) { this.client = client; this.url = url; this.method = method; } public static SimpleHttp doDelete(String url, KeycloakSession session) { return doDelete(url, session.getProvider(HttpClientProvider.class).getHttpClient()); } public static SimpleHttp doDelete(String url, HttpClient client) { return new SimpleHttp(url, "DELETE", client); } public static SimpleHttp doGet(String url, KeycloakSession session) { return doGet(url, session.getProvider(HttpClientProvider.class).getHttpClient()); } public static SimpleHttp doGet(String url, HttpClient client) { return new SimpleHttp(url, "GET", client); } public static SimpleHttp doPost(String url, KeycloakSession session) { return doPost(url, session.getProvider(HttpClientProvider.class).getHttpClient()); } public static SimpleHttp doPost(String url, HttpClient client) { return new SimpleHttp(url, "POST", client); } public static SimpleHttp doPut(String url, HttpClient client) { return new SimpleHttp(url, "PUT", client); } public SimpleHttp header(String name, String value) { if (headers == null) { headers = new HashMap<>(); } headers.put(name, value); return this; } public SimpleHttp json(Object entity) { this.entity = entity; return this; } public SimpleHttp param(String name, String value) { if (params == null) { params = new HashMap<>(); } params.put(name, value); return this; } public SimpleHttp auth(String token) { header("Authorization", "Bearer " + token); return this; } public SimpleHttp authBasic(final String username, final String password) { final String basicCredentials = String.format("%s:%s", username, password); header("Authorization", "Basic " + Base64.encodeBytes(basicCredentials.getBytes())); return this; } public SimpleHttp acceptJson() { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return this; } public JsonNode asJson() throws IOException { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return mapper.readTree(asString()); } public <T> T asJson(Class<T> type) throws IOException { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return JsonSerialization.readValue(asString(), type); } public <T> T asJson(TypeReference<T> type) throws IOException { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return JsonSerialization.readValue(asString(), type); } public String asString() throws IOException { return asResponse().asString(); } public int asStatus() throws IOException { return asResponse().getStatus(); } public Response asResponse() throws IOException { return makeRequest(); } private Response makeRequest() throws IOException { boolean get = method.equals("GET"); boolean post = method.equals("POST"); boolean put = method.equals("PUT"); boolean delete = method.equals("DELETE"); HttpRequestBase httpRequest = new HttpPost(url); if (get) { httpRequest = new HttpGet(appendParameterToUrl(url)); } if (delete) { httpRequest = new HttpDelete(appendParameterToUrl(url)); } if (put) { httpRequest = new HttpPut(appendParameterToUrl(url)); } if (post || put) { if (params != null) { ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(getFormEntityFromParameter()); } else if (entity != null) { if (headers == null || !headers.containsKey(HttpHeaders.CONTENT_TYPE)) { header(HttpHeaders.CONTENT_TYPE, "application/json"); } ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(getJsonEntity()); } else { throw new IllegalStateException("No content set"); } } if (headers != null) { for (Map.Entry<String, String> h : headers.entrySet()) { httpRequest.setHeader(h.getKey(), h.getValue()); } } return new Response(client.execute(httpRequest)); } private URI appendParameterToUrl(String url) throws IOException { URI uri = null; try { URIBuilder uriBuilder = new URIBuilder(url); if (params != null) { for (Map.Entry<String, String> p : params.entrySet()) { uriBuilder.setParameter(p.getKey(), p.getValue()); } } uri = uriBuilder.build(); } catch (URISyntaxException e) { } return uri; } private StringEntity getJsonEntity() throws IOException { return new StringEntity(JsonSerialization.writeValueAsString(entity), ContentType.getByMimeType(headers.get(HttpHeaders.CONTENT_TYPE))); } private UrlEncodedFormEntity getFormEntityFromParameter() throws IOException{ List<NameValuePair> urlParameters = new ArrayList<>(); if (params != null) { for (Map.Entry<String, String> p : params.entrySet()) { urlParameters. add(new BasicNameValuePair(p.getKey(), p.getValue())); } } return new UrlEncodedFormEntity(urlParameters); } public static class Response { private HttpResponse response; private int statusCode = -1; private String responseString; public Response(HttpResponse response) { this.response = response; } private void readResponse() throws IOException { if (statusCode == -1) { statusCode = response.getStatusLine().getStatusCode(); InputStream is; HttpEntity entity = response.getEntity(); if (entity != null) { is = entity.getContent(); ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); try { HeaderIterator it = response.headerIterator(); while (it.hasNext()) { Header header = it.nextHeader(); if (header.getName().equals("Content-Encoding") && header.getValue().equals("gzip")) { is = new GZIPInputStream(is); } } InputStreamReader reader = charset == null ? new InputStreamReader(is) : new InputStreamReader(is, charset); StringWriter writer = new StringWriter(); char[] buffer = new char[1024 * 4]; for (int n = reader.read(buffer); n != -1; n = reader.read(buffer)) { writer.write(buffer, 0, n); } responseString = writer.toString(); } finally { if (is != null) { is.close(); } } } } } public int getStatus() throws IOException { readResponse(); return response.getStatusLine().getStatusCode(); } public JsonNode asJson() throws IOException { return mapper.readTree(asString()); } public <T> T asJson(Class<T> type) throws IOException { return JsonSerialization.readValue(asString(), type); } public <T> T asJson(TypeReference<T> type) throws IOException { return JsonSerialization.readValue(asString(), type); } public String asString() throws IOException { readResponse(); return responseString; } public String getFirstHeader(String name) throws IOException { readResponse(); Header[] headers = response.getHeaders(name); if (headers != null && headers.length > 0) { return headers[0].getValue(); } return null; } public List<String> getHeader(String name) throws IOException { readResponse(); Header[] headers = response.getHeaders(name); if (headers != null && headers.length > 0) { return Stream.of(headers).map(Header::getValue).collect(Collectors.toList()); } return null; } public void close() throws IOException { readResponse(); } } }
server-spi-private/src/main/java/org/keycloak/broker/provider/util/SimpleHttp.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.broker.provider.util; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.keycloak.common.util.Base64; import org.keycloak.connections.httpclient.HttpClientProvider; import org.keycloak.models.KeycloakSession; import org.keycloak.util.JsonSerialization; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; /** * @author <a href="mailto:[email protected]">Stian Thorgersen</a> * @author Vlastimil Elias (velias at redhat dot com) * @author David Klassen ([email protected]) */ public class SimpleHttp { private static final ObjectMapper mapper = new ObjectMapper(); private HttpClient client; private String url; private String method; private Map<String, String> headers; private Map<String, String> params; private Object entity; protected SimpleHttp(String url, String method, HttpClient client) { this.client = client; this.url = url; this.method = method; } public static SimpleHttp doDelete(String url, KeycloakSession session) { return doDelete(url, session.getProvider(HttpClientProvider.class).getHttpClient()); } public static SimpleHttp doDelete(String url, HttpClient client) { return new SimpleHttp(url, "DELETE", client); } public static SimpleHttp doGet(String url, KeycloakSession session) { return doGet(url, session.getProvider(HttpClientProvider.class).getHttpClient()); } public static SimpleHttp doGet(String url, HttpClient client) { return new SimpleHttp(url, "GET", client); } public static SimpleHttp doPost(String url, KeycloakSession session) { return doPost(url, session.getProvider(HttpClientProvider.class).getHttpClient()); } public static SimpleHttp doPost(String url, HttpClient client) { return new SimpleHttp(url, "POST", client); } public static SimpleHttp doPut(String url, HttpClient client) { return new SimpleHttp(url, "PUT", client); } public SimpleHttp header(String name, String value) { if (headers == null) { headers = new HashMap<>(); } headers.put(name, value); return this; } public SimpleHttp json(Object entity) { this.entity = entity; return this; } public SimpleHttp param(String name, String value) { if (params == null) { params = new HashMap<>(); } params.put(name, value); return this; } public SimpleHttp auth(String token) { header("Authorization", "Bearer " + token); return this; } public SimpleHttp authBasic(final String username, final String password) { final String basicCredentials = String.format("%s:%s", username, password); header("Authorization", "Basic " + Base64.encodeBytes(basicCredentials.getBytes())); return this; } public SimpleHttp acceptJson() { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return this; } public JsonNode asJson() throws IOException { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return mapper.readTree(asString()); } public <T> T asJson(Class<T> type) throws IOException { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return JsonSerialization.readValue(asString(), type); } public <T> T asJson(TypeReference<T> type) throws IOException { if (headers == null || !headers.containsKey("Accept")) { header("Accept", "application/json"); } return JsonSerialization.readValue(asString(), type); } public String asString() throws IOException { return asResponse().asString(); } public int asStatus() throws IOException { return asResponse().getStatus(); } public Response asResponse() throws IOException { return makeRequest(); } private Response makeRequest() throws IOException { boolean get = method.equals("GET"); boolean post = method.equals("POST"); boolean put = method.equals("PUT"); boolean delete = method.equals("DELETE"); HttpRequestBase httpRequest = new HttpPost(url); if (get) { httpRequest = new HttpGet(appendParameterToUrl(url)); } if (delete) { httpRequest = new HttpDelete(appendParameterToUrl(url)); } if (put) { httpRequest = new HttpPut(appendParameterToUrl(url)); } if (post || put) { if (params != null) { ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(getFormEntityFromParameter()); } else if (entity != null) { if (headers == null || !headers.containsKey("Content-Type")) { header("Content-Type", "application/json"); } ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(getJsonEntity()); } else { throw new IllegalStateException("No content set"); } } if (headers != null) { for (Map.Entry<String, String> h : headers.entrySet()) { httpRequest.setHeader(h.getKey(), h.getValue()); } } return new Response(client.execute(httpRequest)); } private URI appendParameterToUrl(String url) throws IOException { URI uri = null; try { URIBuilder uriBuilder = new URIBuilder(url); if (params != null) { for (Map.Entry<String, String> p : params.entrySet()) { uriBuilder.setParameter(p.getKey(), p.getValue()); } } uri = uriBuilder.build(); } catch (URISyntaxException e) { } return uri; } private StringEntity getJsonEntity() throws IOException { return new StringEntity(JsonSerialization.writeValueAsString(entity), ContentType.getByMimeType(headers.get("Content-Type"))); } private UrlEncodedFormEntity getFormEntityFromParameter() throws IOException{ List<NameValuePair> urlParameters = new ArrayList<>(); if (params != null) { for (Map.Entry<String, String> p : params.entrySet()) { urlParameters. add(new BasicNameValuePair(p.getKey(), p.getValue())); } } return new UrlEncodedFormEntity(urlParameters); } public static class Response { private HttpResponse response; private int statusCode = -1; private String responseString; public Response(HttpResponse response) { this.response = response; } private void readResponse() throws IOException { if (statusCode == -1) { statusCode = response.getStatusLine().getStatusCode(); InputStream is; HttpEntity entity = response.getEntity(); if (entity != null) { is = entity.getContent(); ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); try { HeaderIterator it = response.headerIterator(); while (it.hasNext()) { Header header = it.nextHeader(); if (header.getName().equals("Content-Encoding") && header.getValue().equals("gzip")) { is = new GZIPInputStream(is); } } InputStreamReader reader = charset == null ? new InputStreamReader(is) : new InputStreamReader(is, charset); StringWriter writer = new StringWriter(); char[] buffer = new char[1024 * 4]; for (int n = reader.read(buffer); n != -1; n = reader.read(buffer)) { writer.write(buffer, 0, n); } responseString = writer.toString(); } finally { if (is != null) { is.close(); } } } } } public int getStatus() throws IOException { readResponse(); return response.getStatusLine().getStatusCode(); } public JsonNode asJson() throws IOException { return mapper.readTree(asString()); } public <T> T asJson(Class<T> type) throws IOException { return JsonSerialization.readValue(asString(), type); } public <T> T asJson(TypeReference<T> type) throws IOException { return JsonSerialization.readValue(asString(), type); } public String asString() throws IOException { readResponse(); return responseString; } public String getFirstHeader(String name) throws IOException { readResponse(); Header[] headers = response.getHeaders(name); if (headers != null && headers.length > 0) { return headers[0].getValue(); } return null; } public List<String> getHeader(String name) throws IOException { readResponse(); Header[] headers = response.getHeaders(name); if (headers != null && headers.length > 0) { return Stream.of(headers).map(Header::getValue).collect(Collectors.toList()); } return null; } public void close() throws IOException { readResponse(); } } }
KEYCLOAK-14310 Replaced string by constant after review amendment
server-spi-private/src/main/java/org/keycloak/broker/provider/util/SimpleHttp.java
KEYCLOAK-14310 Replaced string by constant after review amendment
<ide><path>erver-spi-private/src/main/java/org/keycloak/broker/provider/util/SimpleHttp.java <ide> import org.apache.http.Header; <ide> import org.apache.http.HeaderIterator; <ide> import org.apache.http.HttpEntity; <add>import org.apache.http.HttpHeaders; <ide> import org.apache.http.HttpResponse; <ide> import org.apache.http.NameValuePair; <ide> import org.apache.http.client.HttpClient; <ide> if (params != null) { <ide> ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(getFormEntityFromParameter()); <ide> } else if (entity != null) { <del> if (headers == null || !headers.containsKey("Content-Type")) { <del> header("Content-Type", "application/json"); <add> if (headers == null || !headers.containsKey(HttpHeaders.CONTENT_TYPE)) { <add> header(HttpHeaders.CONTENT_TYPE, "application/json"); <ide> } <ide> ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(getJsonEntity()); <ide> } else { <ide> } <ide> <ide> private StringEntity getJsonEntity() throws IOException { <del> return new StringEntity(JsonSerialization.writeValueAsString(entity), ContentType.getByMimeType(headers.get("Content-Type"))); <add> return new StringEntity(JsonSerialization.writeValueAsString(entity), ContentType.getByMimeType(headers.get(HttpHeaders.CONTENT_TYPE))); <ide> } <ide> <ide> private UrlEncodedFormEntity getFormEntityFromParameter() throws IOException{
Java
mit
error: pathspec 'src/me/christopherdavis/beanstalkc/command/PutJobCommand.java' did not match any file(s) known to git
e7d608e9a1068737f2b40d4176bbbe04ad3c25f3
1
chrisguitarguy/Beanstalkc,chrisguitarguy/Beanstalkc
// This file is part of me.christopherdavis.beanstalkc // Copyright: (c) 2014 Christopher Davis <http://christopherdavis.me> // License: MIT http://opensource.org/licenses/MIT package me.christopherdavis.beanstalkc; import java.io.InputStream; import java.io.OutputStream; import me.christopherdavis.beanstalkc.Command; import me.christopherdavis.beanstalkc.Job; /** * Put a new job into the queue. * * @since 0.1 * @author Christopher Davis <http://christopherdavis.me> */ class PutJobCommand implements Command<Job> { public Job execute(InputStream in, OutputStream out) throws BeanstalkcException { return null; } }
src/me/christopherdavis/beanstalkc/command/PutJobCommand.java
Put job command sample
src/me/christopherdavis/beanstalkc/command/PutJobCommand.java
Put job command sample
<ide><path>rc/me/christopherdavis/beanstalkc/command/PutJobCommand.java <add>// This file is part of me.christopherdavis.beanstalkc <add>// Copyright: (c) 2014 Christopher Davis <http://christopherdavis.me> <add>// License: MIT http://opensource.org/licenses/MIT <add> <add>package me.christopherdavis.beanstalkc; <add> <add>import java.io.InputStream; <add>import java.io.OutputStream; <add>import me.christopherdavis.beanstalkc.Command; <add>import me.christopherdavis.beanstalkc.Job; <add> <add>/** <add> * Put a new job into the queue. <add> * <add> * @since 0.1 <add> * @author Christopher Davis <http://christopherdavis.me> <add> */ <add>class PutJobCommand implements Command<Job> <add>{ <add> public Job execute(InputStream in, OutputStream out) throws BeanstalkcException <add> { <add> return null; <add> } <add>}
Java
apache-2.0
2b5e8de7aea1db94d0c889ec620947f92b554596
0
fady1989/EffectiveJava
package effectiveJava; import effectiveJava.Timer.IMethod; import matrixLib.IMatrix; public class Main { private static final Sum math = new Sum(); public static void main(String[] args) { } public static void useSumClass() { Timer t = new Timer (); t.method = new IMethod() { @Override public void execute() { math.sumFromZeroUpTo(Integer.MAX_VALUE); } }; System.out.println(t.timerExecute()); t.method = new IMethod() { @Override public void execute() { math.sumFromZeroUpToAutoboxed(Integer.MAX_VALUE); } }; System.out.println(t.timerExecute()); } }
src/effectiveJava/Main.java
package effectiveJava; import effectiveJava.Timer.IMethod; import matrixLib.IMatrix; public class Main { private static final Sum math = new Sum(); public static void main(String[] args) { // useSumClass(); } public static void useSumClass() { Timer t = new Timer (); t.method = new IMethod() { @Override public void execute() { math.sumFromZeroUpTo(Integer.MAX_VALUE); } }; System.out.println(t.timerExecute()); t.method = new IMethod() { @Override public void execute() { math.sumFromZeroUpToAutoboxed(Integer.MAX_VALUE); } }; System.out.println(t.timerExecute()); } }
made a change
src/effectiveJava/Main.java
made a change
<ide><path>rc/effectiveJava/Main.java <ide> <ide> public static void main(String[] args) { <ide> <del> <del> // useSumClass(); <ide> <ide> } <ide>
Java
mit
fbc8d7ca32dbf50dbf50a84eeb5de1bbef2e4391
0
protazy/jenkins,vijayto/jenkins,arcivanov/jenkins,stefanbrausch/hudson-main,evernat/jenkins,gusreiber/jenkins,aduprat/jenkins,petermarcoen/jenkins,dariver/jenkins,svanoort/jenkins,fbelzunc/jenkins,paulmillar/jenkins,Krasnyanskiy/jenkins,ydubreuil/jenkins,viqueen/jenkins,ikedam/jenkins,pantheon-systems/jenkins,duzifang/my-jenkins,msrb/jenkins,varmenise/jenkins,hashar/jenkins,iqstack/jenkins,ErikVerheul/jenkins,aldaris/jenkins,elkingtonmcb/jenkins,github-api-test-org/jenkins,DoctorQ/jenkins,kohsuke/hudson,hashar/jenkins,lordofthejars/jenkins,andresrc/jenkins,aheritier/jenkins,yonglehou/jenkins,my7seven/jenkins,deadmoose/jenkins,tangkun75/jenkins,mrobinet/jenkins,noikiy/jenkins,1and1/jenkins,DanielWeber/jenkins,SebastienGllmt/jenkins,khmarbaise/jenkins,jzjzjzj/jenkins,ydubreuil/jenkins,hudson/hudson-2.x,brunocvcunha/jenkins,NehemiahMi/jenkins,github-api-test-org/jenkins,nandan4/Jenkins,lordofthejars/jenkins,hplatou/jenkins,ErikVerheul/jenkins,hemantojhaa/jenkins,dariver/jenkins,jcarrothers-sap/jenkins,brunocvcunha/jenkins,recena/jenkins,chbiel/jenkins,oleg-nenashev/jenkins,guoxu0514/jenkins,albers/jenkins,1and1/jenkins,dbroady1/jenkins,duzifang/my-jenkins,hemantojhaa/jenkins,292388900/jenkins,scoheb/jenkins,evernat/jenkins,huybrechts/hudson,andresrc/jenkins,stephenc/jenkins,albers/jenkins,Vlatombe/jenkins,morficus/jenkins,iterate/coding-dojo,aduprat/jenkins,iqstack/jenkins,SenolOzer/jenkins,jpederzolli/jenkins-1,csimons/jenkins,SenolOzer/jenkins,tastatur/jenkins,dbroady1/jenkins,CodeShane/jenkins,recena/jenkins,wangyikai/jenkins,lvotypko/jenkins3,gusreiber/jenkins,jcarrothers-sap/jenkins,brunocvcunha/jenkins,thomassuckow/jenkins,6WIND/jenkins,ydubreuil/jenkins,olivergondza/jenkins,aduprat/jenkins,gitaccountforprashant/gittest,patbos/jenkins,morficus/jenkins,paulmillar/jenkins,everyonce/jenkins,intelchen/jenkins,noikiy/jenkins,AustinKwang/jenkins,jcsirot/jenkins,lvotypko/jenkins,daniel-beck/jenkins,ikedam/jenkins,luoqii/jenkins,abayer/jenkins,mdonohue/jenkins,lvotypko/jenkins,keyurpatankar/hudson,v1v/jenkins,fbelzunc/jenkins,mrooney/jenkins,jk47/jenkins,Ykus/jenkins,gitaccountforprashant/gittest,jzjzjzj/jenkins,oleg-nenashev/jenkins,sathiya-mit/jenkins,bkmeneguello/jenkins,Jimilian/jenkins,aldaris/jenkins,FarmGeek4Life/jenkins,jk47/jenkins,maikeffi/hudson,vjuranek/jenkins,dennisjlee/jenkins,vijayto/jenkins,batmat/jenkins,mpeltonen/jenkins,petermarcoen/jenkins,aquarellian/jenkins,kohsuke/hudson,jglick/jenkins,svanoort/jenkins,keyurpatankar/hudson,bkmeneguello/jenkins,albers/jenkins,csimons/jenkins,nandan4/Jenkins,mrobinet/jenkins,rashmikanta-1984/jenkins,elkingtonmcb/jenkins,pselle/jenkins,maikeffi/hudson,akshayabd/jenkins,pantheon-systems/jenkins,soenter/jenkins,christ66/jenkins,amruthsoft9/Jenkis,jpbriend/jenkins,damianszczepanik/jenkins,FTG-003/jenkins,jzjzjzj/jenkins,dennisjlee/jenkins,guoxu0514/jenkins,mattclark/jenkins,dariver/jenkins,huybrechts/hudson,aduprat/jenkins,daspilker/jenkins,dbroady1/jenkins,tastatur/jenkins,CodeShane/jenkins,kohsuke/hudson,brunocvcunha/jenkins,AustinKwang/jenkins,mcanthony/jenkins,scoheb/jenkins,olivergondza/jenkins,MarkEWaite/jenkins,singh88/jenkins,hplatou/jenkins,vlajos/jenkins,daspilker/jenkins,DoctorQ/jenkins,alvarolobato/jenkins,aquarellian/jenkins,fbelzunc/jenkins,paulmillar/jenkins,daspilker/jenkins,lvotypko/jenkins2,DoctorQ/jenkins,NehemiahMi/jenkins,my7seven/jenkins,v1v/jenkins,recena/jenkins,bpzhang/jenkins,rashmikanta-1984/jenkins,jpbriend/jenkins,alvarolobato/jenkins,gorcz/jenkins,Jimilian/jenkins,ikedam/jenkins,dariver/jenkins,kzantow/jenkins,Jochen-A-Fuerbacher/jenkins,gusreiber/jenkins,292388900/jenkins,aquarellian/jenkins,evernat/jenkins,Vlatombe/jenkins,msrb/jenkins,rlugojr/jenkins,daspilker/jenkins,batmat/jenkins,shahharsh/jenkins,chbiel/jenkins,hplatou/jenkins,hudson/hudson-2.x,my7seven/jenkins,aldaris/jenkins,v1v/jenkins,ErikVerheul/jenkins,v1v/jenkins,gorcz/jenkins,rsandell/jenkins,mcanthony/jenkins,tfennelly/jenkins,bkmeneguello/jenkins,hplatou/jenkins,lordofthejars/jenkins,Ykus/jenkins,AustinKwang/jenkins,MadsNielsen/jtemp,vvv444/jenkins,wangyikai/jenkins,shahharsh/jenkins,jenkinsci/jenkins,stephenc/jenkins,SebastienGllmt/jenkins,Jochen-A-Fuerbacher/jenkins,azweb76/jenkins,ChrisA89/jenkins,keyurpatankar/hudson,verbitan/jenkins,FarmGeek4Life/jenkins,damianszczepanik/jenkins,lilyJi/jenkins,Wilfred/jenkins,mpeltonen/jenkins,stefanbrausch/hudson-main,alvarolobato/jenkins,gusreiber/jenkins,lilyJi/jenkins,Vlatombe/jenkins,petermarcoen/jenkins,wuwen5/jenkins,godfath3r/jenkins,verbitan/jenkins,aldaris/jenkins,v1v/jenkins,protazy/jenkins,lordofthejars/jenkins,everyonce/jenkins,guoxu0514/jenkins,iterate/coding-dojo,mpeltonen/jenkins,arunsingh/jenkins,chbiel/jenkins,lvotypko/jenkins,gitaccountforprashant/gittest,wangyikai/jenkins,rsandell/jenkins,paulmillar/jenkins,morficus/jenkins,wangyikai/jenkins,andresrc/jenkins,csimons/jenkins,synopsys-arc-oss/jenkins,damianszczepanik/jenkins,verbitan/jenkins,hashar/jenkins,deadmoose/jenkins,shahharsh/jenkins,aheritier/jenkins,my7seven/jenkins,jpederzolli/jenkins-1,pantheon-systems/jenkins,mrooney/jenkins,iqstack/jenkins,bpzhang/jenkins,iterate/coding-dojo,Krasnyanskiy/jenkins,ErikVerheul/jenkins,oleg-nenashev/jenkins,christ66/jenkins,ns163/jenkins,rlugojr/jenkins,jcarrothers-sap/jenkins,luoqii/jenkins,Wilfred/jenkins,chbiel/jenkins,292388900/jenkins,lindzh/jenkins,hudson/hudson-2.x,stephenc/jenkins,mpeltonen/jenkins,mrobinet/jenkins,batmat/jenkins,vivek/hudson,jpbriend/jenkins,mrooney/jenkins,akshayabd/jenkins,daspilker/jenkins,aheritier/jenkins,luoqii/jenkins,daniel-beck/jenkins,MichaelPranovich/jenkins_sc,tfennelly/jenkins,SebastienGllmt/jenkins,stephenc/jenkins,samatdav/jenkins,tangkun75/jenkins,elkingtonmcb/jenkins,mrobinet/jenkins,vijayto/jenkins,292388900/jenkins,batmat/jenkins,arunsingh/jenkins,singh88/jenkins,ChrisA89/jenkins,ajshastri/jenkins,1and1/jenkins,lordofthejars/jenkins,gorcz/jenkins,nandan4/Jenkins,lilyJi/jenkins,deadmoose/jenkins,mcanthony/jenkins,soenter/jenkins,dennisjlee/jenkins,svanoort/jenkins,amruthsoft9/Jenkis,MichaelPranovich/jenkins_sc,amruthsoft9/Jenkis,jglick/jenkins,ajshastri/jenkins,jglick/jenkins,singh88/jenkins,elkingtonmcb/jenkins,FarmGeek4Life/jenkins,aheritier/jenkins,kzantow/jenkins,petermarcoen/jenkins,scoheb/jenkins,jpbriend/jenkins,rlugojr/jenkins,seanlin816/jenkins,6WIND/jenkins,KostyaSha/jenkins,patbos/jenkins,jhoblitt/jenkins,1and1/jenkins,tfennelly/jenkins,pjanouse/jenkins,iterate/coding-dojo,samatdav/jenkins,ydubreuil/jenkins,jpbriend/jenkins,liupugong/jenkins,github-api-test-org/jenkins,godfath3r/jenkins,KostyaSha/jenkins,tastatur/jenkins,jhoblitt/jenkins,dbroady1/jenkins,Krasnyanskiy/jenkins,vijayto/jenkins,aldaris/jenkins,ydubreuil/jenkins,chbiel/jenkins,mcanthony/jenkins,6WIND/jenkins,aquarellian/jenkins,MarkEWaite/jenkins,lindzh/jenkins,mpeltonen/jenkins,liupugong/jenkins,singh88/jenkins,h4ck3rm1k3/jenkins,lvotypko/jenkins2,nandan4/Jenkins,jglick/jenkins,tastatur/jenkins,DoctorQ/jenkins,deadmoose/jenkins,jtnord/jenkins,msrb/jenkins,chbiel/jenkins,amruthsoft9/Jenkis,abayer/jenkins,tfennelly/jenkins,kzantow/jenkins,pjanouse/jenkins,jtnord/jenkins,vijayto/jenkins,goldchang/jenkins,tangkun75/jenkins,lvotypko/jenkins3,aldaris/jenkins,jpederzolli/jenkins-1,ndeloof/jenkins,stefanbrausch/hudson-main,liorhson/jenkins,seanlin816/jenkins,maikeffi/hudson,DanielWeber/jenkins,Jochen-A-Fuerbacher/jenkins,jcsirot/jenkins,wuwen5/jenkins,recena/jenkins,deadmoose/jenkins,ChrisA89/jenkins,ndeloof/jenkins,SenolOzer/jenkins,azweb76/jenkins,tastatur/jenkins,azweb76/jenkins,thomassuckow/jenkins,duzifang/my-jenkins,azweb76/jenkins,wangyikai/jenkins,mrooney/jenkins,azweb76/jenkins,ndeloof/jenkins,singh88/jenkins,soenter/jenkins,sathiya-mit/jenkins,v1v/jenkins,petermarcoen/jenkins,SebastienGllmt/jenkins,Wilfred/jenkins,hplatou/jenkins,aquarellian/jenkins,liupugong/jenkins,goldchang/jenkins,shahharsh/jenkins,keyurpatankar/hudson,intelchen/jenkins,6WIND/jenkins,arunsingh/jenkins,mattclark/jenkins,mdonohue/jenkins,christ66/jenkins,samatdav/jenkins,godfath3r/jenkins,lvotypko/jenkins,kzantow/jenkins,KostyaSha/jenkins,noikiy/jenkins,FTG-003/jenkins,Vlatombe/jenkins,olivergondza/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,soenter/jenkins,MadsNielsen/jtemp,jcsirot/jenkins,yonglehou/jenkins,kohsuke/hudson,morficus/jenkins,paulwellnerbou/jenkins,khmarbaise/jenkins,viqueen/jenkins,daniel-beck/jenkins,FarmGeek4Life/jenkins,scoheb/jenkins,scoheb/jenkins,luoqii/jenkins,Jimilian/jenkins,mrooney/jenkins,DanielWeber/jenkins,amuniz/jenkins,amuniz/jenkins,amruthsoft9/Jenkis,kohsuke/hudson,paulwellnerbou/jenkins,bpzhang/jenkins,olivergondza/jenkins,NehemiahMi/jenkins,gitaccountforprashant/gittest,pjanouse/jenkins,jtnord/jenkins,Wilfred/jenkins,FarmGeek4Life/jenkins,pjanouse/jenkins,sathiya-mit/jenkins,verbitan/jenkins,arunsingh/jenkins,pselle/jenkins,NehemiahMi/jenkins,goldchang/jenkins,jk47/jenkins,christ66/jenkins,KostyaSha/jenkins,github-api-test-org/jenkins,pselle/jenkins,kzantow/jenkins,FTG-003/jenkins,viqueen/jenkins,NehemiahMi/jenkins,arcivanov/jenkins,AustinKwang/jenkins,ajshastri/jenkins,nandan4/Jenkins,vivek/hudson,stefanbrausch/hudson-main,aduprat/jenkins,jtnord/jenkins,vijayto/jenkins,jenkinsci/jenkins,jcarrothers-sap/jenkins,ajshastri/jenkins,maikeffi/hudson,lvotypko/jenkins,singh88/jenkins,rashmikanta-1984/jenkins,MadsNielsen/jtemp,hudson/hudson-2.x,vvv444/jenkins,MadsNielsen/jtemp,nandan4/Jenkins,lordofthejars/jenkins,escoem/jenkins,my7seven/jenkins,patbos/jenkins,vjuranek/jenkins,lvotypko/jenkins3,brunocvcunha/jenkins,brunocvcunha/jenkins,lvotypko/jenkins3,evernat/jenkins,dariver/jenkins,oleg-nenashev/jenkins,albers/jenkins,mattclark/jenkins,ChrisA89/jenkins,pjanouse/jenkins,amuniz/jenkins,hemantojhaa/jenkins,intelchen/jenkins,kzantow/jenkins,SebastienGllmt/jenkins,ErikVerheul/jenkins,singh88/jenkins,jenkinsci/jenkins,thomassuckow/jenkins,seanlin816/jenkins,yonglehou/jenkins,CodeShane/jenkins,SenolOzer/jenkins,6WIND/jenkins,thomassuckow/jenkins,varmenise/jenkins,daniel-beck/jenkins,h4ck3rm1k3/jenkins,abayer/jenkins,jk47/jenkins,dbroady1/jenkins,MarkEWaite/jenkins,mrobinet/jenkins,elkingtonmcb/jenkins,thomassuckow/jenkins,ydubreuil/jenkins,wuwen5/jenkins,aduprat/jenkins,iterate/coding-dojo,jpbriend/jenkins,Jochen-A-Fuerbacher/jenkins,pselle/jenkins,msrb/jenkins,liupugong/jenkins,iqstack/jenkins,lilyJi/jenkins,aquarellian/jenkins,mdonohue/jenkins,varmenise/jenkins,nandan4/Jenkins,jcarrothers-sap/jenkins,jenkinsci/jenkins,protazy/jenkins,gorcz/jenkins,Ykus/jenkins,csimons/jenkins,samatdav/jenkins,synopsys-arc-oss/jenkins,hudson/hudson-2.x,MarkEWaite/jenkins,christ66/jenkins,protazy/jenkins,khmarbaise/jenkins,intelchen/jenkins,jpederzolli/jenkins-1,huybrechts/hudson,iterate/coding-dojo,soenter/jenkins,bpzhang/jenkins,Jochen-A-Fuerbacher/jenkins,Ykus/jenkins,rsandell/jenkins,aquarellian/jenkins,ns163/jenkins,dennisjlee/jenkins,liorhson/jenkins,godfath3r/jenkins,ikedam/jenkins,h4ck3rm1k3/jenkins,ikedam/jenkins,guoxu0514/jenkins,SebastienGllmt/jenkins,jcarrothers-sap/jenkins,everyonce/jenkins,fbelzunc/jenkins,pantheon-systems/jenkins,lvotypko/jenkins,lindzh/jenkins,huybrechts/hudson,MarkEWaite/jenkins,rsandell/jenkins,dennisjlee/jenkins,hemantojhaa/jenkins,lindzh/jenkins,luoqii/jenkins,dbroady1/jenkins,daspilker/jenkins,AustinKwang/jenkins,ns163/jenkins,SenolOzer/jenkins,KostyaSha/jenkins,paulmillar/jenkins,ajshastri/jenkins,evernat/jenkins,viqueen/jenkins,jhoblitt/jenkins,lindzh/jenkins,escoem/jenkins,patbos/jenkins,tangkun75/jenkins,jcsirot/jenkins,aduprat/jenkins,thomassuckow/jenkins,mdonohue/jenkins,github-api-test-org/jenkins,stefanbrausch/hudson-main,yonglehou/jenkins,vvv444/jenkins,batmat/jenkins,tastatur/jenkins,my7seven/jenkins,albers/jenkins,abayer/jenkins,MarkEWaite/jenkins,Krasnyanskiy/jenkins,andresrc/jenkins,hashar/jenkins,MarkEWaite/jenkins,recena/jenkins,FTG-003/jenkins,viqueen/jenkins,mrooney/jenkins,oleg-nenashev/jenkins,seanlin816/jenkins,kohsuke/hudson,mattclark/jenkins,maikeffi/hudson,jcsirot/jenkins,jcsirot/jenkins,akshayabd/jenkins,6WIND/jenkins,NehemiahMi/jenkins,vijayto/jenkins,vjuranek/jenkins,protazy/jenkins,pselle/jenkins,azweb76/jenkins,pantheon-systems/jenkins,lvotypko/jenkins2,damianszczepanik/jenkins,jpbriend/jenkins,morficus/jenkins,Ykus/jenkins,vlajos/jenkins,deadmoose/jenkins,bkmeneguello/jenkins,petermarcoen/jenkins,tangkun75/jenkins,SebastienGllmt/jenkins,intelchen/jenkins,shahharsh/jenkins,jcarrothers-sap/jenkins,KostyaSha/jenkins,MichaelPranovich/jenkins_sc,ns163/jenkins,scoheb/jenkins,daniel-beck/jenkins,goldchang/jenkins,Jimilian/jenkins,protazy/jenkins,292388900/jenkins,bpzhang/jenkins,mpeltonen/jenkins,github-api-test-org/jenkins,h4ck3rm1k3/jenkins,iqstack/jenkins,jhoblitt/jenkins,sathiya-mit/jenkins,vivek/hudson,daniel-beck/jenkins,khmarbaise/jenkins,everyonce/jenkins,vlajos/jenkins,292388900/jenkins,alvarolobato/jenkins,1and1/jenkins,csimons/jenkins,vlajos/jenkins,sathiya-mit/jenkins,arcivanov/jenkins,goldchang/jenkins,svanoort/jenkins,keyurpatankar/hudson,seanlin816/jenkins,jtnord/jenkins,Ykus/jenkins,tfennelly/jenkins,lvotypko/jenkins3,aheritier/jenkins,seanlin816/jenkins,andresrc/jenkins,jpederzolli/jenkins-1,lvotypko/jenkins3,liupugong/jenkins,noikiy/jenkins,hashar/jenkins,godfath3r/jenkins,akshayabd/jenkins,h4ck3rm1k3/jenkins,escoem/jenkins,mattclark/jenkins,lilyJi/jenkins,hashar/jenkins,abayer/jenkins,csimons/jenkins,vlajos/jenkins,DoctorQ/jenkins,MadsNielsen/jtemp,KostyaSha/jenkins,akshayabd/jenkins,mdonohue/jenkins,liorhson/jenkins,rlugojr/jenkins,h4ck3rm1k3/jenkins,synopsys-arc-oss/jenkins,vjuranek/jenkins,kohsuke/hudson,gusreiber/jenkins,shahharsh/jenkins,Wilfred/jenkins,MichaelPranovich/jenkins_sc,azweb76/jenkins,noikiy/jenkins,vivek/hudson,hplatou/jenkins,recena/jenkins,hemantojhaa/jenkins,jhoblitt/jenkins,lvotypko/jenkins2,duzifang/my-jenkins,christ66/jenkins,fbelzunc/jenkins,DanielWeber/jenkins,petermarcoen/jenkins,akshayabd/jenkins,hashar/jenkins,arcivanov/jenkins,arcivanov/jenkins,goldchang/jenkins,vvv444/jenkins,DanielWeber/jenkins,maikeffi/hudson,paulmillar/jenkins,stefanbrausch/hudson-main,CodeShane/jenkins,everyonce/jenkins,rlugojr/jenkins,jhoblitt/jenkins,daniel-beck/jenkins,pselle/jenkins,mattclark/jenkins,brunocvcunha/jenkins,samatdav/jenkins,stephenc/jenkins,ikedam/jenkins,pjanouse/jenkins,lilyJi/jenkins,dariver/jenkins,Jochen-A-Fuerbacher/jenkins,oleg-nenashev/jenkins,abayer/jenkins,stephenc/jenkins,mdonohue/jenkins,SenolOzer/jenkins,tastatur/jenkins,albers/jenkins,lindzh/jenkins,MichaelPranovich/jenkins_sc,escoem/jenkins,morficus/jenkins,guoxu0514/jenkins,verbitan/jenkins,rsandell/jenkins,amuniz/jenkins,Krasnyanskiy/jenkins,paulwellnerbou/jenkins,tfennelly/jenkins,paulwellnerbou/jenkins,Jimilian/jenkins,gorcz/jenkins,lvotypko/jenkins,vjuranek/jenkins,Vlatombe/jenkins,amruthsoft9/Jenkis,everyonce/jenkins,huybrechts/hudson,intelchen/jenkins,evernat/jenkins,lordofthejars/jenkins,MadsNielsen/jtemp,recena/jenkins,jzjzjzj/jenkins,AustinKwang/jenkins,AustinKwang/jenkins,evernat/jenkins,mcanthony/jenkins,ndeloof/jenkins,rashmikanta-1984/jenkins,abayer/jenkins,bpzhang/jenkins,jk47/jenkins,tangkun75/jenkins,ns163/jenkins,jhoblitt/jenkins,6WIND/jenkins,liupugong/jenkins,lvotypko/jenkins3,verbitan/jenkins,luoqii/jenkins,chbiel/jenkins,sathiya-mit/jenkins,varmenise/jenkins,keyurpatankar/hudson,soenter/jenkins,MadsNielsen/jtemp,maikeffi/hudson,arcivanov/jenkins,FarmGeek4Life/jenkins,elkingtonmcb/jenkins,patbos/jenkins,vlajos/jenkins,Krasnyanskiy/jenkins,MarkEWaite/jenkins,jtnord/jenkins,khmarbaise/jenkins,huybrechts/hudson,jk47/jenkins,synopsys-arc-oss/jenkins,vvv444/jenkins,sathiya-mit/jenkins,soenter/jenkins,vvv444/jenkins,hplatou/jenkins,ajshastri/jenkins,CodeShane/jenkins,mrobinet/jenkins,DoctorQ/jenkins,h4ck3rm1k3/jenkins,shahharsh/jenkins,amruthsoft9/Jenkis,hemantojhaa/jenkins,rsandell/jenkins,yonglehou/jenkins,escoem/jenkins,rashmikanta-1984/jenkins,svanoort/jenkins,ikedam/jenkins,liupugong/jenkins,jcarrothers-sap/jenkins,albers/jenkins,lindzh/jenkins,samatdav/jenkins,olivergondza/jenkins,Jimilian/jenkins,duzifang/my-jenkins,ChrisA89/jenkins,hemantojhaa/jenkins,goldchang/jenkins,Krasnyanskiy/jenkins,msrb/jenkins,wuwen5/jenkins,escoem/jenkins,daspilker/jenkins,maikeffi/hudson,christ66/jenkins,damianszczepanik/jenkins,olivergondza/jenkins,batmat/jenkins,godfath3r/jenkins,FTG-003/jenkins,Ykus/jenkins,mrobinet/jenkins,rashmikanta-1984/jenkins,deadmoose/jenkins,ndeloof/jenkins,patbos/jenkins,paulmillar/jenkins,csimons/jenkins,amuniz/jenkins,protazy/jenkins,rashmikanta-1984/jenkins,MichaelPranovich/jenkins_sc,dennisjlee/jenkins,arunsingh/jenkins,amuniz/jenkins,elkingtonmcb/jenkins,yonglehou/jenkins,Vlatombe/jenkins,pjanouse/jenkins,FarmGeek4Life/jenkins,arunsingh/jenkins,ndeloof/jenkins,viqueen/jenkins,vivek/hudson,alvarolobato/jenkins,escoem/jenkins,alvarolobato/jenkins,noikiy/jenkins,DanielWeber/jenkins,seanlin816/jenkins,mcanthony/jenkins,rlugojr/jenkins,damianszczepanik/jenkins,varmenise/jenkins,paulwellnerbou/jenkins,arunsingh/jenkins,wangyikai/jenkins,Wilfred/jenkins,FTG-003/jenkins,tfennelly/jenkins,iterate/coding-dojo,github-api-test-org/jenkins,vivek/hudson,liorhson/jenkins,vivek/hudson,dbroady1/jenkins,mattclark/jenkins,v1v/jenkins,hudson/hudson-2.x,wuwen5/jenkins,guoxu0514/jenkins,aheritier/jenkins,lilyJi/jenkins,iqstack/jenkins,synopsys-arc-oss/jenkins,fbelzunc/jenkins,FTG-003/jenkins,tangkun75/jenkins,jzjzjzj/jenkins,varmenise/jenkins,vjuranek/jenkins,iqstack/jenkins,KostyaSha/jenkins,gitaccountforprashant/gittest,patbos/jenkins,vvv444/jenkins,bkmeneguello/jenkins,lvotypko/jenkins2,my7seven/jenkins,DoctorQ/jenkins,pantheon-systems/jenkins,ErikVerheul/jenkins,wuwen5/jenkins,olivergondza/jenkins,jzjzjzj/jenkins,github-api-test-org/jenkins,varmenise/jenkins,synopsys-arc-oss/jenkins,huybrechts/hudson,andresrc/jenkins,msrb/jenkins,DanielWeber/jenkins,jenkinsci/jenkins,wuwen5/jenkins,ydubreuil/jenkins,aldaris/jenkins,kohsuke/hudson,dariver/jenkins,keyurpatankar/hudson,ajshastri/jenkins,viqueen/jenkins,bkmeneguello/jenkins,liorhson/jenkins,mcanthony/jenkins,jenkinsci/jenkins,bkmeneguello/jenkins,godfath3r/jenkins,khmarbaise/jenkins,damianszczepanik/jenkins,scoheb/jenkins,arcivanov/jenkins,1and1/jenkins,gorcz/jenkins,stefanbrausch/hudson-main,paulwellnerbou/jenkins,rsandell/jenkins,jpederzolli/jenkins-1,wangyikai/jenkins,vjuranek/jenkins,jglick/jenkins,verbitan/jenkins,guoxu0514/jenkins,fbelzunc/jenkins,khmarbaise/jenkins,Vlatombe/jenkins,gorcz/jenkins,duzifang/my-jenkins,duzifang/my-jenkins,noikiy/jenkins,aheritier/jenkins,jtnord/jenkins,andresrc/jenkins,gusreiber/jenkins,svanoort/jenkins,amuniz/jenkins,akshayabd/jenkins,pantheon-systems/jenkins,msrb/jenkins,MichaelPranovich/jenkins_sc,alvarolobato/jenkins,batmat/jenkins,Wilfred/jenkins,pselle/jenkins,jzjzjzj/jenkins,liorhson/jenkins,svanoort/jenkins,thomassuckow/jenkins,morficus/jenkins,keyurpatankar/hudson,oleg-nenashev/jenkins,lvotypko/jenkins2,intelchen/jenkins,damianszczepanik/jenkins,samatdav/jenkins,jenkinsci/jenkins,SenolOzer/jenkins,ns163/jenkins,292388900/jenkins,synopsys-arc-oss/jenkins,mpeltonen/jenkins,gusreiber/jenkins,stephenc/jenkins,everyonce/jenkins,yonglehou/jenkins,shahharsh/jenkins,dennisjlee/jenkins,gorcz/jenkins,jcsirot/jenkins,luoqii/jenkins,ErikVerheul/jenkins,mdonohue/jenkins,goldchang/jenkins,liorhson/jenkins,jglick/jenkins,ChrisA89/jenkins,CodeShane/jenkins,jk47/jenkins,Jimilian/jenkins,NehemiahMi/jenkins,gitaccountforprashant/gittest,paulwellnerbou/jenkins,gitaccountforprashant/gittest,mrooney/jenkins,Jochen-A-Fuerbacher/jenkins,CodeShane/jenkins,vlajos/jenkins,bpzhang/jenkins,jpederzolli/jenkins-1,lvotypko/jenkins2,ndeloof/jenkins,kzantow/jenkins,ikedam/jenkins,jzjzjzj/jenkins,rsandell/jenkins,ns163/jenkins,vivek/hudson,ChrisA89/jenkins,1and1/jenkins,DoctorQ/jenkins,jglick/jenkins,rlugojr/jenkins
package hudson.tasks.junit; import hudson.model.AbstractBuild; import hudson.util.IOException2; import hudson.*; import org.apache.tools.ant.DirectoryScanner; import org.dom4j.DocumentException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Root of all the test results for one build. * * @author Kohsuke Kawaguchi */ public final class TestResult extends MetaTabulatedResult { /** * List of all {@link SuiteResult}s in this test. * This is the core data structure to be persisted in the disk. */ private final List<SuiteResult> suites = new ArrayList<SuiteResult>(); /** * {@link #suites} keyed by their names for faster lookup. */ private transient Map<String,SuiteResult> suitesByName; /** * Results tabulated by package. */ private transient Map<String,PackageResult> byPackages; // set during the freeze phase private transient TestResultAction parent; /** * Number of all tests. */ private transient int totalTests; /** * Number of failed/error tests. */ private transient List<CaseResult> failedTests; /** * Creates an empty result. */ TestResult() { } /** * Collect reports from the given {@link DirectoryScanner}, while * filtering out all files that were created before the given tiem. */ public TestResult(long buildTime, DirectoryScanner results) throws IOException { String[] includedFiles = results.getIncludedFiles(); File baseDir = results.getBasedir(); boolean parsed=false; for (String value : includedFiles) { File reportFile = new File(baseDir, value); // only count files that were actually updated during this build if(buildTime <= reportFile.lastModified()) { parse(reportFile); parsed = true; } } if(!parsed) { long localTime = System.currentTimeMillis(); if(localTime < buildTime) // build time is in the the future. clock on this slave must be running behind throw new AbortException( "Clock on this slave is out of sync with the master, and therefore \n" + "I can't figure out what test results are new and what are old.\n" + "Please keep the slave clock in sync with the master."); File f = new File(baseDir,includedFiles[0]); throw new AbortException( String.format( "Test reports were found but none of them are new. Did tests run? \n"+ "For example, %s is %s old\n", f, Util.getTimeSpanString(buildTime-f.lastModified()))); } } /** * Parses an additional report file. */ public void parse(File reportFile) throws IOException { try { suites.add(new SuiteResult(reportFile)); } catch (RuntimeException e) { throw new IOException2("Failed to read "+reportFile,e); } catch (DocumentException e) { if(!reportFile.getPath().endsWith(".xml")) throw new IOException2("Failed to read "+reportFile+"\n"+ "Is this really a JUnit report file? Your configuration must be matching too many files",e); else throw new IOException2("Failed to read "+reportFile,e); } } public String getDisplayName() { return "Test Result"; } public AbstractBuild<?,?> getOwner() { return parent.owner; } @Override public TestResult getPreviousResult() { TestResultAction p = parent.getPreviousResult(); if(p!=null) return p.getResult(); else return null; } public String getTitle() { return "Test Result"; } public String getChildTitle() { return "Package"; } @Override public int getPassCount() { return totalTests-getFailCount(); } @Override public int getFailCount() { return failedTests.size(); } @Override public List<CaseResult> getFailedTests() { return failedTests; } @Override public Collection<PackageResult> getChildren() { return byPackages.values(); } public PackageResult getDynamic(String packageName, StaplerRequest req, StaplerResponse rsp) { return byPackage(packageName); } public PackageResult byPackage(String packageName) { return byPackages.get(packageName); } public SuiteResult getSuite(String name) { return suitesByName.get(name); } /** * Builds up the transient part of the data structure * from results {@link #parse(File) parsed} so far. * * <p> * After the data is frozen, more files can be parsed * and then freeze can be called again. */ public void freeze(TestResultAction parent) { this.parent = parent; if(suitesByName==null) { // freeze for the first time suitesByName = new HashMap<String,SuiteResult>(); totalTests = 0; failedTests = new ArrayList<CaseResult>(); byPackages = new TreeMap<String,PackageResult>(); } for (SuiteResult s : suites) { if(!s.freeze(this)) continue; suitesByName.put(s.getName(),s); totalTests += s.getCases().size(); for(CaseResult cr : s.getCases()) { if(!cr.isPassed()) failedTests.add(cr); String pkg = cr.getPackageName(); PackageResult pr = byPackage(pkg); if(pr==null) byPackages.put(pkg,pr=new PackageResult(this,pkg)); pr.add(cr); } } Collections.sort(failedTests,CaseResult.BY_AGE); for (PackageResult pr : byPackages.values()) pr.freeze(); } }
core/src/main/java/hudson/tasks/junit/TestResult.java
package hudson.tasks.junit; import hudson.model.AbstractBuild; import hudson.util.IOException2; import hudson.*; import org.apache.tools.ant.DirectoryScanner; import org.dom4j.DocumentException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Root of all the test results for one build. * * @author Kohsuke Kawaguchi */ public final class TestResult extends MetaTabulatedResult { /** * List of all {@link SuiteResult}s in this test. * This is the core data structure to be persisted in the disk. */ private final List<SuiteResult> suites = new ArrayList<SuiteResult>(); /** * {@link #suites} keyed by their names for faster lookup. */ private transient Map<String,SuiteResult> suitesByName; /** * Results tabulated by package. */ private transient Map<String,PackageResult> byPackages; // set during the freeze phase private transient TestResultAction parent; /** * Number of all tests. */ private transient int totalTests; /** * Number of failed/error tests. */ private transient List<CaseResult> failedTests; /** * Creates an empty result. */ TestResult() { } /** * Collect reports from the given {@link DirectoryScanner}, while * filtering out all files that were created before the given tiem. */ public TestResult(long buildTime, DirectoryScanner results) throws IOException { String[] includedFiles = results.getIncludedFiles(); File baseDir = results.getBasedir(); boolean parsed=false; for (String value : includedFiles) { File reportFile = new File(baseDir, value); // only count files that were actually updated during this build if(buildTime <= reportFile.lastModified()) { parse(reportFile); parsed = true; } } if(!parsed) { long localTime = System.currentTimeMillis(); if(localTime < buildTime) // build time is in the the future. clock on this slave must be running behind throw new AbortException( "Clock on this slave is out of sync with the master, and therefore I" + "can't figure out what test results are new and what are old." + "Please keep the slave clock in sync with the master."); File f = new File(baseDir,includedFiles[0]); throw new AbortException( String.format( "Test reports were found but none of them are new. Did tests run? "+ "For example, %s is %s old\n", f, Util.getTimeSpanString(buildTime-f.lastModified()))); } } /** * Parses an additional report file. */ public void parse(File reportFile) throws IOException { try { suites.add(new SuiteResult(reportFile)); } catch (RuntimeException e) { throw new IOException2("Failed to read "+reportFile,e); } catch (DocumentException e) { if(!reportFile.getPath().endsWith(".xml")) throw new IOException2("Failed to read "+reportFile+"\n"+ "Is this really a JUnit report file? Your configuration must be matching too many files",e); else throw new IOException2("Failed to read "+reportFile,e); } } public String getDisplayName() { return "Test Result"; } public AbstractBuild<?,?> getOwner() { return parent.owner; } @Override public TestResult getPreviousResult() { TestResultAction p = parent.getPreviousResult(); if(p!=null) return p.getResult(); else return null; } public String getTitle() { return "Test Result"; } public String getChildTitle() { return "Package"; } @Override public int getPassCount() { return totalTests-getFailCount(); } @Override public int getFailCount() { return failedTests.size(); } @Override public List<CaseResult> getFailedTests() { return failedTests; } @Override public Collection<PackageResult> getChildren() { return byPackages.values(); } public PackageResult getDynamic(String packageName, StaplerRequest req, StaplerResponse rsp) { return byPackage(packageName); } public PackageResult byPackage(String packageName) { return byPackages.get(packageName); } public SuiteResult getSuite(String name) { return suitesByName.get(name); } /** * Builds up the transient part of the data structure * from results {@link #parse(File) parsed} so far. * * <p> * After the data is frozen, more files can be parsed * and then freeze can be called again. */ public void freeze(TestResultAction parent) { this.parent = parent; if(suitesByName==null) { // freeze for the first time suitesByName = new HashMap<String,SuiteResult>(); totalTests = 0; failedTests = new ArrayList<CaseResult>(); byPackages = new TreeMap<String,PackageResult>(); } for (SuiteResult s : suites) { if(!s.freeze(this)) continue; suitesByName.put(s.getName(),s); totalTests += s.getCases().size(); for(CaseResult cr : s.getCases()) { if(!cr.isPassed()) failedTests.add(cr); String pkg = cr.getPackageName(); PackageResult pr = byPackage(pkg); if(pr==null) byPackages.put(pkg,pr=new PackageResult(this,pkg)); pr.add(cr); } } Collections.sort(failedTests,CaseResult.BY_AGE); for (PackageResult pr : byPackages.values()) pr.freeze(); } }
adding new lines for better readability. git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@4403 71c3de6d-444a-0410-be80-ed276b4c234a
core/src/main/java/hudson/tasks/junit/TestResult.java
adding new lines for better readability.
<ide><path>ore/src/main/java/hudson/tasks/junit/TestResult.java <ide> if(localTime < buildTime) <ide> // build time is in the the future. clock on this slave must be running behind <ide> throw new AbortException( <del> "Clock on this slave is out of sync with the master, and therefore I" + <del> "can't figure out what test results are new and what are old." + <add> "Clock on this slave is out of sync with the master, and therefore \n" + <add> "I can't figure out what test results are new and what are old.\n" + <ide> "Please keep the slave clock in sync with the master."); <ide> <ide> File f = new File(baseDir,includedFiles[0]); <ide> throw new AbortException( <ide> String.format( <del> "Test reports were found but none of them are new. Did tests run? "+ <add> "Test reports were found but none of them are new. Did tests run? \n"+ <ide> "For example, %s is %s old\n", f, <ide> Util.getTimeSpanString(buildTime-f.lastModified()))); <ide> }
JavaScript
mit
ae5f9b61c4b99e409e7f700e4b27a601468cac1b
0
GreenCore/icecat
'use strict'; const https = require('https'); const parseString = require('xml2js').parseString; const icecatProduct = require('./product'); /** * * @param instance */ const openCatalog = function(instance) { this.icecat = instance || {}; } /** * getProduct * @param lang * @param GTIN * @returns {Promise} */ openCatalog.prototype.getProduct = function(lang, GTIN) { const httpRequestUrl = this._getBaseUrl(lang) + ';ean_upc=' + GTIN; return this._requestProduct(httpRequestUrl); } /** * Get product by it's id. * * @param {string} lang * @param {integer} productId */ openCatalog.prototype.getByProductId = function(lang, productId) { const httpRequestUrl = this._getBaseUrl(lang) + ';product_id=' + productId; return this._requestProduct(httpRequestUrl); } /** * Create base url. * * @param {string} lang */ openCatalog.prototype._getBaseUrl = function(lang) { const argLANG = 'lang=' + lang; const argOutput = ';output=productxml'; const httpRequestUrl = this.icecat.scheme + this.icecat.httpAuth + '@' + this.icecat.httpUrl + '?' + argLANG + argOutput; return httpRequestUrl; } /** * Fetch the product by the http request url. * * @param httpRequestUrl * @returns {Promise} */ openCatalog.prototype._requestProduct = function(httpRequestUrl) { return new Promise( function(resolve, reject) { let request = https.get(httpRequestUrl, function(response) { let body = ''; response.on('data', function(chunk) { body += chunk; }); response.on('end', function() { parseString(body, function(err, jsonData) { if (err) { return reject(err); } return resolve(new icecatProduct(jsonData, body, httpRequestUrl)); }); }); }); request.on('error', function(err) { return reject(err); }); } ) } module.exports = openCatalog;
lib/OpenCatalog/service.js
'use strict'; const https = require('https'); const parseString = require('xml2js').parseString; const icecatProduct = require('./product'); /** * * @param instance */ const openCatalog = function (instance) { this.icecat = instance || {}; } /** * getProduct * @param lang * @param GTIN * @returns {Promise} */ openCatalog.prototype.getProduct = function (lang, GTIN) { const _this = this; return new Promise( function (resolve, reject) { const argGTIN = 'ean_upc=' + GTIN; const argLANG = ';lang=' + lang; const argOutput = ';output=productxml'; const httpRequestUrl = _this.icecat.scheme + _this.icecat.httpAuth + '@' + _this.icecat.httpUrl + '?' + argGTIN + argLANG + argOutput; let request = https.get(httpRequestUrl, function (response) { let body = ''; response.on('data', function (chunk) { body += chunk; }); response.on('end', function () { parseString(body, function (err, jsonData) { if (err) { return reject(err); } return resolve(new icecatProduct(jsonData, body, httpRequestUrl)); }); }); }); request.on('error', function (err) { return reject(err); }); }); } module.exports = openCatalog;
add #getByProductId method
lib/OpenCatalog/service.js
add #getByProductId method
<ide><path>ib/OpenCatalog/service.js <ide> * <ide> * @param instance <ide> */ <del>const openCatalog = function (instance) { <add>const openCatalog = function(instance) { <ide> this.icecat = instance || {}; <ide> } <ide> <ide> * @param GTIN <ide> * @returns {Promise} <ide> */ <del>openCatalog.prototype.getProduct = function (lang, GTIN) { <del> const _this = this; <add>openCatalog.prototype.getProduct = function(lang, GTIN) { <add> const httpRequestUrl = this._getBaseUrl(lang) + ';ean_upc=' + GTIN; <ide> <add> return this._requestProduct(httpRequestUrl); <add>} <add> <add>/** <add> * Get product by it's id. <add> * <add> * @param {string} lang <add> * @param {integer} productId <add> */ <add>openCatalog.prototype.getByProductId = function(lang, productId) { <add> const httpRequestUrl = this._getBaseUrl(lang) + ';product_id=' + productId; <add> <add> return this._requestProduct(httpRequestUrl); <add>} <add> <add>/** <add> * Create base url. <add> * <add> * @param {string} lang <add> */ <add>openCatalog.prototype._getBaseUrl = function(lang) { <add> const argLANG = 'lang=' + lang; <add> const argOutput = ';output=productxml'; <add> const httpRequestUrl = <add> this.icecat.scheme + <add> this.icecat.httpAuth + '@' + <add> this.icecat.httpUrl + '?' + <add> argLANG + <add> argOutput; <add> <add> return httpRequestUrl; <add>} <add> <add>/** <add> * Fetch the product by the http request url. <add> * <add> * @param httpRequestUrl <add> * @returns {Promise} <add> */ <add>openCatalog.prototype._requestProduct = function(httpRequestUrl) { <ide> return new Promise( <del> function (resolve, reject) { <del> const argGTIN = 'ean_upc=' + GTIN; <del> const argLANG = ';lang=' + lang; <del> const argOutput = ';output=productxml'; <add> function(resolve, reject) { <add> let request = https.get(httpRequestUrl, function(response) { <ide> <del> const httpRequestUrl = <del> _this.icecat.scheme + <del> _this.icecat.httpAuth + '@' + <del> _this.icecat.httpUrl + '?' + <del> argGTIN + <del> argLANG + <del> argOutput; <add> let body = ''; <ide> <del> let request = https.get(httpRequestUrl, function (response) { <del> let body = ''; <del> response.on('data', function (chunk) { <add> response.on('data', function(chunk) { <ide> body += chunk; <ide> }); <del> response.on('end', function () { <del> parseString(body, function (err, jsonData) { <add> <add> response.on('end', function() { <add> parseString(body, function(err, jsonData) { <ide> if (err) { <ide> return reject(err); <ide> } <ide> }); <ide> }); <ide> <del> request.on('error', function (err) { <add> request.on('error', function(err) { <ide> return reject(err); <ide> }); <del> <del> }); <add> } <add> ) <ide> } <ide> <ide> module.exports = openCatalog;
Java
apache-2.0
694d9a6e6ac61a97c591c3471b5615cbaa07cb51
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2001-2006 Janne Jalkanen ([email protected]) This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki.event; import java.lang.ref.WeakReference; import java.util.*; import org.apache.log4j.Logger; /** * A singleton class that manages the addition and removal of WikiEvent * listeners to a event source, as well as the firing of events to those * listeners. An "event source" is the object delegating its event * handling to an inner delegating class supplied by this manager. The * class being serviced is considered a "client" of the delegate. The * WikiEventManager operates across any number of simultaneously-existing * WikiEngines since it manages all delegation on a per-object basis. * Anything that might fire a WikiEvent (or any of its subclasses) can be * a client. * </p> * * <h3>Using a Delegate for Event Listener Management</h3> * <p> * Basically, rather than have all manner of client classes maintain their * own listener lists, add and remove listener methods, any class wanting * to attach listeners can simply request a delegate object to provide that * service. The delegate handles the listener list, the add and remove * listener methods. Firing events is then a matter of calling the * WikiEventManager's {@link #fireEvent(Object,WikiEvent)} method, where * the Object is the client. Prior to instantiating the event object, the * client can call {@link #isListening(Object)} to see there are any * listeners attached to its delegate. * </p> * * <h3>Adding Listeners</h3> * <p> * Adding a WikiEventListener to an object is very simple: * </p> * <pre> * WikiEventManager.addWikiEventListener(object,listener); * </pre> * * <h3>Removing Listeners</h3> * <p> * Removing a WikiEventListener from an object is very simple: * </p> * <pre> * WikiEventManager.removeWikiEventListener(object,listener); * </pre> * If you only have a reference to the listener, the following method * will remove it from any clients managed by the WikiEventManager: * <pre> * WikiEventManager.removeWikiEventListener(listener); * </pre> * * <h3>Backward Compatibility: Replacing Existing <tt>fireEvent()</tt> Methods</h3> * <p> * Using one manager for all events processing permits consolidation of all event * listeners and their associated methods in one place rather than having them * attached to specific subcomponents of an application, and avoids a great deal * of event-related cut-and-paste code. Convenience methods that call the * WikiEventManager for event delegation can be written to maintain existing APIs. * </p> * <p> * For example, an existing <tt>fireEvent()</tt> method might look something like * this: * </p> * <pre> * protected final void fireEvent( WikiEvent event ) * { * for ( Iterator it = m_listeners.iterator(); it.hasNext(); ) * { * WikiEventListener listener = (WikiEventListener)it.next(); * listener.actionPerformed(event); * } * } * </pre> * <p> * One disadvantage is that the above method is supplied with event objects, * which are created even when no listener exists for them. In a busy wiki * with many users unused/unnecessary event creation could be considerable. * Another advantage is that in addition to the iterator, there must be code * to support the addition and remove of listeners. The above could be * replaced with the below code (and with no necessary local support for * adding and removing listeners): * </p> * <pre> * protected final void fireEvent( int type ) * { * if ( WikiEventManager.isListening(this) ) * { * WikiEventManager.fireEvent(this,new WikiEngineEvent(this,type)); * } * } * </pre> * <p> * This only needs to be customized to supply the specific parameters for * whatever WikiEvent you want to create. * </p> * * <h3 id="preloading">Preloading Listeners</h3> * <p> * This may be used to create listeners for objects that don't yet exist, * particularly designed for embedded applications that need to be able * to listen for the instantiation of an Object, by maintaining a cache * of client-less WikiEvent sources that set their client upon being * popped from the cache. Each time any of the methods expecting a client * parameter is called with a null parameter it will preload an internal * cache with a client-less delegate object that will be popped and * returned in preference to creating a new object. This can have unwanted * side effects if there are multiple clients populating the cache with * listeners. The only check is for a Class match, so be aware if others * might be populating the client-less cache with listeners. * </p> * <h3>Listener lifecycle</h3> * <p> * Note that in most cases it is not necessary to remove a listener. * As of 2.4.97, the listeners are stored as WeakReferences, and will be * automatically cleaned at the next garbage collection, if you no longer * hold a reference to them. Of course, until the garbage is collected, * your object might still be getting events, so if you wish to avoid that, * please remove it explicitly as described above. * </p> * @author Murray Altheim * @since 2.4.20 */ public class WikiEventManager { private static final Logger log = Logger.getLogger(WikiEventManager.class); /* If true, permits a WikiEventMonitor to be set. */ private static boolean permitMonitor = false; /* Optional listener to be used as all-event monitor. */ private static WikiEventListener c_monitor = null; /* The Map of client object to WikiEventDelegate. */ private final Map m_delegates = new HashMap(); /* The Vector containing any preloaded WikiEventDelegates. */ private final Vector m_preloadCache = new Vector(); /* Singleton instance of the WikiEventManager. */ private static WikiEventManager c_instance = null; // ............ /** * Constructor for a WikiEventManager. */ private WikiEventManager() { c_instance = this; log.debug("instantiated WikiEventManager"); } /** * As this is a singleton class, this returns the single * instance of this class provided with the property file * filename and bit-wise application settings. * * @return A shared instance of the WikiEventManager */ public static WikiEventManager getInstance() { if( c_instance == null ) { synchronized( WikiEventManager.class ) { WikiEventManager mgr = new WikiEventManager(); // start up any post-instantiation services here return mgr; } } return c_instance; } // public/API methods ...................................................... /** * Registers a WikiEventListener with a WikiEventDelegate for * the provided client object. * * <h3>Monitor Listener</h3> * * If <tt>client</tt> is a reference to the WikiEventManager class * itself and the compile-time flag {@link #permitMonitor} is true, * this attaches the listener as an all-event monitor, overwriting * any previous listener (hence returning true). * <p> * You can remove any existing monitor by either calling this method * with <tt>client</tt> as a reference to this class and the * <tt>listener</tt> parameter as null, or * {@link #removeWikiEventListener(Object,WikiEventListener)} with a * <tt>client</tt> as a reference to this class. The <tt>listener</tt> * parameter in this case is ignored. * * @param client the client of the event source * @param listener the event listener * @return true if the listener was added (i.e., it was not already in the list and was added) */ public static final boolean addWikiEventListener( Object client, WikiEventListener listener ) { if ( client == WikiEventManager.class ) { if ( permitMonitor ) c_monitor = listener; return permitMonitor; } else { WikiEventDelegate delegate = getInstance().getDelegateFor(client); return delegate.addWikiEventListener(listener); } } /** * Un-registers a WikiEventListener with the WikiEventDelegate for * the provided client object. * * @param client the client of the event source * @param listener the event listener * @return true if the listener was found and removed. */ public static final boolean removeWikiEventListener( Object client, WikiEventListener listener ) { if ( client == WikiEventManager.class ) { c_monitor = null; return true; } else { WikiEventDelegate delegate = getInstance().getDelegateFor(client); return delegate.removeWikiEventListener(listener); } } /** * Return the Set containing the WikiEventListeners attached to the * delegate for the supplied client. If there are no attached listeners, * returns an empty Iterator rather than null. Note that this will * create a delegate for the client if it did not exist prior to the call. * * <h3>NOTE</h3> * <p> * This method returns a Set rather than an Iterator because of the high * likelihood of the Set being modified while an Iterator might be active. * This returns an unmodifiable reference to the actual Set containing * the delegate's listeners. Any attempt to modify the Set will throw an * {@link java.lang.UnsupportedOperationException}. This method is not * synchronized and it should be understood that the composition of the * backing Set may change at any time. * </p> * * @param client the client of the event source * @return an unmodifiable Set containing the WikiEventListeners attached to the client * @throws java.lang.UnsupportedOperationException if any attempt is made to modify the Set */ public static final Set getWikiEventListeners( Object client ) throws UnsupportedOperationException { WikiEventDelegate delegate = getInstance().getDelegateFor(client); return delegate.getWikiEventListeners(); } /** * Un-registers a WikiEventListener from any WikiEventDelegate client managed by this * WikiEventManager. Since this is a one-to-one relation, the first match will be * returned upon removal; a true return value indicates the WikiEventListener was * found and removed. * * @param listener the event listener * @return true if the listener was found and removed. */ public static final boolean removeWikiEventListener( WikiEventListener listener ) { // get the Map.entry object for the entire Map, then check match on entry (listener) WikiEventManager mgr = getInstance(); Map sources = mgr.getDelegates(); synchronized( sources ) { // get an iterator over the Map.Enty objects in the map Iterator it = sources.entrySet().iterator(); while( it.hasNext() ) { Map.Entry entry = (Map.Entry)it.next(); // the entry value is the delegate WikiEventDelegate delegate = (WikiEventDelegate)entry.getValue(); // now see if we can remove the listener from the delegate // (delegate may be null because this is a weak reference) if( delegate != null && delegate.removeWikiEventListener(listener) ) { return true; // was removed } } } return false; } /** * Returns true if there are one or more listeners registered with * the provided client Object (undelegated event source). This locates * any delegate and checks to see if it has any listeners attached. * * @param client the client Object * @return True, if there is a listener for this client object. */ public static boolean isListening( Object client ) { WikiEventDelegate source = getInstance().getDelegateFor(client); return source != null ? source.isListening() : false ; } /** * Notify all listeners of the WikiEventDelegate having a registered * interest in change events of the supplied WikiEvent. * * @param client the client initiating the event. * @param event the WikiEvent to fire. */ public static void fireEvent( Object client, WikiEvent event ) { WikiEventDelegate source = getInstance().getDelegateFor(client); if ( source != null ) source.fireEvent(event); if ( c_monitor != null ) c_monitor.actionPerformed(event); } // private and utility methods ............................................. /** * Return the client-to-delegate Map. */ private Map getDelegates() { return m_delegates; } /** * Returns a WikiEventDelegate for the provided client Object. * If the parameter is a class reference, will generate and return a * client-less WikiEventDelegate. If the parameter is not a Class and * the delegate cache contains any objects matching the Class of any * delegates in the cache, the first Class-matching delegate will be * used in preference to creating a new delegate. * If a null parameter is supplied, this will create a client-less * delegate that will attach to the first incoming client (i.e., * there will be no Class-matching requirement). * * @param client the client Object, or alternately a Class reference * @return the WikiEventDelegate. */ private WikiEventDelegate getDelegateFor( Object client ) { synchronized( m_delegates ) { if( client == null || client instanceof Class ) // then preload the cache { WikiEventDelegate delegate = new WikiEventDelegate(client); m_preloadCache.add(delegate); m_delegates.put( client, delegate ); return delegate; } else if( !m_preloadCache.isEmpty() ) { // then see if any of the cached delegates match the class of the incoming client for( int i = m_preloadCache.size()-1 ; i >= 0 ; i-- ) // start with most-recently added { WikiEventDelegate delegate = (WikiEventDelegate)m_preloadCache.elementAt(i); if( delegate.getClientClass() == null || delegate.getClientClass().equals(client.getClass()) ) { // we have a hit, so use it, but only on a client we haven't seen before if( !m_delegates.keySet().contains(client) ) { m_preloadCache.remove(delegate); m_delegates.put( client, delegate ); return delegate; } } } } // otherwise treat normally... WikiEventDelegate delegate = (WikiEventDelegate)m_delegates.get( client ); if( delegate == null ) { delegate = new WikiEventDelegate( client ); m_delegates.put( client, delegate ); } return delegate; } } // ......................................................................... /** * Inner delegating class that manages event listener addition and * removal. Classes that generate events can obtain an instance of * this class from the WikiEventManager and delegate responsibility * to it. Interaction with this delegating class is done via the * methods of the {@link WikiEventDelegate} API. * * @author Murray Altheim * @since 2.4.20 */ private static final class WikiEventDelegate { /* A list of event listeners for this instance. */ private ArrayList m_listenerList = new ArrayList(); private Class m_class = null; /** * Constructor for an WikiEventDelegateImpl, provided * with the client Object it will service, or the Class * of client, the latter when used to preload a future * incoming delegate. */ protected WikiEventDelegate( Object client ) { if( client instanceof Class ) { m_class = (Class)client; } } /** * Returns the class of the client-less delegate, null if * this delegate is attached to a client Object. */ protected Class getClientClass() { return m_class; } /** * Return an unmodifiable Set containing the WikiEventListeners of * this WikiEventDelegateImpl. If there are no attached listeners, * returns an empty Set rather than null. * * @return an unmodifiable Set containing this delegate's WikiEventListeners * @throws java.lang.UnsupportedOperationException if any attempt is made to modify the Set */ public Set getWikiEventListeners() { synchronized( m_listenerList ) { TreeSet set = new TreeSet( new WikiEventListenerComparator() ); for( Iterator i = m_listenerList.iterator(); i.hasNext(); ) { WikiEventListener l = (WikiEventListener) ((WeakReference)i.next()).get(); if( l != null ) { set.add( l ); } } return Collections.unmodifiableSet(set); } } /** * Adds <tt>listener</tt> as a listener for events fired by the WikiEventDelegate. * * @param listener the WikiEventListener to be added * @return true if the listener was added (i.e., it was not already in the list and was added) */ public boolean addWikiEventListener( WikiEventListener listener ) { synchronized( m_listenerList ) { return m_listenerList.add( new WeakReference(listener) ); } } /** * Removes <tt>listener</tt> from the WikiEventDelegate. * * @param listener the WikiEventListener to be removed * @return true if the listener was removed (i.e., it was actually in the list and was removed) */ public boolean removeWikiEventListener( WikiEventListener listener ) { synchronized( m_listenerList ) { for( Iterator i = m_listenerList.iterator(); i.hasNext(); ) { WikiEventListener l = (WikiEventListener) ((WeakReference)i.next()).get(); if( l == listener ) { i.remove(); return true; } } } return false; } /** * Returns true if there are one or more listeners registered * with this instance. */ public boolean isListening() { synchronized( m_listenerList ) { return !m_listenerList.isEmpty(); } } /** * Notify all listeners having a registered interest * in change events of the supplied WikiEvent. */ public void fireEvent( WikiEvent event ) { boolean needsCleanup = false; try { synchronized( m_listenerList ) { for( int i = 0; i < m_listenerList.size(); i++ ) { WikiEventListener listener = (WikiEventListener) ((WeakReference)m_listenerList.get(i)).get(); if( listener != null ) { listener.actionPerformed( event ); } else { needsCleanup = true; } } // // Remove all such listeners which have expired // if( needsCleanup ) { for( int i = 0; i < m_listenerList.size(); i++ ) { WeakReference w = (WeakReference)m_listenerList.get(i); if( w.get() == null ) m_listenerList.remove(i--); } } } } catch( ConcurrentModificationException e ) { // // We don't die, we just don't do notifications in that case. // log.info("Concurrent modification of event list; please report this.",e); } } } // end inner class WikiEventDelegate private static class WikiEventListenerComparator implements Comparator { // TODO: This method is a critical performance bottleneck public int compare(Object arg0, Object arg1) { if( arg0 instanceof WikiEventListener && arg1 instanceof WikiEventListener ) { WikiEventListener w0 = (WikiEventListener) arg0; WikiEventListener w1 = (WikiEventListener) arg1; if( w1 == w0 || w0.equals(w1) ) return 0; return w1.hashCode() - w0.hashCode(); } throw new ClassCastException( arg1.getClass().getName() + " != " + arg0.getClass().getName() ); } } } // end com.ecyrd.jspwiki.event.WikiEventManager
src/com/ecyrd/jspwiki/event/WikiEventManager.java
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2001-2006 Janne Jalkanen ([email protected]) This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki.event; import java.lang.ref.WeakReference; import java.util.*; import org.apache.log4j.Logger; /** * A singleton class that manages the addition and removal of WikiEvent * listeners to a event source, as well as the firing of events to those * listeners. An "event source" is the object delegating its event * handling to an inner delegating class supplied by this manager. The * class being serviced is considered a "client" of the delegate. The * WikiEventManager operates across any number of simultaneously-existing * WikiEngines since it manages all delegation on a per-object basis. * Anything that might fire a WikiEvent (or any of its subclasses) can be * a client. * </p> * * <h3>Using a Delegate for Event Listener Management</h3> * <p> * Basically, rather than have all manner of client classes maintain their * own listener lists, add and remove listener methods, any class wanting * to attach listeners can simply request a delegate object to provide that * service. The delegate handles the listener list, the add and remove * listener methods. Firing events is then a matter of calling the * WikiEventManager's {@link #fireEvent(Object,WikiEvent)} method, where * the Object is the client. Prior to instantiating the event object, the * client can call {@link #isListening(Object)} to see there are any * listeners attached to its delegate. * </p> * * <h3>Adding Listeners</h3> * <p> * Adding a WikiEventListener to an object is very simple: * </p> * <pre> * WikiEventManager.addWikiEventListener(object,listener); * </pre> * * <h3>Removing Listeners</h3> * <p> * Removing a WikiEventListener from an object is very simple: * </p> * <pre> * WikiEventManager.removeWikiEventListener(object,listener); * </pre> * If you only have a reference to the listener, the following method * will remove it from any clients managed by the WikiEventManager: * <pre> * WikiEventManager.removeWikiEventListener(listener); * </pre> * * <h3>Backward Compatibility: Replacing Existing <tt>fireEvent()</tt> Methods</h3> * <p> * Using one manager for all events processing permits consolidation of all event * listeners and their associated methods in one place rather than having them * attached to specific subcomponents of an application, and avoids a great deal * of event-related cut-and-paste code. Convenience methods that call the * WikiEventManager for event delegation can be written to maintain existing APIs. * </p> * <p> * For example, an existing <tt>fireEvent()</tt> method might look something like * this: * </p> * <pre> * protected final void fireEvent( WikiEvent event ) * { * for ( Iterator it = m_listeners.iterator(); it.hasNext(); ) * { * WikiEventListener listener = (WikiEventListener)it.next(); * listener.actionPerformed(event); * } * } * </pre> * <p> * One disadvantage is that the above method is supplied with event objects, * which are created even when no listener exists for them. In a busy wiki * with many users unused/unnecessary event creation could be considerable. * Another advantage is that in addition to the iterator, there must be code * to support the addition and remove of listeners. The above could be * replaced with the below code (and with no necessary local support for * adding and removing listeners): * </p> * <pre> * protected final void fireEvent( int type ) * { * if ( WikiEventManager.isListening(this) ) * { * WikiEventManager.fireEvent(this,new WikiEngineEvent(this,type)); * } * } * </pre> * <p> * This only needs to be customized to supply the specific parameters for * whatever WikiEvent you want to create. * </p> * * <h3 id="preloading">Preloading Listeners</h3> * <p> * This may be used to create listeners for objects that don't yet exist, * particularly designed for embedded applications that need to be able * to listen for the instantiation of an Object, by maintaining a cache * of client-less WikiEvent sources that set their client upon being * popped from the cache. Each time any of the methods expecting a client * parameter is called with a null parameter it will preload an internal * cache with a client-less delegate object that will be popped and * returned in preference to creating a new object. This can have unwanted * side effects if there are multiple clients populating the cache with * listeners. The only check is for a Class match, so be aware if others * might be populating the client-less cache with listeners. * </p> * <h3>Listener lifecycle</h3> * <p> * Note that in most cases it is not necessary to remove a listener. * As of 2.4.97, the listeners are stored as WeakReferences, and will be * automatically cleaned at the next garbage collection, if you no longer * hold a reference to them. Of course, until the garbage is collected, * your object might still be getting events, so if you wish to avoid that, * please remove it explicitly as described above. * </p> * @author Murray Altheim * @since 2.4.20 */ public class WikiEventManager { private static final Logger log = Logger.getLogger(WikiEventManager.class); /* The Map of client object to WikiEventDelegate. */ private final Map m_delegates = new HashMap(); /* The Vector containing any preloaded WikiEventDelegates. */ private final Vector m_preloadCache = new Vector(); /* Singleton instance of the WikiEventManager. */ private static WikiEventManager c_instance = null; // ............ /** * Constructor for a WikiEventManager. */ private WikiEventManager() { c_instance = this; log.debug("instantiated WikiEventManager"); } /** * As this is a singleton class, this returns the single * instance of this class provided with the property file * filename and bit-wise application settings. * * @return A shared instance of the WikiEventManager */ public static WikiEventManager getInstance() { if( c_instance == null ) { synchronized( WikiEventManager.class ) { WikiEventManager mgr = new WikiEventManager(); // start up any post-instantiation services here return mgr; } } return c_instance; } // public/API methods ...................................................... /** * Registers a WikiEventListener with a WikiEventDelegate for * the provided client object. * * @param client the client of the event source * @param listener the event listener * @return true if the listener was added (i.e., it was not already in the list and was added) */ public static final boolean addWikiEventListener( Object client, WikiEventListener listener ) { WikiEventDelegate delegate = getInstance().getDelegateFor(client); return delegate.addWikiEventListener(listener); } /** * Un-registers a WikiEventListener with the WikiEventDelegate for * the provided client object. * * @param client the client of the event source * @param listener the event listener * @return true if the listener was found and removed. */ public static final boolean removeWikiEventListener( Object client, WikiEventListener listener ) { WikiEventDelegate delegate = getInstance().getDelegateFor(client); return delegate.removeWikiEventListener(listener); } /** * Return the Set containing the WikiEventListeners attached to the * delegate for the supplied client. If there are no attached listeners, * returns an empty Iterator rather than null. Note that this will * create a delegate for the client if it did not exist prior to the call. * * <h3>NOTE</h3> * <p> * This method returns a Set rather than an Iterator because of the high * likelihood of the Set being modified while an Iterator might be active. * This returns an unmodifiable reference to the actual Set containing * the delegate's listeners. Any attempt to modify the Set will throw an * {@link java.lang.UnsupportedOperationException}. This method is not * synchronized and it should be understood that the composition of the * backing Set may change at any time. * </p> * * @param client the client of the event source * @return an unmodifiable Set containing the WikiEventListeners attached to the client * @throws java.lang.UnsupportedOperationException if any attempt is made to modify the Set */ public static final Set getWikiEventListeners( Object client ) throws UnsupportedOperationException { WikiEventDelegate delegate = getInstance().getDelegateFor(client); return delegate.getWikiEventListeners(); } /** * Un-registers a WikiEventListener from any WikiEventDelegate client managed by this * WikiEventManager. Since this is a one-to-one relation, the first match will be * returned upon removal; a true return value indicates the WikiEventListener was * found and removed. * * @param listener the event listener * @return true if the listener was found and removed. */ public static final boolean removeWikiEventListener( WikiEventListener listener ) { // get the Map.entry object for the entire Map, then check match on entry (listener) WikiEventManager mgr = getInstance(); Map sources = mgr.getDelegates(); synchronized( sources ) { // get an iterator over the Map.Enty objects in the map Iterator it = sources.entrySet().iterator(); while( it.hasNext() ) { Map.Entry entry = (Map.Entry)it.next(); // the entry value is the delegate WikiEventDelegate delegate = (WikiEventDelegate)entry.getValue(); // now see if we can remove the listener from the delegate // (delegate may be null because this is a weak reference) if( delegate != null && delegate.removeWikiEventListener(listener) ) { return true; // was removed } } } return false; } /** * Returns true if there are one or more listeners registered with * the provided client Object (undelegated event source). This locates * any delegate and checks to see if it has any listeners attached. * * @param client the client Object * @return True, if there is a listener for this client object. */ public static boolean isListening( Object client ) { WikiEventDelegate source = getInstance().getDelegateFor(client); return source != null ? source.isListening() : false ; } /** * Notify all listeners of the WikiEventDelegate having a registered * interest in change events of the supplied WikiEvent. * * @param client the client initiating the event. * @param event the WikiEvent to fire. */ public static void fireEvent( Object client, WikiEvent event ) { WikiEventDelegate source = getInstance().getDelegateFor(client); if ( source != null ) source.fireEvent(event); } // private and utility methods ............................................. /** * Return the client-to-delegate Map. */ private Map getDelegates() { return m_delegates; } /** * Returns a WikiEventDelegate for the provided client Object. * If the parameter is a class reference, will generate and return a * client-less WikiEventDelegate. If the parameter is not a Class and * the delegate cache contains any objects matching the Class of any * delegates in the cache, the first Class-matching delegate will be * used in preference to creating a new delegate. * If a null parameter is supplied, this will create a client-less * delegate that will attach to the first incoming client (i.e., * there will be no Class-matching requirement). * * @param client the client Object, or alternately a Class reference * @return the WikiEventDelegate. */ private WikiEventDelegate getDelegateFor( Object client ) { synchronized( m_delegates ) { if( client == null || client instanceof Class ) // then preload the cache { WikiEventDelegate delegate = new WikiEventDelegate(client); m_preloadCache.add(delegate); m_delegates.put( client, delegate ); return delegate; } else if( !m_preloadCache.isEmpty() ) { // then see if any of the cached delegates match the class of the incoming client for( int i = m_preloadCache.size()-1 ; i >= 0 ; i-- ) // start with most-recently added { WikiEventDelegate delegate = (WikiEventDelegate)m_preloadCache.elementAt(i); if( delegate.getClientClass() == null || delegate.getClientClass().equals(client.getClass()) ) { // we have a hit, so use it, but only on a client we haven't seen before if( !m_delegates.keySet().contains(client) ) { m_preloadCache.remove(delegate); m_delegates.put( client, delegate ); return delegate; } } } } // otherwise treat normally... WikiEventDelegate delegate = (WikiEventDelegate)m_delegates.get( client ); if( delegate == null ) { delegate = new WikiEventDelegate( client ); m_delegates.put( client, delegate ); } return delegate; } } // ......................................................................... /** * Inner delegating class that manages event listener addition and * removal. Classes that generate events can obtain an instance of * this class from the WikiEventManager and delegate responsibility * to it. Interaction with this delegating class is done via the * methods of the {@link WikiEventDelegate} API. * * @author Murray Altheim * @since 2.4.20 */ private static final class WikiEventDelegate { /* A list of event listeners for this instance. */ private ArrayList m_listenerList = new ArrayList(); private Class m_class = null; /** * Constructor for an WikiEventDelegateImpl, provided * with the client Object it will service, or the Class * of client, the latter when used to preload a future * incoming delegate. */ protected WikiEventDelegate( Object client ) { if( client instanceof Class ) { m_class = (Class)client; } } /** * Returns the class of the client-less delegate, null if * this delegate is attached to a client Object. */ protected Class getClientClass() { return m_class; } /** * Return an unmodifiable Set containing the WikiEventListeners of * this WikiEventDelegateImpl. If there are no attached listeners, * returns an empty Set rather than null. * * @return an unmodifiable Set containing this delegate's WikiEventListeners * @throws java.lang.UnsupportedOperationException if any attempt is made to modify the Set */ public Set getWikiEventListeners() { synchronized( m_listenerList ) { TreeSet set = new TreeSet( new WikiEventListenerComparator() ); for( Iterator i = m_listenerList.iterator(); i.hasNext(); ) { WikiEventListener l = (WikiEventListener) ((WeakReference)i.next()).get(); if( l != null ) { set.add( l ); } } return Collections.unmodifiableSet(set); } } /** * Adds <tt>listener</tt> as a listener for events fired by the WikiEventDelegate. * * @param listener the WikiEventListener to be added * @return true if the listener was added (i.e., it was not already in the list and was added) */ public boolean addWikiEventListener( WikiEventListener listener ) { synchronized( m_listenerList ) { return m_listenerList.add( new WeakReference(listener) ); } } /** * Removes <tt>listener</tt> from the WikiEventDelegate. * * @param listener the WikiEventListener to be removed * @return true if the listener was removed (i.e., it was actually in the list and was removed) */ public boolean removeWikiEventListener( WikiEventListener listener ) { synchronized( m_listenerList ) { for( Iterator i = m_listenerList.iterator(); i.hasNext(); ) { WikiEventListener l = (WikiEventListener) ((WeakReference)i.next()).get(); if( l == listener ) { i.remove(); return true; } } } return false; } /** * Returns true if there are one or more listeners registered * with this instance. */ public boolean isListening() { synchronized( m_listenerList ) { return !m_listenerList.isEmpty(); } } /** * Notify all listeners having a registered interest * in change events of the supplied WikiEvent. */ public void fireEvent( WikiEvent event ) { boolean needsCleanup = false; try { synchronized( m_listenerList ) { for( int i = 0; i < m_listenerList.size(); i++ ) { WikiEventListener listener = (WikiEventListener) ((WeakReference)m_listenerList.get(i)).get(); if( listener != null ) { listener.actionPerformed( event ); } else { needsCleanup = true; } } // // Remove all such listeners which have expired // if( needsCleanup ) { for( int i = 0; i < m_listenerList.size(); i++ ) { WeakReference w = (WeakReference)m_listenerList.get(i); if( w.get() == null ) m_listenerList.remove(i--); } } } } catch( ConcurrentModificationException e ) { // // We don't die, we just don't do notifications in that case. // log.info("Concurrent modification of event list; please report this.",e); } } } // end inner class WikiEventDelegate private static class WikiEventListenerComparator implements Comparator { // TODO: This method is a critical performance bottleneck public int compare(Object arg0, Object arg1) { if( arg0 instanceof WikiEventListener && arg1 instanceof WikiEventListener ) { WikiEventListener w0 = (WikiEventListener) arg0; WikiEventListener w1 = (WikiEventListener) arg1; if( w1 == w0 || w0.equals(w1) ) return 0; return w1.hashCode() - w0.hashCode(); } throw new ClassCastException( arg1.getClass().getName() + " != " + arg0.getClass().getName() ); } } } // end com.ecyrd.jspwiki.event.WikiEventManager
Added patch enabling monitoring. git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@626475 13f79535-47bb-0310-9956-ffa450edef68
src/com/ecyrd/jspwiki/event/WikiEventManager.java
Added patch enabling monitoring.
<ide><path>rc/com/ecyrd/jspwiki/event/WikiEventManager.java <ide> { <ide> private static final Logger log = Logger.getLogger(WikiEventManager.class); <ide> <add> /* If true, permits a WikiEventMonitor to be set. */ <add> private static boolean permitMonitor = false; <add> <add> /* Optional listener to be used as all-event monitor. */ <add> private static WikiEventListener c_monitor = null; <add> <ide> /* The Map of client object to WikiEventDelegate. */ <ide> private final Map m_delegates = new HashMap(); <ide> <ide> * Registers a WikiEventListener with a WikiEventDelegate for <ide> * the provided client object. <ide> * <add> * <h3>Monitor Listener</h3> <add> * <add> * If <tt>client</tt> is a reference to the WikiEventManager class <add> * itself and the compile-time flag {@link #permitMonitor} is true, <add> * this attaches the listener as an all-event monitor, overwriting <add> * any previous listener (hence returning true). <add> * <p> <add> * You can remove any existing monitor by either calling this method <add> * with <tt>client</tt> as a reference to this class and the <add> * <tt>listener</tt> parameter as null, or <add> * {@link #removeWikiEventListener(Object,WikiEventListener)} with a <add> * <tt>client</tt> as a reference to this class. The <tt>listener</tt> <add> * parameter in this case is ignored. <add> * <ide> * @param client the client of the event source <ide> * @param listener the event listener <ide> * @return true if the listener was added (i.e., it was not already in the list and was added) <ide> public static final boolean addWikiEventListener( <ide> Object client, WikiEventListener listener ) <ide> { <del> WikiEventDelegate delegate = getInstance().getDelegateFor(client); <del> return delegate.addWikiEventListener(listener); <add> if ( client == WikiEventManager.class ) <add> { <add> if ( permitMonitor ) c_monitor = listener; <add> return permitMonitor; <add> } <add> else <add> { <add> WikiEventDelegate delegate = getInstance().getDelegateFor(client); <add> return delegate.addWikiEventListener(listener); <add> } <ide> } <ide> <ide> <ide> public static final boolean removeWikiEventListener( <ide> Object client, WikiEventListener listener ) <ide> { <del> WikiEventDelegate delegate = getInstance().getDelegateFor(client); <del> return delegate.removeWikiEventListener(listener); <add> if ( client == WikiEventManager.class ) <add> { <add> c_monitor = null; <add> return true; <add> } <add> else <add> { <add> WikiEventDelegate delegate = getInstance().getDelegateFor(client); <add> return delegate.removeWikiEventListener(listener); <add> } <ide> } <ide> <ide> <ide> { <ide> WikiEventDelegate source = getInstance().getDelegateFor(client); <ide> if ( source != null ) source.fireEvent(event); <add> if ( c_monitor != null ) c_monitor.actionPerformed(event); <ide> } <ide> <ide>
Java
apache-2.0
a04a8eb6a091bcedb4593d0f1f9ec3e1a25f5dbc
0
BartRobeyns/audit4j-core,audit4j/audit4j-core
src/main/java/org/audit4j/core/DefaultConfigurationFactory.java
/* * Copyright 2014 Janith Bandara, This source is a part of Audit4j - * An open-source audit platform for Enterprise java platform. * http://mechanizedspace.com/audit4j * http://audit4j.org * * 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.audit4j.core; import org.audit4j.core.dto.AuditLevel; /** * A factory for creating DefaultConfiguration objects. * * @author <a href="mailto:[email protected]">Janith Bandara</a> */ public class DefaultConfigurationFactory extends AbstractConfigurationFactory { /* * (non-Javadoc) * * @see com.audit4j.core.AbstractConfigurationFactory#getAuditLevel() */ @Override public String getAuditLevel() { return AuditLevel.DEFAULT_LEVEL; } }
deleted unwanted file
src/main/java/org/audit4j/core/DefaultConfigurationFactory.java
deleted unwanted file
<ide><path>rc/main/java/org/audit4j/core/DefaultConfigurationFactory.java <del>/* <del> * Copyright 2014 Janith Bandara, This source is a part of Audit4j - <del> * An open-source audit platform for Enterprise java platform. <del> * http://mechanizedspace.com/audit4j <del> * http://audit4j.org <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.audit4j.core; <del> <del>import org.audit4j.core.dto.AuditLevel; <del> <del>/** <del> * A factory for creating DefaultConfiguration objects. <del> * <del> * @author <a href="mailto:[email protected]">Janith Bandara</a> <del> */ <del>public class DefaultConfigurationFactory extends AbstractConfigurationFactory { <del> <del> /* <del> * (non-Javadoc) <del> * <del> * @see com.audit4j.core.AbstractConfigurationFactory#getAuditLevel() <del> */ <del> @Override <del> public String getAuditLevel() { <del> return AuditLevel.DEFAULT_LEVEL; <del> } <del>}
Java
apache-2.0
270ccbe443538e6dc6a548f95399c9b711f306d9
0
csoroiu/untwist,csoroiu/untwist
package ro.sixi.eval.util; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.random.MersenneTwister; public class MersenneTwisterPyCompat extends MersenneTwister { private static final long serialVersionUID = 1L; public MersenneTwisterPyCompat() { super(); } public MersenneTwisterPyCompat(int seed) { this(new int[] { seed }); } public MersenneTwisterPyCompat(int[] seed) { super(seed); } public MersenneTwisterPyCompat(long seed) { super(seed); } @Override public void setSeed(long seed) { int high = (int) (seed >>> 32); if (high == 0) { setSeed(new int[] { (int) seed }); } else { setSeed(new int[] { (int) (seed & 0xffffffffl), high }); } } @Override // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # random_random public double nextDouble() { return (((long) (next(27)) << 26) + next(26)) * 0x1.0p-53; } @Override public float nextFloat() { return (float) nextDouble(); } @Override public int nextInt(int n) throws IllegalArgumentException { if (n > 0) { final int bit_length = Integer.SIZE - Integer.numberOfLeadingZeros(n); int bits; do { bits = next(bit_length); } while (bits >= n); return bits; } throw new NotStrictlyPositiveException(n); } @Override public long nextLong() { final long low = ((long) next(32)) & 0xffffffffL; final long high = ((long) next(32)) << 32; return high | low; } @Override // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # random_getrandbits public void nextBytes(byte[] bytes) { int i = 0; final int iEnd = bytes.length - 4; while (i < iEnd) { final int random = next(32); bytes[i] = (byte) (random & 0xff); bytes[i + 1] = (byte) ((random >> 8) & 0xff); bytes[i + 2] = (byte) ((random >> 16) & 0xff); bytes[i + 3] = (byte) ((random >> 24) & 0xff); i += 4; } int random = next(32); int shift = 32 - (bytes.length - i) * 8; random >>>= shift; while (i < bytes.length) { bytes[i++] = (byte) (random & 0xff); random >>= 8; } } @Override // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # random_getrandbits public long nextLong(long n) throws IllegalArgumentException { if (n > 0) { final int bit_length = Long.SIZE - Long.numberOfLeadingZeros(n); long bits; do { bits = ((long) next(Math.min(32, bit_length))) & 0xffffffffL; if (bit_length > 32) { bits = bits | ((long) next(bit_length - 32)) << 32; } } while (bits >= n); return bits; } throw new NotStrictlyPositiveException(n); } }
src/main/java/ro/sixi/eval/util/MersenneTwisterPyCompat.java
package ro.sixi.eval.util; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.random.MersenneTwister; public class MersenneTwisterPyCompat extends MersenneTwister { private static final long serialVersionUID = 1L; public MersenneTwisterPyCompat() { super(); } public MersenneTwisterPyCompat(int seed) { super(seed); } public MersenneTwisterPyCompat(int[] seed) { super(seed); } public MersenneTwisterPyCompat(long seed) { super(seed); } @Override // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # // random_random public double nextDouble() { return (((long) (next(27)) << 26) + next(26)) * 0x1.0p-53; } @Override public float nextFloat() { return (float) nextDouble(); } @Override public int nextInt(int n) throws IllegalArgumentException { if (n > 0) { final int bit_length = Integer.SIZE - Integer.numberOfLeadingZeros(n); int bits; do { bits = next(bit_length); } while (bits >= n); return bits; } throw new NotStrictlyPositiveException(n); } @Override public long nextLong() { final long low = ((long) next(32)) & 0xffffffffL; final long high = ((long) next(32)) << 32; return high | low; } @Override // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # // random_getrandbits public void nextBytes(byte[] bytes) { int i = 0; final int iEnd = bytes.length - 4; while (i < iEnd) { final int random = next(32); bytes[i] = (byte) (random & 0xff); bytes[i + 1] = (byte) ((random >> 8) & 0xff); bytes[i + 2] = (byte) ((random >> 16) & 0xff); bytes[i + 3] = (byte) ((random >> 24) & 0xff); i += 4; } int random = next(32); int shift = 32 - (bytes.length - i) * 8; random >>>= shift; while (i < bytes.length) { bytes[i++] = (byte) (random & 0xff); random >>= 8; } } @Override // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # // random_getrandbits public long nextLong(long n) throws IllegalArgumentException { if (n > 0) { final int bit_length = Long.SIZE - Long.numberOfLeadingZeros(n); long bits; do { bits = ((long) next(Math.min(32, bit_length))) & 0xffffffffL; if (bit_length > 32) { bits = bits | ((long) next(bit_length - 32)) << 32; } } while (bits >= n); return bits; } throw new NotStrictlyPositiveException(n); } }
fixed setSeed(long)
src/main/java/ro/sixi/eval/util/MersenneTwisterPyCompat.java
fixed setSeed(long)
<ide><path>rc/main/java/ro/sixi/eval/util/MersenneTwisterPyCompat.java <ide> } <ide> <ide> public MersenneTwisterPyCompat(int seed) { <del> super(seed); <add> this(new int[] { seed }); <ide> } <ide> <ide> public MersenneTwisterPyCompat(int[] seed) { <ide> } <ide> <ide> @Override <del> // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # <del> // random_random <add> public void setSeed(long seed) { <add> int high = (int) (seed >>> 32); <add> if (high == 0) { <add> setSeed(new int[] { (int) seed }); <add> } else { <add> setSeed(new int[] { (int) (seed & 0xffffffffl), high }); <add> } <add> } <add> <add> @Override <add> // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # random_random <ide> public double nextDouble() { <ide> return (((long) (next(27)) << 26) + next(26)) * 0x1.0p-53; <ide> } <ide> } <ide> <ide> @Override <del> // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # <del> // random_getrandbits <add> // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # random_getrandbits <ide> public void nextBytes(byte[] bytes) { <ide> int i = 0; <ide> final int iEnd = bytes.length - 4; <ide> } <ide> <ide> @Override <del> // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # <del> // random_getrandbits <add> // http://svn.python.org/projects/python/trunk/Modules/_randommodule.c # random_getrandbits <ide> public long nextLong(long n) throws IllegalArgumentException { <ide> if (n > 0) { <ide> final int bit_length = Long.SIZE - Long.numberOfLeadingZeros(n);
Java
mit
308b03e6253bb118ee12262ebe60fa1c4d8adbc7
0
Malfeasant/SwineMeeper
package us.malfeasant.swinemeeper; import java.util.ArrayList; import java.util.Collections; import javafx.application.Application; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.MenuBar; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.RowConstraints; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class GameBoard extends Application { private final GridPane gameGrid = new GridPane(); private final Label timeLabel = new Label(); private final Label mineLabel = new Label(); private Stage stage; // need this to resize window after adding/removing children- is there a better way? private GameState state; // tracks state of game- can be READY (gameboard is built, but waiting for first click), // RUNNING (board has been clicked on, so timers are running), WON (all non-mine cells uncovered), LOST (hit a mine) private ArrayList<Cell> cells; private int uncovered; // number of uncovered mines- when this reaches total cells - mines, game must be won private int goal; // number of non-mined cells private boolean rebuild = true; // only rebuild the gameboard if the dimensions have changed private Difficulty diff = Persist.loadDifficulty(); private final Timer timer = new Timer(); private final IntegerProperty mineProp = new SimpleIntegerProperty(); private final Button go = new Button("Go"); // has to be here so it can be "clicked" from event handler @Override public void start(Stage primaryStage) throws Exception { stage = primaryStage; // Button go = new Button("Go"); go.setOnAction(e -> newGame()); timeLabel.textProperty().bind(timer.timeProperty().asString("%03d")); mineLabel.textProperty().bind(mineProp.asString("%03d")); GridPane topGrid = new GridPane(); // counters & go button // All this is needed to keep counters at the outside edges of the bar and go button centered: ColumnConstraints ccL = new ColumnConstraints(); ccL.setPercentWidth(100); ccL.setHalignment(HPos.LEFT); ColumnConstraints ccC = new ColumnConstraints(); ccC.setPercentWidth(100); ccC.setHalignment(HPos.CENTER); ColumnConstraints ccR = new ColumnConstraints(); ccR.setPercentWidth(100); ccR.setHalignment(HPos.RIGHT); topGrid.getColumnConstraints().addAll(ccL, ccC, ccR); topGrid.add(mineLabel, 0, 0); topGrid.add(go, 1, 0); topGrid.add(timeLabel, 2, 0); // oops- had these backwards timeLabel.setPadding(new Insets(5)); // keeps it from getting smushed to the edge mineLabel.setPadding(new Insets(5)); MenuBar bar = MenuBuilder.build(this); VBox box = new VBox(bar, topGrid, gameGrid); // this is needed to allow the gameGrid to fill the remaining space when resized VBox.setVgrow(gameGrid, Priority.ALWAYS); gameGrid.setStyle("-fx-font-size: x-large"); stage.iconifiedProperty().addListener((prop, then, now) -> { if (now) { timer.stop(); // pause the timer when minimized } else { if (state == GameState.RUNNING) { timer.start(); } } }); Scene scene = new Scene(box); primaryStage.setScene(scene); primaryStage.setTitle("SwineMeeper"); primaryStage.show(); go.fire(); } void setDifficulty(Difficulty d) { diff = d; Persist.storeDifficulty(diff); // this method pops up dialog if custom is set rebuild = true; go.fire(); // changing difficulty starts a new game } private void newGame() { // Start fresh gameGrid.getChildren().clear(); gameGrid.getColumnConstraints().clear(); gameGrid.getRowConstraints().clear(); timer.stop(); timer.reset(); // Difficulty diff = Persist.loadDifficulty(); Triple t = Persist.getDimensions(diff); mineProp.set(t.mines); cells = new ArrayList<>(t.width * t.height); uncovered = 0; goal = t.height * t.width - t.mines; // allow buttons to resize to fill window: RowConstraints rc = new RowConstraints(); rc.setPercentHeight(100); ColumnConstraints cc = new ColumnConstraints(); cc.setPercentWidth(100); gameGrid.getRowConstraints().add(rc); gameGrid.getColumnConstraints().add(cc); // We need to set the constraint object for each row and column, though they can be the same... for (int i=0; i < t.height - 1; i++) { gameGrid.getRowConstraints().add(rc); } for (int i=0; i < t.width - 1; i++) { gameGrid.getColumnConstraints().add(cc); } // Create bomb cells first, then create remainder unbombed cells, shuffle them, then put them in place for (int i = 0; i < t.width * t.height; i++) { Cell e = new Cell(this); if (i < t.mines) e.setMine(); cells.add(e); } Collections.shuffle(cells); // Top left corner Cell c = cells.get(0); gameGrid.add(c.getButton(), 0, 0); // Top row for (int x = 1; x < t.width; ++x) { c = cells.get(x); gameGrid.add(c.getButton(), x, 0); c.setNeighbor(Direction.WEST, cells.get(x-1)); } // Remaining rows for (int y = 1; y < t.height; ++y) { // Left cell c = cells.get(y * t.width); gameGrid.add(c.getButton(), 0, y); c.setNeighbor(Direction.NORTH, cells.get((y-1) * t.width)); c.setNeighbor(Direction.NORTHEAST, cells.get(1 + (y-1) * t.width)); // Remaining cells for (int x = 1; x < t.width; ++x) { c = cells.get(x + y * t.width); c.setNeighbor(Direction.NORTH, cells.get(x + (y-1) * t.width)); c.setNeighbor(Direction.NORTHWEST, cells.get((x-1) + (y-1) * t.width)); c.setNeighbor(Direction.WEST, cells.get((x-1) + y * t.width)); if (x < t.width - 1) // don't do this on last column c.setNeighbor(Direction.NORTHEAST, cells.get(x + 1 + (y-1) * t.width)); gameGrid.add(c.getButton(), x, y); } } state = GameState.READY; if (rebuild) { stage.sizeToScene(); // Resize window to fit size of gameGrid stage.setMinHeight(stage.getHeight()); // let it be resized, but don't let it get any smaller than this stage.setMinWidth(stage.getWidth()); // (shouldn't this already happen?) rebuild = false; } } void click(MineAction a) { // gameboard has to know about clicks and right clicks to start timer, track flagged mines... if (state.allowClicks()) { switch (a) { case MARK: // these alone do not start the game mineProp.set(mineProp.get() - 1); // goes negative if more marks than mines, that's ok break; case UNMARK: mineProp.set(mineProp.get() + 1); break; case UNCOVER: state = GameState.RUNNING; timer.start(); uncovered++; if (uncovered == goal) { cells.forEach(c -> c.endGame(true)); state = GameState.WON; timer.stop(); if (diff != Difficulty.CUSTOM) { Persist.storeBest(diff, timer.timeProperty().get()); } } break; case KABOOM: state = GameState.LOST; timer.stop(); cells.forEach(c -> c.endGame(false)); break; } } } }
src/us/malfeasant/swinemeeper/GameBoard.java
package us.malfeasant.swinemeeper; import java.util.ArrayList; import java.util.Collections; import javafx.application.Application; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.MenuBar; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.RowConstraints; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class GameBoard extends Application { private final GridPane gameGrid = new GridPane(); private final Label timeLabel = new Label(); private final Label mineLabel = new Label(); private Stage stage; // need this to resize window after adding/removing children- is there a better way? private GameState state; // tracks state of game- can be READY (gameboard is built, but waiting for first click), // RUNNING (board has been clicked on, so timers are running), WON (all non-mine cells uncovered), LOST (hit a mine) private ArrayList<Cell> cells; private int uncovered; // number of uncovered mines- when this reaches total cells - mines, game must be won private int goal; // number of non-mined cells private boolean rebuild = true; // only rebuild the gameboard if the dimensions have changed private Difficulty diff = Persist.loadDifficulty(); private final Timer timer = new Timer(); private final IntegerProperty mineProp = new SimpleIntegerProperty(); private final Button go = new Button("Go"); // has to be here so it can be "clicked" from event handler @Override public void start(Stage primaryStage) throws Exception { stage = primaryStage; // Button go = new Button("Go"); go.setOnAction(e -> newGame()); timeLabel.textProperty().bind(timer.timeProperty().asString("%03d")); mineLabel.textProperty().bind(mineProp.asString("%03d")); GridPane topGrid = new GridPane(); // counters & go button // All this is needed to keep counters at the outside edges of the bar and go button centered: ColumnConstraints ccL = new ColumnConstraints(); ccL.setPercentWidth(100); ccL.setHalignment(HPos.LEFT); ColumnConstraints ccC = new ColumnConstraints(); ccC.setPercentWidth(100); ccC.setHalignment(HPos.CENTER); ColumnConstraints ccR = new ColumnConstraints(); ccR.setPercentWidth(100); ccR.setHalignment(HPos.RIGHT); topGrid.getColumnConstraints().addAll(ccL, ccC, ccR); topGrid.add(mineLabel, 0, 0); topGrid.add(go, 1, 0); topGrid.add(timeLabel, 2, 0); // oops- had these backwards timeLabel.setPadding(new Insets(5)); // keeps it from getting smushed to the edge mineLabel.setPadding(new Insets(5)); MenuBar bar = MenuBuilder.build(this); VBox box = new VBox(bar, topGrid, gameGrid); // this is needed to allow the gameGrid to fill the remaining space when resized VBox.setVgrow(gameGrid, Priority.ALWAYS); gameGrid.setStyle("-fx-font-size: x-large"); Scene scene = new Scene(box); primaryStage.setScene(scene); primaryStage.setTitle("SwineMeeper"); primaryStage.show(); go.fire(); } void setDifficulty(Difficulty d) { diff = d; Persist.storeDifficulty(diff); // this method pops up dialog if custom is set rebuild = true; go.fire(); // changing difficulty starts a new game } private void newGame() { // Start fresh gameGrid.getChildren().clear(); gameGrid.getColumnConstraints().clear(); gameGrid.getRowConstraints().clear(); timer.stop(); timer.reset(); // Difficulty diff = Persist.loadDifficulty(); Triple t = Persist.getDimensions(diff); mineProp.set(t.mines); cells = new ArrayList<>(t.width * t.height); uncovered = 0; goal = t.height * t.width - t.mines; // allow buttons to resize to fill window: RowConstraints rc = new RowConstraints(); rc.setPercentHeight(100); ColumnConstraints cc = new ColumnConstraints(); cc.setPercentWidth(100); gameGrid.getRowConstraints().add(rc); gameGrid.getColumnConstraints().add(cc); // We need to set the constraint object for each row and column, though they can be the same... for (int i=0; i < t.height - 1; i++) { gameGrid.getRowConstraints().add(rc); } for (int i=0; i < t.width - 1; i++) { gameGrid.getColumnConstraints().add(cc); } // Create bomb cells first, then create remainder unbombed cells, shuffle them, then put them in place for (int i = 0; i < t.width * t.height; i++) { Cell e = new Cell(this); if (i < t.mines) e.setMine(); cells.add(e); } Collections.shuffle(cells); // Top left corner Cell c = cells.get(0); gameGrid.add(c.getButton(), 0, 0); // Top row for (int x = 1; x < t.width; ++x) { c = cells.get(x); gameGrid.add(c.getButton(), x, 0); c.setNeighbor(Direction.WEST, cells.get(x-1)); } // Remaining rows for (int y = 1; y < t.height; ++y) { // Left cell c = cells.get(y * t.width); gameGrid.add(c.getButton(), 0, y); c.setNeighbor(Direction.NORTH, cells.get((y-1) * t.width)); c.setNeighbor(Direction.NORTHEAST, cells.get(1 + (y-1) * t.width)); // Remaining cells for (int x = 1; x < t.width; ++x) { c = cells.get(x + y * t.width); c.setNeighbor(Direction.NORTH, cells.get(x + (y-1) * t.width)); c.setNeighbor(Direction.NORTHWEST, cells.get((x-1) + (y-1) * t.width)); c.setNeighbor(Direction.WEST, cells.get((x-1) + y * t.width)); if (x < t.width - 1) // don't do this on last column c.setNeighbor(Direction.NORTHEAST, cells.get(x + 1 + (y-1) * t.width)); gameGrid.add(c.getButton(), x, y); } } state = GameState.READY; if (rebuild) { stage.sizeToScene(); // Resize window to fit size of gameGrid stage.setMinHeight(stage.getHeight()); // let it be resized, but don't let it get any smaller than this stage.setMinWidth(stage.getWidth()); // (shouldn't this already happen?) rebuild = false; } } void click(MineAction a) { // gameboard has to know about clicks and right clicks to start timer, track flagged mines... if (state.allowClicks()) { switch (a) { case MARK: // these alone do not start the game mineProp.set(mineProp.get() - 1); // goes negative if more marks than mines, that's ok break; case UNMARK: mineProp.set(mineProp.get() + 1); break; case UNCOVER: state = GameState.RUNNING; timer.start(); uncovered++; if (uncovered == goal) { cells.forEach(c -> c.endGame(true)); state = GameState.WON; timer.stop(); if (diff != Difficulty.CUSTOM) { Persist.storeBest(diff, timer.timeProperty().get()); } } break; case KABOOM: state = GameState.LOST; timer.stop(); cells.forEach(c -> c.endGame(false)); break; } } } }
Minimize pauses timer
src/us/malfeasant/swinemeeper/GameBoard.java
Minimize pauses timer
<ide><path>rc/us/malfeasant/swinemeeper/GameBoard.java <ide> // this is needed to allow the gameGrid to fill the remaining space when resized <ide> VBox.setVgrow(gameGrid, Priority.ALWAYS); <ide> gameGrid.setStyle("-fx-font-size: x-large"); <add> <add> stage.iconifiedProperty().addListener((prop, then, now) -> { <add> if (now) { <add> timer.stop(); // pause the timer when minimized <add> } else { <add> if (state == GameState.RUNNING) { <add> timer.start(); <add> } <add> } <add> }); <ide> <ide> Scene scene = new Scene(box); <ide> primaryStage.setScene(scene);
Java
mit
2e83e167ccfcbbee526b73a432bebb63ea097f99
0
darshanhs90/Java-InterviewPrep,darshanhs90/Java-Coding
package GeeksforGeeksPractice; /* * Link : http://www.geeksforgeeks.org/ugly-numbers/ */ public class _0094UglyNumbers { public static void main(String[] args) { System.out.println(findUglyNumberNaive(150)); System.out.println(findUglyNumberDP(150)); } private static int findUglyNumberDP(int N) { int[] ugly=new int[N]; ugly[0]=1; int i2=0,i3=0,i5=0; int nextm2=ugly[i2]*2; int nextm3=ugly[i3]*3; int nextm5=ugly[i5]*5; int nextUglyNo=0; for (int i = 1; i < N; i++) { nextUglyNo=Math.min(nextm2, Math.min(nextm3, nextm5)); ugly[i]=nextUglyNo; if(nextUglyNo==nextm2) { i2++; nextm2=ugly[i2]*2; } if(nextUglyNo==nextm3) { i3++; nextm3=ugly[i3]*3; } if(nextUglyNo==nextm5) { i5++; nextm5=ugly[i5]*5; } } return nextUglyNo; } private static int findUglyNumberNaive(int i) { int count=1; int number=1; if(i==1) return 1; else { while(count<i) { number++; if(findUgly(number)) count++; } } return number; } private static boolean findUgly(int number) { number=maxDivide(number,2); number=maxDivide(number,3); number=maxDivide(number,5); return number==1; } private static int maxDivide(int number, int i) { while(number%i==0) number=number/i; return number; } }
src/GeeksforGeeksPractice/_0094UglyNumbers.java
package GeeksforGeeksPractice; /* * Link : http://www.geeksforgeeks.org/ugly-numbers/ */ public class _0094UglyNumbers { public static void main(String[] args) { System.out.println(findUglyNumberNaive(10)); } private static int findUglyNumberNaive(int i) { int count=1; int number=1; if(i==1) return 1; else { while(count<i) { number++; if(findUgly(number)) count++; } } return number; } private static boolean findUgly(int number) { number=maxDivide(number,2); number=maxDivide(number,3); number=maxDivide(number,5); return number==1; } private static int maxDivide(int number, int i) { while(number%i==0) number=number/i; return number; } }
ugly number dp completed
src/GeeksforGeeksPractice/_0094UglyNumbers.java
ugly number dp completed
<ide><path>rc/GeeksforGeeksPractice/_0094UglyNumbers.java <ide> */ <ide> public class _0094UglyNumbers { <ide> public static void main(String[] args) { <del> System.out.println(findUglyNumberNaive(10)); <add> System.out.println(findUglyNumberNaive(150)); <add> System.out.println(findUglyNumberDP(150)); <add> <add> } <add> <add> private static int findUglyNumberDP(int N) { <add> int[] ugly=new int[N]; <add> ugly[0]=1; <add> int i2=0,i3=0,i5=0; <add> int nextm2=ugly[i2]*2; <add> int nextm3=ugly[i3]*3; <add> int nextm5=ugly[i5]*5; <add> int nextUglyNo=0; <add> for (int i = 1; i < N; i++) { <add> nextUglyNo=Math.min(nextm2, Math.min(nextm3, nextm5)); <add> ugly[i]=nextUglyNo; <add> if(nextUglyNo==nextm2) <add> { <add> i2++; <add> nextm2=ugly[i2]*2; <add> } <add> if(nextUglyNo==nextm3) <add> { <add> i3++; <add> nextm3=ugly[i3]*3; <add> } <add> if(nextUglyNo==nextm5) <add> { <add> i5++; <add> nextm5=ugly[i5]*5; <add> } <add> <add> } <add> return nextUglyNo; <ide> } <ide> <ide> private static int findUglyNumberNaive(int i) {
Java
apache-2.0
936c57aeceb73e9fdf6a1315b9b687cb03c4a1b0
0
amasciul/UDPDiscoverer
package fr.masciulli.udpdiscoverer.app; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import fr.masciulli.udpdiscoverer.lib.Callback; import fr.masciulli.udpdiscoverer.lib.Discoverer; public class MainActivity extends ActionBarActivity implements Callback { private static final String TAG = MainActivity.class.getSimpleName(); private EditText messageField; private EditText localPortField; private EditText remotePortField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messageField = (EditText) findViewById(R.id.message); localPortField = (EditText) findViewById(R.id.local_port); remotePortField = (EditText) findViewById(R.id.remote_port); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_send) { String message = messageField.getText().toString(); try { int localPort = Integer.parseInt(localPortField.getText().toString()); int remotePort = Integer.parseInt(remotePortField.getText().toString()); sendMessage(message, localPort, remotePort); } catch (NumberFormatException exception) { Toast.makeText(MainActivity.this, getString(R.string.port_format_error), Toast.LENGTH_SHORT).show(); } return true; } return super.onOptionsItemSelected(item); } @Override public void error(Exception e) { Log.e(TAG, e.getMessage(), e); Toast.makeText(this, getString(R.string.message_notsent), Toast.LENGTH_SHORT).show(); } @Override public void messageSent() { Toast.makeText(this, getString(R.string.message_sent), Toast.LENGTH_SHORT).show(); } private void sendMessage(String message, int localPort, int remotePort) { Discoverer.from(MainActivity.this) .localPort(localPort) .remotePort(remotePort) .data(message.getBytes()) .callback(this) .broadcast(); } }
app/src/main/java/fr/masciulli/udpdiscoverer/app/MainActivity.java
package fr.masciulli.udpdiscoverer.app; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import fr.masciulli.udpdiscoverer.lib.Callback; import fr.masciulli.udpdiscoverer.lib.Discoverer; public class MainActivity extends ActionBarActivity implements Callback { private static final String TAG = MainActivity.class.getSimpleName(); private EditText messageField; private EditText localPortField; private EditText remotePortField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messageField = (EditText) findViewById(R.id.message); localPortField = (EditText) findViewById(R.id.local_port); remotePortField = (EditText) findViewById(R.id.remote_port); } private void sendMessage(String message, int localPort, int remotePort) { Discoverer.from(MainActivity.this) .localPort(localPort) .remotePort(remotePort) .data(message.getBytes()) .callback(this) .broadcast(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_send) { String message = messageField.getText().toString(); try { int localPort = Integer.parseInt(localPortField.getText().toString()); int remotePort = Integer.parseInt(remotePortField.getText().toString()); sendMessage(message, localPort, remotePort); } catch (NumberFormatException exception) { Toast.makeText(MainActivity.this, getString(R.string.port_format_error), Toast.LENGTH_SHORT).show(); } return true; } return super.onOptionsItemSelected(item); } @Override public void error(Exception e) { Log.e(TAG, e.getMessage(), e); Toast.makeText(this, getString(R.string.message_notsent), Toast.LENGTH_SHORT).show(); } @Override public void messageSent() { Toast.makeText(this, getString(R.string.message_sent), Toast.LENGTH_SHORT).show(); } }
Move method
app/src/main/java/fr/masciulli/udpdiscoverer/app/MainActivity.java
Move method
<ide><path>pp/src/main/java/fr/masciulli/udpdiscoverer/app/MainActivity.java <ide> messageField = (EditText) findViewById(R.id.message); <ide> localPortField = (EditText) findViewById(R.id.local_port); <ide> remotePortField = (EditText) findViewById(R.id.remote_port); <del> } <del> <del> private void sendMessage(String message, int localPort, int remotePort) { <del> Discoverer.from(MainActivity.this) <del> .localPort(localPort) <del> .remotePort(remotePort) <del> .data(message.getBytes()) <del> .callback(this) <del> .broadcast(); <ide> } <ide> <ide> @Override <ide> public void messageSent() { <ide> Toast.makeText(this, getString(R.string.message_sent), Toast.LENGTH_SHORT).show(); <ide> } <add> <add> private void sendMessage(String message, int localPort, int remotePort) { <add> Discoverer.from(MainActivity.this) <add> .localPort(localPort) <add> .remotePort(remotePort) <add> .data(message.getBytes()) <add> .callback(this) <add> .broadcast(); <add> } <ide> }
JavaScript
mit
6d9a9735eeb04182589ff9bd98569288667cb8d8
0
sivakumar-kailasam/ember.js,sly7-7/ember.js,kanongil/ember.js,patricksrobertson/ember.js,jaswilli/ember.js,jasonmit/ember.js,csantero/ember.js,sly7-7/ember.js,asakusuma/ember.js,givanse/ember.js,Serabe/ember.js,tildeio/ember.js,mixonic/ember.js,givanse/ember.js,stefanpenner/ember.js,bekzod/ember.js,mixonic/ember.js,sivakumar-kailasam/ember.js,gfvcastro/ember.js,kanongil/ember.js,tildeio/ember.js,runspired/ember.js,jasonmit/ember.js,csantero/ember.js,qaiken/ember.js,jaswilli/ember.js,fpauser/ember.js,qaiken/ember.js,cibernox/ember.js,stefanpenner/ember.js,kennethdavidbuck/ember.js,xiujunma/ember.js,kellyselden/ember.js,Turbo87/ember.js,Gaurav0/ember.js,mfeckie/ember.js,gfvcastro/ember.js,thoov/ember.js,mike-north/ember.js,qaiken/ember.js,thoov/ember.js,kellyselden/ember.js,runspired/ember.js,Serabe/ember.js,emberjs/ember.js,sivakumar-kailasam/ember.js,elwayman02/ember.js,runspired/ember.js,karthiick/ember.js,jasonmit/ember.js,twokul/ember.js,mfeckie/ember.js,knownasilya/ember.js,givanse/ember.js,karthiick/ember.js,sly7-7/ember.js,cibernox/ember.js,Turbo87/ember.js,bekzod/ember.js,Serabe/ember.js,runspired/ember.js,Turbo87/ember.js,GavinJoyce/ember.js,xiujunma/ember.js,gfvcastro/ember.js,emberjs/ember.js,jasonmit/ember.js,miguelcobain/ember.js,xiujunma/ember.js,kellyselden/ember.js,sivakumar-kailasam/ember.js,intercom/ember.js,asakusuma/ember.js,mixonic/ember.js,thoov/ember.js,qaiken/ember.js,GavinJoyce/ember.js,GavinJoyce/ember.js,sandstrom/ember.js,miguelcobain/ember.js,mfeckie/ember.js,karthiick/ember.js,mfeckie/ember.js,mike-north/ember.js,givanse/ember.js,intercom/ember.js,patricksrobertson/ember.js,csantero/ember.js,jaswilli/ember.js,GavinJoyce/ember.js,jasonmit/ember.js,patricksrobertson/ember.js,sandstrom/ember.js,Gaurav0/ember.js,bekzod/ember.js,fpauser/ember.js,miguelcobain/ember.js,mike-north/ember.js,tildeio/ember.js,sandstrom/ember.js,xiujunma/ember.js,twokul/ember.js,cibernox/ember.js,kennethdavidbuck/ember.js,fpauser/ember.js,elwayman02/ember.js,Gaurav0/ember.js,kanongil/ember.js,Serabe/ember.js,miguelcobain/ember.js,knownasilya/ember.js,jaswilli/ember.js,Turbo87/ember.js,elwayman02/ember.js,twokul/ember.js,elwayman02/ember.js,mike-north/ember.js,karthiick/ember.js,bekzod/ember.js,twokul/ember.js,asakusuma/ember.js,kennethdavidbuck/ember.js,Gaurav0/ember.js,stefanpenner/ember.js,kanongil/ember.js,thoov/ember.js,kellyselden/ember.js,asakusuma/ember.js,fpauser/ember.js,kennethdavidbuck/ember.js,patricksrobertson/ember.js,knownasilya/ember.js,intercom/ember.js,gfvcastro/ember.js,sivakumar-kailasam/ember.js,csantero/ember.js,cibernox/ember.js,emberjs/ember.js,intercom/ember.js
import { assign } from 'ember-utils'; import { assert, deprecate } from 'ember-debug'; /** @module ember @submodule ember-routing */ let uuid = 0; class DSL { constructor(name, options) { this.parent = name; this.enableLoadingSubstates = options && options.enableLoadingSubstates; this.matches = []; this.explicitIndex = undefined; this.options = options; } route(name, options = {}, callback) { let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`; if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } assert(`'${name}' cannot be used as a route name.`, (() => { if (options.overrideNameAssertion === true) { return true; } return ['array', 'basic', 'object', 'application'].indexOf(name) === -1; })()); if (this.enableLoadingSubstates) { createRoute(this, `${name}_loading`, { resetNamespace: options.resetNamespace }); createRoute(this, `${name}_error`, { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); } if (callback) { let fullName = getFullName(this, name, options.resetNamespace); let dsl = new DSL(fullName, this.options); createRoute(dsl, 'loading'); createRoute(dsl, 'error', { path: dummyErrorRoute }); callback.call(dsl); createRoute(this, name, options, dsl.generate()); } else { createRoute(this, name, options); } } push(url, name, callback, serialize) { let parts = name.split('.'); if (this.options.engineInfo) { let localFullName = name.slice(this.options.engineInfo.fullName.length + 1); let routeInfo = assign({ localFullName }, this.options.engineInfo); if (serialize) { routeInfo.serializeMethod = serialize; } this.options.addRouteForEngine(name, routeInfo); } else if (serialize) { throw new Error(`Defining a route serializer on route '${name}' outside an Engine is not allowed.`); } if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; } this.matches.push(url, name, callback); } resource(name, options = {}, callback) { if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } options.resetNamespace = true; deprecate('this.resource() is deprecated. Use this.route(\'name\', { resetNamespace: true }, function () {}) instead.', false, { id: 'ember-routing.router-resource', until: '3.0.0' }); this.route(name, options, callback); } generate() { let dslMatches = this.matches; if (!this.explicitIndex) { this.route('index', { path: '/' }); } return match => { for (let i = 0; i < dslMatches.length; i += 3) { match(dslMatches[i]).to(dslMatches[i + 1], dslMatches[i + 2]); } }; } mount(_name, options = {}) { let engineRouteMap = this.options.resolveRouteMap(_name); let name = _name; if (options.as) { name = options.as; } let fullName = getFullName(this, name, options.resetNamespace); let engineInfo = { name: _name, instanceId: uuid++, mountPoint: fullName, fullName }; let path = options.path; if (typeof path !== 'string') { path = `/${name}`; } let callback; let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`; if (engineRouteMap) { let shouldResetEngineInfo = false; let oldEngineInfo = this.options.engineInfo; if (oldEngineInfo) { shouldResetEngineInfo = true; this.options.engineInfo = engineInfo; } let optionsForChild = assign({ engineInfo }, this.options); let childDSL = new DSL(fullName, optionsForChild); createRoute(childDSL, 'loading'); createRoute(childDSL, 'error', { path: dummyErrorRoute }); engineRouteMap.class.call(childDSL); callback = childDSL.generate(); if (shouldResetEngineInfo) { this.options.engineInfo = oldEngineInfo; } } let localFullName = 'application'; let routeInfo = assign({ localFullName }, engineInfo); if (this.enableLoadingSubstates) { // These values are important to register the loading routes under their // proper names for the Router and within the Engine's registry. let substateName = `${name}_loading`; let localFullName = `application_loading`; let routeInfo = assign({ localFullName }, engineInfo); createRoute(this, substateName, { resetNamespace: options.resetNamespace }); this.options.addRouteForEngine(substateName, routeInfo); substateName = `${name}_error`; localFullName = `application_error`; routeInfo = assign({ localFullName }, engineInfo); createRoute(this, substateName, { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); this.options.addRouteForEngine(substateName, routeInfo); } this.options.addRouteForEngine(fullName, routeInfo); this.push(path, fullName, callback); } } export default DSL; function canNest(dsl) { return dsl.parent !== 'application'; } function getFullName(dsl, name, resetNamespace) { if (canNest(dsl) && resetNamespace !== true) { return `${dsl.parent}.${name}`; } else { return name; } } function createRoute(dsl, name, options = {}, callback) { let fullName = getFullName(dsl, name, options.resetNamespace); if (typeof options.path !== 'string') { options.path = `/${name}`; } dsl.push(options.path, fullName, callback, options.serialize); } DSL.map = callback => { let dsl = new DSL(); callback.call(dsl); return dsl; };
packages/ember-routing/lib/system/dsl.js
import { assign } from 'ember-utils'; import { assert, deprecate } from 'ember-debug'; /** @module ember @submodule ember-routing */ let uuid = 0; class DSL { constructor(name, options) { this.parent = name; this.enableLoadingSubstates = options && options.enableLoadingSubstates; this.matches = []; this.explicitIndex = undefined; this.options = options; } route(name, options = {}, callback) { let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`; if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } assert(`'${name}' cannot be used as a route name.`, (() => { if (options.overrideNameAssertion === true) { return true; } return ['array', 'basic', 'object', 'application'].indexOf(name) === -1; })()); if (this.enableLoadingSubstates) { createRoute(this, `${name}_loading`, { resetNamespace: options.resetNamespace }); createRoute(this, `${name}_error`, { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); } if (callback) { let fullName = getFullName(this, name, options.resetNamespace); let dsl = new DSL(fullName, this.options); createRoute(dsl, 'loading'); createRoute(dsl, 'error', { path: dummyErrorRoute }); callback.call(dsl); createRoute(this, name, options, dsl.generate()); } else { createRoute(this, name, options); } } push(url, name, callback, serialize) { let parts = name.split('.'); if (this.options.engineInfo) { let localFullName = name.slice(this.options.engineInfo.fullName.length + 1); let routeInfo = assign({ localFullName }, this.options.engineInfo); if (serialize) { routeInfo.serializeMethod = serialize; } this.options.addRouteForEngine(name, routeInfo); } else if (serialize) { throw new Error(`Defining a route serializer on route '${name}' outside an Engine is not allowed.`); } if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; } this.matches.push([url, name, callback]); } resource(name, options = {}, callback) { if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } options.resetNamespace = true; deprecate('this.resource() is deprecated. Use this.route(\'name\', { resetNamespace: true }, function () {}) instead.', false, { id: 'ember-routing.router-resource', until: '3.0.0' }); this.route(name, options, callback); } generate() { let dslMatches = this.matches; if (!this.explicitIndex) { this.route('index', { path: '/' }); } return match => { for (let i = 0; i < dslMatches.length; i++) { let dslMatch = dslMatches[i]; match(dslMatch[0]).to(dslMatch[1], dslMatch[2]); } }; } mount(_name, options = {}) { let engineRouteMap = this.options.resolveRouteMap(_name); let name = _name; if (options.as) { name = options.as; } let fullName = getFullName(this, name, options.resetNamespace); let engineInfo = { name: _name, instanceId: uuid++, mountPoint: fullName, fullName }; let path = options.path; if (typeof path !== 'string') { path = `/${name}`; } let callback; let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`; if (engineRouteMap) { let shouldResetEngineInfo = false; let oldEngineInfo = this.options.engineInfo; if (oldEngineInfo) { shouldResetEngineInfo = true; this.options.engineInfo = engineInfo; } let optionsForChild = assign({ engineInfo }, this.options); let childDSL = new DSL(fullName, optionsForChild); createRoute(childDSL, 'loading'); createRoute(childDSL, 'error', { path: dummyErrorRoute }); engineRouteMap.class.call(childDSL); callback = childDSL.generate(); if (shouldResetEngineInfo) { this.options.engineInfo = oldEngineInfo; } } let localFullName = 'application'; let routeInfo = assign({ localFullName }, engineInfo); if (this.enableLoadingSubstates) { // These values are important to register the loading routes under their // proper names for the Router and within the Engine's registry. let substateName = `${name}_loading`; let localFullName = `application_loading`; let routeInfo = assign({ localFullName }, engineInfo); createRoute(this, substateName, { resetNamespace: options.resetNamespace }); this.options.addRouteForEngine(substateName, routeInfo); substateName = `${name}_error`; localFullName = `application_error`; routeInfo = assign({ localFullName }, engineInfo); createRoute(this, substateName, { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); this.options.addRouteForEngine(substateName, routeInfo); } this.options.addRouteForEngine(fullName, routeInfo); this.push(path, fullName, callback); } } export default DSL; function canNest(dsl) { return dsl.parent && dsl.parent !== 'application'; } function getFullName(dsl, name, resetNamespace) { if (canNest(dsl) && resetNamespace !== true) { return `${dsl.parent}.${name}`; } else { return name; } } function createRoute(dsl, name, options = {}, callback) { let fullName = getFullName(dsl, name, options.resetNamespace); if (typeof options.path !== 'string') { options.path = `/${name}`; } dsl.push(options.path, fullName, callback, options.serialize); } DSL.map = callback => { let dsl = new DSL(); callback.call(dsl); return dsl; };
use flat array in `dsl`
packages/ember-routing/lib/system/dsl.js
use flat array in `dsl`
<ide><path>ackages/ember-routing/lib/system/dsl.js <ide> <ide> if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; } <ide> <del> this.matches.push([url, name, callback]); <add> this.matches.push(url, name, callback); <ide> } <ide> <ide> resource(name, options = {}, callback) { <ide> } <ide> <ide> return match => { <del> for (let i = 0; i < dslMatches.length; i++) { <del> let dslMatch = dslMatches[i]; <del> match(dslMatch[0]).to(dslMatch[1], dslMatch[2]); <add> for (let i = 0; i < dslMatches.length; i += 3) { <add> match(dslMatches[i]).to(dslMatches[i + 1], dslMatches[i + 2]); <ide> } <ide> }; <ide> } <ide> createRoute(childDSL, 'loading'); <ide> createRoute(childDSL, 'error', { path: dummyErrorRoute }); <ide> <del> <ide> engineRouteMap.class.call(childDSL); <ide> <ide> callback = childDSL.generate(); <ide> export default DSL; <ide> <ide> function canNest(dsl) { <del> return dsl.parent && dsl.parent !== 'application'; <add> return dsl.parent !== 'application'; <ide> } <ide> <ide> function getFullName(dsl, name, resetNamespace) {
Java
apache-2.0
62465ada37700d0576e3d39fbf84b2c5d2cb6cf3
0
jaredrummler/AndroidProcesses
/* * Copyright (C) 2015. Jared Rummler <[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 com.jaredrummler.android.processes.sample.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.os.SystemClock; import android.text.Spanned; import android.text.format.Formatter; import android.util.Log; import com.jaredrummler.android.processes.models.AndroidAppProcess; import com.jaredrummler.android.processes.models.Stat; import com.jaredrummler.android.processes.models.Statm; import com.jaredrummler.android.processes.models.Status; import com.jaredrummler.android.processes.sample.utils.HtmlBuilder; import com.jaredrummler.android.processes.sample.utils.Utils; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Locale; public class ProcessInfoDialog extends DialogFragment { private static final String TAG = "ProcessInfoDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AndroidAppProcess process = getArguments().getParcelable("process"); return new AlertDialog.Builder(getActivity()) .setTitle(Utils.getName(getActivity(), process)) .setMessage(getProcessInfo(process)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); } private Spanned getProcessInfo(AndroidAppProcess process) { HtmlBuilder html = new HtmlBuilder(); html.p().strong("NAME: ").append(process.name).close(); html.p().strong("POLICY: ").append(process.foreground ? "fg" : "bg").close(); html.p().strong("PID: ").append(process.pid).close(); try { Status status = process.status(); html.p().strong("UID/GID: ").append(status.getUid()).append('/').append(status.getGid()).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/status.", process.pid)); } // should probably be run in a background thread. try { Stat stat = process.stat(); html.p().strong("PPID: ").append(stat.ppid()).close(); long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime(); long startTime = bootTime + (10 * stat.starttime()); SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy KK:mm:ss a", Locale.getDefault()); html.p().strong("START TIME: ").append(sdf.format(startTime)).close(); html.p().strong("CPU TIME: ").append((stat.stime() + stat.utime()) / 100).close(); html.p().strong("NICE: ").append(stat.nice()).close(); int rtPriority = stat.rt_priority(); if (rtPriority == 0) { html.p().strong("SCHEDULING PRIORITY: ").append("non-real-time").close(); } else if (rtPriority >= 1 && rtPriority <= 99) { html.p().strong("SCHEDULING PRIORITY: ").append("real-time").close(); } long userModeTicks = stat.utime(); long kernelModeTicks = stat.stime(); long percentOfTimeUserMode; long percentOfTimeKernelMode; if ((kernelModeTicks + userModeTicks) > 0) { percentOfTimeUserMode = (userModeTicks * 100) / (userModeTicks + kernelModeTicks); percentOfTimeKernelMode = (kernelModeTicks * 100) / (userModeTicks + kernelModeTicks); html.p().strong("TIME EXECUTED IN USER MODE: ").append(percentOfTimeUserMode + "%").close(); html.p().strong("TIME EXECUTED IN KERNEL MODE: ").append(percentOfTimeKernelMode + "%").close(); } } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/stat.", process.pid)); } try { Statm statm = process.statm(); html.p().strong("SIZE: ").append(Formatter.formatFileSize(getActivity(), statm.getSize())).close(); html.p().strong("RSS: ").append(Formatter.formatFileSize(getActivity(), statm.getResidentSetSize())).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/statm.", process.pid)); } try { html.p().strong("OOM SCORE: ").append(process.oom_score()).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/oom_score.", process.pid)); } try { html.p().strong("OOM ADJ: ").append(process.oom_adj()).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/oom_adj.", process.pid)); } try { html.p().strong("OOM SCORE ADJ: ").append(process.oom_score_adj()).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/oom_score_adj.", process.pid)); } return html.toSpan(); } }
sample/src/main/java/com/jaredrummler/android/processes/sample/dialogs/ProcessInfoDialog.java
/* * Copyright (C) 2015. Jared Rummler <[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 com.jaredrummler.android.processes.sample.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.os.SystemClock; import android.text.Spanned; import android.text.format.Formatter; import android.util.Log; import com.jaredrummler.android.processes.models.AndroidAppProcess; import com.jaredrummler.android.processes.models.Stat; import com.jaredrummler.android.processes.models.Statm; import com.jaredrummler.android.processes.models.Status; import com.jaredrummler.android.processes.sample.utils.HtmlBuilder; import com.jaredrummler.android.processes.sample.utils.Utils; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Locale; public class ProcessInfoDialog extends DialogFragment { private static final String TAG = "ProcessInfoDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AndroidAppProcess process = getArguments().getParcelable("process"); return new AlertDialog.Builder(getActivity()) .setTitle(Utils.getName(getActivity(), process)) .setMessage(getProcessInfo(process)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); } private Spanned getProcessInfo(AndroidAppProcess process) { HtmlBuilder html = new HtmlBuilder(); html.p().strong("NAME: ").append(process.name).close(); html.p().strong("POLICY: ").append(process.foreground ? "fg" : "bg").close(); html.p().strong("PID: ").append(process.pid).close(); try { Status status = process.status(); html.p().strong("UID/GID: ").append(status.getUid()).append('/').append(status.getGid()).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/status.", process.pid)); } // should probably be run in a background thread. try { Stat stat = process.stat(); html.p().strong("PPID: ").append(stat.ppid()).close(); long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime(); long startTime = bootTime + (10 * stat.starttime()); SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy KK:mm:ss a", Locale.getDefault()); html.p().strong("START TIME: ").append(sdf.format(startTime)).close(); html.p().strong("CPU TIME: ").append((stat.stime() + stat.utime()) / 100).close(); html.p().strong("NICE: ").append(stat.nice()).close(); int rtPriority = stat.rt_priority(); if (rtPriority == 0) { html.p().strong("SCHEDULING PRIORITY: ").append("non-real-time").close(); } else if (rtPriority >= 1 && rtPriority <= 99) { html.p().strong("SCHEDULING PRIORITY: ").append("real-time").close(); } long userModeTicks = stat.utime(); long kernelModeTicks = stat.stime(); long percentOfTimeUserMode; long percentOfTimeKernelMode; if ((kernelModeTicks + userModeTicks) > 0) { percentOfTimeUserMode = (userModeTicks * 100) / (userModeTicks + kernelModeTicks); percentOfTimeKernelMode = (kernelModeTicks * 100) / (userModeTicks + kernelModeTicks); html.p().strong("TIME EXECUTED IN USER MODE: ").append(percentOfTimeUserMode + "%").close(); html.p().strong("TIME EXECUTED IN KERNEL MODE: ").append(percentOfTimeKernelMode + "%").close(); } } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/stat.", process.pid)); } try { Statm statm = process.statm(); html.p().strong("SIZE: ").append(Formatter.formatFileSize(getActivity(), statm.getSize())).close(); html.p().strong("RSS: ").append(Formatter.formatFileSize(getActivity(), statm.getResidentSetSize())).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/statm.", process.pid)); } try { html.p().strong("OOM ADJ: ").append(process.oom_adj()).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/oom_adj.", process.pid)); } try { html.p().strong("OOM SCORE ADJ: ").append(process.oom_score_adj()).close(); } catch (IOException e) { Log.d(TAG, String.format("Error reading /proc/%d/oom_score_adj.", process.pid)); } return html.toSpan(); } }
add oom_score to process info dialog
sample/src/main/java/com/jaredrummler/android/processes/sample/dialogs/ProcessInfoDialog.java
add oom_score to process info dialog
<ide><path>ample/src/main/java/com/jaredrummler/android/processes/sample/dialogs/ProcessInfoDialog.java <ide> } <ide> <ide> try { <add> html.p().strong("OOM SCORE: ").append(process.oom_score()).close(); <add> } catch (IOException e) { <add> Log.d(TAG, String.format("Error reading /proc/%d/oom_score.", process.pid)); <add> } <add> <add> try { <ide> html.p().strong("OOM ADJ: ").append(process.oom_adj()).close(); <ide> } catch (IOException e) { <ide> Log.d(TAG, String.format("Error reading /proc/%d/oom_adj.", process.pid));
Java
apache-2.0
3c692a7e624f4f83950f111d4836fb17df94b92b
0
arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint
/* * Copyright (c) 2010-2017 Evolveum * * 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.evolveum.midpoint.web.util; import com.evolveum.midpoint.common.LocalizationService; import org.apache.wicket.Component; import org.apache.wicket.Session; import org.apache.wicket.resource.loader.IStringResourceLoader; import java.util.Locale; /** * Created by Viliam Repan (lazyman). */ public class MidPointStringResourceLoader implements IStringResourceLoader { private LocalizationService resourceLoader; public MidPointStringResourceLoader(LocalizationService resourceLoader) { this.resourceLoader = resourceLoader; } @Override public String loadStringResource(Class<?> clazz, String key, Locale locale, String style, String variation) { return loadStringResource((Component) null, key, locale, style, variation); } @Override public String loadStringResource(Component component, String key, Locale locale, String style, String variation) { if (locale == null) { locale = Session.exists() ? Session.get().getLocale() : Locale.getDefault(); } return resourceLoader.translate(key, null, locale); } }
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/MidPointStringResourceLoader.java
/* * Copyright (c) 2010-2017 Evolveum * * 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.evolveum.midpoint.web.util; import com.evolveum.midpoint.common.LocalizationService; import org.apache.wicket.Component; import org.apache.wicket.Session; import org.apache.wicket.resource.loader.IStringResourceLoader; import java.util.Locale; /** * Created by Viliam Repan (lazyman). */ public class MidPointStringResourceLoader implements IStringResourceLoader { private LocalizationService resourceLoader; public MidPointStringResourceLoader(LocalizationService resourceLoader) { this.resourceLoader = resourceLoader; } @Override public String loadStringResource(Class<?> clazz, String key, Locale locale, String style, String variation) { return loadStringResource((Component) null, key, locale, style, variation); } @Override public String loadStringResource(Component component, String key, Locale locale, String style, String variation) { if (locale == null) { locale = Session.exists() ? Session.get().getLocale() : Locale.getDefault(); } return resourceLoader.translate(key, null, locale, key); } }
Fixed bug preventing displaying built-in constraint messages for named constraints.
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/MidPointStringResourceLoader.java
Fixed bug preventing displaying built-in constraint messages for named constraints.
<ide><path>ui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/MidPointStringResourceLoader.java <ide> locale = Session.exists() ? Session.get().getLocale() : Locale.getDefault(); <ide> } <ide> <del> return resourceLoader.translate(key, null, locale, key); <add> return resourceLoader.translate(key, null, locale); <ide> } <ide> }
Java
bsd-2-clause
14cbdb317874f25bb71b3e8c50ba4101d0e153ea
0
scifio/scifio
// // FitsReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program 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 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.awt.image.BufferedImage; import java.io.IOException; import loci.formats.*; /** * FitsReader is the file format reader for * Flexible Image Transport System (FITS) images. * * Much of this code was adapted from ImageJ (http://rsb.info.nih.gov/ij). */ public class FitsReader extends FormatReader { // -- Fields -- /** Number of lines in the header. */ private int count; // -- Constructor -- /** Constructs a new FitsReader. */ public FitsReader() { super("Flexible Image Transport System", "fits"); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { return true; } /* @see loci.formats.IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); byte[] buf = new byte[core.sizeX[0] * core.sizeY[0] * FormatTools.getBytesPerPixel(core.pixelType[0])]; return openBytes(no, buf); } /* @see loci.formats.IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (no < 0 || no >= getImageCount()) { throw new FormatException("Invalid image number: " + no); } if (buf.length < core.sizeX[0] * core.sizeY[0] * FormatTools.getBytesPerPixel(core.pixelType[0])) { throw new FormatException("Buffer too small."); } in.seek(2880 + 2880 * (((count * 80) - 1) / 2880)); int line = core.sizeX[0] * FormatTools.getBytesPerPixel(core.pixelType[0]); for (int y=core.sizeY[0]-1; y>=0; y--) { in.read(buf, y*line, line); } return buf; } /* @see loci.formats.IFormatReader#openImage(int) */ public BufferedImage openImage(int no) throws FormatException, IOException { return ImageTools.makeImage(openBytes(no), core.sizeX[0], core.sizeY[0], core.sizeC[0], core.interleaved[0], FormatTools.getBytesPerPixel(core.pixelType[0]), core.littleEndian[0]); } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessStream(id); count = 1; byte[] b = new byte[80]; in.read(b); String line = new String(b); if (!line.startsWith("SIMPLE")) { throw new FormatException("Unsupported FITS file."); } while (true) { count++; in.read(b); line = new String(b); // parse key/value pair int ndx = line.indexOf("="); int comment = line.indexOf("/", ndx); if (comment < 0) comment = line.length(); String key = "", value = ""; if (ndx >= 0) { key = line.substring(0, ndx).trim(); value = line.substring(ndx + 1, comment).trim(); } else key = line.trim(); if (key.equals("END")) break; if (key.equals("BITPIX")) { int bits = Integer.parseInt(value); switch (bits) { case 8: core.pixelType[0] = FormatTools.UINT8; break; case 16: core.pixelType[0] = FormatTools.UINT16; break; case 32: core.pixelType[0] = FormatTools.UINT32; break; case -32: core.pixelType[0] = FormatTools.FLOAT; break; default: throw new FormatException("Unsupported pixel type: " + bits); } } else if (key.equals("NAXIS1")) core.sizeX[0] = Integer.parseInt(value); else if (key.equals("NAXIS2")) core.sizeY[0] = Integer.parseInt(value); else if (key.equals("NAXIS3")) core.sizeZ[0] = Integer.parseInt(value); addMeta(key, value); } core.sizeC[0] = 1; core.sizeT[0] = 1; if (core.sizeZ[0] == 0) core.sizeZ[0] = 1; core.imageCount[0] = core.sizeZ[0]; core.rgb[0] = false; core.littleEndian[0] = false; core.interleaved[0] = false; core.currentOrder[0] = "XYZCT"; MetadataStore store = getMetadataStore(); store.setPixels(new Integer(core.sizeX[0]), new Integer(core.sizeY[0]), new Integer(core.sizeZ[0]), new Integer(core.sizeC[0]), new Integer(core.sizeT[0]), new Integer(core.pixelType[0]), new Boolean(!core.littleEndian[0]), core.currentOrder[0], null, null); } }
loci/formats/in/FitsReader.java
// // FitsReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program 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 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.awt.image.BufferedImage; import java.io.IOException; import loci.formats.*; /** * FitsReader is the file format reader for * Flexible Image Transport System (FITS) images. * * Much of this code was adapted from ImageJ (http://rsb.info.nih.gov/ij). */ public class FitsReader extends FormatReader { // -- Fields -- /** Number of lines in the header. */ private int count; // -- Constructor -- /** Constructs a new FitsReader. */ public FitsReader() { super("Flexible Image Transport System", "fits"); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { return true; } /* @see loci.formats.IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); byte[] buf = new byte[core.sizeX[0] * core.sizeY[0] * FormatTools.getBytesPerPixel(core.pixelType[0])]; return openBytes(no, buf); } /* @see loci.formats.IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (no < 0 || no >= getImageCount()) { throw new FormatException("Invalid image number: " + no); } if (buf.length < core.sizeX[0] * core.sizeY[0] * FormatTools.getBytesPerPixel(core.pixelType[0])) { throw new FormatException("Buffer too small."); } in.seek(2880 + 2880 * (((count * 80) - 1) / 2880)); in.read(buf); return buf; } /* @see loci.formats.IFormatReader#openImage(int) */ public BufferedImage openImage(int no) throws FormatException, IOException { return ImageTools.makeImage(openBytes(no), core.sizeX[0], core.sizeY[0], core.sizeC[0], core.interleaved[0], FormatTools.getBytesPerPixel(core.pixelType[0]), core.littleEndian[0]); } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessStream(id); count = 1; byte[] b = new byte[80]; in.read(b); String line = new String(b); if (!line.startsWith("SIMPLE")) { throw new FormatException("Unsupported FITS file."); } while (true) { count++; in.read(b); line = new String(b); // parse key/value pair int ndx = line.indexOf("="); int comment = line.indexOf("/", ndx); if (comment < 0) comment = line.length(); String key = "", value = ""; if (ndx >= 0) { key = line.substring(0, ndx).trim(); value = line.substring(ndx + 1, comment).trim(); } else key = line.trim(); if (key.equals("END")) break; if (key.equals("BITPIX")) { int bits = Integer.parseInt(value); switch (bits) { case 8: core.pixelType[0] = FormatTools.UINT8; break; case 16: core.pixelType[0] = FormatTools.UINT16; break; case 32: core.pixelType[0] = FormatTools.UINT32; break; case -32: core.pixelType[0] = FormatTools.FLOAT; break; default: throw new FormatException("Unsupported pixel type: " + bits); } } else if (key.equals("NAXIS1")) core.sizeX[0] = Integer.parseInt(value); else if (key.equals("NAXIS2")) core.sizeY[0] = Integer.parseInt(value); else if (key.equals("NAXIS3")) core.sizeZ[0] = Integer.parseInt(value); addMeta(key, value); } core.sizeC[0] = 1; core.sizeT[0] = 1; if (core.sizeZ[0] == 0) core.sizeZ[0] = 1; core.imageCount[0] = core.sizeZ[0]; core.rgb[0] = false; core.littleEndian[0] = false; core.interleaved[0] = false; core.currentOrder[0] = "XYZCT"; MetadataStore store = getMetadataStore(); store.setPixels(new Integer(core.sizeX[0]), new Integer(core.sizeY[0]), new Integer(core.sizeZ[0]), new Integer(core.sizeC[0]), new Integer(core.sizeT[0]), new Integer(core.pixelType[0]), new Boolean(!core.littleEndian[0]), core.currentOrder[0], null, null); } }
Flip images vertically.
loci/formats/in/FitsReader.java
Flip images vertically.
<ide><path>oci/formats/in/FitsReader.java <ide> } <ide> <ide> in.seek(2880 + 2880 * (((count * 80) - 1) / 2880)); <del> in.read(buf); <add> int line = core.sizeX[0] * FormatTools.getBytesPerPixel(core.pixelType[0]); <add> for (int y=core.sizeY[0]-1; y>=0; y--) { <add> in.read(buf, y*line, line); <add> } <ide> return buf; <ide> } <ide>
JavaScript
isc
d78658c7e33751ee0d2862ccd718261ffd4de4f5
0
bmeck/noda-updater
const task = require('generator-runner'); const hyperquest = require('hyperquest'); const concat = require('concat-stream'); const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const semver = require('semver'); const tmp = require('tmp'); const minimatch = require('minimatch'); /* check({ currentVersion: '1.0.0', distUrl: 'https://iojs.org/dist', *approveFilename(filename) { return minimatch(filename, '**darwin*tar.gz'); }, //*approveVersion(version) { return true } }, (err, ret) => { if (err) console.error(`error: ${err.stack}`); else console.log(`return: ${ret}`); }); */ class Cleanup { constructor() { this.todo = null; this.finished = false; } add(fn) { if (this.finished) { fn(); } if (this.todo != null) { this.todo.push(fn); } else { this.todo = [fn]; } } finish() { if (this.finished) { throw new Error('already finished'); } this.finished = true; for (let action of this.todo) { action(); } this.todo = null; } } function check({ currentVersion, distUrl, approveFilename, approveVersion = function* () { return true; } }, cb) { task(function* () { let cleanup = new Cleanup(); try { let {tmp_dir, best_version} = yield { tmp_dir: _ => tmp.dir({ unsafeCleanup:true }, (err, path, dispose) => { cleanup.add(dispose); _(err, path); }), best_version: getVersionFromDist(distUrl, currentVersion, approveVersion) } let version_url = `${distUrl}/${best_version.version}`; // gc best_version = null; // write encrypted key to key_file let key_url = `${version_url}/SHASUMS256.txt.gpg`; let key_file = path.join(tmp_dir, 'key.gpg'); let keyring = path.join(tmp_dir, 'keyring'); let cleartext_sig_url = `${version_url}/SHASUMS256.txt`; let {cleartext_sig_body} = yield { keyring_imported: downloadAndImportKey(key_url, key_file, keyring), cleartext_sig_body: downloadAsString(cleartext_sig_url) }; // download encrypted signatures and transform them to cleartext let encrypted_sig_url = `${version_url}/SHASUMS256.txt.asc`; let decrypted_sig_body = yield decryptStream(hyperquest(encrypted_sig_url), keyring); if (decrypted_sig_body !== cleartext_sig_body) { throw new Error('signature decryption did not match cleartext'); } // gc cleartext_sig_body = null; let signatures = decrypted_sig_body.trim().split(/\n/g).map(line => { let [checksum, filepath] = line.trim().split(/\s+/); return {checksum, filepath}; }); let downloadable_files = yield getApprovedSignatures(signatures, approveFilename); if (downloadable_files.length === 0) { throw new Error('no file was approved to download'); } let resource_file = path.join(tmp_dir, 'resource'); for (let download of downloadable_files) { let download_url = `${version_url}/${download.filepath}` let download_file_stream = fs.createWriteStream(resource_file); yield waitOnStreamOpen(download_file_stream); // shell out because crypto cannot update list of algorithms (future safety) let checksum_child = cp.spawn('shasum', ['-a', '256', '-']); let download_http_stream = hyperquest(download_url); download_http_stream.pipe(checksum_child.stdin); download_http_stream.pipe(download_file_stream); let {checksum_body} = yield { download: waitOnWriteStream(download_file_stream), checksum_code: waitOnChild(checksum_child, 'shasum'), checksum_body: concatStream(checksum_child.stdout) }; if (checksum_body.split(/\s+/)[0] !== download.checksum) { throw new Error(`checksum mismatch on ${download_url}`); } let final_stream = fs.createReadStream(resource_file); yield waitOnStreamOpen(final_stream); return { from: download_url, stream: final_stream, checksum: download.checksum }; } } finally { cleanup.finish(); } }, cb); } function* downloadAsString(url) { let stream = hyperquest(url); return yield concatStream(stream); } function waitOnChild(child, name = 'child process') { return _ => { child.on('exit', (code, signal) => { if (code) _(new Error(`${name} failed with code: ${code}`)); else if (signal) _(new Error(`${name} failed with signal: ${signal}`)); else _(null); }); } } function waitOnWriteStream(stream) { return _ => { stream .on('finish', () => _(null, null) ) .on('error', err => _(err, undefined)); } } function concatStream(stream) { return _ => { stream.pipe(concat( (body) => _(null, String(body)) )) .on('error', (err) => _(err, undefined)); } } function waitOnStreamOpen(stream) { return _ => { function onerror(e) { _(e, undefined); } function onopen() { stream.removeListener('error', onerror); _(null, undefined); } stream.on('open', onopen); stream.on('error', onerror); } } function* getVersionFromDist(distUrl, currentVersion, approveVersion) { let body = yield downloadAsString(`${distUrl}/index.json`); let approved = []; let versions = JSON.parse(body); for (let version of versions) { let approval = yield approveVersion(version); let newer = semver.gt(version.version, currentVersion) if (approval && newer) { approved.push(version); } } if (approved.length === 0) { return null; } let best_version = yield getBestVersion(approved); return best_version; } function* getBestVersion(versionArray, approveVersion) { let best_version = versionArray[0]; let best_version_str = best_version.version.slice(1); for (let version of versionArray) { let version_str = version.version.slice(1); if (semver.gt(version_str, best_version_str)) { best_version = version; best_version_str = version_str; } } return best_version; } function* getApprovedSignatures(signatures, approveFilename) { let approved_signatures = []; for (let signature of signatures) { let approved = yield approveFilename(signature.filepath); if (approved) { approved_signatures.push(signature); } } return approved_signatures; } function* downloadAndImportKey(key_url, key_file, keyring) { let key_body = yield downloadAsString(key_url); yield _ => fs.writeFile(key_file, key_body, _); // create a pgp keyring we can use with the key yield _ => cp.exec(`gpg --no-default-keyring --primary-keyring ${keyring} --import ${key_file}`, _); } function* decryptStream(stream, keyring) { let child = cp.spawn('gpg', ['--no-default-keyring', '--primary-keyring', keyring]); stream.pipe(child.stdin); let {code, decrypted_sig_body} = yield { code: waitOnChild(child, 'gpg'), decrypted_sig_body: concatStream(child.stdout) }; return decrypted_sig_body; }
lib/index.js
const task = require('generator-runner'); const hyperquest = require('hyperquest'); const concat = require('concat-stream'); const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const semver = require('semver'); const tmp = require('tmp'); const minimatch = require('minimatch'); check({ currentVersion: '1.0.0', distUrl: 'https://iojs.org/dist', *approveFilename(filename) { return minimatch(filename, '**darwin*tar.gz'); }, //*approveVersion(version) { return true } }, (err, ret) => { if (err) console.error(`error: ${err.stack}`); else console.log(`return: ${ret}`); }); class Cleanup { constructor() { this.todo = null; this.finished = false; } push(fn) { if (this.finished) { fn(); } } finish(fn) { this.finished = true; if (this.todo != null) { for (let action of this.todo) { action(); } fn(); } else { this.todo = [fn]; } } } function check({ currentVersion, distUrl, approveFilename, approveVersion = function* () { return true; } }, cb) { task(function* () { let cleanup = new Cleanup(); try { let {tmp_dir, version_array} = yield { tmp_dir: _ => tmp.dir({ unsafeCleanup:true }, (err, path, dispose) => { cleanup.push(dispose); _(err, path); }), version_array: getVersionsFromDist(distUrl, currentVersion, approveVersion) } if (version_array.length === 0) { return null; } let best_version = yield getBestVersion(version_array); // gc version_array = null; let version_url = `${distUrl}/${best_version.version}`; // write encrypted key to key_file let key_url = `${version_url}/SHASUMS256.txt.gpg`; let key_file = path.join(tmp_dir, 'key.gpg'); let keyring = path.join(tmp_dir, 'keyring'); let cleartext_sig_url = `${version_url}/SHASUMS256.txt`; let {cleartext_sig_body} = yield { keyring_imported: downloadAndImportKey(key_url, key_file, keyring), cleartext_sig_body: downloadAsString(cleartext_sig_url) }; // download encrypted signatures and transform them to cleartext let encrypted_sig_url = `${version_url}/SHASUMS256.txt.asc`; let child = cp.spawn('gpg', ['--no-default-keyring', '--primary-keyring', keyring]); hyperquest(encrypted_sig_url).pipe(child.stdin); let {code, decrypted_sig_body} = yield { code: waitOnChild(child, 'gpg'), decrypted_sig_body: concatStream(child.stdout) }; if (decrypted_sig_body !== cleartext_sig_body) { throw new Error('signature decryption did not match cleartext'); } // gc cleartext_sig_body = null; let signatures = decrypted_sig_body.trim().split(/\n/g).map(line => { let [checksum, filepath] = line.trim().split(/\s+/); return {checksum, filepath}; }); let downloadable_files = yield getApprovedSignatures(signatures, approveFilename); if (downloadable_files.length === 0) { throw new Error('no file was approved to download'); } let resource_file = path.join(tmp_dir, 'resource'); for (let download of downloadable_files) { let download_url = `${version_url}/${download.filepath}` let download_file_stream = fs.createWriteStream(resource_file); yield waitOnStreamOpen(download_file_stream); // shell out because crypto cannot update list of algorithms (future safety) let checksum_child = cp.spawn('shasum', ['-a', '256', '-']); let download_http_stream = hyperquest(download_url); download_http_stream.pipe(checksum_child.stdin); download_http_stream.pipe(download_file_stream); let {checksum_body} = yield { download: waitOnWriteStream(download_file_stream), checksum_code: waitOnChild(checksum_child, 'shasum'), checksum_body: concatStream(checksum_child.stdout) }; if (checksum_body.split(/\s+/)[0] !== download.checksum) { throw new Error(`checksum mismatch on ${download_url}`); } let final_stream = fs.createReadStream(resource_file); yield waitOnStreamOpen(final_stream); return { from: download_url, stream: final_stream, checksum: download.checksum }; } } finally { cleanup.finish(); } }, cb); } function* downloadAsString(url) { let stream = hyperquest(url); return yield concatStream(stream); } function waitOnChild(child, name = 'child process') { return _ => { child.on('exit', (code, signal) => { if (code) _(new Error(`${name} failed with code: ${code}`)); else if (signal) _(new Error(`${name} failed with signal: ${signal}`)); else _(null); }); } } function waitOnWriteStream(stream) { return _ => { stream .on('finish', () => _(null, null) ) .on('error', err => _(err, undefined)); } } function concatStream(stream) { return _ => { stream.pipe(concat( (body) => _(null, String(body)) )) .on('error', (err) => _(err, undefined)); } } function waitOnStreamOpen(stream) { return _ => { function onerror(e) { _(e, undefined); } function onopen() { stream.removeListener('error', onerror); _(null, undefined); } stream.on('open', onopen); stream.on('error', onerror); } } function* getVersionsFromDist(distUrl, currentVersion, approveVersion) { let body = yield downloadAsString(`${distUrl}/index.json`); let approved = []; let versions = JSON.parse(body); for (let version of versions) { let approval = yield approveVersion(version); let newer = semver.gt(version.version, currentVersion) if (approval && newer) { approved.push(version); } } return approved; } function* getBestVersion(versionArray, approveVersion) { let best_version = versionArray[0]; let best_version_str = best_version.version.slice(1); for (let version of versionArray) { let version_str = version.version.slice(1); if (semver.gt(version_str, best_version_str)) { best_version = version; best_version_str = version_str; } } return best_version; } function* getApprovedSignatures(signatures, approveFilename) { let approved_signatures = []; for (let signature of signatures) { let approved = yield approveFilename(signature.filepath); if (approved) { approved_signatures.push(signature); } } return approved_signatures; } function* downloadAndImportKey(key_url, key_file, keyring) { let key_body = yield downloadAsString(key_url); yield _ => fs.writeFile(key_file, key_body, _); // gc key_body = null; // create a pgp keyring we can use with the key yield _ => cp.exec(`gpg --no-default-keyring --primary-keyring ${keyring} --import ${key_file}`, _); } function withTmpDir() { }
cleanup, move things to fns
lib/index.js
cleanup, move things to fns
<ide><path>ib/index.js <ide> const tmp = require('tmp'); <ide> const minimatch = require('minimatch'); <ide> <add>/* <ide> check({ <ide> currentVersion: '1.0.0', <ide> distUrl: 'https://iojs.org/dist', <ide> if (err) console.error(`error: ${err.stack}`); <ide> else console.log(`return: ${ret}`); <ide> }); <add>*/ <ide> <ide> class Cleanup { <ide> constructor() { <ide> this.finished = false; <ide> } <ide> <del> push(fn) { <add> add(fn) { <ide> if (this.finished) { <ide> fn(); <ide> } <del> } <del> <del> finish(fn) { <del> this.finished = true; <ide> if (this.todo != null) { <del> for (let action of this.todo) { <del> action(); <del> } <del> fn(); <add> this.todo.push(fn); <ide> } <ide> else { <ide> this.todo = [fn]; <ide> } <add> } <add> <add> finish() { <add> if (this.finished) { <add> throw new Error('already finished'); <add> } <add> this.finished = true; <add> for (let action of this.todo) { <add> action(); <add> } <add> this.todo = null; <ide> } <ide> } <ide> <ide> task(function* () { <ide> let cleanup = new Cleanup(); <ide> try { <del> let {tmp_dir, version_array} = yield { <add> let {tmp_dir, best_version} = yield { <ide> tmp_dir: _ => tmp.dir({ <ide> unsafeCleanup:true <ide> }, (err, path, dispose) => { <del> cleanup.push(dispose); <add> cleanup.add(dispose); <ide> _(err, path); <ide> }), <del> version_array: getVersionsFromDist(distUrl, currentVersion, approveVersion) <del> } <del> if (version_array.length === 0) { <del> return null; <del> } <del> <del> let best_version = yield getBestVersion(version_array); <add> best_version: getVersionFromDist(distUrl, currentVersion, approveVersion) <add> } <add> <add> let version_url = `${distUrl}/${best_version.version}`; <ide> <ide> // gc <del> version_array = null; <del> <del> let version_url = `${distUrl}/${best_version.version}`; <add> best_version = null; <ide> <ide> // write encrypted key to key_file <ide> let key_url = `${version_url}/SHASUMS256.txt.gpg`; <ide> cleartext_sig_body: downloadAsString(cleartext_sig_url) <ide> }; <ide> <add> <ide> // download encrypted signatures and transform them to cleartext <ide> let encrypted_sig_url = `${version_url}/SHASUMS256.txt.asc`; <del> let child = cp.spawn('gpg', ['--no-default-keyring', '--primary-keyring', keyring]); <del> hyperquest(encrypted_sig_url).pipe(child.stdin); <del> let {code, decrypted_sig_body} = yield { <del> code: waitOnChild(child, 'gpg'), <del> decrypted_sig_body: concatStream(child.stdout) <del> }; <add> let decrypted_sig_body = yield decryptStream(hyperquest(encrypted_sig_url), keyring); <ide> <ide> if (decrypted_sig_body !== cleartext_sig_body) { <ide> throw new Error('signature decryption did not match cleartext'); <ide> } <ide> } <ide> <del>function* getVersionsFromDist(distUrl, currentVersion, approveVersion) { <add>function* getVersionFromDist(distUrl, currentVersion, approveVersion) { <ide> let body = yield downloadAsString(`${distUrl}/index.json`); <ide> let approved = []; <ide> let versions = JSON.parse(body); <ide> approved.push(version); <ide> } <ide> } <del> return approved; <add> if (approved.length === 0) { <add> return null; <add> } <add> <add> let best_version = yield getBestVersion(approved); <add> <add> return best_version; <ide> } <ide> <ide> function* getBestVersion(versionArray, approveVersion) { <ide> function* downloadAndImportKey(key_url, key_file, keyring) { <ide> let key_body = yield downloadAsString(key_url); <ide> yield _ => fs.writeFile(key_file, key_body, _); <del> // gc <del> key_body = null; <ide> <ide> // create a pgp keyring we can use with the key <ide> yield _ => cp.exec(`gpg --no-default-keyring --primary-keyring ${keyring} --import ${key_file}`, _); <ide> } <ide> <del>function withTmpDir() { <del>} <add>function* decryptStream(stream, keyring) { <add> let child = cp.spawn('gpg', ['--no-default-keyring', '--primary-keyring', keyring]); <add> stream.pipe(child.stdin); <add> let {code, decrypted_sig_body} = yield { <add> code: waitOnChild(child, 'gpg'), <add> decrypted_sig_body: concatStream(child.stdout) <add> }; <add> return decrypted_sig_body; <add>}
Java
unlicense
ba71da87805855bea1f9494a71dbf87993a6b87f
0
Arquisoft/censuses_2a
package es.uniovi.asw; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; import es.uniovi.asw.DBUpdate.factories.Factories; import es.uniovi.asw.DBUpdate.model.Usuario; import es.uniovi.asw.DBUpdate.persistence.UsuarioDao; import es.uniovi.asw.WriteReport.Log; public class TestBD { /* @BeforeClass public static void reiniciarBD(){ UsuarioDao dao= Factories.persistence.createUsuarioDao(); dao.deleteUsuarios(); dao.reiniciaID(); }*/ private static Usuario user ; private static Usuario user1 ; private static Usuario user2 ; private static Usuario user3 ; @BeforeClass public static void crearUsuarios(){ user = new Usuario("Dario Suarez","[email protected]","71778298J",25); user1 = new Usuario("Victor","[email protected]","53548918L",12); user2 = new Usuario("Pepe","[email protected]","83656825Y",30); try{ user3 = new Usuario("Juan","correo3","75603564m",02); }catch(IllegalArgumentException e){ Log log= Factories.service.createLog(); log.createLog(); log.updateLog("testDB", e.getMessage().toString()); log.closeLog(); } } @Test public void testFind() { assertNotNull(Factories.persistence.createUsuarioDao().findByNIF(user.getNIF())); assertNotNull(Factories.persistence.createUsuarioDao().findByNIF(user1.getNIF())); assertNotNull(Factories.persistence.createUsuarioDao().findByNIF(user2.getNIF())); } @Test public void testADD() { assertTrue(Factories.persistence.createUsuarioDao().save(user)); assertTrue(Factories.persistence.createUsuarioDao().save(user1)); //assertTrue(Factories.persistence.createUsuarioDao().save(user3)); assertTrue(Factories.persistence.createUsuarioDao().save(user2)); System.out.println(user.toString()); assertFalse(Factories.persistence.createUsuarioDao().save(user2)); assertFalse(Factories.persistence.createUsuarioDao().save(user1)); assertFalse(Factories.persistence.createUsuarioDao().save(user)); //assertFalse(Factories.persistence.createUsuarioDao().save(user3)); } @Test public void testRemove(){ UsuarioDao dao=Factories.persistence.createUsuarioDao(); assertTrue(dao.delete(user1.getNIF())); assertEquals(2,dao.getUsuarios().size()); assertTrue(dao.delete(user.getNIF())); assertEquals(1,dao.getUsuarios().size()); assertTrue(dao.delete(user2.getNIF())); assertEquals(0,dao.getUsuarios().size()); //assertTrue(dao.delete(user3.getNIF())); //assertEquals(0,dao.getUsuarios().size()); } }
src/test/java/es/uniovi/asw/TestBD.java
package es.uniovi.asw; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; import es.uniovi.asw.DBUpdate.factories.Factories; import es.uniovi.asw.DBUpdate.model.Usuario; import es.uniovi.asw.DBUpdate.persistence.UsuarioDao; import es.uniovi.asw.WriteReport.Log; public class TestBD { /* @BeforeClass public static void reiniciarBD(){ UsuarioDao dao= Factories.persistence.createUsuarioDao(); dao.deleteUsuarios(); dao.reiniciaID(); }*/ private static Usuario user ; private static Usuario user1 ; private static Usuario user2 ; private static Usuario user3 ; @BeforeClass public static void crearUsuarios(){ user = new Usuario("Dario Suarez","[email protected]","71778298J",25); user1 = new Usuario("Victor","correo1","53548918L",12); user2 = new Usuario("Pepe","correo2","83656825Y",30); try{ user3 = new Usuario("Juan","correo3","75603564m",02); }catch(IllegalArgumentException e){ Log log= Factories.service.createLog(); log.createLog(); log.updateLog("testDB", e.getMessage().toString()); log.closeLog(); } } @Test public void testFind() { assertNotNull(Factories.persistence.createUsuarioDao().findByNIF(user.getNIF())); assertNotNull(Factories.persistence.createUsuarioDao().findByNIF(user1.getNIF())); assertNotNull(Factories.persistence.createUsuarioDao().findByNIF(user2.getNIF())); } @Test public void testADD() { assertTrue(Factories.persistence.createUsuarioDao().save(user)); assertTrue(Factories.persistence.createUsuarioDao().save(user1)); //assertTrue(Factories.persistence.createUsuarioDao().save(user3)); assertTrue(Factories.persistence.createUsuarioDao().save(user2)); System.out.println(user.toString()); assertFalse(Factories.persistence.createUsuarioDao().save(user2)); assertFalse(Factories.persistence.createUsuarioDao().save(user1)); assertFalse(Factories.persistence.createUsuarioDao().save(user)); //assertFalse(Factories.persistence.createUsuarioDao().save(user3)); } @Test public void testRemove(){ UsuarioDao dao=Factories.persistence.createUsuarioDao(); assertTrue(dao.delete(user1.getNIF())); assertEquals(2,dao.getUsuarios().size()); assertTrue(dao.delete(user.getNIF())); assertEquals(1,dao.getUsuarios().size()); assertTrue(dao.delete(user2.getNIF())); assertEquals(0,dao.getUsuarios().size()); //assertTrue(dao.delete(user3.getNIF())); //assertEquals(0,dao.getUsuarios().size()); } }
modificacion dario
src/test/java/es/uniovi/asw/TestBD.java
modificacion dario
<ide><path>rc/test/java/es/uniovi/asw/TestBD.java <ide> public static void crearUsuarios(){ <ide> <ide> user = new Usuario("Dario Suarez","[email protected]","71778298J",25); <del> user1 = new Usuario("Victor","correo1","53548918L",12); <del> user2 = new Usuario("Pepe","correo2","83656825Y",30); <add> user1 = new Usuario("Victor","[email protected]","53548918L",12); <add> user2 = new Usuario("Pepe","[email protected]","83656825Y",30); <ide> <ide> try{ <ide> user3 = new Usuario("Juan","correo3","75603564m",02);
Java
unlicense
9040a64dd0dac9daa3233eb52f31e5802917fb71
0
Vexatos/EnderIO,eduardog3000/EnderIO,MrNuggelz/EnderIO,mezz/EnderIO,Vexatos/EnderIO,mmelvin0/EnderIO,D-Inc/EnderIO,Joccob/EnderIO,SleepyTrousers/EnderIO,torteropaid/EnderIO,Samernieve/EnderIO,Quantum64/EnderIO,Joccob/EnderIO,MatthiasMann/EnderIO,HenryLoenwind/EnderIO,eduardog3000/EnderIO
package crazypants.enderio.item.darksteel; import java.util.HashMap; import java.util.Map; import java.util.UUID; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.MovementInput; import cofh.api.energy.IEnergyContainerItem; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.config.Config; import crazypants.enderio.network.PacketHandler; import crazypants.util.Util; import crazypants.vecmath.VecmathUtil; import crazypants.vecmath.Vector3d; import crazypants.vecmath.Vector4d; public class DarkSteelController { public static final DarkSteelController instance = new DarkSteelController(); private AttributeModifier[] walkModifiers = new AttributeModifier[] { new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.WALK_MULTIPLIERS[0], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.WALK_MULTIPLIERS[1], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.WALK_MULTIPLIERS[2], 1), }; private AttributeModifier[] sprintModifiers = new AttributeModifier[] { new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.SPRINT_MULTIPLIERS[0], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.SPRINT_MULTIPLIERS[1], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.SPRINT_MULTIPLIERS[2], 1), }; private AttributeModifier swordDamageModifierPowered = new AttributeModifier(new UUID(63242325, 320981923), "Weapon modifier", 2, 0); private boolean wasJumping; private int jumpCount; private int ticksSinceLastJump; //private boolean isGlideActive = false; private Map<String, Boolean> glideActiveMap = new HashMap<String, Boolean>(); private DarkSteelController() { PacketHandler.INSTANCE.registerMessage(PacketDarkSteelPowerPacket.class, PacketDarkSteelPowerPacket.class, PacketHandler.nextID(), Side.SERVER); PacketHandler.INSTANCE.registerMessage(PacketGlideState.class, PacketGlideState.class, PacketHandler.nextID(), Side.SERVER); } public void setGlideActive(EntityPlayer player, boolean isGlideActive) { if(player.getGameProfile().getName() != null) { glideActiveMap.put(player.getGameProfile().getName(), isGlideActive); } } public boolean isGlideActive(EntityPlayer player) { Boolean isActive = glideActiveMap.get(player.getGameProfile().getName()); if(isActive == null) { return false; } return isActive.booleanValue(); } @SubscribeEvent public void onPlayerTick(TickEvent.PlayerTickEvent event) { EntityPlayer player = event.player; if(event.phase == Phase.START) { //boots updateStepHeightAndFallDistance(player); //leggings updateSpeed(player); //sword updateSword(player); updateGlide(player); } } private void updateGlide(EntityPlayer player) { if(!isGlideActive(player) || !isGliderUpgradeEquipped(player)) { return; } if(!player.onGround && player.motionY < 0 && !player.isSneaking()) { double horizontalSpeed = Config.darkSteelGliderHorizontalSpeed; double verticalSpeed = Config.darkSteelGliderVerticalSpeed; if(player.isSprinting()) { verticalSpeed = Config.darkSteelGliderVerticalSpeedSprinting; } Vector3d look = Util.getLookVecEio(player); Vector3d side = new Vector3d(); side.cross(new Vector3d(0, 1, 0), look); Vector3d playerPos = new Vector3d(player.prevPosX, player.prevPosY, player.prevPosZ); Vector3d b = new Vector3d(playerPos); b.y += 1; Vector3d c = new Vector3d(playerPos); c.add(side); Vector4d plane = new Vector4d(); VecmathUtil.computePlaneEquation(playerPos, b, c, plane); double dist = Math.abs(VecmathUtil.distanceFromPointToPlane(plane, new Vector3d(player.posX, player.posY, player.posZ))); double minDist = 0.15; if(dist < minDist) { double dropRate = (minDist * 10) - (dist * 10); verticalSpeed = verticalSpeed + (verticalSpeed * dropRate * 8); horizontalSpeed -= (0.02 * dropRate); } double x = Math.cos(Math.toRadians(player.rotationYawHead + 90)) * horizontalSpeed; double z = Math.sin(Math.toRadians(player.rotationYawHead + 90)) * horizontalSpeed; player.motionX += x; player.motionZ += z; player.motionY = verticalSpeed; player.fallDistance = 0f; } } public boolean isGliderUpgradeEquipped(EntityPlayer player) { ItemStack chestPlate = player.getEquipmentInSlot(3); GliderUpgrade glideUpgrade = GliderUpgrade.loadFromItem(chestPlate); if(glideUpgrade == null) { return false; } return true; } private void updateSword(EntityPlayer player) { if(ItemDarkSteelSword.isEquipped(player)) { IAttributeInstance attackInst = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.attackDamage); attackInst.removeModifier(swordDamageModifierPowered); ItemStack sword = player.getCurrentEquippedItem(); if(Config.darkSteelSwordPowerUsePerHit <= 0 || EnderIO.itemDarkSteelSword.getEnergyStored(sword) >= Config.darkSteelSwordPowerUsePerHit) { attackInst.applyModifier(swordDamageModifierPowered); } } } private void updateSpeed(EntityPlayer player) { if(player.worldObj.isRemote) { return; } IAttributeInstance moveInst = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.movementSpeed); if(moveInst.getModifier(walkModifiers[0].getID()) != null) { moveInst.removeModifier(walkModifiers[0]); //any will so as they all have the same UID } else if(moveInst.getModifier(sprintModifiers[0].getID()) != null) { moveInst.removeModifier(sprintModifiers[0]); } ItemStack leggings = player.getEquipmentInSlot(2); SpeedUpgrade speedUpgrade = SpeedUpgrade.loadFromItem(leggings); if(leggings != null && leggings.getItem() == EnderIO.itemDarkSteelLeggings && speedUpgrade != null) { double horzMovement = Math.abs(player.distanceWalkedOnStepModified - player.prevDistanceWalkedModified); double costModifier = player.isSprinting() ? Config.darkSteelSprintPowerCost : Config.darkSteelWalkPowerCost; costModifier = costModifier + (costModifier * speedUpgrade.walkMultiplier); int cost = (int) (horzMovement * costModifier); int totalEnergy = getPlayerEnergy(player, EnderIO.itemDarkSteelLeggings); if(totalEnergy > 0) { usePlayerEnergy(player, EnderIO.itemDarkSteelLeggings, cost); if(player.isSprinting()) { moveInst.applyModifier(sprintModifiers[speedUpgrade.level - 1]); } else { moveInst.applyModifier(walkModifiers[speedUpgrade.level - 1]); } } } } private void updateStepHeightAndFallDistance(EntityPlayer player) { ItemStack boots = player.getEquipmentInSlot(1); if(boots != null && boots.getItem() == EnderIO.itemDarkSteelBoots) { int costedDistance = (int) player.fallDistance; if(costedDistance > 0) { int energyCost = costedDistance * Config.darkSteelFallDistanceCost; int totalEnergy = getPlayerEnergy(player, EnderIO.itemDarkSteelBoots); if(totalEnergy > 0 && totalEnergy >= energyCost) { usePlayerEnergy(player, EnderIO.itemDarkSteelBoots, energyCost); player.fallDistance -= costedDistance; } } } JumpUpgrade jumpUpgrade = JumpUpgrade.loadFromItem(boots); if(jumpUpgrade != null && boots != null && boots.getItem() == EnderIO.itemDarkSteelBoots) { player.stepHeight = 1.0023F; } else if(player.stepHeight == 1.0023F) { player.stepHeight = 0.5001F; } } void usePlayerEnergy(EntityPlayer player, ItemDarkSteelArmor armor, int cost) { if(cost == 0) { return; } boolean extracted = false; int remaining = cost; if(Config.darkSteelDrainPowerFromInventory) { for (ItemStack stack : player.inventory.mainInventory) { if(stack != null && stack.getItem() instanceof IEnergyContainerItem) { IEnergyContainerItem cont = (IEnergyContainerItem) stack.getItem(); int used = cont.extractEnergy(stack, remaining, false); remaining -= used; extracted |= used > 0; if(remaining <= 0) { player.inventory.markDirty(); return; } } } } if(armor != null && remaining > 0) { ItemStack stack = player.inventory.armorInventory[3 - armor.armorType]; if(stack != null) { int used = armor.extractEnergy(stack, remaining, false); extracted |= used > 0; } } if(extracted) { player.inventory.markDirty(); } } private int getPlayerEnergy(EntityPlayer player, ItemDarkSteelArmor armor) { int res = 0; if(Config.darkSteelDrainPowerFromInventory) { for (ItemStack stack : player.inventory.mainInventory) { if(stack != null && stack.getItem() instanceof IEnergyContainerItem) { IEnergyContainerItem cont = (IEnergyContainerItem) stack.getItem(); res += cont.extractEnergy(stack, Integer.MAX_VALUE, true); } } } if(armor != null) { ItemStack stack = player.inventory.armorInventory[3 - armor.armorType]; res = armor.getEnergyStored(stack); } return res; } @SideOnly(Side.CLIENT) @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) { if(event.phase == TickEvent.Phase.END) { EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; if(player == null) { return; } MovementInput input = player.movementInput; if(input.jump && !wasJumping) { doJump(player); } else if(input.jump && jumpCount < 3 && ticksSinceLastJump > 5) { doJump(player); } wasJumping = !player.isCollidedVertically; if(!wasJumping) { jumpCount = 0; } ticksSinceLastJump++; } } @SideOnly(Side.CLIENT) private void doJump(EntityClientPlayerMP player) { ItemStack boots = player.getEquipmentInSlot(1); JumpUpgrade jumpUpgrade = JumpUpgrade.loadFromItem(boots); if(jumpUpgrade == null || boots == null || boots.getItem() != EnderIO.itemDarkSteelBoots) { return; } int requiredPower = Config.darkSteelBootsJumpPowerCost * (int) Math.pow(jumpCount + 1, 2.5); int availablePower = getPlayerEnergy(player, EnderIO.itemDarkSteelBoots); if(availablePower > 0 && requiredPower <= availablePower && jumpCount < jumpUpgrade.level) { jumpCount++; player.motionY += 0.15 * Config.darkSteelBootsJumpModifier * jumpCount; ticksSinceLastJump = 0; usePlayerEnergy(player, EnderIO.itemDarkSteelBoots, requiredPower); PacketHandler.INSTANCE.sendToServer(new PacketDarkSteelPowerPacket(requiredPower, EnderIO.itemDarkSteelBoots.armorType)); } } }
src/main/java/crazypants/enderio/item/darksteel/DarkSteelController.java
package crazypants.enderio.item.darksteel; import java.util.HashMap; import java.util.Map; import java.util.UUID; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.MovementInput; import cofh.api.energy.IEnergyContainerItem; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.config.Config; import crazypants.enderio.network.PacketHandler; import crazypants.util.Util; import crazypants.vecmath.VecmathUtil; import crazypants.vecmath.Vector3d; import crazypants.vecmath.Vector4d; public class DarkSteelController { public static final DarkSteelController instance = new DarkSteelController(); private AttributeModifier[] walkModifiers = new AttributeModifier[] { new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.WALK_MULTIPLIERS[0], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.WALK_MULTIPLIERS[1], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.WALK_MULTIPLIERS[2], 1), }; private AttributeModifier[] sprintModifiers = new AttributeModifier[] { new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.SPRINT_MULTIPLIERS[0], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.SPRINT_MULTIPLIERS[1], 1), new AttributeModifier(new UUID(12879874982l, 320981923), "generic.movementSpeed", SpeedUpgrade.SPRINT_MULTIPLIERS[2], 1), }; private AttributeModifier swordDamageModifierPowered = new AttributeModifier(new UUID(63242325, 320981923), "Weapon modifier", 2, 0); private boolean wasJumping; private int jumpCount; private int ticksSinceLastJump; //private boolean isGlideActive = false; private Map<String, Boolean> glideActiveMap = new HashMap<String, Boolean>(); private DarkSteelController() { PacketHandler.INSTANCE.registerMessage(PacketDarkSteelPowerPacket.class, PacketDarkSteelPowerPacket.class, PacketHandler.nextID(), Side.SERVER); PacketHandler.INSTANCE.registerMessage(PacketGlideState.class, PacketGlideState.class, PacketHandler.nextID(), Side.SERVER); } public void setGlideActive(EntityPlayer player, boolean isGlideActive) { if(player.getGameProfile().getName() != null) { glideActiveMap.put(player.getGameProfile().getName(), isGlideActive); } } public boolean isGlideActive(EntityPlayer player) { Boolean isActive = glideActiveMap.get(player.getGameProfile().getName()); if(isActive == null) { return false; } return isActive.booleanValue(); } @SubscribeEvent public void onPlayerTick(TickEvent.PlayerTickEvent event) { EntityPlayer player = event.player; //TODO: I am doing this at Phase.START and Phase.END //boots step height updateStepHeightAndFallDistance(player); //leggings updateSpeed(player); //sword updateSword(player); if(event.phase == Phase.END) { updateGlide(player); } } private void updateGlide(EntityPlayer player) { if(!isGlideActive(player) || !isGliderUpgradeEquipped(player)) { return; } if(!player.onGround && player.motionY < 0 && !player.isSneaking()) { double horizontalSpeed = Config.darkSteelGliderHorizontalSpeed; double verticalSpeed = Config.darkSteelGliderVerticalSpeed; if(player.isSprinting()) { verticalSpeed = Config.darkSteelGliderVerticalSpeedSprinting; } Vector3d look = Util.getLookVecEio(player); Vector3d side = new Vector3d(); side.cross(new Vector3d(0, 1, 0), look); Vector3d playerPos = new Vector3d(player.prevPosX, player.prevPosY, player.prevPosZ); Vector3d b = new Vector3d(playerPos); b.y += 1; Vector3d c = new Vector3d(playerPos); c.add(side); Vector4d plane = new Vector4d(); VecmathUtil.computePlaneEquation(playerPos, b, c, plane); double dist = Math.abs(VecmathUtil.distanceFromPointToPlane(plane, new Vector3d(player.posX, player.posY, player.posZ))); double minDist = 0.15; if(dist < minDist) { double dropRate = (minDist * 10) - (dist * 10); verticalSpeed = verticalSpeed + (verticalSpeed * dropRate * 8); horizontalSpeed -= (0.02 * dropRate); } double x = Math.cos(Math.toRadians(player.rotationYawHead + 90)) * horizontalSpeed; double z = Math.sin(Math.toRadians(player.rotationYawHead + 90)) * horizontalSpeed; player.motionX += x; player.motionZ += z; player.motionY = verticalSpeed; player.fallDistance = 0f; } } public boolean isGliderUpgradeEquipped(EntityPlayer player) { ItemStack chestPlate = player.getEquipmentInSlot(3); GliderUpgrade glideUpgrade = GliderUpgrade.loadFromItem(chestPlate); if(glideUpgrade == null) { return false; } return true; } private void updateSword(EntityPlayer player) { if(ItemDarkSteelSword.isEquipped(player)) { IAttributeInstance attackInst = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.attackDamage); attackInst.removeModifier(swordDamageModifierPowered); ItemStack sword = player.getCurrentEquippedItem(); if(Config.darkSteelSwordPowerUsePerHit <= 0 || EnderIO.itemDarkSteelSword.getEnergyStored(sword) >= Config.darkSteelSwordPowerUsePerHit) { attackInst.applyModifier(swordDamageModifierPowered); } } } private void updateSpeed(EntityPlayer player) { IAttributeInstance moveInst = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.movementSpeed); moveInst.removeModifier(walkModifiers[0]); //any will so as they all have the same UID moveInst.removeModifier(sprintModifiers[0]); ItemStack leggings = player.getEquipmentInSlot(2); SpeedUpgrade speedUpgrade = SpeedUpgrade.loadFromItem(leggings); if(leggings != null && leggings.getItem() == EnderIO.itemDarkSteelLeggings && speedUpgrade != null) { double horzMovement = Math.sqrt(player.motionX * player.motionX + player.motionZ * player.motionZ); double costModifier = player.isSprinting() ? Config.darkSteelSprintPowerCost : Config.darkSteelWalkPowerCost; costModifier = costModifier + (costModifier * speedUpgrade.walkMultiplier); int cost = (int) (horzMovement * costModifier); int totalEnergy = getPlayerEnergy(player, EnderIO.itemDarkSteelLeggings); if(totalEnergy > 0 && totalEnergy >= cost) { usePlayerEnergy(player, EnderIO.itemDarkSteelLeggings, cost); if(player.isSprinting()) { moveInst.applyModifier(sprintModifiers[speedUpgrade.level - 1]); } else { moveInst.applyModifier(walkModifiers[speedUpgrade.level - 1]); } } } } private void updateStepHeightAndFallDistance(EntityPlayer player) { ItemStack boots = player.getEquipmentInSlot(1); if(boots != null && boots.getItem() == EnderIO.itemDarkSteelBoots) { int costedDistance = (int) player.fallDistance; if(costedDistance > 0) { int energyCost = costedDistance * Config.darkSteelFallDistanceCost; int totalEnergy = getPlayerEnergy(player, EnderIO.itemDarkSteelBoots); if(totalEnergy > 0 && totalEnergy >= energyCost) { usePlayerEnergy(player, EnderIO.itemDarkSteelBoots, energyCost); player.fallDistance -= costedDistance; } } } JumpUpgrade jumpUpgrade = JumpUpgrade.loadFromItem(boots); if(jumpUpgrade != null && boots != null && boots.getItem() == EnderIO.itemDarkSteelBoots) { player.stepHeight = 1.0023F; } else if(player.stepHeight == 1.0023F) { player.stepHeight = 0.5001F; } } void usePlayerEnergy(EntityPlayer player, ItemDarkSteelArmor armor, int cost) { if(cost == 0) { return; } int remaining = cost; if(Config.darkSteelDrainPowerFromInventory) { for (ItemStack stack : player.inventory.mainInventory) { if(stack != null && stack.getItem() instanceof IEnergyContainerItem) { IEnergyContainerItem cont = (IEnergyContainerItem) stack.getItem(); remaining -= cont.extractEnergy(stack, remaining, false); if(remaining <= 0) { return; } } } } if(armor != null) { ItemStack stack = player.inventory.armorInventory[3 - armor.armorType]; if(stack != null) { armor.extractEnergy(stack, remaining, false); player.inventory.markDirty(); } } } private int getPlayerEnergy(EntityPlayer player, ItemDarkSteelArmor armor) { int res = 0; if(Config.darkSteelDrainPowerFromInventory) { for (ItemStack stack : player.inventory.mainInventory) { if(stack != null && stack.getItem() instanceof IEnergyContainerItem) { IEnergyContainerItem cont = (IEnergyContainerItem) stack.getItem(); res += cont.extractEnergy(stack, Integer.MAX_VALUE, true); } } } if(armor != null) { ItemStack stack = player.inventory.armorInventory[3 - armor.armorType]; res = armor.getEnergyStored(stack); } return res; } @SideOnly(Side.CLIENT) @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) { if(event.phase == TickEvent.Phase.END) { EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; if(player == null) { return; } MovementInput input = player.movementInput; if(input.jump && !wasJumping) { doJump(player); } else if(input.jump && jumpCount < 3 && ticksSinceLastJump > 5) { doJump(player); } wasJumping = !player.isCollidedVertically; if(!wasJumping) { jumpCount = 0; } ticksSinceLastJump++; } } @SideOnly(Side.CLIENT) private void doJump(EntityClientPlayerMP player) { ItemStack boots = player.getEquipmentInSlot(1); JumpUpgrade jumpUpgrade = JumpUpgrade.loadFromItem(boots); if(jumpUpgrade == null || boots == null || boots.getItem() != EnderIO.itemDarkSteelBoots) { return; } int requiredPower = Config.darkSteelBootsJumpPowerCost * (int) Math.pow(jumpCount + 1, 2.5); int availablePower = getPlayerEnergy(player, EnderIO.itemDarkSteelBoots); if(availablePower > 0 && requiredPower <= availablePower && jumpCount < jumpUpgrade.level) { jumpCount++; player.motionY += 0.15 * Config.darkSteelBootsJumpModifier * jumpCount; ticksSinceLastJump = 0; usePlayerEnergy(player, EnderIO.itemDarkSteelBoots, requiredPower); PacketHandler.INSTANCE.sendToServer(new PacketDarkSteelPowerPacket(requiredPower, EnderIO.itemDarkSteelBoots.armorType)); } } }
Fixed issues when DS leggings with speed upgrade ran out of power.
src/main/java/crazypants/enderio/item/darksteel/DarkSteelController.java
Fixed issues when DS leggings with speed upgrade ran out of power.
<ide><path>rc/main/java/crazypants/enderio/item/darksteel/DarkSteelController.java <ide> public void onPlayerTick(TickEvent.PlayerTickEvent event) { <ide> EntityPlayer player = event.player; <ide> <del> //TODO: I am doing this at Phase.START and Phase.END <del> //boots step height <del> updateStepHeightAndFallDistance(player); <del> <del> //leggings <del> updateSpeed(player); <del> <del> //sword <del> updateSword(player); <del> <del> if(event.phase == Phase.END) { <add> <add> <add> if(event.phase == Phase.START) { <add> //boots <add> updateStepHeightAndFallDistance(player); <add> <add> //leggings <add> updateSpeed(player); <add> <add> //sword <add> updateSword(player); <add> <ide> updateGlide(player); <ide> } <ide> <ide> } <ide> <ide> private void updateSpeed(EntityPlayer player) { <add> if(player.worldObj.isRemote) { <add> return; <add> } <add> <ide> IAttributeInstance moveInst = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.movementSpeed); <del> moveInst.removeModifier(walkModifiers[0]); //any will so as they all have the same UID <del> moveInst.removeModifier(sprintModifiers[0]); <add> if(moveInst.getModifier(walkModifiers[0].getID()) != null) { <add> moveInst.removeModifier(walkModifiers[0]); //any will so as they all have the same UID <add> } else if(moveInst.getModifier(sprintModifiers[0].getID()) != null) { <add> moveInst.removeModifier(sprintModifiers[0]); <add> } <ide> <ide> ItemStack leggings = player.getEquipmentInSlot(2); <ide> SpeedUpgrade speedUpgrade = SpeedUpgrade.loadFromItem(leggings); <ide> if(leggings != null && leggings.getItem() == EnderIO.itemDarkSteelLeggings && speedUpgrade != null) { <ide> <del> double horzMovement = Math.sqrt(player.motionX * player.motionX + player.motionZ * player.motionZ); <del> double costModifier = player.isSprinting() ? Config.darkSteelSprintPowerCost : Config.darkSteelWalkPowerCost; <add> double horzMovement = Math.abs(player.distanceWalkedOnStepModified - player.prevDistanceWalkedModified); <add> double costModifier = player.isSprinting() ? Config.darkSteelSprintPowerCost : Config.darkSteelWalkPowerCost; <ide> costModifier = costModifier + (costModifier * speedUpgrade.walkMultiplier); <ide> int cost = (int) (horzMovement * costModifier); <del> <ide> int totalEnergy = getPlayerEnergy(player, EnderIO.itemDarkSteelLeggings); <del> if(totalEnergy > 0 && totalEnergy >= cost) { <add> <add> if(totalEnergy > 0) { <ide> usePlayerEnergy(player, EnderIO.itemDarkSteelLeggings, cost); <ide> if(player.isSprinting()) { <ide> moveInst.applyModifier(sprintModifiers[speedUpgrade.level - 1]); <ide> if(totalEnergy > 0 && totalEnergy >= energyCost) { <ide> usePlayerEnergy(player, EnderIO.itemDarkSteelBoots, energyCost); <ide> player.fallDistance -= costedDistance; <del> } <del> } <add> } <add> } <ide> } <ide> <ide> JumpUpgrade jumpUpgrade = JumpUpgrade.loadFromItem(boots); <ide> player.stepHeight = 1.0023F; <ide> } else if(player.stepHeight == 1.0023F) { <ide> player.stepHeight = 0.5001F; <del> } <del> } <del> <add> } <add> } <ide> <ide> void usePlayerEnergy(EntityPlayer player, ItemDarkSteelArmor armor, int cost) { <ide> if(cost == 0) { <ide> return; <ide> } <add> boolean extracted = false; <ide> int remaining = cost; <ide> if(Config.darkSteelDrainPowerFromInventory) { <ide> for (ItemStack stack : player.inventory.mainInventory) { <ide> if(stack != null && stack.getItem() instanceof IEnergyContainerItem) { <ide> IEnergyContainerItem cont = (IEnergyContainerItem) stack.getItem(); <del> remaining -= cont.extractEnergy(stack, remaining, false); <add> int used = cont.extractEnergy(stack, remaining, false); <add> remaining -= used; <add> extracted |= used > 0; <ide> if(remaining <= 0) { <add> player.inventory.markDirty(); <ide> return; <ide> } <ide> } <ide> } <ide> } <del> <del> if(armor != null) { <add> if(armor != null && remaining > 0) { <ide> ItemStack stack = player.inventory.armorInventory[3 - armor.armorType]; <ide> if(stack != null) { <del> armor.extractEnergy(stack, remaining, false); <del> player.inventory.markDirty(); <del> } <add> int used = armor.extractEnergy(stack, remaining, false); <add> extracted |= used > 0; <add> } <add> } <add> if(extracted) { <add> player.inventory.markDirty(); <ide> } <ide> } <ide>
JavaScript
mpl-2.0
89af94c8e8179391e44dd4dfa0e6ff50ff80ff39
0
brentan/swift_calcs_client
/* Use the giac_generic class, along with the createGiacElement constructor, to create many of the basic giac function blocks that don't require special controls (such as solve does) */ createGiacElement({ name: 'fft', code: 'fourier transform', helpText: '<<fourier transform <[DATA]>>>\nComputer the discrete fourier transform of the array provided. If the number of elements in DATA is a power of 2, a fast fourier transform routine is used to increase computation speed.', content: [ "<<MathQuill {ghost: 'array'}>>", ], command: "fft($1)" }); createGiacElement({ name: 'ifft', code: 'inverse fourier transform', helpText: '<<inverse fourier transform <[DATA]>>>\nComputer the inverse fourier transform of the array provided.', content: [ "<<MathQuill {ghost: 'array'}>>", ], command: "ifft($1)" }); createGiacElement({ name: 'laplace', code: 'laplace transform', function_of: 's', helpText: '<<laplace <[EXPR]> for <[VAR]>>>\nFinds the laplace transform for the expression EXPR with variable VAR. Result will have variable s.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "laplace($1, $2, 's')" }); createGiacElement({ name: 'ilaplace', code: 'inverse laplace transform', function_of: 'x', helpText: '<<ilaplace <[EXPR]> for <[VAR]>>>\nFinds the laplace transform for the expression EXPR with variable VAR. Result will have variable x.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "ilaplace($1, $2, 'x')" }); createGiacElement({ name: 'fouriera', code: 'fourier coefficient a', function_of: 'n', helpText: '<<fourier a <[EXPR]> for <[VAR]>, period <[T]>, lower bound <[BOUND]>>>\nFinds the expression for the fourier coefficients a<sub>n</sub> for the expression EXPR with variable VAR, period T, and boundes BOUND to BOUND+T.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with period of <<MathQuill {ghost: 'T' }>>", "and lower bound <<MathQuill {ghost: '0', default: '0' }>>", ], pre_command: "assume('n', DOM_INT)", command: "fourier_an($1, $2, $3, 'n', $4)" }); createGiacElement({ name: 'fourierb', code: 'fourier coefficient b', function_of: 'n', helpText: '<<fourier b <[EXPR]> for <[VAR]>, period <[T]>, lower bound <[BOUND]>>>\nFinds the expression for the fourier coefficients b<sub>n</sub> for the expression EXPR with variable VAR, period T, and boundes BOUND to BOUND+T.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with period of <<MathQuill {ghost: 'T' }>>", "and lower bound <<MathQuill {ghost: '0', default: '0' }>>", ], pre_command: "assume('n', DOM_INT)", command: "fourier_bn($1, $2, $3, 'n', $4)" }); createGiacElement({ name: 'fourierc', code: 'fourier coefficient c', function_of: 'n', helpText: '<<fourier c <[EXPR]> for <[VAR]>, period <[T]>, lower bound <[BOUND]>>>\nFinds the expression for the fourier coefficients c<sub>n</sub> for the expression EXPR with variable VAR, period T, and boundes BOUND to BOUND+T.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with period of <<MathQuill {ghost: 'T' }>>", "and lower bound <<MathQuill {ghost: '0', default: '0' }>>", ], pre_command: "assume('n', DOM_INT)", command: "fourier_cn($1, $2, $3, 'n', $4)" }); createGiacElement({ name: 'series', code: 'series expansion', helpText: '<<series <[EXPR]> for <[VAR]> around <[VALUE]> of order <[ORDER]> <[TYPE]>>>\nFinds the series expansion of EXPR with variable VAR about point VALUE of order ORDER and direction specified by TYPE.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "around <<MathQuill {ghost: '0', default: '0' }>>", "of order <<MathQuill {ghost: '5', default: '5'}>> <<SelectBox {options: { 0: 'Bidirectional', 1: 'Unidirectional positive', -1: 'Unidirectional negative'}}>>" ], command: "series($1, $2, $3, $4, $5)" }); createGiacElement({ name: 'taylor', code: 'taylor expansion', helpText: '<<taylor <[EXPR]> for <[VAR]> around <[VALUE]> of order <[ORDER]> <[TYPE]>>>\nFinds the taylor expansion of EXPR with variable VAR about point VALUE of order ORDER and direction specified by TYPE.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "around <<MathQuill {ghost: '0', default: '0' }>>", "of order <<MathQuill {ghost: '5', default: '5'}>> <<SelectBox {options: { 0: 'Bidirectional', 1: 'Unidirectional positive', -1: 'Unidirectional negative'}}>>" ], command: "taylor($1, $2, $4, $3, $5)" }); createGiacElement({ name: 'ztrans', code: 'Z transform', function_of: 'z', helpText: '<<z transform <[EXPR]> for <[VAR]>>>\nFinds the Z transform for the expression EXPR with variable VAR. Result will have variable z.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "ztrans($1, $2, 'z')" }); createGiacElement({ name: 'iztrans', code: 'inverse Z transform', function_of: 'x', helpText: '<<inverse Z transform <[EXPR]> for <[VAR]>>>\nFinds the inverse Z transform for the expression EXPR with variable VAR. Result will have variable x.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "invztrans($1, $2, 'x')" }); createGiacElement({ name: 'fmax', code: 'function maximum', helpText: '<<maximum of <[EXPR]> for <[VAR]> between <[START]> and <[END]>>>\nFinds the maximum value of EXPR for variable VAR between START and END. Value returned is the value of VAR at which the maximum occurs.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "between <<MathQuill {ghost: 'start' }>> and <<MathQuill {ghost: 'end' }>>" ], command: "fMax($1, $2=$3..$4)" }); createGiacElement({ name: 'fmin', code: 'function minimum', helpText: '<<minimum of <[EXPR]> for <[VAR]> between <[START]> and <[END]>>>\nFinds the minimum value of EXPR for variable VAR between START and END. Value returned is the value of VAR at which the minimum occurs.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "between <<MathQuill {ghost: 'start' }>> and <<MathQuill {ghost: 'end' }>>" ], command: "fMin($1, $2=$3..$4)" }); createGiacElement({ name: 'pade', code: 'pade approximant', helpText: '<<pade approximant of <[EXPR]> for <[VAR]> with numerator order <[m]> and denominator order <[m]>>>\nFinds pade approximant of EXPR with variable VAR of order [m/n]', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with numerator order <<MathQuill {ghost: 'm' }>>", "and denominator order <<MathQuill {ghost: 'n' }>>" ], command: "pade($1, '$2', $4+2, $3+1)" });
src/elements/math_output/giac_generic_constructors.js
/* Use the giac_generic class, along with the createGiacElement constructor, to create many of the basic giac function blocks that don't require special controls (such as solve does) */ createGiacElement({ name: 'fft', code: 'fourier transform', helpText: '<<fourier transform <[DATA]>>>\nComputer the discrete fourier transform of the array provided. If the number of elements in DATA is a power of 2, a fast fourier transform routine is used to increase computation speed.', content: [ "<<MathQuill {ghost: 'array'}>>", ], command: "fft($1)" }); createGiacElement({ name: 'ifft', code: 'inverse fourier transform', helpText: '<<inverse fourier transform <[DATA]>>>\nComputer the inverse fourier transform of the array provided.', content: [ "<<MathQuill {ghost: 'array'}>>", ], command: "ifft($1)" }); createGiacElement({ name: 'laplace', code: 'laplace transform', function_of: 's', helpText: '<<laplace <[EXPR]> for <[VAR]>>>\nFinds the laplace transform for the expression EXPR with variable VAR. Result will have variable s.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "laplace($1, $2, 's')" }); createGiacElement({ name: 'ilaplace', code: 'inverse laplace transform', function_of: 'x', helpText: '<<ilaplace <[EXPR]> for <[VAR]>>>\nFinds the laplace transform for the expression EXPR with variable VAR. Result will have variable x.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "ilaplace($1, $2, 'x')" }); createGiacElement({ name: 'fouriera', code: 'fourier coefficient a', function_of: 'n', helpText: '<<fourier a <[EXPR]> for <[VAR]>, period <[T]>, lower bound <[BOUND]>>>\nFinds the expression for the fourier coefficients a<sub>n</sub> for the expression EXPR with variable VAR, period T, and boundes BOUND to BOUND+T.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with period of <<MathQuill {ghost: 'T' }>>", "and lower bound <<MathQuill {ghost: '0', default: '0' }>>", ], pre_command: "assume('n', DOM_INT)", command: "fourier_an($1, $2, $3, 'n', $4)" }); createGiacElement({ name: 'fourierb', code: 'fourier coefficient b', function_of: 'n', helpText: '<<fourier b <[EXPR]> for <[VAR]>, period <[T]>, lower bound <[BOUND]>>>\nFinds the expression for the fourier coefficients b<sub>n</sub> for the expression EXPR with variable VAR, period T, and boundes BOUND to BOUND+T.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with period of <<MathQuill {ghost: 'T' }>>", "and lower bound <<MathQuill {ghost: '0', default: '0' }>>", ], pre_command: "assume('n', DOM_INT)", command: "fourier_bn($1, $2, $3, 'n', $4)" }); createGiacElement({ name: 'fourierc', code: 'fourier coefficient c', function_of: 'n', helpText: '<<fourier c <[EXPR]> for <[VAR]>, period <[T]>, lower bound <[BOUND]>>>\nFinds the expression for the fourier coefficients c<sub>n</sub> for the expression EXPR with variable VAR, period T, and boundes BOUND to BOUND+T.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with period of <<MathQuill {ghost: 'T' }>>", "and lower bound <<MathQuill {ghost: '0', default: '0' }>>", ], pre_command: "assume('n', DOM_INT)", command: "fourier_cn($1, $2, $3, 'n', $4)" }); createGiacElement({ name: 'series', code: 'series expansion', helpText: '<<series <[EXPR]> for <[VAR]> around <[VALUE]> of order <[ORDER]> <[TYPE]>>>\nFinds the series expansion of EXPR with variable VAR about point VALUE of order ORDER and direction specified by TYPE.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "around <<MathQuill {ghost: '0', default: '0' }>>", "of order <<MathQuill {ghost: '5', default: '5'}>> <<SelectBox {options: { 0: 'Bidirectional', 1: 'Unidirectional positive', -1: 'Unidirectional negative'}}>>" ], command: "series($1, $2, $3, $4, $5)" }); createGiacElement({ name: 'taylor', code: 'taylor expansion', helpText: '<<taylor <[EXPR]> for <[VAR]> around <[VALUE]> of order <[ORDER]> <[TYPE]>>>\nFinds the taylor expansion of EXPR with variable VAR about point VALUE of order ORDER and direction specified by TYPE.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "around <<MathQuill {ghost: '0', default: '0' }>>", "of order <<MathQuill {ghost: '5', default: '5'}>> <<SelectBox {options: { 0: 'Bidirectional', 1: 'Unidirectional positive', -1: 'Unidirectional negative'}}>>" ], command: "taylor($1, $2, $3, $4, $5)" }); createGiacElement({ name: 'ztrans', code: 'Z transform', function_of: 'z', helpText: '<<z transform <[EXPR]> for <[VAR]>>>\nFinds the Z transform for the expression EXPR with variable VAR. Result will have variable z.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "ztrans($1, $2, 'z')" }); createGiacElement({ name: 'iztrans', code: 'inverse Z transform', function_of: 'x', helpText: '<<inverse Z transform <[EXPR]> for <[VAR]>>>\nFinds the inverse Z transform for the expression EXPR with variable VAR. Result will have variable x.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>" ], command: "invztrans($1, $2, 'x')" }); createGiacElement({ name: 'fmax', code: 'function maximum', helpText: '<<maximum of <[EXPR]> for <[VAR]> between <[START]> and <[END]>>>\nFinds the maximum value of EXPR for variable VAR between START and END. Value returned is the value of VAR at which the maximum occurs.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "between <<MathQuill {ghost: 'start' }>> and <<MathQuill {ghost: 'end' }>>" ], command: "fMax($1, $2=$3..$4)" }); createGiacElement({ name: 'fmin', code: 'function minimum', helpText: '<<minimum of <[EXPR]> for <[VAR]> between <[START]> and <[END]>>>\nFinds the minimum value of EXPR for variable VAR between START and END. Value returned is the value of VAR at which the minimum occurs.', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "between <<MathQuill {ghost: 'start' }>> and <<MathQuill {ghost: 'end' }>>" ], command: "fMin($1, $2=$3..$4)" }); createGiacElement({ name: 'pade', code: 'pade approximant', helpText: '<<pade approximant of <[EXPR]> for <[VAR]> with numerator order <[m]> and denominator order <[m]>>>\nFinds pade approximant of EXPR with variable VAR of order [m/n]', content: [ " of <<MathQuill {ghost: 'expression'}>>", "for <<MathQuill {ghost: 'variable' }>>", "with numerator order <<MathQuill {ghost: 'm' }>>", "and denominator order <<MathQuill {ghost: 'n' }>>" ], command: "pade($1, '$2', $4+2, $3+1)" });
Fir taylor thing again
src/elements/math_output/giac_generic_constructors.js
Fir taylor thing again
<ide><path>rc/elements/math_output/giac_generic_constructors.js <ide> "around <<MathQuill {ghost: '0', default: '0' }>>", <ide> "of order <<MathQuill {ghost: '5', default: '5'}>> <<SelectBox {options: { 0: 'Bidirectional', 1: 'Unidirectional positive', -1: 'Unidirectional negative'}}>>" <ide> ], <del> command: "taylor($1, $2, $3, $4, $5)" <add> command: "taylor($1, $2, $4, $3, $5)" <ide> }); <ide> createGiacElement({ <ide> name: 'ztrans',
Java
mit
72dc06b7eb12027bf09a3249aea0aa4d06ee7691
0
chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster,chipster/chipster
package fi.csc.microarray.client.visualisation.methods.gbrowser.message; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Time; import java.util.LinkedList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import org.apache.log4j.Logger; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import fi.csc.microarray.client.SwingClientApplication; import fi.csc.microarray.client.screen.ScreenBase; import fi.csc.microarray.client.tasks.Task; import fi.csc.microarray.client.tasks.TaskExecutor; /** * Screen for downloading annotations files used by the genome browser. * * @author Taavi Hupponen * */ public class AnnotationsScreen extends ScreenBase implements ActionListener, ListSelectionListener { private static Logger logger = Logger.getLogger(AnnotationsScreen.class); private Dimension BUTTON_SIZE = new Dimension(120, 22); private JFrame frame = new JFrame("Annotations"); private JTextArea detailsTextArea = new JTextArea(); private JScrollPane detailsScroller; private JButton detailsButton; private JButton closeButton; private JLabel operationLabel = new JLabel(" "); private JLabel parametersLabel = new JLabel(" "); private JLabel statusLabel = new JLabel(" "); private JLabel timeLabel = new JLabel(" "); private JLabel infoLabel = new JLabel(" "); private JXTable table; private AnnotationsTableModel tableModel; private TaskExecutor taskExecutor; private List<Task> tasks = new LinkedList<Task>(); private AnnotationManager annotations; private enum Column { GENOME("Genome"), ANNOTATIONS("Annotations"), REFERENCE("Reference sequence"); private String asString; Column(String asString) { this.asString = asString; } public String toString() { return asString; } }; private class AnnotationsTableModel implements TableModel { private LinkedList<TableModelListener> listeners = new LinkedList<TableModelListener>(); public boolean isCellEditable(int row, int column) { return false; } @Override public int getRowCount() { return annotations.getGenomes().size(); } public Object getValueAt(int row, int column) { // Too big or negative row number if (row >= getRowCount() || row < 0) { return null; } Column col = Column.values()[column]; if (col == Column.GENOME) { return annotations.getGenomes().get(row).species + " " + annotations.getGenomes().get(row).version; } else if (col == Column.ANNOTATIONS) { if (annotations.hasLocalAnnotations(annotations.getGenomes().get(row))) { return new LinkModel("local"); } else { return new LinkModel("Download"); } } else if (col == Column.REFERENCE) { return "local"; } else { throw new IllegalArgumentException("illegal column " + column); } } public void addTableModelListener(TableModelListener l) { listeners.add(l); } public Class<?> getColumnClass(int columnIndex) { return getValueAt(0, columnIndex).getClass(); } public int getColumnCount() { return Column.values().length; } public String getColumnName(int columnIndex) { return Column.values()[columnIndex].toString(); } public void removeTableModelListener(TableModelListener l) { listeners.remove(l); } public void notifyListeners() { for (TableModelListener listener : listeners) { TableModelEvent tableModelEvent = new TableModelEvent(this); listener.tableChanged(tableModelEvent); } } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { } } @SuppressWarnings("serial") public AnnotationsScreen(AnnotationManager annotations) { SwingClientApplication.setPlastic3DLookAndFeel(frame); frame.setPreferredSize(new Dimension(640, 480)); frame.setLocationByPlatform(true); this.annotations = annotations; table = this.getTable(); // Blue selection causes lot of visual problems, and there isn't // any meening for the selection table.setSelectionBackground(table.getBackground()); table.setSelectionForeground(table.getForeground()); JScrollPane tableScroller = new JScrollPane(table); closeButton = new JButton("Close"); closeButton.addActionListener(this); closeButton.setPreferredSize(BUTTON_SIZE); detailsScroller = new JScrollPane(detailsTextArea); detailsButton = new JButton("Show Details"); // to make sure that details get enough area detailsScroller.setMinimumSize(new Dimension(0, 200)); detailsScroller.setVisible(false); detailsTextArea.setEditable(false); detailsButton.addActionListener(this); detailsButton.setPreferredSize(BUTTON_SIZE); detailsButton.setEnabled(false); frame.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.NORTHWEST; c.gridx = 0; c.gridy = 0; c.gridwidth = 4; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; frame.add(tableScroller, c); c.gridy++; // c.gridx=3; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 0.0; c.weighty = 0.0; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.LINE_END; c.insets.bottom = 8; c.insets.right = 8; c.insets.top = 8; frame.add(closeButton, c); frame.pack(); } @SuppressWarnings("serial") private JXTable getTable() { if (table == null) { this.tableModel = new AnnotationsTableModel(); this.table = new JXTable(tableModel) { // To make the custom selection colors also after font size // change @Override public void updateUI() { super.updateUI(); setSelectionBackground(getBackground()); setSelectionForeground(getForeground()); } public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) { Component c = super.prepareRenderer(renderer, rowIndex, vColIndex); // Column col = Column.values()[table // .convertColumnIndexToModel(vColIndex)]; rowIndex = table.convertRowIndexToModel(rowIndex); // if (c instanceof JComponent) { // JComponent jc = (JComponent) c; // // Task task = tasks.get(rowIndex); // if (col == Column.TOOL) { // try { // jc.setToolTipText(task.getParameters() // .toString()); // } catch (Exception e) { // } // } else if (col == Column.STATUS) { // String status = task.getState().toString(); // // if (task.getStateDetail() != null // && task.getStateDetail().length() > 0) { // status += " ( " + task.getStateDetail() + " )"; // } else if (tasks.get(rowIndex) // .getCompletionPercentage() != -1) { // status += " ( " // + task.getCompletionPercentage() // + "% )"; // } // jc.setToolTipText(status); // // } else if (col == Column.TIME) { // long longTime = task.getExecutionTime(); // String min = Strings.toString( // (int) (longTime / 1000) / 60, 2); // String sec = Strings.toString( // (int) (longTime / 1000) % 60, 2); // jc.setToolTipText("Execution time: " + min + ":" // + sec); // } // } return c; } }; table.getSelectionModel().addListSelectionListener(this); table.getColumnModel().getSelectionModel() .addListSelectionListener(this); table.getSelectionModel().setSelectionMode( ListSelectionModel.SINGLE_SELECTION); table.setAutoResizeMode(JXTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); table.getColumnModel().getColumn(Column.GENOME.ordinal()) .setPreferredWidth(250); table.getColumnModel().getColumn(Column.ANNOTATIONS.ordinal()) .setPreferredWidth(80); table.getColumnModel().getColumn(Column.REFERENCE.ordinal()) .setPreferredWidth(80); table.setShowVerticalLines(false); LinkModelAction<LinkModel> linkAction = new LinkModelAction<LinkModel>() { public void actionPerformed(ActionEvent e) { logger.debug("Canceling task: " + tasks.get(table.convertRowIndexToModel(table .getSelectedRow()))); taskExecutor.kill(tasks.get(table .convertRowIndexToModel(table.getSelectedRow()))); setVisited(true); } }; table.getColumn(Column.ANNOTATIONS.ordinal()) .setCellRenderer( new DefaultTableRenderer(new HyperlinkProvider( linkAction))); } return table; } private void refreshLabels(Task task) { detailsTextArea.setText(""); if (task == null) { operationLabel.setText(" "); parametersLabel.setText(" "); statusLabel.setText(" "); timeLabel.setText(" "); infoLabel.setText(" "); } else { operationLabel.setText(task.getName()); try { // TODO Task should give the List of Parameter objects instead // of Strings to show also the names of the parameters, like in // DetailsPanel parametersLabel.setText(task.getParameters().toString()); } catch (Exception e) { parametersLabel.setText("?"); } statusLabel.setText(task.getState().toString()); timeLabel.setText((new Time(task.getStartTime())).toString()); infoLabel.setText(task.getStateDetail()); detailsTextArea.setText(task.getScreenOutput()); // button is enabled if there is something to show, hiding details // is always possible detailsButton.setEnabled((task.getScreenOutput() != null && !task .getScreenOutput().equals("")) || detailsScroller.isVisible()); } } /** * This is called when there are changes in the task information (new task, * or status change) by SwingClientApplication. This should make the UI to * show the changes. Running tasks that aren't already in the table are * added there. */ public void refreshTasks() { logger.debug("Refreshing tasks in Task manager"); for (Task task : taskExecutor.getTasks(true, false)) { if (!tasks.contains(task)) { logger.debug("\tNew task added: " + task.getName()); tasks.add(task); } } tableModel.notifyListeners(); logger.debug("Refreshing done"); } public boolean hasFrame() { return frame != null; } public JFrame getFrame() { return frame; } public void actionPerformed(ActionEvent e) { if (e.getSource() == detailsButton) { if (detailsScroller.isVisible()) { detailsScroller.setVisible(false); detailsButton.setText("Show details"); } else { detailsScroller.setVisible(true); detailsButton.setText("Hide details"); } } else if (e.getSource() == closeButton) { frame.dispose(); } } public void valueChanged(ListSelectionEvent e) { if (table.getSelectedRow() >= 0 && table.getSelectedRow() < tasks.size()) { refreshLabels(tasks.get(table.convertRowIndexToModel(table .getSelectedRow()))); } else { refreshLabels(null); } } /** * To be used for additional information in statusbar * * @return number of failed tasks in task manager */ public int getFailedCount() { int i = 0; for (Task task : tasks) { if (task.getState() == Task.State.FAILED || task.getState() == Task.State.TIMEOUT || task.getState() == Task.State.FAILED_USER_ERROR) { i++; } } return i; } }
src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/message/AnnotationsScreen.java
package fi.csc.microarray.client.visualisation.methods.gbrowser.message; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Time; import java.util.LinkedList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import org.apache.log4j.Logger; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import fi.csc.microarray.client.SwingClientApplication; import fi.csc.microarray.client.screen.ScreenBase; import fi.csc.microarray.client.tasks.Task; import fi.csc.microarray.client.tasks.TaskExecutor; /** * @author Petri Klemelä * */ public class AnnotationsScreen extends ScreenBase implements ActionListener, ListSelectionListener { private static Logger logger = Logger.getLogger(AnnotationsScreen.class); private Dimension BUTTON_SIZE = new Dimension(120, 22); private JFrame frame = new JFrame("Annotations"); private JTextArea detailsTextArea = new JTextArea(); private JScrollPane detailsScroller; private JButton detailsButton; private JButton closeButton; private JLabel operationLabel = new JLabel(" "); private JLabel parametersLabel = new JLabel(" "); private JLabel statusLabel = new JLabel(" "); private JLabel timeLabel = new JLabel(" "); private JLabel infoLabel = new JLabel(" "); private JXTable table; private AnnotationsTableModel tableModel; private TaskExecutor taskExecutor; private List<Task> tasks = new LinkedList<Task>(); private AnnotationManager annotations; private enum Column { GENOME("Genome"), ANNOTATIONS("Annotations"), REFERENCE("Reference sequence"); private String asString; Column(String asString) { this.asString = asString; } public String toString() { return asString; } }; private class AnnotationsTableModel implements TableModel { private LinkedList<TableModelListener> listeners = new LinkedList<TableModelListener>(); public boolean isCellEditable(int row, int column) { return false; } @Override public int getRowCount() { return annotations.getGenomes().size(); } public Object getValueAt(int row, int column) { // Too big or negative row number if (row >= getRowCount() || row < 0) { return null; } Column col = Column.values()[column]; if (col == Column.GENOME) { return annotations.getGenomes().get(row).species + " " + annotations.getGenomes().get(row).version; } else if (col == Column.ANNOTATIONS) { if (annotations.hasLocalAnnotations(annotations.getGenomes().get(row))) { return new LinkModel("local"); } else { return new LinkModel("Download"); } } else if (col == Column.REFERENCE) { return "local"; } else { throw new IllegalArgumentException("illegal column " + column); } } public void addTableModelListener(TableModelListener l) { listeners.add(l); } public Class<?> getColumnClass(int columnIndex) { return getValueAt(0, columnIndex).getClass(); } public int getColumnCount() { return Column.values().length; } public String getColumnName(int columnIndex) { return Column.values()[columnIndex].toString(); } public void removeTableModelListener(TableModelListener l) { listeners.remove(l); } public void notifyListeners() { for (TableModelListener listener : listeners) { TableModelEvent tableModelEvent = new TableModelEvent(this); listener.tableChanged(tableModelEvent); } } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { } } @SuppressWarnings("serial") public AnnotationsScreen(AnnotationManager annotations) { SwingClientApplication.setPlastic3DLookAndFeel(frame); frame.setPreferredSize(new Dimension(640, 480)); frame.setLocationByPlatform(true); this.annotations = annotations; table = this.getTable(); // Blue selection causes lot of visual problems, and there isn't // any meening for the selection table.setSelectionBackground(table.getBackground()); table.setSelectionForeground(table.getForeground()); JScrollPane tableScroller = new JScrollPane(table); closeButton = new JButton("Close"); closeButton.addActionListener(this); closeButton.setPreferredSize(BUTTON_SIZE); detailsScroller = new JScrollPane(detailsTextArea); detailsButton = new JButton("Show Details"); // to make sure that details get enough area detailsScroller.setMinimumSize(new Dimension(0, 200)); detailsScroller.setVisible(false); detailsTextArea.setEditable(false); detailsButton.addActionListener(this); detailsButton.setPreferredSize(BUTTON_SIZE); detailsButton.setEnabled(false); frame.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.NORTHWEST; c.gridx = 0; c.gridy = 0; c.gridwidth = 4; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; frame.add(tableScroller, c); c.gridy++; // c.gridx=3; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 0.0; c.weighty = 0.0; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.LINE_END; c.insets.bottom = 8; c.insets.right = 8; c.insets.top = 8; frame.add(closeButton, c); frame.pack(); } @SuppressWarnings("serial") private JXTable getTable() { if (table == null) { this.tableModel = new AnnotationsTableModel(); this.table = new JXTable(tableModel) { // To make the custom selection colors also after font size // change @Override public void updateUI() { super.updateUI(); setSelectionBackground(getBackground()); setSelectionForeground(getForeground()); } public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) { Component c = super.prepareRenderer(renderer, rowIndex, vColIndex); Column col = Column.values()[table .convertColumnIndexToModel(vColIndex)]; rowIndex = table.convertRowIndexToModel(rowIndex); // if (c instanceof JComponent) { // JComponent jc = (JComponent) c; // // Task task = tasks.get(rowIndex); // if (col == Column.TOOL) { // try { // jc.setToolTipText(task.getParameters() // .toString()); // } catch (Exception e) { // } // } else if (col == Column.STATUS) { // String status = task.getState().toString(); // // if (task.getStateDetail() != null // && task.getStateDetail().length() > 0) { // status += " ( " + task.getStateDetail() + " )"; // } else if (tasks.get(rowIndex) // .getCompletionPercentage() != -1) { // status += " ( " // + task.getCompletionPercentage() // + "% )"; // } // jc.setToolTipText(status); // // } else if (col == Column.TIME) { // long longTime = task.getExecutionTime(); // String min = Strings.toString( // (int) (longTime / 1000) / 60, 2); // String sec = Strings.toString( // (int) (longTime / 1000) % 60, 2); // jc.setToolTipText("Execution time: " + min + ":" // + sec); // } // } return c; } }; table.getSelectionModel().addListSelectionListener(this); table.getColumnModel().getSelectionModel() .addListSelectionListener(this); table.getSelectionModel().setSelectionMode( ListSelectionModel.SINGLE_SELECTION); table.setAutoResizeMode(JXTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); table.getColumnModel().getColumn(Column.GENOME.ordinal()) .setPreferredWidth(250); table.getColumnModel().getColumn(Column.ANNOTATIONS.ordinal()) .setPreferredWidth(80); table.getColumnModel().getColumn(Column.REFERENCE.ordinal()) .setPreferredWidth(80); table.setShowVerticalLines(false); LinkModelAction<LinkModel> linkAction = new LinkModelAction<LinkModel>() { public void actionPerformed(ActionEvent e) { logger.debug("Canceling task: " + tasks.get(table.convertRowIndexToModel(table .getSelectedRow()))); taskExecutor.kill(tasks.get(table .convertRowIndexToModel(table.getSelectedRow()))); setVisited(true); } }; table.getColumn(Column.ANNOTATIONS.ordinal()) .setCellRenderer( new DefaultTableRenderer(new HyperlinkProvider( linkAction))); } return table; } private void refreshLabels(Task task) { detailsTextArea.setText(""); if (task == null) { operationLabel.setText(" "); parametersLabel.setText(" "); statusLabel.setText(" "); timeLabel.setText(" "); infoLabel.setText(" "); } else { operationLabel.setText(task.getName()); try { // TODO Task should give the List of Parameter objects instead // of Strings to show also the names of the parameters, like in // DetailsPanel parametersLabel.setText(task.getParameters().toString()); } catch (Exception e) { parametersLabel.setText("?"); } statusLabel.setText(task.getState().toString()); timeLabel.setText((new Time(task.getStartTime())).toString()); infoLabel.setText(task.getStateDetail()); detailsTextArea.setText(task.getScreenOutput()); // button is enabled if there is something to show, hiding details // is always possible detailsButton.setEnabled((task.getScreenOutput() != null && !task .getScreenOutput().equals("")) || detailsScroller.isVisible()); } } /** * This is called when there are changes in the task information (new task, * or status change) by SwingClientApplication. This should make the UI to * show the changes. Running tasks that aren't already in the table are * added there. */ public void refreshTasks() { logger.debug("Refreshing tasks in Task manager"); for (Task task : taskExecutor.getTasks(true, false)) { if (!tasks.contains(task)) { logger.debug("\tNew task added: " + task.getName()); tasks.add(task); } } tableModel.notifyListeners(); logger.debug("Refreshing done"); } public boolean hasFrame() { return frame != null; } public JFrame getFrame() { return frame; } public void actionPerformed(ActionEvent e) { if (e.getSource() == detailsButton) { if (detailsScroller.isVisible()) { detailsScroller.setVisible(false); detailsButton.setText("Show details"); } else { detailsScroller.setVisible(true); detailsButton.setText("Hide details"); } } else if (e.getSource() == closeButton) { frame.dispose(); } } public void valueChanged(ListSelectionEvent e) { if (table.getSelectedRow() >= 0 && table.getSelectedRow() < tasks.size()) { refreshLabels(tasks.get(table.convertRowIndexToModel(table .getSelectedRow()))); } else { refreshLabels(null); } } /** * To be used for additional information in statusbar * * @return number of failed tasks in task manager */ public int getFailedCount() { int i = 0; for (Task task : tasks) { if (task.getState() == Task.State.FAILED || task.getState() == Task.State.TIMEOUT || task.getState() == Task.State.FAILED_USER_ERROR) { i++; } } return i; } }
cleaned code
src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/message/AnnotationsScreen.java
cleaned code
<ide><path>rc/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/message/AnnotationsScreen.java <ide> import fi.csc.microarray.client.tasks.TaskExecutor; <ide> <ide> /** <del> * @author Petri Klemelä <add> * Screen for downloading annotations files used by the genome browser. <add> * <add> * @author Taavi Hupponen <ide> * <ide> */ <ide> public class AnnotationsScreen extends ScreenBase implements ActionListener, <ide> Component c = super.prepareRenderer(renderer, rowIndex, <ide> vColIndex); <ide> <del> Column col = Column.values()[table <del> .convertColumnIndexToModel(vColIndex)]; <add>// Column col = Column.values()[table <add>// .convertColumnIndexToModel(vColIndex)]; <ide> <ide> rowIndex = table.convertRowIndexToModel(rowIndex); <ide>
JavaScript
mit
f8cc6c288163f435e3a832bb580f232c37150c9d
0
svivian/Pokemon-Showdown,xfix/Pokemon-Showdown,AustinXII/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,urkerab/Pokemon-Showdown,Zarel/Pokemon-Showdown,xfix/Pokemon-Showdown,AustinXII/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,svivian/Pokemon-Showdown,svivian/Pokemon-Showdown,Zarel/Pokemon-Showdown,xfix/Pokemon-Showdown,svivian/Pokemon-Showdown,svivian/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,AustinXII/Pokemon-Showdown,Enigami/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,Enigami/Pokemon-Showdown,Enigami/Pokemon-Showdown,panpawn/Gold-Server,xfix/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,panpawn/Gold-Server,xfix/Pokemon-Showdown,panpawn/Gold-Server,urkerab/Pokemon-Showdown,Enigami/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,urkerab/Pokemon-Showdown,Zarel/Pokemon-Showdown
/** * Matchmaker * Pokemon Showdown - http://pokemonshowdown.com/ * * This keeps track of challenges to battle made between users, setting up * matches between users looking for a battle, and starting new battles. * * @License MIT License */ 'use strict'; /** @type {typeof LadderStoreT} */ const LadderStore = require(typeof Config === 'object' && Config.remoteladder ? './ladders-remote' : './ladders-local'); const SECONDS = 1000; const PERIODIC_MATCH_INTERVAL = 60 * SECONDS; /** * This represents a user's search for a battle under a format. */ class BattleReady { /** * @param {string} userid * @param {string} formatid * @param {string} team * @param {number} [rating = 1000] */ constructor(userid, formatid, team, rating = 0) { /** @type {string} */ this.userid = userid; /** @type {string} */ this.formatid = formatid; /** @type {string} */ this.team = team; /** @type {number} */ this.rating = rating; /** @type {number} */ this.time = Date.now(); } } /** * formatid:userid:BattleReady * @type {Map<string, Map<string, BattleReady>>} */ const searches = new Map(); class Challenge { /** * @param {BattleReady} ready * @param {string} to */ constructor(ready, to) { this.from = ready.userid; this.to = to; this.formatid = ready.formatid; this.ready = ready; } } /** * formatid:userid:BattleReady * @type {Map<string, Challenge[]>} */ const challenges = new Map(); /** * This keeps track of searches for battles, creating a new battle for a newly * added search if a valid match can be made, otherwise periodically * attempting to make a match with looser restrictions until one can be made. */ class Ladder extends LadderStore { /** * @param {string} formatid */ constructor(formatid) { super(formatid); } /** * @param {Connection} connection * @param {string?} team * @return {Promise<BattleReady?>} */ async prepBattle(connection, team = null, isRated = false) { // all validation for a battle goes through here const user = connection.user; const userid = user.userid; if (team === null) team = user.team; if (Rooms.global.lockdown && Rooms.global.lockdown !== 'pre') { let message = `The server is restarting. Battles will be available again in a few minutes.`; if (Rooms.global.lockdown === 'ddos') { message = `The server is under attack. Battles cannot be started at this time.`; } connection.popup(message); return null; } if (Punishments.isBattleBanned(user)) { connection.popup(`You are barred from starting any new games until your battle ban expires.`); return null; } let gameCount = user.games.size; if (Monitor.countConcurrentBattle(gameCount, connection)) { return null; } if (Monitor.countPrepBattle(connection.ip, connection)) { return null; } try { // @ts-ignore TypeScript bug: self-reference this.formatid = Dex.validateFormat(this.formatid); } catch (e) { connection.popup(`Your selected format is invalid:\n\n- ${e.message}`); return null; } const regex = /(?:^|])([^|]*)\|/g; let match = regex.exec(team); while (match) { let nickname = match[1]; if (nickname) { nickname = Chat.nicknamefilter(nickname, user); if (!nickname || nickname !== match[1]) { connection.popup( `Your team was rejected for the following reason:\n\n` + `- Your Pokémon has a banned nickname: ${match[1]}` ); return null; } } match = regex.exec(team); } let rating = 0, valResult; if (isRated && !Ladders.disabled) { let userid = user.userid; [valResult, rating] = await Promise.all([ TeamValidatorAsync(this.formatid).validateTeam(team, !!(user.locked || user.namelocked)), this.getRating(userid), ]); if (userid !== user.userid) { // User feedback for renames handled elsewhere. return null; } if (!rating) rating = 1; } else { if (Ladders.disabled) { connection.popup(`The ladder is temporarily disabled due to technical difficulties - you will not receive ladder rating for this game.`); rating = 1; } valResult = await TeamValidatorAsync(this.formatid).validateTeam(team, !!(user.locked || user.namelocked)); } if (valResult.charAt(0) !== '1') { connection.popup( `Your team was rejected for the following reasons:\n\n` + `- ` + valResult.slice(1).replace(/\n/g, `\n- `) ); return null; } return new BattleReady(userid, this.formatid, valResult.slice(1), rating); } /** * @param {User} user */ static cancelChallenging(user) { const chall = Ladder.getChallenging(user.userid); if (chall) { Ladder.removeChallenge(chall); return true; } return false; } /** * @param {User} user * @param {User} targetUsername */ static rejectChallenge(user, targetUsername) { const targetUserid = toId(targetUsername); const chall = Ladder.getChallenging(targetUserid); if (chall && chall.to === user.userid) { Ladder.removeChallenge(chall); return true; } return false; } /** * @param {string} username */ static clearChallenges(username) { const userid = toId(username); const userChalls = Ladders.challenges.get(userid); if (userChalls) { for (const chall of userChalls.slice()) { let otherUserid; if (chall.from === userid) { otherUserid = chall.to; } else { otherUserid = chall.from; } Ladder.removeChallenge(chall, true); const otherUser = Users(otherUserid); if (otherUser) Ladder.updateChallenges(otherUser); } const user = Users(userid); if (user) Ladder.updateChallenges(user); return true; } return false; } /** * @param {Connection} connection * @param {User} targetUser */ async makeChallenge(connection, targetUser) { const user = connection.user; if (targetUser === user) { connection.popup(`You can't battle yourself. The best you can do is open PS in Private Browsing (or another browser) and log into a different username, and battle that username.`); return false; } if (Ladder.getChallenging(user.userid)) { connection.popup(`You are already challenging someone. Cancel that challenge before challenging someone else.`); return false; } if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) { connection.popup(`The user '${targetUser.name}' is not accepting challenges right now.`); return false; } if (Date.now() < user.lastChallenge + 10 * SECONDS) { // 10 seconds ago, probable misclick connection.popup(`You challenged less than 10 seconds after your last challenge! It's cancelled in case it's a misclick.`); return false; } const ready = await this.prepBattle(connection); if (!ready) return false; Ladder.addChallenge(new Challenge(ready, targetUser.userid)); user.lastChallenge = Date.now(); return true; } /** * @param {Connection} connection * @param {User} targetUser */ static async acceptChallenge(connection, targetUser) { const chall = Ladder.getChallenging(targetUser.userid); if (!chall || chall.to !== connection.user.userid) { connection.popup(`${targetUser.userid} is not challenging you. Maybe they cancelled before you accepted?`); return false; } const ladder = Ladders(chall.formatid); const ready = await ladder.prepBattle(connection); if (!ready) return false; if (Ladder.removeChallenge(chall)) { Ladders.match(chall.ready, ready); } return true; } /** * @param {string} userid */ static getChallenging(userid) { const userChalls = Ladders.challenges.get(userid); if (userChalls) { for (const chall of userChalls) { if (chall.from === userid) return chall; } } return null; } /** * @param {Challenge} challenge */ static addChallenge(challenge, skipUpdate = false) { let challs1 = Ladders.challenges.get(challenge.from); if (!challs1) Ladders.challenges.set(challenge.from, challs1 = []); let challs2 = Ladders.challenges.get(challenge.to); if (!challs2) Ladders.challenges.set(challenge.to, challs2 = []); challs1.push(challenge); challs2.push(challenge); if (!skipUpdate) { const fromUser = Users(challenge.from); if (fromUser) Ladder.updateChallenges(fromUser); const toUser = Users(challenge.to); if (toUser) Ladder.updateChallenges(toUser); } } /** * @param {Challenge} challenge */ static removeChallenge(challenge, skipUpdate = false) { const fromChalls = /** @type {Challenge[]} */ (Ladders.challenges.get(challenge.from)); // the challenge may have been cancelled if (!fromChalls) return false; const fromIndex = fromChalls.indexOf(challenge); if (fromIndex < 0) return false; fromChalls.splice(fromIndex, 1); if (!fromChalls.length) Ladders.challenges.delete(challenge.from); const toChalls = /** @type {Challenge[]} */ (Ladders.challenges.get(challenge.to)); toChalls.splice(toChalls.indexOf(challenge), 1); if (!toChalls.length) Ladders.challenges.delete(challenge.to); if (!skipUpdate) { const fromUser = Users(challenge.from); if (fromUser) Ladder.updateChallenges(fromUser); const toUser = Users(challenge.to); if (toUser) Ladder.updateChallenges(toUser); } return true; } /** * @param {User} user * @param {Connection?} connection */ static updateChallenges(user, connection = null) { if (!user.connected) return; let challengeTo = null; /**@type {{[k: string]: string}} */ let challengesFrom = {}; const userChalls = Ladders.challenges.get(user.userid); if (userChalls) { for (const chall of userChalls) { if (chall.from === user.userid) { challengeTo = { to: chall.to, format: chall.formatid, }; } else { challengesFrom[chall.from] = chall.formatid; } } } (connection || user).send(`|updatechallenges|` + JSON.stringify({ challengesFrom: challengesFrom, challengeTo: challengeTo, })); } /** * @param {User} user * @return {boolean} */ cancelSearch(user) { const formatid = toId(this.formatid); const formatTable = Ladders.searches.get(formatid); if (!formatTable) return false; if (!formatTable.has(user.userid)) return false; formatTable.delete(user.userid); Ladder.updateSearch(user); return true; } /** * @param {User} user * @return {number} cancel count */ static cancelSearches(user) { let cancelCount = 0; for (let formatTable of Ladders.searches.values()) { const search = formatTable.get(user.userid); if (!search) continue; formatTable.delete(user.userid); cancelCount++; } Ladder.updateSearch(user); return cancelCount; } /** * @param {BattleReady} search */ getSearcher(search) { const formatid = toId(this.formatid); const user = Users.get(search.userid); if (!user || !user.connected || user.userid !== search.userid) { const formatTable = Ladders.searches.get(formatid); if (formatTable) formatTable.delete(search.userid); if (user && user.connected) { user.popup(`You changed your name and are no longer looking for a battle in ${formatid}`); Ladder.updateSearch(user); } return null; } return user; } /** * @param {User} user */ static getSearches(user) { let userSearches = []; for (const [formatid, formatTable] of Ladders.searches) { if (formatTable.has(user.userid)) userSearches.push(formatid); } return userSearches; } /** * @param {User} user * @param {Connection?} connection */ static updateSearch(user, connection = null) { let games = /** @type {any} */ ({}); let atLeastOne = false; for (const roomid of user.games) { const room = Rooms(roomid); if (!room) { Monitor.warn(`while searching, room ${roomid} expired for user ${user.userid} in rooms ${[...user.inRooms]} and games ${[...user.games]}`); user.games.delete(roomid); return; } const game = room.game; if (!game) { Monitor.warn(`while searching, room ${roomid} has no game for user ${user.userid} in rooms ${[...user.inRooms]} and games ${[...user.games]}`); user.games.delete(roomid); return; } games[roomid] = game.title + (game.allowRenames ? '' : '*'); atLeastOne = true; } if (!atLeastOne) games = null; let searching = Ladders.getSearches(user); (connection || user).send(`|updatesearch|` + JSON.stringify({ searching: searching, games: games, })); } /** * @param {User} user */ hasSearch(user) { const formatid = toId(this.formatid); const formatTable = Ladders.searches.get(formatid); if (!formatTable) return false; return formatTable.has(user.userid); } /** * Validates a user's team and fetches their rating for a given format * before creating a search for a battle. * @param {User} user * @param {Connection} connection * @return {Promise<void>} */ async searchBattle(user, connection) { if (!user.connected) return; const format = Dex.getFormat(this.formatid); if (!format.searchShow) { connection.popup(`Error: Your format ${format.id} is not ladderable.`); return; } const roomid = this.needsToMove(user); if (roomid) { connection.popup(`Error: You need to make a move in <<${roomid}>> before you can look for another battle.\n\n(This restriction doesn't apply in the first five turns of a battle.)`); return; } if (roomid === null && Date.now() < user.lastDecision + 10 * SECONDS) { connection.popup(`Error: You need to wait 7 seconds after making a move before you can look for another battle.\n\n(This restriction doesn't apply in the first five turns of a battle.)`); return; } let oldUserid = user.userid; const search = await this.prepBattle(connection, null, format.rated !== false); if (oldUserid !== user.userid) return; if (!search) return; this.addSearch(search, user); } /** * null = all battles ok * undefined = not in any battle * @param {User} user */ needsToMove(user) { let out = undefined; for (const roomid of user.games) { const room = Rooms(roomid); if (!room || !room.battle || !room.battle.players[user.userid]) continue; const battle = /** @type {RoomBattle} */ (room.battle); if (battle.requestCount < 6) { // it's fine as long as it's before turn 5 continue; } if (Dex.getFormat(battle.format).allowMultisearch) { continue; } const player = battle.players[user.userid]; if (!battle.requests[player.slot].isWait) return roomid; out = null; } return out; } /** * Verifies whether or not a match made between two users is valid. Returns * @param {BattleReady} search1 * @param {BattleReady} search2 * @param {User=} user1 * @param {User=} user2 * @return {boolean} */ matchmakingOK(search1, search2, user1, user2) { const formatid = toId(this.formatid); if (!user1 || !user2) { // This should never happen. Monitor.crashlog(new Error(`Matched user ${user1 ? search2.userid : search1.userid} not found`), "The matchmaker"); return false; } // users must be different if (user1 === user2) return false; if (Config.fakeladder) { user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; } // users must have different IPs if (user1.latestIp === user2.latestIp) return false; // users must not have been matched immediately previously if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false; // search must be within range let searchRange = 100; let elapsed = Date.now() - Math.min(search1.time, search2.time); if (formatid === 'gen7ou' || formatid === 'gen7oucurrent' || formatid === 'gen7oususpecttest' || formatid === 'gen7randombattle') { searchRange = 50; } searchRange += elapsed / 300; // +1 every .3 seconds if (searchRange > 300) searchRange = 300 + (searchRange - 300) / 10; // +1 every 3 sec after 300 if (searchRange > 600) searchRange = 600; if (Math.abs(search1.rating - search2.rating) > searchRange) return false; user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; } /** * Starts a search for a battle for a user under the given format. * @param {BattleReady} newSearch * @param {User} user */ addSearch(newSearch, user) { const formatid = newSearch.formatid; let formatTable = Ladders.searches.get(formatid); if (!formatTable) { formatTable = new Map(); Ladders.searches.set(formatid, formatTable); } if (formatTable.has(user.userid)) { user.popup(`Couldn't search: You are already searching for a ${formatid} battle.`); return; } // In order from longest waiting to shortest waiting for (let search of formatTable.values()) { const searcher = this.getSearcher(search); if (!searcher) continue; const matched = this.matchmakingOK(search, newSearch, searcher, user); if (matched) { formatTable.delete(search.userid); Ladder.match(search, newSearch); return; } } formatTable.set(newSearch.userid, newSearch); Ladder.updateSearch(user); } /** * Creates a match for a new battle for each format in this.searches if a * valid match can be made. This is run periodically depending on * PERIODIC_MATCH_INTERVAL. */ static periodicMatch() { // In order from longest waiting to shortest waiting for (const [formatid, formatTable] of Ladders.searches) { const matchmaker = Ladders(formatid); let longest = /** @type {[BattleReady, User]?} */ (null); for (let search of formatTable.values()) { if (!longest) { const longestSearcher = matchmaker.getSearcher(search); if (!longestSearcher) continue; longest = [search, longestSearcher]; continue; } let searcher = matchmaker.getSearcher(search); if (!searcher) continue; let [longestSearch, longestSearcher] = longest; let matched = matchmaker.matchmakingOK(search, longestSearch, searcher, longestSearcher); if (matched) { formatTable.delete(search.userid); formatTable.delete(longestSearch.userid); Ladder.match(longestSearch, search); return; } } } } /** * @param {BattleReady} ready1 * @param {BattleReady} ready2 */ static match(ready1, ready2) { if (ready1.formatid !== ready2.formatid) throw new Error(`Format IDs don't match`); const user1 = Users(ready1.userid); const user2 = Users(ready2.userid); if (!user1) { if (!user2) return false; user2.popup(`Sorry, your opponent ${ready1.userid} went offline before your battle could start.`); return false; } if (!user2) { user1.popup(`Sorry, your opponent ${ready2.userid} went offline before your battle could start.`); return false; } Rooms.createBattle(ready1.formatid, { p1: user1, p1team: ready1.team, p2: user2, p2team: ready2.team, rated: Math.min(ready1.rating, ready2.rating), }); } } /** * @param {string} formatid */ function getLadder(formatid) { return new Ladder(formatid); } /** @type {?NodeJS.Timer} */ let periodicMatchInterval = setInterval( () => Ladder.periodicMatch(), PERIODIC_MATCH_INTERVAL ); const Ladders = Object.assign(getLadder, { BattleReady, LadderStore, Ladder, cancelSearches: Ladder.cancelSearches, updateSearch: Ladder.updateSearch, rejectChallenge: Ladder.rejectChallenge, acceptChallenge: Ladder.acceptChallenge, cancelChallenging: Ladder.cancelChallenging, clearChallenges: Ladder.clearChallenges, updateChallenges: Ladder.updateChallenges, visualizeAll: Ladder.visualizeAll, getSearches: Ladder.getSearches, match: Ladder.match, searches, challenges, periodicMatchInterval, // tells the client to ask the server for format information formatsListPrefix: LadderStore.formatsListPrefix, /** @type {true | false | 'db'} */ disabled: false, }); module.exports = Ladders;
server/ladders.js
/** * Matchmaker * Pokemon Showdown - http://pokemonshowdown.com/ * * This keeps track of challenges to battle made between users, setting up * matches between users looking for a battle, and starting new battles. * * @License MIT License */ 'use strict'; /** @type {typeof LadderStoreT} */ const LadderStore = require(typeof Config === 'object' && Config.remoteladder ? './ladders-remote' : './ladders-local'); const SECONDS = 1000; const PERIODIC_MATCH_INTERVAL = 60 * SECONDS; /** * This represents a user's search for a battle under a format. */ class BattleReady { /** * @param {string} userid * @param {string} formatid * @param {string} team * @param {number} [rating = 1000] */ constructor(userid, formatid, team, rating = 0) { /** @type {string} */ this.userid = userid; /** @type {string} */ this.formatid = formatid; /** @type {string} */ this.team = team; /** @type {number} */ this.rating = rating; /** @type {number} */ this.time = Date.now(); } } /** * formatid:userid:BattleReady * @type {Map<string, Map<string, BattleReady>>} */ const searches = new Map(); class Challenge { /** * @param {BattleReady} ready * @param {string} to */ constructor(ready, to) { this.from = ready.userid; this.to = to; this.formatid = ready.formatid; this.ready = ready; } } /** * formatid:userid:BattleReady * @type {Map<string, Challenge[]>} */ const challenges = new Map(); /** * This keeps track of searches for battles, creating a new battle for a newly * added search if a valid match can be made, otherwise periodically * attempting to make a match with looser restrictions until one can be made. */ class Ladder extends LadderStore { /** * @param {string} formatid */ constructor(formatid) { super(formatid); } /** * @param {Connection} connection * @param {string?} team * @return {Promise<BattleReady?>} */ async prepBattle(connection, team = null, isRated = false) { // all validation for a battle goes through here const user = connection.user; const userid = user.userid; if (team === null) team = user.team; if (Rooms.global.lockdown && Rooms.global.lockdown !== 'pre') { let message = `The server is restarting. Battles will be available again in a few minutes.`; if (Rooms.global.lockdown === 'ddos') { message = `The server is under attack. Battles cannot be started at this time.`; } connection.popup(message); return null; } if (Punishments.isBattleBanned(user)) { connection.popup(`You are barred from starting any new games until your battle ban expires.`); return null; } let gameCount = user.games.size; if (Monitor.countConcurrentBattle(gameCount, connection)) { return null; } if (Monitor.countPrepBattle(connection.ip, connection)) { return null; } try { // @ts-ignore TypeScript bug: self-reference this.formatid = Dex.validateFormat(this.formatid); } catch (e) { connection.popup(`Your selected format is invalid:\n\n- ${e.message}`); return null; } const regex = /(?:^|])([^|]*)\|/g; let match = regex.exec(team); while (match) { let nickname = match[1]; if (nickname) { nickname = Chat.nicknamefilter(nickname, user); if (!nickname || nickname !== match[1]) { connection.popup( `Your team was rejected for the following reason:\n\n` + `- Your Pokémon has a banned nickname: ${match[1]}` ); return null; } } match = regex.exec(team); } let rating = 0, valResult; if (isRated && !Ladders.disabled) { let userid = user.userid; [valResult, rating] = await Promise.all([ TeamValidatorAsync(this.formatid).validateTeam(team, !!(user.locked || user.namelocked)), this.getRating(userid), ]); if (userid !== user.userid) { // User feedback for renames handled elsewhere. return null; } if (!rating) rating = 1; } else { if (Ladders.disabled) { connection.popup(`The ladder is temporarily disabled due to technical difficulties - you will not receive ladder rating for this game.`); rating = 1; } valResult = await TeamValidatorAsync(this.formatid).validateTeam(team, !!(user.locked || user.namelocked)); } if (valResult.charAt(0) !== '1') { connection.popup( `Your team was rejected for the following reasons:\n\n` + `- ` + valResult.slice(1).replace(/\n/g, `\n- `) ); return null; } return new BattleReady(userid, this.formatid, valResult.slice(1), rating); } /** * @param {User} user */ static cancelChallenging(user) { const chall = Ladder.getChallenging(user.userid); if (chall) { Ladder.removeChallenge(chall); return true; } return false; } /** * @param {User} user * @param {User} targetUsername */ static rejectChallenge(user, targetUsername) { const targetUserid = toId(targetUsername); const chall = Ladder.getChallenging(targetUserid); if (chall && chall.to === user.userid) { Ladder.removeChallenge(chall); return true; } return false; } /** * @param {string} username */ static clearChallenges(username) { const userid = toId(username); const userChalls = Ladders.challenges.get(userid); if (userChalls) { for (const chall of userChalls.slice()) { let otherUserid; if (chall.from === userid) { otherUserid = chall.to; } else { otherUserid = chall.from; } Ladder.removeChallenge(chall, true); const otherUser = Users(otherUserid); if (otherUser) Ladder.updateChallenges(otherUser); } const user = Users(userid); if (user) Ladder.updateChallenges(user); return true; } return false; } /** * @param {Connection} connection * @param {User} targetUser */ async makeChallenge(connection, targetUser) { const user = connection.user; if (targetUser === user) { connection.popup(`You can't battle yourself. The best you can do is open PS in Private Browsing (or another browser) and log into a different username, and battle that username.`); return false; } if (Ladder.getChallenging(user.userid)) { connection.popup(`You are already challenging someone. Cancel that challenge before challenging someone else.`); return false; } if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) { connection.popup(`The user '${targetUser.name}' is not accepting challenges right now.`); return false; } if (Date.now() < user.lastChallenge + 10 * SECONDS) { // 10 seconds ago, probable misclick connection.popup(`You challenged less than 10 seconds after your last challenge! It's cancelled in case it's a misclick.`); return false; } const ready = await this.prepBattle(connection); if (!ready) return false; Ladder.addChallenge(new Challenge(ready, targetUser.userid)); user.lastChallenge = Date.now(); return true; } /** * @param {Connection} connection * @param {User} targetUser */ static async acceptChallenge(connection, targetUser) { const chall = Ladder.getChallenging(targetUser.userid); if (!chall || chall.to !== connection.user.userid) { connection.popup(`${targetUser.userid} is not challenging you. Maybe they cancelled before you accepted?`); return false; } const ladder = Ladders(chall.formatid); const ready = await ladder.prepBattle(connection); if (!ready) return false; if (Ladder.removeChallenge(chall)) { Ladders.match(chall.ready, ready); } return true; } /** * @param {string} userid */ static getChallenging(userid) { const userChalls = Ladders.challenges.get(userid); if (userChalls) { for (const chall of userChalls) { if (chall.from === userid) return chall; } } return null; } /** * @param {Challenge} challenge */ static addChallenge(challenge, skipUpdate = false) { let challs1 = Ladders.challenges.get(challenge.from); if (!challs1) Ladders.challenges.set(challenge.from, challs1 = []); let challs2 = Ladders.challenges.get(challenge.to); if (!challs2) Ladders.challenges.set(challenge.to, challs2 = []); challs1.push(challenge); challs2.push(challenge); if (!skipUpdate) { const fromUser = Users(challenge.from); if (fromUser) Ladder.updateChallenges(fromUser); const toUser = Users(challenge.to); if (toUser) Ladder.updateChallenges(toUser); } } /** * @param {Challenge} challenge */ static removeChallenge(challenge, skipUpdate = false) { const fromChalls = /** @type {Challenge[]} */ (Ladders.challenges.get(challenge.from)); // the challenge may have been cancelled if (!fromChalls) return false; const fromIndex = fromChalls.indexOf(challenge); if (fromIndex < 0) return false; fromChalls.splice(fromIndex, 1); if (!fromChalls.length) Ladders.challenges.delete(challenge.from); const toChalls = /** @type {Challenge[]} */ (Ladders.challenges.get(challenge.to)); toChalls.splice(toChalls.indexOf(challenge), 1); if (!toChalls.length) Ladders.challenges.delete(challenge.to); if (!skipUpdate) { const fromUser = Users(challenge.from); if (fromUser) Ladder.updateChallenges(fromUser); const toUser = Users(challenge.to); if (toUser) Ladder.updateChallenges(toUser); } return true; } /** * @param {User} user * @param {Connection?} connection */ static updateChallenges(user, connection = null) { if (!user.connected) return; let challengeTo = null; /**@type {{[k: string]: string}} */ let challengesFrom = {}; const userChalls = Ladders.challenges.get(user.userid); if (userChalls) { for (const chall of userChalls) { if (chall.from === user.userid) { challengeTo = { to: chall.to, format: chall.formatid, }; } else { challengesFrom[chall.from] = chall.formatid; } } } (connection || user).send(`|updatechallenges|` + JSON.stringify({ challengesFrom: challengesFrom, challengeTo: challengeTo, })); } /** * @param {User} user * @return {boolean} */ cancelSearch(user) { const formatid = toId(this.formatid); const formatTable = Ladders.searches.get(formatid); if (!formatTable) return false; if (!formatTable.has(user.userid)) return false; formatTable.delete(user.userid); Ladder.updateSearch(user); return true; } /** * @param {User} user * @return {number} cancel count */ static cancelSearches(user) { let cancelCount = 0; for (let formatTable of Ladders.searches.values()) { const search = formatTable.get(user.userid); if (!search) continue; formatTable.delete(user.userid); cancelCount++; } Ladder.updateSearch(user); return cancelCount; } /** * @param {BattleReady} search */ getSearcher(search) { const formatid = toId(this.formatid); const user = Users.get(search.userid); if (!user || !user.connected || user.userid !== search.userid) { const formatTable = Ladders.searches.get(formatid); if (formatTable) formatTable.delete(search.userid); if (user && user.connected) { user.popup(`You changed your name and are no longer looking for a battle in ${formatid}`); Ladder.updateSearch(user); } return null; } return user; } /** * @param {User} user */ static getSearches(user) { let userSearches = []; for (const [formatid, formatTable] of Ladders.searches) { if (formatTable.has(user.userid)) userSearches.push(formatid); } return userSearches; } /** * @param {User} user * @param {Connection?} connection */ static updateSearch(user, connection = null) { let games = /** @type {any} */ ({}); let atLeastOne = false; for (const roomid of user.games) { const room = Rooms(roomid); if (!room) { Monitor.warn(`while searching, room ${roomid} expired for user ${user.userid} in rooms ${[...user.inRooms]} and games ${[...user.games]}`); user.games.delete(roomid); return; } const game = room.game; if (!game) { Monitor.warn(`while searching, room ${roomid} has no game for user ${user.userid} in rooms ${[...user.inRooms]} and games ${[...user.games]}`); user.games.delete(roomid); return; } games[roomid] = game.title + (game.allowRenames ? '' : '*'); atLeastOne = true; } if (!atLeastOne) games = null; let searching = Ladders.getSearches(user); (connection || user).send(`|updatesearch|` + JSON.stringify({ searching: searching, games: games, })); } /** * @param {User} user */ hasSearch(user) { const formatid = toId(this.formatid); const formatTable = Ladders.searches.get(formatid); if (!formatTable) return false; return formatTable.has(user.userid); } /** * Validates a user's team and fetches their rating for a given format * before creating a search for a battle. * @param {User} user * @param {Connection} connection * @return {Promise<void>} */ async searchBattle(user, connection) { if (!user.connected) return; const format = Dex.getFormat(this.formatid); if (!format.searchShow) { connection.popup(`Error: Your format ${format.id} is not ladderable.`); return; } const roomid = this.needsToMove(user); if (roomid) { connection.popup(`Error: You need to make a move in <<${roomid}>> before you can look for another battle.`); return; } if (roomid === null && Date.now() < user.lastDecision + 10 * SECONDS) { connection.popup(`Error: You need to wait 7 seconds after making a move before you can look for another battle.`); return; } let oldUserid = user.userid; const search = await this.prepBattle(connection, null, format.rated !== false); if (oldUserid !== user.userid) return; if (!search) return; this.addSearch(search, user); } /** * null = all battles ok * undefined = not in any battle * @param {User} user */ needsToMove(user) { let out = undefined; for (const roomid of user.games) { const room = Rooms(roomid); if (!room || !room.battle || !room.battle.players[user.userid]) continue; const battle = /** @type {RoomBattle} */ (room.battle); if (battle.requestCount < 6) { // it's fine as long as it's before turn 5 continue; } if (Dex.getFormat(battle.format).allowMultisearch) { continue; } const player = battle.players[user.userid]; if (!battle.requests[player.slot].isWait) return roomid; out = null; } return out; } /** * Verifies whether or not a match made between two users is valid. Returns * @param {BattleReady} search1 * @param {BattleReady} search2 * @param {User=} user1 * @param {User=} user2 * @return {boolean} */ matchmakingOK(search1, search2, user1, user2) { const formatid = toId(this.formatid); if (!user1 || !user2) { // This should never happen. Monitor.crashlog(new Error(`Matched user ${user1 ? search2.userid : search1.userid} not found`), "The matchmaker"); return false; } // users must be different if (user1 === user2) return false; if (Config.fakeladder) { user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; } // users must have different IPs if (user1.latestIp === user2.latestIp) return false; // users must not have been matched immediately previously if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false; // search must be within range let searchRange = 100; let elapsed = Date.now() - Math.min(search1.time, search2.time); if (formatid === 'gen7ou' || formatid === 'gen7oucurrent' || formatid === 'gen7oususpecttest' || formatid === 'gen7randombattle') { searchRange = 50; } searchRange += elapsed / 300; // +1 every .3 seconds if (searchRange > 300) searchRange = 300 + (searchRange - 300) / 10; // +1 every 3 sec after 300 if (searchRange > 600) searchRange = 600; if (Math.abs(search1.rating - search2.rating) > searchRange) return false; user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; } /** * Starts a search for a battle for a user under the given format. * @param {BattleReady} newSearch * @param {User} user */ addSearch(newSearch, user) { const formatid = newSearch.formatid; let formatTable = Ladders.searches.get(formatid); if (!formatTable) { formatTable = new Map(); Ladders.searches.set(formatid, formatTable); } if (formatTable.has(user.userid)) { user.popup(`Couldn't search: You are already searching for a ${formatid} battle.`); return; } // In order from longest waiting to shortest waiting for (let search of formatTable.values()) { const searcher = this.getSearcher(search); if (!searcher) continue; const matched = this.matchmakingOK(search, newSearch, searcher, user); if (matched) { formatTable.delete(search.userid); Ladder.match(search, newSearch); return; } } formatTable.set(newSearch.userid, newSearch); Ladder.updateSearch(user); } /** * Creates a match for a new battle for each format in this.searches if a * valid match can be made. This is run periodically depending on * PERIODIC_MATCH_INTERVAL. */ static periodicMatch() { // In order from longest waiting to shortest waiting for (const [formatid, formatTable] of Ladders.searches) { const matchmaker = Ladders(formatid); let longest = /** @type {[BattleReady, User]?} */ (null); for (let search of formatTable.values()) { if (!longest) { const longestSearcher = matchmaker.getSearcher(search); if (!longestSearcher) continue; longest = [search, longestSearcher]; continue; } let searcher = matchmaker.getSearcher(search); if (!searcher) continue; let [longestSearch, longestSearcher] = longest; let matched = matchmaker.matchmakingOK(search, longestSearch, searcher, longestSearcher); if (matched) { formatTable.delete(search.userid); formatTable.delete(longestSearch.userid); Ladder.match(longestSearch, search); return; } } } } /** * @param {BattleReady} ready1 * @param {BattleReady} ready2 */ static match(ready1, ready2) { if (ready1.formatid !== ready2.formatid) throw new Error(`Format IDs don't match`); const user1 = Users(ready1.userid); const user2 = Users(ready2.userid); if (!user1) { if (!user2) return false; user2.popup(`Sorry, your opponent ${ready1.userid} went offline before your battle could start.`); return false; } if (!user2) { user1.popup(`Sorry, your opponent ${ready2.userid} went offline before your battle could start.`); return false; } Rooms.createBattle(ready1.formatid, { p1: user1, p1team: ready1.team, p2: user2, p2team: ready2.team, rated: Math.min(ready1.rating, ready2.rating), }); } } /** * @param {string} formatid */ function getLadder(formatid) { return new Ladder(formatid); } /** @type {?NodeJS.Timer} */ let periodicMatchInterval = setInterval( () => Ladder.periodicMatch(), PERIODIC_MATCH_INTERVAL ); const Ladders = Object.assign(getLadder, { BattleReady, LadderStore, Ladder, cancelSearches: Ladder.cancelSearches, updateSearch: Ladder.updateSearch, rejectChallenge: Ladder.rejectChallenge, acceptChallenge: Ladder.acceptChallenge, cancelChallenging: Ladder.cancelChallenging, clearChallenges: Ladder.clearChallenges, updateChallenges: Ladder.updateChallenges, visualizeAll: Ladder.visualizeAll, getSearches: Ladder.getSearches, match: Ladder.match, searches, challenges, periodicMatchInterval, // tells the client to ask the server for format information formatsListPrefix: LadderStore.formatsListPrefix, /** @type {true | false | 'db'} */ disabled: false, }); module.exports = Ladders;
Clarify message for multi-laddering
server/ladders.js
Clarify message for multi-laddering
<ide><path>erver/ladders.js <ide> <ide> const roomid = this.needsToMove(user); <ide> if (roomid) { <del> connection.popup(`Error: You need to make a move in <<${roomid}>> before you can look for another battle.`); <add> connection.popup(`Error: You need to make a move in <<${roomid}>> before you can look for another battle.\n\n(This restriction doesn't apply in the first five turns of a battle.)`); <ide> return; <ide> } <ide> <ide> if (roomid === null && Date.now() < user.lastDecision + 10 * SECONDS) { <del> connection.popup(`Error: You need to wait 7 seconds after making a move before you can look for another battle.`); <add> connection.popup(`Error: You need to wait 7 seconds after making a move before you can look for another battle.\n\n(This restriction doesn't apply in the first five turns of a battle.)`); <ide> return; <ide> } <ide>
JavaScript
mpl-2.0
0a5f5eed17073a16882b639d1feb19c1a16df6f6
0
diasdavid/browser-laptop,luixxiul/browser-laptop,diasdavid/browser-laptop,manninglucas/browser-laptop,luixxiul/browser-laptop,timborden/browser-laptop,pmkary/braver,Sh1d0w/browser-laptop,Sh1d0w/browser-laptop,MKuenzi/browser-laptop,dcposch/browser-laptop,luixxiul/browser-laptop,willy-b/browser-laptop,MKuenzi/browser-laptop,Sh1d0w/browser-laptop,pmkary/braver,diasdavid/browser-laptop,dcposch/browser-laptop,pmkary/braver,diasdavid/browser-laptop,willy-b/browser-laptop,dcposch/browser-laptop,Sh1d0w/browser-laptop,darkdh/browser-laptop,jonathansampson/browser-laptop,timborden/browser-laptop,willy-b/browser-laptop,willy-b/browser-laptop,darkdh/browser-laptop,MKuenzi/browser-laptop,dcposch/browser-laptop,manninglucas/browser-laptop,timborden/browser-laptop,MKuenzi/browser-laptop,timborden/browser-laptop,jonathansampson/browser-laptop,pmkary/braver,darkdh/browser-laptop,manninglucas/browser-laptop,jonathansampson/browser-laptop,darkdh/browser-laptop,manninglucas/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' const messages = require('../js/constants/messages') const electron = require('electron') const session = electron.session const BrowserWindow = electron.BrowserWindow const AppStore = require('../js/stores/appStore') const AppConfig = require('../js/constants/appConfig') const urlParse = require('url').parse const filteringFns = [] module.exports.registerFilteringCB = filteringFn => { filteringFns.push(filteringFn) } /** * Register for notifications for webRequest notifications for * a particular session. * @param {object} The session to add webRequest filtering on */ function registerForSession (session) { session.webRequest.onBeforeSendHeaders(function (details, cb) { // Using an electron binary which isn't from Brave if (!details.firstPartyUrl) { cb({}) return } let results for (let i = 0; i < filteringFns.length; i++) { let currentResults = filteringFns[i](details) if (currentResults && !module.exports.isResourceEnabled(currentResults.resourceName)) { continue } results = currentResults if (results.shouldBlock) { break } } let requestHeaders = details.requestHeaders if (module.exports.isThirdPartyHost(urlParse(details.url || '').host, urlParse(details.firstPartyUrl || '').host)) { // Clear cookie and referer on third-party requests requestHeaders['Cookie'] = '' requestHeaders['Referer'] = '' } if (!results || !results.shouldBlock) { cb({requestHeaders: requestHeaders}) } else if (results.shouldBlock) { // We have no good way of knowing which BrowserWindow the blocking is for // yet so send it everywhere and let listeners decide how to respond. BrowserWindow.getAllWindows().forEach(wnd => wnd.webContents.send(messages.BLOCKED_RESOURCE, results.resourceName, details)) cb({ requestHeaders: requestHeaders, cancel: true }) } }) } module.exports.isThirdPartyHost = (baseContextHost, testHost) => { if (!testHost || !baseContextHost) { return true } if (!testHost.endsWith(baseContextHost)) { return true } let c = testHost[testHost.length - baseContextHost.length - 1] return c !== '.' && c !== undefined } module.exports.init = () => { registerForSession(session.fromPartition('')) registerForSession(session.fromPartition('private-1')) registerForSession(session.fromPartition('main-1')) } module.exports.isResourceEnabled = (resourceName) => { const enabledFromState = AppStore.getState().getIn([resourceName, 'enabled']) if (enabledFromState === undefined) { return AppConfig[resourceName].enabled } return enabledFromState }
app/filtering.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' const messages = require('../js/constants/messages') const electron = require('electron') const session = electron.session const BrowserWindow = electron.BrowserWindow const AppStore = require('../js/stores/appStore') const AppConfig = require('../js/constants/appConfig') const urlParse = require('url').parse const filteringFns = [] module.exports.registerFilteringCB = filteringFn => { filteringFns.push(filteringFn) } /** * Register for notifications for webRequest notifications for * a particular session. * @param {object} The session to add webRequest filtering on */ function registerForSession (session) { session.webRequest.onBeforeSendHeaders(function (details, cb) { // Using an electron binary which isn't from Brave if (!details.firstPartyUrl) { cb({}) return } let results let cbArgs = {} for (let i = 0; i < filteringFns.length; i++) { let currentResults = filteringFns[i](details) if (currentResults && !module.exports.isResourceEnabled(currentResults.resourceName)) { continue } results = currentResults cbArgs = cbArgs || results.cbArgs if (results.shouldBlock) { break } } console.log('cbargs', cbArgs) let requestHeaders = cbArgs.requestHeaders || details.requestHeaders if (module.exports.isThirdPartyHost(urlParse(details.url || '').host, urlParse(details.firstPartyUrl || '').host)) { console.log('clearing cookies', details.url, details.host) // Clear cookie and referer on third-party requests requestHeaders['Cookie'] = '' requestHeaders['Referer'] = '' } if (!results) { cb({requestHeaders: requestHeaders}) } else if (results.shouldBlock) { // We have no good way of knowing which BrowserWindow the blocking is for // yet so send it everywhere and let listeners decide how to respond. BrowserWindow.getAllWindows().forEach(wnd => wnd.webContents.send(messages.BLOCKED_RESOURCE, results.resourceName, details)) cb({ requestHeaders: requestHeaders, cancel: results.shouldBlock }) } else { cb({ requestHeaders: requestHeaders, cancel: cbArgs.shouldBlock || false }) } }) } module.exports.isThirdPartyHost = (baseContextHost, testHost) => { if (!testHost || !baseContextHost) { return true } if (!testHost.endsWith(baseContextHost)) { return true } let c = testHost[testHost.length - baseContextHost.length - 1] return c !== '.' && c !== undefined } module.exports.init = () => { registerForSession(session.fromPartition('')) registerForSession(session.fromPartition('private-1')) registerForSession(session.fromPartition('main-1')) } module.exports.isResourceEnabled = (resourceName) => { const enabledFromState = AppStore.getState().getIn([resourceName, 'enabled']) if (enabledFromState === undefined) { return AppConfig[resourceName].enabled } return enabledFromState }
Refactor away results cbArgs This was never getting set to anything other than '{}'
app/filtering.js
Refactor away results cbArgs
<ide><path>pp/filtering.js <ide> } <ide> <ide> let results <del> let cbArgs = {} <ide> for (let i = 0; i < filteringFns.length; i++) { <ide> let currentResults = filteringFns[i](details) <ide> if (currentResults && !module.exports.isResourceEnabled(currentResults.resourceName)) { <ide> continue <ide> } <ide> results = currentResults <del> cbArgs = cbArgs || results.cbArgs <ide> if (results.shouldBlock) { <ide> break <ide> } <ide> } <ide> <del> console.log('cbargs', cbArgs) <del> let requestHeaders = cbArgs.requestHeaders || details.requestHeaders <add> let requestHeaders = details.requestHeaders <ide> if (module.exports.isThirdPartyHost(urlParse(details.url || '').host, <ide> urlParse(details.firstPartyUrl || '').host)) { <del> console.log('clearing cookies', details.url, details.host) <ide> // Clear cookie and referer on third-party requests <ide> requestHeaders['Cookie'] = '' <ide> requestHeaders['Referer'] = '' <ide> } <ide> <del> if (!results) { <add> if (!results || !results.shouldBlock) { <ide> cb({requestHeaders: requestHeaders}) <ide> } else if (results.shouldBlock) { <ide> // We have no good way of knowing which BrowserWindow the blocking is for <ide> wnd.webContents.send(messages.BLOCKED_RESOURCE, results.resourceName, details)) <ide> cb({ <ide> requestHeaders: requestHeaders, <del> cancel: results.shouldBlock <del> }) <del> } else { <del> cb({ <del> requestHeaders: requestHeaders, <del> cancel: cbArgs.shouldBlock || false <add> cancel: true <ide> }) <ide> } <ide> })
Java
apache-2.0
8bd0d0ae4f1a4060f4cbecbecb91148cec3ecddd
0
robertzak/goodreads-parser
package noorg.bookparsing.domain.types; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Copyright 2014 Robert J. Zak * * <p>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 * * <p> http://www.apache.org/licenses/LICENSE-2.0 * * <p>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. * * <p>Indicate the state of the book. * * @author Robert J. Zak * */ public enum ReadState { ABANDONED, CURRENTLY_READING, ON_HOLD, READ, TO_READ, UNKNOWN; private static final Logger logger = LoggerFactory.getLogger( ReadState.class); private static final String CUSTOM_ABANDONED = "abandoned"; // For the Sword & Laser folks private static final String CUSTOM_LEMMED = "lemmed"; private static final String CUSTOM_ON_HOLD = "on-hold"; private static final String GR_CURRENTLY_READING = "currently-reading"; private static final String GR_READ = "read"; private static final String GR_TO_READ = "to-read"; /** * Convert a string to the read state from the 'exclusive' shelf. * If the user has any custom exclusive shelves the result will likely * be {@link #UNKNOWN}. * * Support can be added custom shelves as needed, but should probably be * done minimally. * * @param exclusiveShelf * @return */ public static ReadState parse(final String exclusiveShelf){ ReadState state = UNKNOWN; if(exclusiveShelf != null){ switch(exclusiveShelf){ case CUSTOM_ABANDONED: case CUSTOM_LEMMED: state = ABANDONED; break; case CUSTOM_ON_HOLD: state = ON_HOLD; break; case GR_CURRENTLY_READING: state = CURRENTLY_READING; break; case GR_READ: state = READ; break; case GR_TO_READ: state = TO_READ; break; default: logger.warn("{} is not a supported state", exclusiveShelf); state = UNKNOWN; } } return state; } }
src/main/java/noorg/bookparsing/domain/types/ReadState.java
package noorg.bookparsing.domain.types; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Copyright 2014 Robert J. Zak * * <p>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 * * <p> http://www.apache.org/licenses/LICENSE-2.0 * * <p>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. * * <p>Indicate the state of the book. * * @author Robert J. Zak * */ public enum ReadState { ABANDONED, CURRENTLY_READING, READ, TO_READ, UNKNOWN; private static final Logger logger = LoggerFactory.getLogger( ReadState.class); private static final String CUSTOM_ABANDONED = "abandoned"; // For the Sword & Laser folks private static final String CUSTOM_LEMMED = "lemmed"; private static final String GR_CURRENTLY_READING = "currently-reading"; private static final String GR_READ = "read"; private static final String GR_TO_READ = "to-read"; /** * Convert a string to the read state from the 'exclusive' shelf. * If the user has any custom exclusive shelves the result will likely * be {@link #UNKNOWN}. * * Support can be added custom shelves as needed, but should probably be * done minimally. * * @param exclusiveShelf * @return */ public static ReadState parse(final String exclusiveShelf){ ReadState state = UNKNOWN; if(exclusiveShelf != null){ switch(exclusiveShelf){ case CUSTOM_ABANDONED: case CUSTOM_LEMMED: state = ABANDONED; break; case GR_CURRENTLY_READING: state = CURRENTLY_READING; break; case GR_READ: state = READ; break; case GR_TO_READ: state = TO_READ; break; default: logger.warn("{} is not a supported state", exclusiveShelf); state = UNKNOWN; } } return state; } }
Adding On Hold State I added a new/custom exclusive shelf called On-Hold, so I'm adding this to the enum as it is/could be a somewhat standard custom shelf.
src/main/java/noorg/bookparsing/domain/types/ReadState.java
Adding On Hold State I added a new/custom exclusive shelf called On-Hold, so I'm adding this to the enum as it is/could be a somewhat standard custom shelf.
<ide><path>rc/main/java/noorg/bookparsing/domain/types/ReadState.java <ide> * <ide> */ <ide> public enum ReadState { <del> ABANDONED, CURRENTLY_READING, READ, TO_READ, UNKNOWN; <add> ABANDONED, CURRENTLY_READING, ON_HOLD, READ, TO_READ, UNKNOWN; <ide> <ide> private static final Logger logger = LoggerFactory.getLogger( <ide> ReadState.class); <ide> private static final String CUSTOM_ABANDONED = "abandoned"; <ide> // For the Sword & Laser folks <ide> private static final String CUSTOM_LEMMED = "lemmed"; <add> private static final String CUSTOM_ON_HOLD = "on-hold"; <ide> private static final String GR_CURRENTLY_READING = "currently-reading"; <ide> private static final String GR_READ = "read"; <ide> private static final String GR_TO_READ = "to-read"; <ide> case CUSTOM_LEMMED: <ide> state = ABANDONED; <ide> break; <add> case CUSTOM_ON_HOLD: <add> state = ON_HOLD; <add> break; <ide> case GR_CURRENTLY_READING: <ide> state = CURRENTLY_READING; <ide> break;