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 | 17d1bcfaf5083caf89a00e4670924b8fa85185de | 0 | leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,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.orchestration.internal.registry.config.listener;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenter;
import org.apache.shardingsphere.orchestration.reg.listener.DataChangedEvent;
import org.apache.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(MockitoJUnitRunner.class)
public final class AuthenticationChangedListenerTest {
private static final String AUTHENTICATION_YAML = " users:\n" + " root1:\n password: root1\n"
+ " authorizedSchemas: sharding_db\n" + " root2:\n" + " password: root2\n" + " authorizedSchemas: sharding_db,ms_db";
private AuthenticationChangedListener authenticationChangedListener;
@Mock
private RegistryCenter regCenter;
@Before
public void setUp() {
authenticationChangedListener = new AuthenticationChangedListener("test", regCenter);
}
@Test
public void assertCreateShardingOrchestrationEvent() {
assertThat(authenticationChangedListener.createShardingOrchestrationEvent(
new DataChangedEvent("test", AUTHENTICATION_YAML, ChangedType.UPDATED)).getAuthentication().getUsers().get("root1").getPassword(), is("root1"));
}
}
| sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/registry/config/listener/AuthenticationChangedListenerTest.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.orchestration.internal.registry.config.listener;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenter;
import org.apache.shardingsphere.orchestration.reg.listener.DataChangedEvent;
import org.apache.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(MockitoJUnitRunner.class)
public final class AuthenticationChangedListenerTest {
private static final String AUTHENTICATION_YAML = " users:\n" + " root1:\n password: root1\n"
+ " authorizedSchemas: sharding_db\n" + " root2:\n" + " password: root2\n" + " authorizedSchemas: sharding_db,ms_db";
private AuthenticationChangedListener authenticationChangedListener;
@Mock
private RegistryCenter regCenter;
@Before
public void setUp() {
authenticationChangedListener = new AuthenticationChangedListener("test", regCenter);
}
@Test
public void assertCreateShardingOrchestrationEvent() {
assertThat(
authenticationChangedListener.createShardingOrchestrationEvent(new DataChangedEvent("test", AUTHENTICATION_YAML, ChangedType.UPDATED)).getAuthentication().getUsers().get("root1").getPassword(), is("root1"));
}
}
| check style
| sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/registry/config/listener/AuthenticationChangedListenerTest.java | check style | <ide><path>harding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/registry/config/listener/AuthenticationChangedListenerTest.java
<ide>
<ide> @Test
<ide> public void assertCreateShardingOrchestrationEvent() {
<del> assertThat(
<del> authenticationChangedListener.createShardingOrchestrationEvent(new DataChangedEvent("test", AUTHENTICATION_YAML, ChangedType.UPDATED)).getAuthentication().getUsers().get("root1").getPassword(), is("root1"));
<add> assertThat(authenticationChangedListener.createShardingOrchestrationEvent(
<add> new DataChangedEvent("test", AUTHENTICATION_YAML, ChangedType.UPDATED)).getAuthentication().getUsers().get("root1").getPassword(), is("root1"));
<ide> }
<ide> } |
|
Java | apache-2.0 | a70f94df895b6b41de831e67ede8dcd659199a51 | 0 | archiecobbs/jsimpledb,permazen/permazen,permazen/permazen,archiecobbs/jsimpledb,archiecobbs/jsimpledb,permazen/permazen |
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package io.permazen.spring;
import com.google.common.base.Preconditions;
import io.permazen.JTransaction;
import io.permazen.Permazen;
import io.permazen.ValidationMode;
import io.permazen.core.DatabaseException;
import io.permazen.core.Transaction;
import io.permazen.kv.RetryTransactionException;
import io.permazen.kv.StaleTransactionException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.TransactionTimedOutException;
import org.springframework.transaction.TransactionUsageException;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.ResourceTransactionManager;
import org.springframework.transaction.support.SmartTransactionObject;
import org.springframework.transaction.support.TransactionSynchronization;
/**
* Permazen implementation of Spring's
* {@link org.springframework.transaction.PlatformTransactionManager PlatformTransactionManager} interface,
* allowing methods annotated with Spring's {@link org.springframework.transaction.annotation.Transactional @Transactional}
* annotation to perform transactions on a {@link Permazen} database.
*
* <p>
* Properly integrates with {@link JTransaction#getCurrent JTransaction.getCurrent()} to participate in
* existing transactions when appropriate.
*
* <p>
* For some key/value stores, the value of
* {@link org.springframework.transaction.annotation.Transactional#isolation @Transactional.isolation()}
* is significant; see the documentation for your specific {@link io.permazen.kv.KVDatabase} for details.
*
* @see io.permazen.spring
*/
@SuppressWarnings("serial")
public class PermazenTransactionManager extends AbstractPlatformTransactionManager
implements ResourceTransactionManager, InitializingBean {
/**
* The name of the transaction option passed to
* {@link io.permazen.kv.KVDatabase#createTransaction(Map) KVDatabase.createTransaction()}
* containing the {@linkplain TransactionDefinition#getIsolationLevel isolation level} from the
* transaction definition. Some key/value databases may interpret this option.
* The value of this option is an {@link Isolation} instance.
*/
public static final String ISOLATION_OPTION = Isolation.class.getName();
/**
* The default {@link ValidationMode} to use for transactions ({@link ValidationMode#AUTOMATIC}).
*/
public static final ValidationMode DEFAULT_VALIDATION_MODE = ValidationMode.AUTOMATIC;
/**
* The configured {@link Permazen} from which transactions are created.
*/
protected transient Permazen jdb;
/**
* Whether a new schema version is allowed. Default true.
*/
protected boolean allowNewSchema = true;
/**
* The {@link ValidationMode} to use for transactions.
*/
protected ValidationMode validationMode = DEFAULT_VALIDATION_MODE;
private boolean validateBeforeCommit;
@Override
public void afterPropertiesSet() throws Exception {
if (this.jdb == null)
throw new Exception("no Permazen configured");
}
/**
* Configure the {@link Permazen} that this instance will operate on.
*
* <p>
* Required property.
*
* @param jdb associated database
*/
public void setPermazen(Permazen jdb) {
this.jdb = jdb;
}
/**
* Configure whether a new schema version may be created.
*
* <p>
* Default value is false.
*
* @param allowNewSchema whether to allow recording new schema versions
*/
public void setAllowNewSchema(boolean allowNewSchema) {
this.allowNewSchema = allowNewSchema;
}
/**
* Configure the {@link ValidationMode} to use for transactions.
*
* <p>
* Default value is {@link ValidationMode#AUTOMATIC}.
*
* @param validationMode validation mode for transactions
*/
public void setValidationMode(ValidationMode validationMode) {
this.validationMode = validationMode != null ? validationMode : DEFAULT_VALIDATION_MODE;
}
/**
* Configure whether to invoke {@link JTransaction#validate} just prior to commit (and prior to any
* synchronization callbacks). This also causes validation to be performed at the end of each inner
* transaction that is participating in an outer transaction.
* If set to false, validation still occurs, but only when the outermost transaction commits.
*
* <p>
* Default false.
*
* @param validateBeforeCommit whether to validate after inner transactions
*/
public void setValidateBeforeCommit(boolean validateBeforeCommit) {
this.validateBeforeCommit = validateBeforeCommit;
}
@Override
public Object getResourceFactory() {
return this.jdb;
}
@Override
protected Object doGetTransaction() {
return new TxWrapper(this.getCurrent());
}
@Override
protected boolean isExistingTransaction(Object txObj) {
return ((TxWrapper)txObj).getJTransaction() != null;
}
@Override
protected void doBegin(Object txObj, TransactionDefinition txDef) {
// Sanity check
final TxWrapper tx = (TxWrapper)txObj;
if (tx.getJTransaction() != null)
throw new TransactionUsageException("there is already a transaction associated with the current thread");
// Set transaction options
final Map<String, Object> options = new HashMap<>();
switch (txDef.getIsolationLevel()) {
case TransactionDefinition.ISOLATION_READ_UNCOMMITTED:
options.put(ISOLATION_OPTION, Isolation.READ_UNCOMMITTED);
break;
case TransactionDefinition.ISOLATION_READ_COMMITTED:
options.put(ISOLATION_OPTION, Isolation.READ_COMMITTED);
break;
case TransactionDefinition.ISOLATION_REPEATABLE_READ:
options.put(ISOLATION_OPTION, Isolation.REPEATABLE_READ);
break;
case TransactionDefinition.ISOLATION_SERIALIZABLE:
options.put(ISOLATION_OPTION, Isolation.SERIALIZABLE);
break;
case TransactionDefinition.ISOLATION_DEFAULT:
options.put(ISOLATION_OPTION, Isolation.DEFAULT);
break;
default:
this.logger.warn("unexpected isolation level " + txDef.getIsolationLevel());
break;
}
// Create Permazen transaction
final JTransaction jtx;
try {
jtx = this.createTransaction(options);
} catch (DatabaseException e) {
throw new CannotCreateTransactionException("error creating new Permazen transaction", e);
}
// Configure Permazen transaction and bind to current thread; but if we fail, roll it back
boolean succeeded = false;
try {
this.configureTransaction(jtx, txDef);
JTransaction.setCurrent(jtx);
succeeded = true;
} catch (DatabaseException e) {
throw new CannotCreateTransactionException("error configuring Permazen transaction", e);
} finally {
if (!succeeded) {
JTransaction.setCurrent(null);
try {
jtx.rollback();
} catch (DatabaseException e) {
// ignore
}
}
}
// Done
tx.setJTransaction(jtx);
}
/**
* Create the underlying {@link JTransaction} for a new transaction.
*
* <p>
* The implementation in {@link PermazenTransactionManager} just delegates to
* {@link Permazen#createTransaction(boolean, ValidationMode, Map)} using this instance's configured
* settings for validation mode and allowing new schema versions.
*
* @param options transaction options
* @return newly created {@link JTransaction}
* @throws DatabaseException if an error occurs
*/
protected JTransaction createTransaction(Map<String, Object> options) {
return this.jdb.createTransaction(this.allowNewSchema, this.validationMode, options);
}
/**
* Suspend the current transaction.
*/
@Override
protected Object doSuspend(Object txObj) {
// Sanity check
final JTransaction jtx = ((TxWrapper)txObj).getJTransaction();
if (jtx == null)
throw new TransactionUsageException("no JTransaction exists in the provided transaction object");
if (jtx != this.getCurrent())
throw new TransactionUsageException("the provided transaction object contains the wrong JTransaction");
// Suspend it
if (this.logger.isTraceEnabled())
this.logger.trace("suspending current Permazen transaction " + jtx);
JTransaction.setCurrent(null);
// Done
return jtx;
}
/**
* Resume a previously suspended transaction.
*/
@Override
protected void doResume(Object txObj, Object suspendedResources) {
// Sanity check
if (this.getCurrent() != null)
throw new TransactionUsageException("there is already a transaction associated with the current thread");
// Resume transaction
final JTransaction jtx = (JTransaction)suspendedResources;
if (this.logger.isTraceEnabled())
this.logger.trace("resuming Permazen transaction " + jtx);
JTransaction.setCurrent(jtx);
}
/**
* Configure a new transaction.
*
* <p>
* The implementation in {@link PermazenTransactionManager} sets the transaction's timeout and read-only properties.
*
* @param jtx transaction to configure
* @param txDef transaction definition
* @throws DatabaseException if an error occurs
*/
protected void configureTransaction(JTransaction jtx, TransactionDefinition txDef) {
// Set name
//jtx.setName(txDef.getName());
// Set read-only
if (txDef.isReadOnly())
jtx.getTransaction().setReadOnly(true);
// Set lock timeout
final int timeout = this.determineTimeout(txDef);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
try {
jtx.getTransaction().setTimeout(timeout * 1000L);
} catch (UnsupportedOperationException e) {
if (this.logger.isDebugEnabled())
this.logger.debug("setting non-default timeout of " + timeout + "sec not supported by underlying transaction");
}
}
}
@Override
protected void prepareForCommit(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Validate
if (this.validateBeforeCommit) {
if (this.logger.isTraceEnabled())
this.logger.trace("triggering validation prior to commit of Permazen transaction " + jtx);
jtx.validate();
}
}
@Override
protected void doCommit(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Commit
try {
if (this.logger.isTraceEnabled())
this.logger.trace("committing Permazen transaction " + jtx);
jtx.commit();
} catch (RetryTransactionException e) {
throw new PessimisticLockingFailureException("transaction must be retried", e);
} catch (StaleTransactionException e) {
throw new TransactionTimedOutException("transaction is no longer usable", e);
} catch (DatabaseException e) {
throw new TransactionSystemException("error committing transaction", e);
} finally {
JTransaction.setCurrent(null); // transaction is no longer usable
}
}
@Override
protected void doRollback(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Rollback
try {
if (this.logger.isTraceEnabled())
this.logger.trace("rolling back Permazen transaction " + jtx);
jtx.rollback();
} catch (StaleTransactionException e) {
throw new TransactionTimedOutException("transaction is no longer usable", e);
} catch (DatabaseException e) {
throw new TransactionSystemException("error committing transaction", e);
} finally {
JTransaction.setCurrent(null); // transaction is no longer usable
}
}
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Set rollback only
if (this.logger.isTraceEnabled())
this.logger.trace("marking Permazen transaction " + jtx + " for rollback-only");
jtx.getTransaction().setRollbackOnly();
}
@Override
protected void doCleanupAfterCompletion(Object txObj) {
JTransaction.setCurrent(null);
super.doCleanupAfterCompletion(txObj);
}
@Override
protected void registerAfterCompletionWithExistingTransaction(Object txObj, List<TransactionSynchronization> synchronizations) {
// Get transaction
final JTransaction jtx = ((TxWrapper)txObj).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Add synchronizations
final Transaction tx = jtx.getTransaction();
for (TransactionSynchronization synchronization : synchronizations)
tx.addCallback(new TransactionSynchronizationCallback(synchronization));
}
/**
* Like {@link JTransaction#getCurrent}, but returns null instead of throwing {@link IllegalStateException}.
*
* @return the transaction associated with the current thread, or null if there is none
*/
protected JTransaction getCurrent() {
try {
return JTransaction.getCurrent();
} catch (IllegalStateException e) {
return null;
}
}
// TxWrapper
private static class TxWrapper implements SmartTransactionObject {
private JTransaction jtx;
TxWrapper(JTransaction jtx) {
this.jtx = jtx;
}
public JTransaction getJTransaction() {
return this.jtx;
}
public void setJTransaction(JTransaction jtx) {
this.jtx = jtx;
}
@Override
public boolean isRollbackOnly() {
return this.jtx != null && this.jtx.getTransaction().isRollbackOnly();
}
@Override
public void flush() {
}
}
// SynchronizationCallback
/**
* Adapter class that wraps a Spring {@link TransactionSynchronization} in the
* {@link io.permazen.core.Transaction.Callback} interface.
*/
public static class TransactionSynchronizationCallback implements Transaction.Callback {
protected final TransactionSynchronization synchronization;
/**
* Constructor.
*
* @param synchronization transaction callback
* @throws IllegalArgumentException if {@code synchronization} is null
*/
public TransactionSynchronizationCallback(TransactionSynchronization synchronization) {
Preconditions.checkArgument(synchronization != null, "null synchronization");
this.synchronization = synchronization;
}
@Override
public void beforeCommit(boolean readOnly) {
this.synchronization.beforeCommit(readOnly);
}
@Override
public void beforeCompletion() {
this.synchronization.beforeCompletion();
}
@Override
public void afterCommit() {
this.synchronization.afterCommit();
}
@Override
public void afterCompletion(boolean committed) {
this.synchronization.afterCompletion(committed ?
TransactionSynchronization.STATUS_COMMITTED : TransactionSynchronization.STATUS_ROLLED_BACK);
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null || obj.getClass() != this.getClass())
return false;
final TransactionSynchronizationCallback that = (TransactionSynchronizationCallback)obj;
return this.synchronization.equals(that.synchronization);
}
@Override
public int hashCode() {
return this.synchronization.hashCode();
}
}
}
| permazen-spring/src/main/java/io/permazen/spring/PermazenTransactionManager.java |
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package io.permazen.spring;
import com.google.common.base.Preconditions;
import io.permazen.JTransaction;
import io.permazen.Permazen;
import io.permazen.ValidationMode;
import io.permazen.core.DatabaseException;
import io.permazen.core.Transaction;
import io.permazen.kv.RetryTransactionException;
import io.permazen.kv.StaleTransactionException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.TransactionTimedOutException;
import org.springframework.transaction.TransactionUsageException;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.ResourceTransactionManager;
import org.springframework.transaction.support.SmartTransactionObject;
import org.springframework.transaction.support.TransactionSynchronization;
/**
* Permazen implementation of Spring's
* {@link org.springframework.transaction.PlatformTransactionManager PlatformTransactionManager} interface,
* allowing methods annotated with Spring's {@link org.springframework.transaction.annotation.Transactional @Transactional}
* annotation to perform transactions on a {@link Permazen} database.
*
* <p>
* Properly integrates with {@link JTransaction#getCurrent JTransaction.getCurrent()} to participate in
* existing transactions when appropriate.
*
* <p>
* For some key/value stores, the value of
* {@link org.springframework.transaction.annotation.Transactional#isolation @Transactional.isolation()}
* is significant; see the documentation for your specific {@link io.permazen.kv.KVDatabase} for details.
*
* @see io.permazen.spring
*/
@SuppressWarnings("serial")
public class PermazenTransactionManager extends AbstractPlatformTransactionManager
implements ResourceTransactionManager, InitializingBean {
/**
* The name of the transaction option passed to
* {@link io.permazen.kv.KVDatabase#createTransaction(Map) KVDatabase.createTransaction()}
* containing the {@linkplain TransactionDefinition#getIsolationLevel isolation level} from the
* transaction definition. Some key/value databases may interpret this option.
* The value of this option is an {@link Isolation} instance.
*/
public static final String ISOLATION_OPTION = Isolation.class.getName();
/**
* The default {@link ValidationMode} to use for transactions ({@link ValidationMode#AUTOMATIC}).
*/
public static final ValidationMode DEFAULT_VALIDATION_MODE = ValidationMode.AUTOMATIC;
/**
* The configured {@link Permazen} from which transactions are created.
*/
protected transient Permazen jdb;
/**
* Whether a new schema version is allowed. Default true.
*/
protected boolean allowNewSchema = true;
/**
* The {@link ValidationMode} to use for transactions.
*/
protected ValidationMode validationMode = DEFAULT_VALIDATION_MODE;
private boolean validateBeforeCommit;
@Override
public void afterPropertiesSet() throws Exception {
if (this.jdb == null)
throw new Exception("no Permazen configured");
}
/**
* Configure the {@link Permazen} that this instance will operate on.
*
* <p>
* Required property.
*
* @param jdb associated database
*/
public void setPermazen(Permazen jdb) {
this.jdb = jdb;
}
/**
* Configure whether a new schema version may be created.
*
* <p>
* Default value is false.
*
* @param allowNewSchema whether to allow recording new schema versions
*/
public void setAllowNewSchema(boolean allowNewSchema) {
this.allowNewSchema = allowNewSchema;
}
/**
* Configure the {@link ValidationMode} to use for transactions.
*
* <p>
* Default value is {@link ValidationMode#AUTOMATIC}.
*
* @param validationMode validation mode for transactions
*/
public void setValidationMode(ValidationMode validationMode) {
this.validationMode = validationMode != null ? validationMode : DEFAULT_VALIDATION_MODE;
}
/**
* Configure whether to invoke {@link JTransaction#validate} just prior to commit (and prior to any
* synchronization callbacks). This also causes validation to be performed at the end of each inner
* transaction that is participating in an outer transaction.
* If set to false, validation still occurs, but only when the outermost transaction commits.
*
* <p>
* Default false.
*
* @param validateBeforeCommit whether to validate after inner transactions
*/
public void setValidateBeforeCommit(boolean validateBeforeCommit) {
this.validateBeforeCommit = validateBeforeCommit;
}
@Override
public Object getResourceFactory() {
return this.jdb;
}
@Override
protected Object doGetTransaction() {
return new TxWrapper(this.getCurrent());
}
@Override
protected boolean isExistingTransaction(Object txObj) {
return ((TxWrapper)txObj).getJTransaction() != null;
}
@Override
protected void doBegin(Object txObj, TransactionDefinition txDef) {
// Sanity check
final TxWrapper tx = (TxWrapper)txObj;
if (tx.getJTransaction() != null)
throw new TransactionUsageException("there is already a transaction associated with the current thread");
// Set transaction options
final Map<String, Object> options = new HashMap<>();
switch (txDef.getIsolationLevel()) {
case TransactionDefinition.ISOLATION_READ_UNCOMMITTED:
options.put(ISOLATION_OPTION, Isolation.READ_UNCOMMITTED);
break;
case TransactionDefinition.ISOLATION_READ_COMMITTED:
options.put(ISOLATION_OPTION, Isolation.READ_COMMITTED);
break;
case TransactionDefinition.ISOLATION_REPEATABLE_READ:
options.put(ISOLATION_OPTION, Isolation.REPEATABLE_READ);
break;
case TransactionDefinition.ISOLATION_SERIALIZABLE:
options.put(ISOLATION_OPTION, Isolation.SERIALIZABLE);
break;
case TransactionDefinition.ISOLATION_DEFAULT:
options.put(ISOLATION_OPTION, Isolation.DEFAULT);
break;
default:
this.logger.warn("unexpected isolation level " + txDef.getIsolationLevel());
break;
}
// Create Permazen transaction
final JTransaction jtx;
try {
jtx = this.createTransaction(options);
} catch (DatabaseException e) {
throw new CannotCreateTransactionException("error creating new Permazen transaction", e);
}
// Configure Permazen transaction and bind to current thread; but if we fail, roll it back
boolean succeeded = false;
try {
this.configureTransaction(jtx, txDef);
JTransaction.setCurrent(jtx);
succeeded = true;
} catch (DatabaseException e) {
throw new CannotCreateTransactionException("error configuring Permazen transaction", e);
} finally {
if (!succeeded) {
JTransaction.setCurrent(null);
try {
jtx.rollback();
} catch (DatabaseException e) {
// ignore
}
}
}
// Done
tx.setJTransaction(jtx);
}
/**
* Create the underlying {@link JTransaction} for a new transaction.
*
* <p>
* The implementation in {@link PermazenTransactionManager} just delegates to
* {@link Permazen#createTransaction(boolean, ValidationMode, Map)} using this instance's configured
* settings for validation mode and allowing new schema versions.
*
* @param options transaction options
* @return newly created {@link JTransaction}
* @throws DatabaseException if an error occurs
*/
protected JTransaction createTransaction(Map<String, Object> options) {
return this.jdb.createTransaction(this.allowNewSchema, this.validationMode, options);
}
/**
* Suspend the current transaction.
*/
@Override
protected Object doSuspend(Object txObj) {
// Sanity check
final JTransaction jtx = ((TxWrapper)txObj).getJTransaction();
if (jtx == null)
throw new TransactionUsageException("no JTransaction exists in the provided transaction object");
if (jtx != this.getCurrent())
throw new TransactionUsageException("the provided transaction object contains the wrong JTransaction");
// Suspend it
if (this.logger.isTraceEnabled())
this.logger.trace("suspending current Permazen transaction " + jtx);
JTransaction.setCurrent(null);
// Done
return jtx;
}
/**
* Resume a previously suspended transaction.
*/
@Override
protected void doResume(Object txObj, Object suspendedResources) {
// Sanity check
if (this.getCurrent() != null)
throw new TransactionUsageException("there is already a transaction associated with the current thread");
// Resume transaction
final JTransaction jtx = (JTransaction)suspendedResources;
if (this.logger.isTraceEnabled())
this.logger.trace("resuming Permazen transaction " + jtx);
JTransaction.setCurrent(jtx);
}
/**
* Configure a new transaction.
*
* <p>
* The implementation in {@link PermazenTransactionManager} sets the transaction's timeout and read-only properties.
*
* @param jtx transaction to configure
* @param txDef transaction definition
* @throws DatabaseException if an error occurs
*/
protected void configureTransaction(JTransaction jtx, TransactionDefinition txDef) {
// Set name
//jtx.setName(txDef.getName());
// Set read-only
if (txDef.isReadOnly())
jtx.getTransaction().setReadOnly(true);
// Set lock timeout
final int timeout = this.determineTimeout(txDef);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
try {
jtx.getTransaction().setTimeout(timeout * 1000L);
} catch (UnsupportedOperationException e) {
if (this.logger.isDebugEnabled())
this.logger.debug("setting non-default timeout of " + timeout + "sec not supported by underlying transaction");
}
}
}
@Override
protected void prepareForCommit(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Validate
if (this.validateBeforeCommit) {
if (this.logger.isTraceEnabled())
this.logger.trace("triggering validation prior to commit of Permazen transaction " + jtx);
jtx.validate();
}
}
@Override
protected void doCommit(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Commit
try {
if (this.logger.isTraceEnabled())
this.logger.trace("committing Permazen transaction " + jtx);
jtx.commit();
} catch (RetryTransactionException e) {
throw new PessimisticLockingFailureException("transaction must be retried", e);
} catch (StaleTransactionException e) {
throw new TransactionTimedOutException("transaction is no longer usable", e);
} catch (DatabaseException e) {
throw new TransactionSystemException("error committing transaction", e);
} finally {
JTransaction.setCurrent(null); // transaction is no longer usable
}
}
@Override
protected void doRollback(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Rollback
try {
if (this.logger.isTraceEnabled())
this.logger.trace("rolling back Permazen transaction " + jtx);
jtx.rollback();
} catch (StaleTransactionException e) {
throw new TransactionTimedOutException("transaction is no longer usable", e);
} catch (DatabaseException e) {
throw new TransactionSystemException("error committing transaction", e);
} finally {
JTransaction.setCurrent(null); // transaction is no longer usable
}
}
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) {
// Is there a transaction?
if (!status.hasTransaction())
return;
// Get transaction
final JTransaction jtx = ((TxWrapper)status.getTransaction()).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Set rollback only
if (this.logger.isTraceEnabled())
this.logger.trace("marking Permazen transaction " + jtx + " for rollback-only");
jtx.getTransaction().setRollbackOnly();
}
@Override
protected void doCleanupAfterCompletion(Object txObj) {
JTransaction.setCurrent(null);
}
@Override
protected void registerAfterCompletionWithExistingTransaction(Object txObj, List<TransactionSynchronization> synchronizations) {
// Get transaction
final JTransaction jtx = ((TxWrapper)txObj).getJTransaction();
if (jtx == null)
throw new NoTransactionException("no current JTransaction exists");
// Add synchronizations
final Transaction tx = jtx.getTransaction();
for (TransactionSynchronization synchronization : synchronizations)
tx.addCallback(new TransactionSynchronizationCallback(synchronization));
}
/**
* Like {@link JTransaction#getCurrent}, but returns null instead of throwing {@link IllegalStateException}.
*
* @return the transaction associated with the current thread, or null if there is none
*/
protected JTransaction getCurrent() {
try {
return JTransaction.getCurrent();
} catch (IllegalStateException e) {
return null;
}
}
// TxWrapper
private static class TxWrapper implements SmartTransactionObject {
private JTransaction jtx;
TxWrapper(JTransaction jtx) {
this.jtx = jtx;
}
public JTransaction getJTransaction() {
return this.jtx;
}
public void setJTransaction(JTransaction jtx) {
this.jtx = jtx;
}
@Override
public boolean isRollbackOnly() {
return this.jtx != null && this.jtx.getTransaction().isRollbackOnly();
}
@Override
public void flush() {
}
}
// SynchronizationCallback
/**
* Adapter class that wraps a Spring {@link TransactionSynchronization} in the
* {@link io.permazen.core.Transaction.Callback} interface.
*/
public static class TransactionSynchronizationCallback implements Transaction.Callback {
protected final TransactionSynchronization synchronization;
/**
* Constructor.
*
* @param synchronization transaction callback
* @throws IllegalArgumentException if {@code synchronization} is null
*/
public TransactionSynchronizationCallback(TransactionSynchronization synchronization) {
Preconditions.checkArgument(synchronization != null, "null synchronization");
this.synchronization = synchronization;
}
@Override
public void beforeCommit(boolean readOnly) {
this.synchronization.beforeCommit(readOnly);
}
@Override
public void beforeCompletion() {
this.synchronization.beforeCompletion();
}
@Override
public void afterCommit() {
this.synchronization.afterCommit();
}
@Override
public void afterCompletion(boolean committed) {
this.synchronization.afterCompletion(committed ?
TransactionSynchronization.STATUS_COMMITTED : TransactionSynchronization.STATUS_ROLLED_BACK);
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null || obj.getClass() != this.getClass())
return false;
final TransactionSynchronizationCallback that = (TransactionSynchronizationCallback)obj;
return this.synchronization.equals(that.synchronization);
}
@Override
public int hashCode() {
return this.synchronization.hashCode();
}
}
}
| Invoke superclass's doCleanupAfterCompletion() in override.
| permazen-spring/src/main/java/io/permazen/spring/PermazenTransactionManager.java | Invoke superclass's doCleanupAfterCompletion() in override. | <ide><path>ermazen-spring/src/main/java/io/permazen/spring/PermazenTransactionManager.java
<ide> @Override
<ide> protected void doCleanupAfterCompletion(Object txObj) {
<ide> JTransaction.setCurrent(null);
<add> super.doCleanupAfterCompletion(txObj);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | d9e77445bd8bd75a63fcecc2178e310baf96535b | 0 | madurangasiriwardena/carbon-identity,IndunilRathnayake/carbon-identity,IndunilRathnayake/carbon-identity,0xkasun/carbon-identity,madurangasiriwardena/carbon-identity,darshanasbg/carbon-identity,dracusds123/carbon-identity,thilina27/carbon-identity,wso2/carbon-identity,hasinthaindrajee/carbon-identity,GayanM/carbon-identity,hasinthaindrajee/carbon-identity,GayanM/carbon-identity,nuwand/carbon-identity,madurangasiriwardena/carbon-identity,harsha1979/carbon-identity,malithie/carbon-identity,keerthu/carbon-identity,mefarazath/carbon-identity,thanujalk/carbon-identity,thanujalk/carbon-identity,virajsenevirathne/carbon-identity,virajsenevirathne/carbon-identity,virajsenevirathne/carbon-identity,harsha1979/carbon-identity,Shakila/carbon-identity,liurl3/carbon-identity,thusithathilina/carbon-identity,IsuraD/carbon-identity,damithsenanayake/carbon-identity,hpmtissera/carbon-identity,mefarazath/carbon-identity,damithsenanayake/carbon-identity,godwinamila/carbon-identity,kasungayan/carbon-identity,0xkasun/carbon-identity,nuwandi-is/carbon-identity,thilina27/carbon-identity,kesavany/carbon-identity,kasungayan/carbon-identity,nuwand/carbon-identity,pulasthi7/carbon-identity,GayanM/carbon-identity,thusithathilina/carbon-identity,keerthu/carbon-identity,IndunilRathnayake/carbon-identity,kasungayan/carbon-identity,prabathabey/carbon-identity,Niranjan-K/carbon-identity,pulasthi7/carbon-identity,thilina27/carbon-identity,mefarazath/carbon-identity,Niranjan-K/carbon-identity,hpmtissera/carbon-identity,dracusds123/carbon-identity,keerthu/carbon-identity,prabathabey/carbon-identity,DMHP/carbon-identity,darshanasbg/carbon-identity,thusithathilina/carbon-identity,prabathabey/carbon-identity,malithie/carbon-identity,hasinthaindrajee/carbon-identity,nuwand/carbon-identity,godwinamila/carbon-identity,0xkasun/carbon-identity,nuwandi-is/carbon-identity,DMHP/carbon-identity,DMHP/carbon-identity,johannnallathamby/carbon-identity,thariyarox/carbon-identity,kesavany/carbon-identity,johannnallathamby/carbon-identity,godwinamila/carbon-identity,liurl3/carbon-identity,malithie/carbon-identity,damithsenanayake/carbon-identity,IsuraD/carbon-identity,dracusds123/carbon-identity,johannnallathamby/carbon-identity,wso2/carbon-identity,thariyarox/carbon-identity,wso2/carbon-identity,harsha1979/carbon-identity,IsuraD/carbon-identity,kesavany/carbon-identity,pulasthi7/carbon-identity,thariyarox/carbon-identity,darshanasbg/carbon-identity,ChamaraPhilipsuom/carbon-identity,Shakila/carbon-identity,liurl3/carbon-identity,hpmtissera/carbon-identity,ChamaraPhilipsuom/carbon-identity,Niranjan-K/carbon-identity,Shakila/carbon-identity,thanujalk/carbon-identity,nuwandi-is/carbon-identity,ChamaraPhilipsuom/carbon-identity | /*
* Copyright (c) 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.identity.sso.saml.session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOParticipantCache;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOParticipantCacheEntry;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOParticipantCacheKey;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOSessionIndexCache;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOSessionIndexCacheEntry;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOSessionIndexCacheKey;
/**
* This class is used to persist the sessions established with Service providers
*/
public class SSOSessionPersistenceManager {
private static final int CACHE_TIME_OUT = 157680000;
private static Log log = LogFactory.getLog(SSOSessionPersistenceManager.class);
private static SSOSessionPersistenceManager sessionPersistenceManager;
public static SSOSessionPersistenceManager getPersistenceManager() {
if (sessionPersistenceManager == null) {
sessionPersistenceManager = new SSOSessionPersistenceManager();
}
return sessionPersistenceManager;
}
public static void addSessionInfoDataToCache(String key, SessionInfoData sessionInfoData) {
SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
SAMLSSOParticipantCacheEntry cacheEntry = new SAMLSSOParticipantCacheEntry();
cacheEntry.setSessionInfoData(sessionInfoData);
SAMLSSOParticipantCache.getInstance(CACHE_TIME_OUT).addToCache(cacheKey, cacheEntry);
}
public static void addSessionIndexToCache(String key, String sessionIndex) {
SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
SAMLSSOSessionIndexCacheEntry cacheEntry = new SAMLSSOSessionIndexCacheEntry();
cacheEntry.setSessionIndex(sessionIndex);
SAMLSSOSessionIndexCache.getInstance(CACHE_TIME_OUT).addToCache(cacheKey, cacheEntry);
}
public static SessionInfoData getSessionInfoDataFromCache(String key) {
SessionInfoData sessionInfoData = null;
SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
Object cacheEntryObj = SAMLSSOParticipantCache.getInstance(CACHE_TIME_OUT).getValueFromCache(cacheKey);
if (cacheEntryObj != null) {
sessionInfoData = ((SAMLSSOParticipantCacheEntry) cacheEntryObj).getSessionInfoData();
}
return sessionInfoData;
}
public static String getSessionIndexFromCache(String key) {
String sessionIndex = null;
SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
Object cacheEntryObj = SAMLSSOSessionIndexCache.getInstance(CACHE_TIME_OUT).getValueFromCache(cacheKey);
if (cacheEntryObj != null) {
sessionIndex = ((SAMLSSOSessionIndexCacheEntry) cacheEntryObj).getSessionIndex();
}
return sessionIndex;
}
public static void removeSessionInfoDataFromCache(String key) {
if (key != null) {
SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
SAMLSSOParticipantCache.getInstance(CACHE_TIME_OUT).clearCacheEntry(cacheKey);
}
}
public static void removeSessionIndexFromCache(String key) {
if (key != null) {
SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
SAMLSSOSessionIndexCache.getInstance(CACHE_TIME_OUT).clearCacheEntry(cacheKey);
}
}
public void persistSession(String sessionIndex, String subject, SAMLSSOServiceProviderDO spDO,
String rpSessionId, String issuer, String assertionConsumerURL)
throws IdentityException {
SessionInfoData sessionInfoData = getSessionInfoDataFromCache(sessionIndex);
if (sessionInfoData == null) {
sessionInfoData = new SessionInfoData();
}
//give priority to assertion consuming URL if specified in the request
if (assertionConsumerURL != null) {
spDO.setAssertionConsumerUrl(assertionConsumerURL);
}
sessionInfoData.setSubject(issuer, subject);
sessionInfoData.addServiceProvider(spDO.getIssuer(), spDO, rpSessionId);
addSessionInfoDataToCache(sessionIndex, sessionInfoData);
}
/**
* Get the session infodata for a particular session
*
* @param sessionIndex
* @return
*/
public SessionInfoData getSessionInfo(String sessionIndex) {
return getSessionInfoDataFromCache(sessionIndex);
}
/**
* Remove a particular session
*
* @param sessionIndex
*/
public void removeSession(String sessionIndex) {
removeSessionInfoDataFromCache(sessionIndex);
}
/**
* Check whether this is an existing session
*
* @return
*/
public boolean isExistingSession(String sessionIndex) {
SessionInfoData sessionInfoData = getSessionInfoDataFromCache(sessionIndex);
if (sessionInfoData != null) {
return true;
}
return false;
}
public void persistSession(String tokenId, String sessionIndex) {
if (tokenId == null) {
log.debug("SSO Token Id is null.");
return;
}
if (sessionIndex == null) {
log.debug("SessionIndex is null.");
return;
}
addSessionIndexToCache(tokenId, sessionIndex);
}
public boolean isExistingTokenId(String tokenId) {
String sessionIndex = getSessionIndexFromCache(tokenId);
if (sessionIndex != null) {
return true;
}
return false;
}
public String getSessionIndexFromTokenId(String tokenId) {
return getSessionIndexFromCache(tokenId);
}
public void removeTokenId(String sessionId) {
removeSessionIndexFromCache(sessionId);
}
}
| components/sso-saml/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/session/SSOSessionPersistenceManager.java | /*
* Copyright (c) 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.identity.sso.saml.session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOParticipantCache;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOParticipantCacheEntry;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOParticipantCacheKey;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOSessionIndexCache;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOSessionIndexCacheEntry;
import org.wso2.carbon.identity.sso.saml.cache.SAMLSSOSessionIndexCacheKey;
/**
* This class is used to persist the sessions established with Service providers
*/
public class SSOSessionPersistenceManager {
private static final int CACHE_TIME_OUT = 157680000;
private static Log log = LogFactory.getLog(SSOSessionPersistenceManager.class);
private static SSOSessionPersistenceManager sessionPersistenceManager;
public static SSOSessionPersistenceManager getPersistenceManager() {
if (sessionPersistenceManager == null) {
sessionPersistenceManager = new SSOSessionPersistenceManager();
}
return sessionPersistenceManager;
}
public static void addSessionInfoDataToCache(String key, SessionInfoData sessionInfoData,
int cacheTimeout) {
SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
SAMLSSOParticipantCacheEntry cacheEntry = new SAMLSSOParticipantCacheEntry();
cacheEntry.setSessionInfoData(sessionInfoData);
SAMLSSOParticipantCache.getInstance(cacheTimeout).addToCache(cacheKey, cacheEntry);
}
public static void addSessionIndexToCache(String key, String sessionIndex,
int cacheTimeout) {
SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
SAMLSSOSessionIndexCacheEntry cacheEntry = new SAMLSSOSessionIndexCacheEntry();
cacheEntry.setSessionIndex(sessionIndex);
SAMLSSOSessionIndexCache.getInstance(cacheTimeout).addToCache(cacheKey, cacheEntry);
}
public static SessionInfoData getSessionInfoDataFromCache(String key) {
SessionInfoData sessionInfoData = null;
SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
Object cacheEntryObj = SAMLSSOParticipantCache.getInstance(0).getValueFromCache(cacheKey);
if (cacheEntryObj != null) {
sessionInfoData = ((SAMLSSOParticipantCacheEntry) cacheEntryObj).getSessionInfoData();
}
return sessionInfoData;
}
public static String getSessionIndexFromCache(String key) {
String sessionIndex = null;
SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
Object cacheEntryObj = SAMLSSOSessionIndexCache.getInstance(0).getValueFromCache(cacheKey);
if (cacheEntryObj != null) {
sessionIndex = ((SAMLSSOSessionIndexCacheEntry) cacheEntryObj).getSessionIndex();
}
return sessionIndex;
}
public static void removeSessionInfoDataFromCache(String key) {
if (key != null) {
SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
SAMLSSOParticipantCache.getInstance(0).clearCacheEntry(cacheKey);
}
}
public static void removeSessionIndexFromCache(String key) {
if (key != null) {
SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
SAMLSSOSessionIndexCache.getInstance(0).clearCacheEntry(cacheKey);
}
}
public void persistSession(String sessionIndex, String subject, SAMLSSOServiceProviderDO spDO,
String rpSessionId, String issuer, String assertionConsumerURL)
throws IdentityException {
SessionInfoData sessionInfoData = getSessionInfoDataFromCache(sessionIndex);
if (sessionInfoData == null) {
sessionInfoData = new SessionInfoData();
}
//give priority to assertion consuming URL if specified in the request
if (assertionConsumerURL != null) {
spDO.setAssertionConsumerUrl(assertionConsumerURL);
}
sessionInfoData.setSubject(issuer, subject);
sessionInfoData.addServiceProvider(spDO.getIssuer(), spDO, rpSessionId);
addSessionInfoDataToCache(sessionIndex, sessionInfoData, Integer.parseInt(IdentityUtil.
getProperty("SSOService.SessionIndexCacheTimeout")));
}
/**
* Get the session infodata for a particular session
*
* @param sessionIndex
* @return
*/
public SessionInfoData getSessionInfo(String sessionIndex) {
return getSessionInfoDataFromCache(sessionIndex);
}
/**
* Remove a particular session
*
* @param sessionIndex
*/
public void removeSession(String sessionIndex) {
removeSessionInfoDataFromCache(sessionIndex);
}
/**
* Check whether this is an existing session
*
* @return
*/
public boolean isExistingSession(String sessionIndex) {
SessionInfoData sessionInfoData = getSessionInfoDataFromCache(sessionIndex);
if (sessionInfoData != null) {
return true;
}
return false;
}
public void persistSession(String tokenId, String sessionIndex) {
if (tokenId == null) {
log.debug("SSO Token Id is null.");
return;
}
if (sessionIndex == null) {
log.debug("SessionIndex is null.");
return;
}
addSessionIndexToCache(tokenId, sessionIndex, Integer.parseInt(IdentityUtil.
getProperty("SSOService.SessionIndexCacheTimeout")));
}
public boolean isExistingTokenId(String tokenId) {
String sessionIndex = getSessionIndexFromCache(tokenId);
if (sessionIndex != null) {
return true;
}
return false;
}
public String getSessionIndexFromTokenId(String tokenId) {
return getSessionIndexFromCache(tokenId);
}
public void removeTokenId(String sessionId) {
removeSessionIndexFromCache(sessionId);
}
}
| Sync up timeout of all cache operations of SAML component
| components/sso-saml/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/session/SSOSessionPersistenceManager.java | Sync up timeout of all cache operations of SAML component | <ide><path>omponents/sso-saml/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/session/SSOSessionPersistenceManager.java
<ide> return sessionPersistenceManager;
<ide> }
<ide>
<del> public static void addSessionInfoDataToCache(String key, SessionInfoData sessionInfoData,
<del> int cacheTimeout) {
<add> public static void addSessionInfoDataToCache(String key, SessionInfoData sessionInfoData) {
<ide>
<ide> SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
<ide> SAMLSSOParticipantCacheEntry cacheEntry = new SAMLSSOParticipantCacheEntry();
<ide> cacheEntry.setSessionInfoData(sessionInfoData);
<del> SAMLSSOParticipantCache.getInstance(cacheTimeout).addToCache(cacheKey, cacheEntry);
<add> SAMLSSOParticipantCache.getInstance(CACHE_TIME_OUT).addToCache(cacheKey, cacheEntry);
<ide> }
<ide>
<del> public static void addSessionIndexToCache(String key, String sessionIndex,
<del> int cacheTimeout) {
<add> public static void addSessionIndexToCache(String key, String sessionIndex) {
<ide>
<ide> SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
<ide> SAMLSSOSessionIndexCacheEntry cacheEntry = new SAMLSSOSessionIndexCacheEntry();
<ide> cacheEntry.setSessionIndex(sessionIndex);
<del> SAMLSSOSessionIndexCache.getInstance(cacheTimeout).addToCache(cacheKey, cacheEntry);
<add> SAMLSSOSessionIndexCache.getInstance(CACHE_TIME_OUT).addToCache(cacheKey, cacheEntry);
<ide> }
<ide>
<ide> public static SessionInfoData getSessionInfoDataFromCache(String key) {
<ide>
<ide> SessionInfoData sessionInfoData = null;
<ide> SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
<del> Object cacheEntryObj = SAMLSSOParticipantCache.getInstance(0).getValueFromCache(cacheKey);
<add> Object cacheEntryObj = SAMLSSOParticipantCache.getInstance(CACHE_TIME_OUT).getValueFromCache(cacheKey);
<ide>
<ide> if (cacheEntryObj != null) {
<ide> sessionInfoData = ((SAMLSSOParticipantCacheEntry) cacheEntryObj).getSessionInfoData();
<ide>
<ide> String sessionIndex = null;
<ide> SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
<del> Object cacheEntryObj = SAMLSSOSessionIndexCache.getInstance(0).getValueFromCache(cacheKey);
<add> Object cacheEntryObj = SAMLSSOSessionIndexCache.getInstance(CACHE_TIME_OUT).getValueFromCache(cacheKey);
<ide>
<ide> if (cacheEntryObj != null) {
<ide> sessionIndex = ((SAMLSSOSessionIndexCacheEntry) cacheEntryObj).getSessionIndex();
<ide>
<ide> if (key != null) {
<ide> SAMLSSOParticipantCacheKey cacheKey = new SAMLSSOParticipantCacheKey(key);
<del> SAMLSSOParticipantCache.getInstance(0).clearCacheEntry(cacheKey);
<add> SAMLSSOParticipantCache.getInstance(CACHE_TIME_OUT).clearCacheEntry(cacheKey);
<ide> }
<ide> }
<ide>
<ide>
<ide> if (key != null) {
<ide> SAMLSSOSessionIndexCacheKey cacheKey = new SAMLSSOSessionIndexCacheKey(key);
<del> SAMLSSOSessionIndexCache.getInstance(0).clearCacheEntry(cacheKey);
<add> SAMLSSOSessionIndexCache.getInstance(CACHE_TIME_OUT).clearCacheEntry(cacheKey);
<ide> }
<ide> }
<ide>
<ide> }
<ide> sessionInfoData.setSubject(issuer, subject);
<ide> sessionInfoData.addServiceProvider(spDO.getIssuer(), spDO, rpSessionId);
<del> addSessionInfoDataToCache(sessionIndex, sessionInfoData, Integer.parseInt(IdentityUtil.
<del> getProperty("SSOService.SessionIndexCacheTimeout")));
<add> addSessionInfoDataToCache(sessionIndex, sessionInfoData);
<ide>
<ide> }
<ide>
<ide> log.debug("SessionIndex is null.");
<ide> return;
<ide> }
<del> addSessionIndexToCache(tokenId, sessionIndex, Integer.parseInt(IdentityUtil.
<del> getProperty("SSOService.SessionIndexCacheTimeout")));
<add> addSessionIndexToCache(tokenId, sessionIndex);
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | af692899350b75b4bfc25e1460c8f924507cda84 | 0 | wwjiang007/flink,darionyaphet/flink,greghogan/flink,godfreyhe/flink,wwjiang007/flink,lincoln-lil/flink,zjureel/flink,gyfora/flink,fhueske/flink,fhueske/flink,zjureel/flink,zjureel/flink,shaoxuan-wang/flink,twalthr/flink,kl0u/flink,tony810430/flink,mbode/flink,bowenli86/flink,darionyaphet/flink,tony810430/flink,tony810430/flink,sunjincheng121/flink,zentol/flink,xccui/flink,ueshin/apache-flink,bowenli86/flink,godfreyhe/flink,lincoln-lil/flink,darionyaphet/flink,tony810430/flink,bowenli86/flink,tillrohrmann/flink,twalthr/flink,jinglining/flink,lincoln-lil/flink,tzulitai/flink,mbode/flink,tillrohrmann/flink,greghogan/flink,kl0u/flink,hequn8128/flink,tony810430/flink,wwjiang007/flink,twalthr/flink,tillrohrmann/flink,GJL/flink,sunjincheng121/flink,lincoln-lil/flink,tzulitai/flink,fhueske/flink,kaibozhou/flink,gyfora/flink,lincoln-lil/flink,mbode/flink,greghogan/flink,lincoln-lil/flink,zjureel/flink,shaoxuan-wang/flink,tony810430/flink,hequn8128/flink,tzulitai/flink,kaibozhou/flink,bowenli86/flink,fhueske/flink,shaoxuan-wang/flink,GJL/flink,jinglining/flink,kl0u/flink,zentol/flink,apache/flink,tillrohrmann/flink,hequn8128/flink,GJL/flink,zentol/flink,godfreyhe/flink,shaoxuan-wang/flink,kaibozhou/flink,wwjiang007/flink,clarkyzl/flink,bowenli86/flink,StephanEwen/incubator-flink,sunjincheng121/flink,greghogan/flink,rmetzger/flink,aljoscha/flink,zjureel/flink,mbode/flink,StephanEwen/incubator-flink,darionyaphet/flink,godfreyhe/flink,aljoscha/flink,clarkyzl/flink,aljoscha/flink,tzulitai/flink,gyfora/flink,xccui/flink,apache/flink,kl0u/flink,GJL/flink,aljoscha/flink,xccui/flink,StephanEwen/incubator-flink,zjureel/flink,fhueske/flink,StephanEwen/incubator-flink,StephanEwen/incubator-flink,xccui/flink,hequn8128/flink,zentol/flink,kaibozhou/flink,tillrohrmann/flink,clarkyzl/flink,apache/flink,godfreyhe/flink,rmetzger/flink,StephanEwen/incubator-flink,kl0u/flink,kaibozhou/flink,twalthr/flink,apache/flink,jinglining/flink,fhueske/flink,GJL/flink,apache/flink,zentol/flink,ueshin/apache-flink,shaoxuan-wang/flink,sunjincheng121/flink,apache/flink,tony810430/flink,wwjiang007/flink,kaibozhou/flink,shaoxuan-wang/flink,rmetzger/flink,kl0u/flink,rmetzger/flink,sunjincheng121/flink,rmetzger/flink,mbode/flink,zjureel/flink,greghogan/flink,ueshin/apache-flink,greghogan/flink,godfreyhe/flink,gyfora/flink,sunjincheng121/flink,rmetzger/flink,jinglining/flink,aljoscha/flink,rmetzger/flink,gyfora/flink,tzulitai/flink,ueshin/apache-flink,aljoscha/flink,tillrohrmann/flink,twalthr/flink,jinglining/flink,hequn8128/flink,twalthr/flink,tzulitai/flink,zentol/flink,wwjiang007/flink,darionyaphet/flink,GJL/flink,xccui/flink,clarkyzl/flink,hequn8128/flink,godfreyhe/flink,zentol/flink,gyfora/flink,clarkyzl/flink,twalthr/flink,tillrohrmann/flink,jinglining/flink,lincoln-lil/flink,gyfora/flink,apache/flink,bowenli86/flink,xccui/flink,xccui/flink,ueshin/apache-flink,wwjiang007/flink | /*
* 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.flink.runtime.jobmaster;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.CheckpointingOptions;
import org.apache.flink.core.io.InputSplit;
import org.apache.flink.core.io.InputSplitAssigner;
import org.apache.flink.queryablestate.KvStateID;
import org.apache.flink.runtime.JobException;
import org.apache.flink.runtime.StoppingException;
import org.apache.flink.runtime.accumulators.AccumulatorSnapshot;
import org.apache.flink.runtime.blob.BlobWriter;
import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
import org.apache.flink.runtime.checkpoint.CheckpointDeclineReason;
import org.apache.flink.runtime.checkpoint.CheckpointMetrics;
import org.apache.flink.runtime.checkpoint.CheckpointTriggerException;
import org.apache.flink.runtime.checkpoint.Checkpoints;
import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.execution.SuppressRestartsException;
import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
import org.apache.flink.runtime.executiongraph.Execution;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.ExecutionGraph;
import org.apache.flink.runtime.executiongraph.ExecutionGraphBuilder;
import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
import org.apache.flink.runtime.executiongraph.IntermediateResult;
import org.apache.flink.runtime.executiongraph.JobStatusListener;
import org.apache.flink.runtime.executiongraph.restart.RestartStrategy;
import org.apache.flink.runtime.executiongraph.restart.RestartStrategyResolving;
import org.apache.flink.runtime.heartbeat.HeartbeatListener;
import org.apache.flink.runtime.heartbeat.HeartbeatManager;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.heartbeat.HeartbeatTarget;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobStatus;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.jobmanager.OnCompletionActions;
import org.apache.flink.runtime.jobmanager.PartitionProducerDisposedException;
import org.apache.flink.runtime.jobmaster.exceptions.JobModificationException;
import org.apache.flink.runtime.jobmaster.factories.JobManagerJobMetricGroupFactory;
import org.apache.flink.runtime.jobmaster.slotpool.Scheduler;
import org.apache.flink.runtime.jobmaster.slotpool.SchedulerFactory;
import org.apache.flink.runtime.jobmaster.slotpool.SlotPool;
import org.apache.flink.runtime.jobmaster.slotpool.SlotPoolFactory;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalListener;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.messages.FlinkJobNotFoundException;
import org.apache.flink.runtime.messages.checkpoint.AcknowledgeCheckpoint;
import org.apache.flink.runtime.messages.checkpoint.DeclineCheckpoint;
import org.apache.flink.runtime.messages.webmonitor.JobDetails;
import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
import org.apache.flink.runtime.query.KvStateLocation;
import org.apache.flink.runtime.query.KvStateLocationRegistry;
import org.apache.flink.runtime.query.UnknownKvStateLocation;
import org.apache.flink.runtime.registration.RegisteredRpcConnection;
import org.apache.flink.runtime.registration.RegistrationResponse;
import org.apache.flink.runtime.registration.RetryingRegistration;
import org.apache.flink.runtime.resourcemanager.ResourceManagerGateway;
import org.apache.flink.runtime.resourcemanager.ResourceManagerId;
import org.apache.flink.runtime.rest.handler.legacy.backpressure.BackPressureStatsTracker;
import org.apache.flink.runtime.rest.handler.legacy.backpressure.OperatorBackPressureStats;
import org.apache.flink.runtime.rest.handler.legacy.backpressure.OperatorBackPressureStatsResponse;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.FencedRpcEndpoint;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcUtils;
import org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils;
import org.apache.flink.runtime.state.KeyGroupRange;
import org.apache.flink.runtime.taskexecutor.AccumulatorReport;
import org.apache.flink.runtime.taskexecutor.TaskExecutorGateway;
import org.apache.flink.runtime.taskexecutor.slot.SlotOffer;
import org.apache.flink.runtime.taskmanager.TaskExecutionState;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
import org.apache.flink.runtime.webmonitor.WebMonitorUtils;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.InstantiationUtil;
import org.apache.flink.util.Preconditions;
import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeoutException;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* JobMaster implementation. The job master is responsible for the execution of a single
* {@link JobGraph}.
*
* <p>It offers the following methods as part of its rpc interface to interact with the JobMaster
* remotely:
* <ul>
* <li>{@link #updateTaskExecutionState} updates the task execution state for
* given task</li>
* </ul>
*/
public class JobMaster extends FencedRpcEndpoint<JobMasterId> implements JobMasterGateway, JobMasterService {
/** Default names for Flink's distributed components. */
public static final String JOB_MANAGER_NAME = "jobmanager";
public static final String ARCHIVE_NAME = "archive";
// ------------------------------------------------------------------------
private final JobMasterConfiguration jobMasterConfiguration;
private final ResourceID resourceId;
private final JobGraph jobGraph;
private final Time rpcTimeout;
private final HighAvailabilityServices highAvailabilityServices;
private final BlobWriter blobWriter;
private final JobManagerJobMetricGroupFactory jobMetricGroupFactory;
private final HeartbeatManager<AccumulatorReport, Void> taskManagerHeartbeatManager;
private final HeartbeatManager<Void, Void> resourceManagerHeartbeatManager;
private final ScheduledExecutorService scheduledExecutorService;
private final OnCompletionActions jobCompletionActions;
private final FatalErrorHandler fatalErrorHandler;
private final ClassLoader userCodeLoader;
private final SlotPool slotPool;
private final Scheduler scheduler;
private final RestartStrategy restartStrategy;
// --------- BackPressure --------
private final BackPressureStatsTracker backPressureStatsTracker;
// --------- ResourceManager --------
private final LeaderRetrievalService resourceManagerLeaderRetriever;
// --------- TaskManagers --------
private final Map<ResourceID, Tuple2<TaskManagerLocation, TaskExecutorGateway>> registeredTaskManagers;
// -------- Mutable fields ---------
private ExecutionGraph executionGraph;
@Nullable
private JobManagerJobStatusListener jobStatusListener;
@Nullable
private JobManagerJobMetricGroup jobManagerJobMetricGroup;
@Nullable
private String lastInternalSavepoint;
@Nullable
private ResourceManagerAddress resourceManagerAddress;
@Nullable
private ResourceManagerConnection resourceManagerConnection;
@Nullable
private EstablishedResourceManagerConnection establishedResourceManagerConnection;
private Map<String, Object> accumulators;
// ------------------------------------------------------------------------
public JobMaster(
RpcService rpcService,
JobMasterConfiguration jobMasterConfiguration,
ResourceID resourceId,
JobGraph jobGraph,
HighAvailabilityServices highAvailabilityService,
SlotPoolFactory slotPoolFactory,
SchedulerFactory schedulerFactory,
JobManagerSharedServices jobManagerSharedServices,
HeartbeatServices heartbeatServices,
JobManagerJobMetricGroupFactory jobMetricGroupFactory,
OnCompletionActions jobCompletionActions,
FatalErrorHandler fatalErrorHandler,
ClassLoader userCodeLoader) throws Exception {
super(rpcService, AkkaRpcServiceUtils.createRandomName(JOB_MANAGER_NAME));
final JobMasterGateway selfGateway = getSelfGateway(JobMasterGateway.class);
this.jobMasterConfiguration = checkNotNull(jobMasterConfiguration);
this.resourceId = checkNotNull(resourceId);
this.jobGraph = checkNotNull(jobGraph);
this.rpcTimeout = jobMasterConfiguration.getRpcTimeout();
this.highAvailabilityServices = checkNotNull(highAvailabilityService);
this.blobWriter = jobManagerSharedServices.getBlobWriter();
this.scheduledExecutorService = jobManagerSharedServices.getScheduledExecutorService();
this.jobCompletionActions = checkNotNull(jobCompletionActions);
this.fatalErrorHandler = checkNotNull(fatalErrorHandler);
this.userCodeLoader = checkNotNull(userCodeLoader);
this.jobMetricGroupFactory = checkNotNull(jobMetricGroupFactory);
this.taskManagerHeartbeatManager = heartbeatServices.createHeartbeatManagerSender(
resourceId,
new TaskManagerHeartbeatListener(selfGateway),
rpcService.getScheduledExecutor(),
log);
this.resourceManagerHeartbeatManager = heartbeatServices.createHeartbeatManager(
resourceId,
new ResourceManagerHeartbeatListener(),
rpcService.getScheduledExecutor(),
log);
final String jobName = jobGraph.getName();
final JobID jid = jobGraph.getJobID();
log.info("Initializing job {} ({}).", jobName, jid);
final RestartStrategies.RestartStrategyConfiguration restartStrategyConfiguration =
jobGraph.getSerializedExecutionConfig()
.deserializeValue(userCodeLoader)
.getRestartStrategy();
this.restartStrategy = RestartStrategyResolving.resolve(restartStrategyConfiguration,
jobManagerSharedServices.getRestartStrategyFactory(),
jobGraph.isCheckpointingEnabled());
log.info("Using restart strategy {} for {} ({}).", this.restartStrategy, jobName, jid);
resourceManagerLeaderRetriever = highAvailabilityServices.getResourceManagerLeaderRetriever();
this.slotPool = checkNotNull(slotPoolFactory).createSlotPool(jobGraph.getJobID());
this.scheduler = checkNotNull(schedulerFactory).createScheduler(slotPool);
this.registeredTaskManagers = new HashMap<>(4);
this.backPressureStatsTracker = checkNotNull(jobManagerSharedServices.getBackPressureStatsTracker());
this.lastInternalSavepoint = null;
this.jobManagerJobMetricGroup = jobMetricGroupFactory.create(jobGraph);
this.executionGraph = createAndRestoreExecutionGraph(jobManagerJobMetricGroup);
this.jobStatusListener = null;
this.resourceManagerConnection = null;
this.establishedResourceManagerConnection = null;
this.accumulators = new HashMap<>();
}
//----------------------------------------------------------------------------------------------
// Lifecycle management
//----------------------------------------------------------------------------------------------
/**
* Start the rpc service and begin to run the job.
*
* @param newJobMasterId The necessary fencing token to run the job
* @return Future acknowledge if the job could be started. Otherwise the future contains an exception
*/
public CompletableFuture<Acknowledge> start(final JobMasterId newJobMasterId) throws Exception {
// make sure we receive RPC and async calls
start();
return callAsyncWithoutFencing(() -> startJobExecution(newJobMasterId), RpcUtils.INF_TIMEOUT);
}
/**
* Suspending job, all the running tasks will be cancelled, and communication with other components
* will be disposed.
*
* <p>Mostly job is suspended because of the leadership has been revoked, one can be restart this job by
* calling the {@link #start(JobMasterId)} method once we take the leadership back again.
*
* <p>This method is executed asynchronously
*
* @param cause The reason of why this job been suspended.
* @return Future acknowledge indicating that the job has been suspended. Otherwise the future contains an exception
*/
public CompletableFuture<Acknowledge> suspend(final Exception cause) {
CompletableFuture<Acknowledge> suspendFuture = callAsyncWithoutFencing(
() -> suspendExecution(cause),
RpcUtils.INF_TIMEOUT);
return suspendFuture.whenComplete((acknowledge, throwable) -> stop());
}
/**
* Suspend the job and shutdown all other services including rpc.
*/
@Override
public CompletableFuture<Void> onStop() {
log.info("Stopping the JobMaster for job {}({}).", jobGraph.getName(), jobGraph.getJobID());
// disconnect from all registered TaskExecutors
final Set<ResourceID> taskManagerResourceIds = new HashSet<>(registeredTaskManagers.keySet());
final FlinkException cause = new FlinkException("Stopping JobMaster for job " + jobGraph.getName() +
'(' + jobGraph.getJobID() + ").");
for (ResourceID taskManagerResourceId : taskManagerResourceIds) {
disconnectTaskManager(taskManagerResourceId, cause);
}
taskManagerHeartbeatManager.stop();
resourceManagerHeartbeatManager.stop();
// make sure there is a graceful exit
suspendExecution(new FlinkException("JobManager is shutting down."));
// shut down will internally release all registered slots
slotPool.close();
final CompletableFuture<Void> disposeInternalSavepointFuture;
if (lastInternalSavepoint != null) {
disposeInternalSavepointFuture = CompletableFuture.runAsync(() -> disposeSavepoint(lastInternalSavepoint));
} else {
disposeInternalSavepointFuture = CompletableFuture.completedFuture(null);
}
return FutureUtils.completeAll(Collections.singletonList(disposeInternalSavepointFuture));
}
//----------------------------------------------------------------------------------------------
// RPC methods
//----------------------------------------------------------------------------------------------
@Override
public CompletableFuture<Acknowledge> cancel(Time timeout) {
executionGraph.cancel();
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> stop(Time timeout) {
try {
executionGraph.stop();
} catch (StoppingException e) {
return FutureUtils.completedExceptionally(e);
}
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> rescaleJob(
int newParallelism,
RescalingBehaviour rescalingBehaviour,
Time timeout) {
final ArrayList<JobVertexID> allOperators = new ArrayList<>(jobGraph.getNumberOfVertices());
for (JobVertex jobVertex : jobGraph.getVertices()) {
allOperators.add(jobVertex.getID());
}
return rescaleOperators(allOperators, newParallelism, rescalingBehaviour, timeout);
}
@Override
public CompletableFuture<Acknowledge> rescaleOperators(
Collection<JobVertexID> operators,
int newParallelism,
RescalingBehaviour rescalingBehaviour,
Time timeout) {
if (newParallelism <= 0) {
return FutureUtils.completedExceptionally(
new JobModificationException("The target parallelism of a rescaling operation must be larger than 0."));
}
// 1. Check whether we can rescale the job & rescale the respective vertices
try {
rescaleJobGraph(operators, newParallelism, rescalingBehaviour);
} catch (FlinkException e) {
final String msg = String.format("Cannot rescale job %s.", jobGraph.getName());
log.info(msg, e);
return FutureUtils.completedExceptionally(new JobModificationException(msg, e));
}
final ExecutionGraph currentExecutionGraph = executionGraph;
final JobManagerJobMetricGroup newJobManagerJobMetricGroup = jobMetricGroupFactory.create(jobGraph);
final ExecutionGraph newExecutionGraph;
try {
newExecutionGraph = createExecutionGraph(newJobManagerJobMetricGroup);
} catch (JobExecutionException | JobException e) {
return FutureUtils.completedExceptionally(
new JobModificationException("Could not create rescaled ExecutionGraph.", e));
}
// 3. disable checkpoint coordinator to suppress subsequent checkpoints
final CheckpointCoordinator checkpointCoordinator = currentExecutionGraph.getCheckpointCoordinator();
checkpointCoordinator.stopCheckpointScheduler();
// 4. take a savepoint
final CompletableFuture<String> savepointFuture = getJobModificationSavepoint(timeout);
final CompletableFuture<ExecutionGraph> executionGraphFuture = restoreExecutionGraphFromRescalingSavepoint(
newExecutionGraph,
savepointFuture)
.handleAsync(
(ExecutionGraph executionGraph, Throwable failure) -> {
if (failure != null) {
// in case that we couldn't take a savepoint or restore from it, let's restart the checkpoint
// coordinator and abort the rescaling operation
if (checkpointCoordinator.isPeriodicCheckpointingConfigured()) {
checkpointCoordinator.startCheckpointScheduler();
}
throw new CompletionException(ExceptionUtils.stripCompletionException(failure));
} else {
return executionGraph;
}
},
getMainThreadExecutor());
// 5. suspend the current job
final CompletableFuture<JobStatus> terminationFuture = executionGraphFuture.thenComposeAsync(
(ExecutionGraph ignored) -> {
suspendExecutionGraph(new FlinkException("Job is being rescaled."));
return currentExecutionGraph.getTerminationFuture();
},
getMainThreadExecutor());
final CompletableFuture<Void> suspendedFuture = terminationFuture.thenAccept(
(JobStatus jobStatus) -> {
if (jobStatus != JobStatus.SUSPENDED) {
final String msg = String.format("Job %s rescaling failed because we could not suspend the execution graph.", jobGraph.getName());
log.info(msg);
throw new CompletionException(new JobModificationException(msg));
}
});
// 6. resume the new execution graph from the taken savepoint
final CompletableFuture<Acknowledge> rescalingFuture = suspendedFuture.thenCombineAsync(
executionGraphFuture,
(Void ignored, ExecutionGraph restoredExecutionGraph) -> {
// check if the ExecutionGraph is still the same
if (executionGraph == currentExecutionGraph) {
clearExecutionGraphFields();
assignExecutionGraph(restoredExecutionGraph, newJobManagerJobMetricGroup);
scheduleExecutionGraph();
return Acknowledge.get();
} else {
throw new CompletionException(new JobModificationException("Detected concurrent modification of ExecutionGraph. Aborting the rescaling."));
}
},
getMainThreadExecutor());
rescalingFuture.whenCompleteAsync(
(Acknowledge ignored, Throwable throwable) -> {
if (throwable != null) {
// fail the newly created execution graph
newExecutionGraph.failGlobal(
new SuppressRestartsException(
new FlinkException(
String.format("Failed to rescale the job %s.", jobGraph.getJobID()),
throwable)));
}
}, getMainThreadExecutor());
return rescalingFuture;
}
/**
* Updates the task execution state for a given task.
*
* @param taskExecutionState New task execution state for a given task
* @return Acknowledge the task execution state update
*/
@Override
public CompletableFuture<Acknowledge> updateTaskExecutionState(
final TaskExecutionState taskExecutionState) {
checkNotNull(taskExecutionState, "taskExecutionState");
if (executionGraph.updateState(taskExecutionState)) {
return CompletableFuture.completedFuture(Acknowledge.get());
} else {
return FutureUtils.completedExceptionally(
new ExecutionGraphException("The execution attempt " +
taskExecutionState.getID() + " was not found."));
}
}
@Override
public CompletableFuture<SerializedInputSplit> requestNextInputSplit(
final JobVertexID vertexID,
final ExecutionAttemptID executionAttempt) {
final Execution execution = executionGraph.getRegisteredExecutions().get(executionAttempt);
if (execution == null) {
// can happen when JobManager had already unregistered this execution upon on task failure,
// but TaskManager get some delay to aware of that situation
if (log.isDebugEnabled()) {
log.debug("Can not find Execution for attempt {}.", executionAttempt);
}
// but we should TaskManager be aware of this
return FutureUtils.completedExceptionally(new Exception("Can not find Execution for attempt " + executionAttempt));
}
final ExecutionJobVertex vertex = executionGraph.getJobVertex(vertexID);
if (vertex == null) {
log.error("Cannot find execution vertex for vertex ID {}.", vertexID);
return FutureUtils.completedExceptionally(new Exception("Cannot find execution vertex for vertex ID " + vertexID));
}
final InputSplitAssigner splitAssigner = vertex.getSplitAssigner();
if (splitAssigner == null) {
log.error("No InputSplitAssigner for vertex ID {}.", vertexID);
return FutureUtils.completedExceptionally(new Exception("No InputSplitAssigner for vertex ID " + vertexID));
}
final LogicalSlot slot = execution.getAssignedResource();
final int taskId = execution.getVertex().getParallelSubtaskIndex();
final String host = slot != null ? slot.getTaskManagerLocation().getHostname() : null;
final InputSplit nextInputSplit = splitAssigner.getNextInputSplit(host, taskId);
if (log.isDebugEnabled()) {
log.debug("Send next input split {}.", nextInputSplit);
}
try {
final byte[] serializedInputSplit = InstantiationUtil.serializeObject(nextInputSplit);
return CompletableFuture.completedFuture(new SerializedInputSplit(serializedInputSplit));
} catch (Exception ex) {
log.error("Could not serialize the next input split of class {}.", nextInputSplit.getClass(), ex);
IOException reason = new IOException("Could not serialize the next input split of class " +
nextInputSplit.getClass() + ".", ex);
vertex.fail(reason);
return FutureUtils.completedExceptionally(reason);
}
}
@Override
public CompletableFuture<ExecutionState> requestPartitionState(
final IntermediateDataSetID intermediateResultId,
final ResultPartitionID resultPartitionId) {
final Execution execution = executionGraph.getRegisteredExecutions().get(resultPartitionId.getProducerId());
if (execution != null) {
return CompletableFuture.completedFuture(execution.getState());
}
else {
final IntermediateResult intermediateResult =
executionGraph.getAllIntermediateResults().get(intermediateResultId);
if (intermediateResult != null) {
// Try to find the producing execution
Execution producerExecution = intermediateResult
.getPartitionById(resultPartitionId.getPartitionId())
.getProducer()
.getCurrentExecutionAttempt();
if (producerExecution.getAttemptId().equals(resultPartitionId.getProducerId())) {
return CompletableFuture.completedFuture(producerExecution.getState());
} else {
return FutureUtils.completedExceptionally(new PartitionProducerDisposedException(resultPartitionId));
}
} else {
return FutureUtils.completedExceptionally(new IllegalArgumentException("Intermediate data set with ID "
+ intermediateResultId + " not found."));
}
}
}
@Override
public CompletableFuture<Acknowledge> scheduleOrUpdateConsumers(
final ResultPartitionID partitionID,
final Time timeout) {
try {
executionGraph.scheduleOrUpdateConsumers(partitionID);
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (Exception e) {
return FutureUtils.completedExceptionally(e);
}
}
@Override
public CompletableFuture<Acknowledge> disconnectTaskManager(final ResourceID resourceID, final Exception cause) {
log.debug("Disconnect TaskExecutor {} because: {}", resourceID, cause.getMessage());
taskManagerHeartbeatManager.unmonitorTarget(resourceID);
slotPool.releaseTaskManager(resourceID, cause);
Tuple2<TaskManagerLocation, TaskExecutorGateway> taskManagerConnection = registeredTaskManagers.remove(resourceID);
if (taskManagerConnection != null) {
taskManagerConnection.f1.disconnectJobManager(jobGraph.getJobID(), cause);
}
return CompletableFuture.completedFuture(Acknowledge.get());
}
// TODO: This method needs a leader session ID
@Override
public void acknowledgeCheckpoint(
final JobID jobID,
final ExecutionAttemptID executionAttemptID,
final long checkpointId,
final CheckpointMetrics checkpointMetrics,
final TaskStateSnapshot checkpointState) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
final AcknowledgeCheckpoint ackMessage = new AcknowledgeCheckpoint(
jobID,
executionAttemptID,
checkpointId,
checkpointMetrics,
checkpointState);
if (checkpointCoordinator != null) {
getRpcService().execute(() -> {
try {
checkpointCoordinator.receiveAcknowledgeMessage(ackMessage);
} catch (Throwable t) {
log.warn("Error while processing checkpoint acknowledgement message", t);
}
});
} else {
String errorMessage = "Received AcknowledgeCheckpoint message for job {} with no CheckpointCoordinator";
if (executionGraph.getState() == JobStatus.RUNNING) {
log.error(errorMessage, jobGraph.getJobID());
} else {
log.debug(errorMessage, jobGraph.getJobID());
}
}
}
// TODO: This method needs a leader session ID
@Override
public void declineCheckpoint(DeclineCheckpoint decline) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
getRpcService().execute(() -> {
try {
checkpointCoordinator.receiveDeclineMessage(decline);
} catch (Exception e) {
log.error("Error in CheckpointCoordinator while processing {}", decline, e);
}
});
} else {
String errorMessage = "Received DeclineCheckpoint message for job {} with no CheckpointCoordinator";
if (executionGraph.getState() == JobStatus.RUNNING) {
log.error(errorMessage, jobGraph.getJobID());
} else {
log.debug(errorMessage, jobGraph.getJobID());
}
}
}
@Override
public CompletableFuture<KvStateLocation> requestKvStateLocation(final JobID jobId, final String registrationName) {
// sanity check for the correct JobID
if (jobGraph.getJobID().equals(jobId)) {
if (log.isDebugEnabled()) {
log.debug("Lookup key-value state for job {} with registration " +
"name {}.", jobGraph.getJobID(), registrationName);
}
final KvStateLocationRegistry registry = executionGraph.getKvStateLocationRegistry();
final KvStateLocation location = registry.getKvStateLocation(registrationName);
if (location != null) {
return CompletableFuture.completedFuture(location);
} else {
return FutureUtils.completedExceptionally(new UnknownKvStateLocation(registrationName));
}
} else {
if (log.isDebugEnabled()) {
log.debug("Request of key-value state location for unknown job {} received.", jobId);
}
return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
}
}
@Override
public CompletableFuture<Acknowledge> notifyKvStateRegistered(
final JobID jobId,
final JobVertexID jobVertexId,
final KeyGroupRange keyGroupRange,
final String registrationName,
final KvStateID kvStateId,
final InetSocketAddress kvStateServerAddress) {
if (jobGraph.getJobID().equals(jobId)) {
if (log.isDebugEnabled()) {
log.debug("Key value state registered for job {} under name {}.",
jobGraph.getJobID(), registrationName);
}
try {
executionGraph.getKvStateLocationRegistry().notifyKvStateRegistered(
jobVertexId, keyGroupRange, registrationName, kvStateId, kvStateServerAddress);
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (Exception e) {
log.error("Failed to notify KvStateRegistry about registration {}.", registrationName, e);
return FutureUtils.completedExceptionally(e);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Notification about key-value state registration for unknown job {} received.", jobId);
}
return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
}
}
@Override
public CompletableFuture<Acknowledge> notifyKvStateUnregistered(
JobID jobId,
JobVertexID jobVertexId,
KeyGroupRange keyGroupRange,
String registrationName) {
if (jobGraph.getJobID().equals(jobId)) {
if (log.isDebugEnabled()) {
log.debug("Key value state unregistered for job {} under name {}.",
jobGraph.getJobID(), registrationName);
}
try {
executionGraph.getKvStateLocationRegistry().notifyKvStateUnregistered(
jobVertexId, keyGroupRange, registrationName);
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (Exception e) {
log.error("Failed to notify KvStateRegistry about unregistration {}.", registrationName, e);
return FutureUtils.completedExceptionally(e);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Notification about key-value state deregistration for unknown job {} received.", jobId);
}
return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
}
}
@Override
public CompletableFuture<Collection<SlotOffer>> offerSlots(
final ResourceID taskManagerId,
final Collection<SlotOffer> slots,
final Time timeout) {
Tuple2<TaskManagerLocation, TaskExecutorGateway> taskManager = registeredTaskManagers.get(taskManagerId);
if (taskManager == null) {
return FutureUtils.completedExceptionally(new Exception("Unknown TaskManager " + taskManagerId));
}
final TaskManagerLocation taskManagerLocation = taskManager.f0;
final TaskExecutorGateway taskExecutorGateway = taskManager.f1;
final RpcTaskManagerGateway rpcTaskManagerGateway = new RpcTaskManagerGateway(taskExecutorGateway, getFencingToken());
return CompletableFuture.completedFuture(
slotPool.offerSlots(
taskManagerLocation,
rpcTaskManagerGateway,
slots));
}
@Override
public void failSlot(
final ResourceID taskManagerId,
final AllocationID allocationId,
final Exception cause) {
if (registeredTaskManagers.containsKey(taskManagerId)) {
internalFailAllocation(allocationId, cause);
} else {
log.warn("Cannot fail slot " + allocationId + " because the TaskManager " +
taskManagerId + " is unknown.");
}
}
private void internalFailAllocation(AllocationID allocationId, Exception cause) {
final Optional<ResourceID> resourceIdOptional = slotPool.failAllocation(allocationId, cause);
resourceIdOptional.ifPresent(this::releaseEmptyTaskManager);
}
private void releaseEmptyTaskManager(ResourceID resourceId) {
disconnectTaskManager(resourceId, new FlinkException(String.format("No more slots registered at JobMaster %s.", resourceId)));
}
@Override
public CompletableFuture<RegistrationResponse> registerTaskManager(
final String taskManagerRpcAddress,
final TaskManagerLocation taskManagerLocation,
final Time timeout) {
final ResourceID taskManagerId = taskManagerLocation.getResourceID();
if (registeredTaskManagers.containsKey(taskManagerId)) {
final RegistrationResponse response = new JMTMRegistrationSuccess(resourceId);
return CompletableFuture.completedFuture(response);
} else {
return getRpcService()
.connect(taskManagerRpcAddress, TaskExecutorGateway.class)
.handleAsync(
(TaskExecutorGateway taskExecutorGateway, Throwable throwable) -> {
if (throwable != null) {
return new RegistrationResponse.Decline(throwable.getMessage());
}
slotPool.registerTaskManager(taskManagerId);
registeredTaskManagers.put(taskManagerId, Tuple2.of(taskManagerLocation, taskExecutorGateway));
// monitor the task manager as heartbeat target
taskManagerHeartbeatManager.monitorTarget(taskManagerId, new HeartbeatTarget<Void>() {
@Override
public void receiveHeartbeat(ResourceID resourceID, Void payload) {
// the task manager will not request heartbeat, so this method will never be called currently
}
@Override
public void requestHeartbeat(ResourceID resourceID, Void payload) {
taskExecutorGateway.heartbeatFromJobManager(resourceID);
}
});
return new JMTMRegistrationSuccess(resourceId);
},
getMainThreadExecutor());
}
}
@Override
public void disconnectResourceManager(
final ResourceManagerId resourceManagerId,
final Exception cause) {
if (isConnectingToResourceManager(resourceManagerId)) {
reconnectToResourceManager(cause);
}
}
private boolean isConnectingToResourceManager(ResourceManagerId resourceManagerId) {
return resourceManagerAddress != null
&& resourceManagerAddress.getResourceManagerId().equals(resourceManagerId);
}
@Override
public void heartbeatFromTaskManager(final ResourceID resourceID, AccumulatorReport accumulatorReport) {
taskManagerHeartbeatManager.receiveHeartbeat(resourceID, accumulatorReport);
}
@Override
public void heartbeatFromResourceManager(final ResourceID resourceID) {
resourceManagerHeartbeatManager.requestHeartbeat(resourceID, null);
}
@Override
public CompletableFuture<JobDetails> requestJobDetails(Time timeout) {
final ExecutionGraph currentExecutionGraph = executionGraph;
return CompletableFuture.supplyAsync(() -> WebMonitorUtils.createDetailsForJob(currentExecutionGraph), scheduledExecutorService);
}
@Override
public CompletableFuture<JobStatus> requestJobStatus(Time timeout) {
return CompletableFuture.completedFuture(executionGraph.getState());
}
@Override
public CompletableFuture<ArchivedExecutionGraph> requestJob(Time timeout) {
return CompletableFuture.completedFuture(ArchivedExecutionGraph.createFrom(executionGraph));
}
@Override
public CompletableFuture<String> triggerSavepoint(
@Nullable final String targetDirectory,
final boolean cancelJob,
final Time timeout) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
if (checkpointCoordinator == null) {
return FutureUtils.completedExceptionally(new IllegalStateException(
String.format("Job %s is not a streaming job.", jobGraph.getJobID())));
} else if (targetDirectory == null && !checkpointCoordinator.getCheckpointStorage().hasDefaultSavepointLocation()) {
log.info("Trying to cancel job {} with savepoint, but no savepoint directory configured.", jobGraph.getJobID());
return FutureUtils.completedExceptionally(new IllegalStateException(
"No savepoint directory configured. You can either specify a directory " +
"while cancelling via -s :targetDirectory or configure a cluster-wide " +
"default via key '" + CheckpointingOptions.SAVEPOINT_DIRECTORY.key() + "'."));
}
if (cancelJob) {
checkpointCoordinator.stopCheckpointScheduler();
}
return checkpointCoordinator
.triggerSavepoint(System.currentTimeMillis(), targetDirectory)
.thenApply(CompletedCheckpoint::getExternalPointer)
.handleAsync((path, throwable) -> {
if (throwable != null) {
if (cancelJob) {
startCheckpointScheduler(checkpointCoordinator);
}
throw new CompletionException(throwable);
} else if (cancelJob) {
log.info("Savepoint stored in {}. Now cancelling {}.", path, jobGraph.getJobID());
cancel(timeout);
}
return path;
}, getMainThreadExecutor());
}
private void startCheckpointScheduler(final CheckpointCoordinator checkpointCoordinator) {
if (checkpointCoordinator.isPeriodicCheckpointingConfigured()) {
try {
checkpointCoordinator.startCheckpointScheduler();
} catch (IllegalStateException ignored) {
// Concurrent shut down of the coordinator
}
}
}
@Override
public CompletableFuture<OperatorBackPressureStatsResponse> requestOperatorBackPressureStats(final JobVertexID jobVertexId) {
final ExecutionJobVertex jobVertex = executionGraph.getJobVertex(jobVertexId);
if (jobVertex == null) {
return FutureUtils.completedExceptionally(new FlinkException("JobVertexID not found " +
jobVertexId));
}
final Optional<OperatorBackPressureStats> operatorBackPressureStats =
backPressureStatsTracker.getOperatorBackPressureStats(jobVertex);
return CompletableFuture.completedFuture(OperatorBackPressureStatsResponse.of(
operatorBackPressureStats.orElse(null)));
}
@Override
public void notifyAllocationFailure(AllocationID allocationID, Exception cause) {
internalFailAllocation(allocationID, cause);
}
@Override
public CompletableFuture<Object> updateGlobalAggregate(String aggregateName, Object aggregand, byte[] serializedAggregateFunction) {
AggregateFunction aggregateFunction = null;
try {
aggregateFunction = InstantiationUtil.deserializeObject(serializedAggregateFunction, userCodeLoader);
} catch (Exception e) {
log.error("Error while attempting to deserialize user AggregateFunction.");
return FutureUtils.completedExceptionally(e);
}
Object accumulator = accumulators.get(aggregateName);
if(null == accumulator) {
accumulator = aggregateFunction.createAccumulator();
}
accumulator = aggregateFunction.add(aggregand, accumulator);
accumulators.put(aggregateName, accumulator);
return CompletableFuture.completedFuture(aggregateFunction.getResult(accumulator));
}
//----------------------------------------------------------------------------------------------
// Internal methods
//----------------------------------------------------------------------------------------------
//-- job starting and stopping -----------------------------------------------------------------
private Acknowledge startJobExecution(JobMasterId newJobMasterId) throws Exception {
validateRunsInMainThread();
checkNotNull(newJobMasterId, "The new JobMasterId must not be null.");
if (Objects.equals(getFencingToken(), newJobMasterId)) {
log.info("Already started the job execution with JobMasterId {}.", newJobMasterId);
return Acknowledge.get();
}
setNewFencingToken(newJobMasterId);
startJobMasterServices();
log.info("Starting execution of job {} ({}) under job master id {}.", jobGraph.getName(), jobGraph.getJobID(), newJobMasterId);
resetAndScheduleExecutionGraph();
return Acknowledge.get();
}
private void startJobMasterServices() throws Exception {
// start the slot pool make sure the slot pool now accepts messages for this leader
slotPool.start(getFencingToken(), getAddress(), getMainThreadExecutor());
scheduler.start(getMainThreadExecutor());
//TODO: Remove once the ZooKeeperLeaderRetrieval returns the stored address upon start
// try to reconnect to previously known leader
reconnectToResourceManager(new FlinkException("Starting JobMaster component."));
// job is ready to go, try to establish connection with resource manager
// - activate leader retrieval for the resource manager
// - on notification of the leader, the connection will be established and
// the slot pool will start requesting slots
resourceManagerLeaderRetriever.start(new ResourceManagerLeaderListener());
}
private void setNewFencingToken(JobMasterId newJobMasterId) {
if (getFencingToken() != null) {
log.info("Restarting old job with JobMasterId {}. The new JobMasterId is {}.", getFencingToken(), newJobMasterId);
// first we have to suspend the current execution
suspendExecution(new FlinkException("Old job with JobMasterId " + getFencingToken() +
" is restarted with a new JobMasterId " + newJobMasterId + '.'));
}
// set new leader id
setFencingToken(newJobMasterId);
}
/**
* Suspending job, all the running tasks will be cancelled, and communication with other components
* will be disposed.
*
* <p>Mostly job is suspended because of the leadership has been revoked, one can be restart this job by
* calling the {@link #start(JobMasterId)} method once we take the leadership back again.
*
* @param cause The reason of why this job been suspended.
*/
private Acknowledge suspendExecution(final Exception cause) {
validateRunsInMainThread();
if (getFencingToken() == null) {
log.debug("Job has already been suspended or shutdown.");
return Acknowledge.get();
}
// not leader anymore --> set the JobMasterId to null
setFencingToken(null);
try {
resourceManagerLeaderRetriever.stop();
resourceManagerAddress = null;
} catch (Throwable t) {
log.warn("Failed to stop resource manager leader retriever when suspending.", t);
}
suspendAndClearExecutionGraphFields(cause);
// the slot pool stops receiving messages and clears its pooled slots
slotPool.suspend();
// disconnect from resource manager:
closeResourceManagerConnection(cause);
return Acknowledge.get();
}
private void assignExecutionGraph(
ExecutionGraph newExecutionGraph,
JobManagerJobMetricGroup newJobManagerJobMetricGroup) {
validateRunsInMainThread();
checkState(executionGraph.getState().isTerminalState());
checkState(jobManagerJobMetricGroup == null);
executionGraph = newExecutionGraph;
jobManagerJobMetricGroup = newJobManagerJobMetricGroup;
}
private void resetAndScheduleExecutionGraph() throws Exception {
validateRunsInMainThread();
final CompletableFuture<Void> executionGraphAssignedFuture;
if (executionGraph.getState() == JobStatus.CREATED) {
executionGraphAssignedFuture = CompletableFuture.completedFuture(null);
executionGraph.start(getMainThreadExecutor());
} else {
suspendAndClearExecutionGraphFields(new FlinkException("ExecutionGraph is being reset in order to be rescheduled."));
final JobManagerJobMetricGroup newJobManagerJobMetricGroup = jobMetricGroupFactory.create(jobGraph);
final ExecutionGraph newExecutionGraph = createAndRestoreExecutionGraph(newJobManagerJobMetricGroup);
executionGraphAssignedFuture = executionGraph.getTerminationFuture().handle(
(JobStatus ignored, Throwable throwable) -> {
newExecutionGraph.start(getMainThreadExecutor());
assignExecutionGraph(newExecutionGraph, newJobManagerJobMetricGroup);
return null;
});
}
executionGraphAssignedFuture.thenRun(this::scheduleExecutionGraph);
}
private void scheduleExecutionGraph() {
checkState(jobStatusListener == null);
// register self as job status change listener
jobStatusListener = new JobManagerJobStatusListener();
executionGraph.registerJobStatusListener(jobStatusListener);
try {
executionGraph.scheduleForExecution();
}
catch (Throwable t) {
executionGraph.failGlobal(t);
}
}
private ExecutionGraph createAndRestoreExecutionGraph(JobManagerJobMetricGroup currentJobManagerJobMetricGroup) throws Exception {
ExecutionGraph newExecutionGraph = createExecutionGraph(currentJobManagerJobMetricGroup);
final CheckpointCoordinator checkpointCoordinator = newExecutionGraph.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
// check whether we find a valid checkpoint
if (!checkpointCoordinator.restoreLatestCheckpointedState(
newExecutionGraph.getAllVertices(),
false,
false)) {
// check whether we can restore from a savepoint
tryRestoreExecutionGraphFromSavepoint(newExecutionGraph, jobGraph.getSavepointRestoreSettings());
}
}
return newExecutionGraph;
}
private ExecutionGraph createExecutionGraph(JobManagerJobMetricGroup currentJobManagerJobMetricGroup) throws JobExecutionException, JobException {
return ExecutionGraphBuilder.buildGraph(
null,
jobGraph,
jobMasterConfiguration.getConfiguration(),
scheduledExecutorService,
scheduledExecutorService,
scheduler,
userCodeLoader,
highAvailabilityServices.getCheckpointRecoveryFactory(),
rpcTimeout,
restartStrategy,
currentJobManagerJobMetricGroup,
blobWriter,
jobMasterConfiguration.getSlotRequestTimeout(),
log);
}
private void suspendAndClearExecutionGraphFields(Exception cause) {
suspendExecutionGraph(cause);
clearExecutionGraphFields();
}
private void suspendExecutionGraph(Exception cause) {
executionGraph.suspend(cause);
if (jobManagerJobMetricGroup != null) {
jobManagerJobMetricGroup.close();
}
if (jobStatusListener != null) {
jobStatusListener.stop();
}
}
private void clearExecutionGraphFields() {
jobManagerJobMetricGroup = null;
jobStatusListener = null;
}
/**
* Dispose the savepoint stored under the given path.
*
* @param savepointPath path where the savepoint is stored
*/
private void disposeSavepoint(String savepointPath) {
try {
// delete the temporary savepoint
Checkpoints.disposeSavepoint(
savepointPath,
jobMasterConfiguration.getConfiguration(),
userCodeLoader,
log);
} catch (FlinkException | IOException e) {
log.info("Could not dispose temporary rescaling savepoint under {}.", savepointPath, e);
}
}
/**
* Tries to restore the given {@link ExecutionGraph} from the provided {@link SavepointRestoreSettings}.
*
* @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored
* @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about the savepoint to restore from
* @throws Exception if the {@link ExecutionGraph} could not be restored
*/
private void tryRestoreExecutionGraphFromSavepoint(ExecutionGraph executionGraphToRestore, SavepointRestoreSettings savepointRestoreSettings) throws Exception {
if (savepointRestoreSettings.restoreSavepoint()) {
final CheckpointCoordinator checkpointCoordinator = executionGraphToRestore.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
checkpointCoordinator.restoreSavepoint(
savepointRestoreSettings.getRestorePath(),
savepointRestoreSettings.allowNonRestoredState(),
executionGraphToRestore.getAllVertices(),
userCodeLoader);
}
}
}
//----------------------------------------------------------------------------------------------
private void handleJobMasterError(final Throwable cause) {
if (ExceptionUtils.isJvmFatalError(cause)) {
log.error("Fatal error occurred on JobManager.", cause);
// The fatal error handler implementation should make sure that this call is non-blocking
fatalErrorHandler.onFatalError(cause);
} else {
jobCompletionActions.jobMasterFailed(cause);
}
}
private void jobStatusChanged(
final JobStatus newJobStatus,
long timestamp,
@Nullable final Throwable error) {
validateRunsInMainThread();
if (newJobStatus.isGloballyTerminalState()) {
final ArchivedExecutionGraph archivedExecutionGraph = ArchivedExecutionGraph.createFrom(executionGraph);
scheduledExecutorService.execute(() -> jobCompletionActions.jobReachedGloballyTerminalState(archivedExecutionGraph));
}
}
private void notifyOfNewResourceManagerLeader(final String newResourceManagerAddress, final ResourceManagerId resourceManagerId) {
resourceManagerAddress = createResourceManagerAddress(newResourceManagerAddress, resourceManagerId);
reconnectToResourceManager(new FlinkException(String.format("ResourceManager leader changed to new address %s", resourceManagerAddress)));
}
@Nullable
private ResourceManagerAddress createResourceManagerAddress(@Nullable String newResourceManagerAddress, @Nullable ResourceManagerId resourceManagerId) {
if (newResourceManagerAddress != null) {
// the contract is: address == null <=> id == null
checkNotNull(resourceManagerId);
return new ResourceManagerAddress(newResourceManagerAddress, resourceManagerId);
} else {
return null;
}
}
private void reconnectToResourceManager(Exception cause) {
closeResourceManagerConnection(cause);
tryConnectToResourceManager();
}
private void tryConnectToResourceManager() {
if (resourceManagerAddress != null) {
connectToResourceManager();
}
}
private void connectToResourceManager() {
assert(resourceManagerAddress != null);
assert(resourceManagerConnection == null);
assert(establishedResourceManagerConnection == null);
log.info("Connecting to ResourceManager {}", resourceManagerAddress);
resourceManagerConnection = new ResourceManagerConnection(
log,
jobGraph.getJobID(),
resourceId,
getAddress(),
getFencingToken(),
resourceManagerAddress.getAddress(),
resourceManagerAddress.getResourceManagerId(),
scheduledExecutorService);
resourceManagerConnection.start();
}
private void establishResourceManagerConnection(final JobMasterRegistrationSuccess success) {
final ResourceManagerId resourceManagerId = success.getResourceManagerId();
// verify the response with current connection
if (resourceManagerConnection != null
&& Objects.equals(resourceManagerConnection.getTargetLeaderId(), resourceManagerId)) {
log.info("JobManager successfully registered at ResourceManager, leader id: {}.", resourceManagerId);
final ResourceManagerGateway resourceManagerGateway = resourceManagerConnection.getTargetGateway();
final ResourceID resourceManagerResourceId = success.getResourceManagerResourceId();
establishedResourceManagerConnection = new EstablishedResourceManagerConnection(
resourceManagerGateway,
resourceManagerResourceId);
slotPool.connectToResourceManager(resourceManagerGateway);
resourceManagerHeartbeatManager.monitorTarget(resourceManagerResourceId, new HeartbeatTarget<Void>() {
@Override
public void receiveHeartbeat(ResourceID resourceID, Void payload) {
resourceManagerGateway.heartbeatFromJobManager(resourceID);
}
@Override
public void requestHeartbeat(ResourceID resourceID, Void payload) {
// request heartbeat will never be called on the job manager side
}
});
} else {
log.debug("Ignoring resource manager connection to {} because it's duplicated or outdated.", resourceManagerId);
}
}
private void closeResourceManagerConnection(Exception cause) {
if (establishedResourceManagerConnection != null) {
dissolveResourceManagerConnection(establishedResourceManagerConnection, cause);
establishedResourceManagerConnection = null;
}
if (resourceManagerConnection != null) {
// stop a potentially ongoing registration process
resourceManagerConnection.close();
resourceManagerConnection = null;
}
}
private void dissolveResourceManagerConnection(EstablishedResourceManagerConnection establishedResourceManagerConnection, Exception cause) {
final ResourceID resourceManagerResourceID = establishedResourceManagerConnection.getResourceManagerResourceID();
if (log.isDebugEnabled()) {
log.debug("Close ResourceManager connection {}.", resourceManagerResourceID, cause);
} else {
log.info("Close ResourceManager connection {}: {}.", resourceManagerResourceID, cause.getMessage());
}
resourceManagerHeartbeatManager.unmonitorTarget(resourceManagerResourceID);
ResourceManagerGateway resourceManagerGateway = establishedResourceManagerConnection.getResourceManagerGateway();
resourceManagerGateway.disconnectJobManager(jobGraph.getJobID(), cause);
slotPool.disconnectResourceManager();
}
/**
* Restore the given {@link ExecutionGraph} from the rescaling savepoint. If the {@link ExecutionGraph} could
* be restored, then this savepoint will be recorded as the latest successful modification savepoint. A previous
* savepoint will be disposed. If the rescaling savepoint is empty, the job will be restored from the initially
* provided savepoint.
*
* @param newExecutionGraph to restore
* @param savepointFuture containing the path to the internal modification savepoint
* @return Future which is completed with the restored {@link ExecutionGraph}
*/
private CompletableFuture<ExecutionGraph> restoreExecutionGraphFromRescalingSavepoint(ExecutionGraph newExecutionGraph, CompletableFuture<String> savepointFuture) {
return savepointFuture
.thenApplyAsync(
(@Nullable String savepointPath) -> {
if (savepointPath != null) {
try {
tryRestoreExecutionGraphFromSavepoint(newExecutionGraph, SavepointRestoreSettings.forPath(savepointPath, false));
} catch (Exception e) {
final String message = String.format("Could not restore from temporary rescaling savepoint. This might indicate " +
"that the savepoint %s got corrupted. Deleting this savepoint as a precaution.",
savepointPath);
log.info(message);
CompletableFuture
.runAsync(
() -> {
if (savepointPath.equals(lastInternalSavepoint)) {
lastInternalSavepoint = null;
}
},
getMainThreadExecutor())
.thenRunAsync(
() -> disposeSavepoint(savepointPath),
scheduledExecutorService);
throw new CompletionException(new JobModificationException(message, e));
}
} else {
// No rescaling savepoint, restart from the initial savepoint or none
try {
tryRestoreExecutionGraphFromSavepoint(newExecutionGraph, jobGraph.getSavepointRestoreSettings());
} catch (Exception e) {
final String message = String.format("Could not restore from initial savepoint. This might indicate " +
"that the savepoint %s got corrupted.", jobGraph.getSavepointRestoreSettings().getRestorePath());
log.info(message);
throw new CompletionException(new JobModificationException(message, e));
}
}
return newExecutionGraph;
}, scheduledExecutorService);
}
/**
* Takes an internal savepoint for job modification purposes. If the savepoint was not successful because
* not all tasks were running, it returns the last successful modification savepoint.
*
* @param timeout for the operation
* @return Future which is completed with the savepoint path or the last successful modification savepoint if the
* former was not successful
*/
private CompletableFuture<String> getJobModificationSavepoint(Time timeout) {
return triggerSavepoint(
null,
false,
timeout)
.handleAsync(
(String savepointPath, Throwable throwable) -> {
if (throwable != null) {
final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable);
if (strippedThrowable instanceof CheckpointTriggerException) {
final CheckpointTriggerException checkpointTriggerException = (CheckpointTriggerException) strippedThrowable;
if (checkpointTriggerException.getCheckpointDeclineReason() == CheckpointDeclineReason.NOT_ALL_REQUIRED_TASKS_RUNNING) {
return lastInternalSavepoint;
} else {
throw new CompletionException(checkpointTriggerException);
}
} else {
throw new CompletionException(strippedThrowable);
}
} else {
final String savepointToDispose = lastInternalSavepoint;
lastInternalSavepoint = savepointPath;
if (savepointToDispose != null) {
// dispose the old savepoint asynchronously
CompletableFuture.runAsync(
() -> disposeSavepoint(savepointToDispose),
scheduledExecutorService);
}
return lastInternalSavepoint;
}
},
getMainThreadExecutor());
}
/**
* Rescales the given operators of the {@link JobGraph} of this {@link JobMaster} with respect to given
* parallelism and {@link RescalingBehaviour}.
*
* @param operators to rescale
* @param newParallelism new parallelism for these operators
* @param rescalingBehaviour of the rescaling operation
* @throws FlinkException if the {@link JobGraph} could not be rescaled
*/
private void rescaleJobGraph(Collection<JobVertexID> operators, int newParallelism, RescalingBehaviour rescalingBehaviour) throws FlinkException {
for (JobVertexID jobVertexId : operators) {
final JobVertex jobVertex = jobGraph.findVertexByID(jobVertexId);
// update max parallelism in case that it has not been configured
final ExecutionJobVertex executionJobVertex = executionGraph.getJobVertex(jobVertexId);
if (executionJobVertex != null) {
jobVertex.setMaxParallelism(executionJobVertex.getMaxParallelism());
}
rescalingBehaviour.accept(jobVertex, newParallelism);
}
}
//----------------------------------------------------------------------------------------------
// Service methods
//----------------------------------------------------------------------------------------------
@Override
public JobMasterGateway getGateway() {
return getSelfGateway(JobMasterGateway.class);
}
//----------------------------------------------------------------------------------------------
// Utility classes
//----------------------------------------------------------------------------------------------
private class ResourceManagerLeaderListener implements LeaderRetrievalListener {
@Override
public void notifyLeaderAddress(final String leaderAddress, final UUID leaderSessionID) {
runAsync(
() -> notifyOfNewResourceManagerLeader(
leaderAddress,
ResourceManagerId.fromUuidOrNull(leaderSessionID)));
}
@Override
public void handleError(final Exception exception) {
handleJobMasterError(new Exception("Fatal error in the ResourceManager leader service", exception));
}
}
//----------------------------------------------------------------------------------------------
private class ResourceManagerConnection
extends RegisteredRpcConnection<ResourceManagerId, ResourceManagerGateway, JobMasterRegistrationSuccess> {
private final JobID jobID;
private final ResourceID jobManagerResourceID;
private final String jobManagerRpcAddress;
private final JobMasterId jobMasterId;
ResourceManagerConnection(
final Logger log,
final JobID jobID,
final ResourceID jobManagerResourceID,
final String jobManagerRpcAddress,
final JobMasterId jobMasterId,
final String resourceManagerAddress,
final ResourceManagerId resourceManagerId,
final Executor executor) {
super(log, resourceManagerAddress, resourceManagerId, executor);
this.jobID = checkNotNull(jobID);
this.jobManagerResourceID = checkNotNull(jobManagerResourceID);
this.jobManagerRpcAddress = checkNotNull(jobManagerRpcAddress);
this.jobMasterId = checkNotNull(jobMasterId);
}
@Override
protected RetryingRegistration<ResourceManagerId, ResourceManagerGateway, JobMasterRegistrationSuccess> generateRegistration() {
return new RetryingRegistration<ResourceManagerId, ResourceManagerGateway, JobMasterRegistrationSuccess>(
log,
getRpcService(),
"ResourceManager",
ResourceManagerGateway.class,
getTargetAddress(),
getTargetLeaderId(),
jobMasterConfiguration.getRetryingRegistrationConfiguration()) {
@Override
protected CompletableFuture<RegistrationResponse> invokeRegistration(
ResourceManagerGateway gateway, ResourceManagerId fencingToken, long timeoutMillis) {
Time timeout = Time.milliseconds(timeoutMillis);
return gateway.registerJobManager(
jobMasterId,
jobManagerResourceID,
jobManagerRpcAddress,
jobID,
timeout);
}
};
}
@Override
protected void onRegistrationSuccess(final JobMasterRegistrationSuccess success) {
runAsync(() -> {
// filter out outdated connections
//noinspection ObjectEquality
if (this == resourceManagerConnection) {
establishResourceManagerConnection(success);
}
});
}
@Override
protected void onRegistrationFailure(final Throwable failure) {
handleJobMasterError(failure);
}
}
//----------------------------------------------------------------------------------------------
private class JobManagerJobStatusListener implements JobStatusListener {
private volatile boolean running = true;
@Override
public void jobStatusChanges(
final JobID jobId,
final JobStatus newJobStatus,
final long timestamp,
final Throwable error) {
if (running) {
// run in rpc thread to avoid concurrency
runAsync(() -> jobStatusChanged(newJobStatus, timestamp, error));
}
}
private void stop() {
running = false;
}
}
private class TaskManagerHeartbeatListener implements HeartbeatListener<AccumulatorReport, Void> {
private final JobMasterGateway jobMasterGateway;
private TaskManagerHeartbeatListener(JobMasterGateway jobMasterGateway) {
this.jobMasterGateway = Preconditions.checkNotNull(jobMasterGateway);
}
@Override
public void notifyHeartbeatTimeout(ResourceID resourceID) {
jobMasterGateway.disconnectTaskManager(
resourceID,
new TimeoutException("Heartbeat of TaskManager with id " + resourceID + " timed out."));
}
@Override
public void reportPayload(ResourceID resourceID, AccumulatorReport payload) {
for (AccumulatorSnapshot snapshot : payload.getAccumulatorSnapshots()) {
executionGraph.updateAccumulators(snapshot);
}
}
@Override
public CompletableFuture<Void> retrievePayload(ResourceID resourceID) {
return CompletableFuture.completedFuture(null);
}
}
private class ResourceManagerHeartbeatListener implements HeartbeatListener<Void, Void> {
@Override
public void notifyHeartbeatTimeout(final ResourceID resourceId) {
runAsync(() -> {
log.info("The heartbeat of ResourceManager with id {} timed out.", resourceId);
if (establishedResourceManagerConnection != null && establishedResourceManagerConnection.getResourceManagerResourceID().equals(resourceId)) {
reconnectToResourceManager(
new JobMasterException(
String.format("The heartbeat of ResourceManager with id %s timed out.", resourceId)));
}
});
}
@Override
public void reportPayload(ResourceID resourceID, Void payload) {
// nothing to do since the payload is of type Void
}
@Override
public CompletableFuture<Void> retrievePayload(ResourceID resourceID) {
return CompletableFuture.completedFuture(null);
}
}
@VisibleForTesting
RestartStrategy getRestartStrategy() {
return restartStrategy;
}
@VisibleForTesting
ExecutionGraph getExecutionGraph() {
return executionGraph;
}
}
| flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.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.flink.runtime.jobmaster;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.CheckpointingOptions;
import org.apache.flink.core.io.InputSplit;
import org.apache.flink.core.io.InputSplitAssigner;
import org.apache.flink.queryablestate.KvStateID;
import org.apache.flink.runtime.JobException;
import org.apache.flink.runtime.StoppingException;
import org.apache.flink.runtime.accumulators.AccumulatorSnapshot;
import org.apache.flink.runtime.blob.BlobWriter;
import org.apache.flink.runtime.checkpoint.CheckpointCoordinator;
import org.apache.flink.runtime.checkpoint.CheckpointDeclineReason;
import org.apache.flink.runtime.checkpoint.CheckpointMetrics;
import org.apache.flink.runtime.checkpoint.CheckpointTriggerException;
import org.apache.flink.runtime.checkpoint.Checkpoints;
import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.execution.SuppressRestartsException;
import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
import org.apache.flink.runtime.executiongraph.Execution;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.ExecutionGraph;
import org.apache.flink.runtime.executiongraph.ExecutionGraphBuilder;
import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
import org.apache.flink.runtime.executiongraph.IntermediateResult;
import org.apache.flink.runtime.executiongraph.JobStatusListener;
import org.apache.flink.runtime.executiongraph.restart.RestartStrategy;
import org.apache.flink.runtime.executiongraph.restart.RestartStrategyResolving;
import org.apache.flink.runtime.heartbeat.HeartbeatListener;
import org.apache.flink.runtime.heartbeat.HeartbeatManager;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.heartbeat.HeartbeatTarget;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobStatus;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.jobmanager.OnCompletionActions;
import org.apache.flink.runtime.jobmanager.PartitionProducerDisposedException;
import org.apache.flink.runtime.jobmaster.exceptions.JobModificationException;
import org.apache.flink.runtime.jobmaster.factories.JobManagerJobMetricGroupFactory;
import org.apache.flink.runtime.jobmaster.slotpool.Scheduler;
import org.apache.flink.runtime.jobmaster.slotpool.SchedulerFactory;
import org.apache.flink.runtime.jobmaster.slotpool.SlotPool;
import org.apache.flink.runtime.jobmaster.slotpool.SlotPoolFactory;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalListener;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.messages.FlinkJobNotFoundException;
import org.apache.flink.runtime.messages.checkpoint.AcknowledgeCheckpoint;
import org.apache.flink.runtime.messages.checkpoint.DeclineCheckpoint;
import org.apache.flink.runtime.messages.webmonitor.JobDetails;
import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
import org.apache.flink.runtime.query.KvStateLocation;
import org.apache.flink.runtime.query.KvStateLocationRegistry;
import org.apache.flink.runtime.query.UnknownKvStateLocation;
import org.apache.flink.runtime.registration.RegisteredRpcConnection;
import org.apache.flink.runtime.registration.RegistrationResponse;
import org.apache.flink.runtime.registration.RetryingRegistration;
import org.apache.flink.runtime.resourcemanager.ResourceManagerGateway;
import org.apache.flink.runtime.resourcemanager.ResourceManagerId;
import org.apache.flink.runtime.rest.handler.legacy.backpressure.BackPressureStatsTracker;
import org.apache.flink.runtime.rest.handler.legacy.backpressure.OperatorBackPressureStats;
import org.apache.flink.runtime.rest.handler.legacy.backpressure.OperatorBackPressureStatsResponse;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.FencedRpcEndpoint;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcUtils;
import org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils;
import org.apache.flink.runtime.state.KeyGroupRange;
import org.apache.flink.runtime.taskexecutor.AccumulatorReport;
import org.apache.flink.runtime.taskexecutor.TaskExecutorGateway;
import org.apache.flink.runtime.taskexecutor.slot.SlotOffer;
import org.apache.flink.runtime.taskmanager.TaskExecutionState;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
import org.apache.flink.runtime.webmonitor.WebMonitorUtils;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.InstantiationUtil;
import org.apache.flink.util.Preconditions;
import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeoutException;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* JobMaster implementation. The job master is responsible for the execution of a single
* {@link JobGraph}.
*
* <p>It offers the following methods as part of its rpc interface to interact with the JobMaster
* remotely:
* <ul>
* <li>{@link #updateTaskExecutionState} updates the task execution state for
* given task</li>
* </ul>
*/
public class JobMaster extends FencedRpcEndpoint<JobMasterId> implements JobMasterGateway, JobMasterService {
/** Default names for Flink's distributed components. */
public static final String JOB_MANAGER_NAME = "jobmanager";
public static final String ARCHIVE_NAME = "archive";
// ------------------------------------------------------------------------
private final JobMasterConfiguration jobMasterConfiguration;
private final ResourceID resourceId;
private final JobGraph jobGraph;
private final Time rpcTimeout;
private final HighAvailabilityServices highAvailabilityServices;
private final BlobWriter blobWriter;
private final JobManagerJobMetricGroupFactory jobMetricGroupFactory;
private final HeartbeatManager<AccumulatorReport, Void> taskManagerHeartbeatManager;
private final HeartbeatManager<Void, Void> resourceManagerHeartbeatManager;
private final ScheduledExecutorService scheduledExecutorService;
private final OnCompletionActions jobCompletionActions;
private final FatalErrorHandler fatalErrorHandler;
private final ClassLoader userCodeLoader;
private final SlotPool slotPool;
private final Scheduler scheduler;
private final RestartStrategy restartStrategy;
// --------- BackPressure --------
private final BackPressureStatsTracker backPressureStatsTracker;
// --------- ResourceManager --------
private final LeaderRetrievalService resourceManagerLeaderRetriever;
// --------- TaskManagers --------
private final Map<ResourceID, Tuple2<TaskManagerLocation, TaskExecutorGateway>> registeredTaskManagers;
// -------- Mutable fields ---------
private ExecutionGraph executionGraph;
@Nullable
private JobManagerJobStatusListener jobStatusListener;
@Nullable
private JobManagerJobMetricGroup jobManagerJobMetricGroup;
@Nullable
private String lastInternalSavepoint;
@Nullable
private ResourceManagerAddress resourceManagerAddress;
@Nullable
private ResourceManagerConnection resourceManagerConnection;
@Nullable
private EstablishedResourceManagerConnection establishedResourceManagerConnection;
private Map<String, Object> accumulators;
// ------------------------------------------------------------------------
public JobMaster(
RpcService rpcService,
JobMasterConfiguration jobMasterConfiguration,
ResourceID resourceId,
JobGraph jobGraph,
HighAvailabilityServices highAvailabilityService,
SlotPoolFactory slotPoolFactory,
SchedulerFactory schedulerFactory,
JobManagerSharedServices jobManagerSharedServices,
HeartbeatServices heartbeatServices,
JobManagerJobMetricGroupFactory jobMetricGroupFactory,
OnCompletionActions jobCompletionActions,
FatalErrorHandler fatalErrorHandler,
ClassLoader userCodeLoader) throws Exception {
super(rpcService, AkkaRpcServiceUtils.createRandomName(JOB_MANAGER_NAME));
final JobMasterGateway selfGateway = getSelfGateway(JobMasterGateway.class);
this.jobMasterConfiguration = checkNotNull(jobMasterConfiguration);
this.resourceId = checkNotNull(resourceId);
this.jobGraph = checkNotNull(jobGraph);
this.rpcTimeout = jobMasterConfiguration.getRpcTimeout();
this.highAvailabilityServices = checkNotNull(highAvailabilityService);
this.blobWriter = jobManagerSharedServices.getBlobWriter();
this.scheduledExecutorService = jobManagerSharedServices.getScheduledExecutorService();
this.jobCompletionActions = checkNotNull(jobCompletionActions);
this.fatalErrorHandler = checkNotNull(fatalErrorHandler);
this.userCodeLoader = checkNotNull(userCodeLoader);
this.jobMetricGroupFactory = checkNotNull(jobMetricGroupFactory);
this.taskManagerHeartbeatManager = heartbeatServices.createHeartbeatManagerSender(
resourceId,
new TaskManagerHeartbeatListener(selfGateway),
rpcService.getScheduledExecutor(),
log);
this.resourceManagerHeartbeatManager = heartbeatServices.createHeartbeatManager(
resourceId,
new ResourceManagerHeartbeatListener(),
rpcService.getScheduledExecutor(),
log);
final String jobName = jobGraph.getName();
final JobID jid = jobGraph.getJobID();
log.info("Initializing job {} ({}).", jobName, jid);
final RestartStrategies.RestartStrategyConfiguration restartStrategyConfiguration =
jobGraph.getSerializedExecutionConfig()
.deserializeValue(userCodeLoader)
.getRestartStrategy();
this.restartStrategy = RestartStrategyResolving.resolve(restartStrategyConfiguration,
jobManagerSharedServices.getRestartStrategyFactory(),
jobGraph.isCheckpointingEnabled());
log.info("Using restart strategy {} for {} ({}).", this.restartStrategy, jobName, jid);
resourceManagerLeaderRetriever = highAvailabilityServices.getResourceManagerLeaderRetriever();
this.slotPool = checkNotNull(slotPoolFactory).createSlotPool(jobGraph.getJobID());
this.scheduler = checkNotNull(schedulerFactory).createScheduler(slotPool);
this.registeredTaskManagers = new HashMap<>(4);
this.backPressureStatsTracker = checkNotNull(jobManagerSharedServices.getBackPressureStatsTracker());
this.lastInternalSavepoint = null;
this.jobManagerJobMetricGroup = jobMetricGroupFactory.create(jobGraph);
this.executionGraph = createAndRestoreExecutionGraph(jobManagerJobMetricGroup);
this.jobStatusListener = null;
this.resourceManagerConnection = null;
this.establishedResourceManagerConnection = null;
this.accumulators = new HashMap<>();
}
//----------------------------------------------------------------------------------------------
// Lifecycle management
//----------------------------------------------------------------------------------------------
@Override
public void start() {
throw new UnsupportedOperationException("Should never call start() without leader ID");
}
/**
* Start the rpc service and begin to run the job.
*
* @param newJobMasterId The necessary fencing token to run the job
* @return Future acknowledge if the job could be started. Otherwise the future contains an exception
*/
public CompletableFuture<Acknowledge> start(final JobMasterId newJobMasterId) throws Exception {
// make sure we receive RPC and async calls
super.start();
return callAsyncWithoutFencing(() -> startJobExecution(newJobMasterId), RpcUtils.INF_TIMEOUT);
}
/**
* Suspending job, all the running tasks will be cancelled, and communication with other components
* will be disposed.
*
* <p>Mostly job is suspended because of the leadership has been revoked, one can be restart this job by
* calling the {@link #start(JobMasterId)} method once we take the leadership back again.
*
* <p>This method is executed asynchronously
*
* @param cause The reason of why this job been suspended.
* @return Future acknowledge indicating that the job has been suspended. Otherwise the future contains an exception
*/
public CompletableFuture<Acknowledge> suspend(final Exception cause) {
CompletableFuture<Acknowledge> suspendFuture = callAsyncWithoutFencing(
() -> suspendExecution(cause),
RpcUtils.INF_TIMEOUT);
return suspendFuture.whenComplete((acknowledge, throwable) -> stop());
}
/**
* Suspend the job and shutdown all other services including rpc.
*/
@Override
public CompletableFuture<Void> onStop() {
log.info("Stopping the JobMaster for job {}({}).", jobGraph.getName(), jobGraph.getJobID());
// disconnect from all registered TaskExecutors
final Set<ResourceID> taskManagerResourceIds = new HashSet<>(registeredTaskManagers.keySet());
final FlinkException cause = new FlinkException("Stopping JobMaster for job " + jobGraph.getName() +
'(' + jobGraph.getJobID() + ").");
for (ResourceID taskManagerResourceId : taskManagerResourceIds) {
disconnectTaskManager(taskManagerResourceId, cause);
}
taskManagerHeartbeatManager.stop();
resourceManagerHeartbeatManager.stop();
// make sure there is a graceful exit
suspendExecution(new FlinkException("JobManager is shutting down."));
// shut down will internally release all registered slots
slotPool.close();
final CompletableFuture<Void> disposeInternalSavepointFuture;
if (lastInternalSavepoint != null) {
disposeInternalSavepointFuture = CompletableFuture.runAsync(() -> disposeSavepoint(lastInternalSavepoint));
} else {
disposeInternalSavepointFuture = CompletableFuture.completedFuture(null);
}
return FutureUtils.completeAll(Collections.singletonList(disposeInternalSavepointFuture));
}
//----------------------------------------------------------------------------------------------
// RPC methods
//----------------------------------------------------------------------------------------------
@Override
public CompletableFuture<Acknowledge> cancel(Time timeout) {
executionGraph.cancel();
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> stop(Time timeout) {
try {
executionGraph.stop();
} catch (StoppingException e) {
return FutureUtils.completedExceptionally(e);
}
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> rescaleJob(
int newParallelism,
RescalingBehaviour rescalingBehaviour,
Time timeout) {
final ArrayList<JobVertexID> allOperators = new ArrayList<>(jobGraph.getNumberOfVertices());
for (JobVertex jobVertex : jobGraph.getVertices()) {
allOperators.add(jobVertex.getID());
}
return rescaleOperators(allOperators, newParallelism, rescalingBehaviour, timeout);
}
@Override
public CompletableFuture<Acknowledge> rescaleOperators(
Collection<JobVertexID> operators,
int newParallelism,
RescalingBehaviour rescalingBehaviour,
Time timeout) {
if (newParallelism <= 0) {
return FutureUtils.completedExceptionally(
new JobModificationException("The target parallelism of a rescaling operation must be larger than 0."));
}
// 1. Check whether we can rescale the job & rescale the respective vertices
try {
rescaleJobGraph(operators, newParallelism, rescalingBehaviour);
} catch (FlinkException e) {
final String msg = String.format("Cannot rescale job %s.", jobGraph.getName());
log.info(msg, e);
return FutureUtils.completedExceptionally(new JobModificationException(msg, e));
}
final ExecutionGraph currentExecutionGraph = executionGraph;
final JobManagerJobMetricGroup newJobManagerJobMetricGroup = jobMetricGroupFactory.create(jobGraph);
final ExecutionGraph newExecutionGraph;
try {
newExecutionGraph = createExecutionGraph(newJobManagerJobMetricGroup);
} catch (JobExecutionException | JobException e) {
return FutureUtils.completedExceptionally(
new JobModificationException("Could not create rescaled ExecutionGraph.", e));
}
// 3. disable checkpoint coordinator to suppress subsequent checkpoints
final CheckpointCoordinator checkpointCoordinator = currentExecutionGraph.getCheckpointCoordinator();
checkpointCoordinator.stopCheckpointScheduler();
// 4. take a savepoint
final CompletableFuture<String> savepointFuture = getJobModificationSavepoint(timeout);
final CompletableFuture<ExecutionGraph> executionGraphFuture = restoreExecutionGraphFromRescalingSavepoint(
newExecutionGraph,
savepointFuture)
.handleAsync(
(ExecutionGraph executionGraph, Throwable failure) -> {
if (failure != null) {
// in case that we couldn't take a savepoint or restore from it, let's restart the checkpoint
// coordinator and abort the rescaling operation
if (checkpointCoordinator.isPeriodicCheckpointingConfigured()) {
checkpointCoordinator.startCheckpointScheduler();
}
throw new CompletionException(ExceptionUtils.stripCompletionException(failure));
} else {
return executionGraph;
}
},
getMainThreadExecutor());
// 5. suspend the current job
final CompletableFuture<JobStatus> terminationFuture = executionGraphFuture.thenComposeAsync(
(ExecutionGraph ignored) -> {
suspendExecutionGraph(new FlinkException("Job is being rescaled."));
return currentExecutionGraph.getTerminationFuture();
},
getMainThreadExecutor());
final CompletableFuture<Void> suspendedFuture = terminationFuture.thenAccept(
(JobStatus jobStatus) -> {
if (jobStatus != JobStatus.SUSPENDED) {
final String msg = String.format("Job %s rescaling failed because we could not suspend the execution graph.", jobGraph.getName());
log.info(msg);
throw new CompletionException(new JobModificationException(msg));
}
});
// 6. resume the new execution graph from the taken savepoint
final CompletableFuture<Acknowledge> rescalingFuture = suspendedFuture.thenCombineAsync(
executionGraphFuture,
(Void ignored, ExecutionGraph restoredExecutionGraph) -> {
// check if the ExecutionGraph is still the same
if (executionGraph == currentExecutionGraph) {
clearExecutionGraphFields();
assignExecutionGraph(restoredExecutionGraph, newJobManagerJobMetricGroup);
scheduleExecutionGraph();
return Acknowledge.get();
} else {
throw new CompletionException(new JobModificationException("Detected concurrent modification of ExecutionGraph. Aborting the rescaling."));
}
},
getMainThreadExecutor());
rescalingFuture.whenCompleteAsync(
(Acknowledge ignored, Throwable throwable) -> {
if (throwable != null) {
// fail the newly created execution graph
newExecutionGraph.failGlobal(
new SuppressRestartsException(
new FlinkException(
String.format("Failed to rescale the job %s.", jobGraph.getJobID()),
throwable)));
}
}, getMainThreadExecutor());
return rescalingFuture;
}
/**
* Updates the task execution state for a given task.
*
* @param taskExecutionState New task execution state for a given task
* @return Acknowledge the task execution state update
*/
@Override
public CompletableFuture<Acknowledge> updateTaskExecutionState(
final TaskExecutionState taskExecutionState) {
checkNotNull(taskExecutionState, "taskExecutionState");
if (executionGraph.updateState(taskExecutionState)) {
return CompletableFuture.completedFuture(Acknowledge.get());
} else {
return FutureUtils.completedExceptionally(
new ExecutionGraphException("The execution attempt " +
taskExecutionState.getID() + " was not found."));
}
}
@Override
public CompletableFuture<SerializedInputSplit> requestNextInputSplit(
final JobVertexID vertexID,
final ExecutionAttemptID executionAttempt) {
final Execution execution = executionGraph.getRegisteredExecutions().get(executionAttempt);
if (execution == null) {
// can happen when JobManager had already unregistered this execution upon on task failure,
// but TaskManager get some delay to aware of that situation
if (log.isDebugEnabled()) {
log.debug("Can not find Execution for attempt {}.", executionAttempt);
}
// but we should TaskManager be aware of this
return FutureUtils.completedExceptionally(new Exception("Can not find Execution for attempt " + executionAttempt));
}
final ExecutionJobVertex vertex = executionGraph.getJobVertex(vertexID);
if (vertex == null) {
log.error("Cannot find execution vertex for vertex ID {}.", vertexID);
return FutureUtils.completedExceptionally(new Exception("Cannot find execution vertex for vertex ID " + vertexID));
}
final InputSplitAssigner splitAssigner = vertex.getSplitAssigner();
if (splitAssigner == null) {
log.error("No InputSplitAssigner for vertex ID {}.", vertexID);
return FutureUtils.completedExceptionally(new Exception("No InputSplitAssigner for vertex ID " + vertexID));
}
final LogicalSlot slot = execution.getAssignedResource();
final int taskId = execution.getVertex().getParallelSubtaskIndex();
final String host = slot != null ? slot.getTaskManagerLocation().getHostname() : null;
final InputSplit nextInputSplit = splitAssigner.getNextInputSplit(host, taskId);
if (log.isDebugEnabled()) {
log.debug("Send next input split {}.", nextInputSplit);
}
try {
final byte[] serializedInputSplit = InstantiationUtil.serializeObject(nextInputSplit);
return CompletableFuture.completedFuture(new SerializedInputSplit(serializedInputSplit));
} catch (Exception ex) {
log.error("Could not serialize the next input split of class {}.", nextInputSplit.getClass(), ex);
IOException reason = new IOException("Could not serialize the next input split of class " +
nextInputSplit.getClass() + ".", ex);
vertex.fail(reason);
return FutureUtils.completedExceptionally(reason);
}
}
@Override
public CompletableFuture<ExecutionState> requestPartitionState(
final IntermediateDataSetID intermediateResultId,
final ResultPartitionID resultPartitionId) {
final Execution execution = executionGraph.getRegisteredExecutions().get(resultPartitionId.getProducerId());
if (execution != null) {
return CompletableFuture.completedFuture(execution.getState());
}
else {
final IntermediateResult intermediateResult =
executionGraph.getAllIntermediateResults().get(intermediateResultId);
if (intermediateResult != null) {
// Try to find the producing execution
Execution producerExecution = intermediateResult
.getPartitionById(resultPartitionId.getPartitionId())
.getProducer()
.getCurrentExecutionAttempt();
if (producerExecution.getAttemptId().equals(resultPartitionId.getProducerId())) {
return CompletableFuture.completedFuture(producerExecution.getState());
} else {
return FutureUtils.completedExceptionally(new PartitionProducerDisposedException(resultPartitionId));
}
} else {
return FutureUtils.completedExceptionally(new IllegalArgumentException("Intermediate data set with ID "
+ intermediateResultId + " not found."));
}
}
}
@Override
public CompletableFuture<Acknowledge> scheduleOrUpdateConsumers(
final ResultPartitionID partitionID,
final Time timeout) {
try {
executionGraph.scheduleOrUpdateConsumers(partitionID);
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (Exception e) {
return FutureUtils.completedExceptionally(e);
}
}
@Override
public CompletableFuture<Acknowledge> disconnectTaskManager(final ResourceID resourceID, final Exception cause) {
log.debug("Disconnect TaskExecutor {} because: {}", resourceID, cause.getMessage());
taskManagerHeartbeatManager.unmonitorTarget(resourceID);
slotPool.releaseTaskManager(resourceID, cause);
Tuple2<TaskManagerLocation, TaskExecutorGateway> taskManagerConnection = registeredTaskManagers.remove(resourceID);
if (taskManagerConnection != null) {
taskManagerConnection.f1.disconnectJobManager(jobGraph.getJobID(), cause);
}
return CompletableFuture.completedFuture(Acknowledge.get());
}
// TODO: This method needs a leader session ID
@Override
public void acknowledgeCheckpoint(
final JobID jobID,
final ExecutionAttemptID executionAttemptID,
final long checkpointId,
final CheckpointMetrics checkpointMetrics,
final TaskStateSnapshot checkpointState) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
final AcknowledgeCheckpoint ackMessage = new AcknowledgeCheckpoint(
jobID,
executionAttemptID,
checkpointId,
checkpointMetrics,
checkpointState);
if (checkpointCoordinator != null) {
getRpcService().execute(() -> {
try {
checkpointCoordinator.receiveAcknowledgeMessage(ackMessage);
} catch (Throwable t) {
log.warn("Error while processing checkpoint acknowledgement message", t);
}
});
} else {
String errorMessage = "Received AcknowledgeCheckpoint message for job {} with no CheckpointCoordinator";
if (executionGraph.getState() == JobStatus.RUNNING) {
log.error(errorMessage, jobGraph.getJobID());
} else {
log.debug(errorMessage, jobGraph.getJobID());
}
}
}
// TODO: This method needs a leader session ID
@Override
public void declineCheckpoint(DeclineCheckpoint decline) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
getRpcService().execute(() -> {
try {
checkpointCoordinator.receiveDeclineMessage(decline);
} catch (Exception e) {
log.error("Error in CheckpointCoordinator while processing {}", decline, e);
}
});
} else {
String errorMessage = "Received DeclineCheckpoint message for job {} with no CheckpointCoordinator";
if (executionGraph.getState() == JobStatus.RUNNING) {
log.error(errorMessage, jobGraph.getJobID());
} else {
log.debug(errorMessage, jobGraph.getJobID());
}
}
}
@Override
public CompletableFuture<KvStateLocation> requestKvStateLocation(final JobID jobId, final String registrationName) {
// sanity check for the correct JobID
if (jobGraph.getJobID().equals(jobId)) {
if (log.isDebugEnabled()) {
log.debug("Lookup key-value state for job {} with registration " +
"name {}.", jobGraph.getJobID(), registrationName);
}
final KvStateLocationRegistry registry = executionGraph.getKvStateLocationRegistry();
final KvStateLocation location = registry.getKvStateLocation(registrationName);
if (location != null) {
return CompletableFuture.completedFuture(location);
} else {
return FutureUtils.completedExceptionally(new UnknownKvStateLocation(registrationName));
}
} else {
if (log.isDebugEnabled()) {
log.debug("Request of key-value state location for unknown job {} received.", jobId);
}
return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
}
}
@Override
public CompletableFuture<Acknowledge> notifyKvStateRegistered(
final JobID jobId,
final JobVertexID jobVertexId,
final KeyGroupRange keyGroupRange,
final String registrationName,
final KvStateID kvStateId,
final InetSocketAddress kvStateServerAddress) {
if (jobGraph.getJobID().equals(jobId)) {
if (log.isDebugEnabled()) {
log.debug("Key value state registered for job {} under name {}.",
jobGraph.getJobID(), registrationName);
}
try {
executionGraph.getKvStateLocationRegistry().notifyKvStateRegistered(
jobVertexId, keyGroupRange, registrationName, kvStateId, kvStateServerAddress);
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (Exception e) {
log.error("Failed to notify KvStateRegistry about registration {}.", registrationName, e);
return FutureUtils.completedExceptionally(e);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Notification about key-value state registration for unknown job {} received.", jobId);
}
return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
}
}
@Override
public CompletableFuture<Acknowledge> notifyKvStateUnregistered(
JobID jobId,
JobVertexID jobVertexId,
KeyGroupRange keyGroupRange,
String registrationName) {
if (jobGraph.getJobID().equals(jobId)) {
if (log.isDebugEnabled()) {
log.debug("Key value state unregistered for job {} under name {}.",
jobGraph.getJobID(), registrationName);
}
try {
executionGraph.getKvStateLocationRegistry().notifyKvStateUnregistered(
jobVertexId, keyGroupRange, registrationName);
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (Exception e) {
log.error("Failed to notify KvStateRegistry about unregistration {}.", registrationName, e);
return FutureUtils.completedExceptionally(e);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Notification about key-value state deregistration for unknown job {} received.", jobId);
}
return FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId));
}
}
@Override
public CompletableFuture<Collection<SlotOffer>> offerSlots(
final ResourceID taskManagerId,
final Collection<SlotOffer> slots,
final Time timeout) {
Tuple2<TaskManagerLocation, TaskExecutorGateway> taskManager = registeredTaskManagers.get(taskManagerId);
if (taskManager == null) {
return FutureUtils.completedExceptionally(new Exception("Unknown TaskManager " + taskManagerId));
}
final TaskManagerLocation taskManagerLocation = taskManager.f0;
final TaskExecutorGateway taskExecutorGateway = taskManager.f1;
final RpcTaskManagerGateway rpcTaskManagerGateway = new RpcTaskManagerGateway(taskExecutorGateway, getFencingToken());
return CompletableFuture.completedFuture(
slotPool.offerSlots(
taskManagerLocation,
rpcTaskManagerGateway,
slots));
}
@Override
public void failSlot(
final ResourceID taskManagerId,
final AllocationID allocationId,
final Exception cause) {
if (registeredTaskManagers.containsKey(taskManagerId)) {
internalFailAllocation(allocationId, cause);
} else {
log.warn("Cannot fail slot " + allocationId + " because the TaskManager " +
taskManagerId + " is unknown.");
}
}
private void internalFailAllocation(AllocationID allocationId, Exception cause) {
final Optional<ResourceID> resourceIdOptional = slotPool.failAllocation(allocationId, cause);
resourceIdOptional.ifPresent(this::releaseEmptyTaskManager);
}
private void releaseEmptyTaskManager(ResourceID resourceId) {
disconnectTaskManager(resourceId, new FlinkException(String.format("No more slots registered at JobMaster %s.", resourceId)));
}
@Override
public CompletableFuture<RegistrationResponse> registerTaskManager(
final String taskManagerRpcAddress,
final TaskManagerLocation taskManagerLocation,
final Time timeout) {
final ResourceID taskManagerId = taskManagerLocation.getResourceID();
if (registeredTaskManagers.containsKey(taskManagerId)) {
final RegistrationResponse response = new JMTMRegistrationSuccess(resourceId);
return CompletableFuture.completedFuture(response);
} else {
return getRpcService()
.connect(taskManagerRpcAddress, TaskExecutorGateway.class)
.handleAsync(
(TaskExecutorGateway taskExecutorGateway, Throwable throwable) -> {
if (throwable != null) {
return new RegistrationResponse.Decline(throwable.getMessage());
}
slotPool.registerTaskManager(taskManagerId);
registeredTaskManagers.put(taskManagerId, Tuple2.of(taskManagerLocation, taskExecutorGateway));
// monitor the task manager as heartbeat target
taskManagerHeartbeatManager.monitorTarget(taskManagerId, new HeartbeatTarget<Void>() {
@Override
public void receiveHeartbeat(ResourceID resourceID, Void payload) {
// the task manager will not request heartbeat, so this method will never be called currently
}
@Override
public void requestHeartbeat(ResourceID resourceID, Void payload) {
taskExecutorGateway.heartbeatFromJobManager(resourceID);
}
});
return new JMTMRegistrationSuccess(resourceId);
},
getMainThreadExecutor());
}
}
@Override
public void disconnectResourceManager(
final ResourceManagerId resourceManagerId,
final Exception cause) {
if (isConnectingToResourceManager(resourceManagerId)) {
reconnectToResourceManager(cause);
}
}
private boolean isConnectingToResourceManager(ResourceManagerId resourceManagerId) {
return resourceManagerAddress != null
&& resourceManagerAddress.getResourceManagerId().equals(resourceManagerId);
}
@Override
public void heartbeatFromTaskManager(final ResourceID resourceID, AccumulatorReport accumulatorReport) {
taskManagerHeartbeatManager.receiveHeartbeat(resourceID, accumulatorReport);
}
@Override
public void heartbeatFromResourceManager(final ResourceID resourceID) {
resourceManagerHeartbeatManager.requestHeartbeat(resourceID, null);
}
@Override
public CompletableFuture<JobDetails> requestJobDetails(Time timeout) {
final ExecutionGraph currentExecutionGraph = executionGraph;
return CompletableFuture.supplyAsync(() -> WebMonitorUtils.createDetailsForJob(currentExecutionGraph), scheduledExecutorService);
}
@Override
public CompletableFuture<JobStatus> requestJobStatus(Time timeout) {
return CompletableFuture.completedFuture(executionGraph.getState());
}
@Override
public CompletableFuture<ArchivedExecutionGraph> requestJob(Time timeout) {
return CompletableFuture.completedFuture(ArchivedExecutionGraph.createFrom(executionGraph));
}
@Override
public CompletableFuture<String> triggerSavepoint(
@Nullable final String targetDirectory,
final boolean cancelJob,
final Time timeout) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
if (checkpointCoordinator == null) {
return FutureUtils.completedExceptionally(new IllegalStateException(
String.format("Job %s is not a streaming job.", jobGraph.getJobID())));
} else if (targetDirectory == null && !checkpointCoordinator.getCheckpointStorage().hasDefaultSavepointLocation()) {
log.info("Trying to cancel job {} with savepoint, but no savepoint directory configured.", jobGraph.getJobID());
return FutureUtils.completedExceptionally(new IllegalStateException(
"No savepoint directory configured. You can either specify a directory " +
"while cancelling via -s :targetDirectory or configure a cluster-wide " +
"default via key '" + CheckpointingOptions.SAVEPOINT_DIRECTORY.key() + "'."));
}
if (cancelJob) {
checkpointCoordinator.stopCheckpointScheduler();
}
return checkpointCoordinator
.triggerSavepoint(System.currentTimeMillis(), targetDirectory)
.thenApply(CompletedCheckpoint::getExternalPointer)
.handleAsync((path, throwable) -> {
if (throwable != null) {
if (cancelJob) {
startCheckpointScheduler(checkpointCoordinator);
}
throw new CompletionException(throwable);
} else if (cancelJob) {
log.info("Savepoint stored in {}. Now cancelling {}.", path, jobGraph.getJobID());
cancel(timeout);
}
return path;
}, getMainThreadExecutor());
}
private void startCheckpointScheduler(final CheckpointCoordinator checkpointCoordinator) {
if (checkpointCoordinator.isPeriodicCheckpointingConfigured()) {
try {
checkpointCoordinator.startCheckpointScheduler();
} catch (IllegalStateException ignored) {
// Concurrent shut down of the coordinator
}
}
}
@Override
public CompletableFuture<OperatorBackPressureStatsResponse> requestOperatorBackPressureStats(final JobVertexID jobVertexId) {
final ExecutionJobVertex jobVertex = executionGraph.getJobVertex(jobVertexId);
if (jobVertex == null) {
return FutureUtils.completedExceptionally(new FlinkException("JobVertexID not found " +
jobVertexId));
}
final Optional<OperatorBackPressureStats> operatorBackPressureStats =
backPressureStatsTracker.getOperatorBackPressureStats(jobVertex);
return CompletableFuture.completedFuture(OperatorBackPressureStatsResponse.of(
operatorBackPressureStats.orElse(null)));
}
@Override
public void notifyAllocationFailure(AllocationID allocationID, Exception cause) {
internalFailAllocation(allocationID, cause);
}
@Override
public CompletableFuture<Object> updateGlobalAggregate(String aggregateName, Object aggregand, byte[] serializedAggregateFunction) {
AggregateFunction aggregateFunction = null;
try {
aggregateFunction = InstantiationUtil.deserializeObject(serializedAggregateFunction, userCodeLoader);
} catch (Exception e) {
log.error("Error while attempting to deserialize user AggregateFunction.");
return FutureUtils.completedExceptionally(e);
}
Object accumulator = accumulators.get(aggregateName);
if(null == accumulator) {
accumulator = aggregateFunction.createAccumulator();
}
accumulator = aggregateFunction.add(aggregand, accumulator);
accumulators.put(aggregateName, accumulator);
return CompletableFuture.completedFuture(aggregateFunction.getResult(accumulator));
}
//----------------------------------------------------------------------------------------------
// Internal methods
//----------------------------------------------------------------------------------------------
//-- job starting and stopping -----------------------------------------------------------------
private Acknowledge startJobExecution(JobMasterId newJobMasterId) throws Exception {
validateRunsInMainThread();
checkNotNull(newJobMasterId, "The new JobMasterId must not be null.");
if (Objects.equals(getFencingToken(), newJobMasterId)) {
log.info("Already started the job execution with JobMasterId {}.", newJobMasterId);
return Acknowledge.get();
}
setNewFencingToken(newJobMasterId);
startJobMasterServices();
log.info("Starting execution of job {} ({}) under job master id {}.", jobGraph.getName(), jobGraph.getJobID(), newJobMasterId);
resetAndScheduleExecutionGraph();
return Acknowledge.get();
}
private void startJobMasterServices() throws Exception {
// start the slot pool make sure the slot pool now accepts messages for this leader
slotPool.start(getFencingToken(), getAddress(), getMainThreadExecutor());
scheduler.start(getMainThreadExecutor());
//TODO: Remove once the ZooKeeperLeaderRetrieval returns the stored address upon start
// try to reconnect to previously known leader
reconnectToResourceManager(new FlinkException("Starting JobMaster component."));
// job is ready to go, try to establish connection with resource manager
// - activate leader retrieval for the resource manager
// - on notification of the leader, the connection will be established and
// the slot pool will start requesting slots
resourceManagerLeaderRetriever.start(new ResourceManagerLeaderListener());
}
private void setNewFencingToken(JobMasterId newJobMasterId) {
if (getFencingToken() != null) {
log.info("Restarting old job with JobMasterId {}. The new JobMasterId is {}.", getFencingToken(), newJobMasterId);
// first we have to suspend the current execution
suspendExecution(new FlinkException("Old job with JobMasterId " + getFencingToken() +
" is restarted with a new JobMasterId " + newJobMasterId + '.'));
}
// set new leader id
setFencingToken(newJobMasterId);
}
/**
* Suspending job, all the running tasks will be cancelled, and communication with other components
* will be disposed.
*
* <p>Mostly job is suspended because of the leadership has been revoked, one can be restart this job by
* calling the {@link #start(JobMasterId)} method once we take the leadership back again.
*
* @param cause The reason of why this job been suspended.
*/
private Acknowledge suspendExecution(final Exception cause) {
validateRunsInMainThread();
if (getFencingToken() == null) {
log.debug("Job has already been suspended or shutdown.");
return Acknowledge.get();
}
// not leader anymore --> set the JobMasterId to null
setFencingToken(null);
try {
resourceManagerLeaderRetriever.stop();
resourceManagerAddress = null;
} catch (Throwable t) {
log.warn("Failed to stop resource manager leader retriever when suspending.", t);
}
suspendAndClearExecutionGraphFields(cause);
// the slot pool stops receiving messages and clears its pooled slots
slotPool.suspend();
// disconnect from resource manager:
closeResourceManagerConnection(cause);
return Acknowledge.get();
}
private void assignExecutionGraph(
ExecutionGraph newExecutionGraph,
JobManagerJobMetricGroup newJobManagerJobMetricGroup) {
validateRunsInMainThread();
checkState(executionGraph.getState().isTerminalState());
checkState(jobManagerJobMetricGroup == null);
executionGraph = newExecutionGraph;
jobManagerJobMetricGroup = newJobManagerJobMetricGroup;
}
private void resetAndScheduleExecutionGraph() throws Exception {
validateRunsInMainThread();
final CompletableFuture<Void> executionGraphAssignedFuture;
if (executionGraph.getState() == JobStatus.CREATED) {
executionGraphAssignedFuture = CompletableFuture.completedFuture(null);
executionGraph.start(getMainThreadExecutor());
} else {
suspendAndClearExecutionGraphFields(new FlinkException("ExecutionGraph is being reset in order to be rescheduled."));
final JobManagerJobMetricGroup newJobManagerJobMetricGroup = jobMetricGroupFactory.create(jobGraph);
final ExecutionGraph newExecutionGraph = createAndRestoreExecutionGraph(newJobManagerJobMetricGroup);
executionGraphAssignedFuture = executionGraph.getTerminationFuture().handle(
(JobStatus ignored, Throwable throwable) -> {
newExecutionGraph.start(getMainThreadExecutor());
assignExecutionGraph(newExecutionGraph, newJobManagerJobMetricGroup);
return null;
});
}
executionGraphAssignedFuture.thenRun(this::scheduleExecutionGraph);
}
private void scheduleExecutionGraph() {
checkState(jobStatusListener == null);
// register self as job status change listener
jobStatusListener = new JobManagerJobStatusListener();
executionGraph.registerJobStatusListener(jobStatusListener);
try {
executionGraph.scheduleForExecution();
}
catch (Throwable t) {
executionGraph.failGlobal(t);
}
}
private ExecutionGraph createAndRestoreExecutionGraph(JobManagerJobMetricGroup currentJobManagerJobMetricGroup) throws Exception {
ExecutionGraph newExecutionGraph = createExecutionGraph(currentJobManagerJobMetricGroup);
final CheckpointCoordinator checkpointCoordinator = newExecutionGraph.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
// check whether we find a valid checkpoint
if (!checkpointCoordinator.restoreLatestCheckpointedState(
newExecutionGraph.getAllVertices(),
false,
false)) {
// check whether we can restore from a savepoint
tryRestoreExecutionGraphFromSavepoint(newExecutionGraph, jobGraph.getSavepointRestoreSettings());
}
}
return newExecutionGraph;
}
private ExecutionGraph createExecutionGraph(JobManagerJobMetricGroup currentJobManagerJobMetricGroup) throws JobExecutionException, JobException {
return ExecutionGraphBuilder.buildGraph(
null,
jobGraph,
jobMasterConfiguration.getConfiguration(),
scheduledExecutorService,
scheduledExecutorService,
scheduler,
userCodeLoader,
highAvailabilityServices.getCheckpointRecoveryFactory(),
rpcTimeout,
restartStrategy,
currentJobManagerJobMetricGroup,
blobWriter,
jobMasterConfiguration.getSlotRequestTimeout(),
log);
}
private void suspendAndClearExecutionGraphFields(Exception cause) {
suspendExecutionGraph(cause);
clearExecutionGraphFields();
}
private void suspendExecutionGraph(Exception cause) {
executionGraph.suspend(cause);
if (jobManagerJobMetricGroup != null) {
jobManagerJobMetricGroup.close();
}
if (jobStatusListener != null) {
jobStatusListener.stop();
}
}
private void clearExecutionGraphFields() {
jobManagerJobMetricGroup = null;
jobStatusListener = null;
}
/**
* Dispose the savepoint stored under the given path.
*
* @param savepointPath path where the savepoint is stored
*/
private void disposeSavepoint(String savepointPath) {
try {
// delete the temporary savepoint
Checkpoints.disposeSavepoint(
savepointPath,
jobMasterConfiguration.getConfiguration(),
userCodeLoader,
log);
} catch (FlinkException | IOException e) {
log.info("Could not dispose temporary rescaling savepoint under {}.", savepointPath, e);
}
}
/**
* Tries to restore the given {@link ExecutionGraph} from the provided {@link SavepointRestoreSettings}.
*
* @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored
* @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about the savepoint to restore from
* @throws Exception if the {@link ExecutionGraph} could not be restored
*/
private void tryRestoreExecutionGraphFromSavepoint(ExecutionGraph executionGraphToRestore, SavepointRestoreSettings savepointRestoreSettings) throws Exception {
if (savepointRestoreSettings.restoreSavepoint()) {
final CheckpointCoordinator checkpointCoordinator = executionGraphToRestore.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
checkpointCoordinator.restoreSavepoint(
savepointRestoreSettings.getRestorePath(),
savepointRestoreSettings.allowNonRestoredState(),
executionGraphToRestore.getAllVertices(),
userCodeLoader);
}
}
}
//----------------------------------------------------------------------------------------------
private void handleJobMasterError(final Throwable cause) {
if (ExceptionUtils.isJvmFatalError(cause)) {
log.error("Fatal error occurred on JobManager.", cause);
// The fatal error handler implementation should make sure that this call is non-blocking
fatalErrorHandler.onFatalError(cause);
} else {
jobCompletionActions.jobMasterFailed(cause);
}
}
private void jobStatusChanged(
final JobStatus newJobStatus,
long timestamp,
@Nullable final Throwable error) {
validateRunsInMainThread();
if (newJobStatus.isGloballyTerminalState()) {
final ArchivedExecutionGraph archivedExecutionGraph = ArchivedExecutionGraph.createFrom(executionGraph);
scheduledExecutorService.execute(() -> jobCompletionActions.jobReachedGloballyTerminalState(archivedExecutionGraph));
}
}
private void notifyOfNewResourceManagerLeader(final String newResourceManagerAddress, final ResourceManagerId resourceManagerId) {
resourceManagerAddress = createResourceManagerAddress(newResourceManagerAddress, resourceManagerId);
reconnectToResourceManager(new FlinkException(String.format("ResourceManager leader changed to new address %s", resourceManagerAddress)));
}
@Nullable
private ResourceManagerAddress createResourceManagerAddress(@Nullable String newResourceManagerAddress, @Nullable ResourceManagerId resourceManagerId) {
if (newResourceManagerAddress != null) {
// the contract is: address == null <=> id == null
checkNotNull(resourceManagerId);
return new ResourceManagerAddress(newResourceManagerAddress, resourceManagerId);
} else {
return null;
}
}
private void reconnectToResourceManager(Exception cause) {
closeResourceManagerConnection(cause);
tryConnectToResourceManager();
}
private void tryConnectToResourceManager() {
if (resourceManagerAddress != null) {
connectToResourceManager();
}
}
private void connectToResourceManager() {
assert(resourceManagerAddress != null);
assert(resourceManagerConnection == null);
assert(establishedResourceManagerConnection == null);
log.info("Connecting to ResourceManager {}", resourceManagerAddress);
resourceManagerConnection = new ResourceManagerConnection(
log,
jobGraph.getJobID(),
resourceId,
getAddress(),
getFencingToken(),
resourceManagerAddress.getAddress(),
resourceManagerAddress.getResourceManagerId(),
scheduledExecutorService);
resourceManagerConnection.start();
}
private void establishResourceManagerConnection(final JobMasterRegistrationSuccess success) {
final ResourceManagerId resourceManagerId = success.getResourceManagerId();
// verify the response with current connection
if (resourceManagerConnection != null
&& Objects.equals(resourceManagerConnection.getTargetLeaderId(), resourceManagerId)) {
log.info("JobManager successfully registered at ResourceManager, leader id: {}.", resourceManagerId);
final ResourceManagerGateway resourceManagerGateway = resourceManagerConnection.getTargetGateway();
final ResourceID resourceManagerResourceId = success.getResourceManagerResourceId();
establishedResourceManagerConnection = new EstablishedResourceManagerConnection(
resourceManagerGateway,
resourceManagerResourceId);
slotPool.connectToResourceManager(resourceManagerGateway);
resourceManagerHeartbeatManager.monitorTarget(resourceManagerResourceId, new HeartbeatTarget<Void>() {
@Override
public void receiveHeartbeat(ResourceID resourceID, Void payload) {
resourceManagerGateway.heartbeatFromJobManager(resourceID);
}
@Override
public void requestHeartbeat(ResourceID resourceID, Void payload) {
// request heartbeat will never be called on the job manager side
}
});
} else {
log.debug("Ignoring resource manager connection to {} because it's duplicated or outdated.", resourceManagerId);
}
}
private void closeResourceManagerConnection(Exception cause) {
if (establishedResourceManagerConnection != null) {
dissolveResourceManagerConnection(establishedResourceManagerConnection, cause);
establishedResourceManagerConnection = null;
}
if (resourceManagerConnection != null) {
// stop a potentially ongoing registration process
resourceManagerConnection.close();
resourceManagerConnection = null;
}
}
private void dissolveResourceManagerConnection(EstablishedResourceManagerConnection establishedResourceManagerConnection, Exception cause) {
final ResourceID resourceManagerResourceID = establishedResourceManagerConnection.getResourceManagerResourceID();
if (log.isDebugEnabled()) {
log.debug("Close ResourceManager connection {}.", resourceManagerResourceID, cause);
} else {
log.info("Close ResourceManager connection {}: {}.", resourceManagerResourceID, cause.getMessage());
}
resourceManagerHeartbeatManager.unmonitorTarget(resourceManagerResourceID);
ResourceManagerGateway resourceManagerGateway = establishedResourceManagerConnection.getResourceManagerGateway();
resourceManagerGateway.disconnectJobManager(jobGraph.getJobID(), cause);
slotPool.disconnectResourceManager();
}
/**
* Restore the given {@link ExecutionGraph} from the rescaling savepoint. If the {@link ExecutionGraph} could
* be restored, then this savepoint will be recorded as the latest successful modification savepoint. A previous
* savepoint will be disposed. If the rescaling savepoint is empty, the job will be restored from the initially
* provided savepoint.
*
* @param newExecutionGraph to restore
* @param savepointFuture containing the path to the internal modification savepoint
* @return Future which is completed with the restored {@link ExecutionGraph}
*/
private CompletableFuture<ExecutionGraph> restoreExecutionGraphFromRescalingSavepoint(ExecutionGraph newExecutionGraph, CompletableFuture<String> savepointFuture) {
return savepointFuture
.thenApplyAsync(
(@Nullable String savepointPath) -> {
if (savepointPath != null) {
try {
tryRestoreExecutionGraphFromSavepoint(newExecutionGraph, SavepointRestoreSettings.forPath(savepointPath, false));
} catch (Exception e) {
final String message = String.format("Could not restore from temporary rescaling savepoint. This might indicate " +
"that the savepoint %s got corrupted. Deleting this savepoint as a precaution.",
savepointPath);
log.info(message);
CompletableFuture
.runAsync(
() -> {
if (savepointPath.equals(lastInternalSavepoint)) {
lastInternalSavepoint = null;
}
},
getMainThreadExecutor())
.thenRunAsync(
() -> disposeSavepoint(savepointPath),
scheduledExecutorService);
throw new CompletionException(new JobModificationException(message, e));
}
} else {
// No rescaling savepoint, restart from the initial savepoint or none
try {
tryRestoreExecutionGraphFromSavepoint(newExecutionGraph, jobGraph.getSavepointRestoreSettings());
} catch (Exception e) {
final String message = String.format("Could not restore from initial savepoint. This might indicate " +
"that the savepoint %s got corrupted.", jobGraph.getSavepointRestoreSettings().getRestorePath());
log.info(message);
throw new CompletionException(new JobModificationException(message, e));
}
}
return newExecutionGraph;
}, scheduledExecutorService);
}
/**
* Takes an internal savepoint for job modification purposes. If the savepoint was not successful because
* not all tasks were running, it returns the last successful modification savepoint.
*
* @param timeout for the operation
* @return Future which is completed with the savepoint path or the last successful modification savepoint if the
* former was not successful
*/
private CompletableFuture<String> getJobModificationSavepoint(Time timeout) {
return triggerSavepoint(
null,
false,
timeout)
.handleAsync(
(String savepointPath, Throwable throwable) -> {
if (throwable != null) {
final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable);
if (strippedThrowable instanceof CheckpointTriggerException) {
final CheckpointTriggerException checkpointTriggerException = (CheckpointTriggerException) strippedThrowable;
if (checkpointTriggerException.getCheckpointDeclineReason() == CheckpointDeclineReason.NOT_ALL_REQUIRED_TASKS_RUNNING) {
return lastInternalSavepoint;
} else {
throw new CompletionException(checkpointTriggerException);
}
} else {
throw new CompletionException(strippedThrowable);
}
} else {
final String savepointToDispose = lastInternalSavepoint;
lastInternalSavepoint = savepointPath;
if (savepointToDispose != null) {
// dispose the old savepoint asynchronously
CompletableFuture.runAsync(
() -> disposeSavepoint(savepointToDispose),
scheduledExecutorService);
}
return lastInternalSavepoint;
}
},
getMainThreadExecutor());
}
/**
* Rescales the given operators of the {@link JobGraph} of this {@link JobMaster} with respect to given
* parallelism and {@link RescalingBehaviour}.
*
* @param operators to rescale
* @param newParallelism new parallelism for these operators
* @param rescalingBehaviour of the rescaling operation
* @throws FlinkException if the {@link JobGraph} could not be rescaled
*/
private void rescaleJobGraph(Collection<JobVertexID> operators, int newParallelism, RescalingBehaviour rescalingBehaviour) throws FlinkException {
for (JobVertexID jobVertexId : operators) {
final JobVertex jobVertex = jobGraph.findVertexByID(jobVertexId);
// update max parallelism in case that it has not been configured
final ExecutionJobVertex executionJobVertex = executionGraph.getJobVertex(jobVertexId);
if (executionJobVertex != null) {
jobVertex.setMaxParallelism(executionJobVertex.getMaxParallelism());
}
rescalingBehaviour.accept(jobVertex, newParallelism);
}
}
//----------------------------------------------------------------------------------------------
// Service methods
//----------------------------------------------------------------------------------------------
@Override
public JobMasterGateway getGateway() {
return getSelfGateway(JobMasterGateway.class);
}
//----------------------------------------------------------------------------------------------
// Utility classes
//----------------------------------------------------------------------------------------------
private class ResourceManagerLeaderListener implements LeaderRetrievalListener {
@Override
public void notifyLeaderAddress(final String leaderAddress, final UUID leaderSessionID) {
runAsync(
() -> notifyOfNewResourceManagerLeader(
leaderAddress,
ResourceManagerId.fromUuidOrNull(leaderSessionID)));
}
@Override
public void handleError(final Exception exception) {
handleJobMasterError(new Exception("Fatal error in the ResourceManager leader service", exception));
}
}
//----------------------------------------------------------------------------------------------
private class ResourceManagerConnection
extends RegisteredRpcConnection<ResourceManagerId, ResourceManagerGateway, JobMasterRegistrationSuccess> {
private final JobID jobID;
private final ResourceID jobManagerResourceID;
private final String jobManagerRpcAddress;
private final JobMasterId jobMasterId;
ResourceManagerConnection(
final Logger log,
final JobID jobID,
final ResourceID jobManagerResourceID,
final String jobManagerRpcAddress,
final JobMasterId jobMasterId,
final String resourceManagerAddress,
final ResourceManagerId resourceManagerId,
final Executor executor) {
super(log, resourceManagerAddress, resourceManagerId, executor);
this.jobID = checkNotNull(jobID);
this.jobManagerResourceID = checkNotNull(jobManagerResourceID);
this.jobManagerRpcAddress = checkNotNull(jobManagerRpcAddress);
this.jobMasterId = checkNotNull(jobMasterId);
}
@Override
protected RetryingRegistration<ResourceManagerId, ResourceManagerGateway, JobMasterRegistrationSuccess> generateRegistration() {
return new RetryingRegistration<ResourceManagerId, ResourceManagerGateway, JobMasterRegistrationSuccess>(
log,
getRpcService(),
"ResourceManager",
ResourceManagerGateway.class,
getTargetAddress(),
getTargetLeaderId(),
jobMasterConfiguration.getRetryingRegistrationConfiguration()) {
@Override
protected CompletableFuture<RegistrationResponse> invokeRegistration(
ResourceManagerGateway gateway, ResourceManagerId fencingToken, long timeoutMillis) {
Time timeout = Time.milliseconds(timeoutMillis);
return gateway.registerJobManager(
jobMasterId,
jobManagerResourceID,
jobManagerRpcAddress,
jobID,
timeout);
}
};
}
@Override
protected void onRegistrationSuccess(final JobMasterRegistrationSuccess success) {
runAsync(() -> {
// filter out outdated connections
//noinspection ObjectEquality
if (this == resourceManagerConnection) {
establishResourceManagerConnection(success);
}
});
}
@Override
protected void onRegistrationFailure(final Throwable failure) {
handleJobMasterError(failure);
}
}
//----------------------------------------------------------------------------------------------
private class JobManagerJobStatusListener implements JobStatusListener {
private volatile boolean running = true;
@Override
public void jobStatusChanges(
final JobID jobId,
final JobStatus newJobStatus,
final long timestamp,
final Throwable error) {
if (running) {
// run in rpc thread to avoid concurrency
runAsync(() -> jobStatusChanged(newJobStatus, timestamp, error));
}
}
private void stop() {
running = false;
}
}
private class TaskManagerHeartbeatListener implements HeartbeatListener<AccumulatorReport, Void> {
private final JobMasterGateway jobMasterGateway;
private TaskManagerHeartbeatListener(JobMasterGateway jobMasterGateway) {
this.jobMasterGateway = Preconditions.checkNotNull(jobMasterGateway);
}
@Override
public void notifyHeartbeatTimeout(ResourceID resourceID) {
jobMasterGateway.disconnectTaskManager(
resourceID,
new TimeoutException("Heartbeat of TaskManager with id " + resourceID + " timed out."));
}
@Override
public void reportPayload(ResourceID resourceID, AccumulatorReport payload) {
for (AccumulatorSnapshot snapshot : payload.getAccumulatorSnapshots()) {
executionGraph.updateAccumulators(snapshot);
}
}
@Override
public CompletableFuture<Void> retrievePayload(ResourceID resourceID) {
return CompletableFuture.completedFuture(null);
}
}
private class ResourceManagerHeartbeatListener implements HeartbeatListener<Void, Void> {
@Override
public void notifyHeartbeatTimeout(final ResourceID resourceId) {
runAsync(() -> {
log.info("The heartbeat of ResourceManager with id {} timed out.", resourceId);
if (establishedResourceManagerConnection != null && establishedResourceManagerConnection.getResourceManagerResourceID().equals(resourceId)) {
reconnectToResourceManager(
new JobMasterException(
String.format("The heartbeat of ResourceManager with id %s timed out.", resourceId)));
}
});
}
@Override
public void reportPayload(ResourceID resourceID, Void payload) {
// nothing to do since the payload is of type Void
}
@Override
public CompletableFuture<Void> retrievePayload(ResourceID resourceID) {
return CompletableFuture.completedFuture(null);
}
}
@VisibleForTesting
RestartStrategy getRestartStrategy() {
return restartStrategy;
}
@VisibleForTesting
ExecutionGraph getExecutionGraph() {
return executionGraph;
}
}
| [FLINK-11718] Remove start override from JobMaster
| flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java | [FLINK-11718] Remove start override from JobMaster | <ide><path>link-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java
<ide> // Lifecycle management
<ide> //----------------------------------------------------------------------------------------------
<ide>
<del> @Override
<del> public void start() {
<del> throw new UnsupportedOperationException("Should never call start() without leader ID");
<del> }
<del>
<ide> /**
<ide> * Start the rpc service and begin to run the job.
<ide> *
<ide> */
<ide> public CompletableFuture<Acknowledge> start(final JobMasterId newJobMasterId) throws Exception {
<ide> // make sure we receive RPC and async calls
<del> super.start();
<add> start();
<ide>
<ide> return callAsyncWithoutFencing(() -> startJobExecution(newJobMasterId), RpcUtils.INF_TIMEOUT);
<ide> } |
|
Java | apache-2.0 | dc1671ca509586d7fecb81e24fddab56d5380dae | 0 | apache/incubator-kylin,apache/kylin,apache/kylin,apache/kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin | /*
* 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.kylin.engine.mr.steps;
import java.io.IOException;
import java.util.Random;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.persistence.ResourceStore;
import org.apache.kylin.cube.CubeInstance;
import org.apache.kylin.cube.CubeManager;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.engine.mr.CubingJob;
import org.apache.kylin.engine.mr.CubingJob.AlgorithmEnum;
import org.apache.kylin.engine.mr.HadoopUtil;
import org.apache.kylin.engine.mr.common.BatchConstants;
import org.apache.kylin.engine.mr.common.CubeStatsReader;
import org.apache.kylin.job.exception.ExecuteException;
import org.apache.kylin.job.execution.AbstractExecutable;
import org.apache.kylin.job.execution.ExecutableContext;
import org.apache.kylin.job.execution.ExecuteResult;
import org.apache.kylin.metadata.model.MeasureDesc;
/**
* Save the cube segment statistic to Kylin metadata store
*
*/
public class SaveStatisticsStep extends AbstractExecutable {
public SaveStatisticsStep() {
super();
}
@Override
protected ExecuteResult doWork(ExecutableContext context) throws ExecuteException {
final CubeManager mgr = CubeManager.getInstance(context.getConfig());
final CubeInstance cube = mgr.getCube(CubingExecutableUtil.getCubeName(this.getParams()));
final CubeSegment newSegment = cube.getSegmentById(CubingExecutableUtil.getSegmentId(this.getParams()));
KylinConfig kylinConf = cube.getConfig();
ResourceStore rs = ResourceStore.getStore(kylinConf);
try {
Path statisticsFilePath = new Path(CubingExecutableUtil.getStatisticsPath(this.getParams()), BatchConstants.CFG_STATISTICS_CUBOID_ESTIMATION_FILENAME);
FileSystem fs = FileSystem.get(HadoopUtil.getCurrentConfiguration());
if (!fs.exists(statisticsFilePath))
throw new IOException("File " + statisticsFilePath + " does not exists");
FSDataInputStream is = fs.open(statisticsFilePath);
try {
// put the statistics to metadata store
String statisticsFileName = newSegment.getStatisticsResourcePath();
rs.putResource(statisticsFileName, is, System.currentTimeMillis());
} finally {
IOUtils.closeStream(is);
fs.delete(statisticsFilePath, true);
}
decideCubingAlgorithm(newSegment, kylinConf);
return new ExecuteResult(ExecuteResult.State.SUCCEED, "succeed");
} catch (IOException e) {
logger.error("fail to save cuboid statistics", e);
return new ExecuteResult(ExecuteResult.State.ERROR, e.getLocalizedMessage());
}
}
private void decideCubingAlgorithm(CubeSegment seg, KylinConfig kylinConf) throws IOException {
String algPref = kylinConf.getCubeAlgorithm();
AlgorithmEnum alg;
if (AlgorithmEnum.INMEM.name().equalsIgnoreCase(algPref)) {
alg = AlgorithmEnum.INMEM;
} else if (AlgorithmEnum.LAYER.name().equalsIgnoreCase(algPref)) {
alg = AlgorithmEnum.LAYER;
} else {
int memoryHungryMeasures = 0;
for (MeasureDesc measure : seg.getCubeDesc().getMeasures()) {
if (measure.getFunction().getMeasureType().isMemoryHungry()) {
logger.info("This cube has memory-hungry measure " + measure.getFunction().getExpression());
memoryHungryMeasures++;
}
}
if (memoryHungryMeasures > 4 || (kylinConf.isDevEnv() && memoryHungryMeasures > 0)) {
alg = AlgorithmEnum.LAYER;
} else if ("random".equalsIgnoreCase(algPref)) { // for testing
alg = new Random().nextBoolean() ? AlgorithmEnum.INMEM : AlgorithmEnum.LAYER;
} else { // the default
double threshold = kylinConf.getCubeAlgorithmAutoThreshold();
double mapperOverlapRatio = new CubeStatsReader(seg, kylinConf).getMapperOverlapRatioOfFirstBuild();
logger.info("mapperOverlapRatio for " + seg + " is " + mapperOverlapRatio + " and threshold is " + threshold);
alg = mapperOverlapRatio < threshold ? AlgorithmEnum.INMEM : AlgorithmEnum.LAYER;
}
}
logger.info("The cube algorithm for " + seg + " is " + alg);
CubingJob cubingJob = (CubingJob) executableManager.getJob(CubingExecutableUtil.getCubingJobId(this.getParams()));
cubingJob.setAlgorithm(alg);
}
}
| engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/SaveStatisticsStep.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.kylin.engine.mr.steps;
import java.io.IOException;
import java.util.Random;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.persistence.ResourceStore;
import org.apache.kylin.cube.CubeInstance;
import org.apache.kylin.cube.CubeManager;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.engine.mr.CubingJob;
import org.apache.kylin.engine.mr.CubingJob.AlgorithmEnum;
import org.apache.kylin.engine.mr.HadoopUtil;
import org.apache.kylin.engine.mr.common.BatchConstants;
import org.apache.kylin.engine.mr.common.CubeStatsReader;
import org.apache.kylin.job.exception.ExecuteException;
import org.apache.kylin.job.execution.AbstractExecutable;
import org.apache.kylin.job.execution.ExecutableContext;
import org.apache.kylin.job.execution.ExecuteResult;
import org.apache.kylin.metadata.model.MeasureDesc;
/**
* Save the cube segment statistic to Kylin metadata store
*
*/
public class SaveStatisticsStep extends AbstractExecutable {
public SaveStatisticsStep() {
super();
}
@Override
protected ExecuteResult doWork(ExecutableContext context) throws ExecuteException {
final CubeManager mgr = CubeManager.getInstance(context.getConfig());
final CubeInstance cube = mgr.getCube(CubingExecutableUtil.getCubeName(this.getParams()));
final CubeSegment newSegment = cube.getSegmentById(CubingExecutableUtil.getSegmentId(this.getParams()));
KylinConfig kylinConf = cube.getConfig();
ResourceStore rs = ResourceStore.getStore(kylinConf);
try {
Path statisticsFilePath = new Path(CubingExecutableUtil.getStatisticsPath(this.getParams()), BatchConstants.CFG_STATISTICS_CUBOID_ESTIMATION_FILENAME);
FileSystem fs = FileSystem.get(HadoopUtil.getCurrentConfiguration());
if (!fs.exists(statisticsFilePath))
throw new IOException("File " + statisticsFilePath + " does not exists");
FSDataInputStream is = fs.open(statisticsFilePath);
try {
// put the statistics to metadata store
String statisticsFileName = newSegment.getStatisticsResourcePath();
rs.putResource(statisticsFileName, is, System.currentTimeMillis());
} finally {
IOUtils.closeStream(is);
fs.delete(statisticsFilePath, true);
}
decideCubingAlgorithm(newSegment, kylinConf);
return new ExecuteResult(ExecuteResult.State.SUCCEED, "succeed");
} catch (IOException e) {
logger.error("fail to save cuboid statistics", e);
return new ExecuteResult(ExecuteResult.State.ERROR, e.getLocalizedMessage());
}
}
private void decideCubingAlgorithm(CubeSegment seg, KylinConfig kylinConf) throws IOException {
String algPref = kylinConf.getCubeAlgorithm();
AlgorithmEnum alg;
if (AlgorithmEnum.INMEM.name().equalsIgnoreCase(algPref)) {
alg = AlgorithmEnum.INMEM;
} else if (AlgorithmEnum.LAYER.name().equalsIgnoreCase(algPref)) {
alg = AlgorithmEnum.LAYER;
} else {
boolean memoryHungry = false;
for (MeasureDesc measure : seg.getCubeDesc().getMeasures()) {
if (measure.getFunction().getMeasureType().isMemoryHungry()) {
logger.info("This cube has memory-hungry measure " + measure.getFunction().getExpression());
memoryHungry = true;
break;
}
}
if (memoryHungry == true) {
alg = AlgorithmEnum.LAYER;
} else if ("random".equalsIgnoreCase(algPref)) { // for testing
alg = new Random().nextBoolean() ? AlgorithmEnum.INMEM : AlgorithmEnum.LAYER;
} else { // the default
double threshold = kylinConf.getCubeAlgorithmAutoThreshold();
double mapperOverlapRatio = new CubeStatsReader(seg, kylinConf).getMapperOverlapRatioOfFirstBuild();
logger.info("mapperOverlapRatio for " + seg + " is " + mapperOverlapRatio + " and threshold is " + threshold);
alg = mapperOverlapRatio < threshold ? AlgorithmEnum.INMEM : AlgorithmEnum.LAYER;
}
}
logger.info("The cube algorithm for " + seg + " is " + alg);
CubingJob cubingJob = (CubingJob) executableManager.getJob(CubingExecutableUtil.getCubingJobId(this.getParams()));
cubingJob.setAlgorithm(alg);
}
}
| KYLIN-1418 Memory hungry cube should select LAYER and INMEM cubing smartly
Signed-off-by: shaofengshi <[email protected]>
| engine-mr/src/main/java/org/apache/kylin/engine/mr/steps/SaveStatisticsStep.java | KYLIN-1418 Memory hungry cube should select LAYER and INMEM cubing smartly | <ide><path>ngine-mr/src/main/java/org/apache/kylin/engine/mr/steps/SaveStatisticsStep.java
<ide> } else if (AlgorithmEnum.LAYER.name().equalsIgnoreCase(algPref)) {
<ide> alg = AlgorithmEnum.LAYER;
<ide> } else {
<del> boolean memoryHungry = false;
<add> int memoryHungryMeasures = 0;
<ide> for (MeasureDesc measure : seg.getCubeDesc().getMeasures()) {
<ide> if (measure.getFunction().getMeasureType().isMemoryHungry()) {
<ide> logger.info("This cube has memory-hungry measure " + measure.getFunction().getExpression());
<del> memoryHungry = true;
<del> break;
<add> memoryHungryMeasures++;
<ide> }
<ide> }
<ide>
<del> if (memoryHungry == true) {
<add> if (memoryHungryMeasures > 4 || (kylinConf.isDevEnv() && memoryHungryMeasures > 0)) {
<ide> alg = AlgorithmEnum.LAYER;
<ide> } else if ("random".equalsIgnoreCase(algPref)) { // for testing
<ide> alg = new Random().nextBoolean() ? AlgorithmEnum.INMEM : AlgorithmEnum.LAYER; |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/silverpop/api/client/command/DoubleOptInRecipientCommand.java' did not match any file(s) known to git
| ffd44bb1a60dfeeeebe4dbf30b5b37b2f4d843c0 | 1 | rkovarik/engage-api-client | package com.silverpop.api.client.command;
import java.util.ArrayList;
import java.util.List;
import com.silverpop.api.client.ApiCommand;
import com.silverpop.api.client.XmlApiProperties;
import com.silverpop.api.client.command.elements.Column;
import com.silverpop.api.client.result.RecipientResult;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XmlApiProperties("DoubleOptInRecipient")
public class DoubleOptInRecipientCommand implements ApiCommand {
@XStreamAlias("LIST_ID")
private Integer listId;
@XStreamAlias("SEND_AUTOREPLY")
private Boolean sendAutoreply;
@XStreamAlias("ALLOW_HTML")
private Boolean allowHtml;
@XStreamImplicit(itemFieldName = "COLUMN")
private List<Column> columns;
public DoubleOptInRecipientCommand() {
columns = new ArrayList<Column>();
}
@Override
public Class<RecipientResult> getResultType() {
return RecipientResult.class;
}
public Integer getListId() {
return listId;
}
public void setListId(Integer listId) {
this.listId = listId;
}
public Boolean getSendAutoreply() {
return sendAutoreply;
}
public void setSendAutoreply(Boolean sendAutoreply) {
this.sendAutoreply = sendAutoreply;
}
public Boolean getAllowHtml() {
return allowHtml;
}
public void setAllowHtml(Boolean allowHtml) {
this.allowHtml = allowHtml;
}
public List<Column> getColumns() {
return columns;
}
public void setColumns(List<Column> columns) {
this.columns = columns;
}
public void addColumn(final Column column) {
this.columns.add(column);
}
}
| src/main/java/com/silverpop/api/client/command/DoubleOptInRecipientCommand.java | Issue #37 implement DoubleOptInRecipientCommand
| src/main/java/com/silverpop/api/client/command/DoubleOptInRecipientCommand.java | Issue #37 implement DoubleOptInRecipientCommand | <ide><path>rc/main/java/com/silverpop/api/client/command/DoubleOptInRecipientCommand.java
<add>package com.silverpop.api.client.command;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>import com.silverpop.api.client.ApiCommand;
<add>import com.silverpop.api.client.XmlApiProperties;
<add>import com.silverpop.api.client.command.elements.Column;
<add>import com.silverpop.api.client.result.RecipientResult;
<add>import com.thoughtworks.xstream.annotations.XStreamAlias;
<add>import com.thoughtworks.xstream.annotations.XStreamImplicit;
<add>
<add>@XmlApiProperties("DoubleOptInRecipient")
<add>public class DoubleOptInRecipientCommand implements ApiCommand {
<add>
<add> @XStreamAlias("LIST_ID")
<add> private Integer listId;
<add>
<add> @XStreamAlias("SEND_AUTOREPLY")
<add> private Boolean sendAutoreply;
<add>
<add> @XStreamAlias("ALLOW_HTML")
<add> private Boolean allowHtml;
<add>
<add> @XStreamImplicit(itemFieldName = "COLUMN")
<add> private List<Column> columns;
<add>
<add>
<add> public DoubleOptInRecipientCommand() {
<add> columns = new ArrayList<Column>();
<add> }
<add>
<add> @Override
<add> public Class<RecipientResult> getResultType() {
<add> return RecipientResult.class;
<add> }
<add>
<add> public Integer getListId() {
<add> return listId;
<add> }
<add>
<add> public void setListId(Integer listId) {
<add> this.listId = listId;
<add> }
<add>
<add> public Boolean getSendAutoreply() {
<add> return sendAutoreply;
<add> }
<add>
<add> public void setSendAutoreply(Boolean sendAutoreply) {
<add> this.sendAutoreply = sendAutoreply;
<add> }
<add>
<add> public Boolean getAllowHtml() {
<add> return allowHtml;
<add> }
<add>
<add> public void setAllowHtml(Boolean allowHtml) {
<add> this.allowHtml = allowHtml;
<add> }
<add>
<add> public List<Column> getColumns() {
<add> return columns;
<add> }
<add>
<add> public void setColumns(List<Column> columns) {
<add> this.columns = columns;
<add> }
<add>
<add> public void addColumn(final Column column) {
<add> this.columns.add(column);
<add> }
<add>} |
|
Java | agpl-3.0 | 58413e92ead4d04d999bf7bc18609578dd7a2087 | 0 | splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine | package com.splicemachine.derby.impl.sql.execute.operations;
import static com.splicemachine.test_tools.Rows.row;
import static com.splicemachine.test_tools.Rows.rows;
import static org.junit.Assert.fail;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import com.splicemachine.derby.test.framework.SpliceSchemaWatcher;
import com.splicemachine.derby.test.framework.SpliceWatcher;
import com.splicemachine.homeless.TestUtils;
import com.splicemachine.test_tools.TableCreator;
/**
* @author Jeff Cunningham
* Date: 2/19/15
*/
public class SimpleDateArithmeticIT {
private static SpliceWatcher spliceClassWatcher = new SpliceWatcher();
private static SpliceSchemaWatcher schemaWatcher =
new SpliceSchemaWatcher(SimpleDateArithmeticIT.class.getSimpleName().toUpperCase());
private static final String QUALIFIED_TABLE_NAME = schemaWatcher.schemaName + ".date_add_test";
@ClassRule
public static TestRule chain = RuleChain.outerRule(spliceClassWatcher)
.around(schemaWatcher);
@BeforeClass
public static void createTable() throws Exception {
new TableCreator(spliceClassWatcher.getOrCreateConnection())
.withCreate(String.format("create table %s (s varchar(15), d date, t timestamp, t2 timestamp)", QUALIFIED_TABLE_NAME))
.withInsert(String.format("insert into %s values(?,?,?,?)", QUALIFIED_TABLE_NAME))
.withRows(rows(
row("2012-05-23", new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-26"), Timestamp.valueOf("2000-06-07 17:12:30"), Timestamp.valueOf("2012-12-13 00:00:00"))))
.create();
}
//=========================================================================================================
// Date column
//=========================================================================================================
@Test
public void testPlusDateColumn() throws Exception {
String sqlText =
String.format("select d + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"1988-12-27 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusDateColumn() throws Exception {
String sqlText =
String.format("select d + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"1988-12-27 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testPlusDateColumnCommutative() throws Exception {
String sqlText =
String.format("select 4 + d from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"1988-12-30 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusDateColumnNotCommutative() throws Exception {
String sqlText =
String.format("select 4 - d from %s", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("The '-' operator with a left operand type of 'INTEGER' and a right operand type of 'DATE' is not supported.",
e.getLocalizedMessage());
}
}
@Test
public void testCurrentDateMinusDateColumn() throws Exception {
String sqlText = String.format("select current_date - d from %s", QUALIFIED_TABLE_NAME);
int rows = 0;
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
// can't use static result compare with CURRENT_DATE funct. Best we can do is count rows.
++rows;
}
Assert.assertTrue("\n" + sqlText + "\nExpected at least one row.", rows > 0);
}
@Test
public void testDateColumnMinusCurrentDate() throws Exception {
String sqlText = String.format("select d - current_date from %s", QUALIFIED_TABLE_NAME);
int rows = 0;
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
// can't use static result compare with CURRENT_DATE funct. Best we can do is count rows.
++rows;
}
Assert.assertTrue("\n" + sqlText + "\nExpected at least one row.", rows > 0);
}
//=========================================================================================================
// Values Date
//=========================================================================================================
@Test
public void testPlusDateValues() throws Exception {
String sqlText = "values date('2011-12-26') + 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2011-12-27 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusDateValues() throws Exception {
String sqlText = "values date('2011-12-26') - 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2011-12-25 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testDateMinusDatePositiveValues() throws Exception {
String sqlText = "values date('2011-12-26') - date('2011-06-05')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----\n" +
"204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testDateMinusDateNegativeValues() throws Exception {
String sqlText = "values date('2011-06-05') - date('2011-12-26')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------\n" +
"-204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testDatePlusDateValuesError() throws Exception {
String sqlText = "values date('2011-12-26') + date('2011-06-05')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("DATEs cannot be added. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testMultiplyPlusDateValuesError() throws Exception {
String sqlText = "values date('2011-12-26') * date('2011-06-05')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("DATEs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testDateDivideDateValuesError() throws Exception {
String sqlText = "values date('2011-12-26') / date('2011-06-05')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("DATEs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testDateWithCurrentDateValues() throws Exception {
String sqlText = "values (current_date - 1) - current_date + 2";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"----\n" +
" 1 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
//=========================================================================================================
// Timestamp column
//=========================================================================================================
@Test
public void testPlusTimestampColumn() throws Exception {
String sqlText =
String.format("select t + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2000-06-08 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusTimestampColumn() throws Exception {
String sqlText =
String.format("select t + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2000-06-08 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testPlusTimestampColumnCommutative() throws Exception {
String sqlText =
String.format("select 4 + t from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2000-06-11 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusTimestampColumnNotCommutative() throws Exception {
String sqlText =
String.format("select 4 - t from %s", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("The '-' operator with a left operand type of 'INTEGER' and a right operand type of 'TIMESTAMP' is not supported.",
e.getLocalizedMessage());
}
}
//=========================================================================================================
// Values Timestamp
//=========================================================================================================
@Test
public void testPlusTimestampValues() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') + 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2011-12-27 17:13:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusTimestampValues() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') - 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2011-12-25 17:13:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampMinusTimestampPositiveValues() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') - timestamp('2011-06-05', '05:06:00')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----\n" +
"204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampMinusTimestampNegativeValues() throws Exception {
String sqlText = "values timestamp('2011-06-05', '05:06:00') - timestamp('2011-12-26', '17:13:30')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------\n" +
"-204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testIntegerPlusTimestampValues() throws Exception {
// DB-2943
String sqlText = "values 1+ timestamp('2011-06-05', '05:06:00')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2011-06-06 05:06:00.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampPlusTimestampValuesError() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') + timestamp('2011-06-05', '05:06:00')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("TIMESTAMPs cannot be added. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testMultiplyPlusTimestampValuesError() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') * timestamp('2011-06-05', '05:06:00')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("TIMESTAMPs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testTimestampDivideTimestampValuesError() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') / timestamp('2011-06-05', '05:06:00')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("TIMESTAMPs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
//=========================================================================================================
// Values Timestamp/Date mixed and interesting edge cases
//=========================================================================================================
@Test
public void testDateMinusTimestampValues() throws Exception {
String sqlText = "values date('2011-06-04') - timestamp('2011-06-05', '05:06:00')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"----\n" +
"-1 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampMinusDateValues() throws Exception {
String sqlText = "values timestamp('2011-06-05', '05:06:00') - date('2011-12-26')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------\n" +
"-203 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testAddDateOnLeapYear() throws Exception {
String sqlText = "values Date('2016-02-28') + 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2016-02-29 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testAddDateOnLeapYear2() throws Exception {
String sqlText = "values Date('2016-02-28') + 2 - 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2016-02-29 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testAddDateOnLeapYear3() throws Exception {
String sqlText = "values timestamp('2016-03-28', '22:13:13') - 28";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2016-02-29 22:13:13.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampGTDateCompare() throws Exception {
String sqlText = String.format("select t from %s where t > '2000-04-01'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"T |\n" +
"-----------------------\n" +
"2000-06-07 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testTimestampLTDateCompare() throws Exception {
String sqlText = String.format("select t from %s where t < '2000-07-01'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"T |\n" +
"-----------------------\n" +
"2000-06-07 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testTimestampNETDateCompare() throws Exception {
String sqlText = String.format("select t from %s where t != '2000-06-07'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"T |\n" +
"-----------------------\n" +
"2000-06-07 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testTimestampETDateCompare() throws Exception {
String sqlText = String.format("select t2 from %s where t2 = '2012-12-13'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"T2 |\n" +
"-----------------------\n" +
"2012-12-13 00:00:00.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testDateGTTimestampCompareColummn() throws Exception {
String sqlText = String.format("select d from %s where d > '1988-11-24 00:00:00'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"D |\n" +
"------------\n" +
"1988-12-26 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testDateGTTimestampCompareValues() throws Exception {
String sqlText = "values date('2088-12-26') > '2088-12-25 00:00:00'";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"1 |\n" +
"------\n" +
"true |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testDateLTTimestampCompare() throws Exception {
String sqlText = String.format("select d from %s where d < '1988-12-29 00:00:00'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"D |\n" +
"------------\n" +
"1988-12-26 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testDateNETTimestampCompare() throws Exception {
String sqlText = String.format("select d from %s where d != '1988-12-25 00:00:00'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"D |\n" +
"------------\n" +
"1988-12-26 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testDateETTimestampCompareColumn() throws Exception {
String sqlText = String.format("select d from %s where d = '1988-12-26 00:00:00'", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"D |\n" +
"------------\n" +
"1988-12-26 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testDateETTimestampCompareValues() throws Exception {
String sqlText = "values date('2088-12-26') = '2088-12-26 00:00:00'";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"1 |\n" +
"------\n" +
"true |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testCastToTimestamp() throws Exception {
String sqlText = "values cast(add_months('1993-07-01',3) as timestamp)";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"1 |\n" +
"-----------------------\n" +
"1993-10-01 00:00:00.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
@Test
public void testCastToDate() throws Exception {
String sqlText = "values cast(add_months('1993-07-01 00:00:00',3) as date)";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
String expected =
"1 |\n" +
"------------\n" +
"1993-10-01 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
}
}
}
| splice_machine_test/src/test/java/com/splicemachine/derby/impl/sql/execute/operations/SimpleDateArithmeticIT.java | package com.splicemachine.derby.impl.sql.execute.operations;
import static com.splicemachine.test_tools.Rows.row;
import static com.splicemachine.test_tools.Rows.rows;
import static org.junit.Assert.fail;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import com.splicemachine.derby.test.framework.SpliceSchemaWatcher;
import com.splicemachine.derby.test.framework.SpliceWatcher;
import com.splicemachine.homeless.TestUtils;
import com.splicemachine.test_tools.TableCreator;
/**
* @author Jeff Cunningham
* Date: 2/19/15
*/
public class SimpleDateArithmeticIT {
private static SpliceWatcher spliceClassWatcher = new SpliceWatcher();
private static SpliceSchemaWatcher schemaWatcher =
new SpliceSchemaWatcher(SimpleDateArithmeticIT.class.getSimpleName().toUpperCase());
private static final String QUALIFIED_TABLE_NAME = schemaWatcher.schemaName + ".date_add_test";
@ClassRule
public static TestRule chain = RuleChain.outerRule(spliceClassWatcher)
.around(schemaWatcher);
@BeforeClass
public static void createTable() throws Exception {
new TableCreator(spliceClassWatcher.getOrCreateConnection())
.withCreate(String.format("create table %s (s varchar(15), d date, t timestamp)", QUALIFIED_TABLE_NAME))
.withInsert(String.format("insert into %s values(?,?,?)", QUALIFIED_TABLE_NAME))
.withRows(rows(
row("2012-05-23", new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-26"), Timestamp.valueOf("2000-06-07 17:12:30"))))
.create();
}
@Test
public void testSelect() throws Exception {
String sqlText =
String.format("SELECT * from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"S | D | T |\n" +
"-----------------------------------------------\n" +
"2012-05-23 |1988-12-26 |2000-06-07 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
//=========================================================================================================
// Date column
//=========================================================================================================
@Test
public void testPlusDateColumn() throws Exception {
String sqlText =
String.format("select d + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"1988-12-27 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusDateColumn() throws Exception {
String sqlText =
String.format("select d + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"1988-12-27 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testPlusDateColumnCommutative() throws Exception {
String sqlText =
String.format("select 4 + d from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"1988-12-30 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusDateColumnNotCommutative() throws Exception {
String sqlText =
String.format("select 4 - d from %s", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("The '-' operator with a left operand type of 'INTEGER' and a right operand type of 'DATE' is not supported.",
e.getLocalizedMessage());
}
}
//=========================================================================================================
// Values Date
//=========================================================================================================
@Test
public void testPlusDateValues() throws Exception {
String sqlText = "values date('2011-12-26') + 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2011-12-27 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusDateValues() throws Exception {
String sqlText = "values date('2011-12-26') - 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2011-12-25 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testDateMinusDatePositiveValues() throws Exception {
String sqlText = "values date('2011-12-26') - date('2011-06-05')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----\n" +
"204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testDateMinusDateNegativeValues() throws Exception {
String sqlText = "values date('2011-06-05') - date('2011-12-26')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------\n" +
"-204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testDatePlusDateValuesError() throws Exception {
String sqlText = "values date('2011-12-26') + date('2011-06-05')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("DATEs cannot be added. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testMultiplyPlusDateValuesError() throws Exception {
String sqlText = "values date('2011-12-26') * date('2011-06-05')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("DATEs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testDateDivideDateValuesError() throws Exception {
String sqlText = "values date('2011-12-26') / date('2011-06-05')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("DATEs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testDateWithCurrentDateValues() throws Exception {
String sqlText = "values (current_date - 1) - current_date + 2";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"----\n" +
" 1 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
//=========================================================================================================
// Timestamp column
//=========================================================================================================
@Test
public void testPlusTimestampColumn() throws Exception {
String sqlText =
String.format("select t + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2000-06-08 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusTimestampColumn() throws Exception {
String sqlText =
String.format("select t + 1 from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2000-06-08 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testPlusTimestampColumnCommutative() throws Exception {
String sqlText =
String.format("select 4 + t from %s", QUALIFIED_TABLE_NAME);
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2000-06-11 17:12:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusTimestampColumnNotCommutative() throws Exception {
String sqlText =
String.format("select 4 - t from %s", QUALIFIED_TABLE_NAME);
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("The '-' operator with a left operand type of 'INTEGER' and a right operand type of 'TIMESTAMP' is not supported.",
e.getLocalizedMessage());
}
}
//=========================================================================================================
// Values Timestamp
//=========================================================================================================
@Test
public void testPlusTimestampValues() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') + 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2011-12-27 17:13:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testMinusTimestampValues() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') - 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2011-12-25 17:13:30.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampMinusTimestampPositiveValues() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') - timestamp('2011-06-05', '05:06:00')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----\n" +
"204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampMinusTimestampNegativeValues() throws Exception {
String sqlText = "values timestamp('2011-06-05', '05:06:00') - timestamp('2011-12-26', '17:13:30')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------\n" +
"-204 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testIntegerPlusTimestampValues() throws Exception {
// DB-2943
String sqlText = "values 1+ timestamp('2011-06-05', '05:06:00')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2011-06-06 05:06:00.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampPlusTimestampValuesError() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') + timestamp('2011-06-05', '05:06:00')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("TIMESTAMPs cannot be added. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testMultiplyPlusTimestampValuesError() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') * timestamp('2011-06-05', '05:06:00')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("TIMESTAMPs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
@Test
public void testTimestampDivideTimestampValuesError() throws Exception {
String sqlText = "values timestamp('2011-12-26', '17:13:30') / timestamp('2011-06-05', '05:06:00')";
try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
fail("Expected exception.");
} catch (Exception e) {
Assert.assertEquals("TIMESTAMPs cannot be multiplied or divided. The operation is undefined.",
e.getLocalizedMessage());
}
}
//=========================================================================================================
// Values Timestamp/Date mixed and interesting edge cases
//=========================================================================================================
@Test
public void testDateMinusTimestampValues() throws Exception {
String sqlText = "values date('2011-06-04') - timestamp('2011-06-05', '05:06:00')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"----\n" +
"-1 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testTimestampMinusDateValues() throws Exception {
String sqlText = "values timestamp('2011-06-05', '05:06:00') - date('2011-12-26')";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------\n" +
"-203 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testAddDateOnLeapYear() throws Exception {
String sqlText = "values Date('2016-02-28') + 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2016-02-29 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testAddDateOnLeapYear2() throws Exception {
String sqlText = "values Date('2016-02-28') + 2 - 1";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"------------\n" +
"2016-02-29 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
@Test
public void testAddDateOnLeapYear3() throws Exception {
String sqlText = "values timestamp('2016-03-28', '22:13:13') - 28";
ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
String expected =
"1 |\n" +
"-----------------------\n" +
"2016-02-29 22:13:13.0 |";
Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
rs.close();
}
}
| DB-2862: Allow Date cast to Timestamp. DB-2881: Allow comparison if different date types. DB-2892: Exception subtracting CURRENT_DATE from Date type column.
The fix was to generally allow Dates and Timestamps to be compared and to be involved in arithmetic
by creating a Timestamp from a Date and leaving the time component midnight (00:00:00.0).
All work done in Derby.
Added ITs.
| splice_machine_test/src/test/java/com/splicemachine/derby/impl/sql/execute/operations/SimpleDateArithmeticIT.java | DB-2862: Allow Date cast to Timestamp. DB-2881: Allow comparison if different date types. DB-2892: Exception subtracting CURRENT_DATE from Date type column. | <ide><path>plice_machine_test/src/test/java/com/splicemachine/derby/impl/sql/execute/operations/SimpleDateArithmeticIT.java
<ide> @BeforeClass
<ide> public static void createTable() throws Exception {
<ide> new TableCreator(spliceClassWatcher.getOrCreateConnection())
<del> .withCreate(String.format("create table %s (s varchar(15), d date, t timestamp)", QUALIFIED_TABLE_NAME))
<del> .withInsert(String.format("insert into %s values(?,?,?)", QUALIFIED_TABLE_NAME))
<add> .withCreate(String.format("create table %s (s varchar(15), d date, t timestamp, t2 timestamp)", QUALIFIED_TABLE_NAME))
<add> .withInsert(String.format("insert into %s values(?,?,?,?)", QUALIFIED_TABLE_NAME))
<ide> .withRows(rows(
<del> row("2012-05-23", new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-26"), Timestamp.valueOf("2000-06-07 17:12:30"))))
<add> row("2012-05-23", new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-26"), Timestamp.valueOf("2000-06-07 17:12:30"), Timestamp.valueOf("2012-12-13 00:00:00"))))
<ide> .create();
<del> }
<del>
<del> @Test
<del> public void testSelect() throws Exception {
<del> String sqlText =
<del> String.format("SELECT * from %s", QUALIFIED_TABLE_NAME);
<del>
<del> ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
<del>
<del> String expected =
<del> "S | D | T |\n" +
<del> "-----------------------------------------------\n" +
<del> "2012-05-23 |1988-12-26 |2000-06-07 17:12:30.0 |";
<del> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<del> rs.close();
<ide> }
<ide>
<ide> //=========================================================================================================
<ide> }
<ide> }
<ide>
<add> @Test
<add> public void testCurrentDateMinusDateColumn() throws Exception {
<add> String sqlText = String.format("select current_date - d from %s", QUALIFIED_TABLE_NAME);
<add> int rows = 0;
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add> // can't use static result compare with CURRENT_DATE funct. Best we can do is count rows.
<add> ++rows;
<add> }
<add> Assert.assertTrue("\n" + sqlText + "\nExpected at least one row.", rows > 0);
<add> }
<add>
<add> @Test
<add> public void testDateColumnMinusCurrentDate() throws Exception {
<add> String sqlText = String.format("select d - current_date from %s", QUALIFIED_TABLE_NAME);
<add> int rows = 0;
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add> // can't use static result compare with CURRENT_DATE funct. Best we can do is count rows.
<add> ++rows;
<add> }
<add> Assert.assertTrue("\n" + sqlText + "\nExpected at least one row.", rows > 0);
<add> }
<add>
<ide> //=========================================================================================================
<ide> // Values Date
<ide> //=========================================================================================================
<ide>
<ide> @Test
<ide> public void testAddDateOnLeapYear2() throws Exception {
<del> String sqlText = "values Date('2016-02-28') + 2 - 1";
<add> String sqlText = "values Date('2016-02-28') + 2 - 1";
<ide>
<ide> ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
<ide>
<ide>
<ide> @Test
<ide> public void testAddDateOnLeapYear3() throws Exception {
<del> String sqlText = "values timestamp('2016-03-28', '22:13:13') - 28";
<add> String sqlText = "values timestamp('2016-03-28', '22:13:13') - 28";
<ide>
<ide> ResultSet rs = spliceClassWatcher.executeQuery(sqlText);
<ide>
<ide> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<ide> rs.close();
<ide> }
<add>
<add> @Test
<add> public void testTimestampGTDateCompare() throws Exception {
<add> String sqlText = String.format("select t from %s where t > '2000-04-01'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "T |\n" +
<add> "-----------------------\n" +
<add> "2000-06-07 17:12:30.0 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testTimestampLTDateCompare() throws Exception {
<add> String sqlText = String.format("select t from %s where t < '2000-07-01'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "T |\n" +
<add> "-----------------------\n" +
<add> "2000-06-07 17:12:30.0 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testTimestampNETDateCompare() throws Exception {
<add> String sqlText = String.format("select t from %s where t != '2000-06-07'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "T |\n" +
<add> "-----------------------\n" +
<add> "2000-06-07 17:12:30.0 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testTimestampETDateCompare() throws Exception {
<add> String sqlText = String.format("select t2 from %s where t2 = '2012-12-13'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "T2 |\n" +
<add> "-----------------------\n" +
<add> "2012-12-13 00:00:00.0 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testDateGTTimestampCompareColummn() throws Exception {
<add> String sqlText = String.format("select d from %s where d > '1988-11-24 00:00:00'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "D |\n" +
<add> "------------\n" +
<add> "1988-12-26 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testDateGTTimestampCompareValues() throws Exception {
<add> String sqlText = "values date('2088-12-26') > '2088-12-25 00:00:00'";
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "1 |\n" +
<add> "------\n" +
<add> "true |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testDateLTTimestampCompare() throws Exception {
<add> String sqlText = String.format("select d from %s where d < '1988-12-29 00:00:00'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "D |\n" +
<add> "------------\n" +
<add> "1988-12-26 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testDateNETTimestampCompare() throws Exception {
<add> String sqlText = String.format("select d from %s where d != '1988-12-25 00:00:00'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "D |\n" +
<add> "------------\n" +
<add> "1988-12-26 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testDateETTimestampCompareColumn() throws Exception {
<add> String sqlText = String.format("select d from %s where d = '1988-12-26 00:00:00'", QUALIFIED_TABLE_NAME);
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "D |\n" +
<add> "------------\n" +
<add> "1988-12-26 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testDateETTimestampCompareValues() throws Exception {
<add> String sqlText = "values date('2088-12-26') = '2088-12-26 00:00:00'";
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "1 |\n" +
<add> "------\n" +
<add> "true |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testCastToTimestamp() throws Exception {
<add> String sqlText = "values cast(add_months('1993-07-01',3) as timestamp)";
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "1 |\n" +
<add> "-----------------------\n" +
<add> "1993-10-01 00:00:00.0 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<add>
<add> @Test
<add> public void testCastToDate() throws Exception {
<add> String sqlText = "values cast(add_months('1993-07-01 00:00:00',3) as date)";
<add>
<add> try (ResultSet rs = spliceClassWatcher.executeQuery(sqlText)) {
<add>
<add> String expected =
<add> "1 |\n" +
<add> "------------\n" +
<add> "1993-10-01 |";
<add> Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toStringUnsorted(rs));
<add> }
<add> }
<ide> }
<ide> |
|
JavaScript | bsd-3-clause | f64b36bf513758ed6733eee85aa60bcb088c2b8f | 0 | modulexcite/scrollbench.js,modulexcite/scrollbench.js,natduca/scrollbench.js | /**
* ScrollBench.js - Browser Scroll Benchmark
* @author Matteo Spinelli <[email protected]>
*
* Copyright (c) 2013 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
(function (window, document) {
var CONFIG_URL = 'https://sb.cubiq.org/src/config.js';
var REPORT_URL = '//sb.cubiq.org/report.html';
var reliabilityReport = {};
var now = (function () {
var perfNow = window.performance && // browser may support performance but not performance.now
(performance.now ||
performance.webkitNow ||
performance.mozNow ||
performance.msNow ||
performance.oNow);
if ( perfNow ) {
reliabilityReport.timer = 'performance.now';
return perfNow.bind(window.performance);
}
if ( Date.now ) {
reliabilityReport.timer = 'Date.now';
return Date.now;
}
reliabilityReport.timer = 'Date getTime';
return new Date().getTime();
})();
var rAF = (function () {
var raf = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
if ( raf ) {
reliabilityReport.animation = 'requestAnimationFrame';
return raf;
}
reliabilityReport.animation = 'setTimeout';
return function (callback) { window.setTimeout(callback, 1000 / 60); };
})();
// Normalize viewport size for mobile
function initViewport () {
var vp = document.querySelector('meta[name=viewport]');
var scale = 1 / (window.devicePixelRatio || 1); // pick the best scale factor for the device
if ( !vp ) {
vp = document.createElement('meta');
vp.setAttribute('name', 'viewport');
document.head.appendChild(vp);
}
vp.setAttribute('content', 'width=device-width,initial-scale=' + scale + ',maximum-scale=' + scale + ',user-scalable=0');
}
function getBoundingVisibleRect (el) {
var rect = el.getBoundingClientRect();
var outsideHeight = rect.top + rect.height - window.innerHeight;
var outsideWidth = rect.left + rect.width - window.innerWidth;
if ( outsideHeight > 0 ) {
rect.height -= outsideHeight;
}
if ( outsideWidth > 0 ) {
rect.width -= outsideWidth;
}
return rect;
}
var gpuBenchmarking = window.chrome && window.chrome.gpuBenchmarking;
var asyncScroll = gpuBenchmarking && window.chrome.gpuBenchmarking.smoothScrollBy;
var pageLoaded = true;
if ( document.readyState != 'complete' ) {
pageLoaded = false;
window.addEventListener('load', loaded, false);
function loaded () {
window.removeEventListener('load', loaded, false);
pageLoaded = true;
}
}
/**
* RAFScroller, requestAnimationFrame driver
* @constructor
*/
function RAFScroller () {
}
RAFScroller.prototype = {
getResult: function () {
var result = {};
result.numAnimationFrames = this.timeFrames.length;
result.droppedFrameCount = this._getDroppedFrameCount();
result.totalTimeInSeconds = (this.timeFrames[this.timeFrames.length - 1] - this.timeFrames[0]) / 1000;
return result;
},
start: function (element, travel, step, callback) {
this.element = element;
this.travel = travel;
this.callback = callback;
this.step = step;
this.timeFrames = [];
this.isDocument = this.element == document.documentElement;
if ( this.isDocument ) {
window.scrollTo(0, 0);
} else {
this.element.scrollTop = 0;
}
this.rolling = true;
rAF(this._step.bind(this));
},
stop: function () {
this.rolling = false;
},
_getDroppedFrameCount: function () {
var droppedFrameCount = 0,
frameTime,
i = 1,
l = this.timeFrames.length;
for ( i = 1; i < l; i++ ) {
frameTime = this.timeFrames[i] - this.timeFrames[i-1];
if (frameTime > 1000 / 55) droppedFrameCount++;
}
return droppedFrameCount;
},
_getScrollPosition: function () {
if ( this.isDocument ) {
return {
left: Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
top: Math.max(document.documentElement.scrollTop, document.body.scrollTop)
}; // TODO: check this for cross browser compatibility
}
return {
left: this.element.scrollLeft,
top: this.element.scrollTop
};
},
_step: function () {
var scrollTop = this._getScrollPosition().top;
// check travel at every iteration, this covers possible DOM changes while scrolling
this.travel = Math.min(this.travel, this.element.scrollHeight - (this.isDocument ? window.innerHeight : this.element.clientHeight));
if ( this.travel - scrollTop <= 0 ) {
this.rolling = false;
this.callback();
}
if ( !this.rolling ) return;
rAF(this._step.bind(this));
this.timeFrames.push(now());
scrollTop += this.step;
if ( this.isDocument ) {
window.scrollTo(0, scrollTop);
} else {
this.element.scrollTop = scrollTop;
}
}
};
/**
* SmoothScroller, scroll driver using smoothScrollBy for scrolling
* and gpuBenchmarking Stats
* @constructor
*/
function SmoothScroller () {
}
SmoothScroller.prototype = {
getResult: function () {
var result = this.finalStat;
for (var i in result) {
result[i] -= this.initialStat[i];
}
return result;
},
start: function (element, travel, step, callback) {
var rect = getBoundingVisibleRect(element);
var that = this;
step = travel;
// this wouldn't be strictly needed as Chrome scrolls the document with scrollTop
if ( element == document.documentElement ) {
window.scrollTo(0, 0);
} else {
element.scrollTop = 0;
}
this.initialStat = this._step();
chrome.gpuBenchmarking.smoothScrollBy(step, function () {
that.finalStat = that._step();
callback();
}, rect.left + Math.round(rect.width / 2), rect.top + Math.round(rect.height / 2));
},
stop: function () {
// TODO: how do you stop a smoothScrollBy?
},
_step: function () {
var stats = chrome.gpuBenchmarking.renderingStats();
stats.totalTimeInSeconds = now() / 1000;
return stats;
}
};
/**
* ScrollBench
* @param {Object} options Configure the benchmark
* @constructor
*/
function ScrollBench (options) {
this.ready = false;
this.options = {
element: null,
iterations: 2,
scrollStep: 100,
scrollDriver: '',
onCompletion: null,
loadConfig: false,
scrollableElementFn: null,
waitForFn: null,
initViewport: false
};
for ( var i in options ) {
this.options[i] = options[i];
}
if ( this.options.initViewport ) {
initViewport();
}
if ( this.options.loadConfig ) {
this._loadConfig();
return;
}
this._waitForContent();
}
ScrollBench.prototype = {
handleEvent: function (e) {
if ( e.type == 'scroll' ) {
this._scrollCheck(e);
}
},
_loadConfig: function () {
var that = this;
var script;
function parseConfig () {
var i, l, m;
var regex;
for ( i = 0, l = window.scrollbench_config.pages.length; i < l; i++ ) {
regex = new RegExp(window.scrollbench_config.pages[i].url);
if ( regex.test(window.location.href) ) {
for ( m in window.scrollbench_config.pages[i] ) {
that.options[m] = window.scrollbench_config.pages[i][m];
}
break;
}
}
if ( script ) {
script.removeEventListener('load', parseConfig, false); // be kind, rewind
}
that._waitForContent();
}
if ( window.scrollbench_config ) {
parseConfig();
return;
}
script = document.createElement('script');
script.src = typeof this.options.loadConfig == 'string' ? this.options.loadConfig : CONFIG_URL;
script.addEventListener('load', parseConfig, false);
document.getElementsByTagName('head')[0].appendChild(script);
},
_waitForContent: function () {
var that = this;
function waitingGame () {
if ( that.options.waitForFn() ) {
that._findScrollableElement();
return;
}
setTimeout(waitingGame, 50);
}
if ( typeof this.options.waitForFn == 'function' ) {
waitingGame();
return;
}
this._findScrollableElement();
},
_findScrollableElement: function () {
var that = this;
function setElement (el) {
that.element = el || that.options.element || document.documentElement;
that._getReady();
}
if ( this.options.scrollableElementFn ) {
this.options.scrollableElementFn(setElement);
return;
}
setElement();
},
_getReady: function (el) {
var smoothScroll = !!asyncScroll;
this.options.scrollDriver = this.options.scrollDriver || ( smoothScroll ? 'smoothScroll' : '' );
// one might want to disable smoothScroll even if the browser supports it (for testing mainly)
if ( smoothScroll && this.options.scrollDriver == 'smoothScroll' ) {
reliabilityReport.animation = 'async scroll';
}
if ( reliabilityReport.animation == 'async scroll' ) {
reliabilityReport.resolution = 'high+';
} else if ( reliabilityReport.timer == 'performance.now' && reliabilityReport.animation == 'requestAnimationFrame' ) {
reliabilityReport.resolution = 'medium-';
} else {
reliabilityReport.resolution = 'low!';
}
this.ready = true;
},
_startPass: function () {
this.pass++;
if ( this.options.scrollDriver == 'smoothScroll' ) {
this.scroller = new SmoothScroller();
} else {
this.scroller = new RAFScroller();
}
this.scroller.start(
this.element,
this.travel,
this.options.scrollStep,
this._endPass.bind(this)
);
},
_endPass: function () {
this._updateResult();
if ( this.pass < this.options.iterations ) {
this._startPass();
return;
}
this.result.resolution = reliabilityReport.resolution;
this.result.timer = reliabilityReport.timer;
this.result.animation = reliabilityReport.animation;
this.result.avgTimePerPass = this.result.totalTimeInSeconds / this.pass;
this.result.framesPerSecond = 1000 / (this.result.totalTimeInSeconds / this.result.numAnimationFrames * 1000);
this.result.travel = this.travel;
// add warnings
if ( this.result.droppedFrameCount > this.result.numAnimationFrames / 10 ) {
this.result.droppedFrameCount += '!';
} else if ( this.result.droppedFrameCount > this.result.numAnimationFrames / 20 ) {
this.result.droppedFrameCount += '-';
} else {
this.result.droppedFrameCount += '+';
}
if ( this.result.framesPerSecond < 50 ) {
this.result.framesPerSecond += '!';
} else if ( this.result.framesPerSecond < 56 ) {
this.result.framesPerSecond += '-';
} else {
this.result.framesPerSecond += '+';
}
if ( this.options.onCompletion ) {
this.options.onCompletion(this.result);
return;
}
this._generateReport();
},
start: function () {
if ( !pageLoaded || !this.ready ) {
setTimeout(this.start.bind(this), 100);
return;
}
this.closeReport();
this.pass = 0;
this.result = {};
this.travel = this.element.scrollHeight - (this.element == document.documentElement ? window.innerHeight : this.element.clientHeight);
if ( this.travel <= this.options.scrollStep ) {
alert('Scroll travel too short. No benchmark performed.');
return;
}
setTimeout(this._startPass.bind(this), 100);
this.controlTimer = setTimeout(this._scrollFailed.bind(this), 2100);
(this.element == document.documentElement ? window : this.element).addEventListener('scroll', this, false);
},
stop: function () {
this.scroller.stop();
},
closeReport: function () {
var frame = document.getElementById('scrollbench-report-frame');
if ( !frame ) return;
document.documentElement.removeChild(frame);
document.documentElement.removeChild(document.getElementById('scrollbench-close'));
},
_scrollCheck: function () {
clearTimeout(this.controlTimer);
(this.element == document.documentElement ? window : this.element).removeEventListener('scroll', this, false);
},
_scrollFailed: function () {
this.stop();
(this.element == document.documentElement ? window : this.element).removeEventListener('scroll', this, false);
alert('Sorry, we weren\'t able to perform the test. Please report the culprit site to the ScrollBench team.');
},
_updateResult: function () {
var result = this.scroller.getResult(),
i;
for ( i in result ) {
this.result[i] = (this.result[i] || 0) + result[i];
}
},
_generateReport: function () {
var frame = document.createElement('iframe');
var close = document.createElement('i'); // using an element less prone to aggressive styling
var parms = [];
for ( var r in this.result ) {
parms.push(r + '=' + this.result[r]);
}
// bugfix with overlaying iframe not getting events focus on Android
if ( (/android/gi).test(navigator.appVersion) && this.element == document.documentElement ) {
window.scrollTo(0, 0);
}
frame.style.cssText = 'position:fixed;z-index:2147483640;bottom:0;left:0;width:100%;height:270px;padding:0;margin:0;border:0';
frame.src = REPORT_URL + '#' + encodeURIComponent(parms.join(','));
frame.id = 'scrollbench-report-frame';
document.documentElement.appendChild(frame);
// Close button is on the same parent page to avoid cross-domain errors
close.style.cssText = 'position:fixed;z-index:2147483641;bottom:238px;right:0;width:88px;height:32px;padding:0;margin:0;border:0;background:transparent;cursor:pointer';
close.id = 'scrollbench-close';
close.onclick = this.closeReport.bind(this);
document.documentElement.appendChild(close);
}
};
window.ScrollBench = ScrollBench;
})(window, document); | src/scrollbench.js | /**
* ScrollBench.js - Browser Scroll Benchmark
* @author Matteo Spinelli <[email protected]>
*
* Copyright (c) 2013 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
(function (window, document) {
var CONFIG_URL = 'https://sb.cubiq.org/src/config.js';
var REPORT_URL = '//sb.cubiq.org/report.html';
var reliabilityReport = {};
var now = (function () {
var perfNow = window.performance && // browser may support performance but not performance.now
(performance.now ||
performance.webkitNow ||
performance.mozNow ||
performance.msNow ||
performance.oNow);
if ( perfNow ) {
reliabilityReport.timer = 'performance.now';
return perfNow.bind(window.performance);
}
if ( Date.now ) {
reliabilityReport.timer = 'Date.now';
return Date.now;
}
reliabilityReport.timer = 'Date getTime';
return new Date().getTime();
})();
var rAF = (function () {
var raf = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
if ( raf ) {
reliabilityReport.animation = 'requestAnimationFrame';
return raf;
}
reliabilityReport.animation = 'setTimeout';
return function (callback) { window.setTimeout(callback, 1000 / 60); };
})();
// Normalize viewport size for mobile
function initViewport () {
var vp = document.querySelector('meta[name=viewport]');
var scale = 1 / (window.devicePixelRatio || 1); // pick the best scale factor for the device
if ( !vp ) {
vp = document.createElement('meta');
vp.setAttribute('name', 'viewport');
document.head.appendChild(vp);
}
vp.setAttribute('content', 'width=device-width,initial-scale=' + scale + ',maximum-scale=' + scale + ',user-scalable=0');
}
function getBoundingVisibleRect (el) {
var rect = el.getBoundingClientRect();
var outsideHeight = rect.top + rect.height - window.innerHeight;
var outsideWidth = rect.left + rect.width - window.innerWidth;
if ( outsideHeight > 0 ) {
rect.height -= outsideHeight;
}
if ( outsideWidth > 0 ) {
rect.width -= outsideWidth;
}
return rect;
}
var gpuBenchmarking = window.chrome && window.chrome.gpuBenchmarking;
var asyncScroll = gpuBenchmarking && window.chrome.gpuBenchmarking.smoothScrollBy;
var pageLoaded = true;
if ( document.readyState != 'complete' ) {
pageLoaded = false;
window.addEventListener('load', loaded, false);
function loaded () {
window.removeEventListener('load', loaded, false);
pageLoaded = true;
}
}
/**
* RAFScroller, requestAnimationFrame driver
* @constructor
*/
function RAFScroller () {
}
RAFScroller.prototype = {
getResult: function () {
var result = {};
result.numAnimationFrames = this.timeFrames.length;
result.droppedFrameCount = this._getDroppedFrameCount();
result.totalTimeInSeconds = (this.timeFrames[this.timeFrames.length - 1] - this.timeFrames[0]) / 1000;
return result;
},
start: function (element, travel, step, callback) {
this.element = element;
this.travel = travel;
this.callback = callback;
this.step = step;
this.timeFrames = [];
this.isDocument = this.element == document.documentElement;
if ( this.isDocument ) {
window.scrollTo(0, 0);
} else {
this.element.scrollTop = 0;
}
this.rolling = true;
rAF(this._step.bind(this));
},
stop: function () {
this.rolling = false;
},
_getDroppedFrameCount: function () {
var droppedFrameCount = 0,
frameTime,
i = 1,
l = this.timeFrames.length;
for ( i = 1; i < l; i++ ) {
frameTime = this.timeFrames[i] - this.timeFrames[i-1];
if (frameTime > 1000 / 55) droppedFrameCount++;
}
return droppedFrameCount;
},
_getScrollPosition: function () {
if ( this.isDocument ) {
return {
left: Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
top: Math.max(document.documentElement.scrollTop, document.body.scrollTop)
}; // TODO: check this for cross browser compatibility
}
return {
left: this.element.scrollLeft,
top: this.element.scrollTop
};
},
_step: function () {
var scrollTop = this._getScrollPosition().top;
// check travel at every iteration, this covers possible DOM changes while scrolling
this.travel = this.element.scrollHeight - (this.isDocument ? window.innerHeight : this.element.clientHeight);
if ( this.travel - scrollTop <= 0 ) {
this.rolling = false;
this.callback();
}
if ( !this.rolling ) return;
rAF(this._step.bind(this));
this.timeFrames.push(now());
scrollTop += this.step;
if ( this.isDocument ) {
window.scrollTo(0, scrollTop);
} else {
this.element.scrollTop = scrollTop;
}
}
};
/**
* SmoothScroller, scroll driver using smoothScrollBy for scrolling
* and gpuBenchmarking Stats
* @constructor
*/
function SmoothScroller () {
}
SmoothScroller.prototype = {
getResult: function () {
var result = this.finalStat;
for (var i in result) {
result[i] -= this.initialStat[i];
}
return result;
},
start: function (element, travel, step, callback) {
var rect = getBoundingVisibleRect(element);
var that = this;
step = travel;
// this wouldn't be strictly needed as Chrome scrolls the document with scrollTop
if ( element == document.documentElement ) {
window.scrollTo(0, 0);
} else {
element.scrollTop = 0;
}
this.initialStat = this._step();
chrome.gpuBenchmarking.smoothScrollBy(step, function () {
that.finalStat = that._step();
callback();
}, rect.left + Math.round(rect.width / 2), rect.top + Math.round(rect.height / 2));
},
stop: function () {
// TODO: how do you stop a smoothScrollBy?
},
_step: function () {
var stats = chrome.gpuBenchmarking.renderingStats();
stats.totalTimeInSeconds = now() / 1000;
return stats;
}
};
/**
* ScrollBench
* @param {Object} options Configure the benchmark
* @constructor
*/
function ScrollBench (options) {
this.ready = false;
this.options = {
element: null,
iterations: 2,
scrollStep: 100,
scrollDriver: '',
onCompletion: null,
loadConfig: false,
scrollableElementFn: null,
waitForFn: null,
initViewport: false
};
for ( var i in options ) {
this.options[i] = options[i];
}
if ( this.options.initViewport ) {
initViewport();
}
if ( this.options.loadConfig ) {
this._loadConfig();
return;
}
this._waitForContent();
}
ScrollBench.prototype = {
handleEvent: function (e) {
if ( e.type == 'scroll' ) {
this._scrollCheck(e);
}
},
_loadConfig: function () {
var that = this;
var script;
function parseConfig () {
var i, l, m;
var regex;
for ( i = 0, l = window.scrollbench_config.pages.length; i < l; i++ ) {
regex = new RegExp(window.scrollbench_config.pages[i].url);
if ( regex.test(window.location.href) ) {
for ( m in window.scrollbench_config.pages[i] ) {
that.options[m] = window.scrollbench_config.pages[i][m];
}
break;
}
}
if ( script ) {
script.removeEventListener('load', parseConfig, false); // be kind, rewind
}
that._waitForContent();
}
if ( window.scrollbench_config ) {
parseConfig();
return;
}
script = document.createElement('script');
script.src = typeof this.options.loadConfig == 'string' ? this.options.loadConfig : CONFIG_URL;
script.addEventListener('load', parseConfig, false);
document.getElementsByTagName('head')[0].appendChild(script);
},
_waitForContent: function () {
var that = this;
function waitingGame () {
if ( that.options.waitForFn() ) {
that._findScrollableElement();
return;
}
setTimeout(waitingGame, 50);
}
if ( typeof this.options.waitForFn == 'function' ) {
waitingGame();
return;
}
this._findScrollableElement();
},
_findScrollableElement: function () {
var that = this;
function setElement (el) {
that.element = el || that.options.element || document.documentElement;
that._getReady();
}
if ( this.options.scrollableElementFn ) {
this.options.scrollableElementFn(setElement);
return;
}
setElement();
},
_getReady: function (el) {
var smoothScroll = !!asyncScroll;
this.options.scrollDriver = this.options.scrollDriver || ( smoothScroll ? 'smoothScroll' : '' );
// one might want to disable smoothScroll even if the browser supports it (for testing mainly)
if ( smoothScroll && this.options.scrollDriver == 'smoothScroll' ) {
reliabilityReport.animation = 'async scroll';
}
if ( reliabilityReport.animation == 'async scroll' ) {
reliabilityReport.resolution = 'high+';
} else if ( reliabilityReport.timer == 'performance.now' && reliabilityReport.animation == 'requestAnimationFrame' ) {
reliabilityReport.resolution = 'medium-';
} else {
reliabilityReport.resolution = 'low!';
}
this.ready = true;
},
_startPass: function () {
this.pass++;
if ( this.options.scrollDriver == 'smoothScroll' ) {
this.scroller = new SmoothScroller();
} else {
this.scroller = new RAFScroller();
}
this.scroller.start(
this.element,
this.travel,
this.options.scrollStep,
this._endPass.bind(this)
);
},
_endPass: function () {
this._updateResult();
if ( this.pass < this.options.iterations ) {
this._startPass();
return;
}
this.result.resolution = reliabilityReport.resolution;
this.result.timer = reliabilityReport.timer;
this.result.animation = reliabilityReport.animation;
this.result.avgTimePerPass = this.result.totalTimeInSeconds / this.pass;
this.result.framesPerSecond = 1000 / (this.result.totalTimeInSeconds / this.result.numAnimationFrames * 1000);
this.result.travel = this.travel;
// add warnings
if ( this.result.droppedFrameCount > this.result.numAnimationFrames / 10 ) {
this.result.droppedFrameCount += '!';
} else if ( this.result.droppedFrameCount > this.result.numAnimationFrames / 20 ) {
this.result.droppedFrameCount += '-';
} else {
this.result.droppedFrameCount += '+';
}
if ( this.result.framesPerSecond < 50 ) {
this.result.framesPerSecond += '!';
} else if ( this.result.framesPerSecond < 56 ) {
this.result.framesPerSecond += '-';
} else {
this.result.framesPerSecond += '+';
}
if ( this.options.onCompletion ) {
this.options.onCompletion(this.result);
return;
}
this._generateReport();
},
start: function () {
if ( !pageLoaded || !this.ready ) {
setTimeout(this.start.bind(this), 100);
return;
}
this.closeReport();
this.pass = 0;
this.result = {};
this.travel = this.element.scrollHeight - (this.element == document.documentElement ? window.innerHeight : this.element.clientHeight);
if ( this.travel <= this.options.scrollStep ) {
alert('Scroll travel too short. No benchmark performed.');
return;
}
setTimeout(this._startPass.bind(this), 100);
this.controlTimer = setTimeout(this._scrollFailed.bind(this), 2100);
(this.element == document.documentElement ? window : this.element).addEventListener('scroll', this, false);
},
stop: function () {
this.scroller.stop();
},
closeReport: function () {
var frame = document.getElementById('scrollbench-report-frame');
if ( !frame ) return;
document.documentElement.removeChild(frame);
document.documentElement.removeChild(document.getElementById('scrollbench-close'));
},
_scrollCheck: function () {
clearTimeout(this.controlTimer);
(this.element == document.documentElement ? window : this.element).removeEventListener('scroll', this, false);
},
_scrollFailed: function () {
this.stop();
(this.element == document.documentElement ? window : this.element).removeEventListener('scroll', this, false);
alert('Sorry, we weren\'t able to perform the test. Please report the culprit site to the ScrollBench team.');
},
_updateResult: function () {
var result = this.scroller.getResult(),
i;
for ( i in result ) {
this.result[i] = (this.result[i] || 0) + result[i];
}
},
_generateReport: function () {
var frame = document.createElement('iframe');
var close = document.createElement('i'); // using an element less prone to aggressive styling
var parms = [];
for ( var r in this.result ) {
parms.push(r + '=' + this.result[r]);
}
// bugfix with overlaying iframe not getting events focus on Android
if ( (/android/gi).test(navigator.appVersion) && this.element == document.documentElement ) {
window.scrollTo(0, 0);
}
frame.style.cssText = 'position:fixed;z-index:2147483640;bottom:0;left:0;width:100%;height:270px;padding:0;margin:0;border:0';
frame.src = REPORT_URL + '#' + encodeURIComponent(parms.join(','));
frame.id = 'scrollbench-report-frame';
document.documentElement.appendChild(frame);
// Close button is on the same parent page to avoid cross-domain errors
close.style.cssText = 'position:fixed;z-index:2147483641;bottom:238px;right:0;width:88px;height:32px;padding:0;margin:0;border:0;background:transparent;cursor:pointer';
close.id = 'scrollbench-close';
close.onclick = this.closeReport.bind(this);
document.documentElement.appendChild(close);
}
};
window.ScrollBench = ScrollBench;
})(window, document); | always take the shortest path
| src/scrollbench.js | always take the shortest path | <ide><path>rc/scrollbench.js
<ide> _step: function () {
<ide> var scrollTop = this._getScrollPosition().top;
<ide> // check travel at every iteration, this covers possible DOM changes while scrolling
<del> this.travel = this.element.scrollHeight - (this.isDocument ? window.innerHeight : this.element.clientHeight);
<add> this.travel = Math.min(this.travel, this.element.scrollHeight - (this.isDocument ? window.innerHeight : this.element.clientHeight));
<ide>
<ide> if ( this.travel - scrollTop <= 0 ) {
<ide> this.rolling = false; |
|
Java | apache-2.0 | 4ef0028ae7738901549903f09ccde049bc443dc0 | 0 | FITeagle/adapters,FITeagle/adapters,FITeagle/adapters,FITeagle/adapters | package org.fiteagle.abstractAdapter.dm;
import info.openmultinet.ontology.vocabulary.Http;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.ws.rs.core.Response;
import org.apache.jena.riot.RiotException;
import org.fiteagle.abstractAdapter.AbstractAdapter;
import org.fiteagle.abstractAdapter.AbstractAdapter.InstanceNotFoundException;
import org.fiteagle.abstractAdapter.AbstractAdapter.InvalidRequestException;
import org.fiteagle.abstractAdapter.AbstractAdapter.ProcessingException;
import org.fiteagle.api.core.IMessageBus;
import org.fiteagle.api.core.MessageUtil;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
/**
* subclasses must be annotated as
*
* @ServerEndpoint("/") for this to work!
*/
public abstract class AbstractAdapterWebsocket implements AdapterEventListener {
private static final Logger LOGGER = Logger.getLogger(AbstractAdapterWebsocket.class.getName());
private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
protected abstract Map<String, AbstractAdapter> getAdapterInstances();
@PostConstruct
public void setup() {
for (AbstractAdapter adapter : getAdapterInstances().values()) {
adapter.addListener(this);
}
}
@OnMessage
public String onMessage(final String message) {
Model responseModel = ModelFactory.createDefaultModel();
Resource response = responseModel.createResource();
response.addProperty(RDF.type, Http.Response);
Literal responseCode = responseModel.createLiteral(String.valueOf(Response.Status.OK.getStatusCode()));
Literal responseBody = null;
try{
Model requestModel = parseInputString(message);
Resource request = getRequestResource(requestModel);
responseModel.add(request, Http.response, response);
AbstractAdapter targetAdapter = getTargetAdapterInstance(requestModel);
Model responseBodyModel = null;
if(request.hasProperty(RDF.type, Http.GetRequest)){
responseBodyModel = targetAdapter.getInstances(requestModel);
}
else if(request.hasProperty(RDF.type, Http.PostRequest)){
responseBodyModel = targetAdapter.createInstances(requestModel);
}
else if(request.hasProperty(RDF.type, Http.PutRequest)){
responseBodyModel = targetAdapter.updateInstances(requestModel);
}
else if(request.hasProperty(RDF.type, Http.DeleteRequest)){
responseBodyModel = targetAdapter.deleteInstances(requestModel);
}
responseModel.add(responseBodyModel);
} catch(ProcessingException e){
responseBody = getResponseBodyFromException(responseModel, e);
response.addProperty(Http.body, responseBody);
responseCode = getServerErrorResponseCode(responseModel);
} catch (InvalidRequestException e) {
responseBody = getResponseBodyFromException(responseModel, e);
response.addProperty(Http.body, responseBody);
responseCode = getBadRequestResponseCode(responseModel);
} catch (InstanceNotFoundException e) {
responseBody = getResponseBodyFromException(responseModel, e);
response.addProperty(Http.body, responseBody);
responseCode = getNotFoundResponseCode(responseModel);
}
response.addProperty(Http.responseCode, responseCode);
return MessageUtil.serializeModel(responseModel, IMessageBus.SERIALIZATION_TURTLE);
}
private Literal getNotFoundResponseCode(Model responseModel) {
return responseModel.createLiteral(String.valueOf(Response.Status.NOT_FOUND.getStatusCode()));
}
private Literal getServerErrorResponseCode(Model responseModel) {
return responseModel.createLiteral(String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
}
private Literal getBadRequestResponseCode(Model responseModel) {
return responseModel.createLiteral(String.valueOf(Response.Status.BAD_REQUEST.getStatusCode()));
}
private Literal getResponseBodyFromException(Model responseModel, Exception e) {
Literal responseBody;
if(e.getCause() != null){
responseBody = responseModel.createLiteral(e.getCause().getMessage());
}
else {
responseBody = responseModel.createLiteral(e.getMessage());
}
return responseBody;
}
private AbstractAdapter getTargetAdapterInstance(Model requestModel) throws ProcessingException, InvalidRequestException, InstanceNotFoundException {
AbstractAdapter targetAdapter = null;
for(AbstractAdapter adapterInstance : getAdapterInstances().values()){
if(adapterInstance.isRecipient(requestModel)){
targetAdapter = adapterInstance;
}
}
if(targetAdapter == null){
throw new InstanceNotFoundException("No target adapter found");
}
return targetAdapter;
}
private Model parseInputString(final String message) throws InvalidRequestException {
Model requestModel;
try{
requestModel = MessageUtil.parseSerializedModel(message, IMessageBus.SERIALIZATION_TURTLE);
} catch(RiotException e){
throw new InvalidRequestException("Input must be a turtle-serialized RDF model: "+e.getMessage());
}
return requestModel;
}
private Resource getRequestResource(Model requestModel) throws InvalidRequestException {
List<Resource> requests = getAllRequestResources(requestModel);
if(requests.size() == 0){
throw new InvalidRequestException("No request resource was found");
}
if(requests.size() > 1){
throw new InvalidRequestException("Multiple requests are not supported");
}
Resource request = requests.get(0);
return request;
}
private static List<Resource> getAllRequestResources(Model requestModel) {
List<Resource> requests = new ArrayList<>();
requests.addAll(getRequestResources(requestModel, Http.GetRequest));
requests.addAll(getRequestResources(requestModel, Http.PutRequest));
requests.addAll(getRequestResources(requestModel, Http.PostRequest));
requests.addAll(getRequestResources(requestModel, Http.DeleteRequest));
return requests;
}
private static List<Resource> getRequestResources(Model requestModel, Resource requestType) {
return requestModel.listSubjectsWithProperty(RDF.type, requestType).toList();
}
@OnOpen
public void onOpen(final Session session, final EndpointConfig config) throws IOException {
LOGGER.log(Level.INFO, "Opening WebSocket connection with " + session.getId() + "...");
LOGGER.log(Level.INFO, "Sending adapter description... ");
for(AbstractAdapter adapter : getAdapterInstances().values()){
String description = MessageUtil.serializeModel(adapter.getAdapterDescriptionModel(), IMessageBus.SERIALIZATION_TURTLE);
session.getBasicRemote().sendText(description);
}
queue.add(session);
}
@OnError
public void error(Session session, Throwable t) {
LOGGER.log(Level.INFO, "Error on session " + session.getId() + ": " + t.getMessage());
t.printStackTrace();
queue.remove(session);
}
@OnClose
public void closedConnection(Session session) {
LOGGER.log(Level.INFO, "Closed session: " + session.getId());
queue.remove(session);
}
private static void sendToAllSessions(String message) {
ArrayList<Session> closedSessions = new ArrayList<Session>();
for (Session session : queue) {
if (!session.isOpen()) {
LOGGER.log(Level.INFO, "Closed session: " + session.getId());
closedSessions.add(session);
} else {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
queue.removeAll(closedSessions);
}
@Override
public void publishModelUpdate(Model eventRDF, String requestID, String methodType, String methodTarget) {
String serializedModel = MessageUtil.serializeModel(eventRDF, IMessageBus.SERIALIZATION_TURTLE);
sendToAllSessions(serializedModel);
}
}
| abstract/src/main/java/org/fiteagle/abstractAdapter/dm/AbstractAdapterWebsocket.java | package org.fiteagle.abstractAdapter.dm;
import info.openmultinet.ontology.vocabulary.Http;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.ws.rs.core.Response;
import org.apache.jena.riot.RiotException;
import org.fiteagle.abstractAdapter.AbstractAdapter;
import org.fiteagle.abstractAdapter.AbstractAdapter.InstanceNotFoundException;
import org.fiteagle.abstractAdapter.AbstractAdapter.InvalidRequestException;
import org.fiteagle.abstractAdapter.AbstractAdapter.ProcessingException;
import org.fiteagle.api.core.IMessageBus;
import org.fiteagle.api.core.MessageUtil;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
/**
* subclasses must be annotated as
*
* @ServerEndpoint("/") for this to work!
*/
public abstract class AbstractAdapterWebsocket implements AdapterEventListener {
private static final Logger LOGGER = Logger.getLogger(AbstractAdapterWebsocket.class.getName());
private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
protected abstract Map<String, AbstractAdapter> getAdapterInstances();
@PostConstruct
public void setup() {
for (AbstractAdapter adapter : getAdapterInstances().values()) {
adapter.addListener(this);
}
}
@OnMessage
public String onMessage(final String message) {
Model responseModel = ModelFactory.createDefaultModel();
Resource response = responseModel.createResource();
response.addProperty(RDF.type, Http.Response);
Literal responseCode = responseModel.createLiteral(String.valueOf(Response.Status.OK.getStatusCode()));
Literal responseBody = null;
try{
Model requestModel = parseInputString(message);
Resource request = getRequestResource(requestModel);
responseModel.add(request, Http.response, response);
AbstractAdapter targetAdapter = getTargetAdapterInstance(requestModel);
Model responseBodyModel = null;
if(request.hasProperty(RDF.type, Http.GetRequest)){
responseBodyModel = targetAdapter.getInstances(requestModel);
}
else if(request.hasProperty(RDF.type, Http.PostRequest)){
responseBodyModel = targetAdapter.createInstances(requestModel);
}
else if(request.hasProperty(RDF.type, Http.PutRequest)){
responseBodyModel = targetAdapter.updateInstances(requestModel);
}
else if(request.hasProperty(RDF.type, Http.DeleteRequest)){
responseBodyModel = targetAdapter.deleteInstances(requestModel);
}
responseModel.add(responseBodyModel);
} catch(ProcessingException e){
responseBody = getResponseBodyFromException(responseModel, e);
response.addProperty(Http.body, responseBody);
responseCode = getServerErrorResponseCode(responseModel);
} catch (InvalidRequestException e) {
responseBody = getResponseBodyFromException(responseModel, e);
response.addProperty(Http.body, responseBody);
responseCode = getBadRequestResponseCode(responseModel);
} catch (InstanceNotFoundException e) {
responseBody = getResponseBodyFromException(responseModel, e);
response.addProperty(Http.body, responseBody);
responseCode = getNotFoundResponseCode(responseModel);
}
response.addProperty(Http.responseCode, responseCode);
return MessageUtil.serializeModel(responseModel, IMessageBus.SERIALIZATION_TURTLE);
}
private Literal getNotFoundResponseCode(Model responseModel) {
return responseModel.createLiteral(String.valueOf(Response.Status.NOT_FOUND.getStatusCode()));
}
private Literal getServerErrorResponseCode(Model responseModel) {
return responseModel.createLiteral(String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
}
private Literal getBadRequestResponseCode(Model responseModel) {
return responseModel.createLiteral(String.valueOf(Response.Status.BAD_REQUEST.getStatusCode()));
}
private Literal getResponseBodyFromException(Model responseModel, Exception e) {
Literal responseBody;
if(e.getCause() != null){
responseBody = responseModel.createLiteral(e.getCause().getMessage());
}
else {
responseBody = responseModel.createLiteral(e.getMessage());
}
return responseBody;
}
private AbstractAdapter getTargetAdapterInstance(Model requestModel) throws ProcessingException, InvalidRequestException, InstanceNotFoundException {
AbstractAdapter targetAdapter = null;
for(AbstractAdapter adapterInstance : getAdapterInstances().values()){
if(adapterInstance.isRecipient(requestModel)){
targetAdapter = adapterInstance;
}
}
if(targetAdapter == null){
throw new InstanceNotFoundException("No target adapter found");
}
return targetAdapter;
}
private Model parseInputString(final String message) throws InvalidRequestException {
Model requestModel;
try{
requestModel = MessageUtil.parseSerializedModel(message, IMessageBus.SERIALIZATION_TURTLE);
} catch(RiotException e){
throw new InvalidRequestException("Input must be a turtle-serialized RDF model");
}
return requestModel;
}
private Resource getRequestResource(Model requestModel) throws InvalidRequestException {
List<Resource> requests = getAllRequestResources(requestModel);
if(requests.size() == 0){
throw new InvalidRequestException("No request resource was found");
}
if(requests.size() > 1){
throw new InvalidRequestException("Multiple requests are not supported");
}
Resource request = requests.get(0);
return request;
}
private static List<Resource> getAllRequestResources(Model requestModel) {
List<Resource> requests = new ArrayList<>();
requests.addAll(getRequestResources(requestModel, Http.GetRequest));
requests.addAll(getRequestResources(requestModel, Http.PutRequest));
requests.addAll(getRequestResources(requestModel, Http.PostRequest));
requests.addAll(getRequestResources(requestModel, Http.DeleteRequest));
return requests;
}
private static List<Resource> getRequestResources(Model requestModel, Resource requestType) {
return requestModel.listSubjectsWithProperty(RDF.type, requestType).toList();
}
@OnOpen
public void onOpen(final Session session, final EndpointConfig config) throws IOException {
LOGGER.log(Level.INFO, "Opening WebSocket connection with " + session.getId() + "...");
LOGGER.log(Level.INFO, "Sending adapter description... ");
for(AbstractAdapter adapter : getAdapterInstances().values()){
String description = MessageUtil.serializeModel(adapter.getAdapterDescriptionModel(), IMessageBus.SERIALIZATION_TURTLE);
session.getBasicRemote().sendText(description);
}
queue.add(session);
}
@OnError
public void error(Session session, Throwable t) {
LOGGER.log(Level.INFO, "Error on session " + session.getId() + ": " + t.getMessage());
t.printStackTrace();
queue.remove(session);
}
@OnClose
public void closedConnection(Session session) {
LOGGER.log(Level.INFO, "Closed session: " + session.getId());
queue.remove(session);
}
private static void sendToAllSessions(String message) {
ArrayList<Session> closedSessions = new ArrayList<Session>();
for (Session session : queue) {
if (!session.isOpen()) {
LOGGER.log(Level.INFO, "Closed session: " + session.getId());
closedSessions.add(session);
} else {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
queue.removeAll(closedSessions);
}
@Override
public void publishModelUpdate(Model eventRDF, String requestID, String methodType, String methodTarget) {
String serializedModel = MessageUtil.serializeModel(eventRDF, IMessageBus.SERIALIZATION_TURTLE);
sendToAllSessions(serializedModel);
}
}
| improved websocket parsing exception | abstract/src/main/java/org/fiteagle/abstractAdapter/dm/AbstractAdapterWebsocket.java | improved websocket parsing exception | <ide><path>bstract/src/main/java/org/fiteagle/abstractAdapter/dm/AbstractAdapterWebsocket.java
<ide> try{
<ide> requestModel = MessageUtil.parseSerializedModel(message, IMessageBus.SERIALIZATION_TURTLE);
<ide> } catch(RiotException e){
<del> throw new InvalidRequestException("Input must be a turtle-serialized RDF model");
<add> throw new InvalidRequestException("Input must be a turtle-serialized RDF model: "+e.getMessage());
<ide> }
<ide> return requestModel;
<ide> } |
|
Java | apache-2.0 | b025f71666d971f1770da5830bb3c80bbc2fa242 | 0 | jitsi/jigasi,jitsi/jigasi | /*
* Jigasi, the JItsi GAteway to SIP.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.jitsi.jigasi.stats;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.jitsi.jigasi.*;
import org.jitsi.jigasi.util.*;
import org.jitsi.stats.media.*;
import org.jitsi.utils.concurrent.*;
import org.osgi.framework.*;
import java.util.*;
import java.util.concurrent.*;
/**
* The entry point for stats logging.
* Listens for start of calls to start reporting and end of calls
* to stop reporting.
*
* @author Damian Minkov
*/
public class StatsHandler
extends CallChangeAdapter
{
/**
* The logger.
*/
private final static Logger logger = Logger.getLogger(StatsHandler.class);
/**
* CallStats account property: appId
* The account id from callstats.io settings.
*/
private static final String CS_ACC_PROP_APP_ID = "CallStats.appId";
/**
* CallStats account property: keyId
* The key id from callstats.io settings.
*/
private static final String CS_ACC_PROP_KEY_ID = "CallStats.keyId";
/**
* CallStats account property: keyPath
* The path to the key file on the file system.
*/
private static final String CS_ACC_PROP_KEY_PATH = "CallStats.keyPath";
/**
* CallStats account property: conferenceIDPrefix
* The domain that this stats account is handling.
*/
private static final String CS_ACC_PROP_CONFERENCE_PREFIX
= "CallStats.conferenceIDPrefix";
/**
* CallStats account property: STATISTICS_INTERVAL
* The interval on which to publish statistics.
*/
private static final String CS_ACC_PROP_STATISTICS_INTERVAL
= "CallStats.STATISTICS_INTERVAL";
/**
* The default value for statistics interval.
*/
public static final int DEFAULT_STAT_INTERVAL = 5000;
/**
* CallStats account property: jigasiId
* The jigasi id to report to callstats.io.
*/
private static final String CS_ACC_PROP_JIGASI_ID
= "CallStats.jigasiId";
/**
* The default jigasi id to use if setting is missing.
*/
public static final String DEFAULT_JIGASI_ID = "jigasi";
/**
* The {@link RecurringRunnableExecutor} which periodically invokes
* generating and pushing statistics per call for every statistic from the
* MediaStream.
*/
private static final RecurringRunnableExecutor statisticsExecutor
= new RecurringRunnableExecutor(
StatsHandler.class.getSimpleName() + "-statisticsExecutor");
/**
* List of the processor per call. Kept in order to stop and
* deRegister them from the executor.
*/
private final Map<Call,CallPeriodicRunnable>
statisticsProcessors = new ConcurrentHashMap<>();
/**
* The remote endpoint jvb or sip.
*/
private final String remoteEndpointID;
/**
* The origin ID. From jigasi we always report jigasi-NUMBER as
* the origin ID.
*/
private final String originID;
/**
* Constructs StatsHandler.
* @param remoteEndpointID the remote endpoint.
*/
public StatsHandler(String originID, String remoteEndpointID)
{
this.remoteEndpointID = remoteEndpointID;
this.originID = originID;
}
@Override
public synchronized void callStateChanged(CallChangeEvent evt)
{
Call call = evt.getSourceCall();
if (call.getCallState() == CallState.CALL_IN_PROGRESS)
{
startConferencePeriodicRunnable(call);
}
else if(call.getCallState() == CallState.CALL_ENDED)
{
CallPeriodicRunnable cpr
= statisticsProcessors.remove(call);
if (cpr == null)
{
return;
}
cpr.stop();
statisticsExecutor.deRegisterRecurringRunnable(cpr);
}
}
/**
* Starts <tt>CallPeriodicRunnable</tt> for a call.
* @param call the call.
*/
private void startConferencePeriodicRunnable(Call call)
{
CallContext callContext = (CallContext) call.getData(CallContext.class);
BundleContext bundleContext = JigasiBundleActivator.osgiContext;
Object source = callContext.getSource();
if (source == null)
{
logger.warn(
"No source of callContext found, will not init stats");
return;
}
AccountID targetAccountID = null;
if (source instanceof ProtocolProviderService
&& ((ProtocolProviderService) source).getProtocolName()
.equals(ProtocolNames.JABBER))
{
targetAccountID = ((ProtocolProviderService) source).getAccountID();
}
else
{
// if call is not created by a jabber provider
// try to match conferenceIDPrefix of jabber accounts
// to callContext.getDomain
Collection<ServiceReference<ProtocolProviderService>> providers
= ServiceUtils.getServiceReferences(
bundleContext,
ProtocolProviderService.class);
for (ServiceReference<ProtocolProviderService> serviceRef
: providers)
{
ProtocolProviderService candidate
= bundleContext.getService(serviceRef);
if (ProtocolNames.JABBER.equals(candidate.getProtocolName()))
{
AccountID acc = candidate.getAccountID();
String confPrefix = acc.getAccountPropertyString(
CS_ACC_PROP_CONFERENCE_PREFIX);
if (callContext.getDomain().equals(confPrefix))
{
targetAccountID = acc;
break;
}
}
}
}
if (targetAccountID == null)
{
// No account found with enabled stats
// we are maybe in the case where there are no xmpp control accounts
// this is when outgoing calls are disabled
// and we have only the xmpp client account, which may have the
// callstats settings
for (Call confCall : call.getConference().getCalls())
{
if (confCall.getProtocolProvider().getProtocolName()
.equals(ProtocolNames.JABBER))
{
AccountID acc = confCall.getProtocolProvider()
.getAccountID();
if (acc.getAccountPropertyInt(CS_ACC_PROP_APP_ID, 0) != 0)
{
// there are callstats settings then use it
targetAccountID = acc;
}
}
}
if (targetAccountID == null)
{
logger.debug("No account found with enabled stats");
return;
}
}
int appId
= targetAccountID.getAccountPropertyInt(CS_ACC_PROP_APP_ID, 0);
String keyId
= targetAccountID.getAccountPropertyString(CS_ACC_PROP_KEY_ID);
String keyPath
= targetAccountID.getAccountPropertyString(CS_ACC_PROP_KEY_PATH);
String jigasiId = targetAccountID.getAccountPropertyString(
CS_ACC_PROP_JIGASI_ID, DEFAULT_JIGASI_ID);
String roomName = callContext.getRoomName();
if (roomName.contains("@"))
{
roomName = Util.extractCallIdFromResource(roomName);
}
StatsService statsService
= StatsServiceFactory.getInstance()
.getStatsService(appId, bundleContext);
if (statsService == null)
{
// no service will create it, and listen for its registration
// in OSGi
StatsServiceListener serviceListener = new StatsServiceListener(
bundleContext, roomName, call, targetAccountID);
bundleContext.addServiceListener(serviceListener);
final String targetAccountIDDescription
= targetAccountID.toString();
StatsServiceFactory.getInstance()
.createStatsService(
bundleContext,
appId,
null,
keyId,
keyPath,
jigasiId,
true,
((reason, errorMessage) -> {
logger.error("Jitsi-stats library failed to initialize "
+ "with reason: " + reason
+ " and error message: " + errorMessage
+ " for account: " + targetAccountIDDescription);
bundleContext.removeServiceListener(serviceListener);
// callstats holds this lambda and listener instance
// and we clean instances to make sure we do not leave
// anything behind, as much as possible
serviceListener.clean();
}));
return;
}
createAndStartCallPeriodicRunnable(
statsService, roomName, call, targetAccountID);
}
/**
* Creates and starts <tt>CallPeriodicRunnable</tt>.
* @param statsService the <tt>StatsService</tt> to use for reporting.
* @param conferenceName the conference name.
* @param call the call.
* @param accountID the account.
*/
private void createAndStartCallPeriodicRunnable(
StatsService statsService,
String conferenceName,
Call call,
AccountID accountID)
{
String conferenceIDPrefix = accountID.getAccountPropertyString(
CS_ACC_PROP_CONFERENCE_PREFIX);
int interval = accountID.getAccountPropertyInt(
CS_ACC_PROP_STATISTICS_INTERVAL, DEFAULT_STAT_INTERVAL);
CallPeriodicRunnable cpr
= new CallPeriodicRunnable(
call,
interval,
statsService,
conferenceName,
conferenceIDPrefix,
DEFAULT_JIGASI_ID + "-" + originID,
this.remoteEndpointID);
cpr.start();
// register for periodic execution.
statisticsProcessors.put(call, cpr);
statisticsExecutor.registerRecurringRunnable(cpr);
}
/**
* Waits for <tt>StatsService</tt> to registered to OSGi.
*/
private class StatsServiceListener
implements ServiceListener
{
/**
* The context.
*/
private BundleContext context;
/**
* The conference name.
*/
private String conferenceName;
/**
* The call.
*/
private Call call;
/**
* The accountID.
*/
private AccountID accountID;
/**
* Constructs <tt>StatsServiceListener</tt>.
* @param context the OSGi context.
* @param conferenceName the conference name.
* @param call the call.
* @param accountID the accountID.
*/
StatsServiceListener(
BundleContext context,
String conferenceName,
Call call,
AccountID accountID)
{
this.context = context;
this.conferenceName = conferenceName;
this.call = call;
this.accountID = accountID;
}
/**
* Cleans instances the listener holds.
*/
private void clean()
{
this.context = null;
this.conferenceName = null;
this.call = null;
this.accountID = null;
}
@Override
public void serviceChanged(ServiceEvent ev)
{
if (this.context == null
|| this.conferenceName == null
|| this.call == null
|| this.accountID == null)
{
logger.warn(
"Received serviceChanged after listener was maybe cleaned");
return;
}
Object service;
try
{
service = context.getService(ev.getServiceReference());
}
catch (IllegalArgumentException
| IllegalStateException
| SecurityException ex)
{
service = null;
}
if (service == null || !(service instanceof StatsService))
return;
switch (ev.getType())
{
case ServiceEvent.REGISTERED:
context.removeServiceListener(this);
createAndStartCallPeriodicRunnable(
(StatsService) service,
this.conferenceName,
call,
accountID);
break;
}
}
}
}
| src/main/java/org/jitsi/jigasi/stats/StatsHandler.java | /*
* Jigasi, the JItsi GAteway to SIP.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.jitsi.jigasi.stats;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.jitsi.jigasi.*;
import org.jitsi.jigasi.util.*;
import org.jitsi.stats.media.*;
import org.jitsi.utils.concurrent.*;
import org.osgi.framework.*;
import java.util.*;
import java.util.concurrent.*;
/**
* The entry point for stats logging.
* Listens for start of calls to start reporting and end of calls
* to stop reporting.
*
* @author Damian Minkov
*/
public class StatsHandler
extends CallChangeAdapter
{
/**
* The logger.
*/
private final static Logger logger = Logger.getLogger(StatsHandler.class);
/**
* CallStats account property: appId
* The account id from callstats.io settings.
*/
private static final String CS_ACC_PROP_APP_ID = "CallStats.appId";
/**
* CallStats account property: keyId
* The key id from callstats.io settings.
*/
private static final String CS_ACC_PROP_KEY_ID = "CallStats.keyId";
/**
* CallStats account property: keyPath
* The path to the key file on the file system.
*/
private static final String CS_ACC_PROP_KEY_PATH = "CallStats.keyPath";
/**
* CallStats account property: conferenceIDPrefix
* The domain that this stats account is handling.
*/
private static final String CS_ACC_PROP_CONFERENCE_PREFIX
= "CallStats.conferenceIDPrefix";
/**
* CallStats account property: STATISTICS_INTERVAL
* The interval on which to publish statistics.
*/
private static final String CS_ACC_PROP_STATISTICS_INTERVAL
= "CallStats.STATISTICS_INTERVAL";
/**
* The default value for statistics interval.
*/
public static final int DEFAULT_STAT_INTERVAL = 5000;
/**
* CallStats account property: jigasiId
* The jigasi id to report to callstats.io.
*/
private static final String CS_ACC_PROP_JIGASI_ID
= "CallStats.jigasiId";
/**
* The default jigasi id to use if setting is missing.
*/
public static final String DEFAULT_JIGASI_ID = "jigasi";
/**
* The {@link RecurringRunnableExecutor} which periodically invokes
* generating and pushing statistics per call for every statistic from the
* MediaStream.
*/
private static final RecurringRunnableExecutor statisticsExecutor
= new RecurringRunnableExecutor(
StatsHandler.class.getSimpleName() + "-statisticsExecutor");
/**
* List of the processor per call. Kept in order to stop and
* deRegister them from the executor.
*/
private final Map<Call,CallPeriodicRunnable>
statisticsProcessors = new ConcurrentHashMap<>();
/**
* The remote endpoint jvb or sip.
*/
private final String remoteEndpointID;
/**
* The origin ID. From jigasi we always report jigasi-NUMBER as
* the origin ID.
*/
private final String originID;
/**
* Constructs StatsHandler.
* @param remoteEndpointID the remote endpoint.
*/
public StatsHandler(String originID, String remoteEndpointID)
{
this.remoteEndpointID = remoteEndpointID;
this.originID = originID;
}
@Override
public synchronized void callStateChanged(CallChangeEvent evt)
{
Call call = evt.getSourceCall();
if (call.getCallState() == CallState.CALL_IN_PROGRESS)
{
startConferencePeriodicRunnable(call);
}
else if(call.getCallState() == CallState.CALL_ENDED)
{
CallPeriodicRunnable cpr
= statisticsProcessors.remove(call);
if (cpr == null)
{
return;
}
cpr.stop();
statisticsExecutor.deRegisterRecurringRunnable(cpr);
}
}
/**
* Starts <tt>CallPeriodicRunnable</tt> for a call.
* @param call the call.
*/
private void startConferencePeriodicRunnable(Call call)
{
CallContext callContext = (CallContext) call.getData(CallContext.class);
BundleContext bundleContext = JigasiBundleActivator.osgiContext;
Object source = callContext.getSource();
if (source == null)
{
logger.warn(
"No source of callContext found, will not init stats");
return;
}
AccountID targetAccountID = null;
if (source instanceof ProtocolProviderService
&& ((ProtocolProviderService) source).getProtocolName()
.equals(ProtocolNames.JABBER))
{
targetAccountID = ((ProtocolProviderService) source).getAccountID();
}
else
{
// if call is not created by a jabber provider
// try to match conferenceIDPrefix of jabber accounts
// to callContext.getDomain
Collection<ServiceReference<ProtocolProviderService>> providers
= ServiceUtils.getServiceReferences(
bundleContext,
ProtocolProviderService.class);
for (ServiceReference<ProtocolProviderService> serviceRef
: providers)
{
ProtocolProviderService candidate
= bundleContext.getService(serviceRef);
if (ProtocolNames.JABBER.equals(candidate.getProtocolName()))
{
AccountID acc = candidate.getAccountID();
String confPrefix = acc.getAccountPropertyString(
CS_ACC_PROP_CONFERENCE_PREFIX);
if (callContext.getDomain().equals(confPrefix))
{
targetAccountID = acc;
break;
}
}
}
}
if (targetAccountID == null)
{
// No account found with enabled stats
// we are maybe in the case where there are no xmpp control accounts
// this is when outgoing calls are disabled
// and we have only the xmpp client account, which may have the
// callstats settings
for (Call confCall : call.getConference().getCalls())
{
if (confCall.getProtocolProvider().getProtocolName()
.equals(ProtocolNames.JABBER))
{
AccountID acc = confCall.getProtocolProvider()
.getAccountID();
if (acc.getAccountPropertyInt(CS_ACC_PROP_APP_ID, 0) != 0)
{
// there are callstats settings then use it
targetAccountID = acc;
}
}
}
if (targetAccountID == null)
{
logger.debug("No account found with enabled stats");
return;
}
}
int appId
= targetAccountID.getAccountPropertyInt(CS_ACC_PROP_APP_ID, 0);
String keyId
= targetAccountID.getAccountPropertyString(CS_ACC_PROP_KEY_ID);
String keyPath
= targetAccountID.getAccountPropertyString(CS_ACC_PROP_KEY_PATH);
String jigasiId = targetAccountID.getAccountPropertyString(
CS_ACC_PROP_JIGASI_ID, DEFAULT_JIGASI_ID);
String roomName = callContext.getRoomName();
if (roomName.contains("@"))
{
roomName = Util.extractCallIdFromResource(roomName);
}
StatsService statsService
= StatsServiceFactory.getInstance()
.getStatsService(appId, bundleContext);
if (statsService == null)
{
// no service will create it, and listen for its registration
// in OSGi
StatsServiceListener serviceListener = new StatsServiceListener(
bundleContext, roomName, call, targetAccountID);
bundleContext.addServiceListener(serviceListener);
final String targetAccountIDDescription
= targetAccountID.toString();
StatsServiceFactory.getInstance()
.createStatsService(
bundleContext,
appId,
null,
keyId,
keyPath,
jigasiId,
true,
((reason, errorMessage) -> {
logger.error("Jitsi-stats library failed to initialize "
+ "with reason: " + reason
+ " and error message: " + errorMessage
+ " for account: " + targetAccountIDDescription);
bundleContext.removeServiceListener(serviceListener);
}));
return;
}
createAndStartCallPeriodicRunnable(
statsService, roomName, call, targetAccountID);
}
/**
* Creates and starts <tt>CallPeriodicRunnable</tt>.
* @param statsService the <tt>StatsService</tt> to use for reporting.
* @param conferenceName the conference name.
* @param call the call.
* @param accountID the account.
*/
private void createAndStartCallPeriodicRunnable(
StatsService statsService,
String conferenceName,
Call call,
AccountID accountID)
{
String conferenceIDPrefix = accountID.getAccountPropertyString(
CS_ACC_PROP_CONFERENCE_PREFIX);
int interval = accountID.getAccountPropertyInt(
CS_ACC_PROP_STATISTICS_INTERVAL, DEFAULT_STAT_INTERVAL);
CallPeriodicRunnable cpr
= new CallPeriodicRunnable(
call,
interval,
statsService,
conferenceName,
conferenceIDPrefix,
DEFAULT_JIGASI_ID + "-" + originID,
this.remoteEndpointID);
cpr.start();
// register for periodic execution.
statisticsProcessors.put(call, cpr);
statisticsExecutor.registerRecurringRunnable(cpr);
}
/**
* Waits for <tt>StatsService</tt> to registered to OSGi.
*/
private class StatsServiceListener
implements ServiceListener
{
/**
* The context.
*/
private final BundleContext context;
/**
* The conference name.
*/
private final String conferenceName;
/**
* The call.
*/
private final Call call;
/**
* The accountID.
*/
private final AccountID accountID;
/**
* Constructs <tt>StatsServiceListener</tt>.
* @param context the OSGi context.
* @param conferenceName the conference name.
* @param call the call.
* @param accountID the accountID.
*/
StatsServiceListener(
BundleContext context,
String conferenceName,
Call call,
AccountID accountID)
{
this.context = context;
this.conferenceName = conferenceName;
this.call = call;
this.accountID = accountID;
}
@Override
public void serviceChanged(ServiceEvent ev)
{
Object service;
try
{
service = context.getService(ev.getServiceReference());
}
catch (IllegalArgumentException
| IllegalStateException
| SecurityException ex)
{
service = null;
}
if (service == null || !(service instanceof StatsService))
return;
switch (ev.getType())
{
case ServiceEvent.REGISTERED:
context.removeServiceListener(this);
createAndStartCallPeriodicRunnable(
(StatsService) service,
this.conferenceName,
call,
accountID);
break;
}
}
}
}
| Cleans stats init listener from initial xmpp call.
| src/main/java/org/jitsi/jigasi/stats/StatsHandler.java | Cleans stats init listener from initial xmpp call. | <ide><path>rc/main/java/org/jitsi/jigasi/stats/StatsHandler.java
<ide> + " for account: " + targetAccountIDDescription);
<ide>
<ide> bundleContext.removeServiceListener(serviceListener);
<add>
<add> // callstats holds this lambda and listener instance
<add> // and we clean instances to make sure we do not leave
<add> // anything behind, as much as possible
<add> serviceListener.clean();
<ide> }));
<ide>
<ide> return;
<ide> /**
<ide> * The context.
<ide> */
<del> private final BundleContext context;
<add> private BundleContext context;
<ide>
<ide> /**
<ide> * The conference name.
<ide> */
<del> private final String conferenceName;
<add> private String conferenceName;
<ide>
<ide> /**
<ide> * The call.
<ide> */
<del> private final Call call;
<add> private Call call;
<ide>
<ide> /**
<ide> * The accountID.
<ide> */
<del> private final AccountID accountID;
<add> private AccountID accountID;
<ide>
<ide> /**
<ide> * Constructs <tt>StatsServiceListener</tt>.
<ide> this.accountID = accountID;
<ide> }
<ide>
<add> /**
<add> * Cleans instances the listener holds.
<add> */
<add> private void clean()
<add> {
<add> this.context = null;
<add> this.conferenceName = null;
<add> this.call = null;
<add> this.accountID = null;
<add> }
<add>
<ide> @Override
<ide> public void serviceChanged(ServiceEvent ev)
<ide> {
<add> if (this.context == null
<add> || this.conferenceName == null
<add> || this.call == null
<add> || this.accountID == null)
<add> {
<add> logger.warn(
<add> "Received serviceChanged after listener was maybe cleaned");
<add> return;
<add> }
<add>
<ide> Object service;
<ide>
<ide> try |
|
Java | apache-2.0 | e4b02bd2486c78456afc81137b0562c5d750d22e | 0 | apache/creadur-whisker | /**
* 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.creadur.whisker.model;
import java.util.Collection;
import java.util.Map;
/**
* Indicates that generating an instance of a license
* from the template (for the license family) has failed.
*/
public class LicenseTemplateException extends Exception {
/** Exception are serializable, so provide a SUID. */
private static final long serialVersionUID = -4085365930968672572L;
/**
* Builds an instance.
* @param parameters not null
* @param name not null
* @return not null
*/
public static LicenseTemplateException notLicenseTemplate(
final Map<String, String> parameters, final String name) {
return new LicenseTemplateException("This is not a templated license",
parameters, name);
}
/**
* Constructs an instance.
* @param message not null
* @param parameters parameters passed
* @param name license name
*/
private LicenseTemplateException(final String message,
final Map<String, String> parameters, final String name) {
// TODO: improve reporting
super(message);
}
/**
* Constructs an instance.
* @param message not null
* @param expectedParameters not null
* @param actualParameters not null
*/
private LicenseTemplateException(final String message,
final Collection<String> expectedParameters,
final Collection<String> actualParameters) {
// TODO improve reporting
super(message);
}
/**
* Constructs an instance
* @param message not null
* @param name not null
*/
private LicenseTemplateException(final String message, final String name) {
// TODO improve reporting
super(message);
}
/**
* Builds an exception indicating that parameter passed
* do not fulfill expectations.
* @param expectedParameters not null
* @param actualParameters not null
* @return not null
*/
public static LicenseTemplateException parameterMismatch(
final Collection<String> expectedParameters,
final Collection<String> actualParameters) {
return new LicenseTemplateException("Parameter mismatch.",
expectedParameters, actualParameters);
}
/**
* Builds an exception indicating that duplicate parameter
* names have been passed.
* @param name names the parameter duplicated, not null
* @return not null
*/
public static LicenseTemplateException duplicateParameterName(
final String name) {
return new LicenseTemplateException("Duplicate parameter name.", name);
}
} | apache-whisker-model/src/main/java/org/apache/creadur/whisker/model/LicenseTemplateException.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.creadur.whisker.model;
import java.util.Collection;
import java.util.Map;
/**
* Indicates that generating an instance of a license
* from the template (for the license family) has failed.
*/
public class LicenseTemplateException extends Exception {
/** Exception are serializable, so provide a SUID. */
private static final long serialVersionUID = -4085365930968672572L;
/**
* Builds an instance.
* @param parameters not null
* @param name not null
* @return not null
*/
public static LicenseTemplateException notLicenseTemplate(
final Map<String, String> parameters, final String name) {
return new LicenseTemplateException("This is not a templated license",
parameters, name);
}
/**
* Constructs an instance.
* @param message not null
* @param parameters parameters passed
* @param name license name
*/
public LicenseTemplateException(final String message,
final Map<String, String> parameters, final String name) {
// TODO: improve reporting
super(message);
}
/**
* Constructs an instance.
* @param message not null
* @param expectedParameters not null
* @param actualParameters not null
*/
public LicenseTemplateException(final String message,
final Collection<String> expectedParameters,
final Collection<String> actualParameters) {
// TODO improve reporting
super(message);
}
/**
* Constructs an instance
* @param message not null
* @param name not null
*/
public LicenseTemplateException(final String message, final String name) {
// TODO improve reporting
super(message);
}
/**
* Builds an exception indicating that parameter passed
* do not fulfill expectations.
* @param expectedParameters not null
* @param actualParameters not null
* @return not null
*/
public static LicenseTemplateException parameterMismatch(
final Collection<String> expectedParameters,
final Collection<String> actualParameters) {
return new LicenseTemplateException("Parameter mismatch.",
expectedParameters, actualParameters);
}
/**
* Builds an exception indicating that duplicate parameter
* names have been passed.
* @param name names the parameter duplicated, not null
* @return not null
*/
public static LicenseTemplateException duplicateParameterName(
final String name) {
return new LicenseTemplateException("Duplicate parameter name.", name);
}
} | Enforce factory pattern.
git-svn-id: 58702fe1ff5294ea29773cbe6445e6edf216c548@1372587 13f79535-47bb-0310-9956-ffa450edef68
| apache-whisker-model/src/main/java/org/apache/creadur/whisker/model/LicenseTemplateException.java | Enforce factory pattern. | <ide><path>pache-whisker-model/src/main/java/org/apache/creadur/whisker/model/LicenseTemplateException.java
<ide> * @param parameters parameters passed
<ide> * @param name license name
<ide> */
<del> public LicenseTemplateException(final String message,
<add> private LicenseTemplateException(final String message,
<ide> final Map<String, String> parameters, final String name) {
<ide> // TODO: improve reporting
<ide> super(message);
<ide> * @param expectedParameters not null
<ide> * @param actualParameters not null
<ide> */
<del> public LicenseTemplateException(final String message,
<add> private LicenseTemplateException(final String message,
<ide> final Collection<String> expectedParameters,
<ide> final Collection<String> actualParameters) {
<ide> // TODO improve reporting
<ide> * @param message not null
<ide> * @param name not null
<ide> */
<del> public LicenseTemplateException(final String message, final String name) {
<add> private LicenseTemplateException(final String message, final String name) {
<ide> // TODO improve reporting
<ide> super(message);
<ide> } |
|
Java | apache-2.0 | 9f02f3bfa5ae8999fc08ac9e340dfd8b6fd4b853 | 0 | etcinitd/jalf | package jalf.relation.csv;
import static jalf.util.CollectionUtils.mapOf;
import jalf.AttrName;
import jalf.Relation;
import jalf.Tuple;
import jalf.Type;
import jalf.Visitor;
import jalf.compiler.AbstractRelation;
import jalf.compiler.BaseCog;
import jalf.compiler.Cog;
import jalf.compiler.Compiler;
import jalf.relation.algebra.LeafOperand;
import jalf.relation.materialized.SetMemoryRelation;
import jalf.type.Heading;
import jalf.type.RelationType;
import jalf.type.TupleType;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import au.com.bytecode.opencsv.CSVReader;
public class CsvRelation extends AbstractRelation implements LeafOperand {
private Supplier<InputStream> csvStreamSupplier;
private RelationType type;
private AttrName[] attrNames;
public CsvRelation(Supplier<InputStream> supplier) throws IOException {
csvStreamSupplier = supplier;
installType();
}
@Override
public RelationType getType() {
return type;
}
@Override
public <R> R accept(Visitor<R> visitor) {
return visitor.visit(this);
}
@Override
public Cog toCog(Compiler compiler) {
return new BaseCog(this, () -> getCsvTupleStream());
}
@Override
public boolean equals(Relation other) {
Relation r = this.stream().collect(SetMemoryRelation.collector(other.getType()));
return r.equals(other);
}
///
private void installType() throws IOException {
try (CSVReader reader = getCsvReader()) {
Type<?> stringType = Type.scalarType(String.class);
attrNames = AttrName.attrs(reader.readNext());
Heading h = Heading.dress(attrNames, (name) -> stringType);
type = RelationType.dress(h);
}
}
private Stream<Tuple> getCsvTupleStream() {
TupleType tupleType = getType().toTupleType();
return StreamSupport
.stream(new CsvSpliterator(() -> getCsvReader()), false)
.map((attrValues) -> {
return new Tuple(tupleType, mapOf(attrNames, attrValues));
});
}
private CSVReader getCsvReader() {
return new CSVReader(new InputStreamReader(csvStreamSupplier.get()), ';');
}
static class CsvSpliterator implements Spliterator<String[]> {
private Supplier<CSVReader> readerSupplier;
private CSVReader reader;
private boolean closed = false;
public CsvSpliterator(Supplier<CSVReader> supplier) {
readerSupplier = supplier;
}
@Override
public boolean tryAdvance(Consumer<? super String[]> action) {
if (closed) { return false; }
try {
String[] line = getReader().readNext();
if (line != null) {
action.accept(line);
return true;
} else {
reader.close();
closed = true;
return false;
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public Spliterator<String[]> trySplit() {
return null;
}
@Override
public long estimateSize() {
return Long.MAX_VALUE;
}
@Override
public int characteristics() {
return DISTINCT | NONNULL | IMMUTABLE;
}
private CSVReader getReader() throws IOException {
if (reader == null) {
reader = readerSupplier.get();
reader.readNext();
closed = false;
}
return reader;
}
}
}
| src/main/java/jalf/relation/csv/CsvRelation.java | package jalf.relation.csv;
import static jalf.util.CollectionUtils.mapOf;
import jalf.AttrName;
import jalf.Relation;
import jalf.Tuple;
import jalf.Type;
import jalf.Visitor;
import jalf.compiler.AbstractRelation;
import jalf.compiler.BaseCog;
import jalf.compiler.Cog;
import jalf.compiler.Compiler;
import jalf.relation.algebra.LeafOperand;
import jalf.relation.materialized.SetMemoryRelation;
import jalf.type.Heading;
import jalf.type.RelationType;
import jalf.type.TupleType;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import au.com.bytecode.opencsv.CSVReader;
public class CsvRelation extends AbstractRelation implements LeafOperand {
private Supplier<InputStream> csvStreamSupplier;
private RelationType type;
private AttrName[] attrNames;
public CsvRelation(Supplier<InputStream> supplier) throws IOException {
csvStreamSupplier = supplier;
installType();
}
@Override
public RelationType getType() {
return type;
}
@Override
public <R> R accept(Visitor<R> visitor) {
return visitor.visit(this);
}
@Override
public Cog toCog(Compiler compiler) {
return new BaseCog(this, () -> getCsvTupleStream());
}
@Override
public boolean equals(Relation other) {
Relation r = this.stream().collect(SetMemoryRelation.collector(other.getType()));
return r.equals(other);
}
///
private void installType() throws IOException {
try (CSVReader reader = getCsvReader()) {
Type<?> stringType = Type.scalarType(String.class);
attrNames = AttrName.attrs(reader.readNext());
Heading h = Heading.dress(attrNames, (name) -> stringType);
type = RelationType.dress(h);
}
}
private Stream<Tuple> getCsvTupleStream() {
TupleType tupleType = getType().toTupleType();
return StreamSupport
.stream(new CsvSpliterator(() -> getCsvReader()), false)
.map((attrValues) -> {
return new Tuple(tupleType, mapOf(attrNames, attrValues));
});
}
private CSVReader getCsvReader() {
return new CSVReader(new InputStreamReader(csvStreamSupplier.get()), ';');
}
static class CsvSpliterator implements Spliterator<String[]> {
private Supplier<CSVReader> readerSupplier;
private CSVReader reader;
public CsvSpliterator(Supplier<CSVReader> supplier) {
readerSupplier = supplier;
}
@Override
public boolean tryAdvance(Consumer<? super String[]> action) {
try {
String[] line = getReader().readNext();
if (line != null) {
action.accept(line);
return true;
}
return false;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public Spliterator<String[]> trySplit() {
return null;
}
@Override
public long estimateSize() {
return Long.MAX_VALUE;
}
@Override
public int characteristics() {
return DISTINCT | NONNULL | IMMUTABLE;
}
private CSVReader getReader() throws IOException {
if (reader == null) {
reader = readerSupplier.get();
reader.readNext();
}
return reader;
}
}
}
| Fix stream closing of CsvRelation.
| src/main/java/jalf/relation/csv/CsvRelation.java | Fix stream closing of CsvRelation. | <ide><path>rc/main/java/jalf/relation/csv/CsvRelation.java
<ide>
<ide> private CSVReader reader;
<ide>
<add> private boolean closed = false;
<add>
<ide> public CsvSpliterator(Supplier<CSVReader> supplier) {
<ide> readerSupplier = supplier;
<ide> }
<ide>
<ide> @Override
<ide> public boolean tryAdvance(Consumer<? super String[]> action) {
<add> if (closed) { return false; }
<ide> try {
<ide> String[] line = getReader().readNext();
<ide> if (line != null) {
<ide> action.accept(line);
<ide> return true;
<add> } else {
<add> reader.close();
<add> closed = true;
<add> return false;
<ide> }
<del> return false;
<ide> } catch (IOException ex) {
<ide> throw new RuntimeException(ex);
<ide> }
<ide> if (reader == null) {
<ide> reader = readerSupplier.get();
<ide> reader.readNext();
<add> closed = false;
<ide> }
<ide> return reader;
<ide> } |
|
JavaScript | mit | 6c7aff3f19a24e2f57da9e2df6745850579ce3bd | 0 | ottobonn/roots | import React, {Component} from "react";
import {
StyleSheet,
View,
Text,
TouchableHighlight
} from "react-native";
import {Ionicons} from "@exponent/vector-icons";
import {withNavigation} from "@exponent/ex-navigation";
import GlobalStyles from "../styles";
import TitleText from "./TitleText";
import Router from "../navigation/Router";
@withNavigation
export default class PageFrame extends Component {
constructor(props) {
super(props);
this.goBack = this.goBack.bind(this);
this.gotoSearch = this.gotoSearch.bind(this);
}
goBack() {
if (this.props.navigator.getCurrentIndex() > 0) {
this.props.navigator.pop();
}
}
gotoSearch() {
this.props.navigator.push(Router.getRoute("search"));
}
render() {
overlayStyle = this.props.overlay ? styles.overlay : null;
backButton = this.props.backButton == null ? true : this.props.backButton;
return (
<View style={{flex: 1}}>
<View style={[styles.titleBar, overlayStyle]}>
<View style={styles.leftContainer}>
{backButton &&
<TouchableHighlight onPress={this.goBack} style={styles.backButton}>
<Ionicons name="md-arrow-round-back" size={32} color="white" />
</TouchableHighlight> }
<TitleText style={styles.title} textLines={1}>{this.props.title}</TitleText>
</View>
<View style={styles.rightContainer}>
{this.props.searchButton &&
<TouchableHighlight onPress={this.gotoSearch} style={styles.search}>
<Ionicons name="md-search" size={32} color="white" />
</TouchableHighlight> }
</View>
</View>
<View style={{flex: 1}}>
{this.props.children}
</View>
</View>
);
}
};
PageFrame.propTypes = {
/* True if the frame should sit over the content */
overlay: React.PropTypes.bool,
/* The title to display in the title bar */
title: React.PropTypes.string,
/* Boolean, whether or not to display back button */
backButton: React.PropTypes.bool,
/* Boolean, whether or not to display search button */
searchButton: React.PropTypes.bool,
};
var titleBarHeight = 60;
const styles = StyleSheet.create({
titleBar: {
height: titleBarHeight,
paddingLeft: 10,
backgroundColor: "#4b4b4b",
flexDirection: "row",
alignItems: "center",
elevation: 10
},
overlay: {
marginBottom: -titleBarHeight,
backgroundColor: "transparent",
elevation: 0, // Remove drop shadow
zIndex: 1000 // Make sure overlay is on top of children
},
title: {
color: "white",
fontSize: 20,
paddingLeft: 10,
flex: 1
},
leftContainer: {
flex: 4,
alignItems: "center",
flexDirection: "row",
justifyContent: "flex-start"
},
rightContainer: {
flex: 1,
flexDirection: "row",
justifyContent: "flex-end",
alignItems: "center"
},
backButton: {
padding: 10
},
search: {
paddingRight: 20,
}
});
| components/PageFrame.js | import React, {Component} from "react";
import {
StyleSheet,
View,
Text,
TouchableHighlight
} from "react-native";
import {Ionicons} from "@exponent/vector-icons";
import {withNavigation} from "@exponent/ex-navigation";
import GlobalStyles from "../styles";
import TitleText from "./TitleText";
import Router from "../navigation/Router";
@withNavigation
export default class PageFrame extends Component {
constructor(props) {
super(props);
this.goBack = this.goBack.bind(this);
this.gotoSearch = this.gotoSearch.bind(this);
}
goBack() {
if (this.props.navigator.getCurrentIndex() > 0) {
this.props.navigator.pop();
}
}
gotoSearch() {
this.props.navigator.push(Router.getRoute("search"));
}
render() {
overlayStyle = this.props.overlay ? styles.overlay : null;
backButton = this.props.backButton == null ? true : this.props.backButton;
return (
<View style={{flex: 1}}>
<View style={[styles.titleBar, overlayStyle]}>
<View style={styles.leftContainer}>
{backButton &&
<TouchableHighlight onPress={this.goBack} style={styles.backButton}>
<Ionicons name="md-arrow-round-back" size={32} color="white" />
</TouchableHighlight> }
<TitleText style={styles.title} textLines={1}>{this.props.title}</TitleText>
</View>
<View style={styles.rightContainer}>
{this.props.searchButton &&
<TouchableHighlight onPress={this.gotoSearch} style={styles.search}>
<Ionicons name="md-search" size={32} color="white" />
</TouchableHighlight> }
</View>
</View>
<View style={{flex: 1}}>
{this.props.children}
</View>
</View>
);
}
};
PageFrame.propTypes = {
/* True if the frame should sit over the content */
overlay: React.PropTypes.bool,
/* The title to display in the title bar */
title: React.PropTypes.string,
/* Boolean, whether or not to display back button */
backButton: React.PropTypes.bool,
/* Boolean, whether or not to display search button */
searchButton: React.PropTypes.bool,
};
var titleBarHeight = 60;
const styles = StyleSheet.create({
titleBar: {
height: titleBarHeight,
paddingLeft: 10,
backgroundColor: "#4b4b4b",
flexDirection: "row",
alignItems: "center",
elevation: 10
},
overlay: {
marginBottom: -titleBarHeight,
backgroundColor: "transparent",
elevation: 0, // Remove drop shadow
zIndex: 1000 // Make sure overlay is on top of children
},
title: {
color: "white",
fontSize: 20,
paddingLeft: 10
},
leftContainer: {
alignItems: "center",
flex: 2,
flexDirection: "row",
justifyContent: "flex-start",
},
rightContainer: {
flex: 1,
flexDirection: "row",
justifyContent: "flex-end",
alignItems: "center",
},
backButton: {
padding: 10
},
search: {
paddingRight: 20,
}
});
| Increase title box size to prevent wrapping after fonts load
| components/PageFrame.js | Increase title box size to prevent wrapping after fonts load | <ide><path>omponents/PageFrame.js
<ide> title: {
<ide> color: "white",
<ide> fontSize: 20,
<del> paddingLeft: 10
<add> paddingLeft: 10,
<add> flex: 1
<ide> },
<ide> leftContainer: {
<add> flex: 4,
<ide> alignItems: "center",
<del> flex: 2,
<ide> flexDirection: "row",
<del> justifyContent: "flex-start",
<add> justifyContent: "flex-start"
<ide> },
<ide> rightContainer: {
<ide> flex: 1,
<ide> flexDirection: "row",
<ide> justifyContent: "flex-end",
<del> alignItems: "center",
<add> alignItems: "center"
<ide> },
<ide> backButton: {
<ide> padding: 10 |
|
JavaScript | mit | 43f0fedf0470562796ea03b983ecf4e13e45a16f | 0 | floriico/onyx,floriico/onyx | define([], function () {
'use strict';
var GameRenderer = function (canvas, entities) {
this.canvas = canvas;
this.entities = entities;
this.gc = this.canvas.getContext('2d');
};
GameRenderer.prototype.paint = function paint() {
var len = this.entities.length;
var i;
var entity;
this.gc.fillStyle = '#000';
this.gc.fillRect(0, 0, this.canvas.width, this.canvas.height);
for (i = 0; i < len; i++) {
entity = this.entities[i];
this.gc.save()
this.gc.translate(Math.round(entity.position.x), Math.round(entity.position.y));
entity.componentGraphic.paint(this.gc);
this.gc.restore()
}
};
return GameRenderer;
});
| js/game-renderer.js | define([], function () {
'use strict';
var GameRenderer = function (canvas, entities) {
this.canvas = canvas;
this.entities = entities;
this.gc = this.canvas.getContext('2d');
};
GameRenderer.prototype.paint = function paint() {
var len = this.entities.length;
var i;
var entity;
this.gc.fillStyle = '#000';
this.gc.fillRect(0, 0, this.canvas.width, this.canvas.height);
for (i = 0; i < len; i++) {
entity = this.entities[i];
this.gc.save()
this.gc.translate(entity.position.x, entity.position.y);
entity.componentGraphic.paint(this.gc);
this.gc.restore()
}
};
return GameRenderer;
});
| Avoid subpixel in rendering
Round the position of entities to display them on canvas to avoid subpixel
rendering.
| js/game-renderer.js | Avoid subpixel in rendering | <ide><path>s/game-renderer.js
<ide> for (i = 0; i < len; i++) {
<ide> entity = this.entities[i];
<ide> this.gc.save()
<del> this.gc.translate(entity.position.x, entity.position.y);
<add> this.gc.translate(Math.round(entity.position.x), Math.round(entity.position.y));
<ide> entity.componentGraphic.paint(this.gc);
<ide> this.gc.restore()
<ide> } |
|
Java | apache-2.0 | bd5810458716e6beb655e6b209542ace154d798a | 0 | RackerWilliams/xercesj,RackerWilliams/xercesj,RackerWilliams/xercesj | /*
* 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.xerces.impl.dv.xs;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import org.apache.xerces.impl.dv.ValidationContext;
import org.apache.xerces.util.XMLChar;
/**
* All primitive types plus ID/IDREF/ENTITY/INTEGER are derived from this abstract
* class. It provides extra information XSSimpleTypeDecl requires from each
* type: allowed facets, converting String to actual value, check equality,
* comparison, etc.
*
* @xerces.internal
*
* @author Neeraj Bajaj, Sun Microsystems, inc.
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public abstract class TypeValidator {
private static final boolean USE_CODE_POINT_COUNT_FOR_STRING_LENGTH = AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
return Boolean.getBoolean("org.apache.xerces.impl.dv.xs.useCodePointCountForStringLength") ? Boolean.TRUE : Boolean.FALSE;
}
catch (SecurityException ex) {}
return Boolean.FALSE;
}}) == Boolean.TRUE;
// convert a string to an actual value. for example,
// for number types (decimal, double, float, and types derived from them),
// get the BigDecimal, Double, Flout object.
// for some types (string and derived), they just return the string itself
public abstract Object getActualValue(String content, ValidationContext context)
throws InvalidDatatypeValueException;
// for ID/IDREF/ENTITY types, do some extra checking after the value is
// checked to be valid with respect to both lexical representation and
// facets
public void checkExtraRules(Object value, ValidationContext context) throws InvalidDatatypeValueException {
}
// the following methods might not be supported by every DV.
// but XSSimpleTypeDecl should know which type supports which methods,
// and it's an *internal* error if a method is called on a DV that
// doesn't support it.
//order constants
public static final short LESS_THAN = -1;
public static final short EQUAL = 0;
public static final short GREATER_THAN = 1;
public static final short INDETERMINATE = 2;
// where there is distinction between identity and equality, this method
// will be overwritten
// checks whether the two values are identical; for ex, this distinguishes
// -0.0 from 0.0
public boolean isIdentical (Object value1, Object value2) {
return value1.equals(value2);
}
// check the order relation between the two values
// the parameters are in compiled form (from getActualValue)
public int compare(Object value1, Object value2) {
return -1;
}
// get the length of the value
// the parameters are in compiled form (from getActualValue)
public int getDataLength(Object value) {
if (value instanceof String) {
final String str = (String)value;
if (!USE_CODE_POINT_COUNT_FOR_STRING_LENGTH) {
return str.length();
}
return getCodePointLength(str);
}
return -1;
}
// get the number of digits of the value
// the parameters are in compiled form (from getActualValue)
public int getTotalDigits(Object value) {
return -1;
}
// get the number of fraction digits of the value
// the parameters are in compiled form (from getActualValue)
public int getFractionDigits(Object value) {
return -1;
}
// Returns the length of the string in Unicode code points.
private int getCodePointLength(String value) {
// Count the number of surrogate pairs, and subtract them from
// the total length.
final int len = value.length();
int surrogatePairCount = 0;
for (int i = 0; i < len - 1; ++i) {
if (XMLChar.isHighSurrogate(value.charAt(i))) {
if (XMLChar.isLowSurrogate(value.charAt(++i))) {
++surrogatePairCount;
}
else {
--i;
}
}
}
return len - surrogatePairCount;
}
// check whether the character is in the range 0x30 ~ 0x39
public static final boolean isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
// if the character is in the range 0x30 ~ 0x39, return its int value (0~9),
// otherwise, return -1
public static final int getDigit(char ch) {
return isDigit(ch) ? ch - '0' : -1;
}
//get the number of precision of the value
//the parameters are in compiled form (from getActualValue)
public int getPrecision(Object value){
return 0;
}
//whether this value has a precision. false indicate it's a special value.
public boolean hasPrecision(Object value){
return false;
}
public boolean hasTimeZone(Object value){
return false;
}
} // interface TypeValidator
| src/org/apache/xerces/impl/dv/xs/TypeValidator.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.xerces.impl.dv.xs;
import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import org.apache.xerces.impl.dv.ValidationContext;
/**
* All primitive types plus ID/IDREF/ENTITY/INTEGER are derived from this abstract
* class. It provides extra information XSSimpleTypeDecl requires from each
* type: allowed facets, converting String to actual value, check equality,
* comparison, etc.
*
* @xerces.internal
*
* @author Neeraj Bajaj, Sun Microsystems, inc.
* @author Sandy Gao, IBM
*
* @version $Id$
*/
public abstract class TypeValidator {
// convert a string to an actual value. for example,
// for number types (decimal, double, float, and types derived from them),
// get the BigDecimal, Double, Flout object.
// for some types (string and derived), they just return the string itself
public abstract Object getActualValue(String content, ValidationContext context)
throws InvalidDatatypeValueException;
// for ID/IDREF/ENTITY types, do some extra checking after the value is
// checked to be valid with respect to both lexical representation and
// facets
public void checkExtraRules(Object value, ValidationContext context) throws InvalidDatatypeValueException {
}
// the following methods might not be supported by every DV.
// but XSSimpleTypeDecl should know which type supports which methods,
// and it's an *internal* error if a method is called on a DV that
// doesn't support it.
//order constants
public static final short LESS_THAN = -1;
public static final short EQUAL = 0;
public static final short GREATER_THAN = 1;
public static final short INDETERMINATE = 2;
// where there is distinction between identity and equality, this method
// will be overwritten
// checks whether the two values are identical; for ex, this distinguishes
// -0.0 from 0.0
public boolean isIdentical (Object value1, Object value2) {
return value1.equals(value2);
}
// check the order relation between the two values
// the parameters are in compiled form (from getActualValue)
public int compare(Object value1, Object value2) {
return -1;
}
// get the length of the value
// the parameters are in compiled form (from getActualValue)
public int getDataLength(Object value) {
return (value instanceof String) ? ((String)value).length() : -1;
}
// get the number of digits of the value
// the parameters are in compiled form (from getActualValue)
public int getTotalDigits(Object value) {
return -1;
}
// get the number of fraction digits of the value
// the parameters are in compiled form (from getActualValue)
public int getFractionDigits(Object value) {
return -1;
}
// check whether the character is in the range 0x30 ~ 0x39
public static final boolean isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
// if the character is in the range 0x30 ~ 0x39, return its int value (0~9),
// otherwise, return -1
public static final int getDigit(char ch) {
return isDigit(ch) ? ch - '0' : -1;
}
//get the number of precision of the value
//the parameters are in compiled form (from getActualValue)
public int getPrecision(Object value){
return 0;
}
//whether this value has a precision. false indicate it's a special value.
public boolean hasPrecision(Object value){
return false;
}
public boolean hasTimeZone(Object value){
return false;
}
} // interface TypeValidator
| Introducing a system property for controlling how string length is computed by the schema validator. When org.apache.xerces.impl.dv.xs.useCodePointCountForStringLength=true, the length of an xs:string or xs:anyURI value is calculated by counting the number of Unicode code points in the string. The value of the system property is false by default, preserving the long standing behaviour of computing length in Java chars (i.e. String.length()).
git-svn-id: 39602be06c88ea89c23a8a9fd3d1314146990de6@1375611 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/xerces/impl/dv/xs/TypeValidator.java | Introducing a system property for controlling how string length is computed by the schema validator. When org.apache.xerces.impl.dv.xs.useCodePointCountForStringLength=true, the length of an xs:string or xs:anyURI value is calculated by counting the number of Unicode code points in the string. The value of the system property is false by default, preserving the long standing behaviour of computing length in Java chars (i.e. String.length()). | <ide><path>rc/org/apache/xerces/impl/dv/xs/TypeValidator.java
<ide>
<ide> package org.apache.xerces.impl.dv.xs;
<ide>
<add>import java.security.AccessController;
<add>import java.security.PrivilegedAction;
<add>
<ide> import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
<ide> import org.apache.xerces.impl.dv.ValidationContext;
<add>import org.apache.xerces.util.XMLChar;
<ide>
<ide> /**
<ide> * All primitive types plus ID/IDREF/ENTITY/INTEGER are derived from this abstract
<ide> * @version $Id$
<ide> */
<ide> public abstract class TypeValidator {
<add>
<add> private static final boolean USE_CODE_POINT_COUNT_FOR_STRING_LENGTH = AccessController.doPrivileged(new PrivilegedAction() {
<add> public Object run() {
<add> try {
<add> return Boolean.getBoolean("org.apache.xerces.impl.dv.xs.useCodePointCountForStringLength") ? Boolean.TRUE : Boolean.FALSE;
<add> }
<add> catch (SecurityException ex) {}
<add> return Boolean.FALSE;
<add> }}) == Boolean.TRUE;
<ide>
<ide> // convert a string to an actual value. for example,
<ide> // for number types (decimal, double, float, and types derived from them),
<ide> // get the length of the value
<ide> // the parameters are in compiled form (from getActualValue)
<ide> public int getDataLength(Object value) {
<del> return (value instanceof String) ? ((String)value).length() : -1;
<add> if (value instanceof String) {
<add> final String str = (String)value;
<add> if (!USE_CODE_POINT_COUNT_FOR_STRING_LENGTH) {
<add> return str.length();
<add> }
<add> return getCodePointLength(str);
<add> }
<add> return -1;
<ide> }
<ide>
<ide> // get the number of digits of the value
<ide> // the parameters are in compiled form (from getActualValue)
<ide> public int getFractionDigits(Object value) {
<ide> return -1;
<add> }
<add>
<add> // Returns the length of the string in Unicode code points.
<add> private int getCodePointLength(String value) {
<add> // Count the number of surrogate pairs, and subtract them from
<add> // the total length.
<add> final int len = value.length();
<add> int surrogatePairCount = 0;
<add> for (int i = 0; i < len - 1; ++i) {
<add> if (XMLChar.isHighSurrogate(value.charAt(i))) {
<add> if (XMLChar.isLowSurrogate(value.charAt(++i))) {
<add> ++surrogatePairCount;
<add> }
<add> else {
<add> --i;
<add> }
<add> }
<add> }
<add> return len - surrogatePairCount;
<ide> }
<ide>
<ide> // check whether the character is in the range 0x30 ~ 0x39 |
|
Java | mit | 2b3e396e75d7dbe59b2c99b1859cd6597519d8e7 | 0 | roxanne-baker/game-authoring-environment,roxanne-baker/game-authoring-environment,roxanne-baker/game-authoring-environment | package model.vooga;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class SplashScreen {
private Stage myStage;
private VBox myVBox;
/**
* Constructor that takes in a stage to display the graphics.
* @param stage
*/
public SplashScreen(Stage stage) {
myStage = stage;
}
/**
* Initializes the scene which is displayed in the window.
* @return the splash screen scene
*/
public Scene init(){
BorderPane display = createDisplay();
Scene myScene = new Scene(display, 500, 500);
return myScene;
}
/**
* Creates the splash screen display independently of initializing the scene.
* @return BorderPane in which the contents are the splash screen
*/
private BorderPane createDisplay() {
Group root = new Group();
Button createGame = Utilities.makeButton("Create Game", e -> myStage.setScene(Authoring.init()));
myVBox = new VBox(30);
myVBox.setAlignment(Pos.CENTER);
myVBox.getChildren().add(createGame);
root.getChildren().add(myVBox);
BorderPane splash = new BorderPane();
splash.setCenter(root);
return splash;
}
}
| src/model/vooga/SplashScreen.java | package model.vooga;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class SplashScreen {
private Stage myStage;
private String myLanguage = "English";
private ComboBox<String> myLanguageChooser;
private VBox myVBox;
/**
* Constructor that takes in a stage to display the graphics.
* @param stage
*/
public SplashScreen(Stage stage) {
myStage = stage;
}
/**
* Initializes the scene which is displayed in the window.
* @return the splash screen scene
*/
public Scene init(){
BorderPane display = createDisplay();
Scene myScene = new Scene(display, 500, 500);
return myScene;
}
/**
* Creates the splash screen display independently of initializing the scene.
* @return BorderPane in which the contents are the splash screen
*/
private BorderPane createDisplay() {
Group root = new Group();
Button createGame = Utilities.makeButton("Create Game", e -> myStage.setScene(Authoring.init()));
myVBox = new VBox(30);
myVBox.setAlignment(Pos.CENTER);
myVBox.getChildren().add(createGame);
root.getChildren().add(myVBox);
BorderPane splash = new BorderPane();
splash.setCenter(root);
return splash;
}
}
| delete some shit
| src/model/vooga/SplashScreen.java | delete some shit | <ide><path>rc/model/vooga/SplashScreen.java
<ide> package model.vooga;
<ide>
<del>import javafx.collections.ObservableList;
<ide> import javafx.geometry.Pos;
<ide> import javafx.scene.Group;
<ide> import javafx.scene.Scene;
<ide> import javafx.scene.control.Button;
<del>import javafx.scene.control.ComboBox;
<ide> import javafx.scene.layout.BorderPane;
<del>import javafx.scene.layout.GridPane;
<ide> import javafx.scene.layout.VBox;
<del>import javafx.scene.text.Font;
<del>import javafx.scene.text.Text;
<ide> import javafx.stage.Stage;
<ide>
<ide> public class SplashScreen {
<ide>
<ide> private Stage myStage;
<del> private String myLanguage = "English";
<del> private ComboBox<String> myLanguageChooser;
<ide> private VBox myVBox;
<ide> /**
<ide> * Constructor that takes in a stage to display the graphics. |
|
JavaScript | mit | 7986bf32f04e0001bf44d34806b0270fcc0fea11 | 0 | a8m/ng-translation |
/**
* @ngdoc module
* @name ng.static.filter
*
* @description
* ngStaticFilter get key as a string, and staticFileName as an arguments
* and return the value.
* @example
* <p>{{ 'someKey' | ng-static: 'homepage' }}</p>
*/
angular.module('ng.static.filter', [ 'ng.static.provider' ])
.filter('static', ['$parse', 'ngStatic', function($parse, ngStatic) {
return function(string, staticFile) {
return $parse(string)(ngStatic.get(staticFile)) || string;
}
}]);
| src/ngStaticFilter.js |
/**
* @ngdoc module
* @name ng.static.filter
*
* @description
* ngStaticFilter get key as a string, and staticFileName as an arguments
* and return the value.
* @example
* <p>{{ 'someKey' | ng-static: 'homepage' }}</p>
*/
angular.module('ng.static.filter', [ 'ng.static.provider' ])
.filter('static', ['$parse', 'ngStatic', function($parse, ngStatic) {
return function(string, staticFile) {
return $parse(string)(ngStatic.get(staticFile));
}
}]);
| fix(staticFilter): fix undfined issue
| src/ngStaticFilter.js | fix(staticFilter): fix undfined issue | <ide><path>rc/ngStaticFilter.js
<ide>
<ide> return function(string, staticFile) {
<ide>
<del> return $parse(string)(ngStatic.get(staticFile));
<add> return $parse(string)(ngStatic.get(staticFile)) || string;
<ide>
<ide> }
<ide> |
|
Java | bsd-3-clause | be83edf6d04aa659834ccf2bd0c057dd01dc5acf | 0 | worsht/antlr4,ericvergnaud/antlr4,antlr/antlr4,lncosie/antlr4,chandler14362/antlr4,wjkohnen/antlr4,lncosie/antlr4,parrt/antlr4,parrt/antlr4,chandler14362/antlr4,ericvergnaud/antlr4,chienjchienj/antlr4,hce/antlr4,joshids/antlr4,Pursuit92/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,supriyantomaftuh/antlr4,deveshg/antlr4,wjkohnen/antlr4,hce/antlr4,chandler14362/antlr4,Pursuit92/antlr4,joshids/antlr4,joshids/antlr4,supriyantomaftuh/antlr4,chandler14362/antlr4,ericvergnaud/antlr4,chienjchienj/antlr4,chandler14362/antlr4,worsht/antlr4,lncosie/antlr4,wjkohnen/antlr4,sidhart/antlr4,ericvergnaud/antlr4,mcanthony/antlr4,antlr/antlr4,antlr/antlr4,Pursuit92/antlr4,Pursuit92/antlr4,mcanthony/antlr4,Pursuit92/antlr4,joshids/antlr4,cocosli/antlr4,sidhart/antlr4,cooperra/antlr4,cocosli/antlr4,krzkaczor/antlr4,Pursuit92/antlr4,worsht/antlr4,chandler14362/antlr4,joshids/antlr4,chandler14362/antlr4,chienjchienj/antlr4,parrt/antlr4,ericvergnaud/antlr4,krzkaczor/antlr4,jvanzyl/antlr4,antlr/antlr4,sidhart/antlr4,ericvergnaud/antlr4,antlr/antlr4,wjkohnen/antlr4,jvanzyl/antlr4,mcanthony/antlr4,Distrotech/antlr4,chandler14362/antlr4,parrt/antlr4,wjkohnen/antlr4,chienjchienj/antlr4,antlr/antlr4,joshids/antlr4,chandler14362/antlr4,hce/antlr4,antlr/antlr4,sidhart/antlr4,sidhart/antlr4,worsht/antlr4,Pursuit92/antlr4,chienjchienj/antlr4,antlr/antlr4,cocosli/antlr4,supriyantomaftuh/antlr4,wjkohnen/antlr4,supriyantomaftuh/antlr4,parrt/antlr4,cooperra/antlr4,parrt/antlr4,hce/antlr4,mcanthony/antlr4,antlr/antlr4,wjkohnen/antlr4,joshids/antlr4,krzkaczor/antlr4,supriyantomaftuh/antlr4,antlr/antlr4,Distrotech/antlr4,parrt/antlr4,Pursuit92/antlr4,Distrotech/antlr4,worsht/antlr4,parrt/antlr4,joshids/antlr4,ericvergnaud/antlr4,cocosli/antlr4,jvanzyl/antlr4,ericvergnaud/antlr4,cooperra/antlr4,jvanzyl/antlr4,cooperra/antlr4,parrt/antlr4,Pursuit92/antlr4,Distrotech/antlr4,lncosie/antlr4,krzkaczor/antlr4,Distrotech/antlr4,lncosie/antlr4,mcanthony/antlr4,wjkohnen/antlr4,wjkohnen/antlr4,krzkaczor/antlr4 | /*
* [The "BSD license"]
* Copyright (c) 2012 Terence Parr
* Copyright (c) 2012 Sam Harwell
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.antlr.v4.test;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DefaultErrorStrategy;
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenSource;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.ATNConfig;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.atn.LexerATNSimulator;
import org.antlr.v4.runtime.atn.ParserATNSimulator;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.dfa.DFAState;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.Nullable;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
public class TestPerformance extends BaseTest {
/**
* Parse all java files under this package within the JDK_SOURCE_ROOT
* (environment variable or property defined on the Java command line).
*/
private static final String TOP_PACKAGE = "java.lang";
/**
* {@code true} to load java files from sub-packages of
* {@link #TOP_PACKAGE}.
*/
private static final boolean RECURSIVE = true;
/**
* {@code true} to read all source files from disk into memory before
* starting the parse. The default value is {@code true} to help prevent
* drive speed from affecting the performance results. This value may be set
* to {@code false} to support parsing large input sets which would not
* otherwise fit into memory.
*/
private static final boolean PRELOAD_SOURCES = true;
/**
* The encoding to use when reading source files.
*/
private static final String ENCODING = "UTF-8";
/**
* The maximum number of files to parse in a single iteration.
*/
private static final int MAX_FILES_PER_PARSE_ITERATION = Integer.MAX_VALUE;
/**
* {@code true} to call {@link Collections#shuffle} on the list of input
* files before the first parse iteration.
*/
private static final boolean SHUFFLE_FILES_AT_START = false;
/**
* {@code true} to call {@link Collections#shuffle} before each parse
* iteration <em>after</em> the first.
*/
private static final boolean SHUFFLE_FILES_AFTER_ITERATIONS = false;
/**
* The instance of {@link Random} passed when calling
* {@link Collections#shuffle}.
*/
private static final Random RANDOM = new Random();
/**
* {@code true} to use the Java grammar with expressions in the v4
* left-recursive syntax (Java-LR.g4). {@code false} to use the standard
* grammar (Java.g4). In either case, the grammar is renamed in the
* temporary directory to Java.g4 before compiling.
*/
private static final boolean USE_LR_GRAMMAR = true;
/**
* {@code true} to specify the {@code -Xforce-atn} option when generating
* the grammar, forcing all decisions in {@code JavaParser} to be handled by
* {@link ParserATNSimulator#adaptivePredict}.
*/
private static final boolean FORCE_ATN = false;
/**
* {@code true} to specify the {@code -atn} option when generating the
* grammar. This will cause ANTLR to export the ATN for each decision as a
* DOT (GraphViz) file.
*/
private static final boolean EXPORT_ATN_GRAPHS = true;
/**
* {@code true} to specify the {@code -XdbgST} option when generating the
* grammar.
*/
private static final boolean DEBUG_TEMPLATES = false;
/**
* {@code true} to specify the {@code -XdbgSTWait} option when generating the
* grammar.
*/
private static final boolean DEBUG_TEMPLATES_WAIT = DEBUG_TEMPLATES;
/**
* {@code true} to delete temporary (generated and compiled) files when the
* test completes.
*/
private static final boolean DELETE_TEMP_FILES = true;
/**
* {@code true} to call {@link System#gc} and then wait for 5 seconds at the
* end of the test to make it easier for a profiler to grab a heap dump at
* the end of the test run.
*/
private static final boolean PAUSE_FOR_HEAP_DUMP = false;
/**
* Parse each file with {@code JavaParser.compilationUnit}.
*/
private static final boolean RUN_PARSER = true;
/**
* {@code true} to use {@link BailErrorStrategy}, {@code false} to use
* {@link DefaultErrorStrategy}.
*/
private static final boolean BAIL_ON_ERROR = false;
/**
* {@code true} to compute a checksum for verifying consistency across
* optimizations and multiple passes.
*/
private static final boolean COMPUTE_CHECKSUM = true;
/**
* This value is passed to {@link Parser#setBuildParseTree}.
*/
private static final boolean BUILD_PARSE_TREES = false;
/**
* Use
* {@link ParseTreeWalker#DEFAULT}{@code .}{@link ParseTreeWalker#walk walk}
* with the {@code JavaParserBaseListener} to show parse tree walking
* overhead. If {@link #BUILD_PARSE_TREES} is {@code false}, the listener
* will instead be called during the parsing process via
* {@link Parser#addParseListener}.
*/
private static final boolean BLANK_LISTENER = false;
/**
* Shows the number of {@link DFAState} and {@link ATNConfig} instances in
* the DFA cache at the end of each pass. If {@link #REUSE_LEXER_DFA} and/or
* {@link #REUSE_PARSER_DFA} are false, the corresponding instance numbers
* will only apply to one file (the last file if {@link #NUMBER_OF_THREADS}
* is 0, otherwise the last file which was parsed on the first thread).
*/
private static final boolean SHOW_DFA_STATE_STATS = true;
/**
* Specify the {@link PredictionMode} used by the
* {@link ParserATNSimulator}. If {@link #TWO_STAGE_PARSING} is
* {@code true}, this value only applies to the second stage, as the first
* stage will always use {@link PredictionMode#SLL}.
*/
private static final PredictionMode PREDICTION_MODE = PredictionMode.LL;
private static final boolean TWO_STAGE_PARSING = true;
private static final boolean SHOW_CONFIG_STATS = false;
private static final boolean REPORT_SYNTAX_ERRORS = true;
private static final boolean REPORT_AMBIGUITIES = false;
private static final boolean REPORT_FULL_CONTEXT = false;
private static final boolean REPORT_CONTEXT_SENSITIVITY = REPORT_FULL_CONTEXT;
/**
* If {@code true}, a single {@code JavaLexer} will be used, and
* {@link Lexer#setInputStream} will be called to initialize it for each
* source file. Otherwise, a new instance will be created for each file.
*/
private static final boolean REUSE_LEXER = false;
/**
* If {@code true}, a single DFA will be used for lexing which is shared
* across all threads and files. Otherwise, each file will be lexed with its
* own DFA which is accomplished by creating one ATN instance per thread and
* clearing its DFA cache before lexing each file.
*/
private static final boolean REUSE_LEXER_DFA = true;
/**
* If {@code true}, a single {@code JavaParser} will be used, and
* {@link Parser#setInputStream} will be called to initialize it for each
* source file. Otherwise, a new instance will be created for each file.
*/
private static final boolean REUSE_PARSER = false;
/**
* If {@code true}, a single DFA will be used for parsing which is shared
* across all threads and files. Otherwise, each file will be parsed with
* its own DFA which is accomplished by creating one ATN instance per thread
* and clearing its DFA cache before parsing each file.
*/
private static final boolean REUSE_PARSER_DFA = true;
/**
* If {@code true}, the shared lexer and parser are reset after each pass.
* If {@code false}, all passes after the first will be fully "warmed up",
* which makes them faster and can compare them to the first warm-up pass,
* but it will not distinguish bytecode load/JIT time from warm-up time
* during the first pass.
*/
private static final boolean CLEAR_DFA = false;
/**
* Total number of passes to make over the source.
*/
private static final int PASSES = 4;
/**
* Number of parser threads to use.
*/
private static final int NUMBER_OF_THREADS = 1;
private static final Lexer[] sharedLexers = new Lexer[NUMBER_OF_THREADS];
private static final Parser[] sharedParsers = new Parser[NUMBER_OF_THREADS];
private static final ParseTreeListener[] sharedListeners = new ParseTreeListener[NUMBER_OF_THREADS];
private final AtomicInteger tokenCount = new AtomicInteger();
private int currentPass;
@Test
//@org.junit.Ignore
public void compileJdk() throws IOException, InterruptedException {
String jdkSourceRoot = getSourceRoot("JDK");
assertTrue("The JDK_SOURCE_ROOT environment variable must be set for performance testing.", jdkSourceRoot != null && !jdkSourceRoot.isEmpty());
compileJavaParser(USE_LR_GRAMMAR);
final String lexerName = "JavaLexer";
final String parserName = "JavaParser";
final String listenerName = "JavaBaseListener";
final String entryPoint = "compilationUnit";
ParserFactory factory = getParserFactory(lexerName, parserName, listenerName, entryPoint);
if (!TOP_PACKAGE.isEmpty()) {
jdkSourceRoot = jdkSourceRoot + '/' + TOP_PACKAGE.replace('.', '/');
}
File directory = new File(jdkSourceRoot);
assertTrue(directory.isDirectory());
FilenameFilter filesFilter = FilenameFilters.extension(".java", false);
FilenameFilter directoriesFilter = FilenameFilters.ALL_FILES;
List<InputDescriptor> sources = loadSources(directory, filesFilter, directoriesFilter, RECURSIVE);
if (SHUFFLE_FILES_AT_START) {
Collections.shuffle(sources, RANDOM);
}
System.out.format("Located %d source files.%n", sources.size());
System.out.print(getOptionsDescription(TOP_PACKAGE));
currentPass = 0;
parse1(factory, sources);
for (int i = 0; i < PASSES - 1; i++) {
currentPass = i + 1;
if (CLEAR_DFA) {
if (sharedLexers.length > 0) {
ATN atn = sharedLexers[0].getATN();
for (int j = 0; j < sharedLexers[0].getInterpreter().decisionToDFA.length; j++) {
sharedLexers[0].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j);
}
}
if (sharedParsers.length > 0) {
ATN atn = sharedParsers[0].getATN();
for (int j = 0; j < sharedParsers[0].getInterpreter().decisionToDFA.length; j++) {
sharedParsers[0].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j);
}
}
Arrays.fill(sharedLexers, null);
Arrays.fill(sharedParsers, null);
}
if (SHUFFLE_FILES_AFTER_ITERATIONS) {
Collections.shuffle(sources, RANDOM);
}
parse2(factory, sources);
}
sources.clear();
if (PAUSE_FOR_HEAP_DUMP) {
System.gc();
System.out.println("Pausing before application exit.");
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private String getSourceRoot(String prefix) {
String sourceRoot = System.getenv(prefix+"_SOURCE_ROOT");
if (sourceRoot == null) {
sourceRoot = System.getProperty(prefix+"_SOURCE_ROOT");
}
return sourceRoot;
}
@Override
protected void eraseTempDir() {
if (DELETE_TEMP_FILES) {
super.eraseTempDir();
}
}
public static String getOptionsDescription(String topPackage) {
StringBuilder builder = new StringBuilder();
builder.append("Input=");
if (topPackage.isEmpty()) {
builder.append("*");
}
else {
builder.append(topPackage).append(".*");
}
builder.append(", Grammar=").append(USE_LR_GRAMMAR ? "LR" : "Standard");
builder.append(", ForceAtn=").append(FORCE_ATN);
builder.append(newline);
builder.append("Op=Lex").append(RUN_PARSER ? "+Parse" : " only");
builder.append(", Strategy=").append(BAIL_ON_ERROR ? BailErrorStrategy.class.getSimpleName() : DefaultErrorStrategy.class.getSimpleName());
builder.append(", BuildParseTree=").append(BUILD_PARSE_TREES);
builder.append(", WalkBlankListener=").append(BLANK_LISTENER);
builder.append(newline);
builder.append("Lexer=").append(REUSE_LEXER ? "setInputStream" : "newInstance");
builder.append(", Parser=").append(REUSE_PARSER ? "setInputStream" : "newInstance");
builder.append(", AfterPass=").append(CLEAR_DFA ? "newInstance" : "setInputStream");
builder.append(newline);
return builder.toString();
}
/**
* This method is separate from {@link #parse2} so the first pass can be distinguished when analyzing
* profiler results.
*/
protected void parse1(ParserFactory factory, Collection<InputDescriptor> sources) throws InterruptedException {
System.gc();
parseSources(factory, sources);
}
/**
* This method is separate from {@link #parse1} so the first pass can be distinguished when analyzing
* profiler results.
*/
protected void parse2(ParserFactory factory, Collection<InputDescriptor> sources) throws InterruptedException {
System.gc();
parseSources(factory, sources);
}
protected List<InputDescriptor> loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive) {
List<InputDescriptor> result = new ArrayList<InputDescriptor>();
loadSources(directory, filesFilter, directoriesFilter, recursive, result);
return result;
}
protected void loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive, Collection<InputDescriptor> result) {
assert directory.isDirectory();
File[] sources = directory.listFiles(filesFilter);
for (File file : sources) {
if (!file.isFile()) {
continue;
}
result.add(new InputDescriptor(file.getAbsolutePath()));
}
if (recursive) {
File[] children = directory.listFiles(directoriesFilter);
for (File child : children) {
if (child.isDirectory()) {
loadSources(child, filesFilter, directoriesFilter, true, result);
}
}
}
}
int configOutputSize = 0;
@SuppressWarnings("unused")
protected void parseSources(final ParserFactory factory, Collection<InputDescriptor> sources) throws InterruptedException {
long startTime = System.currentTimeMillis();
tokenCount.set(0);
int inputSize = 0;
int inputCount = 0;
Collection<Future<FileParseResult>> results = new ArrayList<Future<FileParseResult>>();
ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS, new NumberedThreadFactory());
for (InputDescriptor inputDescriptor : sources) {
if (inputCount >= MAX_FILES_PER_PARSE_ITERATION) {
break;
}
final CharStream input = inputDescriptor.getInputStream();
input.seek(0);
inputSize += input.size();
inputCount++;
Future<FileParseResult> futureChecksum = executorService.submit(new Callable<FileParseResult>() {
@Override
public FileParseResult call() {
// this incurred a great deal of overhead and was causing significant variations in performance results.
//System.out.format("Parsing file %s\n", input.getSourceName());
try {
return factory.parseFile(input, ((NumberedThread)Thread.currentThread()).getThreadNumber());
} catch (IllegalStateException ex) {
ex.printStackTrace(System.err);
} catch (Throwable t) {
t.printStackTrace(System.err);
}
return null;
}
});
results.add(futureChecksum);
}
Checksum checksum = new CRC32();
for (Future<FileParseResult> future : results) {
int fileChecksum = 0;
try {
FileParseResult fileResult = future.get();
fileChecksum = fileResult.checksum;
} catch (ExecutionException ex) {
Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);
}
if (COMPUTE_CHECKSUM) {
updateChecksum(checksum, fileChecksum);
}
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
System.out.format("Total parse time for %d files (%d KB, %d tokens, checksum 0x%8X): %dms%n",
inputCount,
inputSize / 1024,
tokenCount.get(),
COMPUTE_CHECKSUM ? checksum.getValue() : 0,
System.currentTimeMillis() - startTime);
if (sharedLexers.length > 0) {
Lexer lexer = sharedLexers[0];
final LexerATNSimulator lexerInterpreter = lexer.getInterpreter();
final DFA[] modeToDFA = lexerInterpreter.decisionToDFA;
if (SHOW_DFA_STATE_STATS) {
int states = 0;
int configs = 0;
Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();
for (int i = 0; i < modeToDFA.length; i++) {
DFA dfa = modeToDFA[i];
if (dfa == null) {
continue;
}
states += dfa.states.size();
for (DFAState state : dfa.states.values()) {
configs += state.configs.size();
uniqueConfigs.addAll(state.configs);
}
}
System.out.format("There are %d lexer DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size());
}
}
if (RUN_PARSER && sharedParsers.length > 0) {
Parser parser = sharedParsers[0];
// make sure the individual DFAState objects actually have unique ATNConfig arrays
final ParserATNSimulator interpreter = parser.getInterpreter();
final DFA[] decisionToDFA = interpreter.decisionToDFA;
if (SHOW_DFA_STATE_STATS) {
int states = 0;
int configs = 0;
Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();
for (int i = 0; i < decisionToDFA.length; i++) {
DFA dfa = decisionToDFA[i];
if (dfa == null) {
continue;
}
states += dfa.states.size();
for (DFAState state : dfa.states.values()) {
configs += state.configs.size();
uniqueConfigs.addAll(state.configs);
}
}
System.out.format("There are %d parser DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size());
}
int localDfaCount = 0;
int globalDfaCount = 0;
int localConfigCount = 0;
int globalConfigCount = 0;
int[] contextsInDFAState = new int[0];
for (int i = 0; i < decisionToDFA.length; i++) {
DFA dfa = decisionToDFA[i];
if (dfa == null) {
continue;
}
if (SHOW_CONFIG_STATS) {
for (DFAState state : dfa.states.keySet()) {
if (state.configs.size() >= contextsInDFAState.length) {
contextsInDFAState = Arrays.copyOf(contextsInDFAState, state.configs.size() + 1);
}
if (state.isAcceptState) {
boolean hasGlobal = false;
for (ATNConfig config : state.configs) {
if (config.reachesIntoOuterContext > 0) {
globalConfigCount++;
hasGlobal = true;
} else {
localConfigCount++;
}
}
if (hasGlobal) {
globalDfaCount++;
} else {
localDfaCount++;
}
}
contextsInDFAState[state.configs.size()]++;
}
}
}
if (SHOW_CONFIG_STATS && currentPass == 0) {
System.out.format(" DFA accept states: %d total, %d with only local context, %d with a global context%n", localDfaCount + globalDfaCount, localDfaCount, globalDfaCount);
System.out.format(" Config stats: %d total, %d local, %d global%n", localConfigCount + globalConfigCount, localConfigCount, globalConfigCount);
if (SHOW_DFA_STATE_STATS) {
for (int i = 0; i < contextsInDFAState.length; i++) {
if (contextsInDFAState[i] != 0) {
System.out.format(" %d configs = %d%n", i, contextsInDFAState[i]);
}
}
}
}
}
}
protected void compileJavaParser(boolean leftRecursive) throws IOException {
String grammarFileName = "Java.g4";
String sourceName = leftRecursive ? "Java-LR.g4" : "Java.g4";
String body = load(sourceName, null);
List<String> extraOptions = new ArrayList<String>();
extraOptions.add("-Werror");
if (FORCE_ATN) {
extraOptions.add("-Xforce-atn");
}
if (EXPORT_ATN_GRAPHS) {
extraOptions.add("-atn");
}
if (DEBUG_TEMPLATES) {
extraOptions.add("-XdbgST");
if (DEBUG_TEMPLATES_WAIT) {
extraOptions.add("-XdbgSTWait");
}
}
extraOptions.add("-visitor");
String[] extraOptionsArray = extraOptions.toArray(new String[extraOptions.size()]);
boolean success = rawGenerateAndBuildRecognizer(grammarFileName, body, "JavaParser", "JavaLexer", true, extraOptionsArray);
assertTrue(success);
}
protected String load(String fileName, @Nullable String encoding)
throws IOException
{
if ( fileName==null ) {
return null;
}
String fullFileName = getClass().getPackage().getName().replace('.', '/') + '/' + fileName;
int size = 65000;
InputStreamReader isr;
InputStream fis = getClass().getClassLoader().getResourceAsStream(fullFileName);
if ( encoding!=null ) {
isr = new InputStreamReader(fis, encoding);
}
else {
isr = new InputStreamReader(fis);
}
try {
char[] data = new char[size];
int n = isr.read(data);
return new String(data, 0, n);
}
finally {
isr.close();
}
}
private static void updateChecksum(Checksum checksum, int value) {
checksum.update((value) & 0xFF);
checksum.update((value >>> 8) & 0xFF);
checksum.update((value >>> 16) & 0xFF);
checksum.update((value >>> 24) & 0xFF);
}
private static void updateChecksum(Checksum checksum, Token token) {
if (token == null) {
checksum.update(0);
return;
}
updateChecksum(checksum, token.getStartIndex());
updateChecksum(checksum, token.getStopIndex());
updateChecksum(checksum, token.getLine());
updateChecksum(checksum, token.getCharPositionInLine());
updateChecksum(checksum, token.getType());
updateChecksum(checksum, token.getChannel());
}
protected ParserFactory getParserFactory(String lexerName, String parserName, String listenerName, final String entryPoint) {
try {
ClassLoader loader = new URLClassLoader(new URL[] { new File(tmpdir).toURI().toURL() }, ClassLoader.getSystemClassLoader());
final Class<? extends Lexer> lexerClass = loader.loadClass(lexerName).asSubclass(Lexer.class);
final Class<? extends Parser> parserClass = loader.loadClass(parserName).asSubclass(Parser.class);
final Class<? extends ParseTreeListener> listenerClass = loader.loadClass(listenerName).asSubclass(ParseTreeListener.class);
final Constructor<? extends Lexer> lexerCtor = lexerClass.getConstructor(CharStream.class);
final Constructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class);
// construct initial instances of the lexer and parser to deserialize their ATNs
TokenSource tokenSource = lexerCtor.newInstance(new ANTLRInputStream(""));
parserCtor.newInstance(new CommonTokenStream(tokenSource));
return new ParserFactory() {
@Override
public FileParseResult parseFile(CharStream input, int thread) {
final Checksum checksum = new CRC32();
final long startTime = System.nanoTime();
assert thread >= 0 && thread < NUMBER_OF_THREADS;
try {
ParseTreeListener listener = sharedListeners[thread];
if (listener == null) {
listener = listenerClass.newInstance();
sharedListeners[thread] = listener;
}
Lexer lexer = sharedLexers[thread];
if (REUSE_LEXER && lexer != null) {
lexer.setInputStream(input);
} else {
lexer = lexerCtor.newInstance(input);
sharedLexers[thread] = lexer;
if (!REUSE_LEXER_DFA) {
Field decisionToDFAField = LexerATNSimulator.class.getDeclaredField("decisionToDFA");
decisionToDFAField.setAccessible(true);
decisionToDFAField.set(lexer.getInterpreter(), lexer.getInterpreter().decisionToDFA.clone());
}
}
if (!REUSE_LEXER_DFA) {
ATN atn = lexer.getATN();
for (int i = 0; i < lexer.getInterpreter().decisionToDFA.length; i++) {
lexer.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);
}
}
CommonTokenStream tokens = new CommonTokenStream(lexer);
tokens.fill();
tokenCount.addAndGet(tokens.size());
if (COMPUTE_CHECKSUM) {
for (Token token : tokens.getTokens()) {
updateChecksum(checksum, token);
}
}
if (!RUN_PARSER) {
return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), null, tokens.size(), startTime, lexer, null);
}
Parser parser = sharedParsers[thread];
if (REUSE_PARSER && parser != null) {
parser.setInputStream(tokens);
} else {
parser = parserCtor.newInstance(tokens);
sharedParsers[thread] = parser;
}
parser.removeErrorListeners();
if (!TWO_STAGE_PARSING) {
parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
parser.addErrorListener(new SummarizingDiagnosticErrorListener());
}
if (!REUSE_PARSER_DFA) {
Field decisionToDFAField = ParserATNSimulator.class.getDeclaredField("decisionToDFA");
decisionToDFAField.setAccessible(true);
decisionToDFAField.set(parser.getInterpreter(), parser.getInterpreter().decisionToDFA.clone());
}
if (!REUSE_PARSER_DFA) {
ATN atn = parser.getATN();
for (int i = 0; i < parser.getInterpreter().decisionToDFA.length; i++) {
parser.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);
}
}
parser.getInterpreter().setPredictionMode(TWO_STAGE_PARSING ? PredictionMode.SLL : PREDICTION_MODE);
parser.setBuildParseTree(BUILD_PARSE_TREES);
if (!BUILD_PARSE_TREES && BLANK_LISTENER) {
parser.addParseListener(listener);
}
if (BAIL_ON_ERROR || TWO_STAGE_PARSING) {
parser.setErrorHandler(new BailErrorStrategy());
}
Method parseMethod = parserClass.getMethod(entryPoint);
Object parseResult;
ParseTreeListener checksumParserListener = null;
try {
if (COMPUTE_CHECKSUM) {
checksumParserListener = new ChecksumParseTreeListener(checksum);
parser.addParseListener(checksumParserListener);
}
parseResult = parseMethod.invoke(parser);
} catch (InvocationTargetException ex) {
if (!TWO_STAGE_PARSING) {
throw ex;
}
String sourceName = tokens.getSourceName();
sourceName = sourceName != null && !sourceName.isEmpty() ? sourceName+": " : "";
System.err.println(sourceName+"Forced to retry with full context.");
if (!(ex.getCause() instanceof ParseCancellationException)) {
throw ex;
}
tokens.reset();
if (REUSE_PARSER && parser != null) {
parser.setInputStream(tokens);
} else {
parser = parserCtor.newInstance(tokens);
sharedParsers[thread] = parser;
}
parser.removeErrorListeners();
parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
parser.addErrorListener(new SummarizingDiagnosticErrorListener());
parser.getInterpreter().setPredictionMode(PredictionMode.LL);
parser.setBuildParseTree(BUILD_PARSE_TREES);
if (!BUILD_PARSE_TREES && BLANK_LISTENER) {
parser.addParseListener(listener);
}
if (BAIL_ON_ERROR) {
parser.setErrorHandler(new BailErrorStrategy());
}
parseResult = parseMethod.invoke(parser);
}
finally {
if (checksumParserListener != null) {
parser.removeParseListener(checksumParserListener);
}
}
assertThat(parseResult, instanceOf(ParseTree.class));
if (BUILD_PARSE_TREES && BLANK_LISTENER) {
ParseTreeWalker.DEFAULT.walk(listener, (ParseTree)parseResult);
}
return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), (ParseTree)parseResult, tokens.size(), startTime, lexer, parser);
} catch (Exception e) {
if (!REPORT_SYNTAX_ERRORS && e instanceof ParseCancellationException) {
return new FileParseResult("unknown", (int)checksum.getValue(), null, 0, startTime, null, null);
}
e.printStackTrace(System.out);
throw new IllegalStateException(e);
}
}
};
} catch (Exception e) {
e.printStackTrace(System.out);
Assert.fail(e.getMessage());
throw new IllegalStateException(e);
}
}
protected interface ParserFactory {
FileParseResult parseFile(CharStream input, int thread);
}
protected static class FileParseResult {
public final String sourceName;
public final int checksum;
public final ParseTree parseTree;
public final int tokenCount;
public final long startTime;
public final long endTime;
public final int lexerDFASize;
public final int parserDFASize;
public FileParseResult(String sourceName, int checksum, @Nullable ParseTree parseTree, int tokenCount, long startTime, Lexer lexer, Parser parser) {
this.sourceName = sourceName;
this.checksum = checksum;
this.parseTree = parseTree;
this.tokenCount = tokenCount;
this.startTime = startTime;
this.endTime = System.nanoTime();
if (lexer != null) {
LexerATNSimulator interpreter = lexer.getInterpreter();
int dfaSize = 0;
for (DFA dfa : interpreter.decisionToDFA) {
if (dfa != null && dfa.states != null) {
dfaSize += dfa.states.size();
}
}
lexerDFASize = dfaSize;
} else {
lexerDFASize = 0;
}
if (parser != null) {
ParserATNSimulator interpreter = parser.getInterpreter();
int dfaSize = 0;
for (DFA dfa : interpreter.decisionToDFA) {
if (dfa != null && dfa.states != null) {
dfaSize += dfa.states.size();
}
}
parserDFASize = dfaSize;
} else {
parserDFASize = 0;
}
}
}
private static class DescriptiveErrorListener extends BaseErrorListener {
public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener();
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
int line, int charPositionInLine,
String msg, RecognitionException e)
{
if (!REPORT_SYNTAX_ERRORS) {
return;
}
String sourceName = recognizer.getInputStream().getSourceName();
if (!sourceName.isEmpty()) {
sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine);
}
System.err.println(sourceName+"line "+line+":"+charPositionInLine+" "+msg);
}
}
private static class SummarizingDiagnosticErrorListener extends DiagnosticErrorListener {
@Override
public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet ambigAlts, ATNConfigSet configs) {
if (!REPORT_AMBIGUITIES) {
return;
}
super.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, ambigAlts, configs);
}
@Override
public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) {
if (!REPORT_FULL_CONTEXT) {
return;
}
super.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, configs);
}
@Override
public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) {
if (!REPORT_CONTEXT_SENSITIVITY) {
return;
}
super.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, configs);
}
}
protected static final class FilenameFilters {
public static final FilenameFilter ALL_FILES = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return true;
}
};
public static FilenameFilter extension(String extension) {
return extension(extension, true);
}
public static FilenameFilter extension(String extension, boolean caseSensitive) {
return new FileExtensionFilenameFilter(extension, caseSensitive);
}
public static FilenameFilter name(String filename) {
return name(filename, true);
}
public static FilenameFilter name(String filename, boolean caseSensitive) {
return new FileNameFilenameFilter(filename, caseSensitive);
}
public static FilenameFilter all(FilenameFilter... filters) {
return new AllFilenameFilter(filters);
}
public static FilenameFilter any(FilenameFilter... filters) {
return new AnyFilenameFilter(filters);
}
public static FilenameFilter none(FilenameFilter... filters) {
return not(any(filters));
}
public static FilenameFilter not(FilenameFilter filter) {
return new NotFilenameFilter(filter);
}
private FilenameFilters() {
}
protected static class FileExtensionFilenameFilter implements FilenameFilter {
private final String extension;
private final boolean caseSensitive;
public FileExtensionFilenameFilter(String extension, boolean caseSensitive) {
if (!extension.startsWith(".")) {
extension = '.' + extension;
}
this.extension = extension;
this.caseSensitive = caseSensitive;
}
@Override
public boolean accept(File dir, String name) {
if (caseSensitive) {
return name.endsWith(extension);
} else {
return name.toLowerCase().endsWith(extension);
}
}
}
protected static class FileNameFilenameFilter implements FilenameFilter {
private final String filename;
private final boolean caseSensitive;
public FileNameFilenameFilter(String filename, boolean caseSensitive) {
this.filename = filename;
this.caseSensitive = caseSensitive;
}
@Override
public boolean accept(File dir, String name) {
if (caseSensitive) {
return name.equals(filename);
} else {
return name.toLowerCase().equals(filename);
}
}
}
protected static class AllFilenameFilter implements FilenameFilter {
private final FilenameFilter[] filters;
public AllFilenameFilter(FilenameFilter[] filters) {
this.filters = filters;
}
@Override
public boolean accept(File dir, String name) {
for (FilenameFilter filter : filters) {
if (!filter.accept(dir, name)) {
return false;
}
}
return true;
}
}
protected static class AnyFilenameFilter implements FilenameFilter {
private final FilenameFilter[] filters;
public AnyFilenameFilter(FilenameFilter[] filters) {
this.filters = filters;
}
@Override
public boolean accept(File dir, String name) {
for (FilenameFilter filter : filters) {
if (filter.accept(dir, name)) {
return true;
}
}
return false;
}
}
protected static class NotFilenameFilter implements FilenameFilter {
private final FilenameFilter filter;
public NotFilenameFilter(FilenameFilter filter) {
this.filter = filter;
}
@Override
public boolean accept(File dir, String name) {
return !filter.accept(dir, name);
}
}
}
protected static class NumberedThread extends Thread {
private final int threadNumber;
public NumberedThread(Runnable target, int threadNumber) {
super(target);
this.threadNumber = threadNumber;
}
public final int getThreadNumber() {
return threadNumber;
}
}
protected static class NumberedThreadFactory implements ThreadFactory {
private final AtomicInteger nextThread = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
int threadNumber = nextThread.getAndIncrement();
assert threadNumber < NUMBER_OF_THREADS;
return new NumberedThread(r, threadNumber);
}
}
protected static class ChecksumParseTreeListener implements ParseTreeListener {
private static final int VISIT_TERMINAL = 1;
private static final int VISIT_ERROR_NODE = 2;
private static final int ENTER_RULE = 3;
private static final int EXIT_RULE = 4;
private final Checksum checksum;
public ChecksumParseTreeListener(Checksum checksum) {
this.checksum = checksum;
}
@Override
public void visitTerminal(TerminalNode node) {
checksum.update(VISIT_TERMINAL);
updateChecksum(checksum, node.getSymbol());
}
@Override
public void visitErrorNode(ErrorNode node) {
checksum.update(VISIT_ERROR_NODE);
updateChecksum(checksum, node.getSymbol());
}
@Override
public void enterEveryRule(ParserRuleContext ctx) {
checksum.update(ENTER_RULE);
updateChecksum(checksum, ctx.getRuleIndex());
updateChecksum(checksum, ctx.getStart());
}
@Override
public void exitEveryRule(ParserRuleContext ctx) {
checksum.update(EXIT_RULE);
updateChecksum(checksum, ctx.getRuleIndex());
updateChecksum(checksum, ctx.getStop());
}
}
protected static final class InputDescriptor {
private final String source;
private Reference<CharStream> inputStream;
public InputDescriptor(@NotNull String source) {
this.source = source;
if (PRELOAD_SOURCES) {
getInputStream();
}
}
@NotNull
public CharStream getInputStream() {
CharStream stream = inputStream != null ? inputStream.get() : null;
if (stream == null) {
try {
stream = new ANTLRFileStream(source, ENCODING);
} catch (IOException ex) {
Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);
stream = new ANTLRInputStream("");
}
if (PRELOAD_SOURCES) {
inputStream = new StrongReference<CharStream>(stream);
} else {
inputStream = new SoftReference<CharStream>(stream);
}
}
return stream;
}
}
public static class StrongReference<T> extends WeakReference<T> {
public final T referent;
public StrongReference(T referent) {
super(referent);
this.referent = referent;
}
@Override
public T get() {
return referent;
}
}
}
| tool/test/org/antlr/v4/test/TestPerformance.java | /*
* [The "BSD license"]
* Copyright (c) 2012 Terence Parr
* Copyright (c) 2012 Sam Harwell
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.antlr.v4.test;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DefaultErrorStrategy;
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenSource;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.ATNConfig;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.atn.LexerATNSimulator;
import org.antlr.v4.runtime.atn.ParserATNSimulator;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.dfa.DFAState;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.Nullable;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
public class TestPerformance extends BaseTest {
/**
* Parse all java files under this package within the JDK_SOURCE_ROOT
* (environment variable or property defined on the Java command line).
*/
private static final String TOP_PACKAGE = "java.lang";
/**
* {@code true} to load java files from sub-packages of
* {@link #TOP_PACKAGE}.
*/
private static final boolean RECURSIVE = true;
/**
* {@code true} to read all source files from disk into memory before
* starting the parse. The default value is {@code true} to help prevent
* drive speed from affecting the performance results. This value may be set
* to {@code false} to support parsing large input sets which would not
* otherwise fit into memory.
*/
private static final boolean PRELOAD_SOURCES = true;
/**
* The encoding to use when reading source files.
*/
private static final String ENCODING = "UTF-8";
/**
* The maximum number of files to parse in a single iteration.
*/
private static final int MAX_FILES_PER_PARSE_ITERATION = Integer.MAX_VALUE;
/**
* {@code true} to call {@link Collections#shuffle} on the list of input
* files before the first parse iteration.
*/
private static final boolean SHUFFLE_FILES_AT_START = false;
/**
* {@code true} to call {@link Collections#shuffle} before each parse
* iteration <em>after</em> the first.
*/
private static final boolean SHUFFLE_FILES_AFTER_ITERATIONS = false;
/**
* The instance of {@link Random} passed when calling
* {@link Collections#shuffle}.
*/
private static final Random RANDOM = new Random();
/**
* {@code true} to use the Java grammar with expressions in the v4
* left-recursive syntax (Java-LR.g4). {@code false} to use the standard
* grammar (Java.g4). In either case, the grammar is renamed in the
* temporary directory to Java.g4 before compiling.
*/
private static final boolean USE_LR_GRAMMAR = true;
/**
* {@code true} to specify the {@code -Xforce-atn} option when generating
* the grammar, forcing all decisions in {@code JavaParser} to be handled by
* {@link ParserATNSimulator#adaptivePredict}.
*/
private static final boolean FORCE_ATN = false;
/**
* {@code true} to specify the {@code -atn} option when generating the
* grammar. This will cause ANTLR to export the ATN for each decision as a
* DOT (GraphViz) file.
*/
private static final boolean EXPORT_ATN_GRAPHS = true;
/**
* {@code true} to specify the {@code -XdbgST} option when generating the
* grammar.
*/
private static final boolean DEBUG_TEMPLATES = false;
/**
* {@code true} to specify the {@code -XdbgSTWait} option when generating the
* grammar.
*/
private static final boolean DEBUG_TEMPLATES_WAIT = DEBUG_TEMPLATES;
/**
* {@code true} to delete temporary (generated and compiled) files when the
* test completes.
*/
private static final boolean DELETE_TEMP_FILES = true;
/**
* {@code true} to call {@link System#gc} and then wait for 5 seconds at the
* end of the test to make it easier for a profiler to grab a heap dump at
* the end of the test run.
*/
private static final boolean PAUSE_FOR_HEAP_DUMP = false;
/**
* Parse each file with {@code JavaParser.compilationUnit}.
*/
private static final boolean RUN_PARSER = true;
/**
* {@code true} to use {@link BailErrorStrategy}, {@code false} to use
* {@link DefaultErrorStrategy}.
*/
private static final boolean BAIL_ON_ERROR = false;
/**
* {@code true} to compute a checksum for verifying consistency across
* optimizations and multiple passes.
*/
private static final boolean COMPUTE_CHECKSUM = true;
/**
* This value is passed to {@link Parser#setBuildParseTree}.
*/
private static final boolean BUILD_PARSE_TREES = false;
/**
* Use
* {@link ParseTreeWalker#DEFAULT}{@code .}{@link ParseTreeWalker#walk walk}
* with the {@code JavaParserBaseListener} to show parse tree walking
* overhead. If {@link #BUILD_PARSE_TREES} is {@code false}, the listener
* will instead be called during the parsing process via
* {@link Parser#addParseListener}.
*/
private static final boolean BLANK_LISTENER = false;
/**
* Shows the number of {@link DFAState} and {@link ATNConfig} instances in
* the DFA cache at the end of each pass. If {@link #REUSE_LEXER_DFA} and/or
* {@link #REUSE_PARSER_DFA} are false, the corresponding instance numbers
* will only apply to one file (the last file if {@link #NUMBER_OF_THREADS}
* is 0, otherwise the last file which was parsed on the first thread).
*/
private static final boolean SHOW_DFA_STATE_STATS = true;
/**
* Specify the {@link PredictionMode} used by the
* {@link ParserATNSimulator}. If {@link #TWO_STAGE_PARSING} is
* {@code true}, this value only applies to the second stage, as the first
* stage will always use {@link PredictionMode#SLL}.
*/
private static final PredictionMode PREDICTION_MODE = PredictionMode.LL;
private static final boolean TWO_STAGE_PARSING = true;
private static final boolean SHOW_CONFIG_STATS = false;
private static final boolean REPORT_SYNTAX_ERRORS = true;
private static final boolean REPORT_AMBIGUITIES = false;
private static final boolean REPORT_FULL_CONTEXT = false;
private static final boolean REPORT_CONTEXT_SENSITIVITY = REPORT_FULL_CONTEXT;
/**
* If {@code true}, a single {@code JavaLexer} will be used, and
* {@link Lexer#setInputStream} will be called to initialize it for each
* source file. Otherwise, a new instance will be created for each file.
*/
private static final boolean REUSE_LEXER = false;
/**
* If {@code true}, a single DFA will be used for lexing which is shared
* across all threads and files. Otherwise, each file will be lexed with its
* own DFA which is accomplished by creating one ATN instance per thread and
* clearing its DFA cache before lexing each file.
*/
private static final boolean REUSE_LEXER_DFA = true;
/**
* If {@code true}, a single {@code JavaParser} will be used, and
* {@link Parser#setInputStream} will be called to initialize it for each
* source file. Otherwise, a new instance will be created for each file.
*/
private static final boolean REUSE_PARSER = false;
/**
* If {@code true}, a single DFA will be used for parsing which is shared
* across all threads and files. Otherwise, each file will be parsed with
* its own DFA which is accomplished by creating one ATN instance per thread
* and clearing its DFA cache before parsing each file.
*/
private static final boolean REUSE_PARSER_DFA = true;
/**
* If {@code true}, the shared lexer and parser are reset after each pass.
* If {@code false}, all passes after the first will be fully "warmed up",
* which makes them faster and can compare them to the first warm-up pass,
* but it will not distinguish bytecode load/JIT time from warm-up time
* during the first pass.
*/
private static final boolean CLEAR_DFA = false;
/**
* Total number of passes to make over the source.
*/
private static final int PASSES = 4;
/**
* Number of parser threads to use.
*/
private static final int NUMBER_OF_THREADS = 1;
private static final Lexer[] sharedLexers = new Lexer[NUMBER_OF_THREADS];
private static final Parser[] sharedParsers = new Parser[NUMBER_OF_THREADS];
private static final ParseTreeListener[] sharedListeners = new ParseTreeListener[NUMBER_OF_THREADS];
private final AtomicInteger tokenCount = new AtomicInteger();
private int currentPass;
@Test
//@org.junit.Ignore
public void compileJdk() throws IOException, InterruptedException {
String jdkSourceRoot = getSourceRoot("JDK");
assertTrue("The JDK_SOURCE_ROOT environment variable must be set for performance testing.", jdkSourceRoot != null && !jdkSourceRoot.isEmpty());
compileJavaParser(USE_LR_GRAMMAR);
final String lexerName = "JavaLexer";
final String parserName = "JavaParser";
final String listenerName = "JavaBaseListener";
final String entryPoint = "compilationUnit";
ParserFactory factory = getParserFactory(lexerName, parserName, listenerName, entryPoint);
if (!TOP_PACKAGE.isEmpty()) {
jdkSourceRoot = jdkSourceRoot + '/' + TOP_PACKAGE.replace('.', '/');
}
File directory = new File(jdkSourceRoot);
assertTrue(directory.isDirectory());
FilenameFilter filesFilter = FilenameFilters.extension(".java", false);
FilenameFilter directoriesFilter = FilenameFilters.ALL_FILES;
List<InputDescriptor> sources = loadSources(directory, filesFilter, directoriesFilter, RECURSIVE);
if (SHUFFLE_FILES_AT_START) {
Collections.shuffle(sources, RANDOM);
}
System.out.format("Located %d source files.%n", sources.size());
System.out.print(getOptionsDescription(TOP_PACKAGE));
currentPass = 0;
parse1(factory, sources);
for (int i = 0; i < PASSES - 1; i++) {
currentPass = i + 1;
if (CLEAR_DFA) {
if (sharedLexers.length > 0) {
ATN atn = sharedLexers[0].getATN();
for (int j = 0; j < sharedLexers[0].getInterpreter().decisionToDFA.length; j++) {
sharedLexers[0].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j);
}
}
if (sharedParsers.length > 0) {
ATN atn = sharedParsers[0].getATN();
for (int j = 0; j < sharedParsers[0].getInterpreter().decisionToDFA.length; j++) {
sharedParsers[0].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j);
}
}
Arrays.fill(sharedLexers, null);
Arrays.fill(sharedParsers, null);
}
if (SHUFFLE_FILES_AFTER_ITERATIONS) {
Collections.shuffle(sources, RANDOM);
}
parse2(factory, sources);
}
sources.clear();
if (PAUSE_FOR_HEAP_DUMP) {
System.gc();
System.out.println("Pausing before application exit.");
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private String getSourceRoot(String prefix) {
String sourceRoot = System.getenv(prefix+"_SOURCE_ROOT");
if (sourceRoot == null) {
sourceRoot = System.getProperty(prefix+"_SOURCE_ROOT");
}
return sourceRoot;
}
@Override
protected void eraseTempDir() {
if (DELETE_TEMP_FILES) {
super.eraseTempDir();
}
}
public static String getOptionsDescription(String topPackage) {
StringBuilder builder = new StringBuilder();
builder.append("Input=");
if (topPackage.isEmpty()) {
builder.append("*");
}
else {
builder.append(topPackage).append(".*");
}
builder.append(", Grammar=").append(USE_LR_GRAMMAR ? "LR" : "Standard");
builder.append(", ForceAtn=").append(FORCE_ATN);
builder.append(newline);
builder.append("Op=Lex").append(RUN_PARSER ? "+Parse" : " only");
builder.append(", Strategy=").append(BAIL_ON_ERROR ? BailErrorStrategy.class.getSimpleName() : DefaultErrorStrategy.class.getSimpleName());
builder.append(", BuildParseTree=").append(BUILD_PARSE_TREES);
builder.append(", WalkBlankListener=").append(BLANK_LISTENER);
builder.append(newline);
builder.append("Lexer=").append(REUSE_LEXER ? "setInputStream" : "newInstance");
builder.append(", Parser=").append(REUSE_PARSER ? "setInputStream" : "newInstance");
builder.append(", AfterPass=").append(CLEAR_DFA ? "newInstance" : "setInputStream");
builder.append(newline);
return builder.toString();
}
/**
* This method is separate from {@link #parse2} so the first pass can be distinguished when analyzing
* profiler results.
*/
protected void parse1(ParserFactory factory, Collection<InputDescriptor> sources) throws InterruptedException {
System.gc();
parseSources(factory, sources);
}
/**
* This method is separate from {@link #parse1} so the first pass can be distinguished when analyzing
* profiler results.
*/
protected void parse2(ParserFactory factory, Collection<InputDescriptor> sources) throws InterruptedException {
System.gc();
parseSources(factory, sources);
}
protected List<InputDescriptor> loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive) {
List<InputDescriptor> result = new ArrayList<InputDescriptor>();
loadSources(directory, filesFilter, directoriesFilter, recursive, result);
return result;
}
protected void loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive, Collection<InputDescriptor> result) {
assert directory.isDirectory();
File[] sources = directory.listFiles(filesFilter);
for (File file : sources) {
if (!file.isFile()) {
continue;
}
result.add(new InputDescriptor(file.getAbsolutePath()));
}
if (recursive) {
File[] children = directory.listFiles(directoriesFilter);
for (File child : children) {
if (child.isDirectory()) {
loadSources(child, filesFilter, directoriesFilter, true, result);
}
}
}
}
int configOutputSize = 0;
@SuppressWarnings("unused")
protected void parseSources(final ParserFactory factory, Collection<InputDescriptor> sources) throws InterruptedException {
long startTime = System.currentTimeMillis();
tokenCount.set(0);
int inputSize = 0;
int inputCount = 0;
Collection<Future<Integer>> results = new ArrayList<Future<Integer>>();
ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS, new NumberedThreadFactory());
for (InputDescriptor inputDescriptor : sources) {
if (inputCount >= MAX_FILES_PER_PARSE_ITERATION) {
break;
}
final CharStream input = inputDescriptor.getInputStream();
input.seek(0);
inputSize += input.size();
inputCount++;
Future<Integer> futureChecksum = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() {
// this incurred a great deal of overhead and was causing significant variations in performance results.
//System.out.format("Parsing file %s\n", input.getSourceName());
try {
return factory.parseFile(input, ((NumberedThread)Thread.currentThread()).getThreadNumber());
} catch (IllegalStateException ex) {
ex.printStackTrace(System.err);
} catch (Throwable t) {
t.printStackTrace(System.err);
}
return -1;
}
});
results.add(futureChecksum);
}
Checksum checksum = new CRC32();
for (Future<Integer> future : results) {
int value = 0;
try {
value = future.get();
} catch (ExecutionException ex) {
Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);
}
if (COMPUTE_CHECKSUM) {
updateChecksum(checksum, value);
}
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
System.out.format("Total parse time for %d files (%d KB, %d tokens, checksum 0x%8X): %dms%n",
inputCount,
inputSize / 1024,
tokenCount.get(),
COMPUTE_CHECKSUM ? checksum.getValue() : 0,
System.currentTimeMillis() - startTime);
if (sharedLexers.length > 0) {
Lexer lexer = sharedLexers[0];
final LexerATNSimulator lexerInterpreter = lexer.getInterpreter();
final DFA[] modeToDFA = lexerInterpreter.decisionToDFA;
if (SHOW_DFA_STATE_STATS) {
int states = 0;
int configs = 0;
Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();
for (int i = 0; i < modeToDFA.length; i++) {
DFA dfa = modeToDFA[i];
if (dfa == null) {
continue;
}
states += dfa.states.size();
for (DFAState state : dfa.states.values()) {
configs += state.configs.size();
uniqueConfigs.addAll(state.configs);
}
}
System.out.format("There are %d lexer DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size());
}
}
if (RUN_PARSER && sharedParsers.length > 0) {
Parser parser = sharedParsers[0];
// make sure the individual DFAState objects actually have unique ATNConfig arrays
final ParserATNSimulator interpreter = parser.getInterpreter();
final DFA[] decisionToDFA = interpreter.decisionToDFA;
if (SHOW_DFA_STATE_STATS) {
int states = 0;
int configs = 0;
Set<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();
for (int i = 0; i < decisionToDFA.length; i++) {
DFA dfa = decisionToDFA[i];
if (dfa == null) {
continue;
}
states += dfa.states.size();
for (DFAState state : dfa.states.values()) {
configs += state.configs.size();
uniqueConfigs.addAll(state.configs);
}
}
System.out.format("There are %d parser DFAState instances, %d configs (%d unique).%n", states, configs, uniqueConfigs.size());
}
int localDfaCount = 0;
int globalDfaCount = 0;
int localConfigCount = 0;
int globalConfigCount = 0;
int[] contextsInDFAState = new int[0];
for (int i = 0; i < decisionToDFA.length; i++) {
DFA dfa = decisionToDFA[i];
if (dfa == null) {
continue;
}
if (SHOW_CONFIG_STATS) {
for (DFAState state : dfa.states.keySet()) {
if (state.configs.size() >= contextsInDFAState.length) {
contextsInDFAState = Arrays.copyOf(contextsInDFAState, state.configs.size() + 1);
}
if (state.isAcceptState) {
boolean hasGlobal = false;
for (ATNConfig config : state.configs) {
if (config.reachesIntoOuterContext > 0) {
globalConfigCount++;
hasGlobal = true;
} else {
localConfigCount++;
}
}
if (hasGlobal) {
globalDfaCount++;
} else {
localDfaCount++;
}
}
contextsInDFAState[state.configs.size()]++;
}
}
}
if (SHOW_CONFIG_STATS && currentPass == 0) {
System.out.format(" DFA accept states: %d total, %d with only local context, %d with a global context%n", localDfaCount + globalDfaCount, localDfaCount, globalDfaCount);
System.out.format(" Config stats: %d total, %d local, %d global%n", localConfigCount + globalConfigCount, localConfigCount, globalConfigCount);
if (SHOW_DFA_STATE_STATS) {
for (int i = 0; i < contextsInDFAState.length; i++) {
if (contextsInDFAState[i] != 0) {
System.out.format(" %d configs = %d%n", i, contextsInDFAState[i]);
}
}
}
}
}
}
protected void compileJavaParser(boolean leftRecursive) throws IOException {
String grammarFileName = "Java.g4";
String sourceName = leftRecursive ? "Java-LR.g4" : "Java.g4";
String body = load(sourceName, null);
List<String> extraOptions = new ArrayList<String>();
extraOptions.add("-Werror");
if (FORCE_ATN) {
extraOptions.add("-Xforce-atn");
}
if (EXPORT_ATN_GRAPHS) {
extraOptions.add("-atn");
}
if (DEBUG_TEMPLATES) {
extraOptions.add("-XdbgST");
if (DEBUG_TEMPLATES_WAIT) {
extraOptions.add("-XdbgSTWait");
}
}
extraOptions.add("-visitor");
String[] extraOptionsArray = extraOptions.toArray(new String[extraOptions.size()]);
boolean success = rawGenerateAndBuildRecognizer(grammarFileName, body, "JavaParser", "JavaLexer", true, extraOptionsArray);
assertTrue(success);
}
protected String load(String fileName, @Nullable String encoding)
throws IOException
{
if ( fileName==null ) {
return null;
}
String fullFileName = getClass().getPackage().getName().replace('.', '/') + '/' + fileName;
int size = 65000;
InputStreamReader isr;
InputStream fis = getClass().getClassLoader().getResourceAsStream(fullFileName);
if ( encoding!=null ) {
isr = new InputStreamReader(fis, encoding);
}
else {
isr = new InputStreamReader(fis);
}
try {
char[] data = new char[size];
int n = isr.read(data);
return new String(data, 0, n);
}
finally {
isr.close();
}
}
private static void updateChecksum(Checksum checksum, int value) {
checksum.update((value) & 0xFF);
checksum.update((value >>> 8) & 0xFF);
checksum.update((value >>> 16) & 0xFF);
checksum.update((value >>> 24) & 0xFF);
}
private static void updateChecksum(Checksum checksum, Token token) {
if (token == null) {
checksum.update(0);
return;
}
updateChecksum(checksum, token.getStartIndex());
updateChecksum(checksum, token.getStopIndex());
updateChecksum(checksum, token.getLine());
updateChecksum(checksum, token.getCharPositionInLine());
updateChecksum(checksum, token.getType());
updateChecksum(checksum, token.getChannel());
}
protected ParserFactory getParserFactory(String lexerName, String parserName, String listenerName, final String entryPoint) {
try {
ClassLoader loader = new URLClassLoader(new URL[] { new File(tmpdir).toURI().toURL() }, ClassLoader.getSystemClassLoader());
final Class<? extends Lexer> lexerClass = loader.loadClass(lexerName).asSubclass(Lexer.class);
final Class<? extends Parser> parserClass = loader.loadClass(parserName).asSubclass(Parser.class);
final Class<? extends ParseTreeListener> listenerClass = loader.loadClass(listenerName).asSubclass(ParseTreeListener.class);
final Constructor<? extends Lexer> lexerCtor = lexerClass.getConstructor(CharStream.class);
final Constructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class);
// construct initial instances of the lexer and parser to deserialize their ATNs
TokenSource tokenSource = lexerCtor.newInstance(new ANTLRInputStream(""));
parserCtor.newInstance(new CommonTokenStream(tokenSource));
return new ParserFactory() {
@Override
public int parseFile(CharStream input, int thread) {
final Checksum checksum = new CRC32();
assert thread >= 0 && thread < NUMBER_OF_THREADS;
try {
ParseTreeListener listener = sharedListeners[thread];
if (listener == null) {
listener = listenerClass.newInstance();
sharedListeners[thread] = listener;
}
Lexer lexer = sharedLexers[thread];
if (REUSE_LEXER && lexer != null) {
lexer.setInputStream(input);
} else {
lexer = lexerCtor.newInstance(input);
sharedLexers[thread] = lexer;
if (!REUSE_LEXER_DFA) {
Field decisionToDFAField = LexerATNSimulator.class.getDeclaredField("decisionToDFA");
decisionToDFAField.setAccessible(true);
decisionToDFAField.set(lexer.getInterpreter(), lexer.getInterpreter().decisionToDFA.clone());
}
}
if (!REUSE_LEXER_DFA) {
ATN atn = lexer.getATN();
for (int i = 0; i < lexer.getInterpreter().decisionToDFA.length; i++) {
lexer.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);
}
}
CommonTokenStream tokens = new CommonTokenStream(lexer);
tokens.fill();
tokenCount.addAndGet(tokens.size());
if (COMPUTE_CHECKSUM) {
for (Token token : tokens.getTokens()) {
updateChecksum(checksum, token);
}
}
if (!RUN_PARSER) {
return (int)checksum.getValue();
}
Parser parser = sharedParsers[thread];
if (REUSE_PARSER && parser != null) {
parser.setInputStream(tokens);
} else {
parser = parserCtor.newInstance(tokens);
sharedParsers[thread] = parser;
}
parser.removeErrorListeners();
if (!TWO_STAGE_PARSING) {
parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
parser.addErrorListener(new SummarizingDiagnosticErrorListener());
}
if (!REUSE_PARSER_DFA) {
Field decisionToDFAField = ParserATNSimulator.class.getDeclaredField("decisionToDFA");
decisionToDFAField.setAccessible(true);
decisionToDFAField.set(parser.getInterpreter(), parser.getInterpreter().decisionToDFA.clone());
}
if (!REUSE_PARSER_DFA) {
ATN atn = parser.getATN();
for (int i = 0; i < parser.getInterpreter().decisionToDFA.length; i++) {
parser.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);
}
}
parser.getInterpreter().setPredictionMode(TWO_STAGE_PARSING ? PredictionMode.SLL : PREDICTION_MODE);
parser.setBuildParseTree(BUILD_PARSE_TREES);
if (!BUILD_PARSE_TREES && BLANK_LISTENER) {
parser.addParseListener(listener);
}
if (BAIL_ON_ERROR || TWO_STAGE_PARSING) {
parser.setErrorHandler(new BailErrorStrategy());
}
Method parseMethod = parserClass.getMethod(entryPoint);
Object parseResult;
ParseTreeListener checksumParserListener = null;
try {
if (COMPUTE_CHECKSUM) {
checksumParserListener = new ChecksumParseTreeListener(checksum);
parser.addParseListener(checksumParserListener);
}
parseResult = parseMethod.invoke(parser);
} catch (InvocationTargetException ex) {
if (!TWO_STAGE_PARSING) {
throw ex;
}
String sourceName = tokens.getSourceName();
sourceName = sourceName != null && !sourceName.isEmpty() ? sourceName+": " : "";
System.err.println(sourceName+"Forced to retry with full context.");
if (!(ex.getCause() instanceof ParseCancellationException)) {
throw ex;
}
tokens.reset();
if (REUSE_PARSER && parser != null) {
parser.setInputStream(tokens);
} else {
parser = parserCtor.newInstance(tokens);
sharedParsers[thread] = parser;
}
parser.removeErrorListeners();
parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
parser.addErrorListener(new SummarizingDiagnosticErrorListener());
parser.getInterpreter().setPredictionMode(PredictionMode.LL);
parser.setBuildParseTree(BUILD_PARSE_TREES);
if (!BUILD_PARSE_TREES && BLANK_LISTENER) {
parser.addParseListener(listener);
}
if (BAIL_ON_ERROR) {
parser.setErrorHandler(new BailErrorStrategy());
}
parseResult = parseMethod.invoke(parser);
}
finally {
if (checksumParserListener != null) {
parser.removeParseListener(checksumParserListener);
}
}
assertThat(parseResult, instanceOf(ParseTree.class));
if (BUILD_PARSE_TREES && BLANK_LISTENER) {
ParseTreeWalker.DEFAULT.walk(listener, (ParseTree)parseResult);
}
} catch (Exception e) {
if (!REPORT_SYNTAX_ERRORS && e instanceof ParseCancellationException) {
return (int)checksum.getValue();
}
e.printStackTrace(System.out);
throw new IllegalStateException(e);
}
return (int)checksum.getValue();
}
};
} catch (Exception e) {
e.printStackTrace(System.out);
Assert.fail(e.getMessage());
throw new IllegalStateException(e);
}
}
protected interface ParserFactory {
int parseFile(CharStream input, int thread);
}
private static class DescriptiveErrorListener extends BaseErrorListener {
public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener();
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
int line, int charPositionInLine,
String msg, RecognitionException e)
{
if (!REPORT_SYNTAX_ERRORS) {
return;
}
String sourceName = recognizer.getInputStream().getSourceName();
if (!sourceName.isEmpty()) {
sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine);
}
System.err.println(sourceName+"line "+line+":"+charPositionInLine+" "+msg);
}
}
private static class SummarizingDiagnosticErrorListener extends DiagnosticErrorListener {
@Override
public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet ambigAlts, ATNConfigSet configs) {
if (!REPORT_AMBIGUITIES) {
return;
}
super.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, ambigAlts, configs);
}
@Override
public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) {
if (!REPORT_FULL_CONTEXT) {
return;
}
super.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, configs);
}
@Override
public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, ATNConfigSet configs) {
if (!REPORT_CONTEXT_SENSITIVITY) {
return;
}
super.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, configs);
}
}
protected static final class FilenameFilters {
public static final FilenameFilter ALL_FILES = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return true;
}
};
public static FilenameFilter extension(String extension) {
return extension(extension, true);
}
public static FilenameFilter extension(String extension, boolean caseSensitive) {
return new FileExtensionFilenameFilter(extension, caseSensitive);
}
public static FilenameFilter name(String filename) {
return name(filename, true);
}
public static FilenameFilter name(String filename, boolean caseSensitive) {
return new FileNameFilenameFilter(filename, caseSensitive);
}
public static FilenameFilter all(FilenameFilter... filters) {
return new AllFilenameFilter(filters);
}
public static FilenameFilter any(FilenameFilter... filters) {
return new AnyFilenameFilter(filters);
}
public static FilenameFilter none(FilenameFilter... filters) {
return not(any(filters));
}
public static FilenameFilter not(FilenameFilter filter) {
return new NotFilenameFilter(filter);
}
private FilenameFilters() {
}
protected static class FileExtensionFilenameFilter implements FilenameFilter {
private final String extension;
private final boolean caseSensitive;
public FileExtensionFilenameFilter(String extension, boolean caseSensitive) {
if (!extension.startsWith(".")) {
extension = '.' + extension;
}
this.extension = extension;
this.caseSensitive = caseSensitive;
}
@Override
public boolean accept(File dir, String name) {
if (caseSensitive) {
return name.endsWith(extension);
} else {
return name.toLowerCase().endsWith(extension);
}
}
}
protected static class FileNameFilenameFilter implements FilenameFilter {
private final String filename;
private final boolean caseSensitive;
public FileNameFilenameFilter(String filename, boolean caseSensitive) {
this.filename = filename;
this.caseSensitive = caseSensitive;
}
@Override
public boolean accept(File dir, String name) {
if (caseSensitive) {
return name.equals(filename);
} else {
return name.toLowerCase().equals(filename);
}
}
}
protected static class AllFilenameFilter implements FilenameFilter {
private final FilenameFilter[] filters;
public AllFilenameFilter(FilenameFilter[] filters) {
this.filters = filters;
}
@Override
public boolean accept(File dir, String name) {
for (FilenameFilter filter : filters) {
if (!filter.accept(dir, name)) {
return false;
}
}
return true;
}
}
protected static class AnyFilenameFilter implements FilenameFilter {
private final FilenameFilter[] filters;
public AnyFilenameFilter(FilenameFilter[] filters) {
this.filters = filters;
}
@Override
public boolean accept(File dir, String name) {
for (FilenameFilter filter : filters) {
if (filter.accept(dir, name)) {
return true;
}
}
return false;
}
}
protected static class NotFilenameFilter implements FilenameFilter {
private final FilenameFilter filter;
public NotFilenameFilter(FilenameFilter filter) {
this.filter = filter;
}
@Override
public boolean accept(File dir, String name) {
return !filter.accept(dir, name);
}
}
}
protected static class NumberedThread extends Thread {
private final int threadNumber;
public NumberedThread(Runnable target, int threadNumber) {
super(target);
this.threadNumber = threadNumber;
}
public final int getThreadNumber() {
return threadNumber;
}
}
protected static class NumberedThreadFactory implements ThreadFactory {
private final AtomicInteger nextThread = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
int threadNumber = nextThread.getAndIncrement();
assert threadNumber < NUMBER_OF_THREADS;
return new NumberedThread(r, threadNumber);
}
}
protected static class ChecksumParseTreeListener implements ParseTreeListener {
private static final int VISIT_TERMINAL = 1;
private static final int VISIT_ERROR_NODE = 2;
private static final int ENTER_RULE = 3;
private static final int EXIT_RULE = 4;
private final Checksum checksum;
public ChecksumParseTreeListener(Checksum checksum) {
this.checksum = checksum;
}
@Override
public void visitTerminal(TerminalNode node) {
checksum.update(VISIT_TERMINAL);
updateChecksum(checksum, node.getSymbol());
}
@Override
public void visitErrorNode(ErrorNode node) {
checksum.update(VISIT_ERROR_NODE);
updateChecksum(checksum, node.getSymbol());
}
@Override
public void enterEveryRule(ParserRuleContext ctx) {
checksum.update(ENTER_RULE);
updateChecksum(checksum, ctx.getRuleIndex());
updateChecksum(checksum, ctx.getStart());
}
@Override
public void exitEveryRule(ParserRuleContext ctx) {
checksum.update(EXIT_RULE);
updateChecksum(checksum, ctx.getRuleIndex());
updateChecksum(checksum, ctx.getStop());
}
}
protected static final class InputDescriptor {
private final String source;
private Reference<CharStream> inputStream;
public InputDescriptor(@NotNull String source) {
this.source = source;
if (PRELOAD_SOURCES) {
getInputStream();
}
}
@NotNull
public CharStream getInputStream() {
CharStream stream = inputStream != null ? inputStream.get() : null;
if (stream == null) {
try {
stream = new ANTLRFileStream(source, ENCODING);
} catch (IOException ex) {
Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);
stream = new ANTLRInputStream("");
}
if (PRELOAD_SOURCES) {
inputStream = new StrongReference<CharStream>(stream);
} else {
inputStream = new SoftReference<CharStream>(stream);
}
}
return stream;
}
}
public static class StrongReference<T> extends WeakReference<T> {
public final T referent;
public StrongReference(T referent) {
super(referent);
this.referent = referent;
}
@Override
public T get() {
return referent;
}
}
}
| Gather additional parsing statistics from each file
| tool/test/org/antlr/v4/test/TestPerformance.java | Gather additional parsing statistics from each file | <ide><path>ool/test/org/antlr/v4/test/TestPerformance.java
<ide> int inputSize = 0;
<ide> int inputCount = 0;
<ide>
<del> Collection<Future<Integer>> results = new ArrayList<Future<Integer>>();
<add> Collection<Future<FileParseResult>> results = new ArrayList<Future<FileParseResult>>();
<ide> ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS, new NumberedThreadFactory());
<ide> for (InputDescriptor inputDescriptor : sources) {
<ide> if (inputCount >= MAX_FILES_PER_PARSE_ITERATION) {
<ide> input.seek(0);
<ide> inputSize += input.size();
<ide> inputCount++;
<del> Future<Integer> futureChecksum = executorService.submit(new Callable<Integer>() {
<add> Future<FileParseResult> futureChecksum = executorService.submit(new Callable<FileParseResult>() {
<ide> @Override
<del> public Integer call() {
<add> public FileParseResult call() {
<ide> // this incurred a great deal of overhead and was causing significant variations in performance results.
<ide> //System.out.format("Parsing file %s\n", input.getSourceName());
<ide> try {
<ide> t.printStackTrace(System.err);
<ide> }
<ide>
<del> return -1;
<add> return null;
<ide> }
<ide> });
<ide>
<ide> }
<ide>
<ide> Checksum checksum = new CRC32();
<del> for (Future<Integer> future : results) {
<del> int value = 0;
<add> for (Future<FileParseResult> future : results) {
<add> int fileChecksum = 0;
<ide> try {
<del> value = future.get();
<add> FileParseResult fileResult = future.get();
<add> fileChecksum = fileResult.checksum;
<ide> } catch (ExecutionException ex) {
<ide> Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);
<ide> }
<ide>
<ide> if (COMPUTE_CHECKSUM) {
<del> updateChecksum(checksum, value);
<add> updateChecksum(checksum, fileChecksum);
<ide> }
<ide> }
<ide>
<ide>
<ide> return new ParserFactory() {
<ide> @Override
<del> public int parseFile(CharStream input, int thread) {
<add> public FileParseResult parseFile(CharStream input, int thread) {
<ide> final Checksum checksum = new CRC32();
<ide>
<add> final long startTime = System.nanoTime();
<ide> assert thread >= 0 && thread < NUMBER_OF_THREADS;
<ide>
<ide> try {
<ide> }
<ide>
<ide> if (!RUN_PARSER) {
<del> return (int)checksum.getValue();
<add> return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), null, tokens.size(), startTime, lexer, null);
<ide> }
<ide>
<ide> Parser parser = sharedParsers[thread];
<ide> if (BUILD_PARSE_TREES && BLANK_LISTENER) {
<ide> ParseTreeWalker.DEFAULT.walk(listener, (ParseTree)parseResult);
<ide> }
<add>
<add> return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), (ParseTree)parseResult, tokens.size(), startTime, lexer, parser);
<ide> } catch (Exception e) {
<ide> if (!REPORT_SYNTAX_ERRORS && e instanceof ParseCancellationException) {
<del> return (int)checksum.getValue();
<add> return new FileParseResult("unknown", (int)checksum.getValue(), null, 0, startTime, null, null);
<ide> }
<ide>
<ide> e.printStackTrace(System.out);
<ide> throw new IllegalStateException(e);
<ide> }
<del>
<del> return (int)checksum.getValue();
<ide> }
<ide> };
<ide> } catch (Exception e) {
<ide> }
<ide>
<ide> protected interface ParserFactory {
<del> int parseFile(CharStream input, int thread);
<add> FileParseResult parseFile(CharStream input, int thread);
<ide> }
<add>
<add> protected static class FileParseResult {
<add> public final String sourceName;
<add> public final int checksum;
<add> public final ParseTree parseTree;
<add> public final int tokenCount;
<add> public final long startTime;
<add> public final long endTime;
<add>
<add> public final int lexerDFASize;
<add> public final int parserDFASize;
<add>
<add> public FileParseResult(String sourceName, int checksum, @Nullable ParseTree parseTree, int tokenCount, long startTime, Lexer lexer, Parser parser) {
<add> this.sourceName = sourceName;
<add> this.checksum = checksum;
<add> this.parseTree = parseTree;
<add> this.tokenCount = tokenCount;
<add> this.startTime = startTime;
<add> this.endTime = System.nanoTime();
<add>
<add> if (lexer != null) {
<add> LexerATNSimulator interpreter = lexer.getInterpreter();
<add>
<add> int dfaSize = 0;
<add> for (DFA dfa : interpreter.decisionToDFA) {
<add> if (dfa != null && dfa.states != null) {
<add> dfaSize += dfa.states.size();
<add> }
<add> }
<add>
<add> lexerDFASize = dfaSize;
<add> } else {
<add> lexerDFASize = 0;
<add> }
<add>
<add> if (parser != null) {
<add> ParserATNSimulator interpreter = parser.getInterpreter();
<add>
<add> int dfaSize = 0;
<add> for (DFA dfa : interpreter.decisionToDFA) {
<add> if (dfa != null && dfa.states != null) {
<add> dfaSize += dfa.states.size();
<add> }
<add> }
<add>
<add> parserDFASize = dfaSize;
<add> } else {
<add> parserDFASize = 0;
<add> }
<add> }
<add> }
<ide>
<ide> private static class DescriptiveErrorListener extends BaseErrorListener {
<ide> public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener(); |
|
Java | apache-2.0 | bdf2db79a34e4d432856e0e658f3dbe30099a5f3 | 0 | synthetichealth/synthea,synthetichealth/synthea,synthetichealth/synthea | package org.mitre.synthea.export;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.dstu2.composite.AddressDt;
import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.CodingDt;
import ca.uhn.fhir.model.dstu2.composite.ContactPointDt;
import ca.uhn.fhir.model.dstu2.composite.HumanNameDt;
import ca.uhn.fhir.model.dstu2.composite.MoneyDt;
import ca.uhn.fhir.model.dstu2.composite.NarrativeDt;
import ca.uhn.fhir.model.dstu2.composite.PeriodDt;
import ca.uhn.fhir.model.dstu2.composite.QuantityDt;
import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.composite.SimpleQuantityDt;
import ca.uhn.fhir.model.dstu2.composite.TimingDt;
import ca.uhn.fhir.model.dstu2.composite.TimingDt.Repeat;
import ca.uhn.fhir.model.dstu2.resource.AllergyIntolerance;
import ca.uhn.fhir.model.dstu2.resource.BaseResource;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry;
import ca.uhn.fhir.model.dstu2.resource.Bundle.EntryRequest;
import ca.uhn.fhir.model.dstu2.resource.CarePlan.Activity;
import ca.uhn.fhir.model.dstu2.resource.CarePlan.ActivityDetail;
import ca.uhn.fhir.model.dstu2.resource.Condition;
import ca.uhn.fhir.model.dstu2.resource.DiagnosticReport;
import ca.uhn.fhir.model.dstu2.resource.Encounter.Hospitalization;
import ca.uhn.fhir.model.dstu2.resource.ImagingStudy.Series;
import ca.uhn.fhir.model.dstu2.resource.ImagingStudy.SeriesInstance;
import ca.uhn.fhir.model.dstu2.resource.Immunization;
import ca.uhn.fhir.model.dstu2.resource.MedicationOrder;
import ca.uhn.fhir.model.dstu2.resource.MedicationOrder.DosageInstruction;
import ca.uhn.fhir.model.dstu2.resource.Observation.Component;
import ca.uhn.fhir.model.dstu2.resource.Organization;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.dstu2.resource.Patient.Communication;
import ca.uhn.fhir.model.dstu2.valueset.AdministrativeGenderEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceCategoryEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceCriticalityEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.BundleTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.CarePlanActivityStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.CarePlanStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ClaimTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.ConditionCategoryCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.ConditionClinicalStatusCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.ConditionVerificationStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ContactPointSystemEnum;
import ca.uhn.fhir.model.dstu2.valueset.ContactPointUseEnum;
import ca.uhn.fhir.model.dstu2.valueset.DiagnosticReportStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.EncounterClassEnum;
import ca.uhn.fhir.model.dstu2.valueset.EncounterStateEnum;
import ca.uhn.fhir.model.dstu2.valueset.GoalStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.HTTPVerbEnum;
import ca.uhn.fhir.model.dstu2.valueset.IdentifierTypeCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.InstanceAvailabilityEnum;
import ca.uhn.fhir.model.dstu2.valueset.MaritalStatusCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.MedicationOrderStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.NameUseEnum;
import ca.uhn.fhir.model.dstu2.valueset.NarrativeStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ObservationStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ProcedureStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.UnitsOfTimeEnum;
import ca.uhn.fhir.model.dstu2.valueset.UseEnum;
import ca.uhn.fhir.model.primitive.BooleanDt;
import ca.uhn.fhir.model.primitive.CodeDt;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.DateTimeDt;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.IntegerDt;
import ca.uhn.fhir.model.primitive.OidDt;
import ca.uhn.fhir.model.primitive.PositiveIntDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.UnsignedIntDt;
import ca.uhn.fhir.model.primitive.XhtmlDt;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.sis.geometry.DirectPosition2D;
import org.mitre.synthea.helpers.Config;
import org.mitre.synthea.helpers.Utilities;
import org.mitre.synthea.world.agents.Person;
import org.mitre.synthea.world.agents.Provider;
import org.mitre.synthea.world.concepts.Costs;
import org.mitre.synthea.world.concepts.HealthRecord;
import org.mitre.synthea.world.concepts.HealthRecord.CarePlan;
import org.mitre.synthea.world.concepts.HealthRecord.Claim;
import org.mitre.synthea.world.concepts.HealthRecord.Code;
import org.mitre.synthea.world.concepts.HealthRecord.Encounter;
import org.mitre.synthea.world.concepts.HealthRecord.ImagingStudy;
import org.mitre.synthea.world.concepts.HealthRecord.Medication;
import org.mitre.synthea.world.concepts.HealthRecord.Observation;
import org.mitre.synthea.world.concepts.HealthRecord.Procedure;
import org.mitre.synthea.world.concepts.HealthRecord.Report;
public class FhirDstu2 {
// HAPI FHIR warns that the context creation is expensive, and should be performed
// per-application, not per-record
private static final FhirContext FHIR_CTX = FhirContext.forDstu2();
private static final String SNOMED_URI = "http://snomed.info/sct";
private static final String LOINC_URI = "http://loinc.org";
private static final String RXNORM_URI = "http://www.nlm.nih.gov/research/umls/rxnorm";
private static final String CVX_URI = "http://hl7.org/fhir/sid/cvx";
private static final String DISCHARGE_URI = "http://www.nubc.org/patient-discharge";
private static final String SYNTHEA_EXT = "http://synthetichealth.github.io/synthea/";
private static final String DICOM_DCM_URI = "http://dicom.nema.org/resources/ontology/DCM";
@SuppressWarnings("rawtypes")
private static final Map raceEthnicityCodes = loadRaceEthnicityCodes();
@SuppressWarnings("rawtypes")
private static final Map languageLookup = loadLanguageLookup();
protected static boolean TRANSACTION_BUNDLE =
Boolean.parseBoolean(Config.get("exporter.fhir.transaction_bundle"));
private static final String COUNTRY_CODE = Config.get("generate.geography.country_code");
@SuppressWarnings("rawtypes")
private static Map loadRaceEthnicityCodes() {
String filename = "race_ethnicity_codes.json";
try {
String json = Utilities.readResource(filename);
Gson g = new Gson();
return g.fromJson(json, HashMap.class);
} catch (Exception e) {
System.err.println("ERROR: unable to load json: " + filename);
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings("rawtypes")
private static Map loadLanguageLookup() {
String filename = "language_lookup.json";
try {
String json = Utilities.readResource(filename);
Gson g = new Gson();
return g.fromJson(json, HashMap.class);
} catch (Exception e) {
System.err.println("ERROR: unable to load json: " + filename);
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
/**
* Convert the given Person into a JSON String, containing a FHIR Bundle of the Person and the
* associated entries from their health record.
*
* @param person
* Person to generate the FHIR JSON for
* @param stopTime
* Time the simulation ended
* @return String containing a JSON representation of a FHIR Bundle containing the Person's health
* record
*/
public static String convertToFHIR(Person person, long stopTime) {
Bundle bundle = new Bundle();
if (TRANSACTION_BUNDLE) {
bundle.setType(BundleTypeEnum.TRANSACTION);
} else {
bundle.setType(BundleTypeEnum.COLLECTION);
}
Entry personEntry = basicInfo(person, bundle, stopTime);
for (Encounter encounter : person.record.encounters) {
Entry encounterEntry = encounter(person, personEntry, bundle, encounter);
for (HealthRecord.Entry condition : encounter.conditions) {
condition(personEntry, bundle, encounterEntry, condition);
}
for (HealthRecord.Entry allergy : encounter.allergies) {
allergy(personEntry, bundle, encounterEntry, allergy);
}
for (Observation observation : encounter.observations) {
observation(personEntry, bundle, encounterEntry, observation);
}
for (Procedure procedure : encounter.procedures) {
procedure(personEntry, bundle, encounterEntry, procedure);
}
for (Medication medication : encounter.medications) {
medication(personEntry, bundle, encounterEntry, medication);
}
for (HealthRecord.Entry immunization : encounter.immunizations) {
immunization(personEntry, bundle, encounterEntry, immunization);
}
for (Report report : encounter.reports) {
report(personEntry, bundle, encounterEntry, report);
}
for (CarePlan careplan : encounter.careplans) {
careplan(personEntry, bundle, encounterEntry, careplan);
}
for (ImagingStudy imagingStudy : encounter.imagingStudies) {
imagingStudy(personEntry, bundle, encounterEntry, imagingStudy);
}
// one claim per encounter
encounterClaim(personEntry, bundle, encounterEntry, encounter.claim);
}
String bundleJson = FHIR_CTX.newJsonParser().setPrettyPrint(true)
.encodeResourceToString(bundle);
return bundleJson;
}
/**
* Map the given Person to a FHIR Patient resource, and add it to the given Bundle.
*
* @param person
* The Person
* @param bundle
* The Bundle to add to
* @param stopTime
* Time the simulation ended
* @return The created Entry
*/
@SuppressWarnings("rawtypes")
private static Entry basicInfo(Person person, Bundle bundle, long stopTime) {
Patient patientResource = new Patient();
patientResource.addIdentifier().setSystem("https://github.com/synthetichealth/synthea")
.setValue((String) person.attributes.get(Person.ID));
patientResource.addIdentifier()
.setType(IdentifierTypeCodesEnum.MR)
.setSystem("http://hospital.smarthealthit.org")
.setValue((String) person.attributes.get(Person.ID));
patientResource.addIdentifier()
.setType(IdentifierTypeCodesEnum.SOCIAL_BENEFICIARY_IDENTIFIER)
.setSystem("http://hl7.org/fhir/sid/us-ssn")
.setValue((String) person.attributes.get(Person.IDENTIFIER_SSN));
if (person.attributes.get(Person.IDENTIFIER_DRIVERS) != null) {
patientResource.addIdentifier()
.setType(IdentifierTypeCodesEnum.DL)
.setSystem("urn:oid:2.16.840.1.113883.4.3.25")
.setValue((String) person.attributes.get(Person.IDENTIFIER_DRIVERS));
}
ExtensionDt raceExtension = new ExtensionDt();
raceExtension.setUrl("http://hl7.org/fhir/StructureDefinition/us-core-race");
String race = (String) person.attributes.get(Person.RACE);
ExtensionDt ethnicityExtension = new ExtensionDt();
ethnicityExtension.setUrl("http://hl7.org/fhir/StructureDefinition/us-core-ethnicity");
String ethnicity = (String) person.attributes.get(Person.ETHNICITY);
if (race.equals("hispanic")) {
race = "other";
ethnicity = "hispanic";
} else {
ethnicity = "nonhispanic";
}
String raceDisplay;
switch (race) {
case "white":
raceDisplay = "White";
break;
case "black":
raceDisplay = "Black or African American";
break;
case "asian":
raceDisplay = "Asian";
break;
case "native":
raceDisplay = "American Indian or Alaska Native";
break;
default: // Hispanic or Other (Put Hawaiian and Pacific Islander here for now)
raceDisplay = "Other";
break;
}
String ethnicityDisplay;
if (ethnicity.equals("hispanic")) {
ethnicityDisplay = "Hispanic or Latino";
} else {
ethnicityDisplay = "Not Hispanic or Latino";
}
Code raceCode = new Code(
"http://hl7.org/fhir/v3/Race",
(String) raceEthnicityCodes.get(race),
raceDisplay);
Code ethnicityCode = new Code(
"http://hl7.org/fhir/v3/Ethnicity",
(String) raceEthnicityCodes.get(ethnicity),
ethnicityDisplay);
raceExtension.setValue(mapCodeToCodeableConcept(raceCode, "http://hl7.org/fhir/v3/Race"));
ethnicityExtension.setValue(mapCodeToCodeableConcept(ethnicityCode, "http://hl7.org/fhir/v3/Ethnicity"));
patientResource.addUndeclaredExtension(raceExtension);
patientResource.addUndeclaredExtension(ethnicityExtension);
String firstLanguage = (String) person.attributes.get(Person.FIRST_LANGUAGE);
Map languageMap = (Map) languageLookup.get(firstLanguage);
Code languageCode = new Code((String) languageMap.get("system"),
(String) languageMap.get("code"), (String) languageMap.get("display"));
List<Communication> communication = new ArrayList<Communication>();
Communication language = new Communication();
language
.setLanguage(mapCodeToCodeableConcept(languageCode, (String) languageMap.get("system")));
communication.add(language);
patientResource.setCommunication(communication);
HumanNameDt name = patientResource.addName();
name.setUse(NameUseEnum.OFFICIAL);
name.addGiven((String) person.attributes.get(Person.FIRST_NAME));
List<StringDt> officialFamilyNames = new ArrayList<StringDt>();
officialFamilyNames.add(new StringDt((String) person.attributes.get(Person.LAST_NAME)));
name.setFamily(officialFamilyNames);
if (person.attributes.get(Person.NAME_PREFIX) != null) {
name.addPrefix((String) person.attributes.get(Person.NAME_PREFIX));
}
if (person.attributes.get(Person.NAME_SUFFIX) != null) {
name.addSuffix((String) person.attributes.get(Person.NAME_SUFFIX));
}
if (person.attributes.get(Person.MAIDEN_NAME) != null) {
HumanNameDt maidenName = patientResource.addName();
maidenName.setUse(NameUseEnum.MAIDEN);
maidenName.addGiven((String) person.attributes.get(Person.FIRST_NAME));
List<StringDt> maidenFamilyNames = new ArrayList<StringDt>();
maidenFamilyNames.add(new StringDt((String) person.attributes.get(Person.MAIDEN_NAME)));
maidenName.setFamily(maidenFamilyNames);
if (person.attributes.get(Person.NAME_PREFIX) != null) {
maidenName.addPrefix((String) person.attributes.get(Person.NAME_PREFIX));
}
if (person.attributes.get(Person.NAME_SUFFIX) != null) {
maidenName.addSuffix((String) person.attributes.get(Person.NAME_SUFFIX));
}
}
ExtensionDt mothersMaidenNameExtension = new ExtensionDt();
mothersMaidenNameExtension
.setUrl("http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName");
String mothersMaidenName = (String) person.attributes.get(Person.NAME_MOTHER);
mothersMaidenNameExtension.setValue(new StringDt(mothersMaidenName));
patientResource.addUndeclaredExtension(mothersMaidenNameExtension);
long birthdate = (long) person.attributes.get(Person.BIRTHDATE);
patientResource.setBirthDate(new DateDt(new Date(birthdate)));
ExtensionDt birthSexExtension = new ExtensionDt();
birthSexExtension.setUrl("http://hl7.org/fhir/us/core/StructureDefinition/us-core-birthsex");
if (person.attributes.get(Person.GENDER).equals("M")) {
patientResource.setGender(AdministrativeGenderEnum.MALE);
birthSexExtension.setValue(new CodeDt("M"));
} else if (person.attributes.get(Person.GENDER).equals("F")) {
patientResource.setGender(AdministrativeGenderEnum.FEMALE);
birthSexExtension.setValue(new CodeDt("F"));
}
patientResource.addUndeclaredExtension(birthSexExtension);
String state = (String) person.attributes.get(Person.STATE);
AddressDt addrResource = patientResource.addAddress();
addrResource.addLine((String) person.attributes.get(Person.ADDRESS))
.setCity((String) person.attributes.get(Person.CITY))
.setPostalCode((String) person.attributes.get(Person.ZIP))
.setState(state);
if (COUNTRY_CODE != null) {
addrResource.setCountry(COUNTRY_CODE);
}
DirectPosition2D coord = person.getLatLon();
if (coord != null) {
ExtensionDt geolocationExtension = new ExtensionDt();
geolocationExtension.setUrl("http://hl7.org/fhir/StructureDefinition/geolocation");
ExtensionDt latitudeExtension = new ExtensionDt();
ExtensionDt longitudeExtension = new ExtensionDt();
latitudeExtension.setUrl("latitude");
longitudeExtension.setUrl("longitude");
latitudeExtension.setValue(new DecimalDt(coord.getX()));
longitudeExtension.setValue(new DecimalDt(coord.getY()));
geolocationExtension.addUndeclaredExtension(latitudeExtension);
geolocationExtension.addUndeclaredExtension(longitudeExtension);
addrResource.addUndeclaredExtension(geolocationExtension);
}
AddressDt birthplace = new AddressDt();
birthplace.setCity((String) person.attributes.get(Person.BIRTHPLACE)).setState(state);
if (COUNTRY_CODE != null) {
birthplace.setCountry(COUNTRY_CODE);
}
ExtensionDt birthplaceExtension = new ExtensionDt();
birthplaceExtension.setUrl("http://hl7.org/fhir/StructureDefinition/birthPlace");
birthplaceExtension.setValue(birthplace);
patientResource.addUndeclaredExtension(birthplaceExtension);
if (person.attributes.get(Person.MULTIPLE_BIRTH_STATUS) != null) {
patientResource.setMultipleBirth(
new IntegerDt((int) person.attributes.get(Person.MULTIPLE_BIRTH_STATUS)));
} else {
patientResource.setMultipleBirth(new BooleanDt(false));
}
patientResource.addTelecom().setSystem(ContactPointSystemEnum.PHONE)
.setUse(ContactPointUseEnum.HOME).setValue((String) person.attributes.get(Person.TELECOM));
String maritalStatus = ((String) person.attributes.get(Person.MARITAL_STATUS));
if (maritalStatus != null) {
patientResource.setMaritalStatus(MaritalStatusCodesEnum.forCode(maritalStatus.toUpperCase()));
} else {
patientResource.setMaritalStatus(MaritalStatusCodesEnum.S);
}
if (!person.alive(stopTime)) {
patientResource.setDeceased(convertFhirDateTime(person.record.death, true));
}
String generatedBySynthea = "Generated by <a href=\"https://github.com/synthetichealth/synthea\">Synthea</a>."
+ "Version identifier: " + Utilities.SYNTHEA_VERSION + " . "
+ " Person seed: " + person.seed
+ " Population seed: " + person.populationSeed;
patientResource.setText(new NarrativeDt(
new XhtmlDt(generatedBySynthea), NarrativeStatusEnum.GENERATED));
// DALY and QALY values
// we only write the last(current) one to the patient record
Double dalyValue = (Double) person.attributes.get("most-recent-daly");
Double qalyValue = (Double) person.attributes.get("most-recent-qaly");
if (dalyValue != null) {
ExtensionDt dalyExtension = new ExtensionDt();
dalyExtension.setUrl(SYNTHEA_EXT + "disability-adjusted-life-years");
DecimalDt daly = new DecimalDt(dalyValue);
dalyExtension.setValue(daly);
patientResource.addUndeclaredExtension(dalyExtension);
ExtensionDt qalyExtension = new ExtensionDt();
qalyExtension.setUrl(SYNTHEA_EXT + "quality-adjusted-life-years");
DecimalDt qaly = new DecimalDt(qalyValue);
qalyExtension.setValue(qaly);
patientResource.addUndeclaredExtension(qalyExtension);
}
return newEntry(bundle, patientResource);
}
/**
* Map the given Encounter into a FHIR Encounter resource, and add it to the given Bundle.
*
* @param person
* Patient at the encounter.
* @param personEntry
* Entry for the Person
* @param bundle
* The Bundle to add to
* @param encounter
* The current Encounter
* @return The added Entry
*/
private static Entry encounter(Person person, Entry personEntry,
Bundle bundle, Encounter encounter) {
ca.uhn.fhir.model.dstu2.resource.Encounter encounterResource =
new ca.uhn.fhir.model.dstu2.resource.Encounter();
encounterResource.setStatus(EncounterStateEnum.FINISHED);
if (encounter.codes.isEmpty()) {
// wellness encounter
encounterResource.addType().addCoding().setCode("185349003")
.setDisplay("Encounter for check up").setSystem(SNOMED_URI);
} else {
Code code = encounter.codes.get(0);
encounterResource.addType(mapCodeToCodeableConcept(code, SNOMED_URI));
}
encounterResource.setClassElement(EncounterClassEnum.forCode(encounter.type));
encounterResource.setPeriod(new PeriodDt()
.setStart(new DateTimeDt(new Date(encounter.start)))
.setEnd(new DateTimeDt(new Date(encounter.stop))));
if (encounter.reason != null) {
encounterResource.addReason().addCoding().setCode(encounter.reason.code)
.setDisplay(encounter.reason.display).setSystem(SNOMED_URI);
}
if (encounter.provider != null) {
String providerFullUrl = findProviderUrl(encounter.provider, bundle);
if (providerFullUrl != null) {
encounterResource.setServiceProvider(new ResourceReferenceDt(providerFullUrl));
} else {
Entry providerOrganization = provider(bundle, encounter.provider);
encounterResource
.setServiceProvider(new ResourceReferenceDt(providerOrganization.getFullUrl()));
}
} else { // no associated provider, patient goes to ambulatory provider
Provider provider = person.getAmbulatoryProvider(encounter.start);
String providerFullUrl = findProviderUrl(provider, bundle);
if (providerFullUrl != null) {
encounterResource.setServiceProvider(new ResourceReferenceDt(providerFullUrl));
} else {
Entry providerOrganization = provider(bundle, provider);
encounterResource
.setServiceProvider(new ResourceReferenceDt(providerOrganization.getFullUrl()));
}
}
if (encounter.discharge != null) {
Hospitalization hospitalization = new Hospitalization();
Code dischargeDisposition = new Code(DISCHARGE_URI, encounter.discharge.code,
encounter.discharge.display);
hospitalization
.setDischargeDisposition(mapCodeToCodeableConcept(dischargeDisposition, DISCHARGE_URI));
encounterResource.setHospitalization(hospitalization);
}
return newEntry(bundle, encounterResource);
}
/**
* Find the provider entry in this bundle, and return the associated "fullUrl" attribute.
* @param provider A given provider.
* @param bundle The current bundle being generated.
* @return Provider.fullUrl if found, otherwise null.
*/
private static String findProviderUrl(Provider provider, Bundle bundle) {
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Organization")) {
Organization org = (Organization) entry.getResource();
if (org.getIdentifierFirstRep().getValue().equals(provider.getResourceID())) {
return entry.getFullUrl();
}
}
}
return null;
}
/**
* Create an entry for the given Claim, which references a Medication.
*
* @param personEntry
* Entry for the person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter
* @param claim
* the Claim object
* @param medicationEntry
* The Entry for the Medication object, previously created
* @return the added Entry
*/
private static Entry medicationClaim(Entry personEntry, Bundle bundle, Entry encounterEntry,
Claim claim, Entry medicationEntry) {
ca.uhn.fhir.model.dstu2.resource.Claim claimResource =
new ca.uhn.fhir.model.dstu2.resource.Claim();
ca.uhn.fhir.model.dstu2.resource.Encounter encounterResource =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry
.getResource();
// assume institutional claim
claimResource.setType(ClaimTypeEnum.INSTITUTIONAL); // TODO review claim type
claimResource.setUse(UseEnum.COMPLETE);
claimResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
claimResource.setOrganization(encounterResource.getServiceProvider());
// add prescription.
claimResource.setPrescription(new ResourceReferenceDt(medicationEntry.getFullUrl()));
return newEntry(bundle, claimResource);
}
/**
* Create an entry for the given Claim, associated to an Encounter.
*
* @param personEntry
* Entry for the person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter
* @param claim
* the Claim object
* @return the added Entry
*/
private static Entry encounterClaim(Entry personEntry, Bundle bundle, Entry encounterEntry,
Claim claim) {
ca.uhn.fhir.model.dstu2.resource.Claim claimResource =
new ca.uhn.fhir.model.dstu2.resource.Claim();
ca.uhn.fhir.model.dstu2.resource.Encounter encounterResource =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry
.getResource();
// assume institutional claim
claimResource.setType(ClaimTypeEnum.INSTITUTIONAL);
claimResource.setUse(UseEnum.COMPLETE);
claimResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
claimResource.setOrganization(encounterResource.getServiceProvider());
// Add data for the encounter
ca.uhn.fhir.model.dstu2.resource.Claim.Item encounterItem =
new ca.uhn.fhir.model.dstu2.resource.Claim.Item();
encounterItem.setSequence(new PositiveIntDt(1));
// assume item type is clinical service invoice
CodingDt itemType = new CodingDt();
itemType.setSystem("http://hl7.org/fhir/v3/ActCode")
.setCode("CSINV")
.setDisplay("clinical service invoice");
encounterItem.setType(itemType);
CodingDt itemService = new CodingDt();
ca.uhn.fhir.model.dstu2.resource.Encounter encounter =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry.getResource();
itemService.setSystem(encounter.getTypeFirstRep().getCodingFirstRep().getSystem())
.setCode(encounter.getTypeFirstRep().getCodingFirstRep().getCode())
.setDisplay(encounter.getTypeFirstRep().getCodingFirstRep().getDisplay());
encounterItem.setService(itemService);
claimResource.addItem(encounterItem);
int itemSequence = 2;
int conditionSequence = 1;
for (HealthRecord.Entry item : claim.items) {
if (Costs.hasCost(item)) {
// update claimItems list
ca.uhn.fhir.model.dstu2.resource.Claim.Item procedureItem =
new ca.uhn.fhir.model.dstu2.resource.Claim.Item();
procedureItem.setSequence(new PositiveIntDt(itemSequence));
// calculate the cost of the procedure
MoneyDt moneyResource = new MoneyDt();
moneyResource.setCode("USD");
moneyResource.setSystem("urn:iso:std:iso:4217");
moneyResource.setValue(item.cost());
procedureItem.setNet(moneyResource);
// assume item type is clinical service invoice
itemType = new CodingDt();
itemType.setSystem("http://hl7.org/fhir/v3/ActCode")
.setCode("CSINV")
.setDisplay("clinical service invoice");
procedureItem.setType(itemType);
// item service should match the entry code
itemService = new CodingDt();
itemService.setSystem(item.codes.get(0).system)
.setCode(item.codes.get(0).code)
.setDisplay(item.codes.get(0).display);
procedureItem.setService(itemService);
claimResource.addItem(procedureItem);
} else {
// assume it's a Condition, we don't have a Condition class specifically
// add diagnosisComponent to claim
ca.uhn.fhir.model.dstu2.resource.Claim.Diagnosis diagnosisComponent =
new ca.uhn.fhir.model.dstu2.resource.Claim.Diagnosis();
diagnosisComponent.setSequence(new PositiveIntDt(conditionSequence));
if (item.codes.size() > 0) {
// use first code
diagnosisComponent.setDiagnosis(
new CodingDt(item.codes.get(0).system, item.codes.get(0).code));
}
claimResource.addDiagnosis(diagnosisComponent);
conditionSequence++;
}
itemSequence++;
}
return newEntry(bundle, claimResource);
}
/**
* Map the Condition into a FHIR Condition resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param condition
* The Condition
* @return The added Entry
*/
private static Entry condition(Entry personEntry, Bundle bundle, Entry encounterEntry,
HealthRecord.Entry condition) {
Condition conditionResource = new Condition();
conditionResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
conditionResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Code code = condition.codes.get(0);
conditionResource.setCode(mapCodeToCodeableConcept(code, SNOMED_URI));
conditionResource.setCategory(ConditionCategoryCodesEnum.DIAGNOSIS);
conditionResource.setVerificationStatus(ConditionVerificationStatusEnum.CONFIRMED);
conditionResource.setClinicalStatus(ConditionClinicalStatusCodesEnum.ACTIVE);
conditionResource.setOnset(convertFhirDateTime(condition.start, true));
conditionResource.setDateRecorded(new DateDt(new Date(condition.start)));
if (condition.stop != 0) {
conditionResource.setAbatement(convertFhirDateTime(condition.stop, true));
conditionResource.setClinicalStatus(ConditionClinicalStatusCodesEnum.RESOLVED);
}
Entry conditionEntry = newEntry(bundle, conditionResource);
condition.fullUrl = conditionEntry.getFullUrl();
return conditionEntry;
}
/**
* Map the Condition into a FHIR AllergyIntolerance resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param allergy
* The Allergy Entry
* @return The added Entry
*/
private static Entry allergy(Entry personEntry, Bundle bundle,
Entry encounterEntry, HealthRecord.Entry allergy) {
AllergyIntolerance allergyResource = new AllergyIntolerance();
allergyResource.setOnset((DateTimeDt)convertFhirDateTime(allergy.start, true));
if (allergy.stop == 0) {
allergyResource.setStatus(AllergyIntoleranceStatusEnum.ACTIVE);
} else {
allergyResource.setStatus(AllergyIntoleranceStatusEnum.INACTIVE);
}
allergyResource.setType(AllergyIntoleranceTypeEnum.ALLERGY);
AllergyIntoleranceCategoryEnum category = AllergyIntoleranceCategoryEnum.FOOD;
allergyResource.setCategory(category); // TODO: allergy categories in GMF
allergyResource.setCriticality(AllergyIntoleranceCriticalityEnum.LOW_RISK);
allergyResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
Code code = allergy.codes.get(0);
allergyResource.setSubstance(mapCodeToCodeableConcept(code, SNOMED_URI));
Entry allergyEntry = newEntry(bundle, allergyResource);
allergy.fullUrl = allergyEntry.getFullUrl();
return allergyEntry;
}
/**
* Map the given Observation into a FHIR Observation resource, and add it to the given Bundle.
*
* @param personEntry
* The Person Entry
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param observation
* The Observation
* @return The added Entry
*/
private static Entry observation(Entry personEntry, Bundle bundle, Entry encounterEntry,
Observation observation) {
ca.uhn.fhir.model.dstu2.resource.Observation observationResource =
new ca.uhn.fhir.model.dstu2.resource.Observation();
observationResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
observationResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
observationResource.setStatus(ObservationStatusEnum.FINAL);
Code code = observation.codes.get(0);
observationResource.setCode(mapCodeToCodeableConcept(code, LOINC_URI));
Code category = new Code("http://hl7.org/fhir/observation-category", observation.category,
observation.category);
observationResource.setCategory(
mapCodeToCodeableConcept(category, "http://hl7.org/fhir/observation-category"));
if (observation.value != null) {
IDatatype value = mapValueToFHIRType(observation.value, observation.unit);
observationResource.setValue(value);
} else if (observation.observations != null && !observation.observations.isEmpty()) {
// multi-observation (ex blood pressure)
for (Observation subObs : observation.observations) {
Component comp = new Component();
comp.setCode(mapCodeToCodeableConcept(subObs.codes.get(0), LOINC_URI));
IDatatype value = mapValueToFHIRType(subObs.value, subObs.unit);
comp.setValue(value);
observationResource.addComponent(comp);
}
}
observationResource.setEffective(convertFhirDateTime(observation.start, true));
observationResource.setIssued(new InstantDt(new Date(observation.start)));
Entry entry = newEntry(bundle, observationResource);
observation.fullUrl = entry.getFullUrl();
return entry;
}
private static IDatatype mapValueToFHIRType(Object value, String unit) {
if (value == null) {
return null;
} else if (value instanceof Condition) {
Code conditionCode = ((HealthRecord.Entry) value).codes.get(0);
return mapCodeToCodeableConcept(conditionCode, SNOMED_URI);
} else if (value instanceof Code) {
return mapCodeToCodeableConcept((Code) value, SNOMED_URI);
} else if (value instanceof String) {
return new StringDt((String) value);
} else if (value instanceof Number) {
return new QuantityDt().setValue(((Number) value).doubleValue())
.setCode(unit).setSystem("http://unitsofmeasure.org")
.setUnit(unit);
} else {
throw new IllegalArgumentException("unexpected observation value class: "
+ value.getClass().toString() + "; " + value);
}
}
/**
* Map the given Procedure into a FHIR Procedure resource, and add it to the given Bundle.
*
* @param personEntry
* The Person entry
* @param bundle
* Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param procedure
* The Procedure
* @return The added Entry
*/
private static Entry procedure(Entry personEntry, Bundle bundle, Entry encounterEntry,
Procedure procedure) {
ca.uhn.fhir.model.dstu2.resource.Procedure procedureResource =
new ca.uhn.fhir.model.dstu2.resource.Procedure();
procedureResource.setStatus(ProcedureStatusEnum.COMPLETED);
procedureResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
procedureResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Code code = procedure.codes.get(0);
procedureResource.setCode(mapCodeToCodeableConcept(code, SNOMED_URI));
if (procedure.stop != 0L) {
Date startDate = new Date(procedure.start);
Date endDate = new Date(procedure.stop);
procedureResource.setPerformed(
new PeriodDt().setStart(new DateTimeDt(startDate)).setEnd(new DateTimeDt(endDate)));
} else {
procedureResource.setPerformed(convertFhirDateTime(procedure.start, true));
}
if (!procedure.reasons.isEmpty()) {
Code reason = procedure.reasons.get(0); // Only one element in list
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
CodingDt coding = condition.getCode().getCoding().get(0); // Only one element in list
if (reason.code.equals(coding.getCode())) {
procedureResource.setReason(new ResourceReferenceDt(entry.getFullUrl()));
}
}
}
}
Entry procedureEntry = newEntry(bundle, procedureResource);
procedure.fullUrl = procedureEntry.getFullUrl();
return procedureEntry;
}
private static Entry immunization(Entry personEntry, Bundle bundle, Entry encounterEntry,
HealthRecord.Entry immunization) {
Immunization immResource = new Immunization();
immResource.setStatus("completed");
immResource.setDate(new DateTimeDt(new Date(immunization.start)));
immResource.setVaccineCode(mapCodeToCodeableConcept(immunization.codes.get(0), CVX_URI));
immResource.setReported(new BooleanDt(false));
immResource.setWasNotGiven(false);
immResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
immResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Entry immunizationEntry = newEntry(bundle, immResource);
immunization.fullUrl = immunizationEntry.getFullUrl();
return immunizationEntry;
}
/**
* Map the given Medication to a FHIR MedicationRequest resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the Medication to
* @param encounterEntry
* Current Encounter entry
* @param medication
* The Medication
* @return The added Entry
*/
private static Entry medication(Entry personEntry, Bundle bundle, Entry encounterEntry,
Medication medication) {
MedicationOrder medicationResource = new MedicationOrder();
medicationResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
medicationResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
medicationResource.setMedication(mapCodeToCodeableConcept(medication.codes.get(0), RXNORM_URI));
medicationResource.setDateWritten(new DateTimeDt(new Date(medication.start)));
if (medication.stop != 0L) {
medicationResource.setStatus(MedicationOrderStatusEnum.STOPPED);
} else {
medicationResource.setStatus(MedicationOrderStatusEnum.ACTIVE);
}
if (!medication.reasons.isEmpty()) {
// Only one element in list
Code reason = medication.reasons.get(0);
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
// Only one element in list
CodingDt coding = condition.getCode().getCoding().get(0);
if (reason.code.equals(coding.getCode())) {
medicationResource.setReason(new ResourceReferenceDt(entry.getFullUrl()));
}
}
}
}
if (medication.prescriptionDetails != null) {
JsonObject rxInfo = medication.prescriptionDetails;
DosageInstruction dosage = new DosageInstruction();
// as_needed is true if present
dosage.setAsNeeded(new BooleanDt(rxInfo.has("as_needed")));
// as_needed is true if present
if ((rxInfo.has("dosage")) && (!rxInfo.has("as_needed"))) {
TimingDt timing = new TimingDt();
Repeat timingRepeatComponent = new Repeat();
timingRepeatComponent
.setFrequency(rxInfo.get("dosage").getAsJsonObject().get("frequency").getAsInt());
timingRepeatComponent
.setPeriod(rxInfo.get("dosage").getAsJsonObject().get("period").getAsDouble());
timingRepeatComponent.setPeriodUnits(
convertUcumCode(rxInfo.get("dosage").getAsJsonObject().get("unit").getAsString()));
timing.setRepeat(timingRepeatComponent);
dosage.setTiming(timing);
QuantityDt dose = new SimpleQuantityDt()
.setValue(rxInfo.get("dosage").getAsJsonObject().get("amount").getAsDouble());
dosage.setDose(dose);
if (rxInfo.has("instructions")) {
for (JsonElement instructionElement : rxInfo.get("instructions").getAsJsonArray()) {
JsonObject instruction = instructionElement.getAsJsonObject();
Code instructionCode = new Code(SNOMED_URI, instruction.get("code").getAsString(),
instruction.get("display").getAsString());
dosage.setAdditionalInstructions(mapCodeToCodeableConcept(instructionCode, SNOMED_URI));
}
}
}
List<DosageInstruction> dosageInstruction = new ArrayList<DosageInstruction>();
dosageInstruction.add(dosage);
medicationResource.setDosageInstruction(dosageInstruction);
}
Entry medicationEntry = newEntry(bundle, medicationResource);
// create new claim for medication
medicationClaim(personEntry, bundle, encounterEntry, medication.claim, medicationEntry);
return medicationEntry;
}
/**
* Map the given Report to a FHIR DiagnosticReport resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the Report to
* @param encounterEntry
* Current Encounter entry
* @param report
* The Report
* @return The added Entry
*/
private static Entry report(Entry personEntry, Bundle bundle, Entry encounterEntry,
Report report) {
DiagnosticReport reportResource = new DiagnosticReport();
reportResource.setStatus(DiagnosticReportStatusEnum.FINAL);
/*
* Technically, the CodeableConcept system should be "http://hl7.org/fhir/v2/0074"
* But the official Argonauts profiles incorrectly list the category pattern as
* the ValueSet (which contains the above system) as
* "http://hl7.org/fhir/ValueSet/diagnostic-service-sections", so we repeat the
* error here.
*/
CodeableConceptDt category =
new CodeableConceptDt("http://hl7.org/fhir/ValueSet/diagnostic-service-sections", "LAB");
reportResource.setCategory(category);
reportResource.setCode(mapCodeToCodeableConcept(report.codes.get(0), LOINC_URI));
reportResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
reportResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
reportResource.setEffective(convertFhirDateTime(report.start, true));
reportResource.setIssued(new InstantDt(new Date(report.start)));
ca.uhn.fhir.model.dstu2.resource.Encounter encounter =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry.getResource();
reportResource.setPerformer(encounter.getServiceProvider());
for (Observation observation : report.observations) {
ResourceReferenceDt reference = new ResourceReferenceDt(observation.fullUrl);
reference.setDisplay(observation.codes.get(0).display);
List<ResourceReferenceDt> result = new ArrayList<ResourceReferenceDt>();
result.add(reference);
reportResource.setResult(result);
}
return newEntry(bundle, reportResource);
}
/**
* Map the given CarePlan to a FHIR CarePlan resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the CarePlan to
* @param encounterEntry
* Current Encounter entry
* @param carePlan
* The CarePlan to map to FHIR and add to the bundle
* @return The added Entry
*/
private static Entry careplan(Entry personEntry, Bundle bundle, Entry encounterEntry,
CarePlan carePlan) {
ca.uhn.fhir.model.dstu2.resource.CarePlan careplanResource =
new ca.uhn.fhir.model.dstu2.resource.CarePlan();
careplanResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
careplanResource.setContext(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Code code = carePlan.codes.get(0);
careplanResource.addCategory(mapCodeToCodeableConcept(code, SNOMED_URI));
CarePlanActivityStatusEnum activityStatus;
GoalStatusEnum goalStatus;
PeriodDt period = new PeriodDt().setStart(new DateTimeDt(new Date(carePlan.start)));
careplanResource.setPeriod(period);
if (carePlan.stop != 0L) {
period.setEnd(new DateTimeDt(new Date(carePlan.stop)));
careplanResource.setStatus(CarePlanStatusEnum.COMPLETED);
activityStatus = CarePlanActivityStatusEnum.COMPLETED;
goalStatus = GoalStatusEnum.ACHIEVED;
} else {
careplanResource.setStatus(CarePlanStatusEnum.ACTIVE);
activityStatus = CarePlanActivityStatusEnum.IN_PROGRESS;
goalStatus = GoalStatusEnum.IN_PROGRESS;
}
if (!carePlan.activities.isEmpty()) {
for (Code activity : carePlan.activities) {
Activity activityComponent = new Activity();
ActivityDetail activityDetailComponent = new ActivityDetail();
activityDetailComponent.setStatus(activityStatus);
activityDetailComponent.setCode(mapCodeToCodeableConcept(activity, SNOMED_URI));
activityDetailComponent.setProhibited(new BooleanDt(false));
activityComponent.setDetail(activityDetailComponent);
careplanResource.addActivity(activityComponent);
}
}
if (!carePlan.reasons.isEmpty()) {
// Only one element in list
Code reason = carePlan.reasons.get(0);
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
// Only one element in list
CodingDt coding = condition.getCode().getCoding().get(0);
if (reason.code.equals(coding.getCode())) {
careplanResource.addAddresses().setReference(entry.getFullUrl());
}
}
}
}
for (JsonObject goal : carePlan.goals) {
Entry goalEntry = caregoal(bundle, goalStatus, goal);
careplanResource.addGoal().setReference(goalEntry.getFullUrl());
}
return newEntry(bundle, careplanResource);
}
/**
* Map the given ImagingStudy to a FHIR ImagingStudy resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the ImagingStudy to
* @param encounterEntry
* Current Encounter entry
* @param imagingStudy
* The ImagingStudy to map to FHIR and add to the bundle
* @return The added Entry
*/
private static Entry imagingStudy(Entry personEntry, Bundle bundle, Entry encounterEntry,
ImagingStudy imagingStudy) {
ca.uhn.fhir.model.dstu2.resource.ImagingStudy imagingStudyResource =
new ca.uhn.fhir.model.dstu2.resource.ImagingStudy();
OidDt studyUid = new OidDt();
studyUid.setValue("urn:oid:" + imagingStudy.dicomUid);
imagingStudyResource.setUid(studyUid);
imagingStudyResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
DateTimeDt startDate = new DateTimeDt(new Date(imagingStudy.start));
imagingStudyResource.setStarted(startDate);
// Convert the series into their FHIR equivalents
int numberOfSeries = imagingStudy.series.size();
imagingStudyResource.setNumberOfSeries(new UnsignedIntDt(numberOfSeries));
List<Series> seriesResourceList = new ArrayList<Series>();
int totalNumberOfInstances = 0;
int seriesNo = 1;
for (ImagingStudy.Series series : imagingStudy.series) {
Series seriesResource = new Series();
OidDt seriesUid = new OidDt();
seriesUid.setValue("urn:oid:" + series.dicomUid);
seriesResource.setUid(seriesUid);
seriesResource.setNumber(new UnsignedIntDt(seriesNo));
seriesResource.setStarted(startDate);
seriesResource.setAvailability(InstanceAvailabilityEnum.UNAVAILABLE);
CodeableConceptDt modalityConcept = mapCodeToCodeableConcept(series.modality, DICOM_DCM_URI);
seriesResource.setModality(modalityConcept.getCoding().get(0));
CodeableConceptDt bodySiteConcept = mapCodeToCodeableConcept(series.bodySite, SNOMED_URI);
seriesResource.setBodySite(bodySiteConcept.getCoding().get(0));
// Convert the images in each series into their FHIR equivalents
int numberOfInstances = series.instances.size();
seriesResource.setNumberOfInstances(new UnsignedIntDt(numberOfInstances));
totalNumberOfInstances += numberOfInstances;
List<SeriesInstance> instanceResourceList = new ArrayList<SeriesInstance>();
int instanceNo = 1;
for (ImagingStudy.Instance instance : series.instances) {
SeriesInstance instanceResource = new SeriesInstance();
OidDt instanceUid = new OidDt();
instanceUid.setValue("urn:oid:" + instance.dicomUid);
instanceResource.setUid(instanceUid);
instanceResource.setTitle(instance.title);
OidDt sopOid = new OidDt();
sopOid.setValue("urn:oid:" + instance.sopClass.code);
instanceResource.setSopClass(sopOid);
instanceResource.setNumber(new UnsignedIntDt(instanceNo));
instanceResourceList.add(instanceResource);
instanceNo += 1;
}
seriesResource.setInstance(instanceResourceList);
seriesResourceList.add(seriesResource);
seriesNo += 1;
}
imagingStudyResource.setSeries(seriesResourceList);
imagingStudyResource.setNumberOfInstances(totalNumberOfInstances);
return newEntry(bundle, imagingStudyResource);
}
/**
* Map the Provider into a FHIR Organization resource, and add it to the given Bundle.
*
* @param bundle
* The Bundle to add to
* @param provider
* The Provider
* @return The added Entry
*/
private static Entry provider(Bundle bundle, Provider provider) {
ca.uhn.fhir.model.dstu2.resource.Organization organizationResource =
new ca.uhn.fhir.model.dstu2.resource.Organization();
CodeableConceptDt organizationType = mapCodeToCodeableConcept(
new Code("http://hl7.org/fhir/ValueSet/organization-type", "prov", "Healthcare Provider"),
"Healthcare Provider");
organizationResource.addIdentifier().setSystem("https://github.com/synthetichealth/synthea")
.setValue((String) provider.getResourceID());
organizationResource.setName(provider.name);
organizationResource.setType(organizationType);
AddressDt address = new AddressDt()
.addLine(provider.address)
.setCity(provider.city)
.setPostalCode(provider.zip)
.setState(provider.state);
if (COUNTRY_CODE != null) {
address.setCountry(COUNTRY_CODE);
}
organizationResource.addAddress(address);
if (provider.phone != null && !provider.phone.isEmpty()) {
ContactPointDt contactPoint = new ContactPointDt()
.setSystem(ContactPointSystemEnum.PHONE)
.setValue(provider.phone);
organizationResource.addTelecom(contactPoint);
}
return newEntry(bundle, organizationResource);
}
/*
* Map the JsonObject into a FHIR Goal resource, and add it to the given Bundle.
*
* @param bundle The Bundle to add to
*
* @param goalStatus The GoalStatus
*
* @param goal The JsonObject
*
* @return The added Entry
*/
private static Entry caregoal(Bundle bundle, GoalStatusEnum goalStatus, JsonObject goal) {
ca.uhn.fhir.model.dstu2.resource.Goal goalResource =
new ca.uhn.fhir.model.dstu2.resource.Goal();
goalResource.setStatus(goalStatus);
if (goal.has("text")) {
goalResource.setDescription(goal.get("text").getAsString());
} else if (goal.has("codes")) {
JsonObject code = goal.get("codes").getAsJsonArray().get(0).getAsJsonObject();
goalResource.setDescription(code.get("display").getAsString());
} else if (goal.has("observation")) {
// build up our own text from the observation condition, similar to the graphviz logic
JsonObject logic = goal.get("observation").getAsJsonObject();
String[] text = {
logic.get("codes").getAsJsonArray().get(0).getAsJsonObject().get("display").getAsString(),
logic.get("operator").getAsString(), logic.get("value").getAsString() };
goalResource.setDescription(String.join(" ", text));
}
if (goal.has("addresses")) {
for (JsonElement reasonElement : goal.get("addresses").getAsJsonArray()) {
if (reasonElement instanceof JsonObject) {
JsonObject reasonObject = reasonElement.getAsJsonObject();
String reasonCode = reasonObject.get("codes").getAsJsonObject().get("SNOMED-CT")
.getAsJsonArray().get(0).getAsString();
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
// Only one element in list
CodingDt coding = condition.getCode().getCoding().get(0);
if (reasonCode.equals(coding.getCode())) {
goalResource.addAddresses().setReference(entry.getFullUrl());
}
}
}
}
}
}
return newEntry(bundle, goalResource);
}
/**
* Convert the unit into a UnitsOfTime.
*
* @param unit
* unit String
* @return a UnitsOfTime representing the given unit
*/
private static UnitsOfTimeEnum convertUcumCode(String unit) {
// From: http://hl7.org/fhir/ValueSet/units-of-time
switch (unit) {
case "seconds":
return UnitsOfTimeEnum.S;
case "minutes":
return UnitsOfTimeEnum.MIN;
case "hours":
return UnitsOfTimeEnum.H;
case "days":
return UnitsOfTimeEnum.D;
case "weeks":
return UnitsOfTimeEnum.WK;
case "months":
return UnitsOfTimeEnum.MO;
case "years":
return UnitsOfTimeEnum.A;
default:
return null;
}
}
/**
* Convert the timestamp into a FHIR DateType or DateTimeType.
*
* @param datetime
* Timestamp
* @param time
* If true, return a DateTimeDt; if false, return a DateDt.
* @return a DateDt or DateTimeDt representing the given timestamp
*/
private static IDatatype convertFhirDateTime(long datetime, boolean time) {
Date date = new Date(datetime);
if (time) {
return new DateTimeDt(date);
} else {
return new DateDt(date);
}
}
/**
* Helper function to convert a Code into a CodeableConceptDt. Takes an optional system, which
* replaces the Code.system in the resulting CodeableConceptDt if not null.
*
* @param from
* The Code to create a CodeableConcept from.
* @param system
* The system identifier, such as a URI. Optional; may be null.
* @return The converted CodeableConcept
*/
private static CodeableConceptDt mapCodeToCodeableConcept(Code from, String system) {
CodeableConceptDt to = new CodeableConceptDt();
if (from.display != null) {
to.setText(from.display);
}
CodingDt coding = new CodingDt();
coding.setCode(from.code);
coding.setDisplay(from.display);
if (system == null) {
coding.setSystem(from.system);
} else {
coding.setSystem(system);
}
to.addCoding(coding);
return to;
}
/**
* Helper function to create an Entry for the given Resource within the given Bundle. Sets the
* resourceID to a random UUID, sets the entry's fullURL to that resourceID, and adds the entry to
* the bundle.
*
* @param bundle
* The Bundle to add the Entry to
* @param resource
* Resource the new Entry should contain
* @return the created Entry
*/
private static Entry newEntry(Bundle bundle, BaseResource resource) {
Entry entry = bundle.addEntry();
String resourceID = UUID.randomUUID().toString();
resource.setId(resourceID);
entry.setFullUrl("urn:uuid:" + resourceID);
entry.setResource(resource);
if (TRANSACTION_BUNDLE) {
EntryRequest request = entry.getRequest();
request.setMethod(HTTPVerbEnum.POST);
request.setUrl(resource.getResourceName());
entry.setRequest(request);
}
return entry;
}
}
| src/main/java/org/mitre/synthea/export/FhirDstu2.java | package org.mitre.synthea.export;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.dstu2.composite.AddressDt;
import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.CodingDt;
import ca.uhn.fhir.model.dstu2.composite.ContactPointDt;
import ca.uhn.fhir.model.dstu2.composite.HumanNameDt;
import ca.uhn.fhir.model.dstu2.composite.MoneyDt;
import ca.uhn.fhir.model.dstu2.composite.NarrativeDt;
import ca.uhn.fhir.model.dstu2.composite.PeriodDt;
import ca.uhn.fhir.model.dstu2.composite.QuantityDt;
import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.composite.SimpleQuantityDt;
import ca.uhn.fhir.model.dstu2.composite.TimingDt;
import ca.uhn.fhir.model.dstu2.composite.TimingDt.Repeat;
import ca.uhn.fhir.model.dstu2.resource.AllergyIntolerance;
import ca.uhn.fhir.model.dstu2.resource.BaseResource;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry;
import ca.uhn.fhir.model.dstu2.resource.Bundle.EntryRequest;
import ca.uhn.fhir.model.dstu2.resource.CarePlan.Activity;
import ca.uhn.fhir.model.dstu2.resource.CarePlan.ActivityDetail;
import ca.uhn.fhir.model.dstu2.resource.Condition;
import ca.uhn.fhir.model.dstu2.resource.DiagnosticReport;
import ca.uhn.fhir.model.dstu2.resource.Encounter.Hospitalization;
import ca.uhn.fhir.model.dstu2.resource.ImagingStudy.Series;
import ca.uhn.fhir.model.dstu2.resource.ImagingStudy.SeriesInstance;
import ca.uhn.fhir.model.dstu2.resource.Immunization;
import ca.uhn.fhir.model.dstu2.resource.MedicationOrder;
import ca.uhn.fhir.model.dstu2.resource.MedicationOrder.DosageInstruction;
import ca.uhn.fhir.model.dstu2.resource.Observation.Component;
import ca.uhn.fhir.model.dstu2.resource.Organization;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.dstu2.resource.Patient.Communication;
import ca.uhn.fhir.model.dstu2.valueset.AdministrativeGenderEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceCategoryEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceCriticalityEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.AllergyIntoleranceTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.BundleTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.CarePlanActivityStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.CarePlanStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ClaimTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.ConditionCategoryCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.ConditionClinicalStatusCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.ConditionVerificationStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ContactPointSystemEnum;
import ca.uhn.fhir.model.dstu2.valueset.ContactPointUseEnum;
import ca.uhn.fhir.model.dstu2.valueset.DiagnosticReportStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.EncounterClassEnum;
import ca.uhn.fhir.model.dstu2.valueset.EncounterStateEnum;
import ca.uhn.fhir.model.dstu2.valueset.GoalStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.HTTPVerbEnum;
import ca.uhn.fhir.model.dstu2.valueset.IdentifierTypeCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.InstanceAvailabilityEnum;
import ca.uhn.fhir.model.dstu2.valueset.MaritalStatusCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.MedicationOrderStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.NameUseEnum;
import ca.uhn.fhir.model.dstu2.valueset.NarrativeStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ObservationStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.ProcedureStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.UnitsOfTimeEnum;
import ca.uhn.fhir.model.dstu2.valueset.UseEnum;
import ca.uhn.fhir.model.primitive.BooleanDt;
import ca.uhn.fhir.model.primitive.CodeDt;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.DateTimeDt;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.IntegerDt;
import ca.uhn.fhir.model.primitive.OidDt;
import ca.uhn.fhir.model.primitive.PositiveIntDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.UnsignedIntDt;
import ca.uhn.fhir.model.primitive.XhtmlDt;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.sis.geometry.DirectPosition2D;
import org.mitre.synthea.helpers.Config;
import org.mitre.synthea.helpers.Utilities;
import org.mitre.synthea.world.agents.Person;
import org.mitre.synthea.world.agents.Provider;
import org.mitre.synthea.world.concepts.Costs;
import org.mitre.synthea.world.concepts.HealthRecord;
import org.mitre.synthea.world.concepts.HealthRecord.CarePlan;
import org.mitre.synthea.world.concepts.HealthRecord.Claim;
import org.mitre.synthea.world.concepts.HealthRecord.Code;
import org.mitre.synthea.world.concepts.HealthRecord.Encounter;
import org.mitre.synthea.world.concepts.HealthRecord.ImagingStudy;
import org.mitre.synthea.world.concepts.HealthRecord.Medication;
import org.mitre.synthea.world.concepts.HealthRecord.Observation;
import org.mitre.synthea.world.concepts.HealthRecord.Procedure;
import org.mitre.synthea.world.concepts.HealthRecord.Report;
public class FhirDstu2 {
// HAPI FHIR warns that the context creation is expensive, and should be performed
// per-application, not per-record
private static final FhirContext FHIR_CTX = FhirContext.forDstu2();
private static final String SNOMED_URI = "http://snomed.info/sct";
private static final String LOINC_URI = "http://loinc.org";
private static final String RXNORM_URI = "http://www.nlm.nih.gov/research/umls/rxnorm";
private static final String CVX_URI = "http://hl7.org/fhir/sid/cvx";
private static final String DISCHARGE_URI = "http://www.nubc.org/patient-discharge";
private static final String SYNTHEA_EXT = "http://synthetichealth.github.io/synthea/";
private static final String DICOM_DCM_URI = "http://dicom.nema.org/resources/ontology/DCM";
@SuppressWarnings("rawtypes")
private static final Map raceEthnicityCodes = loadRaceEthnicityCodes();
@SuppressWarnings("rawtypes")
private static final Map languageLookup = loadLanguageLookup();
protected static boolean TRANSACTION_BUNDLE =
Boolean.parseBoolean(Config.get("exporter.fhir.transaction_bundle"));
private static final String COUNTRY_CODE = Config.get("generate.geography.country_code");
@SuppressWarnings("rawtypes")
private static Map loadRaceEthnicityCodes() {
String filename = "race_ethnicity_codes.json";
try {
String json = Utilities.readResource(filename);
Gson g = new Gson();
return g.fromJson(json, HashMap.class);
} catch (Exception e) {
System.err.println("ERROR: unable to load json: " + filename);
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings("rawtypes")
private static Map loadLanguageLookup() {
String filename = "language_lookup.json";
try {
String json = Utilities.readResource(filename);
Gson g = new Gson();
return g.fromJson(json, HashMap.class);
} catch (Exception e) {
System.err.println("ERROR: unable to load json: " + filename);
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
/**
* Convert the given Person into a JSON String, containing a FHIR Bundle of the Person and the
* associated entries from their health record.
*
* @param person
* Person to generate the FHIR JSON for
* @param stopTime
* Time the simulation ended
* @return String containing a JSON representation of a FHIR Bundle containing the Person's health
* record
*/
public static String convertToFHIR(Person person, long stopTime) {
Bundle bundle = new Bundle();
if (TRANSACTION_BUNDLE) {
bundle.setType(BundleTypeEnum.TRANSACTION);
} else {
bundle.setType(BundleTypeEnum.COLLECTION);
}
Entry personEntry = basicInfo(person, bundle, stopTime);
for (Encounter encounter : person.record.encounters) {
Entry encounterEntry = encounter(person, personEntry, bundle, encounter);
for (HealthRecord.Entry condition : encounter.conditions) {
condition(personEntry, bundle, encounterEntry, condition);
}
for (HealthRecord.Entry allergy : encounter.allergies) {
allergy(personEntry, bundle, encounterEntry, allergy);
}
for (Observation observation : encounter.observations) {
observation(personEntry, bundle, encounterEntry, observation);
}
for (Procedure procedure : encounter.procedures) {
procedure(personEntry, bundle, encounterEntry, procedure);
}
for (Medication medication : encounter.medications) {
medication(personEntry, bundle, encounterEntry, medication);
}
for (HealthRecord.Entry immunization : encounter.immunizations) {
immunization(personEntry, bundle, encounterEntry, immunization);
}
for (Report report : encounter.reports) {
report(personEntry, bundle, encounterEntry, report);
}
for (CarePlan careplan : encounter.careplans) {
careplan(personEntry, bundle, encounterEntry, careplan);
}
for (ImagingStudy imagingStudy : encounter.imagingStudies) {
imagingStudy(personEntry, bundle, encounterEntry, imagingStudy);
}
// one claim per encounter
encounterClaim(personEntry, bundle, encounterEntry, encounter.claim);
}
String bundleJson = FHIR_CTX.newJsonParser().setPrettyPrint(true)
.encodeResourceToString(bundle);
return bundleJson;
}
/**
* Map the given Person to a FHIR Patient resource, and add it to the given Bundle.
*
* @param person
* The Person
* @param bundle
* The Bundle to add to
* @param stopTime
* Time the simulation ended
* @return The created Entry
*/
@SuppressWarnings("rawtypes")
private static Entry basicInfo(Person person, Bundle bundle, long stopTime) {
Patient patientResource = new Patient();
patientResource.addIdentifier().setSystem("https://github.com/synthetichealth/synthea")
.setValue((String) person.attributes.get(Person.ID));
patientResource.addIdentifier()
.setType(IdentifierTypeCodesEnum.MR)
.setSystem("http://hospital.smarthealthit.org")
.setValue((String) person.attributes.get(Person.ID));
patientResource.addIdentifier()
.setType(IdentifierTypeCodesEnum.SOCIAL_BENEFICIARY_IDENTIFIER)
.setSystem("http://hl7.org/fhir/sid/us-ssn")
.setValue((String) person.attributes.get(Person.IDENTIFIER_SSN));
if (person.attributes.get(Person.IDENTIFIER_DRIVERS) != null) {
patientResource.addIdentifier()
.setType(IdentifierTypeCodesEnum.DL)
.setSystem("urn:oid:2.16.840.1.113883.4.3.25")
.setValue((String) person.attributes.get(Person.IDENTIFIER_DRIVERS));
}
ExtensionDt raceExtension = new ExtensionDt();
raceExtension.setUrl("http://hl7.org/fhir/StructureDefinition/us-core-race");
String race = (String) person.attributes.get(Person.RACE);
ExtensionDt ethnicityExtension = new ExtensionDt();
ethnicityExtension.setUrl("http://hl7.org/fhir/StructureDefinition/us-core-ethnicity");
String ethnicity = (String) person.attributes.get(Person.ETHNICITY);
if (race.equals("hispanic")) {
race = "other";
ethnicity = "hispanic";
} else {
ethnicity = "nonhispanic";
}
String raceDisplay;
switch (race) {
case "white":
raceDisplay = "White";
break;
case "black":
raceDisplay = "Black or African American";
break;
case "asian":
raceDisplay = "Asian";
break;
case "native":
raceDisplay = "American Indian or Alaska Native";
break;
default: // Hispanic or Other (Put Hawaiian and Pacific Islander here for now)
raceDisplay = "Other";
break;
}
String ethnicityDisplay;
if (ethnicity.equals("hispanic")) {
ethnicityDisplay = "Hispanic or Latino";
} else {
ethnicityDisplay = "Not Hispanic or Latino";
}
Code raceCode = new Code(
"http://hl7.org/fhir/v3/Race",
(String) raceEthnicityCodes.get(race),
raceDisplay);
Code ethnicityCode = new Code(
"http://hl7.org/fhir/v3/Ethnicity",
(String) raceEthnicityCodes.get(ethnicity),
ethnicityDisplay);
raceExtension.setValue(mapCodeToCodeableConcept(raceCode, "http://hl7.org/fhir/v3/Race"));
ethnicityExtension.setValue(mapCodeToCodeableConcept(ethnicityCode, "http://hl7.org/fhir/v3/Ethnicity"));
patientResource.addUndeclaredExtension(raceExtension);
patientResource.addUndeclaredExtension(ethnicityExtension);
String firstLanguage = (String) person.attributes.get(Person.FIRST_LANGUAGE);
Map languageMap = (Map) languageLookup.get(firstLanguage);
Code languageCode = new Code((String) languageMap.get("system"),
(String) languageMap.get("code"), (String) languageMap.get("display"));
List<Communication> communication = new ArrayList<Communication>();
Communication language = new Communication();
language
.setLanguage(mapCodeToCodeableConcept(languageCode, (String) languageMap.get("system")));
communication.add(language);
patientResource.setCommunication(communication);
HumanNameDt name = patientResource.addName();
name.setUse(NameUseEnum.OFFICIAL);
name.addGiven((String) person.attributes.get(Person.FIRST_NAME));
List<StringDt> officialFamilyNames = new ArrayList<StringDt>();
officialFamilyNames.add(new StringDt((String) person.attributes.get(Person.LAST_NAME)));
name.setFamily(officialFamilyNames);
if (person.attributes.get(Person.NAME_PREFIX) != null) {
name.addPrefix((String) person.attributes.get(Person.NAME_PREFIX));
}
if (person.attributes.get(Person.NAME_SUFFIX) != null) {
name.addSuffix((String) person.attributes.get(Person.NAME_SUFFIX));
}
if (person.attributes.get(Person.MAIDEN_NAME) != null) {
HumanNameDt maidenName = patientResource.addName();
maidenName.setUse(NameUseEnum.MAIDEN);
maidenName.addGiven((String) person.attributes.get(Person.FIRST_NAME));
List<StringDt> maidenFamilyNames = new ArrayList<StringDt>();
maidenFamilyNames.add(new StringDt((String) person.attributes.get(Person.MAIDEN_NAME)));
maidenName.setFamily(maidenFamilyNames);
if (person.attributes.get(Person.NAME_PREFIX) != null) {
maidenName.addPrefix((String) person.attributes.get(Person.NAME_PREFIX));
}
if (person.attributes.get(Person.NAME_SUFFIX) != null) {
maidenName.addSuffix((String) person.attributes.get(Person.NAME_SUFFIX));
}
}
ExtensionDt mothersMaidenNameExtension = new ExtensionDt();
mothersMaidenNameExtension
.setUrl("http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName");
String mothersMaidenName = (String) person.attributes.get(Person.NAME_MOTHER);
mothersMaidenNameExtension.setValue(new StringDt(mothersMaidenName));
patientResource.addUndeclaredExtension(mothersMaidenNameExtension);
long birthdate = (long) person.attributes.get(Person.BIRTHDATE);
patientResource.setBirthDate(new DateDt(new Date(birthdate)));
ExtensionDt birthSexExtension = new ExtensionDt();
birthSexExtension.setUrl("http://hl7.org/fhir/us/core/StructureDefinition/us-core-birthsex");
if (person.attributes.get(Person.GENDER).equals("M")) {
patientResource.setGender(AdministrativeGenderEnum.MALE);
birthSexExtension.setValue(new CodeDt("M"));
} else if (person.attributes.get(Person.GENDER).equals("F")) {
patientResource.setGender(AdministrativeGenderEnum.FEMALE);
birthSexExtension.setValue(new CodeDt("F"));
}
patientResource.addUndeclaredExtension(birthSexExtension);
String state = (String) person.attributes.get(Person.STATE);
AddressDt addrResource = patientResource.addAddress();
addrResource.addLine((String) person.attributes.get(Person.ADDRESS))
.setCity((String) person.attributes.get(Person.CITY))
.setPostalCode((String) person.attributes.get(Person.ZIP))
.setState(state);
if (COUNTRY_CODE != null) {
addrResource.setCountry(COUNTRY_CODE);
}
DirectPosition2D coord = (DirectPosition2D) person.attributes.get(Person.COORDINATE);
if (coord != null) {
ExtensionDt geolocationExtension = new ExtensionDt();
geolocationExtension.setUrl("http://hl7.org/fhir/StructureDefinition/geolocation");
ExtensionDt latitudeExtension = new ExtensionDt();
ExtensionDt longitudeExtension = new ExtensionDt();
latitudeExtension.setUrl("latitude");
longitudeExtension.setUrl("longitude");
latitudeExtension.setValue(new DecimalDt(coord.getY()));
longitudeExtension.setValue(new DecimalDt(coord.getX()));
geolocationExtension.addUndeclaredExtension(latitudeExtension);
geolocationExtension.addUndeclaredExtension(longitudeExtension);
addrResource.addUndeclaredExtension(geolocationExtension);
}
AddressDt birthplace = new AddressDt();
birthplace.setCity((String) person.attributes.get(Person.BIRTHPLACE)).setState(state);
if (COUNTRY_CODE != null) {
birthplace.setCountry(COUNTRY_CODE);
}
ExtensionDt birthplaceExtension = new ExtensionDt();
birthplaceExtension.setUrl("http://hl7.org/fhir/StructureDefinition/birthPlace");
birthplaceExtension.setValue(birthplace);
patientResource.addUndeclaredExtension(birthplaceExtension);
if (person.attributes.get(Person.MULTIPLE_BIRTH_STATUS) != null) {
patientResource.setMultipleBirth(
new IntegerDt((int) person.attributes.get(Person.MULTIPLE_BIRTH_STATUS)));
} else {
patientResource.setMultipleBirth(new BooleanDt(false));
}
patientResource.addTelecom().setSystem(ContactPointSystemEnum.PHONE)
.setUse(ContactPointUseEnum.HOME).setValue((String) person.attributes.get(Person.TELECOM));
String maritalStatus = ((String) person.attributes.get(Person.MARITAL_STATUS));
if (maritalStatus != null) {
patientResource.setMaritalStatus(MaritalStatusCodesEnum.forCode(maritalStatus.toUpperCase()));
} else {
patientResource.setMaritalStatus(MaritalStatusCodesEnum.S);
}
if (!person.alive(stopTime)) {
patientResource.setDeceased(convertFhirDateTime(person.record.death, true));
}
String generatedBySynthea = "Generated by <a href=\"https://github.com/synthetichealth/synthea\">Synthea</a>."
+ "Version identifier: " + Utilities.SYNTHEA_VERSION + " . "
+ " Person seed: " + person.seed
+ " Population seed: " + person.populationSeed;
patientResource.setText(new NarrativeDt(
new XhtmlDt(generatedBySynthea), NarrativeStatusEnum.GENERATED));
// DALY and QALY values
// we only write the last(current) one to the patient record
Double dalyValue = (Double) person.attributes.get("most-recent-daly");
Double qalyValue = (Double) person.attributes.get("most-recent-qaly");
if (dalyValue != null) {
ExtensionDt dalyExtension = new ExtensionDt();
dalyExtension.setUrl(SYNTHEA_EXT + "disability-adjusted-life-years");
DecimalDt daly = new DecimalDt(dalyValue);
dalyExtension.setValue(daly);
patientResource.addUndeclaredExtension(dalyExtension);
ExtensionDt qalyExtension = new ExtensionDt();
qalyExtension.setUrl(SYNTHEA_EXT + "quality-adjusted-life-years");
DecimalDt qaly = new DecimalDt(qalyValue);
qalyExtension.setValue(qaly);
patientResource.addUndeclaredExtension(qalyExtension);
}
return newEntry(bundle, patientResource);
}
/**
* Map the given Encounter into a FHIR Encounter resource, and add it to the given Bundle.
*
* @param person
* Patient at the encounter.
* @param personEntry
* Entry for the Person
* @param bundle
* The Bundle to add to
* @param encounter
* The current Encounter
* @return The added Entry
*/
private static Entry encounter(Person person, Entry personEntry,
Bundle bundle, Encounter encounter) {
ca.uhn.fhir.model.dstu2.resource.Encounter encounterResource =
new ca.uhn.fhir.model.dstu2.resource.Encounter();
encounterResource.setStatus(EncounterStateEnum.FINISHED);
if (encounter.codes.isEmpty()) {
// wellness encounter
encounterResource.addType().addCoding().setCode("185349003")
.setDisplay("Encounter for check up").setSystem(SNOMED_URI);
} else {
Code code = encounter.codes.get(0);
encounterResource.addType(mapCodeToCodeableConcept(code, SNOMED_URI));
}
encounterResource.setClassElement(EncounterClassEnum.forCode(encounter.type));
encounterResource.setPeriod(new PeriodDt()
.setStart(new DateTimeDt(new Date(encounter.start)))
.setEnd(new DateTimeDt(new Date(encounter.stop))));
if (encounter.reason != null) {
encounterResource.addReason().addCoding().setCode(encounter.reason.code)
.setDisplay(encounter.reason.display).setSystem(SNOMED_URI);
}
if (encounter.provider != null) {
String providerFullUrl = findProviderUrl(encounter.provider, bundle);
if (providerFullUrl != null) {
encounterResource.setServiceProvider(new ResourceReferenceDt(providerFullUrl));
} else {
Entry providerOrganization = provider(bundle, encounter.provider);
encounterResource
.setServiceProvider(new ResourceReferenceDt(providerOrganization.getFullUrl()));
}
} else { // no associated provider, patient goes to ambulatory provider
Provider provider = person.getAmbulatoryProvider(encounter.start);
String providerFullUrl = findProviderUrl(provider, bundle);
if (providerFullUrl != null) {
encounterResource.setServiceProvider(new ResourceReferenceDt(providerFullUrl));
} else {
Entry providerOrganization = provider(bundle, provider);
encounterResource
.setServiceProvider(new ResourceReferenceDt(providerOrganization.getFullUrl()));
}
}
if (encounter.discharge != null) {
Hospitalization hospitalization = new Hospitalization();
Code dischargeDisposition = new Code(DISCHARGE_URI, encounter.discharge.code,
encounter.discharge.display);
hospitalization
.setDischargeDisposition(mapCodeToCodeableConcept(dischargeDisposition, DISCHARGE_URI));
encounterResource.setHospitalization(hospitalization);
}
return newEntry(bundle, encounterResource);
}
/**
* Find the provider entry in this bundle, and return the associated "fullUrl" attribute.
* @param provider A given provider.
* @param bundle The current bundle being generated.
* @return Provider.fullUrl if found, otherwise null.
*/
private static String findProviderUrl(Provider provider, Bundle bundle) {
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Organization")) {
Organization org = (Organization) entry.getResource();
if (org.getIdentifierFirstRep().getValue().equals(provider.getResourceID())) {
return entry.getFullUrl();
}
}
}
return null;
}
/**
* Create an entry for the given Claim, which references a Medication.
*
* @param personEntry
* Entry for the person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter
* @param claim
* the Claim object
* @param medicationEntry
* The Entry for the Medication object, previously created
* @return the added Entry
*/
private static Entry medicationClaim(Entry personEntry, Bundle bundle, Entry encounterEntry,
Claim claim, Entry medicationEntry) {
ca.uhn.fhir.model.dstu2.resource.Claim claimResource =
new ca.uhn.fhir.model.dstu2.resource.Claim();
ca.uhn.fhir.model.dstu2.resource.Encounter encounterResource =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry
.getResource();
// assume institutional claim
claimResource.setType(ClaimTypeEnum.INSTITUTIONAL); // TODO review claim type
claimResource.setUse(UseEnum.COMPLETE);
claimResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
claimResource.setOrganization(encounterResource.getServiceProvider());
// add prescription.
claimResource.setPrescription(new ResourceReferenceDt(medicationEntry.getFullUrl()));
return newEntry(bundle, claimResource);
}
/**
* Create an entry for the given Claim, associated to an Encounter.
*
* @param personEntry
* Entry for the person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter
* @param claim
* the Claim object
* @return the added Entry
*/
private static Entry encounterClaim(Entry personEntry, Bundle bundle, Entry encounterEntry,
Claim claim) {
ca.uhn.fhir.model.dstu2.resource.Claim claimResource =
new ca.uhn.fhir.model.dstu2.resource.Claim();
ca.uhn.fhir.model.dstu2.resource.Encounter encounterResource =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry
.getResource();
// assume institutional claim
claimResource.setType(ClaimTypeEnum.INSTITUTIONAL);
claimResource.setUse(UseEnum.COMPLETE);
claimResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
claimResource.setOrganization(encounterResource.getServiceProvider());
// Add data for the encounter
ca.uhn.fhir.model.dstu2.resource.Claim.Item encounterItem =
new ca.uhn.fhir.model.dstu2.resource.Claim.Item();
encounterItem.setSequence(new PositiveIntDt(1));
// assume item type is clinical service invoice
CodingDt itemType = new CodingDt();
itemType.setSystem("http://hl7.org/fhir/v3/ActCode")
.setCode("CSINV")
.setDisplay("clinical service invoice");
encounterItem.setType(itemType);
CodingDt itemService = new CodingDt();
ca.uhn.fhir.model.dstu2.resource.Encounter encounter =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry.getResource();
itemService.setSystem(encounter.getTypeFirstRep().getCodingFirstRep().getSystem())
.setCode(encounter.getTypeFirstRep().getCodingFirstRep().getCode())
.setDisplay(encounter.getTypeFirstRep().getCodingFirstRep().getDisplay());
encounterItem.setService(itemService);
claimResource.addItem(encounterItem);
int itemSequence = 2;
int conditionSequence = 1;
for (HealthRecord.Entry item : claim.items) {
if (Costs.hasCost(item)) {
// update claimItems list
ca.uhn.fhir.model.dstu2.resource.Claim.Item procedureItem =
new ca.uhn.fhir.model.dstu2.resource.Claim.Item();
procedureItem.setSequence(new PositiveIntDt(itemSequence));
// calculate the cost of the procedure
MoneyDt moneyResource = new MoneyDt();
moneyResource.setCode("USD");
moneyResource.setSystem("urn:iso:std:iso:4217");
moneyResource.setValue(item.cost());
procedureItem.setNet(moneyResource);
// assume item type is clinical service invoice
itemType = new CodingDt();
itemType.setSystem("http://hl7.org/fhir/v3/ActCode")
.setCode("CSINV")
.setDisplay("clinical service invoice");
procedureItem.setType(itemType);
// item service should match the entry code
itemService = new CodingDt();
itemService.setSystem(item.codes.get(0).system)
.setCode(item.codes.get(0).code)
.setDisplay(item.codes.get(0).display);
procedureItem.setService(itemService);
claimResource.addItem(procedureItem);
} else {
// assume it's a Condition, we don't have a Condition class specifically
// add diagnosisComponent to claim
ca.uhn.fhir.model.dstu2.resource.Claim.Diagnosis diagnosisComponent =
new ca.uhn.fhir.model.dstu2.resource.Claim.Diagnosis();
diagnosisComponent.setSequence(new PositiveIntDt(conditionSequence));
if (item.codes.size() > 0) {
// use first code
diagnosisComponent.setDiagnosis(
new CodingDt(item.codes.get(0).system, item.codes.get(0).code));
}
claimResource.addDiagnosis(diagnosisComponent);
conditionSequence++;
}
itemSequence++;
}
return newEntry(bundle, claimResource);
}
/**
* Map the Condition into a FHIR Condition resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param condition
* The Condition
* @return The added Entry
*/
private static Entry condition(Entry personEntry, Bundle bundle, Entry encounterEntry,
HealthRecord.Entry condition) {
Condition conditionResource = new Condition();
conditionResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
conditionResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Code code = condition.codes.get(0);
conditionResource.setCode(mapCodeToCodeableConcept(code, SNOMED_URI));
conditionResource.setCategory(ConditionCategoryCodesEnum.DIAGNOSIS);
conditionResource.setVerificationStatus(ConditionVerificationStatusEnum.CONFIRMED);
conditionResource.setClinicalStatus(ConditionClinicalStatusCodesEnum.ACTIVE);
conditionResource.setOnset(convertFhirDateTime(condition.start, true));
conditionResource.setDateRecorded(new DateDt(new Date(condition.start)));
if (condition.stop != 0) {
conditionResource.setAbatement(convertFhirDateTime(condition.stop, true));
conditionResource.setClinicalStatus(ConditionClinicalStatusCodesEnum.RESOLVED);
}
Entry conditionEntry = newEntry(bundle, conditionResource);
condition.fullUrl = conditionEntry.getFullUrl();
return conditionEntry;
}
/**
* Map the Condition into a FHIR AllergyIntolerance resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param allergy
* The Allergy Entry
* @return The added Entry
*/
private static Entry allergy(Entry personEntry, Bundle bundle,
Entry encounterEntry, HealthRecord.Entry allergy) {
AllergyIntolerance allergyResource = new AllergyIntolerance();
allergyResource.setOnset((DateTimeDt)convertFhirDateTime(allergy.start, true));
if (allergy.stop == 0) {
allergyResource.setStatus(AllergyIntoleranceStatusEnum.ACTIVE);
} else {
allergyResource.setStatus(AllergyIntoleranceStatusEnum.INACTIVE);
}
allergyResource.setType(AllergyIntoleranceTypeEnum.ALLERGY);
AllergyIntoleranceCategoryEnum category = AllergyIntoleranceCategoryEnum.FOOD;
allergyResource.setCategory(category); // TODO: allergy categories in GMF
allergyResource.setCriticality(AllergyIntoleranceCriticalityEnum.LOW_RISK);
allergyResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
Code code = allergy.codes.get(0);
allergyResource.setSubstance(mapCodeToCodeableConcept(code, SNOMED_URI));
Entry allergyEntry = newEntry(bundle, allergyResource);
allergy.fullUrl = allergyEntry.getFullUrl();
return allergyEntry;
}
/**
* Map the given Observation into a FHIR Observation resource, and add it to the given Bundle.
*
* @param personEntry
* The Person Entry
* @param bundle
* The Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param observation
* The Observation
* @return The added Entry
*/
private static Entry observation(Entry personEntry, Bundle bundle, Entry encounterEntry,
Observation observation) {
ca.uhn.fhir.model.dstu2.resource.Observation observationResource =
new ca.uhn.fhir.model.dstu2.resource.Observation();
observationResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
observationResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
observationResource.setStatus(ObservationStatusEnum.FINAL);
Code code = observation.codes.get(0);
observationResource.setCode(mapCodeToCodeableConcept(code, LOINC_URI));
Code category = new Code("http://hl7.org/fhir/observation-category", observation.category,
observation.category);
observationResource.setCategory(
mapCodeToCodeableConcept(category, "http://hl7.org/fhir/observation-category"));
if (observation.value != null) {
IDatatype value = mapValueToFHIRType(observation.value, observation.unit);
observationResource.setValue(value);
} else if (observation.observations != null && !observation.observations.isEmpty()) {
// multi-observation (ex blood pressure)
for (Observation subObs : observation.observations) {
Component comp = new Component();
comp.setCode(mapCodeToCodeableConcept(subObs.codes.get(0), LOINC_URI));
IDatatype value = mapValueToFHIRType(subObs.value, subObs.unit);
comp.setValue(value);
observationResource.addComponent(comp);
}
}
observationResource.setEffective(convertFhirDateTime(observation.start, true));
observationResource.setIssued(new InstantDt(new Date(observation.start)));
Entry entry = newEntry(bundle, observationResource);
observation.fullUrl = entry.getFullUrl();
return entry;
}
private static IDatatype mapValueToFHIRType(Object value, String unit) {
if (value == null) {
return null;
} else if (value instanceof Condition) {
Code conditionCode = ((HealthRecord.Entry) value).codes.get(0);
return mapCodeToCodeableConcept(conditionCode, SNOMED_URI);
} else if (value instanceof Code) {
return mapCodeToCodeableConcept((Code) value, SNOMED_URI);
} else if (value instanceof String) {
return new StringDt((String) value);
} else if (value instanceof Number) {
return new QuantityDt().setValue(((Number) value).doubleValue())
.setCode(unit).setSystem("http://unitsofmeasure.org")
.setUnit(unit);
} else {
throw new IllegalArgumentException("unexpected observation value class: "
+ value.getClass().toString() + "; " + value);
}
}
/**
* Map the given Procedure into a FHIR Procedure resource, and add it to the given Bundle.
*
* @param personEntry
* The Person entry
* @param bundle
* Bundle to add to
* @param encounterEntry
* The current Encounter entry
* @param procedure
* The Procedure
* @return The added Entry
*/
private static Entry procedure(Entry personEntry, Bundle bundle, Entry encounterEntry,
Procedure procedure) {
ca.uhn.fhir.model.dstu2.resource.Procedure procedureResource =
new ca.uhn.fhir.model.dstu2.resource.Procedure();
procedureResource.setStatus(ProcedureStatusEnum.COMPLETED);
procedureResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
procedureResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Code code = procedure.codes.get(0);
procedureResource.setCode(mapCodeToCodeableConcept(code, SNOMED_URI));
if (procedure.stop != 0L) {
Date startDate = new Date(procedure.start);
Date endDate = new Date(procedure.stop);
procedureResource.setPerformed(
new PeriodDt().setStart(new DateTimeDt(startDate)).setEnd(new DateTimeDt(endDate)));
} else {
procedureResource.setPerformed(convertFhirDateTime(procedure.start, true));
}
if (!procedure.reasons.isEmpty()) {
Code reason = procedure.reasons.get(0); // Only one element in list
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
CodingDt coding = condition.getCode().getCoding().get(0); // Only one element in list
if (reason.code.equals(coding.getCode())) {
procedureResource.setReason(new ResourceReferenceDt(entry.getFullUrl()));
}
}
}
}
Entry procedureEntry = newEntry(bundle, procedureResource);
procedure.fullUrl = procedureEntry.getFullUrl();
return procedureEntry;
}
private static Entry immunization(Entry personEntry, Bundle bundle, Entry encounterEntry,
HealthRecord.Entry immunization) {
Immunization immResource = new Immunization();
immResource.setStatus("completed");
immResource.setDate(new DateTimeDt(new Date(immunization.start)));
immResource.setVaccineCode(mapCodeToCodeableConcept(immunization.codes.get(0), CVX_URI));
immResource.setReported(new BooleanDt(false));
immResource.setWasNotGiven(false);
immResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
immResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Entry immunizationEntry = newEntry(bundle, immResource);
immunization.fullUrl = immunizationEntry.getFullUrl();
return immunizationEntry;
}
/**
* Map the given Medication to a FHIR MedicationRequest resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the Medication to
* @param encounterEntry
* Current Encounter entry
* @param medication
* The Medication
* @return The added Entry
*/
private static Entry medication(Entry personEntry, Bundle bundle, Entry encounterEntry,
Medication medication) {
MedicationOrder medicationResource = new MedicationOrder();
medicationResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
medicationResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
medicationResource.setMedication(mapCodeToCodeableConcept(medication.codes.get(0), RXNORM_URI));
medicationResource.setDateWritten(new DateTimeDt(new Date(medication.start)));
if (medication.stop != 0L) {
medicationResource.setStatus(MedicationOrderStatusEnum.STOPPED);
} else {
medicationResource.setStatus(MedicationOrderStatusEnum.ACTIVE);
}
if (!medication.reasons.isEmpty()) {
// Only one element in list
Code reason = medication.reasons.get(0);
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
// Only one element in list
CodingDt coding = condition.getCode().getCoding().get(0);
if (reason.code.equals(coding.getCode())) {
medicationResource.setReason(new ResourceReferenceDt(entry.getFullUrl()));
}
}
}
}
if (medication.prescriptionDetails != null) {
JsonObject rxInfo = medication.prescriptionDetails;
DosageInstruction dosage = new DosageInstruction();
// as_needed is true if present
dosage.setAsNeeded(new BooleanDt(rxInfo.has("as_needed")));
// as_needed is true if present
if ((rxInfo.has("dosage")) && (!rxInfo.has("as_needed"))) {
TimingDt timing = new TimingDt();
Repeat timingRepeatComponent = new Repeat();
timingRepeatComponent
.setFrequency(rxInfo.get("dosage").getAsJsonObject().get("frequency").getAsInt());
timingRepeatComponent
.setPeriod(rxInfo.get("dosage").getAsJsonObject().get("period").getAsDouble());
timingRepeatComponent.setPeriodUnits(
convertUcumCode(rxInfo.get("dosage").getAsJsonObject().get("unit").getAsString()));
timing.setRepeat(timingRepeatComponent);
dosage.setTiming(timing);
QuantityDt dose = new SimpleQuantityDt()
.setValue(rxInfo.get("dosage").getAsJsonObject().get("amount").getAsDouble());
dosage.setDose(dose);
if (rxInfo.has("instructions")) {
for (JsonElement instructionElement : rxInfo.get("instructions").getAsJsonArray()) {
JsonObject instruction = instructionElement.getAsJsonObject();
Code instructionCode = new Code(SNOMED_URI, instruction.get("code").getAsString(),
instruction.get("display").getAsString());
dosage.setAdditionalInstructions(mapCodeToCodeableConcept(instructionCode, SNOMED_URI));
}
}
}
List<DosageInstruction> dosageInstruction = new ArrayList<DosageInstruction>();
dosageInstruction.add(dosage);
medicationResource.setDosageInstruction(dosageInstruction);
}
Entry medicationEntry = newEntry(bundle, medicationResource);
// create new claim for medication
medicationClaim(personEntry, bundle, encounterEntry, medication.claim, medicationEntry);
return medicationEntry;
}
/**
* Map the given Report to a FHIR DiagnosticReport resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the Report to
* @param encounterEntry
* Current Encounter entry
* @param report
* The Report
* @return The added Entry
*/
private static Entry report(Entry personEntry, Bundle bundle, Entry encounterEntry,
Report report) {
DiagnosticReport reportResource = new DiagnosticReport();
reportResource.setStatus(DiagnosticReportStatusEnum.FINAL);
/*
* Technically, the CodeableConcept system should be "http://hl7.org/fhir/v2/0074"
* But the official Argonauts profiles incorrectly list the category pattern as
* the ValueSet (which contains the above system) as
* "http://hl7.org/fhir/ValueSet/diagnostic-service-sections", so we repeat the
* error here.
*/
CodeableConceptDt category =
new CodeableConceptDt("http://hl7.org/fhir/ValueSet/diagnostic-service-sections", "LAB");
reportResource.setCategory(category);
reportResource.setCode(mapCodeToCodeableConcept(report.codes.get(0), LOINC_URI));
reportResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
reportResource.setEncounter(new ResourceReferenceDt(encounterEntry.getFullUrl()));
reportResource.setEffective(convertFhirDateTime(report.start, true));
reportResource.setIssued(new InstantDt(new Date(report.start)));
ca.uhn.fhir.model.dstu2.resource.Encounter encounter =
(ca.uhn.fhir.model.dstu2.resource.Encounter) encounterEntry.getResource();
reportResource.setPerformer(encounter.getServiceProvider());
for (Observation observation : report.observations) {
ResourceReferenceDt reference = new ResourceReferenceDt(observation.fullUrl);
reference.setDisplay(observation.codes.get(0).display);
List<ResourceReferenceDt> result = new ArrayList<ResourceReferenceDt>();
result.add(reference);
reportResource.setResult(result);
}
return newEntry(bundle, reportResource);
}
/**
* Map the given CarePlan to a FHIR CarePlan resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the CarePlan to
* @param encounterEntry
* Current Encounter entry
* @param carePlan
* The CarePlan to map to FHIR and add to the bundle
* @return The added Entry
*/
private static Entry careplan(Entry personEntry, Bundle bundle, Entry encounterEntry,
CarePlan carePlan) {
ca.uhn.fhir.model.dstu2.resource.CarePlan careplanResource =
new ca.uhn.fhir.model.dstu2.resource.CarePlan();
careplanResource.setSubject(new ResourceReferenceDt(personEntry.getFullUrl()));
careplanResource.setContext(new ResourceReferenceDt(encounterEntry.getFullUrl()));
Code code = carePlan.codes.get(0);
careplanResource.addCategory(mapCodeToCodeableConcept(code, SNOMED_URI));
CarePlanActivityStatusEnum activityStatus;
GoalStatusEnum goalStatus;
PeriodDt period = new PeriodDt().setStart(new DateTimeDt(new Date(carePlan.start)));
careplanResource.setPeriod(period);
if (carePlan.stop != 0L) {
period.setEnd(new DateTimeDt(new Date(carePlan.stop)));
careplanResource.setStatus(CarePlanStatusEnum.COMPLETED);
activityStatus = CarePlanActivityStatusEnum.COMPLETED;
goalStatus = GoalStatusEnum.ACHIEVED;
} else {
careplanResource.setStatus(CarePlanStatusEnum.ACTIVE);
activityStatus = CarePlanActivityStatusEnum.IN_PROGRESS;
goalStatus = GoalStatusEnum.IN_PROGRESS;
}
if (!carePlan.activities.isEmpty()) {
for (Code activity : carePlan.activities) {
Activity activityComponent = new Activity();
ActivityDetail activityDetailComponent = new ActivityDetail();
activityDetailComponent.setStatus(activityStatus);
activityDetailComponent.setCode(mapCodeToCodeableConcept(activity, SNOMED_URI));
activityDetailComponent.setProhibited(new BooleanDt(false));
activityComponent.setDetail(activityDetailComponent);
careplanResource.addActivity(activityComponent);
}
}
if (!carePlan.reasons.isEmpty()) {
// Only one element in list
Code reason = carePlan.reasons.get(0);
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
// Only one element in list
CodingDt coding = condition.getCode().getCoding().get(0);
if (reason.code.equals(coding.getCode())) {
careplanResource.addAddresses().setReference(entry.getFullUrl());
}
}
}
}
for (JsonObject goal : carePlan.goals) {
Entry goalEntry = caregoal(bundle, goalStatus, goal);
careplanResource.addGoal().setReference(goalEntry.getFullUrl());
}
return newEntry(bundle, careplanResource);
}
/**
* Map the given ImagingStudy to a FHIR ImagingStudy resource, and add it to the given Bundle.
*
* @param personEntry
* The Entry for the Person
* @param bundle
* Bundle to add the ImagingStudy to
* @param encounterEntry
* Current Encounter entry
* @param imagingStudy
* The ImagingStudy to map to FHIR and add to the bundle
* @return The added Entry
*/
private static Entry imagingStudy(Entry personEntry, Bundle bundle, Entry encounterEntry,
ImagingStudy imagingStudy) {
ca.uhn.fhir.model.dstu2.resource.ImagingStudy imagingStudyResource =
new ca.uhn.fhir.model.dstu2.resource.ImagingStudy();
OidDt studyUid = new OidDt();
studyUid.setValue("urn:oid:" + imagingStudy.dicomUid);
imagingStudyResource.setUid(studyUid);
imagingStudyResource.setPatient(new ResourceReferenceDt(personEntry.getFullUrl()));
DateTimeDt startDate = new DateTimeDt(new Date(imagingStudy.start));
imagingStudyResource.setStarted(startDate);
// Convert the series into their FHIR equivalents
int numberOfSeries = imagingStudy.series.size();
imagingStudyResource.setNumberOfSeries(new UnsignedIntDt(numberOfSeries));
List<Series> seriesResourceList = new ArrayList<Series>();
int totalNumberOfInstances = 0;
int seriesNo = 1;
for (ImagingStudy.Series series : imagingStudy.series) {
Series seriesResource = new Series();
OidDt seriesUid = new OidDt();
seriesUid.setValue("urn:oid:" + series.dicomUid);
seriesResource.setUid(seriesUid);
seriesResource.setNumber(new UnsignedIntDt(seriesNo));
seriesResource.setStarted(startDate);
seriesResource.setAvailability(InstanceAvailabilityEnum.UNAVAILABLE);
CodeableConceptDt modalityConcept = mapCodeToCodeableConcept(series.modality, DICOM_DCM_URI);
seriesResource.setModality(modalityConcept.getCoding().get(0));
CodeableConceptDt bodySiteConcept = mapCodeToCodeableConcept(series.bodySite, SNOMED_URI);
seriesResource.setBodySite(bodySiteConcept.getCoding().get(0));
// Convert the images in each series into their FHIR equivalents
int numberOfInstances = series.instances.size();
seriesResource.setNumberOfInstances(new UnsignedIntDt(numberOfInstances));
totalNumberOfInstances += numberOfInstances;
List<SeriesInstance> instanceResourceList = new ArrayList<SeriesInstance>();
int instanceNo = 1;
for (ImagingStudy.Instance instance : series.instances) {
SeriesInstance instanceResource = new SeriesInstance();
OidDt instanceUid = new OidDt();
instanceUid.setValue("urn:oid:" + instance.dicomUid);
instanceResource.setUid(instanceUid);
instanceResource.setTitle(instance.title);
OidDt sopOid = new OidDt();
sopOid.setValue("urn:oid:" + instance.sopClass.code);
instanceResource.setSopClass(sopOid);
instanceResource.setNumber(new UnsignedIntDt(instanceNo));
instanceResourceList.add(instanceResource);
instanceNo += 1;
}
seriesResource.setInstance(instanceResourceList);
seriesResourceList.add(seriesResource);
seriesNo += 1;
}
imagingStudyResource.setSeries(seriesResourceList);
imagingStudyResource.setNumberOfInstances(totalNumberOfInstances);
return newEntry(bundle, imagingStudyResource);
}
/**
* Map the Provider into a FHIR Organization resource, and add it to the given Bundle.
*
* @param bundle
* The Bundle to add to
* @param provider
* The Provider
* @return The added Entry
*/
private static Entry provider(Bundle bundle, Provider provider) {
ca.uhn.fhir.model.dstu2.resource.Organization organizationResource =
new ca.uhn.fhir.model.dstu2.resource.Organization();
CodeableConceptDt organizationType = mapCodeToCodeableConcept(
new Code("http://hl7.org/fhir/ValueSet/organization-type", "prov", "Healthcare Provider"),
"Healthcare Provider");
organizationResource.addIdentifier().setSystem("https://github.com/synthetichealth/synthea")
.setValue((String) provider.getResourceID());
organizationResource.setName(provider.name);
organizationResource.setType(organizationType);
AddressDt address = new AddressDt()
.addLine(provider.address)
.setCity(provider.city)
.setPostalCode(provider.zip)
.setState(provider.state);
if (COUNTRY_CODE != null) {
address.setCountry(COUNTRY_CODE);
}
organizationResource.addAddress(address);
if (provider.phone != null && !provider.phone.isEmpty()) {
ContactPointDt contactPoint = new ContactPointDt()
.setSystem(ContactPointSystemEnum.PHONE)
.setValue(provider.phone);
organizationResource.addTelecom(contactPoint);
}
return newEntry(bundle, organizationResource);
}
/*
* Map the JsonObject into a FHIR Goal resource, and add it to the given Bundle.
*
* @param bundle The Bundle to add to
*
* @param goalStatus The GoalStatus
*
* @param goal The JsonObject
*
* @return The added Entry
*/
private static Entry caregoal(Bundle bundle, GoalStatusEnum goalStatus, JsonObject goal) {
ca.uhn.fhir.model.dstu2.resource.Goal goalResource =
new ca.uhn.fhir.model.dstu2.resource.Goal();
goalResource.setStatus(goalStatus);
if (goal.has("text")) {
goalResource.setDescription(goal.get("text").getAsString());
} else if (goal.has("codes")) {
JsonObject code = goal.get("codes").getAsJsonArray().get(0).getAsJsonObject();
goalResource.setDescription(code.get("display").getAsString());
} else if (goal.has("observation")) {
// build up our own text from the observation condition, similar to the graphviz logic
JsonObject logic = goal.get("observation").getAsJsonObject();
String[] text = {
logic.get("codes").getAsJsonArray().get(0).getAsJsonObject().get("display").getAsString(),
logic.get("operator").getAsString(), logic.get("value").getAsString() };
goalResource.setDescription(String.join(" ", text));
}
if (goal.has("addresses")) {
for (JsonElement reasonElement : goal.get("addresses").getAsJsonArray()) {
if (reasonElement instanceof JsonObject) {
JsonObject reasonObject = reasonElement.getAsJsonObject();
String reasonCode = reasonObject.get("codes").getAsJsonObject().get("SNOMED-CT")
.getAsJsonArray().get(0).getAsString();
for (Entry entry : bundle.getEntry()) {
if (entry.getResource().getResourceName().equals("Condition")) {
Condition condition = (Condition) entry.getResource();
// Only one element in list
CodingDt coding = condition.getCode().getCoding().get(0);
if (reasonCode.equals(coding.getCode())) {
goalResource.addAddresses().setReference(entry.getFullUrl());
}
}
}
}
}
}
return newEntry(bundle, goalResource);
}
/**
* Convert the unit into a UnitsOfTime.
*
* @param unit
* unit String
* @return a UnitsOfTime representing the given unit
*/
private static UnitsOfTimeEnum convertUcumCode(String unit) {
// From: http://hl7.org/fhir/ValueSet/units-of-time
switch (unit) {
case "seconds":
return UnitsOfTimeEnum.S;
case "minutes":
return UnitsOfTimeEnum.MIN;
case "hours":
return UnitsOfTimeEnum.H;
case "days":
return UnitsOfTimeEnum.D;
case "weeks":
return UnitsOfTimeEnum.WK;
case "months":
return UnitsOfTimeEnum.MO;
case "years":
return UnitsOfTimeEnum.A;
default:
return null;
}
}
/**
* Convert the timestamp into a FHIR DateType or DateTimeType.
*
* @param datetime
* Timestamp
* @param time
* If true, return a DateTimeDt; if false, return a DateDt.
* @return a DateDt or DateTimeDt representing the given timestamp
*/
private static IDatatype convertFhirDateTime(long datetime, boolean time) {
Date date = new Date(datetime);
if (time) {
return new DateTimeDt(date);
} else {
return new DateDt(date);
}
}
/**
* Helper function to convert a Code into a CodeableConceptDt. Takes an optional system, which
* replaces the Code.system in the resulting CodeableConceptDt if not null.
*
* @param from
* The Code to create a CodeableConcept from.
* @param system
* The system identifier, such as a URI. Optional; may be null.
* @return The converted CodeableConcept
*/
private static CodeableConceptDt mapCodeToCodeableConcept(Code from, String system) {
CodeableConceptDt to = new CodeableConceptDt();
if (from.display != null) {
to.setText(from.display);
}
CodingDt coding = new CodingDt();
coding.setCode(from.code);
coding.setDisplay(from.display);
if (system == null) {
coding.setSystem(from.system);
} else {
coding.setSystem(system);
}
to.addCoding(coding);
return to;
}
/**
* Helper function to create an Entry for the given Resource within the given Bundle. Sets the
* resourceID to a random UUID, sets the entry's fullURL to that resourceID, and adds the entry to
* the bundle.
*
* @param bundle
* The Bundle to add the Entry to
* @param resource
* Resource the new Entry should contain
* @return the created Entry
*/
private static Entry newEntry(Bundle bundle, BaseResource resource) {
Entry entry = bundle.addEntry();
String resourceID = UUID.randomUUID().toString();
resource.setId(resourceID);
entry.setFullUrl("urn:uuid:" + resourceID);
entry.setResource(resource);
if (TRANSACTION_BUNDLE) {
EntryRequest request = entry.getRequest();
request.setMethod(HTTPVerbEnum.POST);
request.setUrl(resource.getResourceName());
entry.setRequest(request);
}
return entry;
}
}
| swapped latitude and longitude
| src/main/java/org/mitre/synthea/export/FhirDstu2.java | swapped latitude and longitude | <ide><path>rc/main/java/org/mitre/synthea/export/FhirDstu2.java
<ide> addrResource.setCountry(COUNTRY_CODE);
<ide> }
<ide>
<del> DirectPosition2D coord = (DirectPosition2D) person.attributes.get(Person.COORDINATE);
<add> DirectPosition2D coord = person.getLatLon();
<ide> if (coord != null) {
<ide> ExtensionDt geolocationExtension = new ExtensionDt();
<ide> geolocationExtension.setUrl("http://hl7.org/fhir/StructureDefinition/geolocation");
<ide> ExtensionDt longitudeExtension = new ExtensionDt();
<ide> latitudeExtension.setUrl("latitude");
<ide> longitudeExtension.setUrl("longitude");
<del> latitudeExtension.setValue(new DecimalDt(coord.getY()));
<del> longitudeExtension.setValue(new DecimalDt(coord.getX()));
<add> latitudeExtension.setValue(new DecimalDt(coord.getX()));
<add> longitudeExtension.setValue(new DecimalDt(coord.getY()));
<ide> geolocationExtension.addUndeclaredExtension(latitudeExtension);
<ide> geolocationExtension.addUndeclaredExtension(longitudeExtension);
<ide> addrResource.addUndeclaredExtension(geolocationExtension); |
|
Java | mit | fa64a0ef93ccf852147fb3f69f3d334b705acbbf | 0 | hayaksu/Android_IM_App | package com.TextMining;
import com.parse.CountCallback;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
/**
* Created by Marwa Khan on 20/3/2016.
* Class Description: This class should remove any ignore words in the message
* Note: the ignore words list is in the server database and it include a list of stop words such as "من"
*/
public class WordNormalization {
//Method to remove the words
// Input: String
// Output: String
public static String RemoveWords(String str)
{
String newStr = "";
if (str.length() == 1 && str.matches("([\u0600-\u06FF])|([0-9])|([a-zA-Z])"))
return newStr;
if (!str.contains(" ")) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("IgnoreWordsDatabase");
//Remove the Word
query.whereEqualTo("StopWord", str);
try {
List<ParseObject> OutputList = query.find();
if (OutputList.size() == 0)
newStr += str;
} catch (ParseException e) {
e.printStackTrace();
}
}
else
{
newStr = RemoveConnectedWords(str);
}
return newStr;
}
// Method to check and remove connected ignore words ex. "in-the" after formmating is "in the"
// Thus. we need further splitting and checking in these cases
private static String RemoveConnectedWords(String str)
{
String[] ArrayStr = str.split(" ");
String newString= "";
ParseQuery<ParseObject> query = ParseQuery.getQuery("IgnoreWordsDatabase");
for (int index= 0; index < ArrayStr.length; ++index)
{
if(!ArrayStr[index].equals(" ")) {
query.whereEqualTo("StopWord", ArrayStr[index]);
try {
List<ParseObject> OutputList = query.find();
if (OutputList.size() == 0)
newString += ArrayStr[index] + " ";
} catch (ParseException e) {
e.printStackTrace();
}
}
}
if (!newString.isEmpty())
newString = newString.substring(0, newString.length() - 1);
return newString;
}
public static String FilterWords(String str) {
if (str.matches("^[A-Za-z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$"))
return str;
//Remove Diacrities + Shaddah
String CurrentStr = str.replaceAll("[\u064E\u064B\u064F\u064C\u0650\u064D\u0652\u0640\u0651]", "");
CurrentStr = CurrentStr.toLowerCase();
//Replace Hamza
CurrentStr = CurrentStr.replaceAll("[\u0623\u0625\u0622]", "\u0627");
//Remove Taa Marbutah
CurrentStr = CurrentStr.replaceAll("\u0629", "\u0647");
String regex = "(https?|ftp|file){1}:?/?/?[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
String regex2 = "(www.){1}?/?/?[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
if ((CurrentStr.toLowerCase().contains("http") && CurrentStr.matches(regex) == false) || (CurrentStr.contains("www") && CurrentStr.matches(regex2) == false ) )
{
String regexToSplit = "(?=[^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]])(?<=[.|\u0600])";
String[] testingURL = CurrentStr.replaceAll(regexToSplit, " ").split(" ");
String newStr = "";
for(int index = 0; index < testingURL.length; ++index)
{
if (testingURL[index].contains("http") || testingURL[index].contains("www")) {
if (!testingURL[index].matches(regex))
{
testingURL[index] = testingURL[index].substring(0, testingURL[index].length() - 1);
PrepareData.HasURL = true;
}
}
newStr +=testingURL[index] + " ";
}
if (!newStr.isEmpty())
newStr = newStr.substring(0, newStr.length() - 1);
return newStr;
}
if (!CurrentStr.matches(regex) && !CurrentStr.matches(regex2)) {
CurrentStr = CurrentStr.replaceAll("[^A-Z|a-z|0-9|\u0621-\u065F|\u066E-\u06D3|\u06D5]", " ");
if (CurrentStr.startsWith(" "))
CurrentStr = CurrentStr.substring(1);
else if (CurrentStr.endsWith(" "))
CurrentStr = CurrentStr.substring(0, CurrentStr.length() - 1);
CurrentStr = CurrentStr.replaceAll("[0-9@%$!~><*-]", " ");
CurrentStr = CurrentStr.replaceAll("\\s+", " ");
}
return CurrentStr;
}
}
| MessagingTutorialSkeleton/src/main/java/com/TextMining/WordNormalization.java | package com.TextMining;
import com.parse.CountCallback;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
/**
* Created by Sakurmi on 11/3/2015.
*/
public class WordNormalization {
public static String RemoveWords(String str)
{
String newStr = "";
if (str.length() == 1 && str.matches("([\u0600-\u06FF])|([0-9])|([a-zA-Z])"))
return newStr;
if (!str.contains(" ")) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("IgnoreWordsDatabase");
//Remove the Word
query.whereEqualTo("StopWord", str);
try {
List<ParseObject> OutputList = query.find();
//System.out.println("Current:" + str + "-");
//System.out.println("Current:" + OutputList.size());
if (OutputList.size() == 0)
newStr += str;
//System.out.println(newStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
else
{
newStr = RemoveConnectedWords(str);
}
//System.out.println("calling Fun"+newStr);
return newStr;
}
private static String RemoveConnectedWords(String str)
{
String[] ArrayStr = str.split(" ");
String newString= "";
ParseQuery<ParseObject> query = ParseQuery.getQuery("IgnoreWordsDatabase");
for (int index= 0; index < ArrayStr.length; ++index)
{
if(!ArrayStr[index].equals(" ")) {
query.whereEqualTo("StopWord", ArrayStr[index]);
try {
List<ParseObject> OutputList = query.find();
//System.out.println("Current:" + ArrayStr[index] + "-");
//System.out.println("Current:" + OutputList.size());
//System.out.println(OutputList.size() == 0);
if (OutputList.size() == 0)
newString += ArrayStr[index] + " ";
// System.out.println("kkkk:" + newString);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
// System.out.println("Befor sub"+newString +"**");
if (!newString.isEmpty())
newString = newString.substring(0, newString.length() - 1);
// System.out.println("Aftter sub"+newString);
return newString;
}
public static String FilterWords(String str) {
if (str.matches("^[A-Za-z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$"))
return str;
//Remove Diacrities + Shaddah
String CurrentStr = str.replaceAll("[\u064E\u064B\u064F\u064C\u0650\u064D\u0652\u0640\u0651]", "");
CurrentStr = CurrentStr.toLowerCase();
//Replace Hamza
CurrentStr = CurrentStr.replaceAll("[\u0623\u0625\u0622]", "\u0627");
//Remove Taa Marbutah
CurrentStr = CurrentStr.replaceAll("\u0629", "\u0647");
String regex = "(https?|ftp|file){1}:?/?/?[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
String regex2 = "(www.){1}?/?/?[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
if ((CurrentStr.toLowerCase().contains("http") && CurrentStr.matches(regex) == false) || (CurrentStr.contains("www") && CurrentStr.matches(regex2) == false ) )
{
String regexToSplit = "(?=[^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]])(?<=[.|\u0600])";
String[] testingURL = CurrentStr.replaceAll(regexToSplit, " ").split(" ");
String newStr = "";
for(int index = 0; index < testingURL.length; ++index)
{
if (testingURL[index].contains("http") || testingURL[index].contains("www")) {
if (!testingURL[index].matches(regex))
{
testingURL[index] = testingURL[index].substring(0, testingURL[index].length() - 1);
PrepareData.HasURL = true;
// CheckPhishingURL (testingURL[index]);
}
}
newStr +=testingURL[index] + " ";
}
if (!newStr.isEmpty())
newStr = newStr.substring(0, newStr.length() - 1);
return newStr;
}
if (!CurrentStr.matches(regex) && !CurrentStr.matches(regex2)) {
CurrentStr = CurrentStr.replaceAll("[^A-Z|a-z|0-9|\u0621-\u065F|\u066E-\u06D3|\u06D5]", " ");
if (CurrentStr.startsWith(" "))
CurrentStr = CurrentStr.substring(1);
else if (CurrentStr.endsWith(" "))
CurrentStr = CurrentStr.substring(0, CurrentStr.length() - 1);
CurrentStr = CurrentStr.replaceAll("[0-9@%$!~><*-]", " ");
CurrentStr = CurrentStr.replaceAll("\\s+", " ");
}
//CurrentStr;
return CurrentStr;
}
/* public static boolean CheckPhishingURL(String url)
{
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments += URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("myapp", "UTF-8") + "&";
arguments +=URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("12341234", "UTF-8") + "&";
arguments +=URLEncoder.encode("appver", "UTF-8") + "=" + URLEncoder.encode("1.5.2", "UTF-8") + "&";
arguments +=URLEncoder.encode("pver", "UTF-8") + "=" + URLEncoder.encode("3.0", "UTF-8");
// Construct the url object representing cgi script
URL url = new URL(baseURL + "?" + arguments);
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print("2");
pout.println();
pout.print("http://www.google.com");
pout.println();
pout.print("http://www.facebook.com");
pout.close();
return true;
}*/
}
| Update WordNormalization.java
Code cleaning + Class description | MessagingTutorialSkeleton/src/main/java/com/TextMining/WordNormalization.java | Update WordNormalization.java | <ide><path>essagingTutorialSkeleton/src/main/java/com/TextMining/WordNormalization.java
<ide> import java.util.List;
<ide>
<ide> /**
<del> * Created by Sakurmi on 11/3/2015.
<add> * Created by Marwa Khan on 20/3/2016.
<add> * Class Description: This class should remove any ignore words in the message
<add> * Note: the ignore words list is in the server database and it include a list of stop words such as "من"
<ide> */
<ide> public class WordNormalization {
<ide>
<add>
<add> //Method to remove the words
<add> // Input: String
<add> // Output: String
<ide> public static String RemoveWords(String str)
<ide> {
<ide> String newStr = "";
<ide>
<ide> try {
<ide> List<ParseObject> OutputList = query.find();
<del>
<del> //System.out.println("Current:" + str + "-");
<del> //System.out.println("Current:" + OutputList.size());
<del>
<add>
<ide> if (OutputList.size() == 0)
<ide> newStr += str;
<del>
<del> //System.out.println(newStr);
<del>
<add>
<ide> } catch (ParseException e) {
<ide> e.printStackTrace();
<ide> }
<ide> newStr = RemoveConnectedWords(str);
<ide> }
<ide>
<del> //System.out.println("calling Fun"+newStr);
<del>
<ide> return newStr;
<ide> }
<ide>
<del>
<add> // Method to check and remove connected ignore words ex. "in-the" after formmating is "in the"
<add> // Thus. we need further splitting and checking in these cases
<ide> private static String RemoveConnectedWords(String str)
<ide> {
<ide> String[] ArrayStr = str.split(" ");
<ide> try {
<ide> List<ParseObject> OutputList = query.find();
<ide>
<del> //System.out.println("Current:" + ArrayStr[index] + "-");
<del> //System.out.println("Current:" + OutputList.size());
<del>
<del> //System.out.println(OutputList.size() == 0);
<del>
<ide> if (OutputList.size() == 0)
<ide> newString += ArrayStr[index] + " ";
<del>
<del>// System.out.println("kkkk:" + newString);
<ide>
<ide> } catch (ParseException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<ide> }
<del> // System.out.println("Befor sub"+newString +"**");
<ide>
<ide> if (!newString.isEmpty())
<ide> newString = newString.substring(0, newString.length() - 1);
<ide>
<del> // System.out.println("Aftter sub"+newString);
<ide>
<ide> return newString;
<ide> }
<ide> testingURL[index] = testingURL[index].substring(0, testingURL[index].length() - 1);
<ide>
<ide> PrepareData.HasURL = true;
<del> // CheckPhishingURL (testingURL[index]);
<ide> }
<ide> }
<ide>
<ide> CurrentStr = CurrentStr.replaceAll("[0-9@%$!~><*-]", " ");
<ide> CurrentStr = CurrentStr.replaceAll("\\s+", " ");
<ide> }
<del>
<del> //CurrentStr;
<ide> return CurrentStr;
<ide> }
<del>
<del> /* public static boolean CheckPhishingURL(String url)
<del> {
<del> String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
<del>
<del> String arguments = "";
<del> arguments += URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("myapp", "UTF-8") + "&";
<del> arguments +=URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("12341234", "UTF-8") + "&";
<del> arguments +=URLEncoder.encode("appver", "UTF-8") + "=" + URLEncoder.encode("1.5.2", "UTF-8") + "&";
<del> arguments +=URLEncoder.encode("pver", "UTF-8") + "=" + URLEncoder.encode("3.0", "UTF-8");
<del>
<del>// Construct the url object representing cgi script
<del> URL url = new URL(baseURL + "?" + arguments);
<del>
<del>// Get a URLConnection object, to write to POST method
<del> URLConnection connect = url.openConnection();
<del>
<del>// Specify connection settings
<del> connect.setDoInput(true);
<del> connect.setDoOutput(true);
<del>
<del>// Get an output stream for writing
<del> OutputStream output = connect.getOutputStream();
<del> PrintStream pout = new PrintStream (output);
<del> pout.print("2");
<del> pout.println();
<del> pout.print("http://www.google.com");
<del> pout.println();
<del> pout.print("http://www.facebook.com");
<del> pout.close();
<del>
<del> return true;
<del> }*/
<ide> } |
|
Java | agpl-3.0 | 60d7c2fbaa7c0d6ecb195d96d05e7f848e0c1a80 | 0 | ngaut/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,ngaut/sql-layer,relateiq/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,shunwang/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,relateiq/sql-layer,ngaut/sql-layer,jaytaylor/sql-layer,wfxiang08/sql-layer-1 | package com.akiban.cserver.util;
import com.akiban.cserver.message.BulkLoadRequest;
import com.akiban.message.AkibaConnection;
import com.akiban.message.MessageRegistry;
import com.akiban.network.AkibaNetworkHandler;
import com.akiban.network.CommEventNotifier;
import com.akiban.network.NetworkHandlerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BulkLoaderClient
{
public static void main(String[] args) throws Exception
{
new BulkLoaderClient(args).run();
}
private void run() throws Exception
{
startServer();
AkibaNetworkHandler networkHandler =
NetworkHandlerFactory.getHandler(cserverHost, Integer.toString(cserverPort), null);
AkibaConnection connection = AkibaConnection.createConnection(networkHandler);
try {
BulkLoadRequest request = new BulkLoadRequest(dbHost,
dbPort,
dbUser,
dbPassword,
groups,
artifactsSchema,
sourceSchemas,
resume,
cleanup);
connection.send(request);
} finally {
NetworkHandlerFactory.closeNetwork();
}
}
private BulkLoaderClient(String[] args) throws Exception
{
int a = 0;
try {
while (a < args.length) {
String flag = args[a++];
if (flag.equals("--resume")) {
resume = true;
} else if (flag.equals("--cleanup")) {
cleanup = true;
} else if (flag.equals("--temp")) {
artifactsSchema = args[a++];
} else if (flag.equals("--mysql")) {
String hostAndPort = args[a++];
int colon = hostAndPort.indexOf(':');
if (colon < 0) {
dbHost = hostAndPort;
dbPort = DEFAULT_MYSQL_PORT;
} else {
dbHost = hostAndPort.substring(colon);
dbPort = Integer.parseInt(hostAndPort.substring(colon + 1));
}
} else if (flag.equals("--user")) {
dbUser = args[a++];
} else if (flag.equals("--password")) {
dbPassword = args[a++];
} else if (flag.equals("--source")) {
String targetAndSource = args[a++];
int colon = targetAndSource.indexOf(':');
if (colon < 0) {
usage(null);
}
String target = targetAndSource.substring(0, colon);
String source = targetAndSource.substring(colon + 1);
sourceSchemas.put(target, source);
} else if (flag.equals("--cserver")) {
String hostAndPort = args[a++];
int colon = hostAndPort.indexOf(':');
if (colon < 0) {
usage(null);
} else {
cserverHost = hostAndPort.substring(0, colon);
cserverPort = Integer.parseInt(hostAndPort.substring(colon + 1));
}
} else if (flag.equals("--group")) {
groups.add(args[a++]);
} else {
usage(null);
}
}
} catch (Exception e) {
usage(e);
}
if (dbHost == null || dbUser == null || groups.isEmpty()) {
usage(null);
}
}
private ChannelNotifier startServer()
{
MessageRegistry.reset();
MessageRegistry.initialize();
MessageRegistry.only().registerModule("com.akiban.cserver.message");
MessageRegistry.only().registerModule("com.akiban.message");
ChannelNotifier notifier = new ChannelNotifier();
NetworkHandlerFactory.initializeNetwork(LOCALHOST,
Integer.toString(BULK_LOADER_CLIENT_LISTENER_PORT),
notifier);
return notifier;
}
private static void usage(Exception e) throws Exception
{
for (String line : USAGE) {
System.err.println(line);
}
if (null != e) {
System.err.println(e.getMessage());
}
System.exit(1);
}
private static final String[] USAGE = {
"aload --mysql MYSQL_HOST[:MYSQL_PORT] --user USER [--password PASSWORD] (--group GROUP)+ " +
"--cserver CSERVER_HOST:CSERVER_PORT " +
"--temp TEMP_SCHEMA (--source TARGET_SCHEMA:SOURCE_SCHEMA)* [--resume] [--nocleanup]",
"",
"Copies data from a MySQL database into a chunkserver. Data is transformed in the MySQL database, before it ",
"is written to the chunkserver. ",
"",
"The database being copied is located at MYSQL_HOST:MYSQL_PORT, and is accessed as USER, identified by ",
"PASSWORD if provided. Only the named GROUPs will be copied. At least one GROUP must be specified, and ",
"multiple GROUPs may be specified, (repeating the --group flag for each).",
"",
"The chunkserver being loaded is located at CSERVER_HOST:CSERVER_PORT.",
"The database being loaded must already have a schema installed. Loading will add data to presumably empty tables.",
"By default, the source and target schema names are assumed to match. If they don't, then source schema names",
"can be specified using one or more --source specifications. For example --source abc:def will copy data from",
"the abc schema of the database at HOST:PORT into the def schema locally. Table names must match in source and",
"target schemas.",
"",
"If --resume is specified, then the previously attempted migration, whose state is stored in TEMP_SCHEMA, ",
"is resumed. If --resume is not specified, then any state from a previous load, saved in TEMP_SCHEMA, is lost.",
"",
"If --nocleanup is specified, then the TEMP_SCHEMA is not deleted when the load completes.",
""
};
private static final String LOCALHOST = "localhost";
private static final int DEFAULT_MYSQL_PORT = 3306;
private static final int BULK_LOADER_CLIENT_LISTENER_PORT = 9999; // because there has to be one
private String cserverHost;
private int cserverPort;
private boolean resume = false;
private boolean cleanup = false;
private String artifactsSchema;
private String dbHost;
private int dbPort;
private String dbUser;
private String dbPassword;
private final Map<String, String> sourceSchemas = new HashMap<String, String>();
private final List<String> groups = new ArrayList<String>();
// Inner classes
public class ChannelNotifier implements CommEventNotifier
{
@Override
public void onConnect(AkibaNetworkHandler handler)
{
}
@Override
public void onDisconnect(AkibaNetworkHandler handler)
{
handler.disconnectWorker();
}
}
}
| src/main/java/com/akiban/cserver/util/BulkLoaderClient.java | package com.akiban.cserver.util;
import com.akiban.cserver.message.BulkLoadRequest;
import com.akiban.message.AkibaConnection;
import com.akiban.message.MessageRegistry;
import com.akiban.network.AkibaNetworkHandler;
import com.akiban.network.CommEventNotifier;
import com.akiban.network.NetworkHandlerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BulkLoaderClient
{
public static void main(String[] args) throws Exception
{
new BulkLoaderClient(args).run();
}
private void run() throws Exception
{
startServer();
AkibaNetworkHandler networkHandler =
NetworkHandlerFactory.getHandler(cserverHost, Integer.toString(cserverPort), null);
AkibaConnection connection = AkibaConnection.createConnection(networkHandler);
try {
BulkLoadRequest request = new BulkLoadRequest(dbHost,
dbPort,
dbUser,
dbPassword,
groups,
artifactsSchema,
sourceSchemas,
resume,
cleanup);
connection.send(request);
} finally {
NetworkHandlerFactory.closeNetwork();
}
}
private BulkLoaderClient(String[] args) throws Exception
{
int a = 0;
try {
while (a < args.length) {
String flag = args[a++];
if (flag.equals("--resume")) {
resume = true;
} else if (flag.equals("--cleanup")) {
cleanup = true;
} else if (flag.equals("--temp")) {
artifactsSchema = args[a++];
} else if (flag.equals("--mysql")) {
String hostAndPort = args[a++];
int colon = hostAndPort.indexOf(':');
if (colon < 0) {
dbHost = hostAndPort;
dbPort = DEFAULT_MYSQL_PORT;
} else {
dbHost = hostAndPort.substring(colon);
dbPort = Integer.parseInt(hostAndPort.substring(colon + 1));
}
} else if (flag.equals("--user")) {
dbUser = args[a++];
} else if (flag.equals("--password")) {
dbPassword = args[a++];
} else if (flag.equals("--source")) {
String targetAndSource = args[a++];
int colon = targetAndSource.indexOf(':');
if (colon < 0) {
usage(null);
}
String target = targetAndSource.substring(0, colon);
String source = targetAndSource.substring(colon + 1);
sourceSchemas.put(target, source);
} else if (flag.equals("--cserver")) {
String hostAndPort = args[a++];
int colon = hostAndPort.indexOf(':');
if (colon < 0) {
usage(null);
} else {
cserverHost = hostAndPort.substring(0, colon);
cserverPort = Integer.parseInt(hostAndPort.substring(colon + 1));
}
} else if (flag.equals("--group")) {
groups.add(args[a++]);
} else {
usage(null);
}
}
} catch (Exception e) {
usage(e);
}
if (dbHost == null || dbUser == null || groups.isEmpty()) {
usage(null);
}
}
private ChannelNotifier startServer()
{
MessageRegistry.reset();
MessageRegistry.initialize();
MessageRegistry.only().registerModule("com.akiban.cserver.message");
MessageRegistry.only().registerModule("com.akiban.message");
ChannelNotifier notifier = new ChannelNotifier();
NetworkHandlerFactory.initializeNetwork(LOCALHOST,
Integer.toString(BULK_LOADER_CLIENT_LISTENER_PORT),
notifier);
return notifier;
}
private static void usage(Exception e) throws Exception
{
for (String line : USAGE) {
System.err.println(line);
}
System.err.println(e.getMessage());
System.exit(1);
}
private static final String[] USAGE = {
"aload --mysql MYSQL_HOST[:MYSQL_PORT] --user USER [--password PASSWORD] (--group GROUP)+ " +
"--cserver CSERVER_HOST:CSERVER_PORT " +
"--temp TEMP_SCHEMA (--source TARGET_SCHEMA:SOURCE_SCHEMA)* [--resume] [--nocleanup]",
"",
"Copies data from a MySQL database into a chunkserver. Data is transformed in the MySQL database, before it ",
"is written to the chunkserver. ",
"",
"The database being copied is located at MYSQL_HOST:MYSQL_PORT, and is accessed as USER, identified by ",
"PASSWORD if provided. Only the named GROUPs will be copied. At least one GROUP must be specified, and ",
"multiple GROUPs may be specified, (repeating the --group flag for each).",
"",
"The chunkserver being loaded is located at CSERVER_HOST:CSERVER_PORT.",
"The database being loaded must already have a schema installed. Loading will add data to presumably empty tables.",
"By default, the source and target schema names are assumed to match. If they don't, then source schema names",
"can be specified using one or more --source specifications. For example --source abc:def will copy data from",
"the abc schema of the database at HOST:PORT into the def schema locally. Table names must match in source and",
"target schemas.",
"",
"If --resume is specified, then the previously attempted migration, whose state is stored in TEMP_SCHEMA, ",
"is resumed. If --resume is not specified, then any state from a previous load, saved in TEMP_SCHEMA, is lost.",
"",
"If --nocleanup is specified, then the TEMP_SCHEMA is not deleted when the load completes.",
""
};
private static final String LOCALHOST = "localhost";
private static final int DEFAULT_MYSQL_PORT = 3306;
private static final int BULK_LOADER_CLIENT_LISTENER_PORT = 9999; // because there has to be one
private String cserverHost;
private int cserverPort;
private boolean resume = false;
private boolean cleanup = false;
private String artifactsSchema;
private String dbHost;
private int dbPort;
private String dbUser;
private String dbPassword;
private final Map<String, String> sourceSchemas = new HashMap<String, String>();
private final List<String> groups = new ArrayList<String>();
// Inner classes
public class ChannelNotifier implements CommEventNotifier
{
@Override
public void onConnect(AkibaNetworkHandler handler)
{
}
@Override
public void onDisconnect(AkibaNetworkHandler handler)
{
handler.disconnectWorker();
}
}
}
| Small fix to bulk loading client to check if exception passed to usage method is null before using it. | src/main/java/com/akiban/cserver/util/BulkLoaderClient.java | Small fix to bulk loading client to check if exception passed to usage method is null before using it. | <ide><path>rc/main/java/com/akiban/cserver/util/BulkLoaderClient.java
<ide> for (String line : USAGE) {
<ide> System.err.println(line);
<ide> }
<del> System.err.println(e.getMessage());
<add> if (null != e) {
<add> System.err.println(e.getMessage());
<add> }
<ide> System.exit(1);
<ide> }
<ide> |
|
Java | mit | error: pathspec 'src/e131_prodcon_dispatchqueue.java' did not match any file(s) known to git
| 25d99a50b3b5612dbef1008b0a9380832e05e391 | 1 | pluton8/java_concurrency_examples | import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A classical, simplified example of the producer and consumer pattern. Here a
* Producer works in its own thread, produces a product every 100 ms., and
* notifies about that its listener. The listener is a Consumer, which processes
* the product. A Consumer has a listener as well to notify it when it's done.
*
* NOTA BENE: in this example, the listener's callback functions are called
* asynchronously and explicitly on the specified DispatchQueue. (The
* DispatchQueue class is a humble and very simple mock of the dispatch_queue_t
* type in Apple's GCD library.) The serial queue implies that one of the
* callbacks will not be called while another one is executing.
*
* How to stop the queue though? In a usual case, the Consumer doesn't care
* exactly which queue it's running in as long as it's the same one for every
* invocation (to get rid of messy synchronization). In this sample, the main
* thread is responsible for creation and shutting down the queue. To know when
* to shut down and join() the queue thread, the main object implements the
* ConsumerListener, and waits until the Consumer is done (using Lock and
* Condition objects). The rest is easy, the object shuts down the queue (with a
* sentinel), and joins its thread.
*
* Created by u on 2014-01-11.
*/
public class e131_prodcon_dispatchqueue {
static interface ProducerListener {
void producerCreatedProduct(Producer producer, int product);
void producerFinished(Producer producer);
}
static class DispatchQueue implements Runnable {
final BlockingQueue<Runnable> runnables =
new LinkedBlockingQueue<Runnable>();
private static final Runnable SENTINEL = new Runnable() {
@Override
public void run() {
}
};
@Override
public void run() {
try {
while (!Thread.interrupted()) {
final Runnable runnable = runnables.take();
if (SENTINEL == runnable) {
break;
}
runnable.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void dispatchAsync(Runnable runnable) {
try {
runnables.put(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void shutdown() {
dispatchAsync(SENTINEL);
}
}
static class Producer implements Runnable {
final DispatchQueue listenerQueue;
ProducerListener listener;
Producer(ProducerListener listener, DispatchQueue listenerQueue) {
this.listener = listener;
this.listenerQueue = listenerQueue;
}
@Override
public void run() {
Logger.log("Starting producer");
for (int i = 0; i < 5; ++i) {
waitForProduct();
Logger.log("Created product %d", i);
if (isListenerReady()) {
final int finalI = i;
listenerQueue.dispatchAsync(new Runnable() {
@Override
public void run() {
listener.producerCreatedProduct(Producer.this,
finalI);
}
});
}
}
if (isListenerReady()) {
listenerQueue.dispatchAsync(new Runnable() {
@Override
public void run() {
listener.producerFinished(Producer.this);
}
});
}
}
private boolean isListenerReady() {
return (listener != null) && (listenerQueue != null);
}
private void waitForProduct() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static interface ConsumerListener {
void consumerFinished(Consumer consumer);
}
static class Consumer implements ProducerListener {
final ConsumerListener listener;
Consumer(ConsumerListener listener) {
this.listener = listener;
}
@Override
public void producerCreatedProduct(Producer producer, int product) {
Logger.log("Producer created product %d", product);
consumeProduct();
Logger.log("Consumed %d, nom-nom", product);
}
private void consumeProduct() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void producerFinished(Producer producer) {
Logger.log("Producer finished");
if (listener != null) {
listener.consumerFinished(this);
}
}
}
static class Sample implements ConsumerListener {
private final Lock lock = new ReentrantLock();
private final Condition finishedCondition = lock.newCondition();
private boolean finished = false;
void run() throws InterruptedException {
DispatchQueue workerQueue = new DispatchQueue();
final Consumer consumer = new Consumer(this);
final Producer producer = new Producer(consumer, workerQueue);
Thread producerThread = new Thread(producer, "ProducerThread");
Thread workerQueueThread = new Thread(workerQueue,
"WorkerQueueThread");
producerThread.start();
workerQueueThread.start();
producerThread.join();
lock.lock();
try {
while (!finished) {
finishedCondition.await();
}
Logger.log("The process is finished, shutting down the queue");
workerQueue.shutdown();
workerQueueThread.join();
} finally {
lock.unlock();
}
}
@Override
public void consumerFinished(Consumer consumer) {
lock.lock();
try {
Logger.log("Consumer finished");
finished = true;
finishedCondition.signal();
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
new Sample().run();
long finish = System.currentTimeMillis();
System.out.println("\nDone in " + (finish - start) + " ms.");
}
}
| src/e131_prodcon_dispatchqueue.java | Producer/consumer sample where the main object shuts down the DispatchQueue
| src/e131_prodcon_dispatchqueue.java | Producer/consumer sample where the main object shuts down the DispatchQueue | <ide><path>rc/e131_prodcon_dispatchqueue.java
<add>import java.util.concurrent.BlockingQueue;
<add>import java.util.concurrent.LinkedBlockingQueue;
<add>import java.util.concurrent.locks.Condition;
<add>import java.util.concurrent.locks.Lock;
<add>import java.util.concurrent.locks.ReentrantLock;
<add>
<add>/**
<add> * A classical, simplified example of the producer and consumer pattern. Here a
<add> * Producer works in its own thread, produces a product every 100 ms., and
<add> * notifies about that its listener. The listener is a Consumer, which processes
<add> * the product. A Consumer has a listener as well to notify it when it's done.
<add> *
<add> * NOTA BENE: in this example, the listener's callback functions are called
<add> * asynchronously and explicitly on the specified DispatchQueue. (The
<add> * DispatchQueue class is a humble and very simple mock of the dispatch_queue_t
<add> * type in Apple's GCD library.) The serial queue implies that one of the
<add> * callbacks will not be called while another one is executing.
<add> *
<add> * How to stop the queue though? In a usual case, the Consumer doesn't care
<add> * exactly which queue it's running in as long as it's the same one for every
<add> * invocation (to get rid of messy synchronization). In this sample, the main
<add> * thread is responsible for creation and shutting down the queue. To know when
<add> * to shut down and join() the queue thread, the main object implements the
<add> * ConsumerListener, and waits until the Consumer is done (using Lock and
<add> * Condition objects). The rest is easy, the object shuts down the queue (with a
<add> * sentinel), and joins its thread.
<add> *
<add> * Created by u on 2014-01-11.
<add> */
<add>public class e131_prodcon_dispatchqueue {
<add> static interface ProducerListener {
<add> void producerCreatedProduct(Producer producer, int product);
<add>
<add> void producerFinished(Producer producer);
<add> }
<add>
<add> static class DispatchQueue implements Runnable {
<add> final BlockingQueue<Runnable> runnables =
<add> new LinkedBlockingQueue<Runnable>();
<add> private static final Runnable SENTINEL = new Runnable() {
<add> @Override
<add> public void run() {
<add> }
<add> };
<add>
<add> @Override
<add> public void run() {
<add> try {
<add> while (!Thread.interrupted()) {
<add> final Runnable runnable = runnables.take();
<add> if (SENTINEL == runnable) {
<add> break;
<add> }
<add> runnable.run();
<add> }
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> public void dispatchAsync(Runnable runnable) {
<add> try {
<add> runnables.put(runnable);
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> public void shutdown() {
<add> dispatchAsync(SENTINEL);
<add> }
<add> }
<add>
<add> static class Producer implements Runnable {
<add> final DispatchQueue listenerQueue;
<add> ProducerListener listener;
<add>
<add> Producer(ProducerListener listener, DispatchQueue listenerQueue) {
<add> this.listener = listener;
<add> this.listenerQueue = listenerQueue;
<add> }
<add>
<add> @Override
<add> public void run() {
<add> Logger.log("Starting producer");
<add> for (int i = 0; i < 5; ++i) {
<add> waitForProduct();
<add> Logger.log("Created product %d", i);
<add>
<add> if (isListenerReady()) {
<add> final int finalI = i;
<add> listenerQueue.dispatchAsync(new Runnable() {
<add> @Override
<add> public void run() {
<add> listener.producerCreatedProduct(Producer.this,
<add> finalI);
<add> }
<add> });
<add> }
<add> }
<add>
<add> if (isListenerReady()) {
<add> listenerQueue.dispatchAsync(new Runnable() {
<add> @Override
<add> public void run() {
<add> listener.producerFinished(Producer.this);
<add> }
<add> });
<add> }
<add> }
<add>
<add> private boolean isListenerReady() {
<add> return (listener != null) && (listenerQueue != null);
<add> }
<add>
<add> private void waitForProduct() {
<add> try {
<add> Thread.sleep(100);
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add> }
<add>
<add> static interface ConsumerListener {
<add> void consumerFinished(Consumer consumer);
<add> }
<add>
<add> static class Consumer implements ProducerListener {
<add> final ConsumerListener listener;
<add>
<add> Consumer(ConsumerListener listener) {
<add> this.listener = listener;
<add> }
<add>
<add> @Override
<add> public void producerCreatedProduct(Producer producer, int product) {
<add> Logger.log("Producer created product %d", product);
<add> consumeProduct();
<add> Logger.log("Consumed %d, nom-nom", product);
<add> }
<add>
<add> private void consumeProduct() {
<add> try {
<add> Thread.sleep(50);
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> @Override
<add> public void producerFinished(Producer producer) {
<add> Logger.log("Producer finished");
<add> if (listener != null) {
<add> listener.consumerFinished(this);
<add> }
<add> }
<add> }
<add>
<add> static class Sample implements ConsumerListener {
<add> private final Lock lock = new ReentrantLock();
<add> private final Condition finishedCondition = lock.newCondition();
<add> private boolean finished = false;
<add>
<add> void run() throws InterruptedException {
<add> DispatchQueue workerQueue = new DispatchQueue();
<add>
<add> final Consumer consumer = new Consumer(this);
<add> final Producer producer = new Producer(consumer, workerQueue);
<add>
<add> Thread producerThread = new Thread(producer, "ProducerThread");
<add> Thread workerQueueThread = new Thread(workerQueue,
<add> "WorkerQueueThread");
<add>
<add> producerThread.start();
<add> workerQueueThread.start();
<add>
<add> producerThread.join();
<add>
<add> lock.lock();
<add> try {
<add> while (!finished) {
<add> finishedCondition.await();
<add> }
<add> Logger.log("The process is finished, shutting down the queue");
<add> workerQueue.shutdown();
<add> workerQueueThread.join();
<add> } finally {
<add> lock.unlock();
<add> }
<add> }
<add>
<add> @Override
<add> public void consumerFinished(Consumer consumer) {
<add> lock.lock();
<add> try {
<add> Logger.log("Consumer finished");
<add> finished = true;
<add> finishedCondition.signal();
<add> } finally {
<add> lock.unlock();
<add> }
<add> }
<add> }
<add>
<add> public static void main(String[] args) throws InterruptedException {
<add> long start = System.currentTimeMillis();
<add>
<add> new Sample().run();
<add>
<add> long finish = System.currentTimeMillis();
<add> System.out.println("\nDone in " + (finish - start) + " ms.");
<add> }
<add>} |
|
JavaScript | mit | b41ba11032b12da9501a742d56b7e17db2d18aba | 0 | template-extension/template-chrome | /* Copyright (C) 2011 Alasdair Mercer, http://neocotic.com/
*
* 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.
*/
/**
* <p>Main controller for the extension and manages all copy requests.</p>
* @author <a href="http://neocotic.com">Alasdair Mercer</a>
* @since 0.2.0.0 - Previously named <code>urlcopy</code>.
* @requires jQuery
* @requires jQuery URL Parser Plugin
* @requires mustache.js
* @namespace
*/
var ext = {
/**
* <p>A list of blacklisted extension IDs who should be prevented from
* making requests to the extension.</p>
* @private
* @type String[]
*/
blacklistedExtensions: [],
/**
* <p>The details of the user's current browser.</p>
* @since 0.1.0.3
* @private
* @type Object
*/
browser: {
/**
* <p>The name of the browser (i.e. <code>Chrome</code>).</p>
* @since 0.1.0.3
* @private
* @type String
*/
title: 'Chrome',
/**
* <p>The version of the browser (e.g. <code>12.0.742.122</code>).</p>
* @since 0.1.0.3
* @private
* @type String
*/
version: ''
},
/**
* <p>The default features to be used by this extension.</p>
* @since 0.1.0.0
* @private
* @type Object[]
*/
defaultFeatures: [{
content: '<a href="{{url}}"' +
'{#doAnchorTarget} target="_blank"{/doAnchorTarget}' +
'{#doAnchorTitle} title="{{title}}"{/doAnchorTitle}' +
'>{{title}}</a>',
enabled: true,
image: 11,
index: 2,
name: '_anchor',
readOnly: true,
shortcut: 'A',
title: chrome.i18n.getMessage('copy_anchor')
}, {
content: '[url={url}]{title}[/url]',
enabled: false,
image: 7,
index: 5,
name: '_bbcode',
readOnly: true,
shortcut: 'B',
title: chrome.i18n.getMessage('copy_bbcode')
}, {
content: '{#encode}{url}{/encode}',
enabled: true,
image: 5,
index: 3,
name: '_encoded',
readOnly: true,
shortcut: 'E',
title: chrome.i18n.getMessage('copy_encoded')
}, {
content: '[{title}]({url})',
enabled: false,
image: 7,
index: 4,
name: '_markdown',
readOnly: true,
shortcut: 'M',
title: chrome.i18n.getMessage('copy_markdown')
}, {
content: '{short}',
enabled: true,
image: 16,
index: 1,
name: '_short',
readOnly: true,
shortcut: 'S',
title: chrome.i18n.getMessage('copy_short')
}, {
content: '{url}',
enabled: true,
image: 8,
index: 0,
name: '_url',
readOnly: true,
shortcut: 'U',
title: chrome.i18n.getMessage('copy_url')
}],
/**
* <p>The list of copy request features supported by the extension.</p>
* <p>This list ordered to match that specified by the user.</p>
* @see ext.updateFeatures
* @type Object[]
*/
features: [],
/**
* <p>The details of the images available as feature icons.</p>
* @since 0.2.0.0
* @private
* @type Object[]
*/
images: [{
file: 'spacer.gif',
id: 0,
name: chrome.i18n.getMessage('feat_none'),
separate: true
}, {
file: 'feat_auction.png',
id: 1,
name: chrome.i18n.getMessage('feat_auction')
}, {
file: 'feat_bug.png',
id: 2,
name: chrome.i18n.getMessage('feat_bug')
}, {
file: 'feat_clipboard.png',
id: 3,
name: chrome.i18n.getMessage('feat_clipboard')
}, {
file: 'feat_clipboard_empty.png',
id: 4,
name: chrome.i18n.getMessage('feat_clipboard_empty')
}, {
file: 'feat_component.png',
id: 5,
name: chrome.i18n.getMessage('feat_component')
}, {
file: 'feat_cookies.png',
id: 6,
name: chrome.i18n.getMessage('feat_cookies')
}, {
file: 'feat_discussion.png',
id: 7,
name: chrome.i18n.getMessage('feat_discussion')
}, {
file: 'feat_globe.png',
id: 8,
name: chrome.i18n.getMessage('feat_globe')
}, {
file: 'feat_google.png',
id: 9,
name: chrome.i18n.getMessage('feat_google')
}, {
file: 'feat_heart.png',
id: 10,
name: chrome.i18n.getMessage('feat_heart')
}, {
file: 'feat_html.png',
id: 11,
name: chrome.i18n.getMessage('feat_html')
}, {
file: 'feat_key.png',
id: 12,
name: chrome.i18n.getMessage('feat_key')
}, {
file: 'feat_lightbulb.png',
id: 13,
name: chrome.i18n.getMessage('feat_lightbulb')
}, {
file: 'feat_lighthouse.png',
id: 14,
name: chrome.i18n.getMessage('feat_lighthouse')
}, {
file: 'feat_lightning.png',
id: 15,
name: chrome.i18n.getMessage('feat_lightning')
}, {
file: 'feat_link.png',
id: 16,
name: chrome.i18n.getMessage('feat_link')
}, {
file: 'feat_linux.png',
id: 17,
name: chrome.i18n.getMessage('feat_linux')
}, {
file: 'feat_mail.png',
id: 18,
name: chrome.i18n.getMessage('feat_mail')
}, {
file: 'feat_newspaper.png',
id: 19,
name: chrome.i18n.getMessage('feat_newspaper')
}, {
file: 'feat_note.png',
id: 20,
name: chrome.i18n.getMessage('feat_note')
}, {
file: 'feat_page.png',
id: 21,
name: chrome.i18n.getMessage('feat_page')
}, {
file: 'feat_plugin.png',
id: 22,
name: chrome.i18n.getMessage('feat_plugin')
}, {
file: 'feat_rss.png',
id: 23,
name: chrome.i18n.getMessage('feat_rss')
}, {
file: 'feat_script.png',
id: 24,
name: chrome.i18n.getMessage('feat_script')
}, {
file: 'feat_scull.png',
id: 25,
name: chrome.i18n.getMessage('feat_scull')
}, {
file: 'feat_sign.png',
id: 26,
name: chrome.i18n.getMessage('feat_sign')
}, {
file: 'feat_siren.png',
id: 27,
name: chrome.i18n.getMessage('feat_siren')
}, {
file: 'feat_star.png',
id: 28,
name: chrome.i18n.getMessage('feat_star')
}, {
file: 'feat_support.png',
id: 29,
name: chrome.i18n.getMessage('feat_support')
}, {
file: 'feat_tag.png',
id: 30,
name: chrome.i18n.getMessage('feat_tag')
}, {
file: 'feat_tags.png',
id: 31,
name: chrome.i18n.getMessage('feat_tags')
}, {
file: 'feat_thumb_down.png',
id: 32,
name: chrome.i18n.getMessage('feat_thumb_down')
}, {
file: 'feat_thumb_up.png',
id: 33,
name: chrome.i18n.getMessage('feat_thumb_up')
}, {
file: 'feat_tools.png',
id: 34,
name: chrome.i18n.getMessage('feat_tools')
}],
/**
* <p>Provides potential of displaying a message to the user other than the
* defaults that depend on the value of {@link ext.status}.</p>
* <p>This value is reset to an empty String after every copy request.</p>
* @since 0.1.0.0
* @type String
*/
message: '',
/**
* <p>The name of the user's operating system.</p>
* @since 0.1.0.3
* @private
* @type String
*/
operatingSystem: '',
/**
* <p>The details used to determine the operating system being used by the
* user.</p>
* @since 0.1.0.3
* @private
* @type Object[]
*/
operatingSystems: [{
substring: 'Win',
title: 'Windows'
}, {
substring: 'Mac',
title: 'Mac'
}, {
substring: 'Linux',
title: 'Linux'
}],
/**
* <p>The HTML to populate the popup with.</p>
* <p>This should be updated whenever changes are made to the features.</p>
* @see ext.updateFeatures
* @since 0.1.0.0
* @type String
*/
popupHTML: '',
/**
* <p>String representation of the keyboard modifiers listened to by this
* extension on Windows/Linux platforms.</p>
* @since 0.1.0.0
* @type String
*/
shortcutModifiers: 'Ctrl+Alt+',
/**
* <p>String representation of the keyboard modifiers listened to by this
* extension on Mac platforms.</p>
* @since 0.1.0.0
* @type String
*/
shortcutMacModifiers: '⇧⌥',
/**
* <p>The URL shortener services supported by this extension.</p>
* @since 0.1.0.0
* @private
* @type Object[]
*/
shorteners: [{
contentType: 'application/x-www-form-urlencoded',
getParameters: function (url) {
var params = {
apiKey: 'R_2371fda46305d0ec3065972f5e72800e',
format: 'json',
login: 'forchoon',
longUrl: url
};
if (utils.get('bitlyApiKey') && utils.get('bitlyUsername')) {
params.x_apiKey = utils.get('bitlyApiKey');
params.x_login = utils.get('bitlyUsername');
}
return params;
},
input: function (url) {
return null;
},
isEnabled: function () {
return utils.get('bitly');
},
method: 'GET',
name: 'bit.ly',
output: function (resp) {
return JSON.parse(resp).data.url;
},
url: function () {
return 'http://api.bitly.com/v3/shorten';
}
}, {
contentType: 'application/json',
getParameters: function (url) {
return {
key: 'AIzaSyD504IwHeL3V2aw6ZGYQRgwWnJ38jNl2MY'
};
},
input: function (url) {
return JSON.stringify({longUrl: url});
},
isEnabled: function () {
return utils.get('googl');
},
isOAuthEnabled: function () {
return utils.get('googlOAuth');
},
method: 'POST',
name: 'goo.gl',
oauth: ChromeExOAuth.initBackgroundPage({
access_url: 'https://www.google.com/accounts/OAuthGetAccessToken',
app_name: chrome.i18n.getMessage('app_name'),
authorize_url: 'https://www.google.com/accounts/' +
'OAuthAuthorizeToken',
consumer_key: 'anonymous',
consumer_secret: 'anonymous',
request_url: 'https://www.google.com/accounts/' +
'OAuthGetRequestToken',
scope: 'https://www.googleapis.com/auth/urlshortener'
}),
output: function (resp) {
return JSON.parse(resp).id;
},
url: function () {
return 'https://www.googleapis.com/urlshortener/v1/url';
}
}, {
contentType: 'application/json',
getParameters: function (url) {
var params = {
action: 'shorturl',
format: 'json',
url: url
};
if (utils.get('yourlsPassword') && utils.get('yourlsUsername')) {
params.password = utils.get('yourlsPassword');
params.username = utils.get('yourlsUsername');
} else if (utils.get('yourlsSignature')) {
params.signature = utils.get('yourlsSignature');
}
return params;
},
input: function (url) {
return null;
},
isEnabled: function () {
return utils.get('yourls');
},
method: 'POST',
name: 'YOURLS',
output: function (resp) {
return JSON.parse(resp).shorturl;
},
url: function () {
return utils.get('yourlsUrl');
}
}],
/**
* <p>Indicates whether or not the current copy request was a success.</p>
* <p>This value is reset to <code>false</code> after every copy
* request.</p>
* @type Boolean
*/
status: false,
/**
* <p>Contains the extensions supported by this extension for compatibility
* purposes.</p>
* @since 0.1.0.0
* @type Object[]
*/
support: [{
// IE Tab
extensionId: 'hehijbfgiekmjfkfjpbkbammjbdenadd',
title: function (title) {
var str = 'IE: ';
if (title) {
var idx = title.indexOf(str);
if (idx !== -1) {
return title.substring(idx + str.length);
}
}
return title;
},
url: function (url) {
var str = 'iecontainer.html#url=';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
return decodeURIComponent(url.substring(idx + str.length));
}
}
return url;
}
}, {
// IE Tab Classic
extensionId: 'miedgcmlgpmdagojnnbemlkgidepfjfi',
title: function (title) {
return title;
},
url: function (url) {
var str = 'ie.html#';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
return url.substring(idx + str.length);
}
}
return url;
}
}, {
// IE Tab Multi (Enhance)
extensionId: 'fnfnbeppfinmnjnjhedifcfllpcfgeea',
title: function (title) {
return title;
},
url: function (url) {
var str = 'navigate.html?chromeurl=',
str2 = '[escape]';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
url = url.substring(idx + str.length);
if (url && url.indexOf(str2) === 0) {
url = decodeURIComponent(url.substring(str2.length));
}
return url;
}
}
return url;
}
}, {
// Mozilla Gecko Tab
extensionId: 'icoloanbecehinobmflpeglknkplbfbm',
title: function (title) {
return title;
},
url: function (url) {
var str = 'navigate.html?chromeurl=',
str2 = '[escape]';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
url = url.substring(idx + str.length);
if (url && url.indexOf(str2) === 0) {
url = decodeURIComponent(url.substring(str2.length));
}
return url;
}
}
return url;
}
}],
/**
* <p>The current version of this extension.</p>
* @since 0.1.0.3
* @private
* @type String
*/
version: '',
/**
* <p>Extracts additional data with the provided information and adds it to
* the specified object.</p>
* @param {Tab} tab The tab whose information is to be extracted.
* @param {Object} data The data to receive the additional data.
* @param {function} callback The function to be called once the
* information has been extracted.
* @since 0.1.1.0
* @private
*/
addAdditionalData: function (tab, data, callback) {
chrome.cookies.getAll({url: data.url}, function (cookies) {
var cookieNames = [];
cookies = cookies || [];
// Extracts the names of every cookie
for (var i = 0; i < cookies.length; i++) {
cookieNames.push(cookies[i].name);
}
$.extend(data, {
cookie: function () {
return function (text, render) {
var name = render(text),
value = '';
// Attempts to find the value for the cookie name
for (var j = 0; j < cookies.length; j++) {
if (cookies[j].name === name) {
value = cookies[j].value;
break;
}
}
return value;
};
},
cookies: cookieNames
});
// Prevents hanging on pages where content script wasn't executed
if (ext.isProtectedPage(tab)) {
$.extend(data, {
selection: '',
selectionlinks: []
});
callback();
} else {
chrome.tabs.sendRequest(tab.id, {}, function (response) {
$.extend(data, {
selection: response.text || '',
selectionlinks: response.urls || []
});
callback();
});
}
});
},
/**
* <p>Adds the specified feature name to those stored in localStorage.</p>
* <p>The feature name is only added if it doesn't already exist.</p>
* @param {String} name The feature name to be stored.
* @returns {Boolean} <code>true</code> if the name was stored; otherwise
* <code>false</code>.
* @since 0.1.0.0
* @private
*/
addFeatureName: function (name) {
var features = utils.get('features');
if (features.indexOf(name) === -1) {
features.push(name);
utils.set('features', features);
return true;
}
return false;
},
/**
* <p>Creates an Object containing data based on information derived from
* the specified tab and menu item data.</p>
* @param {Tab} tab The tab whose information is to be extracted.
* @param {OnClickData} onClickData The details about the menu item clicked
* and the context where the click happened.
* @param {function} shortCallback The function to be called if/when a
* shortened URL is requested when parsing the template's content.
* @returns {Object} The data based on information extracted from the tab
* provided and its URL. This can contain Strings, Arrays, Objects, and
* functions.
* @see ext.buildStandardData
* @since 0.1.0.0
* @private
*/
buildDerivedData: function (tab, onClickData, shortCallback) {
var data = {
title: tab.title,
url: ''
};
if (onClickData.linkUrl) {
data.url = onClickData.linkUrl;
} else if (onClickData.srcUrl) {
data.url = onClickData.srcUrl;
} else if (onClickData.frameUrl) {
data.url = onClickData.frameUrl;
} else {
data.url = onClickData.pageUrl;
}
return ext.buildStandardData(data, shortCallback);
},
/**
* <p>Creates a <code><li/></code> representing the feature provided.
* This is to be inserted in to the <code><ul/></code> in the popup
* page but is created here to optimize display times for the popup.</p>
* @param {Object} feature The information of the feature to be used.
* @returns {jQuery} The generated <code><li/></code> jQuery object.
* @since 0.1.0.0
* @private
*/
buildFeature: function (feature) {
var image = '';
for (var j = 0; j < ext.images.length; j++) {
if (ext.images[j].id === feature.image) {
image = '../images/' + ext.images[j].file;
break;
}
}
image = image || '../images/spacer.png';
var item = $('<li/>', {
name: feature.name,
onclick: 'popup.sendRequest(this);'
}),
menu = $('<div/>', {
'class': 'menu',
style: 'background-image: url(\'' + image + '\');'
});
menu.append($('<span/>', {
'class': 'text',
text: feature.title
}));
if (utils.get('shortcuts')) {
var modifiers = ext.shortcutModifiers;
if (ext.isThisPlatform('mac')) {
modifiers = ext.shortcutMacModifiers;
}
menu.append($('<span/>', {
'class': 'shortcut',
html: (feature.shortcut) ? modifiers + feature.shortcut : ''
}));
}
return item.append(menu);
},
/**
* <p>Builds the HTML to populate the popup with to optimize popup loading
* times.</p>
* @since 0.1.0.0
* @private
*/
buildPopup: function () {
var item = $('<div id="item"/>'),
itemList = $('<ul id="itemList"/>'),
loadDiv = $('<div id="loadDiv"/>');
loadDiv.append($('<img src="../images/loading.gif"/>'), $('<div/>', {
text: chrome.i18n.getMessage('shortening')
}));
// Generates the HTML for each feature
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].enabled) {
itemList.append(ext.buildFeature(ext.features[i]));
}
}
// Adds generic message to state the obvious... list is empty
if (itemList.find('li').length === 0) {
$('<li/>').append(
$('<div/>', {
'class': 'menu',
style: 'background-image: url(\'../images/spacer.png\');'
}).append(
$('<span/>', {
'class': 'text',
style: 'margin-left: 0',
text: chrome.i18n.getMessage('empty')
})
)
).appendTo(itemList);
}
item.append(itemList);
ext.popupHTML = $('<div/>').append(loadDiv, item).html();
},
/**
* <p>Creates an Object containing data based on information extracted from
* the specified tab.</p>
* <p>This function merges this data with additional information relating
* to the URL of the tab.</p>
* <p>If a shortened URL is requested when parsing the template's content
* later the callback function specified is called to handle this scenario
* as we don't want to call a URL shortener service unless it is
* required.</p>
* @param {Tab} tab The tab whose information is to be extracted.
* @param {function} shortCallback The function to be called if/when a
* shortened URL is requested when parsing the template's content.
* @returns {Object} The data based on information extracted from the tab
* provided and its URL. This can contain Strings, Arrays, Objects, and
* functions.
* @since 0.1.0.0
* @private
*/
buildStandardData: function (tab, shortCallback) {
var compatibility = false,
data = {},
title = '',
url = {};
for (var i = 0; i < ext.support.length; i++) {
if (ext.isExtensionActive(tab,
ext.support[i].extensionId)) {
title = ext.support[i].title(tab.title);
url = $.url(ext.support[i].url(tab.url));
compatibility = true;
break;
}
}
if (!compatibility) {
title = tab.title;
url = $.url(tab.url);
}
$.extend(data, url.attr(), {
bitly: utils.get('bitly'),
bitlyapikey: utils.get('bitlyApiKey'),
bitlyusername: utils.get('bitlyUsername'),
browser: ext.browser.title,
browserversion: ext.browser.version,
contextmenu: utils.get('contextMenu'),
cookiesenabled: window.navigator.cookieEnabled,
decode: function () {
return function (text, render) {
return decodeURIComponent(render(text));
};
},
doanchortarget: utils.get('doAnchorTarget'),
doanchortitle: utils.get('doAnchorTitle'),
encode: function () {
return function (text, render) {
return encodeURIComponent(render(text));
};
},
// Deprecated since 0.1.0.2, use encode instead
encoded: encodeURIComponent(url.attr('source')),
favicon: tab.favIconUrl,
fparam: function () {
return function (text, render) {
return url.fparam(render(text));
};
},
fparams: url.fparam(),
fsegment: function () {
return function (text, render) {
return url.fsegment(parseInt(render(text), 10));
};
},
fsegments: url.fsegment(),
googl: utils.get('googl'),
googloauth: utils.get('googlOAuth'),
java: window.navigator.javaEnabled(),
notificationduration: utils.get('notificationDuration') / 1000,
notifications: utils.get('notifications'),
offline: !window.navigator.onLine,
// Deprecated since 0.1.0.2, use originalUrl instead
originalsource: tab.url,
originaltitle: tab.title || url.attr('source'),
originalurl: tab.url,
os: ext.operatingSystem,
param: function () {
return function (text, render) {
return url.param(render(text));
};
},
params: url.param(),
segment: function () {
return function (text, render) {
return url.segment(parseInt(render(text), 10));
};
},
segments: url.segment(),
'short': function () {
return shortCallback();
},
shortcuts: utils.get('shortcuts'),
title: title || url.attr('source'),
url: url.attr('source'),
version: ext.version,
yourls: utils.get('yourls'),
yourlspassword: utils.get('yourlsPassword'),
yourlssignature: utils.get('yourlsSignature'),
yourlsurl: utils.get('yourlsUrl'),
yourlsusername: utils.get('yourlsUsername')
});
return data;
},
/**
* <p>Calls the active URL shortener service with the URL provided in order
* to obtain a corresponding short URL.</p>
* <p>This function calls the callback function specified with the result
* once it has been received.</p>
* @param {String} url The URL to be shortened and added to the clipboard.
* @param {function} callback The function to be called once a response has
* been received.
* @see ext.shorteners
* @since 0.1.0.0 - Previously located in <code>helper</code>.
*/
callUrlShortener: function (url, callback) {
ext.callUrlShortenerHelper(url, function (url, service) {
var name = service.name;
if (!service.url()) {
callback({
message: chrome.i18n.getMessage('shortener_config_error',
name),
shortener: name,
success: false
});
return;
}
try {
var params = service.getParameters(url) || {};
var req = new XMLHttpRequest();
req.open(service.method, service.url() + '?' + $.param(params),
true);
req.setRequestHeader('Content-Type', service.contentType);
if (service.oauth && service.isOAuthEnabled()) {
req.setRequestHeader('Authorization',
service.oauth.getAuthorizationHeader(service.url(),
service.method, params));
}
req.onreadystatechange = function () {
if (req.readyState === 4) {
callback({
shortUrl: service.output(req.responseText),
shortener: name,
success: true
});
}
};
req.send(service.input(url));
} catch (e) {
console.log(e.message || e);
callback({
message: chrome.i18n.getMessage('shortener_error', name),
shortener: name,
success: false
});
}
});
},
/**
* <p>Helper method which determines when the callback function provided is
* called depending on whether or not the active URL Shortener supports
* OAuth.</p>
* @param {String} url The URL to be shortened and added to the clipboard.
* @param {Function} callback The function that is called either
* immediately or once autherized if OAuth is supported.
* @see ext.callUrlShortener
* @since 0.1.0.0 - Previously located in <code>helper</code>.
* @private
*/
callUrlShortenerHelper: function (url, callback) {
var service = ext.getUrlShortener();
if (service.oauth && service.isOAuthEnabled()) {
service.oauth.authorize(function () {
callback(url, service);
});
} else {
callback(url, service);
}
},
/**
* <p>Adds the specified string to the system clipboard.</p>
* <p>This is the core function for copying to the clipboard by the
* extension. All supported copy requests should, at some point, call this
* function.</p>
* <p>If the string provided is empty a single space will be copied
* instead.</p>
* @param {String} str The string to be added to the clipboard.
* @param {Boolean} [hidden] <code>true</code> to avoid updating
* {@link ext.status} and showing a notification; otherwise
* <code>false</code>.
*/
copy: function (str, hidden) {
var result = false,
sandbox = $('#sandbox').val(str).select();
result = document.execCommand('copy');
sandbox.val('');
if (!hidden) {
ext.status = result;
ext.showNotification();
}
},
/**
* <p>Deletes the values of the feature with the specified name from
* their respective locations.</p>
* @param {String} name The name of the feature whose values are to be
* deleted.
* @since 0.1.0.0
* @private
*/
deleteFeature: function (name) {
utils.remove('feat_' + name + '_content');
utils.remove('feat_' + name + '_enabled');
utils.remove('feat_' + name + '_image');
utils.remove('feat_' + name + '_index');
utils.remove('feat_' + name + '_readonly');
utils.remove('feat_' + name + '_shortcut');
utils.remove('feat_' + name + '_title');
},
/**
* <p>Injects and executes the <code>content.js</code> script within each
* of the tabs provided (where valid).</p>
* @param {Object[]} tabs The tabs to execute the script in.
* @private
*/
executeScriptsInExistingTabs: function (tabs) {
for (var i = 0; i < tabs.length; i++) {
if (!ext.isProtectedPage(tabs[i])) {
chrome.tabs.executeScript(tabs[i].id, {file: 'js/content.js'});
}
}
},
/**
* <p>Injects and executes the <code>content.js</code> script within all
* the tabs (where valid) of each Chrome window.</p>
* @private
*/
executeScriptsInExistingWindows: function () {
chrome.windows.getAll(null, function (windows) {
for (var i = 0; i < windows.length; i++) {
chrome.tabs.query({windowId: windows[i].id},
ext.executeScriptsInExistingTabs);
}
});
},
/**
* <p>Attempts to return the current version of the user's browser.</p>
* @returns {String} The browser's version.
* @since 0.1.0.3
* @private
*/
getBrowserVersion: function () {
var str = navigator.userAgent,
idx = str.indexOf(ext.browser.title);
if (idx !== -1) {
str = str.substring(idx + ext.browser.title.length + 1);
idx = str.indexOf(' ');
return (idx === -1) ? str : str.substring(0, idx);
}
},
/**
* <p>Attempts to return the information for the any feature with the
* specified menu identifier assigned to it.</p>
* @param {Integer} menuId The menu identifier to be queried.
* @returns {Object} The feature using the menu identifier provided, if
* possible.
* @since 0.1.0.0
* @private
*/
getFeatureWithMenuId: function (menuId) {
var feature;
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].menuId === menuId) {
feature = ext.features[i];
break;
}
}
return feature;
},
/**
* <p>Attempts to return the information for the any feature with the
* specified shortcut assigned to it.</p>
* <p>Disabled features are not included in this search.</p>
* @param {String} shortcut The shortcut to be queried.
* @returns {Object} The feature using the shortcut provided, if possible.
* @since 0.1.0.0
*/
getFeatureWithShortcut: function (shortcut) {
var feature;
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].enabled &&
ext.features[i].shortcut === shortcut) {
feature = ext.features[i];
break;
}
}
return feature;
},
/**
* <p>Attempts to return the operating system being used by the user.</p>
* @returns {String} The user's operating system.
* @since 0.1.0.3
* @private
*/
getOperatingSystem: function () {
var os = {},
str = navigator.platform;
for (var i = 0; i < ext.operatingSystems.length; i++) {
os = ext.operatingSystems[i];
if (str.indexOf(os.substring) !== -1) {
str = os.title;
break;
}
}
return str;
},
/**
* <p>Returns the information for the active URL shortener service.</p>
* @returns {Object} The active URL shortener.
* @see ext.shorteners
*/
getUrlShortener: function () {
// Attempts to lookup enabled URL shortener service
for (var i = 0; i < ext.shorteners.length; i++) {
if (ext.shorteners[i].isEnabled()) {
return ext.shorteners[i];
}
}
/*
* Should never reach here but we'll return goo.gl service by default
* after ensuring it's enabled from now on to save some time next
* lookup.
*/
utils.set('googl', true);
return ext.shorteners[1];
},
/**
* <p>Initializes the background page.</p>
* <p>This involves initializing the settings, injecting keyboard shortcut
* listeners and adding the request listeners.</p>
*/
init: function () {
utils.init('update_progress', {
features: [],
settings: [],
shorteners: []
});
ext.init_update();
utils.init('contextMenu', true);
utils.init('notifications', true);
utils.init('notificationDuration', 3000);
utils.init('shortcuts', true);
utils.init('doAnchorTarget', false);
utils.init('doAnchorTitle', false);
ext.initFeatures();
ext.initUrlShorteners();
ext.executeScriptsInExistingWindows();
chrome.extension.onRequest.addListener(ext.onRequest);
chrome.extension.onRequestExternal.addListener(ext.onExternalRequest);
// Derives static browser and OS information
ext.browser.version = ext.getBrowserVersion();
ext.operatingSystem = ext.getOperatingSystem();
// Derives extension's version
$.getJSON(chrome.extension.getURL('manifest.json'), function (data) {
ext.version = data.version;
});
},
/**
* <p>Handles the conversion/removal of older version of settings that may
* have been stored previously by {@link ext.init}.</p>
* @since 0.1.0.0
* @private
*/
init_update: function () {
var update = utils.get('update_progress');
// Checks if 0.1.0.0 update for settings is required
if (update.settings.indexOf('0.1.0.0') === -1) {
// Performs 0.1.0.0 update for settings
utils.rename('settingNotification', 'notifications', true);
utils.rename('settingNotificationTimer', 'notificationDuration',
3000);
utils.rename('settingShortcut', 'shortcuts', true);
utils.rename('settingTargetAttr', 'doAnchorTarget', false);
utils.rename('settingTitleAttr', 'doAnchorTitle', false);
utils.remove('settingIeTabExtract');
utils.remove('settingIeTabTitle');
// Ensures 0.1.0.0 update for settings is not performed again
update.settings.push('0.1.0.0');
utils.set('update_progress', update);
}
},
/**
* <p>Initilaizes the values of the specified feature by potentially
* storing them in to their respective locations.</p>
* <p>This function should only be used initializing default features and
* some values will always overwrite the existing one to provide
* functionality for changing current defaults.</p>
* <p>Names of initialized features are also added to that stored in
* localStorage if they do not already exist there.</p>
* @param {Object} feature The feature whose values are to be initialized.
* @param {String} feature.content The mustache template for the feature
* (overwrites).
* @param {Boolean} feature.enabled <code>true</code> if the feature is
* enabled; otherwise <code>false</code>.
* @param {Integer} feature.image The identifier of the feature's image.
* @param {Integer} feature.index The index representing the feature's
* display order.
* @param {String} feature.name The unique name of the feature.
* @param {Boolean} feature.readOnly <code>true</code> if the feature is
* read-only and certain values cannot be editted by the user; otherwise
* <code>false</code> (overwrites).
* @param {String} feature.shortcut The keyboard shortcut assigned to the
* feature.
* @param {String} feature.title The title of the feature (overwrites).
* @returns {Object} The feature provided.
* @since 0.1.0.0
* @private
*/
initFeature: function (feature) {
var name = feature.name;
utils.set('feat_' + name + '_content', feature.content);
utils.init('feat_' + name + '_enabled', feature.enabled);
utils.init('feat_' + name + '_image', feature.image);
utils.init('feat_' + name + '_index', feature.index);
utils.set('feat_' + name + '_readonly', feature.readOnly);
utils.init('feat_' + name + '_shortcut', feature.shortcut);
utils.set('feat_' + name + '_title', feature.title);
ext.addFeatureName(name);
return feature;
},
/**
* <p>Initializes the supported copy request features (including their
* corresponding settings).</p>
* @private
*/
initFeatures: function () {
utils.init('features', []);
ext.initFeatures_update();
for (var i = 0; i < ext.defaultFeatures.length; i++) {
ext.initFeature(ext.defaultFeatures[i]);
}
ext.updateFeatures();
},
/**
* <p>Handles the conversion/removal of older version of settings that may
* have been stored previously by {@link ext.initFeatures}.</p>
* @since 0.1.0.0
* @private
*/
initFeatures_update: function () {
var update = utils.get('update_progress');
// Checks if 0.1.0.0 update for features is required
if (update.features.indexOf('0.1.0.0') === -1) {
// Performs 0.1.0.0 update for features
utils.rename('copyAnchorEnabled', 'feat__anchor_enabled', true);
utils.rename('copyAnchorOrder', 'feat__anchor_index', 2);
utils.rename('copyBBCodeEnabled', 'feat__bbcode_enabled', false);
utils.rename('copyBBCodeOrder', 'feat__bbcode_index', 4);
utils.rename('copyEncodedEnabled', 'feat__encoded_enabled', true);
utils.rename('copyEncodedOrder', 'feat__encoded_index', 3);
utils.rename('copyShortEnabled', 'feat__short_enabled', true);
utils.rename('copyShortOrder', 'feat__short_index', 1);
utils.rename('copyUrlEnabled', 'feat__url_enabled', true);
utils.rename('copyUrlOrder', 'feat__url_index', 0);
// Ensures 0.1.0.0 update for features is not performed again
update.features.push('0.1.0.0');
utils.set('update_progress', update);
}
// Checks if 0.2.0.0 update for features is required
if (update.features.indexOf('0.2.0.0') === -1) {
// Performs 0.2.0.0 update for features
var image,
names = utils.get('features');
for (var i = 0; i < names.length; i++) {
utils.rename('feat_' + names[i] + '_template', 'feat_' +
names[i] + '_content');
image = utils.get('feat_' + names[i] + '_image');
if (typeof image === 'string') {
for (var j = 0; j < ext.images.length; j++) {
if (ext.images[j].file === image) {
utils.set('feat_' + names[i] + '_image',
ext.images[j].id);
break;
}
}
} else if (typeof image === 'undefined') {
utils.set('feat_' + names[i] + '_image', 0);
}
}
// Ensures 0.2.0.0 update for features is not performed again
update.features.push('0.2.0.0');
utils.set('update_progress', update);
}
},
/**
* <p>Initializes the settings related to the supported URL Shortener
* services.</p>
* @private
*/
initUrlShorteners: function () {
ext.initUrlShorteners_update();
utils.init('bitly', false);
utils.init('bitlyApiKey', '');
utils.init('bitlyUsername', '');
utils.init('googl', true);
utils.init('googlOAuth', true);
utils.init('yourls', false);
utils.init('yourlsPassword', '');
utils.init('yourlsSignature', '');
utils.init('yourlsUrl', '');
utils.init('yourlsUsername', '');
},
/**
* <p>Handles the conversion/removal of older version of settings that may
* have been stored previously by {@link ext.initUrlShorteners}.</p>
* @since 0.1.0.0
* @private
*/
initUrlShorteners_update: function () {
var update = utils.get('update_progress');
// Checks if 0.1.0.0 update for URL shorteners is required
if (update.shorteners.indexOf('0.1.0.0') === -1) {
// Performs 0.1.0.0 update for URL shorteners
utils.rename('bitlyEnabled', 'bitly', false);
utils.rename('bitlyXApiKey', 'bitlyApiKey', '');
utils.rename('bitlyXLogin', 'bitlyUsername', '');
utils.rename('googleEnabled', 'googl', true);
utils.rename('googleOAuthEnabled', 'googlOAuth', true);
// Ensures 0.1.0.0 update for URL shorteners is not performed again
update.shorteners.push('0.1.0.0');
utils.set('update_progress', update);
}
},
/**
* <p>Determines whether or not the sender provided is from a blacklisted
* extension.</p>
* @param {MessageSender} sender The sender to be tested.
* @returns {Boolean} <code>true</code> if the sender is blacklisted;
* otherwise <code>false</code>.
* @private
*/
isBlacklisted: function (sender) {
for (var i = 0; i < ext.blacklistedExtensions.length; i++) {
if (ext.blacklistedExtensions[i] === sender.id) {
return true;
}
}
return false;
},
/**
* <p>Returns whether or not the extension with the specified identifier is
* active on the tab provided.</p>
* @param {Tab} tab The tab to be tested.
* @param {String} extensionId The identifier of the extension to be
* tested.
* @returns {Boolean} <code>true</code> if the extension is active on the
* tab provided; otherwise <code>false</code>.
* @since 0.1.1.1
* @private
*/
isExtensionActive: function (tab, extensionId) {
return (ext.isSpecialPage(tab) && tab.url.indexOf(extensionId) !== -1);
},
/**
* <p>Determines whether or not the tab provided is currently displaying a
* page on the Chrome Extension Gallery (i.e. Web Store).</p>
* @param {Tab} tab The tab to be tested.
* @returns {Boolean} <code>true</code> if displaying a page on the Chrome
* Extension Gallery; otherwise <code>false</code>.
* @since 0.2.1.0
*/
isExtensionGallery: function (tab) {
return tab.url.indexOf('https://chrome.google.com/webstore') === 0;
},
/**
* <p>Determines whether or not the tab provided is currently display a
* <em>protected</em> page (i.e. a page that content scripts cannot be
* executed on).</p>
* @param {Tab} tab The tab to be tested.
* @returns {Boolean} <code>true</code> if displaying a <em>protected</em>
* page; otherwise <code>false</code>.
* @since 0.2.1.0
*/
isProtectedPage: function (tab) {
return ext.isSpecialPage(tab) || ext.isExtensionGallery(tab);
},
/**
* <p>Determines whether or not the tab provided is currently displaying a
* <em>special</em> page (i.e. a page that is internal to the browser).</p>
* @param {Tab} tab The tab to be tested.
* @returns {Boolean} <code>true</code> if displaying a <em>special</em>
* page; otherwise <code>false</code>.
*/
isSpecialPage: function (tab) {
return tab.url.indexOf('chrome') === 0;
},
/**
* <p>Determines whether or not the user's OS matches that provided.</p>
* @param {String} os The operating system to be tested.
* @returns {Boolean} <code>true</code> if the user's OS matches that
* specified; otherwise <code>false</code>.
*/
isThisPlatform: function (os) {
return navigator.userAgent.toLowerCase().indexOf(os) !== -1;
},
/**
* <p>Loads the values of the feature with the specified name from their
* respective locations.</p>
* @param {String} name The name of the feature whose values are to be
* fetched.
* @returns {Object} The feature for the name provided.
* @since 0.1.0.0
* @private
*/
loadFeature: function (name) {
return {
content: utils.get('feat_' + name + '_content'),
enabled: utils.get('feat_' + name + '_enabled'),
image: utils.get('feat_' + name + '_image'),
index: utils.get('feat_' + name + '_index'),
name: name,
readOnly: utils.get('feat_' + name + '_readonly'),
shortcut: utils.get('feat_' + name + '_shortcut'),
title: utils.get('feat_' + name + '_title')
};
},
/**
* <p>Loads the values of each stored feature from their respective
* locations.</p>
* <p>The array returned is sorted based on the index of each feature.</p>
* @returns {Object[]} The array of the features loaded.
* @since 0.1.0.0
*/
loadFeatures: function () {
var features = [],
names = utils.get('features');
for (var i = 0; i < names.length; i++) {
features.push(ext.loadFeature(names[i]));
}
features.sort(function (a, b) {
return a.index - b.index;
});
return features;
},
/**
* <p>Listener for external requests to the extension.</p>
* <p>This function only serves the request if the originating extension is
* not blacklisted.</p>
* @param {Object} request The request sent by the calling script.
* @param {Object} request.data The data for the copy request feature to be
* served.
* @param {KeyEvent} [request.data.e] The DOM <code>KeyEvent</code>
* responsible for generating the copy request. Only used if type is
* "shortcut".
* @param {String} [request.data.feature] The name of the feature on which
* to execute the copy request.
* @param {String} [request.data.key] The character of the final key
* responsible for firing the <code>KeyEvent</code>. Only used if type is
* "shortcut".
* @param {String} request.type The type of request being made.
* @param {MessageSender} [sender] An object containing information about
* the script context that sent a message or request.
* @param {function} [sendResponse] Function to call when you have a
* response. The argument should be any JSON-ifiable object, or undefined
* if there is no response.
* @private
*/
onExternalRequest: function (request, sender, sendResponse) {
if (!ext.isBlacklisted(sender)) {
ext.onRequest(request, sender, sendResponse);
}
},
/**
* <p>Listener for internal requests to the extension.</p>
* <p>If the request originated from a keyboard shortcut this function only
* serves that request if the keyboard shortcuts have been enabled by the
* user (or by default).</p>
* @param {Object} request The request sent by the calling script.
* @param {Object} request.data The data for the copy request feature to be
* served.
* @param {KeyEvent} [request.data.e] The DOM <code>KeyEvent</code>
* responsible for generating the copy request. Only used if type is
* "shortcut".
* @param {String} [request.data.feature] The name of the feature on which
* to execute the copy request.
* @param {String} [request.data.key] The character of the final key
* responsible for firing the <code>KeyEvent</code>. Only used if type is
* "shortcut".
* @param {String} request.type The type of request being made.
* @param {MessageSender} [sender] An object containing information about
* the script context that sent a message or request.
* @param {function} [sendResponse] Function to call when you have a
* response. The argument should be any JSON-ifiable object, or undefined
* if there is no response.
* @private
*/
onRequest: function (request, sender, sendResponse) {
if (request.type !== 'shortcut' || utils.get('shortcuts')) {
ext.onRequestHelper(request, sender, sendResponse);
}
},
/**
* <p>Helper function for the internal/external request listeners.</p>
* <p>This function will handle the request based on its type and the data
* provided.</p>
* @param {Object} request The request sent by the calling script.
* @param {Object} request.data The data for the copy request feature to be
* served.
* @param {KeyEvent} [request.data.e] The DOM <code>KeyEvent</code>
* responsible for generating the copy request. Only used if type is
* "shortcut".
* @param {String} [request.data.feature] The name of the feature on which
* to execute the copy request.
* @param {String} [request.data.key] The character of the final key
* responsible for firing the <code>KeyEvent</code>. Only used if type is
* "shortcut".
* @param {String} request.type The type of request being made.
* @param {MessageSender} [sender] An object containing information about
* the script context that sent a message or request.
* @param {function} [sendResponse] Function to call when you have a
* response. The argument should be any JSON-ifiable object, or undefined
* if there is no response.
* @private
*/
onRequestHelper: function (request, sender, sendResponse) {
if (request.type === 'version') {
sendResponse({version: ext.version});
return;
}
chrome.tabs.query({active: true}, function (tab) {
var data = {},
feature,
popup = chrome.extension.getViews({type: 'popup'})[0],
shortCalled = false,
shortPlaceholder = 'short' +
(Math.floor(Math.random() * 99999 + 1000));
function copyOutput(str) {
if (str) {
ext.copy(str);
} else {
ext.message = chrome.i18n.getMessage('copy_fail_empty');
ext.status = false;
ext.showNotification();
}
}
function shortCallback() {
shortCalled = true;
return '{' + shortPlaceholder + '}';
}
if (popup) {
$('#item', popup.document).hide();
$('#loadDiv', popup.document).show();
}
try {
switch (request.type) {
case 'menu':
data = ext.buildDerivedData(tab, request.data,
shortCallback);
feature = ext.getFeatureWithMenuId(
request.data.menuItemId);
break;
case 'popup':
// Should be cheaper than searching ext.features...
data = ext.buildStandardData(tab, shortCallback);
feature = ext.loadFeature(request.data.name);
break;
case 'shortcut':
data = ext.buildStandardData(tab, shortCallback);
feature = ext.getFeatureWithShortcut(request.data.key);
break;
}
} catch (e) {
if (e instanceof URIError) {
ext.message = chrome.i18n.getMessage('copy_fail_uri');
} else {
ext.message = chrome.i18n.getMessage('copy_fail_error');
}
ext.status = false;
ext.showNotification();
return;
}
if (feature) {
ext.addAdditionalData(tab, data, function () {
if (!feature.content) {
// Displays empty template error message
copyOutput();
return;
}
var output = Mustache.to_html(feature.content, data);
if (shortCalled) {
ext.callUrlShortener(data.source, function (response) {
if (response.success && response.shortUrl) {
var newData = {};
newData[shortPlaceholder] = response.shortUrl;
copyOutput(Mustache.to_html(output, newData));
} else {
if (!response.message) {
response.message = chrome.i18n.getMessage(
'shortener_error',
response.shortener);
}
ext.message = response.message;
ext.status = false;
ext.showNotification();
}
});
} else {
copyOutput(output);
}
});
} else {
if (popup) {
popup.close();
}
}
});
},
/**
* <p>Attempts to retrieve the contents of the system clipboard.</p>
* @returns {String} The string taken from the clipboard.
* @since 0.2.0.1
*/
paste: function () {
var result = '',
sandbox = $('#sandbox').val('').select();
if (document.execCommand('paste')) {
result = sandbox.val();
}
sandbox.val('');
return result;
},
/**
* <p>Removes the specified feature name from those stored in
* localStorage.</p>
* @param {String} name The feature name to be removed.
* @since 0.1.0.0
* @private
*/
removeFeatureName: function (name) {
var features = utils.get('features'),
idx = features.indexOf(name);
if (idx !== -1) {
features.splice(idx, 1);
utils.set('features', features);
}
},
/**
* <p>Resets the message and status associated with the current copy
* request.</p>
* <p>This function should be called on the completion of a copy request
* regardless of its outcome.</p>
*/
reset: function () {
ext.message = '';
ext.status = false;
},
/**
* <p>Stores the values of the specified feature in to their respective
* locations.</p>
* @param {Object} feature The feature whose values are to be saved.
* @param {String} feature.content The mustache template for the feature.
* @param {Boolean} feature.enabled <code>true</code> if the feature is
* enabled; otherwise <code>false</code>.
* @param {Integer} feature.image The identifier of the feature's image.
* @param {Integer} feature.index The index representing the feature's
* display order.
* @param {String} feature.name The unique name of the feature.
* @param {Boolean} feature.readOnly <code>true</code> if the feature is
* read-only and certain values cannot be editted by the user; otherwise
* <code>false</code>.
* @param {String} feature.shortcut The keyboard shortcut assigned to the
* feature.
* @param {String} feature.title The title of the feature.
* @returns {Object} The feature provided.
* @since 0.1.0.0
* @private
*/
saveFeature: function (feature) {
var name = feature.name;
utils.set('feat_' + name + '_content', feature.content);
utils.set('feat_' + name + '_enabled', feature.enabled);
utils.set('feat_' + name + '_image', feature.image);
utils.set('feat_' + name + '_index', feature.index);
utils.set('feat_' + name + '_readonly', feature.readOnly);
utils.set('feat_' + name + '_shortcut', feature.shortcut);
utils.set('feat_' + name + '_title', feature.title);
return feature;
},
/**
* <p>Stores the values of each of the speciifed features in to their
* respective locations.</p>
* <p>Any features no longer in use are removed from localStorage in an
* attempt to keep capacity under control.</p>
* @param {Object[]} features The features whose values are to be saved.
* @returns {Object[]} The array of features provided.
* @since 0.1.0.0
*/
saveFeatures: function (features) {
var names = [],
oldNames = utils.get('features');
for (var i = 0; i < features.length; i++) {
names.push(features[i].name);
ext.saveFeature(features[i]);
}
// Ensures any features no longer used are removed from localStorage
for (var j = 0; j < oldNames.length; j++) {
if (names.indexOf(oldNames[j]) === -1) {
ext.deleteFeature(oldNames[j]);
}
}
utils.set('features', names);
return features;
},
/**
* <p>Displays a Chrome notification to inform the user on whether or not
* the copy request was successful.</p>
* <p>This function ensures that {@link ext} is reset and that
* notifications are only displayed if specified by the user (or by
* default).</p>
* @see ext.reset
*/
showNotification: function () {
var popup = chrome.extension.getViews({type: 'popup'})[0];
if (utils.get('notifications')) {
webkitNotifications.createHTMLNotification(
chrome.extension.getURL('pages/notification.html')
).show();
} else {
ext.reset();
}
if (popup) {
popup.close();
}
},
/**
* <p>Updates the context menu items to reflect respective features.</p>
* @since 0.1.0.0
* @private
*/
updateContextMenu: function () {
// Ensures any previously added context menu items are removed
chrome.contextMenus.removeAll(function () {
function onMenuClick(info, tab) {
ext.onRequestHelper({
data: info,
type: 'menu'
});
}
if (utils.get('contextMenu')) {
var menuId,
parentId = chrome.contextMenus.create({
contexts: ['all'],
title: chrome.i18n.getMessage('name')
});
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].enabled) {
menuId = chrome.contextMenus.create({
contexts: ['all'],
onclick: onMenuClick,
parentId: parentId,
title: ext.features[i].title
});
ext.features[i].menuId = menuId;
}
}
}
});
},
/**
* <p>Updates the list of features stored locally to reflect that stored
* in localStorage.</p>
* <p>It is important that this function is called whenever features might
* of changed as this also updates the prepared popup HTML.</p>
*/
updateFeatures: function () {
ext.features = ext.loadFeatures();
ext.buildPopup();
ext.updateContextMenu();
}
}; | src/js/background.js | /* Copyright (C) 2011 Alasdair Mercer, http://neocotic.com/
*
* 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.
*/
/**
* <p>Main controller for the extension and manages all copy requests.</p>
* @author <a href="http://neocotic.com">Alasdair Mercer</a>
* @since 0.2.0.0 - Previously named <code>urlcopy</code>.
* @requires jQuery
* @requires jQuery URL Parser Plugin
* @requires mustache.js
* @namespace
*/
var ext = {
/**
* <p>A list of blacklisted extension IDs who should be prevented from
* making requests to the extension.</p>
* @private
* @type String[]
*/
blacklistedExtensions: [],
/**
* <p>The details of the user's current browser.</p>
* @since 0.1.0.3
* @private
* @type Object
*/
browser: {
/**
* <p>The name of the browser (i.e. <code>Chrome</code>).</p>
* @since 0.1.0.3
* @private
* @type String
*/
title: 'Chrome',
/**
* <p>The version of the browser (e.g. <code>12.0.742.122</code>).</p>
* @since 0.1.0.3
* @private
* @type String
*/
version: ''
},
/**
* <p>The default features to be used by this extension.</p>
* @since 0.1.0.0
* @private
* @type Object[]
*/
defaultFeatures: [{
content: '<a href="{{url}}"' +
'{#doAnchorTarget} target="_blank"{/doAnchorTarget}' +
'{#doAnchorTitle} title="{{title}}"{/doAnchorTitle}' +
'>{{title}}</a>',
enabled: true,
image: 11,
index: 2,
name: '_anchor',
readOnly: true,
shortcut: 'A',
title: chrome.i18n.getMessage('copy_anchor')
}, {
content: '[url={url}]{title}[/url]',
enabled: false,
image: 7,
index: 5,
name: '_bbcode',
readOnly: true,
shortcut: 'B',
title: chrome.i18n.getMessage('copy_bbcode')
}, {
content: '{#encode}{url}{/encode}',
enabled: true,
image: 5,
index: 3,
name: '_encoded',
readOnly: true,
shortcut: 'E',
title: chrome.i18n.getMessage('copy_encoded')
}, {
content: '[{title}]({url})',
enabled: false,
image: 7,
index: 4,
name: '_markdown',
readOnly: true,
shortcut: 'M',
title: chrome.i18n.getMessage('copy_markdown')
}, {
content: '{short}',
enabled: true,
image: 16,
index: 1,
name: '_short',
readOnly: true,
shortcut: 'S',
title: chrome.i18n.getMessage('copy_short')
}, {
content: '{url}',
enabled: true,
image: 8,
index: 0,
name: '_url',
readOnly: true,
shortcut: 'U',
title: chrome.i18n.getMessage('copy_url')
}],
/**
* <p>The list of copy request features supported by the extension.</p>
* <p>This list ordered to match that specified by the user.</p>
* @see ext.updateFeatures
* @type Object[]
*/
features: [],
/**
* <p>The details of the images available as feature icons.</p>
* @since 0.2.0.0
* @private
* @type Object[]
*/
images: [{
file: 'spacer.gif',
id: 0,
name: chrome.i18n.getMessage('feat_none'),
separate: true
}, {
file: 'feat_auction.png',
id: 1,
name: chrome.i18n.getMessage('feat_auction')
}, {
file: 'feat_bug.png',
id: 2,
name: chrome.i18n.getMessage('feat_bug')
}, {
file: 'feat_clipboard.png',
id: 3,
name: chrome.i18n.getMessage('feat_clipboard')
}, {
file: 'feat_clipboard_empty.png',
id: 4,
name: chrome.i18n.getMessage('feat_clipboard_empty')
}, {
file: 'feat_component.png',
id: 5,
name: chrome.i18n.getMessage('feat_component')
}, {
file: 'feat_cookies.png',
id: 6,
name: chrome.i18n.getMessage('feat_cookies')
}, {
file: 'feat_discussion.png',
id: 7,
name: chrome.i18n.getMessage('feat_discussion')
}, {
file: 'feat_globe.png',
id: 8,
name: chrome.i18n.getMessage('feat_globe')
}, {
file: 'feat_google.png',
id: 9,
name: chrome.i18n.getMessage('feat_google')
}, {
file: 'feat_heart.png',
id: 10,
name: chrome.i18n.getMessage('feat_heart')
}, {
file: 'feat_html.png',
id: 11,
name: chrome.i18n.getMessage('feat_html')
}, {
file: 'feat_key.png',
id: 12,
name: chrome.i18n.getMessage('feat_key')
}, {
file: 'feat_lightbulb.png',
id: 13,
name: chrome.i18n.getMessage('feat_lightbulb')
}, {
file: 'feat_lighthouse.png',
id: 14,
name: chrome.i18n.getMessage('feat_lighthouse')
}, {
file: 'feat_lightning.png',
id: 15,
name: chrome.i18n.getMessage('feat_lightning')
}, {
file: 'feat_link.png',
id: 16,
name: chrome.i18n.getMessage('feat_link')
}, {
file: 'feat_linux.png',
id: 17,
name: chrome.i18n.getMessage('feat_linux')
}, {
file: 'feat_mail.png',
id: 18,
name: chrome.i18n.getMessage('feat_mail')
}, {
file: 'feat_newspaper.png',
id: 19,
name: chrome.i18n.getMessage('feat_newspaper')
}, {
file: 'feat_note.png',
id: 20,
name: chrome.i18n.getMessage('feat_note')
}, {
file: 'feat_page.png',
id: 21,
name: chrome.i18n.getMessage('feat_page')
}, {
file: 'feat_plugin.png',
id: 22,
name: chrome.i18n.getMessage('feat_plugin')
}, {
file: 'feat_rss.png',
id: 23,
name: chrome.i18n.getMessage('feat_rss')
}, {
file: 'feat_script.png',
id: 24,
name: chrome.i18n.getMessage('feat_script')
}, {
file: 'feat_scull.png',
id: 25,
name: chrome.i18n.getMessage('feat_scull')
}, {
file: 'feat_sign.png',
id: 26,
name: chrome.i18n.getMessage('feat_sign')
}, {
file: 'feat_siren.png',
id: 27,
name: chrome.i18n.getMessage('feat_siren')
}, {
file: 'feat_star.png',
id: 28,
name: chrome.i18n.getMessage('feat_star')
}, {
file: 'feat_support.png',
id: 29,
name: chrome.i18n.getMessage('feat_support')
}, {
file: 'feat_tag.png',
id: 30,
name: chrome.i18n.getMessage('feat_tag')
}, {
file: 'feat_tags.png',
id: 31,
name: chrome.i18n.getMessage('feat_tags')
}, {
file: 'feat_thumb_down.png',
id: 32,
name: chrome.i18n.getMessage('feat_thumb_down')
}, {
file: 'feat_thumb_up.png',
id: 33,
name: chrome.i18n.getMessage('feat_thumb_up')
}, {
file: 'feat_tools.png',
id: 34,
name: chrome.i18n.getMessage('feat_tools')
}],
/**
* <p>Provides potential of displaying a message to the user other than the
* defaults that depend on the value of {@link ext.status}.</p>
* <p>This value is reset to an empty String after every copy request.</p>
* @since 0.1.0.0
* @type String
*/
message: '',
/**
* <p>The name of the user's operating system.</p>
* @since 0.1.0.3
* @private
* @type String
*/
operatingSystem: '',
/**
* <p>The details used to determine the operating system being used by the
* user.</p>
* @since 0.1.0.3
* @private
* @type Object[]
*/
operatingSystems: [{
substring: 'Win',
title: 'Windows'
}, {
substring: 'Mac',
title: 'Mac'
}, {
substring: 'Linux',
title: 'Linux'
}],
/**
* <p>The HTML to populate the popup with.</p>
* <p>This should be updated whenever changes are made to the features.</p>
* @see ext.updateFeatures
* @since 0.1.0.0
* @type String
*/
popupHTML: '',
/**
* <p>String representation of the keyboard modifiers listened to by this
* extension on Windows/Linux platforms.</p>
* @since 0.1.0.0
* @type String
*/
shortcutModifiers: 'Ctrl+Alt+',
/**
* <p>String representation of the keyboard modifiers listened to by this
* extension on Mac platforms.</p>
* @since 0.1.0.0
* @type String
*/
shortcutMacModifiers: '⇧⌥',
/**
* <p>The URL shortener services supported by this extension.</p>
* @since 0.1.0.0
* @private
* @type Object[]
*/
shorteners: [{
contentType: 'application/x-www-form-urlencoded',
getParameters: function (url) {
var params = {
apiKey: 'R_2371fda46305d0ec3065972f5e72800e',
format: 'json',
login: 'forchoon',
longUrl: url
};
if (utils.get('bitlyApiKey') && utils.get('bitlyUsername')) {
params.x_apiKey = utils.get('bitlyApiKey');
params.x_login = utils.get('bitlyUsername');
}
return params;
},
input: function (url) {
return null;
},
isEnabled: function () {
return utils.get('bitly');
},
method: 'GET',
name: 'bit.ly',
output: function (resp) {
return JSON.parse(resp).data.url;
},
url: function () {
return 'http://api.bitly.com/v3/shorten';
}
}, {
contentType: 'application/json',
getParameters: function (url) {
return {
key: 'AIzaSyD504IwHeL3V2aw6ZGYQRgwWnJ38jNl2MY'
};
},
input: function (url) {
return JSON.stringify({longUrl: url});
},
isEnabled: function () {
return utils.get('googl');
},
isOAuthEnabled: function () {
return utils.get('googlOAuth');
},
method: 'POST',
name: 'goo.gl',
oauth: ChromeExOAuth.initBackgroundPage({
access_url: 'https://www.google.com/accounts/OAuthGetAccessToken',
app_name: chrome.i18n.getMessage('app_name'),
authorize_url: 'https://www.google.com/accounts/' +
'OAuthAuthorizeToken',
consumer_key: 'anonymous',
consumer_secret: 'anonymous',
request_url: 'https://www.google.com/accounts/' +
'OAuthGetRequestToken',
scope: 'https://www.googleapis.com/auth/urlshortener'
}),
output: function (resp) {
return JSON.parse(resp).id;
},
url: function () {
return 'https://www.googleapis.com/urlshortener/v1/url';
}
}, {
contentType: 'application/json',
getParameters: function (url) {
var params = {
action: 'shorturl',
format: 'json',
url: url
};
if (utils.get('yourlsPassword') && utils.get('yourlsUsername')) {
params.password = utils.get('yourlsPassword');
params.username = utils.get('yourlsUsername');
} else if (utils.get('yourlsSignature')) {
params.signature = utils.get('yourlsSignature');
}
return params;
},
input: function (url) {
return null;
},
isEnabled: function () {
return utils.get('yourls');
},
method: 'POST',
name: 'YOURLS',
output: function (resp) {
return JSON.parse(resp).shorturl;
},
url: function () {
return utils.get('yourlsUrl');
}
}],
/**
* <p>Indicates whether or not the current copy request was a success.</p>
* <p>This value is reset to <code>false</code> after every copy
* request.</p>
* @type Boolean
*/
status: false,
/**
* <p>Contains the extensions supported by this extension for compatibility
* purposes.</p>
* @since 0.1.0.0
* @type Object[]
*/
support: [{
// IE Tab
extensionId: 'hehijbfgiekmjfkfjpbkbammjbdenadd',
title: function (title) {
var str = 'IE: ';
if (title) {
var idx = title.indexOf(str);
if (idx !== -1) {
return title.substring(idx + str.length);
}
}
return title;
},
url: function (url) {
var str = 'iecontainer.html#url=';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
return decodeURIComponent(url.substring(idx + str.length));
}
}
return url;
}
}, {
// IE Tab Classic
extensionId: 'miedgcmlgpmdagojnnbemlkgidepfjfi',
title: function (title) {
return title;
},
url: function (url) {
var str = 'ie.html#';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
return url.substring(idx + str.length);
}
}
return url;
}
}, {
// IE Tab Multi (Enhance)
extensionId: 'fnfnbeppfinmnjnjhedifcfllpcfgeea',
title: function (title) {
return title;
},
url: function (url) {
var str = 'navigate.html?chromeurl=',
str2 = '[escape]';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
url = url.substring(idx + str.length);
if (url && url.indexOf(str2) === 0) {
url = decodeURIComponent(url.substring(str2.length));
}
return url;
}
}
return url;
}
}, {
// Mozilla Gecko Tab
extensionId: 'icoloanbecehinobmflpeglknkplbfbm',
title: function (title) {
return title;
},
url: function (url) {
var str = 'navigate.html?chromeurl=',
str2 = '[escape]';
if (url) {
var idx = url.indexOf(str);
if (idx !== -1) {
url = url.substring(idx + str.length);
if (url && url.indexOf(str2) === 0) {
url = decodeURIComponent(url.substring(str2.length));
}
return url;
}
}
return url;
}
}],
/**
* <p>The current version of this extension.</p>
* @since 0.1.0.3
* @private
* @type String
*/
version: '',
/**
* <p>Extracts additional data with the provided information and adds it to
* the specified object.</p>
* @param {Tab} tab The tab whose information is to be extracted.
* @param {Object} data The data to receive the additional data.
* @param {function} callback The function to be called once the
* information has been extracted.
* @since 0.1.1.0
* @private
*/
addAdditionalData: function (tab, data, callback) {
chrome.cookies.getAll({url: data.url}, function (cookies) {
var cookieNames = [];
cookies = cookies || [];
// Extracts the names of every cookie
for (var i = 0; i < cookies.length; i++) {
cookieNames.push(cookies[i].name);
}
$.extend(data, {
cookie: function () {
return function (text, render) {
var name = render(text),
value = '';
// Attempts to find the value for the cookie name
for (var j = 0; j < cookies.length; j++) {
if (cookies[j].name === name) {
value = cookies[j].value;
break;
}
}
return value;
};
},
cookies: cookieNames
});
// Prevents hanging on pages where content script wasn't executed
if (ext.isProtectedPage(tab)) {
$.extend(data, {
selection: '',
selectionlinks: []
});
callback();
} else {
chrome.tabs.sendRequest(tab.id, {}, function (response) {
$.extend(data, {
selection: response.text || '',
selectionlinks: response.urls || []
});
callback();
});
}
});
},
/**
* <p>Adds the specified feature name to those stored in localStorage.</p>
* <p>The feature name is only added if it doesn't already exist.</p>
* @param {String} name The feature name to be stored.
* @returns {Boolean} <code>true</code> if the name was stored; otherwise
* <code>false</code>.
* @since 0.1.0.0
* @private
*/
addFeatureName: function (name) {
var features = utils.get('features');
if (features.indexOf(name) === -1) {
features.push(name);
utils.set('features', features);
return true;
}
return false;
},
/**
* <p>Creates an Object containing data based on information derived from
* the specified tab and menu item data.</p>
* @param {Tab} tab The tab whose information is to be extracted.
* @param {OnClickData} onClickData The details about the menu item clicked
* and the context where the click happened.
* @param {function} shortCallback The function to be called if/when a
* shortened URL is requested when parsing the template's content.
* @returns {Object} The data based on information extracted from the tab
* provided and its URL. This can contain Strings, Arrays, Objects, and
* functions.
* @see ext.buildStandardData
* @since 0.1.0.0
* @private
*/
buildDerivedData: function (tab, onClickData, shortCallback) {
var data = {
title: tab.title,
url: ''
};
if (onClickData.linkUrl) {
data.url = onClickData.linkUrl;
} else if (onClickData.srcUrl) {
data.url = onClickData.srcUrl;
} else if (onClickData.frameUrl) {
data.url = onClickData.frameUrl;
} else {
data.url = onClickData.pageUrl;
}
return ext.buildStandardData(data, shortCallback);
},
/**
* <p>Creates a <code><li/></code> representing the feature provided.
* This is to be inserted in to the <code><ul/></code> in the popup
* page but is created here to optimize display times for the popup.</p>
* @param {Object} feature The information of the feature to be used.
* @returns {jQuery} The generated <code><li/></code> jQuery object.
* @since 0.1.0.0
* @private
*/
buildFeature: function (feature) {
var image = '';
for (var j = 0; j < ext.images.length; j++) {
if (ext.images[j].id === feature.image) {
image = '../images/' + ext.images[j].file;
break;
}
}
image = image || '../images/spacer.png';
var item = $('<li/>', {
name: feature.name,
onclick: 'popup.sendRequest(this);'
}),
menu = $('<div/>', {
'class': 'menu',
style: 'background-image: url(\'' + image + '\');'
});
menu.append($('<span/>', {
'class': 'text',
text: feature.title
}));
if (utils.get('shortcuts')) {
var modifiers = ext.shortcutModifiers;
if (ext.isThisPlatform('mac')) {
modifiers = ext.shortcutMacModifiers;
}
menu.append($('<span/>', {
'class': 'shortcut',
html: (feature.shortcut) ? modifiers + feature.shortcut : ''
}));
}
return item.append(menu);
},
/**
* <p>Builds the HTML to populate the popup with to optimize popup loading
* times.</p>
* @since 0.1.0.0
* @private
*/
buildPopup: function () {
var item = $('<div id="item"/>'),
itemList = $('<ul id="itemList"/>'),
loadDiv = $('<div id="loadDiv"/>');
loadDiv.append($('<img src="../images/loading.gif"/>'), $('<div/>', {
text: chrome.i18n.getMessage('shortening')
}));
// Generates the HTML for each feature
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].enabled) {
itemList.append(ext.buildFeature(ext.features[i]));
}
}
// Adds generic message to state the obvious... list is empty
if (itemList.find('li').length === 0) {
$('<li/>').append(
$('<div/>', {
'class': 'menu',
style: 'background-image: url(\'../images/spacer.png\');'
}).append(
$('<span/>', {
'class': 'text',
style: 'margin-left: 0',
text: chrome.i18n.getMessage('empty')
})
)
).appendTo(itemList);
}
item.append(itemList);
ext.popupHTML = $('<div/>').append(loadDiv, item).html();
},
/**
* <p>Creates an Object containing data based on information extracted from
* the specified tab.</p>
* <p>This function merges this data with additional information relating
* to the URL of the tab.</p>
* <p>If a shortened URL is requested when parsing the template's content
* later the callback function specified is called to handle this scenario
* as we don't want to call a URL shortener service unless it is
* required.</p>
* @param {Tab} tab The tab whose information is to be extracted.
* @param {function} shortCallback The function to be called if/when a
* shortened URL is requested when parsing the template's content.
* @returns {Object} The data based on information extracted from the tab
* provided and its URL. This can contain Strings, Arrays, Objects, and
* functions.
* @since 0.1.0.0
* @private
*/
buildStandardData: function (tab, shortCallback) {
var compatibility = false,
data = {},
title = '',
url = {};
for (var i = 0; i < ext.support.length; i++) {
if (ext.isExtensionActive(tab,
ext.support[i].extensionId)) {
title = ext.support[i].title(tab.title);
url = $.url(ext.support[i].url(tab.url));
compatibility = true;
break;
}
}
if (!compatibility) {
title = tab.title;
url = $.url(tab.url);
}
$.extend(data, url.attr(), {
bitly: utils.get('bitly'),
bitlyapikey: utils.get('bitlyApiKey'),
bitlyusername: utils.get('bitlyUsername'),
browser: ext.browser.title,
browserversion: ext.browser.version,
contextmenu: utils.get('contextMenu'),
cookiesenabled: window.navigator.cookieEnabled,
decode: function () {
return function (text, render) {
return decodeURIComponent(render(text));
};
},
doanchortarget: utils.get('doAnchorTarget'),
doanchortitle: utils.get('doAnchorTitle'),
encode: function () {
return function (text, render) {
return encodeURIComponent(render(text));
};
},
// Deprecated since 0.1.0.2, use encode instead
encoded: encodeURIComponent(url.attr('source')),
favicon: tab.favIconUrl,
fparam: function () {
return function (text, render) {
return url.fparam(render(text));
};
},
fparams: url.fparam(),
fsegment: function () {
return function (text, render) {
return url.fsegment(parseInt(render(text), 10));
};
},
fsegments: url.fsegment(),
googl: utils.get('googl'),
googloauth: utils.get('googlOAuth'),
java: window.navigator.javaEnabled(),
notificationduration: utils.get('notificationDuration') / 1000,
notifications: utils.get('notifications'),
offline: !window.navigator.onLine,
// Deprecated since 0.1.0.2, use originalUrl instead
originalsource: tab.url,
originaltitle: tab.title || url.attr('source'),
originalurl: tab.url,
os: ext.operatingSystem,
param: function () {
return function (text, render) {
return url.param(render(text));
};
},
params: url.param(),
segment: function () {
return function (text, render) {
return url.segment(parseInt(render(text), 10));
};
},
segments: url.segment(),
'short': function () {
return shortCallback();
},
shortcuts: utils.get('shortcuts'),
title: title || url.attr('source'),
url: url.attr('source'),
version: ext.version,
yourls: utils.get('yourls'),
yourlspassword: utils.get('yourlsPassword'),
yourlssignature: utils.get('yourlsSignature'),
yourlsurl: utils.get('yourlsUrl'),
yourlsusername: utils.get('yourlsUsername')
});
return data;
},
/**
* <p>Calls the active URL shortener service with the URL provided in order
* to obtain a corresponding short URL.</p>
* <p>This function calls the callback function specified with the result
* once it has been received.</p>
* @param {String} url The URL to be shortened and added to the clipboard.
* @param {function} callback The function to be called once a response has
* been received.
* @see ext.shorteners
* @since 0.1.0.0 - Previously located in <code>helper</code>.
*/
callUrlShortener: function (url, callback) {
ext.callUrlShortenerHelper(url, function (url, service) {
var name = service.name;
if (!service.url()) {
callback({
message: chrome.i18n.getMessage('shortener_config_error',
name),
shortener: name,
success: false
});
return;
}
try {
var params = service.getParameters(url) || {};
var req = new XMLHttpRequest();
req.open(service.method, service.url() + '?' + $.param(params),
true);
req.setRequestHeader('Content-Type', service.contentType);
if (service.oauth && service.isOAuthEnabled()) {
req.setRequestHeader('Authorization',
service.oauth.getAuthorizationHeader(service.url(),
service.method, params));
}
req.onreadystatechange = function () {
if (req.readyState === 4) {
callback({
shortUrl: service.output(req.responseText),
shortener: name,
success: true
});
}
};
req.send(service.input(url));
} catch (e) {
console.log(e.message || e);
callback({
message: chrome.i18n.getMessage('shortener_error', name),
shortener: name,
success: false
});
}
});
},
/**
* <p>Helper method which determines when the callback function provided is
* called depending on whether or not the active URL Shortener supports
* OAuth.</p>
* @param {String} url The URL to be shortened and added to the clipboard.
* @param {Function} callback The function that is called either
* immediately or once autherized if OAuth is supported.
* @see ext.callUrlShortener
* @since 0.1.0.0 - Previously located in <code>helper</code>.
* @private
*/
callUrlShortenerHelper: function (url, callback) {
var service = ext.getUrlShortener();
if (service.oauth && service.isOAuthEnabled()) {
service.oauth.authorize(function () {
callback(url, service);
});
} else {
callback(url, service);
}
},
/**
* <p>Adds the specified string to the system clipboard.</p>
* <p>This is the core function for copying to the clipboard by the
* extension. All supported copy requests should, at some point, call this
* function.</p>
* <p>If the string provided is empty a single space will be copied
* instead.</p>
* @param {String} str The string to be added to the clipboard.
* @param {Boolean} [hidden] <code>true</code> to avoid updating
* {@link ext.status} and showing a notification; otherwise
* <code>false</code>.
*/
copy: function (str, hidden) {
var result = false,
sandbox = $('#sandbox').val(str).select();
result = document.execCommand('copy');
sandbox.val('');
if (!hidden) {
ext.status = result;
ext.showNotification();
}
},
/**
* <p>Deletes the values of the feature with the specified name from
* their respective locations.</p>
* @param {String} name The name of the feature whose values are to be
* deleted.
* @since 0.1.0.0
* @private
*/
deleteFeature: function (name) {
utils.remove('feat_' + name + '_content');
utils.remove('feat_' + name + '_enabled');
utils.remove('feat_' + name + '_image');
utils.remove('feat_' + name + '_index');
utils.remove('feat_' + name + '_readonly');
utils.remove('feat_' + name + '_shortcut');
utils.remove('feat_' + name + '_title');
},
/**
* <p>Injects and executes the <code>content.js</code> script within each
* of the tabs provided (where valid).</p>
* @param {Object[]} tabs The tabs to execute the script in.
* @private
*/
executeScriptsInExistingTabs: function (tabs) {
for (var i = 0; i < tabs.length; i++) {
if (!ext.isProtectedPage(tabs[i])) {
chrome.tabs.executeScript(tabs[i].id, {file: 'js/content.js'});
}
}
},
/**
* <p>Injects and executes the <code>content.js</code> script within all
* the tabs (where valid) of each Chrome window.</p>
* @private
*/
executeScriptsInExistingWindows: function () {
chrome.windows.getAll(null, function (windows) {
for (var i = 0; i < windows.length; i++) {
chrome.tabs.getAllInWindow(windows[i].id,
ext.executeScriptsInExistingTabs);
}
});
},
/**
* <p>Attempts to return the current version of the user's browser.</p>
* @returns {String} The browser's version.
* @since 0.1.0.3
* @private
*/
getBrowserVersion: function () {
var str = navigator.userAgent,
idx = str.indexOf(ext.browser.title);
if (idx !== -1) {
str = str.substring(idx + ext.browser.title.length + 1);
idx = str.indexOf(' ');
return (idx === -1) ? str : str.substring(0, idx);
}
},
/**
* <p>Attempts to return the information for the any feature with the
* specified menu identifier assigned to it.</p>
* @param {Integer} menuId The menu identifier to be queried.
* @returns {Object} The feature using the menu identifier provided, if
* possible.
* @since 0.1.0.0
* @private
*/
getFeatureWithMenuId: function (menuId) {
var feature;
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].menuId === menuId) {
feature = ext.features[i];
break;
}
}
return feature;
},
/**
* <p>Attempts to return the information for the any feature with the
* specified shortcut assigned to it.</p>
* <p>Disabled features are not included in this search.</p>
* @param {String} shortcut The shortcut to be queried.
* @returns {Object} The feature using the shortcut provided, if possible.
* @since 0.1.0.0
*/
getFeatureWithShortcut: function (shortcut) {
var feature;
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].enabled &&
ext.features[i].shortcut === shortcut) {
feature = ext.features[i];
break;
}
}
return feature;
},
/**
* <p>Attempts to return the operating system being used by the user.</p>
* @returns {String} The user's operating system.
* @since 0.1.0.3
* @private
*/
getOperatingSystem: function () {
var os = {},
str = navigator.platform;
for (var i = 0; i < ext.operatingSystems.length; i++) {
os = ext.operatingSystems[i];
if (str.indexOf(os.substring) !== -1) {
str = os.title;
break;
}
}
return str;
},
/**
* <p>Returns the information for the active URL shortener service.</p>
* @returns {Object} The active URL shortener.
* @see ext.shorteners
*/
getUrlShortener: function () {
// Attempts to lookup enabled URL shortener service
for (var i = 0; i < ext.shorteners.length; i++) {
if (ext.shorteners[i].isEnabled()) {
return ext.shorteners[i];
}
}
/*
* Should never reach here but we'll return goo.gl service by default
* after ensuring it's enabled from now on to save some time next
* lookup.
*/
utils.set('googl', true);
return ext.shorteners[1];
},
/**
* <p>Initializes the background page.</p>
* <p>This involves initializing the settings, injecting keyboard shortcut
* listeners and adding the request listeners.</p>
*/
init: function () {
utils.init('update_progress', {
features: [],
settings: [],
shorteners: []
});
ext.init_update();
utils.init('contextMenu', true);
utils.init('notifications', true);
utils.init('notificationDuration', 3000);
utils.init('shortcuts', true);
utils.init('doAnchorTarget', false);
utils.init('doAnchorTitle', false);
ext.initFeatures();
ext.initUrlShorteners();
ext.executeScriptsInExistingWindows();
chrome.extension.onRequest.addListener(ext.onRequest);
chrome.extension.onRequestExternal.addListener(ext.onExternalRequest);
// Derives static browser and OS information
ext.browser.version = ext.getBrowserVersion();
ext.operatingSystem = ext.getOperatingSystem();
// Derives extension's version
$.getJSON(chrome.extension.getURL('manifest.json'), function (data) {
ext.version = data.version;
});
},
/**
* <p>Handles the conversion/removal of older version of settings that may
* have been stored previously by {@link ext.init}.</p>
* @since 0.1.0.0
* @private
*/
init_update: function () {
var update = utils.get('update_progress');
// Checks if 0.1.0.0 update for settings is required
if (update.settings.indexOf('0.1.0.0') === -1) {
// Performs 0.1.0.0 update for settings
utils.rename('settingNotification', 'notifications', true);
utils.rename('settingNotificationTimer', 'notificationDuration',
3000);
utils.rename('settingShortcut', 'shortcuts', true);
utils.rename('settingTargetAttr', 'doAnchorTarget', false);
utils.rename('settingTitleAttr', 'doAnchorTitle', false);
utils.remove('settingIeTabExtract');
utils.remove('settingIeTabTitle');
// Ensures 0.1.0.0 update for settings is not performed again
update.settings.push('0.1.0.0');
utils.set('update_progress', update);
}
},
/**
* <p>Initilaizes the values of the specified feature by potentially
* storing them in to their respective locations.</p>
* <p>This function should only be used initializing default features and
* some values will always overwrite the existing one to provide
* functionality for changing current defaults.</p>
* <p>Names of initialized features are also added to that stored in
* localStorage if they do not already exist there.</p>
* @param {Object} feature The feature whose values are to be initialized.
* @param {String} feature.content The mustache template for the feature
* (overwrites).
* @param {Boolean} feature.enabled <code>true</code> if the feature is
* enabled; otherwise <code>false</code>.
* @param {Integer} feature.image The identifier of the feature's image.
* @param {Integer} feature.index The index representing the feature's
* display order.
* @param {String} feature.name The unique name of the feature.
* @param {Boolean} feature.readOnly <code>true</code> if the feature is
* read-only and certain values cannot be editted by the user; otherwise
* <code>false</code> (overwrites).
* @param {String} feature.shortcut The keyboard shortcut assigned to the
* feature.
* @param {String} feature.title The title of the feature (overwrites).
* @returns {Object} The feature provided.
* @since 0.1.0.0
* @private
*/
initFeature: function (feature) {
var name = feature.name;
utils.set('feat_' + name + '_content', feature.content);
utils.init('feat_' + name + '_enabled', feature.enabled);
utils.init('feat_' + name + '_image', feature.image);
utils.init('feat_' + name + '_index', feature.index);
utils.set('feat_' + name + '_readonly', feature.readOnly);
utils.init('feat_' + name + '_shortcut', feature.shortcut);
utils.set('feat_' + name + '_title', feature.title);
ext.addFeatureName(name);
return feature;
},
/**
* <p>Initializes the supported copy request features (including their
* corresponding settings).</p>
* @private
*/
initFeatures: function () {
utils.init('features', []);
ext.initFeatures_update();
for (var i = 0; i < ext.defaultFeatures.length; i++) {
ext.initFeature(ext.defaultFeatures[i]);
}
ext.updateFeatures();
},
/**
* <p>Handles the conversion/removal of older version of settings that may
* have been stored previously by {@link ext.initFeatures}.</p>
* @since 0.1.0.0
* @private
*/
initFeatures_update: function () {
var update = utils.get('update_progress');
// Checks if 0.1.0.0 update for features is required
if (update.features.indexOf('0.1.0.0') === -1) {
// Performs 0.1.0.0 update for features
utils.rename('copyAnchorEnabled', 'feat__anchor_enabled', true);
utils.rename('copyAnchorOrder', 'feat__anchor_index', 2);
utils.rename('copyBBCodeEnabled', 'feat__bbcode_enabled', false);
utils.rename('copyBBCodeOrder', 'feat__bbcode_index', 4);
utils.rename('copyEncodedEnabled', 'feat__encoded_enabled', true);
utils.rename('copyEncodedOrder', 'feat__encoded_index', 3);
utils.rename('copyShortEnabled', 'feat__short_enabled', true);
utils.rename('copyShortOrder', 'feat__short_index', 1);
utils.rename('copyUrlEnabled', 'feat__url_enabled', true);
utils.rename('copyUrlOrder', 'feat__url_index', 0);
// Ensures 0.1.0.0 update for features is not performed again
update.features.push('0.1.0.0');
utils.set('update_progress', update);
}
// Checks if 0.2.0.0 update for features is required
if (update.features.indexOf('0.2.0.0') === -1) {
// Performs 0.2.0.0 update for features
var image,
names = utils.get('features');
for (var i = 0; i < names.length; i++) {
utils.rename('feat_' + names[i] + '_template', 'feat_' +
names[i] + '_content');
image = utils.get('feat_' + names[i] + '_image');
if (typeof image === 'string') {
for (var j = 0; j < ext.images.length; j++) {
if (ext.images[j].file === image) {
utils.set('feat_' + names[i] + '_image',
ext.images[j].id);
break;
}
}
} else if (typeof image === 'undefined') {
utils.set('feat_' + names[i] + '_image', 0);
}
}
// Ensures 0.2.0.0 update for features is not performed again
update.features.push('0.2.0.0');
utils.set('update_progress', update);
}
},
/**
* <p>Initializes the settings related to the supported URL Shortener
* services.</p>
* @private
*/
initUrlShorteners: function () {
ext.initUrlShorteners_update();
utils.init('bitly', false);
utils.init('bitlyApiKey', '');
utils.init('bitlyUsername', '');
utils.init('googl', true);
utils.init('googlOAuth', true);
utils.init('yourls', false);
utils.init('yourlsPassword', '');
utils.init('yourlsSignature', '');
utils.init('yourlsUrl', '');
utils.init('yourlsUsername', '');
},
/**
* <p>Handles the conversion/removal of older version of settings that may
* have been stored previously by {@link ext.initUrlShorteners}.</p>
* @since 0.1.0.0
* @private
*/
initUrlShorteners_update: function () {
var update = utils.get('update_progress');
// Checks if 0.1.0.0 update for URL shorteners is required
if (update.shorteners.indexOf('0.1.0.0') === -1) {
// Performs 0.1.0.0 update for URL shorteners
utils.rename('bitlyEnabled', 'bitly', false);
utils.rename('bitlyXApiKey', 'bitlyApiKey', '');
utils.rename('bitlyXLogin', 'bitlyUsername', '');
utils.rename('googleEnabled', 'googl', true);
utils.rename('googleOAuthEnabled', 'googlOAuth', true);
// Ensures 0.1.0.0 update for URL shorteners is not performed again
update.shorteners.push('0.1.0.0');
utils.set('update_progress', update);
}
},
/**
* <p>Determines whether or not the sender provided is from a blacklisted
* extension.</p>
* @param {MessageSender} sender The sender to be tested.
* @returns {Boolean} <code>true</code> if the sender is blacklisted;
* otherwise <code>false</code>.
* @private
*/
isBlacklisted: function (sender) {
for (var i = 0; i < ext.blacklistedExtensions.length; i++) {
if (ext.blacklistedExtensions[i] === sender.id) {
return true;
}
}
return false;
},
/**
* <p>Returns whether or not the extension with the specified identifier is
* active on the tab provided.</p>
* @param {Tab} tab The tab to be tested.
* @param {String} extensionId The identifier of the extension to be
* tested.
* @returns {Boolean} <code>true</code> if the extension is active on the
* tab provided; otherwise <code>false</code>.
* @since 0.1.1.1
* @private
*/
isExtensionActive: function (tab, extensionId) {
return (ext.isSpecialPage(tab) && tab.url.indexOf(extensionId) !== -1);
},
/**
* <p>Determines whether or not the tab provided is currently displaying a
* page on the Chrome Extension Gallery (i.e. Web Store).</p>
* @param {Tab} tab The tab to be tested.
* @returns {Boolean} <code>true</code> if displaying a page on the Chrome
* Extension Gallery; otherwise <code>false</code>.
* @since 0.2.1.0
*/
isExtensionGallery: function (tab) {
return tab.url.indexOf('https://chrome.google.com/webstore') === 0;
},
/**
* <p>Determines whether or not the tab provided is currently display a
* <em>protected</em> page (i.e. a page that content scripts cannot be
* executed on).</p>
* @param {Tab} tab The tab to be tested.
* @returns {Boolean} <code>true</code> if displaying a <em>protected</em>
* page; otherwise <code>false</code>.
* @since 0.2.1.0
*/
isProtectedPage: function (tab) {
return ext.isSpecialPage(tab) || ext.isExtensionGallery(tab);
},
/**
* <p>Determines whether or not the tab provided is currently displaying a
* <em>special</em> page (i.e. a page that is internal to the browser).</p>
* @param {Tab} tab The tab to be tested.
* @returns {Boolean} <code>true</code> if displaying a <em>special</em>
* page; otherwise <code>false</code>.
*/
isSpecialPage: function (tab) {
return tab.url.indexOf('chrome') === 0;
},
/**
* <p>Determines whether or not the user's OS matches that provided.</p>
* @param {String} os The operating system to be tested.
* @returns {Boolean} <code>true</code> if the user's OS matches that
* specified; otherwise <code>false</code>.
*/
isThisPlatform: function (os) {
return navigator.userAgent.toLowerCase().indexOf(os) !== -1;
},
/**
* <p>Loads the values of the feature with the specified name from their
* respective locations.</p>
* @param {String} name The name of the feature whose values are to be
* fetched.
* @returns {Object} The feature for the name provided.
* @since 0.1.0.0
* @private
*/
loadFeature: function (name) {
return {
content: utils.get('feat_' + name + '_content'),
enabled: utils.get('feat_' + name + '_enabled'),
image: utils.get('feat_' + name + '_image'),
index: utils.get('feat_' + name + '_index'),
name: name,
readOnly: utils.get('feat_' + name + '_readonly'),
shortcut: utils.get('feat_' + name + '_shortcut'),
title: utils.get('feat_' + name + '_title')
};
},
/**
* <p>Loads the values of each stored feature from their respective
* locations.</p>
* <p>The array returned is sorted based on the index of each feature.</p>
* @returns {Object[]} The array of the features loaded.
* @since 0.1.0.0
*/
loadFeatures: function () {
var features = [],
names = utils.get('features');
for (var i = 0; i < names.length; i++) {
features.push(ext.loadFeature(names[i]));
}
features.sort(function (a, b) {
return a.index - b.index;
});
return features;
},
/**
* <p>Listener for external requests to the extension.</p>
* <p>This function only serves the request if the originating extension is
* not blacklisted.</p>
* @param {Object} request The request sent by the calling script.
* @param {Object} request.data The data for the copy request feature to be
* served.
* @param {KeyEvent} [request.data.e] The DOM <code>KeyEvent</code>
* responsible for generating the copy request. Only used if type is
* "shortcut".
* @param {String} [request.data.feature] The name of the feature on which
* to execute the copy request.
* @param {String} [request.data.key] The character of the final key
* responsible for firing the <code>KeyEvent</code>. Only used if type is
* "shortcut".
* @param {String} request.type The type of request being made.
* @param {MessageSender} [sender] An object containing information about
* the script context that sent a message or request.
* @param {function} [sendResponse] Function to call when you have a
* response. The argument should be any JSON-ifiable object, or undefined
* if there is no response.
* @private
*/
onExternalRequest: function (request, sender, sendResponse) {
if (!ext.isBlacklisted(sender)) {
ext.onRequest(request, sender, sendResponse);
}
},
/**
* <p>Listener for internal requests to the extension.</p>
* <p>If the request originated from a keyboard shortcut this function only
* serves that request if the keyboard shortcuts have been enabled by the
* user (or by default).</p>
* @param {Object} request The request sent by the calling script.
* @param {Object} request.data The data for the copy request feature to be
* served.
* @param {KeyEvent} [request.data.e] The DOM <code>KeyEvent</code>
* responsible for generating the copy request. Only used if type is
* "shortcut".
* @param {String} [request.data.feature] The name of the feature on which
* to execute the copy request.
* @param {String} [request.data.key] The character of the final key
* responsible for firing the <code>KeyEvent</code>. Only used if type is
* "shortcut".
* @param {String} request.type The type of request being made.
* @param {MessageSender} [sender] An object containing information about
* the script context that sent a message or request.
* @param {function} [sendResponse] Function to call when you have a
* response. The argument should be any JSON-ifiable object, or undefined
* if there is no response.
* @private
*/
onRequest: function (request, sender, sendResponse) {
if (request.type !== 'shortcut' || utils.get('shortcuts')) {
ext.onRequestHelper(request, sender, sendResponse);
}
},
/**
* <p>Helper function for the internal/external request listeners.</p>
* <p>This function will handle the request based on its type and the data
* provided.</p>
* @param {Object} request The request sent by the calling script.
* @param {Object} request.data The data for the copy request feature to be
* served.
* @param {KeyEvent} [request.data.e] The DOM <code>KeyEvent</code>
* responsible for generating the copy request. Only used if type is
* "shortcut".
* @param {String} [request.data.feature] The name of the feature on which
* to execute the copy request.
* @param {String} [request.data.key] The character of the final key
* responsible for firing the <code>KeyEvent</code>. Only used if type is
* "shortcut".
* @param {String} request.type The type of request being made.
* @param {MessageSender} [sender] An object containing information about
* the script context that sent a message or request.
* @param {function} [sendResponse] Function to call when you have a
* response. The argument should be any JSON-ifiable object, or undefined
* if there is no response.
* @private
*/
onRequestHelper: function (request, sender, sendResponse) {
if (request.type === 'version') {
sendResponse({version: ext.version});
return;
}
chrome.tabs.getSelected(null, function (tab) {
var data = {},
feature,
popup = chrome.extension.getViews({type: 'popup'})[0],
shortCalled = false,
shortPlaceholder = 'short' +
(Math.floor(Math.random() * 99999 + 1000));
function copyOutput(str) {
if (str) {
ext.copy(str);
} else {
ext.message = chrome.i18n.getMessage('copy_fail_empty');
ext.status = false;
ext.showNotification();
}
}
function shortCallback() {
shortCalled = true;
return '{' + shortPlaceholder + '}';
}
if (popup) {
$('#item', popup.document).hide();
$('#loadDiv', popup.document).show();
}
try {
switch (request.type) {
case 'menu':
data = ext.buildDerivedData(tab, request.data,
shortCallback);
feature = ext.getFeatureWithMenuId(
request.data.menuItemId);
break;
case 'popup':
// Should be cheaper than searching ext.features...
data = ext.buildStandardData(tab, shortCallback);
feature = ext.loadFeature(request.data.name);
break;
case 'shortcut':
data = ext.buildStandardData(tab, shortCallback);
feature = ext.getFeatureWithShortcut(request.data.key);
break;
}
} catch (e) {
if (e instanceof URIError) {
ext.message = chrome.i18n.getMessage('copy_fail_uri');
} else {
ext.message = chrome.i18n.getMessage('copy_fail_error');
}
ext.status = false;
ext.showNotification();
return;
}
if (feature) {
ext.addAdditionalData(tab, data, function () {
if (!feature.content) {
// Displays empty template error message
copyOutput();
return;
}
var output = Mustache.to_html(feature.content, data);
if (shortCalled) {
ext.callUrlShortener(data.source, function (response) {
if (response.success && response.shortUrl) {
var newData = {};
newData[shortPlaceholder] = response.shortUrl;
copyOutput(Mustache.to_html(output, newData));
} else {
if (!response.message) {
response.message = chrome.i18n.getMessage(
'shortener_error',
response.shortener);
}
ext.message = response.message;
ext.status = false;
ext.showNotification();
}
});
} else {
copyOutput(output);
}
});
} else {
if (popup) {
popup.close();
}
}
});
},
/**
* <p>Attempts to retrieve the contents of the system clipboard.</p>
* @returns {String} The string taken from the clipboard.
* @since 0.2.0.1
*/
paste: function () {
var result = '',
sandbox = $('#sandbox').val('').select();
if (document.execCommand('paste')) {
result = sandbox.val();
}
sandbox.val('');
return result;
},
/**
* <p>Removes the specified feature name from those stored in
* localStorage.</p>
* @param {String} name The feature name to be removed.
* @since 0.1.0.0
* @private
*/
removeFeatureName: function (name) {
var features = utils.get('features'),
idx = features.indexOf(name);
if (idx !== -1) {
features.splice(idx, 1);
utils.set('features', features);
}
},
/**
* <p>Resets the message and status associated with the current copy
* request.</p>
* <p>This function should be called on the completion of a copy request
* regardless of its outcome.</p>
*/
reset: function () {
ext.message = '';
ext.status = false;
},
/**
* <p>Stores the values of the specified feature in to their respective
* locations.</p>
* @param {Object} feature The feature whose values are to be saved.
* @param {String} feature.content The mustache template for the feature.
* @param {Boolean} feature.enabled <code>true</code> if the feature is
* enabled; otherwise <code>false</code>.
* @param {Integer} feature.image The identifier of the feature's image.
* @param {Integer} feature.index The index representing the feature's
* display order.
* @param {String} feature.name The unique name of the feature.
* @param {Boolean} feature.readOnly <code>true</code> if the feature is
* read-only and certain values cannot be editted by the user; otherwise
* <code>false</code>.
* @param {String} feature.shortcut The keyboard shortcut assigned to the
* feature.
* @param {String} feature.title The title of the feature.
* @returns {Object} The feature provided.
* @since 0.1.0.0
* @private
*/
saveFeature: function (feature) {
var name = feature.name;
utils.set('feat_' + name + '_content', feature.content);
utils.set('feat_' + name + '_enabled', feature.enabled);
utils.set('feat_' + name + '_image', feature.image);
utils.set('feat_' + name + '_index', feature.index);
utils.set('feat_' + name + '_readonly', feature.readOnly);
utils.set('feat_' + name + '_shortcut', feature.shortcut);
utils.set('feat_' + name + '_title', feature.title);
return feature;
},
/**
* <p>Stores the values of each of the speciifed features in to their
* respective locations.</p>
* <p>Any features no longer in use are removed from localStorage in an
* attempt to keep capacity under control.</p>
* @param {Object[]} features The features whose values are to be saved.
* @returns {Object[]} The array of features provided.
* @since 0.1.0.0
*/
saveFeatures: function (features) {
var names = [],
oldNames = utils.get('features');
for (var i = 0; i < features.length; i++) {
names.push(features[i].name);
ext.saveFeature(features[i]);
}
// Ensures any features no longer used are removed from localStorage
for (var j = 0; j < oldNames.length; j++) {
if (names.indexOf(oldNames[j]) === -1) {
ext.deleteFeature(oldNames[j]);
}
}
utils.set('features', names);
return features;
},
/**
* <p>Displays a Chrome notification to inform the user on whether or not
* the copy request was successful.</p>
* <p>This function ensures that {@link ext} is reset and that
* notifications are only displayed if specified by the user (or by
* default).</p>
* @see ext.reset
*/
showNotification: function () {
var popup = chrome.extension.getViews({type: 'popup'})[0];
if (utils.get('notifications')) {
webkitNotifications.createHTMLNotification(
chrome.extension.getURL('pages/notification.html')
).show();
} else {
ext.reset();
}
if (popup) {
popup.close();
}
},
/**
* <p>Updates the context menu items to reflect respective features.</p>
* @since 0.1.0.0
* @private
*/
updateContextMenu: function () {
// Ensures any previously added context menu items are removed
chrome.contextMenus.removeAll(function () {
function onMenuClick(info, tab) {
ext.onRequestHelper({
data: info,
type: 'menu'
});
}
if (utils.get('contextMenu')) {
var menuId,
parentId = chrome.contextMenus.create({
contexts: ['all'],
title: chrome.i18n.getMessage('name')
});
for (var i = 0; i < ext.features.length; i++) {
if (ext.features[i].enabled) {
menuId = chrome.contextMenus.create({
contexts: ['all'],
onclick: onMenuClick,
parentId: parentId,
title: ext.features[i].title
});
ext.features[i].menuId = menuId;
}
}
}
});
},
/**
* <p>Updates the list of features stored locally to reflect that stored
* in localStorage.</p>
* <p>It is important that this function is called whenever features might
* of changed as this also updates the prepared popup HTML.</p>
*/
updateFeatures: function () {
ext.features = ext.loadFeatures();
ext.buildPopup();
ext.updateContextMenu();
}
}; | replacing deprecated methods for #54
| src/js/background.js | replacing deprecated methods for #54 | <ide><path>rc/js/background.js
<ide> executeScriptsInExistingWindows: function () {
<ide> chrome.windows.getAll(null, function (windows) {
<ide> for (var i = 0; i < windows.length; i++) {
<del> chrome.tabs.getAllInWindow(windows[i].id,
<add> chrome.tabs.query({windowId: windows[i].id},
<ide> ext.executeScriptsInExistingTabs);
<ide> }
<ide> });
<ide> sendResponse({version: ext.version});
<ide> return;
<ide> }
<del> chrome.tabs.getSelected(null, function (tab) {
<add> chrome.tabs.query({active: true}, function (tab) {
<ide> var data = {},
<ide> feature,
<ide> popup = chrome.extension.getViews({type: 'popup'})[0], |
|
Java | apache-2.0 | error: pathspec 'platform/util/src/com/intellij/util/ui/JBInsets.java' did not match any file(s) known to git
| 0fd893c1e801097a4337bedf347956620339e9df | 1 | pwoodworth/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,robovm/robovm-studio,allotria/intellij-community,supersven/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ryano144/intellij-community,holmes/intellij-community,ernestp/consulo,clumsy/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,da1z/intellij-community,FHannes/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,signed/intellij-community,vvv1559/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,Distrotech/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,semonte/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,caot/intellij-community,Lekanich/intellij-community,consulo/consulo,asedunov/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,amith01994/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,caot/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,allotria/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,blademainer/intellij-community,dslomov/intellij-community,semonte/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,fitermay/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,slisson/intellij-community,caot/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ibinti/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,slisson/intellij-community,izonder/intellij-community,supersven/intellij-community,slisson/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,slisson/intellij-community,signed/intellij-community,diorcety/intellij-community,kool79/intellij-community,kdwink/intellij-community,izonder/intellij-community,vladmm/intellij-community,da1z/intellij-community,apixandru/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,FHannes/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,consulo/consulo,FHannes/intellij-community,signed/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,apixandru/intellij-community,amith01994/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ryano144/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,slisson/intellij-community,kool79/intellij-community,vvv1559/intellij-community,da1z/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,robovm/robovm-studio,clumsy/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,samthor/intellij-community,supersven/intellij-community,amith01994/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,fitermay/intellij-community,dslomov/intellij-community,signed/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,ibinti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,FHannes/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,clumsy/intellij-community,allotria/intellij-community,hurricup/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,caot/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,allotria/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,hurricup/intellij-community,xfournet/intellij-community,caot/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ernestp/consulo,mglukhikh/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,kdwink/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,kdwink/intellij-community,supersven/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,semonte/intellij-community,samthor/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,ernestp/consulo,gnuhub/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,allotria/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,da1z/intellij-community,jagguli/intellij-community,slisson/intellij-community,consulo/consulo,semonte/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,semonte/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,diorcety/intellij-community,fnouama/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,consulo/consulo,vladmm/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,signed/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,retomerz/intellij-community,petteyg/intellij-community,izonder/intellij-community,retomerz/intellij-community,diorcety/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,clumsy/intellij-community,ibinti/intellij-community,retomerz/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,retomerz/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ryano144/intellij-community,caot/intellij-community,kool79/intellij-community,petteyg/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,semonte/intellij-community,consulo/consulo,salguarnieri/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,blademainer/intellij-community,slisson/intellij-community,holmes/intellij-community,adedayo/intellij-community,xfournet/intellij-community,izonder/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,retomerz/intellij-community,blademainer/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,samthor/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,petteyg/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,da1z/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,holmes/intellij-community,adedayo/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,amith01994/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ryano144/intellij-community,ibinti/intellij-community,adedayo/intellij-community,diorcety/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,caot/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ernestp/consulo,jagguli/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,signed/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,jagguli/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,supersven/intellij-community,petteyg/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,holmes/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,holmes/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ryano144/intellij-community,FHannes/intellij-community,samthor/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,consulo/consulo,FHannes/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,signed/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,robovm/robovm-studio,jagguli/intellij-community,FHannes/intellij-community,robovm/robovm-studio,clumsy/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ernestp/consulo,vladmm/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,xfournet/intellij-community,asedunov/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,allotria/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,holmes/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,izonder/intellij-community,kool79/intellij-community,hurricup/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,retomerz/intellij-community,jagguli/intellij-community,robovm/robovm-studio,slisson/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,allotria/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,kool79/intellij-community,ibinti/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,da1z/intellij-community,xfournet/intellij-community,diorcety/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,caot/intellij-community,hurricup/intellij-community,xfournet/intellij-community,kool79/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,signed/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,supersven/intellij-community,supersven/intellij-community,signed/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,caot/intellij-community | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.ui;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class JBInsets extends Insets {
/**
* Creates and initializes a new <code>Insets</code> object with the
* specified top, left, bottom, and right insets.
*
* @param top the inset from the top.
* @param left the inset from the left.
* @param bottom the inset from the bottom.
* @param right the inset from the right.
*/
public JBInsets(int top, int left, int bottom, int right) {
super(top, left, bottom, right);
}
public int width() {
return left + right;
}
public int height() {
return top + bottom;
}
public static JBInsets create(@NotNull Insets insets) {
return insets instanceof JBInsets ? (JBInsets)insets
: new JBInsets(insets.top, insets.left, insets.bottom, insets.right);
}
}
| platform/util/src/com/intellij/util/ui/JBInsets.java | width + height
| platform/util/src/com/intellij/util/ui/JBInsets.java | width + height | <ide><path>latform/util/src/com/intellij/util/ui/JBInsets.java
<add>/*
<add> * Copyright 2000-2011 JetBrains s.r.o.
<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>package com.intellij.util.ui;
<add>
<add>import org.jetbrains.annotations.NotNull;
<add>
<add>import java.awt.*;
<add>
<add>/**
<add> * @author Konstantin Bulenkov
<add> */
<add>public class JBInsets extends Insets {
<add> /**
<add> * Creates and initializes a new <code>Insets</code> object with the
<add> * specified top, left, bottom, and right insets.
<add> *
<add> * @param top the inset from the top.
<add> * @param left the inset from the left.
<add> * @param bottom the inset from the bottom.
<add> * @param right the inset from the right.
<add> */
<add> public JBInsets(int top, int left, int bottom, int right) {
<add> super(top, left, bottom, right);
<add> }
<add>
<add> public int width() {
<add> return left + right;
<add> }
<add>
<add> public int height() {
<add> return top + bottom;
<add> }
<add>
<add> public static JBInsets create(@NotNull Insets insets) {
<add> return insets instanceof JBInsets ? (JBInsets)insets
<add> : new JBInsets(insets.top, insets.left, insets.bottom, insets.right);
<add> }
<add>} |
|
Java | apache-2.0 | 07efb963a967fd8d3c2342fb137f826481390ad3 | 0 | FasterXML/jackson-core,FasterXML/jackson-core | package com.fasterxml.jackson.core.json;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.io.*;
public class UTF8JsonGenerator
extends JsonGeneratorImpl
{
private final static byte BYTE_u = (byte) 'u';
private final static byte BYTE_0 = (byte) '0';
private final static byte BYTE_LBRACKET = (byte) '[';
private final static byte BYTE_RBRACKET = (byte) ']';
private final static byte BYTE_LCURLY = (byte) '{';
private final static byte BYTE_RCURLY = (byte) '}';
private final static byte BYTE_BACKSLASH = (byte) '\\';
private final static byte BYTE_COMMA = (byte) ',';
private final static byte BYTE_COLON = (byte) ':';
private final static byte BYTE_QUOTE = (byte) '"';
protected final static int SURR1_FIRST = 0xD800;
protected final static int SURR1_LAST = 0xDBFF;
protected final static int SURR2_FIRST = 0xDC00;
protected final static int SURR2_LAST = 0xDFFF;
// intermediate copies only made up to certain length...
private final static int MAX_BYTES_TO_BUFFER = 512;
final static byte[] HEX_CHARS = CharTypes.copyHexBytes();
private final static byte[] NULL_BYTES = { 'n', 'u', 'l', 'l' };
private final static byte[] TRUE_BYTES = { 't', 'r', 'u', 'e' };
private final static byte[] FALSE_BYTES = { 'f', 'a', 'l', 's', 'e' };
/*
/**********************************************************
/* Output buffering
/**********************************************************
*/
/**
* Underlying output stream used for writing JSON content.
*/
final protected OutputStream _outputStream;
/**
* Intermediate buffer in which contents are buffered before
* being written using {@link #_outputStream}.
*/
protected byte[] _outputBuffer;
/**
* Pointer to the position right beyond the last character to output
* (end marker; may be past the buffer)
*/
protected int _outputTail = 0;
/**
* End marker of the output buffer; one past the last valid position
* within the buffer.
*/
protected final int _outputEnd;
/**
* Maximum number of <code>char</code>s that we know will always fit
* in the output buffer after escaping
*/
protected final int _outputMaxContiguous;
/**
* Intermediate buffer in which characters of a String are copied
* before being encoded.
*/
protected char[] _charBuffer;
/**
* Length of <code>_charBuffer</code>
*/
protected final int _charBufferLength;
/**
* 6 character temporary buffer allocated if needed, for constructing
* escape sequences
*/
protected byte[] _entityBuffer;
/**
* Flag that indicates whether the output buffer is recycable (and
* needs to be returned to recycler once we are done) or not.
*/
protected boolean _bufferRecyclable;
/*
/**********************************************************
/* Quick flags
/**********************************************************
*/
/**
* Flag that is set if quoting is not to be added around
* JSON Object property names.
*/
protected final boolean _cfgUnqNames;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public UTF8JsonGenerator(IOContext ctxt, int features, ObjectCodec codec,
OutputStream out)
{
super(ctxt, features, codec);
_outputStream = out;
_bufferRecyclable = true;
_outputBuffer = ctxt.allocWriteEncodingBuffer();
_outputEnd = _outputBuffer.length;
/* To be exact, each char can take up to 6 bytes when escaped (Unicode
* escape with backslash, 'u' and 4 hex digits); but to avoid fluctuation,
* we will actually round down to only do up to 1/8 number of chars
*/
_outputMaxContiguous = _outputEnd >> 3;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
// By default we use this feature to determine additional quoting
if (isEnabled(Feature.ESCAPE_NON_ASCII)) {
setHighestNonEscapedChar(127);
}
_cfgUnqNames = !Feature.QUOTE_FIELD_NAMES.enabledIn(features);
}
public UTF8JsonGenerator(IOContext ctxt, int features, ObjectCodec codec,
OutputStream out,
byte[] outputBuffer, int outputOffset, boolean bufferRecyclable)
{
super(ctxt, features, codec);
_outputStream = out;
_bufferRecyclable = bufferRecyclable;
_outputTail = outputOffset;
_outputBuffer = outputBuffer;
_outputEnd = _outputBuffer.length;
// up to 6 bytes per char (see above), rounded up to 1/8
_outputMaxContiguous = _outputEnd >> 3;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
_cfgUnqNames = !Feature.QUOTE_FIELD_NAMES.enabledIn(features);
}
/*
/**********************************************************
/* Overridden configuration methods
/**********************************************************
*/
@Override
public Object getOutputTarget() {
return _outputStream;
}
/*
/**********************************************************
/* Overridden methods
/**********************************************************
*/
@Override
public void writeFieldName(String name) throws IOException
{
if (_cfgPrettyPrinter != null) {
_writePPFieldName(name);
return;
}
final int status = _writeContext.writeFieldName(name);
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) { // need comma
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_COMMA;
}
/* To support [JACKSON-46], we'll do this:
* (Question: should quoting of spaces (etc) still be enabled?)
*/
if (_cfgUnqNames) {
_writeStringSegments(name, false);
return;
}
final int len = name.length();
// Does it fit in buffer?
if (len > _charBufferLength) { // no, offline
_writeStringSegments(name, true);
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
name.getChars(0, len, _charBuffer, 0);
// But as one segment, or multiple?
if (len <= _outputMaxContiguous) {
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(_charBuffer, 0, len);
} else {
_writeStringSegments(_charBuffer, 0, len);
}
// and closing quotes; need room for one more char:
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeFieldName(SerializableString name) throws IOException
{
if (_cfgPrettyPrinter != null) {
_writePPFieldName(name);
return;
}
final int status = _writeContext.writeFieldName(name.getValue());
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_COMMA;
}
if (_cfgUnqNames) {
_writeUnq(name);
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
int len = name.appendQuotedUTF8(_outputBuffer, _outputTail);
if (len < 0) { // couldn't append, bit longer processing
_writeBytes(name.asQuotedUTF8());
} else {
_outputTail += len;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
private final void _writeUnq(SerializableString name) throws IOException {
int len = name.appendQuotedUTF8(_outputBuffer, _outputTail);
if (len < 0) {
_writeBytes(name.asQuotedUTF8());
} else {
_outputTail += len;
}
}
/*
/**********************************************************
/* Output method implementations, structural
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException
{
_verifyValueWrite("start an array");
_writeContext = _writeContext.createChildArrayContext();
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeStartArray(this);
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_LBRACKET;
}
}
@Override
public final void writeEndArray() throws IOException
{
if (!_writeContext.inArray()) {
_reportError("Current context not an ARRAY but "+_writeContext.getTypeDesc());
}
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeEndArray(this, _writeContext.getEntryCount());
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_RBRACKET;
}
_writeContext = _writeContext.getParent();
}
@Override
public final void writeStartObject() throws IOException
{
_verifyValueWrite("start an object");
_writeContext = _writeContext.createChildObjectContext();
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeStartObject(this);
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_LCURLY;
}
}
@Override
public final void writeEndObject() throws IOException
{
if (!_writeContext.inObject()) {
_reportError("Current context not an object but "+_writeContext.getTypeDesc());
}
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeEndObject(this, _writeContext.getEntryCount());
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_RCURLY;
}
_writeContext = _writeContext.getParent();
}
/**
* Specialized version of <code>_writeFieldName</code>, off-lined
* to keep the "fast path" as simple (and hopefully fast) as possible.
*/
protected final void _writePPFieldName(String name) throws IOException
{
int status = _writeContext.writeFieldName(name);
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if ((status == JsonWriteContext.STATUS_OK_AFTER_COMMA)) {
_cfgPrettyPrinter.writeObjectEntrySeparator(this);
} else {
_cfgPrettyPrinter.beforeObjectEntries(this);
}
if (_cfgUnqNames) {
_writeStringSegments(name, false);
return;
}
final int len = name.length();
if (len > _charBufferLength) {
_writeStringSegments(name, true);
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
name.getChars(0, len, _charBuffer, 0);
// But as one segment, or multiple?
if (len <= _outputMaxContiguous) {
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(_charBuffer, 0, len);
} else {
_writeStringSegments(_charBuffer, 0, len);
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
protected final void _writePPFieldName(SerializableString name) throws IOException
{
final int status = _writeContext.writeFieldName(name.getValue());
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) {
_cfgPrettyPrinter.writeObjectEntrySeparator(this);
} else {
_cfgPrettyPrinter.beforeObjectEntries(this);
}
final boolean addQuotes = !_cfgUnqNames; // standard
if (addQuotes) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
_writeBytes(name.asQuotedUTF8());
if (addQuotes) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
}
/*
/**********************************************************
/* Output method implementations, textual
/**********************************************************
*/
@Override
public void writeString(String text) throws IOException
{
_verifyValueWrite("write text value");
if (text == null) {
_writeNull();
return;
}
// First: can we make a local copy of chars that make up text?
final int len = text.length();
if (len > _charBufferLength) { // nope: off-line handling
_writeStringSegments(text, true);
return;
}
// yes: good.
text.getChars(0, len, _charBuffer, 0);
// Output: if we can't guarantee it fits in output buffer, off-line as well:
if (len > _outputMaxContiguous) {
_writeLongString(_charBuffer, 0, len);
return;
}
if ((_outputTail + len) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeStringSegment(_charBuffer, 0, len); // we checked space already above
/* [JACKSON-462] But that method may have had to expand multi-byte Unicode
* chars, so we must check again
*/
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
private void _writeLongString(char[] text, int offset, int len) throws IOException
{
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeStringSegments(_charBuffer, 0, len);
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeString(char[] text, int offset, int len) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
// One or multiple segments?
if (len <= _outputMaxContiguous) {
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(text, offset, len);
} else {
_writeStringSegments(text, offset, len);
}
// And finally, closing quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public final void writeString(SerializableString text) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
int len = text.appendQuotedUTF8(_outputBuffer, _outputTail);
if (len < 0) {
_writeBytes(text.asQuotedUTF8());
} else {
_outputTail += len;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeBytes(text, offset, length);
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeUTF8String(byte[] text, int offset, int len) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
// One or multiple segments?
if (len <= _outputMaxContiguous) {
_writeUTF8Segment(text, offset, len);
} else {
_writeUTF8Segments(text, offset, len);
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
/*
/**********************************************************
/* Output method implementations, unprocessed ("raw")
/**********************************************************
*/
@Override
public void writeRaw(String text)
throws IOException, JsonGenerationException
{
int start = 0;
int len = text.length();
while (len > 0) {
char[] buf = _charBuffer;
final int blen = buf.length;
final int len2 = (len < blen) ? len : blen;
text.getChars(start, start+len2, buf, 0);
writeRaw(buf, 0, len2);
start += len2;
len -= len2;
}
}
@Override
public void writeRaw(String text, int offset, int len)
throws IOException, JsonGenerationException
{
while (len > 0) {
char[] buf = _charBuffer;
final int blen = buf.length;
final int len2 = (len < blen) ? len : blen;
text.getChars(offset, offset+len2, buf, 0);
writeRaw(buf, 0, len2);
offset += len2;
len -= len2;
}
}
@Override
public void writeRaw(SerializableString text) throws IOException, JsonGenerationException
{
byte[] raw = text.asUnquotedUTF8();
if (raw.length > 0) {
_writeBytes(raw);
}
}
// @TODO: rewrite for speed...
@Override
public final void writeRaw(char[] cbuf, int offset, int len)
throws IOException, JsonGenerationException
{
// First: if we have 3 x charCount spaces, we know it'll fit just fine
{
int len3 = len+len+len;
if ((_outputTail + len3) > _outputEnd) {
// maybe we could flush?
if (_outputEnd < len3) { // wouldn't be enough...
_writeSegmentedRaw(cbuf, offset, len);
return;
}
// yes, flushing brings enough space
_flushBuffer();
}
}
len += offset; // now marks the end
// Note: here we know there is enough room, hence no output boundary checks
main_loop:
while (offset < len) {
inner_loop:
while (true) {
int ch = (int) cbuf[offset];
if (ch > 0x7F) {
break inner_loop;
}
_outputBuffer[_outputTail++] = (byte) ch;
if (++offset >= len) {
break main_loop;
}
}
char ch = cbuf[offset++];
if (ch < 0x800) { // 2-byte?
_outputBuffer[_outputTail++] = (byte) (0xc0 | (ch >> 6));
_outputBuffer[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
} else {
offset = _outputRawMultiByteChar(ch, cbuf, offset, len);
}
}
}
@Override
public void writeRaw(char ch)
throws IOException, JsonGenerationException
{
if ((_outputTail + 3) >= _outputEnd) {
_flushBuffer();
}
final byte[] bbuf = _outputBuffer;
if (ch <= 0x7F) {
bbuf[_outputTail++] = (byte) ch;
} else if (ch < 0x800) { // 2-byte?
bbuf[_outputTail++] = (byte) (0xc0 | (ch >> 6));
bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
} else {
/*offset =*/ _outputRawMultiByteChar(ch, null, 0, 0);
}
}
/**
* Helper method called when it is possible that output of raw section
* to output may cross buffer boundary
*/
private final void _writeSegmentedRaw(char[] cbuf, int offset, int len)
throws IOException, JsonGenerationException
{
final int end = _outputEnd;
final byte[] bbuf = _outputBuffer;
main_loop:
while (offset < len) {
inner_loop:
while (true) {
int ch = (int) cbuf[offset];
if (ch >= 0x80) {
break inner_loop;
}
// !!! TODO: fast(er) writes (roll input, output checks in one)
if (_outputTail >= end) {
_flushBuffer();
}
bbuf[_outputTail++] = (byte) ch;
if (++offset >= len) {
break main_loop;
}
}
if ((_outputTail + 3) >= _outputEnd) {
_flushBuffer();
}
char ch = cbuf[offset++];
if (ch < 0x800) { // 2-byte?
bbuf[_outputTail++] = (byte) (0xc0 | (ch >> 6));
bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
} else {
offset = _outputRawMultiByteChar(ch, cbuf, offset, len);
}
}
}
/*
/**********************************************************
/* Output method implementations, base64-encoded binary
/**********************************************************
*/
@Override
public void writeBinary(Base64Variant b64variant,
byte[] data, int offset, int len)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write binary value");
// Starting quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeBinary(b64variant, data, offset, offset+len);
// and closing quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public int writeBinary(Base64Variant b64variant,
InputStream data, int dataLength)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write binary value");
// Starting quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
byte[] encodingBuffer = _ioContext.allocBase64Buffer();
int bytes;
try {
if (dataLength < 0) { // length unknown
bytes = _writeBinary(b64variant, data, encodingBuffer);
} else {
int missing = _writeBinary(b64variant, data, encodingBuffer, dataLength);
if (missing > 0) {
_reportError("Too few bytes available: missing "+missing+" bytes (out of "+dataLength+")");
}
bytes = dataLength;
}
} finally {
_ioContext.releaseBase64Buffer(encodingBuffer);
}
// and closing quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
return bytes;
}
/*
/**********************************************************
/* Output method implementations, primitive
/**********************************************************
*/
@Override
public void writeNumber(short s)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
// up to 5 digits and possible minus sign
if ((_outputTail + 6) >= _outputEnd) {
_flushBuffer();
}
if (_cfgNumbersAsStrings) {
_writeQuotedShort(s);
return;
}
_outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail);
}
private final void _writeQuotedShort(short s) throws IOException {
if ((_outputTail + 8) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail);
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeNumber(int i)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
// up to 10 digits and possible minus sign
if ((_outputTail + 11) >= _outputEnd) {
_flushBuffer();
}
if (_cfgNumbersAsStrings) {
_writeQuotedInt(i);
return;
}
_outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail);
}
private final void _writeQuotedInt(int i) throws IOException
{
if ((_outputTail + 13) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail);
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeNumber(long l)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
if (_cfgNumbersAsStrings) {
_writeQuotedLong(l);
return;
}
if ((_outputTail + 21) >= _outputEnd) {
// up to 20 digits, minus sign
_flushBuffer();
}
_outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail);
}
private final void _writeQuotedLong(long l) throws IOException
{
if ((_outputTail + 23) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail);
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeNumber(BigInteger value)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
if (value == null) {
_writeNull();
} else if (_cfgNumbersAsStrings) {
_writeQuotedRaw(value);
} else {
writeRaw(value.toString());
}
}
@Override
public void writeNumber(double d)
throws IOException, JsonGenerationException
{
if (_cfgNumbersAsStrings ||
// [JACKSON-139]
(((Double.isNaN(d) || Double.isInfinite(d))
&& isEnabled(Feature.QUOTE_NON_NUMERIC_NUMBERS)))) {
writeString(String.valueOf(d));
return;
}
// What is the max length for doubles? 40 chars?
_verifyValueWrite("write number");
writeRaw(String.valueOf(d));
}
@Override
public void writeNumber(float f)
throws IOException, JsonGenerationException
{
if (_cfgNumbersAsStrings ||
// [JACKSON-139]
(((Float.isNaN(f) || Float.isInfinite(f))
&& isEnabled(Feature.QUOTE_NON_NUMERIC_NUMBERS)))) {
writeString(String.valueOf(f));
return;
}
// What is the max length for floats?
_verifyValueWrite("write number");
writeRaw(String.valueOf(f));
}
@Override
public void writeNumber(BigDecimal value)
throws IOException, JsonGenerationException
{
// Don't really know max length for big decimal, no point checking
_verifyValueWrite("write number");
if (value == null) {
_writeNull();
} else if (_cfgNumbersAsStrings) {
_writeQuotedRaw(value);
} else if (isEnabled(Feature.WRITE_BIGDECIMAL_AS_PLAIN)) {
writeRaw(value.toPlainString());
} else {
writeRaw(value.toString());
}
}
@Override
public void writeNumber(String encodedValue)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
if (_cfgNumbersAsStrings) {
_writeQuotedRaw(encodedValue);
} else {
writeRaw(encodedValue);
}
}
private final void _writeQuotedRaw(Object value) throws IOException
{
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
writeRaw(value.toString());
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeBoolean(boolean state)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write boolean value");
if ((_outputTail + 5) >= _outputEnd) {
_flushBuffer();
}
byte[] keyword = state ? TRUE_BYTES : FALSE_BYTES;
int len = keyword.length;
System.arraycopy(keyword, 0, _outputBuffer, _outputTail, len);
_outputTail += len;
}
@Override
public void writeNull()
throws IOException, JsonGenerationException
{
_verifyValueWrite("write null value");
_writeNull();
}
/*
/**********************************************************
/* Implementations for other methods
/**********************************************************
*/
@Override
protected final void _verifyValueWrite(String typeMsg)
throws IOException, JsonGenerationException
{
int status = _writeContext.writeValue();
if (status == JsonWriteContext.STATUS_EXPECT_NAME) {
_reportError("Can not "+typeMsg+", expecting field name");
}
if (_cfgPrettyPrinter == null) {
byte b;
switch (status) {
case JsonWriteContext.STATUS_OK_AFTER_COMMA:
b = BYTE_COMMA;
break;
case JsonWriteContext.STATUS_OK_AFTER_COLON:
b = BYTE_COLON;
break;
case JsonWriteContext.STATUS_OK_AFTER_SPACE: // root-value separator
if (_rootValueSeparator != null) {
byte[] raw = _rootValueSeparator.asUnquotedUTF8();
if (raw.length > 0) {
_writeBytes(raw);
}
}
return;
case JsonWriteContext.STATUS_OK_AS_IS:
default:
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail] = b;
++_outputTail;
return;
}
// Otherwise, pretty printer knows what to do...
_verifyPrettyValueWrite(typeMsg, status);
}
protected final void _verifyPrettyValueWrite(String typeMsg, int status)
throws IOException, JsonGenerationException
{
// If we have a pretty printer, it knows what to do:
switch (status) {
case JsonWriteContext.STATUS_OK_AFTER_COMMA: // array
_cfgPrettyPrinter.writeArrayValueSeparator(this);
break;
case JsonWriteContext.STATUS_OK_AFTER_COLON:
_cfgPrettyPrinter.writeObjectFieldValueSeparator(this);
break;
case JsonWriteContext.STATUS_OK_AFTER_SPACE:
_cfgPrettyPrinter.writeRootValueSeparator(this);
break;
case JsonWriteContext.STATUS_OK_AS_IS:
// First entry, but of which context?
if (_writeContext.inArray()) {
_cfgPrettyPrinter.beforeArrayValues(this);
} else if (_writeContext.inObject()) {
_cfgPrettyPrinter.beforeObjectEntries(this);
}
break;
default:
_throwInternal();
break;
}
}
/*
/**********************************************************
/* Low-level output handling
/**********************************************************
*/
@Override
public void flush()
throws IOException
{
_flushBuffer();
if (_outputStream != null) {
if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) {
_outputStream.flush();
}
}
}
@Override
public void close()
throws IOException
{
super.close();
/* 05-Dec-2008, tatu: To add [JACKSON-27], need to close open
* scopes.
*/
// First: let's see that we still have buffers...
if (_outputBuffer != null
&& isEnabled(Feature.AUTO_CLOSE_JSON_CONTENT)) {
while (true) {
JsonStreamContext ctxt = getOutputContext();
if (ctxt.inArray()) {
writeEndArray();
} else if (ctxt.inObject()) {
writeEndObject();
} else {
break;
}
}
}
_flushBuffer();
/* 25-Nov-2008, tatus: As per [JACKSON-16] we are not to call close()
* on the underlying Reader, unless we "own" it, or auto-closing
* feature is enabled.
* One downside: when using UTF8Writer, underlying buffer(s)
* may not be properly recycled if we don't close the writer.
*/
if (_outputStream != null) {
if (_ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_TARGET)) {
_outputStream.close();
} else if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) {
// If we can't close it, we should at least flush
_outputStream.flush();
}
}
// Internal buffer(s) generator has can now be released as well
_releaseBuffers();
}
@Override
protected void _releaseBuffers()
{
byte[] buf = _outputBuffer;
if (buf != null && _bufferRecyclable) {
_outputBuffer = null;
_ioContext.releaseWriteEncodingBuffer(buf);
}
char[] cbuf = _charBuffer;
if (cbuf != null) {
_charBuffer = null;
_ioContext.releaseConcatBuffer(cbuf);
}
}
/*
/**********************************************************
/* Internal methods, low-level writing, raw bytes
/**********************************************************
*/
private final void _writeBytes(byte[] bytes) throws IOException
{
final int len = bytes.length;
if ((_outputTail + len) > _outputEnd) {
_flushBuffer();
// still not enough?
if (len > MAX_BYTES_TO_BUFFER) {
_outputStream.write(bytes, 0, len);
return;
}
}
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, len);
_outputTail += len;
}
private final void _writeBytes(byte[] bytes, int offset, int len) throws IOException
{
if ((_outputTail + len) > _outputEnd) {
_flushBuffer();
// still not enough?
if (len > MAX_BYTES_TO_BUFFER) {
_outputStream.write(bytes, offset, len);
return;
}
}
System.arraycopy(bytes, offset, _outputBuffer, _outputTail, len);
_outputTail += len;
}
/*
/**********************************************************
/* Internal methods, mid-level writing, String segments
/**********************************************************
*/
/**
* Method called when String to write is long enough not to fit
* completely in temporary copy buffer. If so, we will actually
* copy it in small enough chunks so it can be directly fed
* to single-segment writes (instead of maximum slices that
* would fit in copy buffer)
*/
private final void _writeStringSegments(String text, boolean addQuotes) throws IOException
{
if (addQuotes) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
int left = text.length();
int offset = 0;
final char[] cbuf = _charBuffer;
while (left > 0) {
int len = Math.min(_outputMaxContiguous, left);
text.getChars(offset, offset+len, cbuf, 0);
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(cbuf, 0, len);
offset += len;
left -= len;
}
if (addQuotes) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
}
/**
* Method called when character sequence to write is long enough that
* its maximum encoded and escaped form is not guaranteed to fit in
* the output buffer. If so, we will need to choose smaller output
* chunks to write at a time.
*/
private final void _writeStringSegments(char[] cbuf, int offset, int totalLen)
throws IOException, JsonGenerationException
{
do {
int len = Math.min(_outputMaxContiguous, totalLen);
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(cbuf, offset, len);
offset += len;
totalLen -= len;
} while (totalLen > 0);
}
/*
/**********************************************************
/* Internal methods, low-level writing, text segments
/**********************************************************
*/
/**
* This method called when the string content is already in
* a char buffer, and its maximum total encoded and escaped length
* can not exceed size of the output buffer.
* Caller must ensure that there is enough space in output buffer,
* assuming case of all non-escaped ASCII characters, as well as
* potentially enough space for other cases (but not necessarily flushed)
*/
private final void _writeStringSegment(char[] cbuf, int offset, int len)
throws IOException, JsonGenerationException
{
// note: caller MUST ensure (via flushing) there's room for ASCII only
// Fast+tight loop for ASCII-only, no-escaping-needed output
len += offset; // becomes end marker, then
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
while (offset < len) {
int ch = cbuf[offset];
// note: here we know that (ch > 0x7F) will cover case of escaping non-ASCII too:
if (ch > 0x7F || escCodes[ch] != 0) {
break;
}
outputBuffer[outputPtr++] = (byte) ch;
++offset;
}
_outputTail = outputPtr;
if (offset < len) {
// [JACKSON-106]
if (_characterEscapes != null) {
_writeCustomStringSegment2(cbuf, offset, len);
// [JACKSON-102]
} else if (_maximumNonEscapedChar == 0) {
_writeStringSegment2(cbuf, offset, len);
} else {
_writeStringSegmentASCII2(cbuf, offset, len);
}
}
}
/**
* Secondary method called when content contains characters to escape,
* and/or multi-byte UTF-8 characters.
*/
private final void _writeStringSegment2(final char[] cbuf, int offset, final int end)
throws IOException, JsonGenerationException
{
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((_outputTail + 6 * (end - offset)) > _outputEnd) {
_flushBuffer();
}
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
while (offset < end) {
int ch = cbuf[offset++];
if (ch <= 0x7F) {
if (escCodes[ch] == 0) {
outputBuffer[outputPtr++] = (byte) ch;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
continue;
}
if (ch <= 0x7FF) { // fine, just needs 2 byte output
outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6));
outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
} else {
outputPtr = _outputMultiByteChar(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, text segment
/* with additional escaping (ASCII or such)
/**********************************************************
*/
/**
* Same as <code>_writeStringSegment2(char[], ...)</code., but with
* additional escaping for high-range code points
*/
private final void _writeStringSegmentASCII2(final char[] cbuf, int offset, final int end)
throws IOException, JsonGenerationException
{
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((_outputTail + 6 * (end - offset)) > _outputEnd) {
_flushBuffer();
}
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
final int maxUnescaped = _maximumNonEscapedChar;
while (offset < end) {
int ch = cbuf[offset++];
if (ch <= 0x7F) {
if (escCodes[ch] == 0) {
outputBuffer[outputPtr++] = (byte) ch;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
continue;
}
if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars:
outputPtr = _writeGenericEscape(ch, outputPtr);
continue;
}
if (ch <= 0x7FF) { // fine, just needs 2 byte output
outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6));
outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
} else {
outputPtr = _outputMultiByteChar(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, text segment
/* with fully custom escaping (and possibly escaping of non-ASCII
/**********************************************************
*/
/**
* Same as <code>_writeStringSegmentASCII2(char[], ...)</code., but with
* additional checking for completely custom escapes
*/
private final void _writeCustomStringSegment2(final char[] cbuf, int offset, final int end)
throws IOException, JsonGenerationException
{
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((_outputTail + 6 * (end - offset)) > _outputEnd) {
_flushBuffer();
}
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
// may or may not have this limit
final int maxUnescaped = (_maximumNonEscapedChar <= 0) ? 0xFFFF : _maximumNonEscapedChar;
final CharacterEscapes customEscapes = _characterEscapes; // non-null
while (offset < end) {
int ch = cbuf[offset++];
if (ch <= 0x7F) {
if (escCodes[ch] == 0) {
outputBuffer[outputPtr++] = (byte) ch;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else if (escape == CharacterEscapes.ESCAPE_CUSTOM) {
SerializableString esc = customEscapes.getEscapeSequence(ch);
if (esc == null) {
_reportError("Invalid custom escape definitions; custom escape not found for character code 0x"
+Integer.toHexString(ch)+", although was supposed to have one");
}
outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset);
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
continue;
}
if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars:
outputPtr = _writeGenericEscape(ch, outputPtr);
continue;
}
SerializableString esc = customEscapes.getEscapeSequence(ch);
if (esc != null) {
outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset);
continue;
}
if (ch <= 0x7FF) { // fine, just needs 2 byte output
outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6));
outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
} else {
outputPtr = _outputMultiByteChar(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
private final int _writeCustomEscape(byte[] outputBuffer, int outputPtr, SerializableString esc, int remainingChars)
throws IOException, JsonGenerationException
{
byte[] raw = esc.asUnquotedUTF8(); // must be escaped at this point, shouldn't double-quote
int len = raw.length;
if (len > 6) { // may violate constraints we have, do offline
return _handleLongCustomEscape(outputBuffer, outputPtr, _outputEnd, raw, remainingChars);
}
// otherwise will fit without issues, so:
System.arraycopy(raw, 0, outputBuffer, outputPtr, len);
return (outputPtr + len);
}
private final int _handleLongCustomEscape(byte[] outputBuffer, int outputPtr, int outputEnd, byte[] raw,
int remainingChars)
throws IOException, JsonGenerationException
{
int len = raw.length;
if ((outputPtr + len) > outputEnd) {
_outputTail = outputPtr;
_flushBuffer();
outputPtr = _outputTail;
if (len > outputBuffer.length) { // very unlikely, but possible...
_outputStream.write(raw, 0, len);
return outputPtr;
}
System.arraycopy(raw, 0, outputBuffer, outputPtr, len);
outputPtr += len;
}
// but is the invariant still obeyed? If not, flush once more
if ((outputPtr + 6 * remainingChars) > outputEnd) {
_flushBuffer();
return _outputTail;
}
return outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, "raw UTF-8" segments
/**********************************************************
*/
/**
* Method called when UTF-8 encoded (but NOT yet escaped!) content is not guaranteed
* to fit in the output buffer after escaping; as such, we just need to
* chunk writes.
*/
private final void _writeUTF8Segments(byte[] utf8, int offset, int totalLen)
throws IOException, JsonGenerationException
{
do {
int len = Math.min(_outputMaxContiguous, totalLen);
_writeUTF8Segment(utf8, offset, len);
offset += len;
totalLen -= len;
} while (totalLen > 0);
}
private final void _writeUTF8Segment(byte[] utf8, final int offset, final int len)
throws IOException, JsonGenerationException
{
// fast loop to see if escaping is needed; don't copy, just look
final int[] escCodes = _outputEscapes;
for (int ptr = offset, end = offset + len; ptr < end; ) {
// 28-Feb-2011, tatu: escape codes just cover 7-bit range, so:
int ch = utf8[ptr++];
if ((ch >= 0) && escCodes[ch] != 0) {
_writeUTF8Segment2(utf8, offset, len);
return;
}
}
// yes, fine, just copy the sucker
if ((_outputTail + len) > _outputEnd) { // enough room or need to flush?
_flushBuffer(); // but yes once we flush (caller guarantees length restriction)
}
System.arraycopy(utf8, offset, _outputBuffer, _outputTail, len);
_outputTail += len;
}
private final void _writeUTF8Segment2(final byte[] utf8, int offset, int len)
throws IOException, JsonGenerationException
{
int outputPtr = _outputTail;
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((outputPtr + (len * 6)) > _outputEnd) {
_flushBuffer();
outputPtr = _outputTail;
}
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
len += offset; // so 'len' becomes 'end'
while (offset < len) {
byte b = utf8[offset++];
int ch = b;
if (ch < 0 || escCodes[ch] == 0) {
outputBuffer[outputPtr++] = b;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, base64 encoded
/**********************************************************
*/
protected final void _writeBinary(Base64Variant b64variant,
byte[] input, int inputPtr, final int inputEnd)
throws IOException, JsonGenerationException
{
// Encoding is by chunks of 3 input, 4 output chars, so:
int safeInputEnd = inputEnd - 3;
// Let's also reserve room for possible (and quoted) lf char each round
int safeOutputEnd = _outputEnd - 6;
int chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
// Ok, first we loop through all full triplets of data:
while (inputPtr <= safeInputEnd) {
if (_outputTail > safeOutputEnd) { // need to flush
_flushBuffer();
}
// First, mash 3 bytes into lsb of 32-bit int
int b24 = ((int) input[inputPtr++]) << 8;
b24 |= ((int) input[inputPtr++]) & 0xFF;
b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF);
_outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail);
if (--chunksBeforeLF <= 0) {
// note: must quote in JSON value
_outputBuffer[_outputTail++] = '\\';
_outputBuffer[_outputTail++] = 'n';
chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
}
}
// And then we may have 1 or 2 leftover bytes to encode
int inputLeft = inputEnd - inputPtr; // 0, 1 or 2
if (inputLeft > 0) { // yes, but do we have room for output?
if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but...
_flushBuffer();
}
int b24 = ((int) input[inputPtr++]) << 16;
if (inputLeft == 2) {
b24 |= (((int) input[inputPtr++]) & 0xFF) << 8;
}
_outputTail = b64variant.encodeBase64Partial(b24, inputLeft, _outputBuffer, _outputTail);
}
}
// write-method called when length is definitely known
protected final int _writeBinary(Base64Variant b64variant,
InputStream data, byte[] readBuffer, int bytesLeft)
throws IOException, JsonGenerationException
{
int inputPtr = 0;
int inputEnd = 0;
int lastFullOffset = -3;
// Let's also reserve room for possible (and quoted) LF char each round
int safeOutputEnd = _outputEnd - 6;
int chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
while (bytesLeft > 2) { // main loop for full triplets
if (inputPtr > lastFullOffset) {
inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft);
inputPtr = 0;
if (inputEnd < 3) { // required to try to read to have at least 3 bytes
break;
}
lastFullOffset = inputEnd-3;
}
if (_outputTail > safeOutputEnd) { // need to flush
_flushBuffer();
}
int b24 = ((int) readBuffer[inputPtr++]) << 8;
b24 |= ((int) readBuffer[inputPtr++]) & 0xFF;
b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF);
bytesLeft -= 3;
_outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail);
if (--chunksBeforeLF <= 0) {
_outputBuffer[_outputTail++] = '\\';
_outputBuffer[_outputTail++] = 'n';
chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
}
}
// And then we may have 1 or 2 leftover bytes to encode
if (bytesLeft > 0) {
inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft);
inputPtr = 0;
if (inputEnd > 0) { // yes, but do we have room for output?
if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but...
_flushBuffer();
}
int b24 = ((int) readBuffer[inputPtr++]) << 16;
int amount;
if (inputPtr < inputEnd) {
b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8;
amount = 2;
} else {
amount = 1;
}
_outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail);
bytesLeft -= amount;
}
}
return bytesLeft;
}
// write method when length is unknown
protected final int _writeBinary(Base64Variant b64variant,
InputStream data, byte[] readBuffer)
throws IOException, JsonGenerationException
{
int inputPtr = 0;
int inputEnd = 0;
int lastFullOffset = -3;
int bytesDone = 0;
// Let's also reserve room for possible (and quoted) LF char each round
int safeOutputEnd = _outputEnd - 6;
int chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
// Ok, first we loop through all full triplets of data:
while (true) {
if (inputPtr > lastFullOffset) { // need to load more
inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, readBuffer.length);
inputPtr = 0;
if (inputEnd < 3) { // required to try to read to have at least 3 bytes
break;
}
lastFullOffset = inputEnd-3;
}
if (_outputTail > safeOutputEnd) { // need to flush
_flushBuffer();
}
// First, mash 3 bytes into lsb of 32-bit int
int b24 = ((int) readBuffer[inputPtr++]) << 8;
b24 |= ((int) readBuffer[inputPtr++]) & 0xFF;
b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF);
bytesDone += 3;
_outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail);
if (--chunksBeforeLF <= 0) {
_outputBuffer[_outputTail++] = '\\';
_outputBuffer[_outputTail++] = 'n';
chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
}
}
// And then we may have 1 or 2 leftover bytes to encode
if (inputPtr < inputEnd) { // yes, but do we have room for output?
if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but...
_flushBuffer();
}
int b24 = ((int) readBuffer[inputPtr++]) << 16;
int amount = 1;
if (inputPtr < inputEnd) {
b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8;
amount = 2;
}
bytesDone += amount;
_outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail);
}
return bytesDone;
}
private final int _readMore(InputStream in,
byte[] readBuffer, int inputPtr, int inputEnd,
int maxRead) throws IOException
{
// anything to shift to front?
int i = 0;
while (inputPtr < inputEnd) {
readBuffer[i++] = readBuffer[inputPtr++];
}
inputPtr = 0;
inputEnd = i;
maxRead = Math.min(maxRead, readBuffer.length);
do {
int length = maxRead - inputEnd;
if (length == 0) {
break;
}
int count = in.read(readBuffer, inputEnd, length);
if (count < 0) {
return inputEnd;
}
inputEnd += count;
} while (inputEnd < 3);
return inputEnd;
}
/*
/**********************************************************
/* Internal methods, character escapes/encoding
/**********************************************************
*/
/**
* Method called to output a character that is beyond range of
* 1- and 2-byte UTF-8 encodings, when outputting "raw"
* text (meaning it is not to be escaped or quoted)
*/
private final int _outputRawMultiByteChar(int ch, char[] cbuf, int inputOffset, int inputLen)
throws IOException
{
// Let's handle surrogates gracefully (as 4 byte output):
if (ch >= SURR1_FIRST) {
if (ch <= SURR2_LAST) { // yes, outside of BMP
// Do we have second part?
if (inputOffset >= inputLen || cbuf == null) { // nope... have to note down
_reportError("Split surrogate on writeRaw() input (last character)");
}
_outputSurrogates(ch, cbuf[inputOffset]);
return (inputOffset+1);
}
}
final byte[] bbuf = _outputBuffer;
bbuf[_outputTail++] = (byte) (0xe0 | (ch >> 12));
bbuf[_outputTail++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
return inputOffset;
}
protected final void _outputSurrogates(int surr1, int surr2)
throws IOException
{
int c = _decodeSurrogate(surr1, surr2);
if ((_outputTail + 4) > _outputEnd) {
_flushBuffer();
}
final byte[] bbuf = _outputBuffer;
bbuf[_outputTail++] = (byte) (0xf0 | (c >> 18));
bbuf[_outputTail++] = (byte) (0x80 | ((c >> 12) & 0x3f));
bbuf[_outputTail++] = (byte) (0x80 | ((c >> 6) & 0x3f));
bbuf[_outputTail++] = (byte) (0x80 | (c & 0x3f));
}
/**
*
* @param ch
* @param outputPtr Position within output buffer to append multi-byte in
*
* @return New output position after appending
*
* @throws IOException
*/
private final int _outputMultiByteChar(int ch, int outputPtr)
throws IOException
{
byte[] bbuf = _outputBuffer;
if (ch >= SURR1_FIRST && ch <= SURR2_LAST) { // yes, outside of BMP; add an escape
bbuf[outputPtr++] = BYTE_BACKSLASH;
bbuf[outputPtr++] = BYTE_u;
bbuf[outputPtr++] = HEX_CHARS[(ch >> 12) & 0xF];
bbuf[outputPtr++] = HEX_CHARS[(ch >> 8) & 0xF];
bbuf[outputPtr++] = HEX_CHARS[(ch >> 4) & 0xF];
bbuf[outputPtr++] = HEX_CHARS[ch & 0xF];
} else {
bbuf[outputPtr++] = (byte) (0xe0 | (ch >> 12));
bbuf[outputPtr++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
bbuf[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
}
return outputPtr;
}
protected final int _decodeSurrogate(int surr1, int surr2) throws IOException
{
// First is known to be valid, but how about the other?
if (surr2 < SURR2_FIRST || surr2 > SURR2_LAST) {
String msg = "Incomplete surrogate pair: first char 0x"+Integer.toHexString(surr1)+", second 0x"+Integer.toHexString(surr2);
_reportError(msg);
}
int c = 0x10000 + ((surr1 - SURR1_FIRST) << 10) + (surr2 - SURR2_FIRST);
return c;
}
private final void _writeNull() throws IOException
{
if ((_outputTail + 4) >= _outputEnd) {
_flushBuffer();
}
System.arraycopy(NULL_BYTES, 0, _outputBuffer, _outputTail, 4);
_outputTail += 4;
}
/**
* Method called to write a generic Unicode escape for given character.
*
* @param charToEscape Character to escape using escape sequence (\\uXXXX)
*/
private int _writeGenericEscape(int charToEscape, int outputPtr)
throws IOException
{
final byte[] bbuf = _outputBuffer;
bbuf[outputPtr++] = BYTE_BACKSLASH;
bbuf[outputPtr++] = BYTE_u;
if (charToEscape > 0xFF) {
int hi = (charToEscape >> 8) & 0xFF;
bbuf[outputPtr++] = HEX_CHARS[hi >> 4];
bbuf[outputPtr++] = HEX_CHARS[hi & 0xF];
charToEscape &= 0xFF;
} else {
bbuf[outputPtr++] = BYTE_0;
bbuf[outputPtr++] = BYTE_0;
}
// We know it's a control char, so only the last 2 chars are non-0
bbuf[outputPtr++] = HEX_CHARS[charToEscape >> 4];
bbuf[outputPtr++] = HEX_CHARS[charToEscape & 0xF];
return outputPtr;
}
protected final void _flushBuffer() throws IOException
{
int len = _outputTail;
if (len > 0) {
_outputTail = 0;
_outputStream.write(_outputBuffer, 0, len);
}
}
}
| src/main/java/com/fasterxml/jackson/core/json/UTF8JsonGenerator.java | package com.fasterxml.jackson.core.json;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.io.*;
public class UTF8JsonGenerator
extends JsonGeneratorImpl
{
private final static byte BYTE_u = (byte) 'u';
private final static byte BYTE_0 = (byte) '0';
private final static byte BYTE_LBRACKET = (byte) '[';
private final static byte BYTE_RBRACKET = (byte) ']';
private final static byte BYTE_LCURLY = (byte) '{';
private final static byte BYTE_RCURLY = (byte) '}';
private final static byte BYTE_BACKSLASH = (byte) '\\';
private final static byte BYTE_COMMA = (byte) ',';
private final static byte BYTE_COLON = (byte) ':';
private final static byte BYTE_QUOTE = (byte) '"';
protected final static int SURR1_FIRST = 0xD800;
protected final static int SURR1_LAST = 0xDBFF;
protected final static int SURR2_FIRST = 0xDC00;
protected final static int SURR2_LAST = 0xDFFF;
// intermediate copies only made up to certain length...
private final static int MAX_BYTES_TO_BUFFER = 512;
final static byte[] HEX_CHARS = CharTypes.copyHexBytes();
private final static byte[] NULL_BYTES = { 'n', 'u', 'l', 'l' };
private final static byte[] TRUE_BYTES = { 't', 'r', 'u', 'e' };
private final static byte[] FALSE_BYTES = { 'f', 'a', 'l', 's', 'e' };
/*
/**********************************************************
/* Output buffering
/**********************************************************
*/
/**
* Underlying output stream used for writing JSON content.
*/
final protected OutputStream _outputStream;
/**
* Intermediate buffer in which contents are buffered before
* being written using {@link #_outputStream}.
*/
protected byte[] _outputBuffer;
/**
* Pointer to the position right beyond the last character to output
* (end marker; may be past the buffer)
*/
protected int _outputTail = 0;
/**
* End marker of the output buffer; one past the last valid position
* within the buffer.
*/
protected final int _outputEnd;
/**
* Maximum number of <code>char</code>s that we know will always fit
* in the output buffer after escaping
*/
protected final int _outputMaxContiguous;
/**
* Intermediate buffer in which characters of a String are copied
* before being encoded.
*/
protected char[] _charBuffer;
/**
* Length of <code>_charBuffer</code>
*/
protected final int _charBufferLength;
/**
* 6 character temporary buffer allocated if needed, for constructing
* escape sequences
*/
protected byte[] _entityBuffer;
/**
* Flag that indicates whether the output buffer is recycable (and
* needs to be returned to recycler once we are done) or not.
*/
protected boolean _bufferRecyclable;
/*
/**********************************************************
/* Quick flags
/**********************************************************
*/
/**
* Flag that is set if quoting is not to be added around
* JSON Object property names.
*/
protected final boolean _cfgUnqNames;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public UTF8JsonGenerator(IOContext ctxt, int features, ObjectCodec codec,
OutputStream out)
{
super(ctxt, features, codec);
_outputStream = out;
_bufferRecyclable = true;
_outputBuffer = ctxt.allocWriteEncodingBuffer();
_outputEnd = _outputBuffer.length;
/* To be exact, each char can take up to 6 bytes when escaped (Unicode
* escape with backslash, 'u' and 4 hex digits); but to avoid fluctuation,
* we will actually round down to only do up to 1/8 number of chars
*/
_outputMaxContiguous = _outputEnd >> 3;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
// By default we use this feature to determine additional quoting
if (isEnabled(Feature.ESCAPE_NON_ASCII)) {
setHighestNonEscapedChar(127);
}
_cfgUnqNames = !Feature.QUOTE_FIELD_NAMES.enabledIn(features);
}
public UTF8JsonGenerator(IOContext ctxt, int features, ObjectCodec codec,
OutputStream out,
byte[] outputBuffer, int outputOffset, boolean bufferRecyclable)
{
super(ctxt, features, codec);
_outputStream = out;
_bufferRecyclable = bufferRecyclable;
_outputTail = outputOffset;
_outputBuffer = outputBuffer;
_outputEnd = _outputBuffer.length;
// up to 6 bytes per char (see above), rounded up to 1/8
_outputMaxContiguous = _outputEnd >> 3;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
_cfgUnqNames = !Feature.QUOTE_FIELD_NAMES.enabledIn(features);
}
/*
/**********************************************************
/* Overridden configuration methods
/**********************************************************
*/
@Override
public Object getOutputTarget() {
return _outputStream;
}
/*
/**********************************************************
/* Overridden methods
/**********************************************************
*/
@Override
public void writeFieldName(String name) throws IOException
{
if (_cfgPrettyPrinter != null) {
_writePPFieldName(name);
return;
}
final int status = _writeContext.writeFieldName(name);
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) { // need comma
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_COMMA;
}
/* To support [JACKSON-46], we'll do this:
* (Question: should quoting of spaces (etc) still be enabled?)
*/
if (_cfgUnqNames) {
_writeStringSegments(name);
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
// The beef:
final int len = name.length();
if (len <= _charBufferLength) { // yes, fits right in
name.getChars(0, len, _charBuffer, 0);
// But as one segment, or multiple?
if (len <= _outputMaxContiguous) {
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(_charBuffer, 0, len);
} else {
_writeStringSegments(_charBuffer, 0, len);
}
} else {
_writeStringSegments(name);
}
// and closing quotes; need room for one more char:
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeFieldName(SerializableString name) throws IOException
{
if (_cfgPrettyPrinter != null) {
_writePPFieldName(name);
return;
}
final int status = _writeContext.writeFieldName(name.getValue());
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_COMMA;
}
_writeFieldName(name);
}
protected final void _writeFieldName(SerializableString name) throws IOException
{
if (_cfgUnqNames) {
_writeUnq(name);
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
int len = name.appendQuotedUTF8(_outputBuffer, _outputTail);
if (len < 0) { // couldn't append, bit longer processing
_writeBytes(name.asQuotedUTF8());
} else {
_outputTail += len;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
private final void _writeUnq(SerializableString name) throws IOException {
int len = name.appendQuotedUTF8(_outputBuffer, _outputTail);
if (len < 0) {
_writeBytes(name.asQuotedUTF8());
} else {
_outputTail += len;
}
}
/*
/**********************************************************
/* Output method implementations, structural
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException
{
_verifyValueWrite("start an array");
_writeContext = _writeContext.createChildArrayContext();
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeStartArray(this);
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_LBRACKET;
}
}
@Override
public final void writeEndArray() throws IOException
{
if (!_writeContext.inArray()) {
_reportError("Current context not an ARRAY but "+_writeContext.getTypeDesc());
}
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeEndArray(this, _writeContext.getEntryCount());
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_RBRACKET;
}
_writeContext = _writeContext.getParent();
}
@Override
public final void writeStartObject() throws IOException
{
_verifyValueWrite("start an object");
_writeContext = _writeContext.createChildObjectContext();
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeStartObject(this);
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_LCURLY;
}
}
@Override
public final void writeEndObject() throws IOException
{
if (!_writeContext.inObject()) {
_reportError("Current context not an object but "+_writeContext.getTypeDesc());
}
if (_cfgPrettyPrinter != null) {
_cfgPrettyPrinter.writeEndObject(this, _writeContext.getEntryCount());
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_RCURLY;
}
_writeContext = _writeContext.getParent();
}
/**
* Specialized version of <code>_writeFieldName</code>, off-lined
* to keep the "fast path" as simple (and hopefully fast) as possible.
*/
protected final void _writePPFieldName(String name) throws IOException
{
int status = _writeContext.writeFieldName(name);
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if ((status == JsonWriteContext.STATUS_OK_AFTER_COMMA)) {
_cfgPrettyPrinter.writeObjectEntrySeparator(this);
} else {
_cfgPrettyPrinter.beforeObjectEntries(this);
}
if (_cfgUnqNames) { // standard
_writeStringSegments(name);
} else {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
final int len = name.length();
if (len <= _charBufferLength) { // yes, fits right in
name.getChars(0, len, _charBuffer, 0);
// But as one segment, or multiple?
if (len <= _outputMaxContiguous) {
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(_charBuffer, 0, len);
} else {
_writeStringSegments(_charBuffer, 0, len);
}
} else {
_writeStringSegments(name);
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
}
protected final void _writePPFieldName(SerializableString name) throws IOException
{
final int status = _writeContext.writeFieldName(name.getValue());
if (status == JsonWriteContext.STATUS_EXPECT_VALUE) {
_reportError("Can not write a field name, expecting a value");
}
if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) {
_cfgPrettyPrinter.writeObjectEntrySeparator(this);
} else {
_cfgPrettyPrinter.beforeObjectEntries(this);
}
final boolean addQuotes = !_cfgUnqNames; // standard
if (addQuotes) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
_writeBytes(name.asQuotedUTF8());
if (addQuotes) {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
}
/*
/**********************************************************
/* Output method implementations, textual
/**********************************************************
*/
@Override
public void writeString(String text) throws IOException
{
_verifyValueWrite("write text value");
if (text == null) {
_writeNull();
return;
}
// First: can we make a local copy of chars that make up text?
final int len = text.length();
if (len > _charBufferLength) { // nope: off-line handling
_writeLongString(text);
return;
}
// yes: good.
text.getChars(0, len, _charBuffer, 0);
// Output: if we can't guarantee it fits in output buffer, off-line as well:
if (len > _outputMaxContiguous) {
_writeLongString(_charBuffer, 0, len);
return;
}
if ((_outputTail + len) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeStringSegment(_charBuffer, 0, len); // we checked space already above
/* [JACKSON-462] But that method may have had to expand multi-byte Unicode
* chars, so we must check again
*/
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
private void _writeLongString(String text) throws IOException
{
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeStringSegments(text);
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
private void _writeLongString(char[] text, int offset, int len) throws IOException
{
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeStringSegments(_charBuffer, 0, len);
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeString(char[] text, int offset, int len) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
// One or multiple segments?
if (len <= _outputMaxContiguous) {
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(text, offset, len);
} else {
_writeStringSegments(text, offset, len);
}
// And finally, closing quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public final void writeString(SerializableString text) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
int len = text.appendQuotedUTF8(_outputBuffer, _outputTail);
if (len < 0) {
_writeBytes(text.asQuotedUTF8());
} else {
_outputTail += len;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeBytes(text, offset, length);
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeUTF8String(byte[] text, int offset, int len) throws IOException
{
_verifyValueWrite("write text value");
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
// One or multiple segments?
if (len <= _outputMaxContiguous) {
_writeUTF8Segment(text, offset, len);
} else {
_writeUTF8Segments(text, offset, len);
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
/*
/**********************************************************
/* Output method implementations, unprocessed ("raw")
/**********************************************************
*/
@Override
public void writeRaw(String text)
throws IOException, JsonGenerationException
{
int start = 0;
int len = text.length();
while (len > 0) {
char[] buf = _charBuffer;
final int blen = buf.length;
final int len2 = (len < blen) ? len : blen;
text.getChars(start, start+len2, buf, 0);
writeRaw(buf, 0, len2);
start += len2;
len -= len2;
}
}
@Override
public void writeRaw(String text, int offset, int len)
throws IOException, JsonGenerationException
{
while (len > 0) {
char[] buf = _charBuffer;
final int blen = buf.length;
final int len2 = (len < blen) ? len : blen;
text.getChars(offset, offset+len2, buf, 0);
writeRaw(buf, 0, len2);
offset += len2;
len -= len2;
}
}
@Override
public void writeRaw(SerializableString text) throws IOException, JsonGenerationException
{
byte[] raw = text.asUnquotedUTF8();
if (raw.length > 0) {
_writeBytes(raw);
}
}
// @TODO: rewrite for speed...
@Override
public final void writeRaw(char[] cbuf, int offset, int len)
throws IOException, JsonGenerationException
{
// First: if we have 3 x charCount spaces, we know it'll fit just fine
{
int len3 = len+len+len;
if ((_outputTail + len3) > _outputEnd) {
// maybe we could flush?
if (_outputEnd < len3) { // wouldn't be enough...
_writeSegmentedRaw(cbuf, offset, len);
return;
}
// yes, flushing brings enough space
_flushBuffer();
}
}
len += offset; // now marks the end
// Note: here we know there is enough room, hence no output boundary checks
main_loop:
while (offset < len) {
inner_loop:
while (true) {
int ch = (int) cbuf[offset];
if (ch > 0x7F) {
break inner_loop;
}
_outputBuffer[_outputTail++] = (byte) ch;
if (++offset >= len) {
break main_loop;
}
}
char ch = cbuf[offset++];
if (ch < 0x800) { // 2-byte?
_outputBuffer[_outputTail++] = (byte) (0xc0 | (ch >> 6));
_outputBuffer[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
} else {
offset = _outputRawMultiByteChar(ch, cbuf, offset, len);
}
}
}
@Override
public void writeRaw(char ch)
throws IOException, JsonGenerationException
{
if ((_outputTail + 3) >= _outputEnd) {
_flushBuffer();
}
final byte[] bbuf = _outputBuffer;
if (ch <= 0x7F) {
bbuf[_outputTail++] = (byte) ch;
} else if (ch < 0x800) { // 2-byte?
bbuf[_outputTail++] = (byte) (0xc0 | (ch >> 6));
bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
} else {
/*offset =*/ _outputRawMultiByteChar(ch, null, 0, 0);
}
}
/**
* Helper method called when it is possible that output of raw section
* to output may cross buffer boundary
*/
private final void _writeSegmentedRaw(char[] cbuf, int offset, int len)
throws IOException, JsonGenerationException
{
final int end = _outputEnd;
final byte[] bbuf = _outputBuffer;
main_loop:
while (offset < len) {
inner_loop:
while (true) {
int ch = (int) cbuf[offset];
if (ch >= 0x80) {
break inner_loop;
}
// !!! TODO: fast(er) writes (roll input, output checks in one)
if (_outputTail >= end) {
_flushBuffer();
}
bbuf[_outputTail++] = (byte) ch;
if (++offset >= len) {
break main_loop;
}
}
if ((_outputTail + 3) >= _outputEnd) {
_flushBuffer();
}
char ch = cbuf[offset++];
if (ch < 0x800) { // 2-byte?
bbuf[_outputTail++] = (byte) (0xc0 | (ch >> 6));
bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
} else {
offset = _outputRawMultiByteChar(ch, cbuf, offset, len);
}
}
}
/*
/**********************************************************
/* Output method implementations, base64-encoded binary
/**********************************************************
*/
@Override
public void writeBinary(Base64Variant b64variant,
byte[] data, int offset, int len)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write binary value");
// Starting quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_writeBinary(b64variant, data, offset, offset+len);
// and closing quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public int writeBinary(Base64Variant b64variant,
InputStream data, int dataLength)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write binary value");
// Starting quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
byte[] encodingBuffer = _ioContext.allocBase64Buffer();
int bytes;
try {
if (dataLength < 0) { // length unknown
bytes = _writeBinary(b64variant, data, encodingBuffer);
} else {
int missing = _writeBinary(b64variant, data, encodingBuffer, dataLength);
if (missing > 0) {
_reportError("Too few bytes available: missing "+missing+" bytes (out of "+dataLength+")");
}
bytes = dataLength;
}
} finally {
_ioContext.releaseBase64Buffer(encodingBuffer);
}
// and closing quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
return bytes;
}
/*
/**********************************************************
/* Output method implementations, primitive
/**********************************************************
*/
@Override
public void writeNumber(short s)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
// up to 5 digits and possible minus sign
if ((_outputTail + 6) >= _outputEnd) {
_flushBuffer();
}
if (_cfgNumbersAsStrings) {
_writeQuotedShort(s);
return;
}
_outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail);
}
private final void _writeQuotedShort(short s) throws IOException {
if ((_outputTail + 8) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail);
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeNumber(int i)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
// up to 10 digits and possible minus sign
if ((_outputTail + 11) >= _outputEnd) {
_flushBuffer();
}
if (_cfgNumbersAsStrings) {
_writeQuotedInt(i);
return;
}
_outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail);
}
private final void _writeQuotedInt(int i) throws IOException
{
if ((_outputTail + 13) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail);
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeNumber(long l)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
if (_cfgNumbersAsStrings) {
_writeQuotedLong(l);
return;
}
if ((_outputTail + 21) >= _outputEnd) {
// up to 20 digits, minus sign
_flushBuffer();
}
_outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail);
}
private final void _writeQuotedLong(long l) throws IOException
{
if ((_outputTail + 23) >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
_outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail);
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeNumber(BigInteger value)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
if (value == null) {
_writeNull();
} else if (_cfgNumbersAsStrings) {
_writeQuotedRaw(value);
} else {
writeRaw(value.toString());
}
}
@Override
public void writeNumber(double d)
throws IOException, JsonGenerationException
{
if (_cfgNumbersAsStrings ||
// [JACKSON-139]
(((Double.isNaN(d) || Double.isInfinite(d))
&& isEnabled(Feature.QUOTE_NON_NUMERIC_NUMBERS)))) {
writeString(String.valueOf(d));
return;
}
// What is the max length for doubles? 40 chars?
_verifyValueWrite("write number");
writeRaw(String.valueOf(d));
}
@Override
public void writeNumber(float f)
throws IOException, JsonGenerationException
{
if (_cfgNumbersAsStrings ||
// [JACKSON-139]
(((Float.isNaN(f) || Float.isInfinite(f))
&& isEnabled(Feature.QUOTE_NON_NUMERIC_NUMBERS)))) {
writeString(String.valueOf(f));
return;
}
// What is the max length for floats?
_verifyValueWrite("write number");
writeRaw(String.valueOf(f));
}
@Override
public void writeNumber(BigDecimal value)
throws IOException, JsonGenerationException
{
// Don't really know max length for big decimal, no point checking
_verifyValueWrite("write number");
if (value == null) {
_writeNull();
} else if (_cfgNumbersAsStrings) {
_writeQuotedRaw(value);
} else if (isEnabled(Feature.WRITE_BIGDECIMAL_AS_PLAIN)) {
writeRaw(value.toPlainString());
} else {
writeRaw(value.toString());
}
}
@Override
public void writeNumber(String encodedValue)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write number");
if (_cfgNumbersAsStrings) {
_writeQuotedRaw(encodedValue);
} else {
writeRaw(encodedValue);
}
}
private final void _writeQuotedRaw(Object value) throws IOException
{
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
writeRaw(value.toString());
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_QUOTE;
}
@Override
public void writeBoolean(boolean state)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write boolean value");
if ((_outputTail + 5) >= _outputEnd) {
_flushBuffer();
}
byte[] keyword = state ? TRUE_BYTES : FALSE_BYTES;
int len = keyword.length;
System.arraycopy(keyword, 0, _outputBuffer, _outputTail, len);
_outputTail += len;
}
@Override
public void writeNull()
throws IOException, JsonGenerationException
{
_verifyValueWrite("write null value");
_writeNull();
}
/*
/**********************************************************
/* Implementations for other methods
/**********************************************************
*/
@Override
protected final void _verifyValueWrite(String typeMsg)
throws IOException, JsonGenerationException
{
int status = _writeContext.writeValue();
if (status == JsonWriteContext.STATUS_EXPECT_NAME) {
_reportError("Can not "+typeMsg+", expecting field name");
}
if (_cfgPrettyPrinter == null) {
byte b;
switch (status) {
case JsonWriteContext.STATUS_OK_AFTER_COMMA:
b = BYTE_COMMA;
break;
case JsonWriteContext.STATUS_OK_AFTER_COLON:
b = BYTE_COLON;
break;
case JsonWriteContext.STATUS_OK_AFTER_SPACE: // root-value separator
if (_rootValueSeparator != null) {
byte[] raw = _rootValueSeparator.asUnquotedUTF8();
if (raw.length > 0) {
_writeBytes(raw);
}
}
return;
case JsonWriteContext.STATUS_OK_AS_IS:
default:
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail] = b;
++_outputTail;
return;
}
// Otherwise, pretty printer knows what to do...
_verifyPrettyValueWrite(typeMsg, status);
}
protected final void _verifyPrettyValueWrite(String typeMsg, int status)
throws IOException, JsonGenerationException
{
// If we have a pretty printer, it knows what to do:
switch (status) {
case JsonWriteContext.STATUS_OK_AFTER_COMMA: // array
_cfgPrettyPrinter.writeArrayValueSeparator(this);
break;
case JsonWriteContext.STATUS_OK_AFTER_COLON:
_cfgPrettyPrinter.writeObjectFieldValueSeparator(this);
break;
case JsonWriteContext.STATUS_OK_AFTER_SPACE:
_cfgPrettyPrinter.writeRootValueSeparator(this);
break;
case JsonWriteContext.STATUS_OK_AS_IS:
// First entry, but of which context?
if (_writeContext.inArray()) {
_cfgPrettyPrinter.beforeArrayValues(this);
} else if (_writeContext.inObject()) {
_cfgPrettyPrinter.beforeObjectEntries(this);
}
break;
default:
_throwInternal();
break;
}
}
/*
/**********************************************************
/* Low-level output handling
/**********************************************************
*/
@Override
public void flush()
throws IOException
{
_flushBuffer();
if (_outputStream != null) {
if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) {
_outputStream.flush();
}
}
}
@Override
public void close()
throws IOException
{
super.close();
/* 05-Dec-2008, tatu: To add [JACKSON-27], need to close open
* scopes.
*/
// First: let's see that we still have buffers...
if (_outputBuffer != null
&& isEnabled(Feature.AUTO_CLOSE_JSON_CONTENT)) {
while (true) {
JsonStreamContext ctxt = getOutputContext();
if (ctxt.inArray()) {
writeEndArray();
} else if (ctxt.inObject()) {
writeEndObject();
} else {
break;
}
}
}
_flushBuffer();
/* 25-Nov-2008, tatus: As per [JACKSON-16] we are not to call close()
* on the underlying Reader, unless we "own" it, or auto-closing
* feature is enabled.
* One downside: when using UTF8Writer, underlying buffer(s)
* may not be properly recycled if we don't close the writer.
*/
if (_outputStream != null) {
if (_ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_TARGET)) {
_outputStream.close();
} else if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) {
// If we can't close it, we should at least flush
_outputStream.flush();
}
}
// Internal buffer(s) generator has can now be released as well
_releaseBuffers();
}
@Override
protected void _releaseBuffers()
{
byte[] buf = _outputBuffer;
if (buf != null && _bufferRecyclable) {
_outputBuffer = null;
_ioContext.releaseWriteEncodingBuffer(buf);
}
char[] cbuf = _charBuffer;
if (cbuf != null) {
_charBuffer = null;
_ioContext.releaseConcatBuffer(cbuf);
}
}
/*
/**********************************************************
/* Internal methods, low-level writing, raw bytes
/**********************************************************
*/
private final void _writeBytes(byte[] bytes) throws IOException
{
final int len = bytes.length;
if ((_outputTail + len) > _outputEnd) {
_flushBuffer();
// still not enough?
if (len > MAX_BYTES_TO_BUFFER) {
_outputStream.write(bytes, 0, len);
return;
}
}
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, len);
_outputTail += len;
}
private final void _writeBytes(byte[] bytes, int offset, int len) throws IOException
{
if ((_outputTail + len) > _outputEnd) {
_flushBuffer();
// still not enough?
if (len > MAX_BYTES_TO_BUFFER) {
_outputStream.write(bytes, offset, len);
return;
}
}
System.arraycopy(bytes, offset, _outputBuffer, _outputTail, len);
_outputTail += len;
}
/*
/**********************************************************
/* Internal methods, mid-level writing, String segments
/**********************************************************
*/
/**
* Method called when String to write is long enough not to fit
* completely in temporary copy buffer. If so, we will actually
* copy it in small enough chunks so it can be directly fed
* to single-segment writes (instead of maximum slices that
* would fit in copy buffer)
*/
private final void _writeStringSegments(String text)
throws IOException, JsonGenerationException
{
int left = text.length();
int offset = 0;
final char[] cbuf = _charBuffer;
while (left > 0) {
int len = Math.min(_outputMaxContiguous, left);
text.getChars(offset, offset+len, cbuf, 0);
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(cbuf, 0, len);
offset += len;
left -= len;
}
}
/**
* Method called when character sequence to write is long enough that
* its maximum encoded and escaped form is not guaranteed to fit in
* the output buffer. If so, we will need to choose smaller output
* chunks to write at a time.
*/
private final void _writeStringSegments(char[] cbuf, int offset, int totalLen)
throws IOException, JsonGenerationException
{
do {
int len = Math.min(_outputMaxContiguous, totalLen);
if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
_flushBuffer();
}
_writeStringSegment(cbuf, offset, len);
offset += len;
totalLen -= len;
} while (totalLen > 0);
}
/*
/**********************************************************
/* Internal methods, low-level writing, text segments
/**********************************************************
*/
/**
* This method called when the string content is already in
* a char buffer, and its maximum total encoded and escaped length
* can not exceed size of the output buffer.
* Caller must ensure that there is enough space in output buffer,
* assuming case of all non-escaped ASCII characters, as well as
* potentially enough space for other cases (but not necessarily flushed)
*/
private final void _writeStringSegment(char[] cbuf, int offset, int len)
throws IOException, JsonGenerationException
{
// note: caller MUST ensure (via flushing) there's room for ASCII only
// Fast+tight loop for ASCII-only, no-escaping-needed output
len += offset; // becomes end marker, then
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
while (offset < len) {
int ch = cbuf[offset];
// note: here we know that (ch > 0x7F) will cover case of escaping non-ASCII too:
if (ch > 0x7F || escCodes[ch] != 0) {
break;
}
outputBuffer[outputPtr++] = (byte) ch;
++offset;
}
_outputTail = outputPtr;
if (offset < len) {
// [JACKSON-106]
if (_characterEscapes != null) {
_writeCustomStringSegment2(cbuf, offset, len);
// [JACKSON-102]
} else if (_maximumNonEscapedChar == 0) {
_writeStringSegment2(cbuf, offset, len);
} else {
_writeStringSegmentASCII2(cbuf, offset, len);
}
}
}
/**
* Secondary method called when content contains characters to escape,
* and/or multi-byte UTF-8 characters.
*/
private final void _writeStringSegment2(final char[] cbuf, int offset, final int end)
throws IOException, JsonGenerationException
{
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((_outputTail + 6 * (end - offset)) > _outputEnd) {
_flushBuffer();
}
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
while (offset < end) {
int ch = cbuf[offset++];
if (ch <= 0x7F) {
if (escCodes[ch] == 0) {
outputBuffer[outputPtr++] = (byte) ch;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
continue;
}
if (ch <= 0x7FF) { // fine, just needs 2 byte output
outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6));
outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
} else {
outputPtr = _outputMultiByteChar(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, text segment
/* with additional escaping (ASCII or such)
/**********************************************************
*/
/**
* Same as <code>_writeStringSegment2(char[], ...)</code., but with
* additional escaping for high-range code points
*/
private final void _writeStringSegmentASCII2(final char[] cbuf, int offset, final int end)
throws IOException, JsonGenerationException
{
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((_outputTail + 6 * (end - offset)) > _outputEnd) {
_flushBuffer();
}
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
final int maxUnescaped = _maximumNonEscapedChar;
while (offset < end) {
int ch = cbuf[offset++];
if (ch <= 0x7F) {
if (escCodes[ch] == 0) {
outputBuffer[outputPtr++] = (byte) ch;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
continue;
}
if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars:
outputPtr = _writeGenericEscape(ch, outputPtr);
continue;
}
if (ch <= 0x7FF) { // fine, just needs 2 byte output
outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6));
outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
} else {
outputPtr = _outputMultiByteChar(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, text segment
/* with fully custom escaping (and possibly escaping of non-ASCII
/**********************************************************
*/
/**
* Same as <code>_writeStringSegmentASCII2(char[], ...)</code., but with
* additional checking for completely custom escapes
*/
private final void _writeCustomStringSegment2(final char[] cbuf, int offset, final int end)
throws IOException, JsonGenerationException
{
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((_outputTail + 6 * (end - offset)) > _outputEnd) {
_flushBuffer();
}
int outputPtr = _outputTail;
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
// may or may not have this limit
final int maxUnescaped = (_maximumNonEscapedChar <= 0) ? 0xFFFF : _maximumNonEscapedChar;
final CharacterEscapes customEscapes = _characterEscapes; // non-null
while (offset < end) {
int ch = cbuf[offset++];
if (ch <= 0x7F) {
if (escCodes[ch] == 0) {
outputBuffer[outputPtr++] = (byte) ch;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else if (escape == CharacterEscapes.ESCAPE_CUSTOM) {
SerializableString esc = customEscapes.getEscapeSequence(ch);
if (esc == null) {
_reportError("Invalid custom escape definitions; custom escape not found for character code 0x"
+Integer.toHexString(ch)+", although was supposed to have one");
}
outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset);
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
continue;
}
if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars:
outputPtr = _writeGenericEscape(ch, outputPtr);
continue;
}
SerializableString esc = customEscapes.getEscapeSequence(ch);
if (esc != null) {
outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset);
continue;
}
if (ch <= 0x7FF) { // fine, just needs 2 byte output
outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6));
outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
} else {
outputPtr = _outputMultiByteChar(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
private final int _writeCustomEscape(byte[] outputBuffer, int outputPtr, SerializableString esc, int remainingChars)
throws IOException, JsonGenerationException
{
byte[] raw = esc.asUnquotedUTF8(); // must be escaped at this point, shouldn't double-quote
int len = raw.length;
if (len > 6) { // may violate constraints we have, do offline
return _handleLongCustomEscape(outputBuffer, outputPtr, _outputEnd, raw, remainingChars);
}
// otherwise will fit without issues, so:
System.arraycopy(raw, 0, outputBuffer, outputPtr, len);
return (outputPtr + len);
}
private final int _handleLongCustomEscape(byte[] outputBuffer, int outputPtr, int outputEnd, byte[] raw,
int remainingChars)
throws IOException, JsonGenerationException
{
int len = raw.length;
if ((outputPtr + len) > outputEnd) {
_outputTail = outputPtr;
_flushBuffer();
outputPtr = _outputTail;
if (len > outputBuffer.length) { // very unlikely, but possible...
_outputStream.write(raw, 0, len);
return outputPtr;
}
System.arraycopy(raw, 0, outputBuffer, outputPtr, len);
outputPtr += len;
}
// but is the invariant still obeyed? If not, flush once more
if ((outputPtr + 6 * remainingChars) > outputEnd) {
_flushBuffer();
return _outputTail;
}
return outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, "raw UTF-8" segments
/**********************************************************
*/
/**
* Method called when UTF-8 encoded (but NOT yet escaped!) content is not guaranteed
* to fit in the output buffer after escaping; as such, we just need to
* chunk writes.
*/
private final void _writeUTF8Segments(byte[] utf8, int offset, int totalLen)
throws IOException, JsonGenerationException
{
do {
int len = Math.min(_outputMaxContiguous, totalLen);
_writeUTF8Segment(utf8, offset, len);
offset += len;
totalLen -= len;
} while (totalLen > 0);
}
private final void _writeUTF8Segment(byte[] utf8, final int offset, final int len)
throws IOException, JsonGenerationException
{
// fast loop to see if escaping is needed; don't copy, just look
final int[] escCodes = _outputEscapes;
for (int ptr = offset, end = offset + len; ptr < end; ) {
// 28-Feb-2011, tatu: escape codes just cover 7-bit range, so:
int ch = utf8[ptr++];
if ((ch >= 0) && escCodes[ch] != 0) {
_writeUTF8Segment2(utf8, offset, len);
return;
}
}
// yes, fine, just copy the sucker
if ((_outputTail + len) > _outputEnd) { // enough room or need to flush?
_flushBuffer(); // but yes once we flush (caller guarantees length restriction)
}
System.arraycopy(utf8, offset, _outputBuffer, _outputTail, len);
_outputTail += len;
}
private final void _writeUTF8Segment2(final byte[] utf8, int offset, int len)
throws IOException, JsonGenerationException
{
int outputPtr = _outputTail;
// Ok: caller guarantees buffer can have room; but that may require flushing:
if ((outputPtr + (len * 6)) > _outputEnd) {
_flushBuffer();
outputPtr = _outputTail;
}
final byte[] outputBuffer = _outputBuffer;
final int[] escCodes = _outputEscapes;
len += offset; // so 'len' becomes 'end'
while (offset < len) {
byte b = utf8[offset++];
int ch = b;
if (ch < 0 || escCodes[ch] == 0) {
outputBuffer[outputPtr++] = b;
continue;
}
int escape = escCodes[ch];
if (escape > 0) { // 2-char escape, fine
outputBuffer[outputPtr++] = BYTE_BACKSLASH;
outputBuffer[outputPtr++] = (byte) escape;
} else {
// ctrl-char, 6-byte escape...
outputPtr = _writeGenericEscape(ch, outputPtr);
}
}
_outputTail = outputPtr;
}
/*
/**********************************************************
/* Internal methods, low-level writing, base64 encoded
/**********************************************************
*/
protected final void _writeBinary(Base64Variant b64variant,
byte[] input, int inputPtr, final int inputEnd)
throws IOException, JsonGenerationException
{
// Encoding is by chunks of 3 input, 4 output chars, so:
int safeInputEnd = inputEnd - 3;
// Let's also reserve room for possible (and quoted) lf char each round
int safeOutputEnd = _outputEnd - 6;
int chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
// Ok, first we loop through all full triplets of data:
while (inputPtr <= safeInputEnd) {
if (_outputTail > safeOutputEnd) { // need to flush
_flushBuffer();
}
// First, mash 3 bytes into lsb of 32-bit int
int b24 = ((int) input[inputPtr++]) << 8;
b24 |= ((int) input[inputPtr++]) & 0xFF;
b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF);
_outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail);
if (--chunksBeforeLF <= 0) {
// note: must quote in JSON value
_outputBuffer[_outputTail++] = '\\';
_outputBuffer[_outputTail++] = 'n';
chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
}
}
// And then we may have 1 or 2 leftover bytes to encode
int inputLeft = inputEnd - inputPtr; // 0, 1 or 2
if (inputLeft > 0) { // yes, but do we have room for output?
if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but...
_flushBuffer();
}
int b24 = ((int) input[inputPtr++]) << 16;
if (inputLeft == 2) {
b24 |= (((int) input[inputPtr++]) & 0xFF) << 8;
}
_outputTail = b64variant.encodeBase64Partial(b24, inputLeft, _outputBuffer, _outputTail);
}
}
// write-method called when length is definitely known
protected final int _writeBinary(Base64Variant b64variant,
InputStream data, byte[] readBuffer, int bytesLeft)
throws IOException, JsonGenerationException
{
int inputPtr = 0;
int inputEnd = 0;
int lastFullOffset = -3;
// Let's also reserve room for possible (and quoted) LF char each round
int safeOutputEnd = _outputEnd - 6;
int chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
while (bytesLeft > 2) { // main loop for full triplets
if (inputPtr > lastFullOffset) {
inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft);
inputPtr = 0;
if (inputEnd < 3) { // required to try to read to have at least 3 bytes
break;
}
lastFullOffset = inputEnd-3;
}
if (_outputTail > safeOutputEnd) { // need to flush
_flushBuffer();
}
int b24 = ((int) readBuffer[inputPtr++]) << 8;
b24 |= ((int) readBuffer[inputPtr++]) & 0xFF;
b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF);
bytesLeft -= 3;
_outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail);
if (--chunksBeforeLF <= 0) {
_outputBuffer[_outputTail++] = '\\';
_outputBuffer[_outputTail++] = 'n';
chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
}
}
// And then we may have 1 or 2 leftover bytes to encode
if (bytesLeft > 0) {
inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft);
inputPtr = 0;
if (inputEnd > 0) { // yes, but do we have room for output?
if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but...
_flushBuffer();
}
int b24 = ((int) readBuffer[inputPtr++]) << 16;
int amount;
if (inputPtr < inputEnd) {
b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8;
amount = 2;
} else {
amount = 1;
}
_outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail);
bytesLeft -= amount;
}
}
return bytesLeft;
}
// write method when length is unknown
protected final int _writeBinary(Base64Variant b64variant,
InputStream data, byte[] readBuffer)
throws IOException, JsonGenerationException
{
int inputPtr = 0;
int inputEnd = 0;
int lastFullOffset = -3;
int bytesDone = 0;
// Let's also reserve room for possible (and quoted) LF char each round
int safeOutputEnd = _outputEnd - 6;
int chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
// Ok, first we loop through all full triplets of data:
while (true) {
if (inputPtr > lastFullOffset) { // need to load more
inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, readBuffer.length);
inputPtr = 0;
if (inputEnd < 3) { // required to try to read to have at least 3 bytes
break;
}
lastFullOffset = inputEnd-3;
}
if (_outputTail > safeOutputEnd) { // need to flush
_flushBuffer();
}
// First, mash 3 bytes into lsb of 32-bit int
int b24 = ((int) readBuffer[inputPtr++]) << 8;
b24 |= ((int) readBuffer[inputPtr++]) & 0xFF;
b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF);
bytesDone += 3;
_outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail);
if (--chunksBeforeLF <= 0) {
_outputBuffer[_outputTail++] = '\\';
_outputBuffer[_outputTail++] = 'n';
chunksBeforeLF = b64variant.getMaxLineLength() >> 2;
}
}
// And then we may have 1 or 2 leftover bytes to encode
if (inputPtr < inputEnd) { // yes, but do we have room for output?
if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but...
_flushBuffer();
}
int b24 = ((int) readBuffer[inputPtr++]) << 16;
int amount = 1;
if (inputPtr < inputEnd) {
b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8;
amount = 2;
}
bytesDone += amount;
_outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail);
}
return bytesDone;
}
private final int _readMore(InputStream in,
byte[] readBuffer, int inputPtr, int inputEnd,
int maxRead) throws IOException
{
// anything to shift to front?
int i = 0;
while (inputPtr < inputEnd) {
readBuffer[i++] = readBuffer[inputPtr++];
}
inputPtr = 0;
inputEnd = i;
maxRead = Math.min(maxRead, readBuffer.length);
do {
int length = maxRead - inputEnd;
if (length == 0) {
break;
}
int count = in.read(readBuffer, inputEnd, length);
if (count < 0) {
return inputEnd;
}
inputEnd += count;
} while (inputEnd < 3);
return inputEnd;
}
/*
/**********************************************************
/* Internal methods, character escapes/encoding
/**********************************************************
*/
/**
* Method called to output a character that is beyond range of
* 1- and 2-byte UTF-8 encodings, when outputting "raw"
* text (meaning it is not to be escaped or quoted)
*/
private final int _outputRawMultiByteChar(int ch, char[] cbuf, int inputOffset, int inputLen)
throws IOException
{
// Let's handle surrogates gracefully (as 4 byte output):
if (ch >= SURR1_FIRST) {
if (ch <= SURR2_LAST) { // yes, outside of BMP
// Do we have second part?
if (inputOffset >= inputLen || cbuf == null) { // nope... have to note down
_reportError("Split surrogate on writeRaw() input (last character)");
}
_outputSurrogates(ch, cbuf[inputOffset]);
return (inputOffset+1);
}
}
final byte[] bbuf = _outputBuffer;
bbuf[_outputTail++] = (byte) (0xe0 | (ch >> 12));
bbuf[_outputTail++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
return inputOffset;
}
protected final void _outputSurrogates(int surr1, int surr2)
throws IOException
{
int c = _decodeSurrogate(surr1, surr2);
if ((_outputTail + 4) > _outputEnd) {
_flushBuffer();
}
final byte[] bbuf = _outputBuffer;
bbuf[_outputTail++] = (byte) (0xf0 | (c >> 18));
bbuf[_outputTail++] = (byte) (0x80 | ((c >> 12) & 0x3f));
bbuf[_outputTail++] = (byte) (0x80 | ((c >> 6) & 0x3f));
bbuf[_outputTail++] = (byte) (0x80 | (c & 0x3f));
}
/**
*
* @param ch
* @param outputPtr Position within output buffer to append multi-byte in
*
* @return New output position after appending
*
* @throws IOException
*/
private final int _outputMultiByteChar(int ch, int outputPtr)
throws IOException
{
byte[] bbuf = _outputBuffer;
if (ch >= SURR1_FIRST && ch <= SURR2_LAST) { // yes, outside of BMP; add an escape
bbuf[outputPtr++] = BYTE_BACKSLASH;
bbuf[outputPtr++] = BYTE_u;
bbuf[outputPtr++] = HEX_CHARS[(ch >> 12) & 0xF];
bbuf[outputPtr++] = HEX_CHARS[(ch >> 8) & 0xF];
bbuf[outputPtr++] = HEX_CHARS[(ch >> 4) & 0xF];
bbuf[outputPtr++] = HEX_CHARS[ch & 0xF];
} else {
bbuf[outputPtr++] = (byte) (0xe0 | (ch >> 12));
bbuf[outputPtr++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
bbuf[outputPtr++] = (byte) (0x80 | (ch & 0x3f));
}
return outputPtr;
}
protected final int _decodeSurrogate(int surr1, int surr2) throws IOException
{
// First is known to be valid, but how about the other?
if (surr2 < SURR2_FIRST || surr2 > SURR2_LAST) {
String msg = "Incomplete surrogate pair: first char 0x"+Integer.toHexString(surr1)+", second 0x"+Integer.toHexString(surr2);
_reportError(msg);
}
int c = 0x10000 + ((surr1 - SURR1_FIRST) << 10) + (surr2 - SURR2_FIRST);
return c;
}
private final void _writeNull() throws IOException
{
if ((_outputTail + 4) >= _outputEnd) {
_flushBuffer();
}
System.arraycopy(NULL_BYTES, 0, _outputBuffer, _outputTail, 4);
_outputTail += 4;
}
/**
* Method called to write a generic Unicode escape for given character.
*
* @param charToEscape Character to escape using escape sequence (\\uXXXX)
*/
private int _writeGenericEscape(int charToEscape, int outputPtr)
throws IOException
{
final byte[] bbuf = _outputBuffer;
bbuf[outputPtr++] = BYTE_BACKSLASH;
bbuf[outputPtr++] = BYTE_u;
if (charToEscape > 0xFF) {
int hi = (charToEscape >> 8) & 0xFF;
bbuf[outputPtr++] = HEX_CHARS[hi >> 4];
bbuf[outputPtr++] = HEX_CHARS[hi & 0xF];
charToEscape &= 0xFF;
} else {
bbuf[outputPtr++] = BYTE_0;
bbuf[outputPtr++] = BYTE_0;
}
// We know it's a control char, so only the last 2 chars are non-0
bbuf[outputPtr++] = HEX_CHARS[charToEscape >> 4];
bbuf[outputPtr++] = HEX_CHARS[charToEscape & 0xF];
return outputPtr;
}
protected final void _flushBuffer() throws IOException
{
int len = _outputTail;
if (len > 0) {
_outputTail = 0;
_outputStream.write(_outputBuffer, 0, len);
}
}
}
| Last tweaking of byte-based writer
| src/main/java/com/fasterxml/jackson/core/json/UTF8JsonGenerator.java | Last tweaking of byte-based writer | <ide><path>rc/main/java/com/fasterxml/jackson/core/json/UTF8JsonGenerator.java
<ide> * (Question: should quoting of spaces (etc) still be enabled?)
<ide> */
<ide> if (_cfgUnqNames) {
<del> _writeStringSegments(name);
<add> _writeStringSegments(name, false);
<ide> return;
<ide> }
<del> if (_outputTail >= _outputEnd) {
<del> _flushBuffer();
<del> }
<del> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<del> // The beef:
<ide> final int len = name.length();
<del> if (len <= _charBufferLength) { // yes, fits right in
<del> name.getChars(0, len, _charBuffer, 0);
<del> // But as one segment, or multiple?
<del> if (len <= _outputMaxContiguous) {
<del> if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
<del> _flushBuffer();
<del> }
<del> _writeStringSegment(_charBuffer, 0, len);
<del> } else {
<del> _writeStringSegments(_charBuffer, 0, len);
<del> }
<add> // Does it fit in buffer?
<add> if (len > _charBufferLength) { // no, offline
<add> _writeStringSegments(name, true);
<add> return;
<add> }
<add> if (_outputTail >= _outputEnd) {
<add> _flushBuffer();
<add> }
<add> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<add> name.getChars(0, len, _charBuffer, 0);
<add> // But as one segment, or multiple?
<add> if (len <= _outputMaxContiguous) {
<add> if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
<add> _flushBuffer();
<add> }
<add> _writeStringSegment(_charBuffer, 0, len);
<ide> } else {
<del> _writeStringSegments(name);
<del> }
<del>
<add> _writeStringSegments(_charBuffer, 0, len);
<add> }
<ide> // and closing quotes; need room for one more char:
<ide> if (_outputTail >= _outputEnd) {
<ide> _flushBuffer();
<ide> }
<ide> _outputBuffer[_outputTail++] = BYTE_COMMA;
<ide> }
<del> _writeFieldName(name);
<del> }
<del>
<del> protected final void _writeFieldName(SerializableString name) throws IOException
<del> {
<ide> if (_cfgUnqNames) {
<ide> _writeUnq(name);
<ide> return;
<ide> } else {
<ide> _cfgPrettyPrinter.beforeObjectEntries(this);
<ide> }
<del> if (_cfgUnqNames) { // standard
<del> _writeStringSegments(name);
<add> if (_cfgUnqNames) {
<add> _writeStringSegments(name, false);
<add> return;
<add> }
<add> final int len = name.length();
<add> if (len > _charBufferLength) {
<add> _writeStringSegments(name, true);
<add> return;
<add> }
<add> if (_outputTail >= _outputEnd) {
<add> _flushBuffer();
<add> }
<add> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<add> name.getChars(0, len, _charBuffer, 0);
<add> // But as one segment, or multiple?
<add> if (len <= _outputMaxContiguous) {
<add> if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
<add> _flushBuffer();
<add> }
<add> _writeStringSegment(_charBuffer, 0, len);
<ide> } else {
<del> if (_outputTail >= _outputEnd) {
<del> _flushBuffer();
<del> }
<del> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<del> final int len = name.length();
<del> if (len <= _charBufferLength) { // yes, fits right in
<del> name.getChars(0, len, _charBuffer, 0);
<del> // But as one segment, or multiple?
<del> if (len <= _outputMaxContiguous) {
<del> if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space
<del> _flushBuffer();
<del> }
<del> _writeStringSegment(_charBuffer, 0, len);
<del> } else {
<del> _writeStringSegments(_charBuffer, 0, len);
<del> }
<del> } else {
<del> _writeStringSegments(name);
<del> }
<del> if (_outputTail >= _outputEnd) {
<del> _flushBuffer();
<del> }
<del> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<del> }
<add> _writeStringSegments(_charBuffer, 0, len);
<add> }
<add> if (_outputTail >= _outputEnd) {
<add> _flushBuffer();
<add> }
<add> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<ide> }
<ide>
<ide> protected final void _writePPFieldName(SerializableString name) throws IOException
<ide> // First: can we make a local copy of chars that make up text?
<ide> final int len = text.length();
<ide> if (len > _charBufferLength) { // nope: off-line handling
<del> _writeLongString(text);
<add> _writeStringSegments(text, true);
<ide> return;
<ide> }
<ide> // yes: good.
<ide> /* [JACKSON-462] But that method may have had to expand multi-byte Unicode
<ide> * chars, so we must check again
<ide> */
<del> if (_outputTail >= _outputEnd) {
<del> _flushBuffer();
<del> }
<del> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<del> }
<del>
<del> private void _writeLongString(String text) throws IOException
<del> {
<del> if (_outputTail >= _outputEnd) {
<del> _flushBuffer();
<del> }
<del> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<del> _writeStringSegments(text);
<ide> if (_outputTail >= _outputEnd) {
<ide> _flushBuffer();
<ide> }
<ide> * to single-segment writes (instead of maximum slices that
<ide> * would fit in copy buffer)
<ide> */
<del> private final void _writeStringSegments(String text)
<del> throws IOException, JsonGenerationException
<del> {
<add> private final void _writeStringSegments(String text, boolean addQuotes) throws IOException
<add> {
<add> if (addQuotes) {
<add> if (_outputTail >= _outputEnd) {
<add> _flushBuffer();
<add> }
<add> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<add> }
<add>
<ide> int left = text.length();
<ide> int offset = 0;
<ide> final char[] cbuf = _charBuffer;
<ide> _writeStringSegment(cbuf, 0, len);
<ide> offset += len;
<ide> left -= len;
<add> }
<add>
<add> if (addQuotes) {
<add> if (_outputTail >= _outputEnd) {
<add> _flushBuffer();
<add> }
<add> _outputBuffer[_outputTail++] = BYTE_QUOTE;
<ide> }
<ide> }
<ide> |
|
Java | epl-1.0 | d862575fceaf74cd105b71695bcd9efd862f59bb | 0 | DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base | package ch.elexis.ebanking.qr;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;
import ch.elexis.core.model.IContact;
import ch.elexis.core.model.builder.IContactBuilder.OrganizationBuilder;
import ch.elexis.core.model.builder.IContactBuilder.PersonBuilder;
import ch.elexis.core.services.holder.CoreModelServiceHolder;
import ch.elexis.core.types.Country;
import ch.elexis.core.types.Gender;
import ch.elexis.ebanking.qr.model.QRBillData;
import ch.rgw.tools.Money;
public class QRBillDataBuilderTest {
private IContact cdtr;
private IContact dbtr;
@Before
public void before(){
cdtr = new PersonBuilder(CoreModelServiceHolder.get(), "CdtrFirstname", "CdtrLastname",
LocalDate.of(2000, 2, 2), Gender.FEMALE).mandator().build();
cdtr.setExtInfo("IBAN", "CH4431999123000889012");
cdtr.setStreet("Grosse Marktgasse 28");
cdtr.setZip("9400");
cdtr.setCity("Rorschach");
cdtr.setCountry(Country.CH);
dbtr = new OrganizationBuilder(CoreModelServiceHolder.get(), "DbtrOrg").build();
dbtr.setStreet("Rue du Lac 1268");
dbtr.setZip("2501");
dbtr.setCity("Biel");
dbtr.setCountry(Country.CH);
}
@Test
public void buildSuccess(){
QRBillDataBuilder builder = new QRBillDataBuilder(cdtr, new Money(12.00), "CHF", dbtr);
builder.reference("977598000000002414281387835");
builder.unstructuredRemark("Ähnliche Rechnung #23 oder -23 über +23 mit <23");
QRBillData data = builder.build();
assertNotNull(data);
String qrData = data.toString();
assertTrue(StringUtils.isNotEmpty(qrData));
String[] parts = qrData.split("\r\n", -1);
assertEquals(32, parts.length);
assertEquals("CH4431999123000889012", parts[3]);
assertEquals("Grosse Marktgasse 28", parts[6]);
assertEquals("9400 Rorschach", parts[7]);
assertEquals("", parts[8]);
assertEquals("", parts[9]);
assertEquals("CH", parts[10]);
assertEquals("12.00", parts[18]);
assertEquals("CHF", parts[19]);
assertEquals("DbtrOrg", parts[21]);
assertEquals("Rue du Lac 1268", parts[22]);
assertEquals("CH", parts[26]);
assertEquals("QRR", parts[27]);
assertEquals("977598000000002414281387835", parts[28]);
assertEquals("Ähnliche Rechnung #23 oder -23 über +23 mit <23", parts[29]);
}
}
| tests/ch.elexis.ebanking.qr.test/src/ch/elexis/ebanking/qr/QRBillDataBuilderTest.java | package ch.elexis.ebanking.qr;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;
import ch.elexis.core.model.IContact;
import ch.elexis.core.model.builder.IContactBuilder.OrganizationBuilder;
import ch.elexis.core.model.builder.IContactBuilder.PersonBuilder;
import ch.elexis.core.services.holder.CoreModelServiceHolder;
import ch.elexis.core.types.Country;
import ch.elexis.core.types.Gender;
import ch.elexis.ebanking.qr.model.QRBillData;
import ch.rgw.tools.Money;
public class QRBillDataBuilderTest {
private IContact cdtr;
private IContact dbtr;
@Before
public void before(){
cdtr = new PersonBuilder(CoreModelServiceHolder.get(), "CdtrFirstname", "CdtrLastname",
LocalDate.of(2000, 2, 2), Gender.FEMALE).mandator().build();
cdtr.setExtInfo("IBAN", "CH4431999123000889012");
cdtr.setStreet("Grosse Marktgasse 28");
cdtr.setZip("9400");
cdtr.setCity("Rorschach");
cdtr.setCountry(Country.CH);
dbtr = new OrganizationBuilder(CoreModelServiceHolder.get(), "DbtrOrg").build();
dbtr.setStreet("Rue du Lac 1268");
dbtr.setZip("2501");
dbtr.setCity("Biel");
dbtr.setCountry(Country.CH);
}
@Test
public void buildSuccess(){
QRBillDataBuilder builder = new QRBillDataBuilder(cdtr, new Money(12.00), "CHF", dbtr);
builder.reference("977598000000002414281387835");
builder.unstructuredRemark("Ähnliche Rechnung #23 oder -23 über +23 mit <23");
QRBillData data = builder.build();
assertNotNull(data);
String qrData = data.toString();
assertTrue(StringUtils.isNotEmpty(qrData));
String[] parts = qrData.split("\r\n", -1);
assertEquals(32, parts.length);
assertEquals("CH4431999123000889012", parts[3]);
assertEquals("Grosse Marktgasse 28", parts[6]);
assertEquals("9400 Rorschach", parts[7]);
assertEquals("", parts[8]);
assertEquals("", parts[9]);
assertEquals("CH", parts[10]);
assertEquals("12.00", parts[18]);
assertEquals("CHF", parts[19]);
assertEquals("DbtrOrg", parts[21]);
assertEquals("Rue du Lac 1268", parts[22]);
assertEquals("CH", parts[26]);
assertEquals("SCOR", parts[27]);
assertEquals("977598000000002414281387835", parts[28]);
assertEquals("Ähnliche Rechnung #23 oder -23 über +23 mit <23", parts[29]);
}
}
| [19897] test for QRR reference type | tests/ch.elexis.ebanking.qr.test/src/ch/elexis/ebanking/qr/QRBillDataBuilderTest.java | [19897] test for QRR reference type | <ide><path>ests/ch.elexis.ebanking.qr.test/src/ch/elexis/ebanking/qr/QRBillDataBuilderTest.java
<ide> assertEquals("Rue du Lac 1268", parts[22]);
<ide> assertEquals("CH", parts[26]);
<ide>
<del> assertEquals("SCOR", parts[27]);
<add> assertEquals("QRR", parts[27]);
<ide> assertEquals("977598000000002414281387835", parts[28]);
<ide>
<ide> assertEquals("Ähnliche Rechnung #23 oder -23 über +23 mit <23", parts[29]); |
|
Java | apache-2.0 | 3331d7484d473042fae19df9b9d96a5a09e853ff | 0 | kakao/hbase-tools,kakao/hbase-tools,kakao/hbase-tools | /*
* Copyright 2015 Kakao Corporation
*
* 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.kakao.hbase.common;
import com.kakao.hbase.common.util.Util;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.lang.ArrayUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public abstract class Args {
public static final String OPTION_REGION = "region";
public static final String OPTION_OUTPUT = "output";
public static final String OPTION_VERBOSE = "verbose";
public static final String OPTION_DEBUG = "debug";
public static final String OPTION_KERBEROS_CONFIG = "krbconf";
public static final String OPTION_KEY_TAB = "keytab";
public static final String OPTION_REGION_SERVER = "rs";
public static final String OPTION_PRINCIPAL = "principal";
public static final String OPTION_REALM = "realm";
public static final String OPTION_FORCE_PROCEED = "force-proceed";
public static final String OPTION_KEEP = "keep";
public static final String OPTION_SKIP_FLUSH = "skip-flush";
public static final String OPTION_EXCLUDE = "exclude";
public static final String OPTION_OVERRIDE = "override";
public static final String OPTION_AFTER_FAILURE = "after-failure";
public static final String OPTION_AFTER_SUCCESS = "after-success";
public static final String OPTION_CLEAR_WATCH_LEAK = "clear-watch-leak";
public static final String OPTION_CLEAR_WATCH_LEAK_ONLY = "clear-watch-leak-only";
public static final String OPTION_OPTIMIZE = "optimize";
public static final String OPTION_TURN_BALANCER_OFF = "turn-balancer-off";
public static final String OPTION_BALANCE_FACTOR = "factor";
public static final String OPTION_TEST = "test";
public static final String OPTION_HTTP_PORT = "port";
public static final String OPTION_INTERVAL = "interval";
public static final String OPTION_MOVE_ASYNC = "move-async";
public static final String OPTION_MAX_ITERATION = "max-iteration";
public static final String INVALID_ARGUMENTS = "Invalid arguments";
public static final String ALL_TABLES = "";
private static final int INTERVAL_DEFAULT_MS = 10 * 1000;
protected final String zookeeperQuorum;
protected final OptionSet optionSet;
public Args(String[] args) throws IOException {
OptionSet optionSetTemp = createOptionParser().parse(args);
List<?> nonOptionArguments = optionSetTemp.nonOptionArguments();
if (nonOptionArguments.size() < 1) throw new IllegalArgumentException(INVALID_ARGUMENTS);
String arg = (String) nonOptionArguments.get(0);
if (Util.isFile(arg)) {
String[] newArgs = (String[]) ArrayUtils.addAll(parseArgsFile(arg), Arrays.copyOfRange(args, 1, args.length));
this.optionSet = createOptionParser().parse(newArgs);
this.zookeeperQuorum = (String) optionSet.nonOptionArguments().get(0);
} else {
this.optionSet = optionSetTemp;
this.zookeeperQuorum = arg;
}
}
public static String commonUsage() {
return " args file:\n"
+ " Plain text file that contains args and options.\n"
+ " common options:\n"
+ " --" + Args.OPTION_FORCE_PROCEED + ": Do not ask whether to proceed.\n"
+ " --" + Args.OPTION_TEST + ": Set test mode.\n"
+ " --" + Args.OPTION_DEBUG + ": Print debug log.\n"
+ " --" + Args.OPTION_VERBOSE + ": Print some more messages.\n"
+ " --" + Args.OPTION_AFTER_FAILURE
+ "=<script> : The script to run when this running is failed.\n"
+ " The first argument of the script should be a message string.\n"
+ " --" + Args.OPTION_AFTER_SUCCESS
+ "=<script> : The script to run when this running is successfully finished.\n"
+ " The first argument of the script should be a message string.\n"
+ " --" + Args.OPTION_KEY_TAB + "=<keytab file>: Kerberos keytab file. Use absolute path.\n"
+ " --" + Args.OPTION_PRINCIPAL + "=<principal>: Kerberos principal.\n"
+ " --" + Args.OPTION_REALM + "=<realm>: Kerberos realm to use."
+ " Set this arg if it is not the default realm.\n"
+ " --" + Args.OPTION_KERBEROS_CONFIG + "=<kerberos config file>: Kerberos config file." +
" Use absolute path.\n";
}
public static String[] parseArgsFile(String fileName) throws IOException {
return parseArgsFile(fileName, false);
}
public static String[] parseArgsFile(String fileName, boolean fromResource) throws IOException {
final String string;
if (fromResource) {
string = Util.readFromResource(fileName);
} else {
string = Util.readFromFile(fileName);
}
return string.split("[ \n]");
}
@Override
public String toString() {
if (optionSet == null) return "";
return (optionSet.nonOptionArguments() == null ? "" : optionSet.nonOptionArguments().toString())
+ " - " + (optionSet.asMap() == null ? "" : optionSet.asMap().toString());
}
public String getTableName() {
if (optionSet.nonOptionArguments().size() > 1) {
return (String) optionSet.nonOptionArguments().get(1);
} else {
return Args.ALL_TABLES;
}
}
public String getZookeeperQuorum() {
return zookeeperQuorum;
}
protected abstract OptionParser createOptionParser();
protected OptionParser createCommonOptionParser() {
OptionParser optionParser = new OptionParser();
optionParser.accepts(OPTION_FORCE_PROCEED);
optionParser.accepts(OPTION_TEST);
optionParser.accepts(OPTION_DEBUG);
optionParser.accepts(OPTION_VERBOSE);
optionParser.accepts(OPTION_KEY_TAB).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_PRINCIPAL).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_REALM).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_KERBEROS_CONFIG).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_AFTER_FAILURE).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_AFTER_SUCCESS).withRequiredArg().ofType(String.class);
return optionParser;
}
public String getAfterFailedScript() {
if (optionSet.has(OPTION_AFTER_FAILURE)) {
return (String) optionSet.valueOf(OPTION_AFTER_FAILURE);
} else {
return null;
}
}
public String getAfterFinishedScript() {
if (optionSet.has(OPTION_AFTER_SUCCESS)) {
return (String) optionSet.valueOf(OPTION_AFTER_SUCCESS);
} else {
return null;
}
}
public int getIntervalMS() {
if (optionSet.has(OPTION_INTERVAL))
return (Integer) optionSet.valueOf(OPTION_INTERVAL) * 1000;
else return INTERVAL_DEFAULT_MS;
}
public boolean has(String optionName) {
return optionSet.has(optionName);
}
public Object valueOf(String optionName) {
Object arg = optionSet.valueOf(optionName);
if (arg != null && arg instanceof String) {
String argString = ((String) arg).trim();
return argString.length() == 0 ? null : argString;
} else {
return arg;
}
}
public OptionSet getOptionSet() {
return optionSet;
}
public boolean isForceProceed() {
return optionSet.has(OPTION_FORCE_PROCEED);
}
}
| hbase0.98/hbase-common-0.98/src/main/java/com/kakao/hbase/common/Args.java | /*
* Copyright 2015 Kakao Corporation
*
* 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.kakao.hbase.common;
import com.kakao.hbase.common.util.Util;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.lang.ArrayUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public abstract class Args {
public static final String OPTION_REGION = "region";
public static final String OPTION_OUTPUT = "output";
public static final String OPTION_VERBOSE = "verbose";
public static final String OPTION_DEBUG = "debug";
public static final String OPTION_KERBEROS_CONFIG = "krbconf";
public static final String OPTION_KEY_TAB = "keytab";
public static final String OPTION_REGION_SERVER = "rs";
public static final String OPTION_PRINCIPAL = "principal";
public static final String OPTION_REALM = "realm";
public static final String OPTION_FORCE_PROCEED = "force-proceed";
public static final String OPTION_KEEP = "keep";
public static final String OPTION_SKIP_FLUSH = "skip-flush";
public static final String OPTION_EXCLUDE = "exclude";
public static final String OPTION_OVERRIDE = "override";
public static final String OPTION_AFTER_FAILURE = "after-failure";
public static final String OPTION_AFTER_SUCCESS = "after-success";
public static final String OPTION_CLEAR_WATCH_LEAK = "clear-watch-leak";
public static final String OPTION_CLEAR_WATCH_LEAK_ONLY = "clear-watch-leak-only";
public static final String OPTION_OPTIMIZE = "optimize";
public static final String OPTION_TURN_BALANCER_OFF = "turn-balancer-off";
public static final String OPTION_BALANCE_FACTOR = "factor";
public static final String OPTION_TEST = "test";
public static final String OPTION_HTTP_PORT = "port";
public static final String OPTION_INTERVAL = "interval";
public static final String OPTION_MOVE_ASYNC = "move-async";
public static final String OPTION_MAX_ITERATION = "max-iteration";
public static final String INVALID_ARGUMENTS = "Invalid arguments";
public static final String ALL_TABLES = "";
private static final int INTERVAL_DEFAULT_MS = 10 * 1000;
protected final String zookeeperQuorum;
protected final OptionSet optionSet;
public Args(String[] args) throws IOException {
OptionSet optionSetTemp = createOptionParser().parse(args);
List<?> nonOptionArguments = optionSetTemp.nonOptionArguments();
if (nonOptionArguments.size() < 1) throw new IllegalArgumentException(INVALID_ARGUMENTS);
String arg = (String) nonOptionArguments.get(0);
if (Util.isFile(arg)) {
String[] newArgs = (String[]) ArrayUtils.addAll(parseArgsFile(arg), Arrays.copyOfRange(args, 1, args.length));
this.optionSet = createOptionParser().parse(newArgs);
this.zookeeperQuorum = (String) optionSet.nonOptionArguments().get(0);
} else {
this.optionSet = optionSetTemp;
this.zookeeperQuorum = arg;
}
}
public static String commonUsage() {
return " args file:\n"
+ " Plain text file that contains args and options.\n"
+ " common options:\n"
+ " --" + Args.OPTION_FORCE_PROCEED + ": Do not ask whether to proceed.\n"
+ " --" + Args.OPTION_TEST + ": Set test mode.\n"
+ " --" + Args.OPTION_DEBUG + ": Print debug log.\n"
+ " --" + Args.OPTION_VERBOSE + ": Print some more messages.\n"
+ " --" + Args.OPTION_AFTER_FAILURE
+ "=<script> : The script to run when this running is failed."
+ " The first argument of the script should be a message string.\n"
+ " --" + Args.OPTION_AFTER_SUCCESS
+ "=<script> : The script to run when this running is successfully finished."
+ " The first argument of the script should be a message string.\n"
+ " --" + Args.OPTION_KEY_TAB + "=<keytab file>: Kerberos keytab file. Use absolute path.\n"
+ " --" + Args.OPTION_PRINCIPAL + "=<principal>: Kerberos principal.\n"
+ " --" + Args.OPTION_REALM + "=<realm>: Kerberos realm to use."
+ " Set this arg if it is not the default realm.\n"
+ " --" + Args.OPTION_KERBEROS_CONFIG + "=<kerberos config file>: Kerberos config file." +
" Use absolute path.\n";
}
public static String[] parseArgsFile(String fileName) throws IOException {
return parseArgsFile(fileName, false);
}
public static String[] parseArgsFile(String fileName, boolean fromResource) throws IOException {
final String string;
if (fromResource) {
string = Util.readFromResource(fileName);
} else {
string = Util.readFromFile(fileName);
}
return string.split("[ \n]");
}
@Override
public String toString() {
if (optionSet == null) return "";
return (optionSet.nonOptionArguments() == null ? "" : optionSet.nonOptionArguments().toString())
+ " - " + (optionSet.asMap() == null ? "" : optionSet.asMap().toString());
}
public String getTableName() {
if (optionSet.nonOptionArguments().size() > 1) {
return (String) optionSet.nonOptionArguments().get(1);
} else {
return Args.ALL_TABLES;
}
}
public String getZookeeperQuorum() {
return zookeeperQuorum;
}
protected abstract OptionParser createOptionParser();
protected OptionParser createCommonOptionParser() {
OptionParser optionParser = new OptionParser();
optionParser.accepts(OPTION_FORCE_PROCEED);
optionParser.accepts(OPTION_TEST);
optionParser.accepts(OPTION_DEBUG);
optionParser.accepts(OPTION_VERBOSE);
optionParser.accepts(OPTION_KEY_TAB).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_PRINCIPAL).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_REALM).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_KERBEROS_CONFIG).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_AFTER_FAILURE).withRequiredArg().ofType(String.class);
optionParser.accepts(OPTION_AFTER_SUCCESS).withRequiredArg().ofType(String.class);
return optionParser;
}
public String getAfterFailedScript() {
if (optionSet.has(OPTION_AFTER_FAILURE)) {
return (String) optionSet.valueOf(OPTION_AFTER_FAILURE);
} else {
return null;
}
}
public String getAfterFinishedScript() {
if (optionSet.has(OPTION_AFTER_SUCCESS)) {
return (String) optionSet.valueOf(OPTION_AFTER_SUCCESS);
} else {
return null;
}
}
public int getIntervalMS() {
if (optionSet.has(OPTION_INTERVAL))
return (Integer) optionSet.valueOf(OPTION_INTERVAL) * 1000;
else return INTERVAL_DEFAULT_MS;
}
public boolean has(String optionName) {
return optionSet.has(optionName);
}
public Object valueOf(String optionName) {
Object arg = optionSet.valueOf(optionName);
if (arg != null && arg instanceof String) {
String argString = ((String) arg).trim();
return argString.length() == 0 ? null : argString;
} else {
return arg;
}
}
public OptionSet getOptionSet() {
return optionSet;
}
public boolean isForceProceed() {
return optionSet.has(OPTION_FORCE_PROCEED);
}
}
| update usage
| hbase0.98/hbase-common-0.98/src/main/java/com/kakao/hbase/common/Args.java | update usage | <ide><path>base0.98/hbase-common-0.98/src/main/java/com/kakao/hbase/common/Args.java
<ide> + " --" + Args.OPTION_DEBUG + ": Print debug log.\n"
<ide> + " --" + Args.OPTION_VERBOSE + ": Print some more messages.\n"
<ide> + " --" + Args.OPTION_AFTER_FAILURE
<del> + "=<script> : The script to run when this running is failed."
<del> + " The first argument of the script should be a message string.\n"
<add> + "=<script> : The script to run when this running is failed.\n"
<add> + " The first argument of the script should be a message string.\n"
<ide> + " --" + Args.OPTION_AFTER_SUCCESS
<del> + "=<script> : The script to run when this running is successfully finished."
<del> + " The first argument of the script should be a message string.\n"
<add> + "=<script> : The script to run when this running is successfully finished.\n"
<add> + " The first argument of the script should be a message string.\n"
<ide> + " --" + Args.OPTION_KEY_TAB + "=<keytab file>: Kerberos keytab file. Use absolute path.\n"
<ide> + " --" + Args.OPTION_PRINCIPAL + "=<principal>: Kerberos principal.\n"
<ide> + " --" + Args.OPTION_REALM + "=<realm>: Kerberos realm to use." |
|
Java | agpl-3.0 | 7f3c59c9630dc753060b06d4826d22704a09ef98 | 0 | imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms | package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.PhoneDTO;
import com.imcode.imcms.domain.dto.UserDTO;
import com.imcode.imcms.domain.dto.UserFormData;
import com.imcode.imcms.domain.exception.UserNotExistsException;
import com.imcode.imcms.domain.service.PhoneService;
import com.imcode.imcms.domain.service.RoleService;
import com.imcode.imcms.domain.service.UserAdminRolesService;
import com.imcode.imcms.domain.service.UserRolesService;
import com.imcode.imcms.domain.service.UserService;
import com.imcode.imcms.model.Phone;
import com.imcode.imcms.model.PhoneType;
import com.imcode.imcms.model.PhoneTypes;
import com.imcode.imcms.model.Role;
import com.imcode.imcms.model.Roles;
import com.imcode.imcms.persistence.entity.User;
import com.imcode.imcms.persistence.repository.UserRepository;
import imcode.server.LanguageMapper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@Service
@Transactional
class DefaultUserService implements UserService {
private final static Logger log = Logger.getLogger(DefaultUserService.class.getName());
private final UserRepository userRepository;
private final RoleService roleService;
private final PhoneService phoneService;
private final UserRolesService userRolesService;
private final UserAdminRolesService userAdminRolesService;
@PersistenceContext
private EntityManager entityManager;
DefaultUserService(UserRepository userRepository,
RoleService roleService,
PhoneService phoneService,
UserRolesService userRolesService,
UserAdminRolesService userAdminRolesService) {
this.userRepository = userRepository;
this.roleService = roleService;
this.phoneService = phoneService;
this.userRolesService = userRolesService;
this.userAdminRolesService = userAdminRolesService;
}
@Override
public User getUser(int id) {
return Optional.ofNullable(userRepository.findById(id))
.orElseThrow(() -> new UserNotExistsException(id));
}
@Override
public User getUser(String login) {
return Optional.ofNullable(userRepository.findByLogin(login))
.orElseThrow(() -> new UserNotExistsException(login));
}
@Override
public void updateUser(UserDTO updateData) {
final Integer id = updateData.getId();
if (id == null) return;
final User user = getUser(id);
updatePresentUserFields(user, updateData);
userRepository.save(user);
}
private void updatePresentUserFields(User user, UserDTO updateData) {
updateFieldIfPresent(updateData::getId, user::setId);
updateFieldIfPresent(updateData::getEmail, user::setEmail);
updateFieldIfPresent(updateData::getFirstName, user::setFirstName);
updateFieldIfPresent(updateData::getLastName, user::setLastName);
updateFieldIfPresent(updateData::getLogin, user::setLogin);
updateFieldIfPresent(updateData::getActive, user::setActive);
}
private <T> void updateFieldIfPresent(Supplier<T> fieldGetter, Consumer<T> fieldSetter) {
Optional.ofNullable(fieldGetter.get()).ifPresent(fieldSetter);
}
@Override
public List<UserDTO> getAdminUsers() {
return toDTO(userRepository.findUsersWithRoleIds(Roles.USER_ADMIN.getId(), Roles.SUPER_ADMIN.getId()));
}
@Override
public List<UserDTO> getAllActiveUsers() {
return toDTO(userRepository.findByActiveIsTrue());
}
@Override
public List<UserDTO> getUsersByEmail(String email) {
return toDTO(userRepository.findByEmail(email));
}
private List<UserDTO> toDTO(Collection<User> users) {
return users.stream().map(UserDTO::new).collect(Collectors.toList());
}
@Override
public UserFormData getUserData(int userId) throws UserNotExistsException {
final User userJPA = getUser(userId);
final UserFormData userFormData = new UserFormData(userJPA);
setUserPhones(userFormData, userId);
setUserRoles(userFormData, userId);
setUserAdminRoles(userFormData, userId);
return userFormData;
}
private void setUserPhones(UserFormData userFormData, int userId) {
final List<Phone> userPhones = phoneService.getUserPhones(userId);
final List<String> userPhoneNumbers = new ArrayList<>();
final List<Integer> userPhoneNumberTypes = new ArrayList<>();
for (Phone userPhone : userPhones) {
userPhoneNumbers.add(userPhone.getNumber());
userPhoneNumberTypes.add(userPhone.getPhoneType().getId());
}
userFormData.setUserPhoneNumber(userPhoneNumbers.toArray(new String[0]));
userFormData.setUserPhoneNumberType(userPhoneNumberTypes.toArray(new Integer[0]));
}
private void setUserRoles(UserFormData userFormData, int userId) {
final int[] userRoleIds = toRoleIds(userRolesService.getRolesByUser(userId));
userFormData.setRoleIds(userRoleIds);
}
private void setUserAdminRoles(UserFormData userFormData, int userId) {
final int[] userRoleIds = toRoleIds(userAdminRolesService.getAdminRolesByUser(userId));
userFormData.setUserAdminRoleIds(userRoleIds);
}
private int[] toRoleIds(Collection<Role> roles) {
return roles.stream()
.filter(Predicate.isEqual(Roles.USER).negate())
.mapToInt(Role::getId)
.toArray();
}
@Override
public void saveUser(UserFormData userData) {
final User user = saveAndGetUser(userData);
updateUserData(userData, user);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
protected User saveAndGetUser(UserFormData userData) {
final User user = toUserJPA(userData);
if (userData.getId() != null) {
final User existingUser = userRepository.findById(userData.getId());
user.setPassword(existingUser.getPassword());
user.setPasswordReset(existingUser.getPasswordReset());
user.setSessionId(existingUser.getSessionId());
user.setRememberCd(existingUser.getRememberCd());
user.setPasswordType(existingUser.getPasswordType());
user.setExternal(existingUser.isExternal());
}
return userRepository.save(user);
}
private User toUserJPA(UserFormData userData) {
final User user = new User(userData);
user.setLanguageIso639_2(LanguageMapper.convert639_1to639_2(userData.getLangCode()));
return user;
}
private void updateUserData(UserFormData userData, User user) {
updateUserPhones(userData, user);
updateUserRoles(userData, user);
updateUserAdminRoles(userData, user);
}
void updateUserPhones(UserFormData userData, User user) {
final List<Phone> phoneNumbers = collectPhoneNumbers(userData, user);
phoneService.updateUserPhones(phoneNumbers, user.getId());
}
List<Phone> collectPhoneNumbers(UserFormData userData, User user) {
final String[] userPhoneNumbers = userData.getUserPhoneNumber();
final Integer[] userPhoneNumberTypes = userData.getUserPhoneNumberType();
if ((userPhoneNumbers == null)
|| (userPhoneNumberTypes == null)
|| (userPhoneNumbers.length <= 0)
|| (userPhoneNumberTypes.length <= 0)
|| (userPhoneNumbers.length != userPhoneNumberTypes.length))
{ // actually I don't know what to do if arrays have different length, however null and zero-length is fine
return Collections.emptyList();
}
List<Phone> numbers = new ArrayList<>();
for (int i = 0; i < userPhoneNumbers.length; i++) {
try {
final String userPhoneNumber = userPhoneNumbers[i];
final PhoneType numberType = PhoneTypes.getPhoneTypeById(userPhoneNumberTypes[i]);
numbers.add(new PhoneDTO(userPhoneNumber, user, numberType));
} catch (Exception e) {
log.error("Something wrong with phone numbers.", e);
}
}
return numbers;
}
private void updateUserRoles(UserFormData userData, User user) {
final List<Role> userRoles = collectRoles(userData.getRoleIds());
userRolesService.updateUserRoles(userRoles, user);
}
private void updateUserAdminRoles(UserFormData userData, User user) {
final List<Role> administrateRoles = collectRoles(userData.getUserAdminRoleIds());
userAdminRolesService.updateUserAdminRoles(administrateRoles, user);
}
List<Role> collectRoles(int[] roleIdsInt) {
if (roleIdsInt == null || roleIdsInt.length == 0) return Collections.emptyList();
return Arrays.stream(roleIdsInt)
.mapToObj(roleService::getById)
.collect(Collectors.toList());
}
// TODO: 13.10.17 Was moved. Rewrite to human code.
@Override
public List<User> findAll(boolean includeExternal, boolean includeInactive) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> c = cb.createQuery(User.class);
Root<User> user = c.from(User.class);
javax.persistence.criteria.Predicate criteria = cb.conjunction();
if (!includeExternal) {
criteria = cb.and(criteria, cb.notEqual(user.get("external"), 2));
}
if (!includeInactive) {
criteria = cb.and(criteria, cb.isTrue(user.get("active")));
}
c.select(user).where(criteria);
return entityManager.createQuery(c).getResultList();
}
// TODO: 13.10.17 Was moved. Rewrite to human code.
@Override
public List<User> findByNamePrefix(String prefix, boolean includeInactive) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> c = cb.createQuery(User.class);
Root<User> user = c.from(User.class);
javax.persistence.criteria.Predicate criteria = cb.notEqual(user.get("external"), 2);
if (!includeInactive) {
criteria = cb.and(criteria, cb.isTrue(user.get("active")));
}
criteria = cb.and(
criteria,
cb.or(
cb.like(user.get("login"), prefix),
cb.like(user.get("email"), prefix),
cb.like(user.get("firstName"), prefix),
cb.like(user.get("lastName"), prefix),
cb.like(user.get("title"), prefix),
cb.like(user.get("company"), prefix)
)
);
c.select(user).where(criteria).orderBy(cb.asc(user.get("lastName")), cb.asc(user.get("firstName")));
return entityManager.createQuery(c).getResultList();
}
}
| src/main/java/com/imcode/imcms/domain/service/api/DefaultUserService.java | package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.PhoneDTO;
import com.imcode.imcms.domain.dto.UserDTO;
import com.imcode.imcms.domain.dto.UserFormData;
import com.imcode.imcms.domain.exception.UserNotExistsException;
import com.imcode.imcms.domain.service.PhoneService;
import com.imcode.imcms.domain.service.RoleService;
import com.imcode.imcms.domain.service.UserAdminRolesService;
import com.imcode.imcms.domain.service.UserRolesService;
import com.imcode.imcms.domain.service.UserService;
import com.imcode.imcms.model.Phone;
import com.imcode.imcms.model.PhoneType;
import com.imcode.imcms.model.PhoneTypes;
import com.imcode.imcms.model.Role;
import com.imcode.imcms.model.Roles;
import com.imcode.imcms.persistence.entity.User;
import com.imcode.imcms.persistence.repository.UserRepository;
import imcode.server.LanguageMapper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@Service
class DefaultUserService implements UserService {
private final static Logger log = Logger.getLogger(DefaultUserService.class.getName());
private final UserRepository userRepository;
private final RoleService roleService;
private final PhoneService phoneService;
private final UserRolesService userRolesService;
private final UserAdminRolesService userAdminRolesService;
@PersistenceContext
private EntityManager entityManager;
DefaultUserService(UserRepository userRepository,
RoleService roleService,
PhoneService phoneService,
UserRolesService userRolesService,
UserAdminRolesService userAdminRolesService) {
this.userRepository = userRepository;
this.roleService = roleService;
this.phoneService = phoneService;
this.userRolesService = userRolesService;
this.userAdminRolesService = userAdminRolesService;
}
@Override
public User getUser(int id) {
return Optional.ofNullable(userRepository.findById(id))
.orElseThrow(() -> new UserNotExistsException(id));
}
@Override
public User getUser(String login) {
return Optional.ofNullable(userRepository.findByLogin(login))
.orElseThrow(() -> new UserNotExistsException(login));
}
@Override
public void updateUser(UserDTO updateData) {
final Integer id = updateData.getId();
if (id == null) return;
final User user = getUser(id);
updatePresentUserFields(user, updateData);
userRepository.save(user);
}
private void updatePresentUserFields(User user, UserDTO updateData) {
updateFieldIfPresent(updateData::getId, user::setId);
updateFieldIfPresent(updateData::getEmail, user::setEmail);
updateFieldIfPresent(updateData::getFirstName, user::setFirstName);
updateFieldIfPresent(updateData::getLastName, user::setLastName);
updateFieldIfPresent(updateData::getLogin, user::setLogin);
updateFieldIfPresent(updateData::getActive, user::setActive);
}
private <T> void updateFieldIfPresent(Supplier<T> fieldGetter, Consumer<T> fieldSetter) {
Optional.ofNullable(fieldGetter.get()).ifPresent(fieldSetter);
}
@Override
public List<UserDTO> getAdminUsers() {
return toDTO(userRepository.findUsersWithRoleIds(Roles.USER_ADMIN.getId(), Roles.SUPER_ADMIN.getId()));
}
@Override
public List<UserDTO> getAllActiveUsers() {
return toDTO(userRepository.findByActiveIsTrue());
}
@Override
public List<UserDTO> getUsersByEmail(String email) {
return toDTO(userRepository.findByEmail(email));
}
private List<UserDTO> toDTO(Collection<User> users) {
return users.stream().map(UserDTO::new).collect(Collectors.toList());
}
@Override
public UserFormData getUserData(int userId) throws UserNotExistsException {
final User userJPA = getUser(userId);
final UserFormData userFormData = new UserFormData(userJPA);
setUserPhones(userFormData, userId);
setUserRoles(userFormData, userId);
setUserAdminRoles(userFormData, userId);
return userFormData;
}
private void setUserPhones(UserFormData userFormData, int userId) {
final List<Phone> userPhones = phoneService.getUserPhones(userId);
final List<String> userPhoneNumbers = new ArrayList<>();
final List<Integer> userPhoneNumberTypes = new ArrayList<>();
for (Phone userPhone : userPhones) {
userPhoneNumbers.add(userPhone.getNumber());
userPhoneNumberTypes.add(userPhone.getPhoneType().getId());
}
userFormData.setUserPhoneNumber(userPhoneNumbers.toArray(new String[0]));
userFormData.setUserPhoneNumberType(userPhoneNumberTypes.toArray(new Integer[0]));
}
private void setUserRoles(UserFormData userFormData, int userId) {
final int[] userRoleIds = toRoleIds(userRolesService.getRolesByUser(userId));
userFormData.setRoleIds(userRoleIds);
}
private void setUserAdminRoles(UserFormData userFormData, int userId) {
final int[] userRoleIds = toRoleIds(userAdminRolesService.getAdminRolesByUser(userId));
userFormData.setUserAdminRoleIds(userRoleIds);
}
private int[] toRoleIds(Collection<Role> roles) {
return roles.stream()
.filter(Predicate.isEqual(Roles.USER).negate())
.mapToInt(Role::getId)
.toArray();
}
@Override
public void saveUser(UserFormData userData) {
final User user = saveAndGetUser(userData);
updateUserData(userData, user);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
protected User saveAndGetUser(UserFormData userData) {
final User user = toUserJPA(userData);
if (userData.getId() != null) {
final User existingUser = userRepository.findById(userData.getId());
user.setPassword(existingUser.getPassword());
user.setPasswordReset(existingUser.getPasswordReset());
user.setSessionId(existingUser.getSessionId());
user.setRememberCd(existingUser.getRememberCd());
user.setPasswordType(existingUser.getPasswordType());
user.setExternal(existingUser.isExternal());
}
return userRepository.save(user);
}
private User toUserJPA(UserFormData userData) {
final User user = new User(userData);
user.setLanguageIso639_2(LanguageMapper.convert639_1to639_2(userData.getLangCode()));
return user;
}
private void updateUserData(UserFormData userData, User user) {
updateUserPhones(userData, user);
updateUserRoles(userData, user);
updateUserAdminRoles(userData, user);
}
void updateUserPhones(UserFormData userData, User user) {
final List<Phone> phoneNumbers = collectPhoneNumbers(userData, user);
phoneService.updateUserPhones(phoneNumbers, user.getId());
}
List<Phone> collectPhoneNumbers(UserFormData userData, User user) {
final String[] userPhoneNumbers = userData.getUserPhoneNumber();
final Integer[] userPhoneNumberTypes = userData.getUserPhoneNumberType();
if ((userPhoneNumbers == null)
|| (userPhoneNumberTypes == null)
|| (userPhoneNumbers.length <= 0)
|| (userPhoneNumberTypes.length <= 0)
|| (userPhoneNumbers.length != userPhoneNumberTypes.length))
{ // actually I don't know what to do if arrays have different length, however null and zero-length is fine
return Collections.emptyList();
}
List<Phone> numbers = new ArrayList<>();
for (int i = 0; i < userPhoneNumbers.length; i++) {
try {
final String userPhoneNumber = userPhoneNumbers[i];
final PhoneType numberType = PhoneTypes.getPhoneTypeById(userPhoneNumberTypes[i]);
numbers.add(new PhoneDTO(userPhoneNumber, user, numberType));
} catch (Exception e) {
log.error("Something wrong with phone numbers.", e);
}
}
return numbers;
}
private void updateUserRoles(UserFormData userData, User user) {
final List<Role> userRoles = collectRoles(userData.getRoleIds());
userRolesService.updateUserRoles(userRoles, user);
}
private void updateUserAdminRoles(UserFormData userData, User user) {
final List<Role> administrateRoles = collectRoles(userData.getUserAdminRoleIds());
userAdminRolesService.updateUserAdminRoles(administrateRoles, user);
}
List<Role> collectRoles(int[] roleIdsInt) {
if (roleIdsInt == null || roleIdsInt.length == 0) return Collections.emptyList();
return Arrays.stream(roleIdsInt)
.mapToObj(roleService::getById)
.collect(Collectors.toList());
}
// TODO: 13.10.17 Was moved. Rewrite to human code.
@Override
public List<User> findAll(boolean includeExternal, boolean includeInactive) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> c = cb.createQuery(User.class);
Root<User> user = c.from(User.class);
javax.persistence.criteria.Predicate criteria = cb.conjunction();
if (!includeExternal) {
criteria = cb.and(criteria, cb.notEqual(user.get("external"), 2));
}
if (!includeInactive) {
criteria = cb.and(criteria, cb.isTrue(user.get("active")));
}
c.select(user).where(criteria);
return entityManager.createQuery(c).getResultList();
}
// TODO: 13.10.17 Was moved. Rewrite to human code.
@Override
public List<User> findByNamePrefix(String prefix, boolean includeInactive) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> c = cb.createQuery(User.class);
Root<User> user = c.from(User.class);
javax.persistence.criteria.Predicate criteria = cb.notEqual(user.get("external"), 2);
if (!includeInactive) {
criteria = cb.and(criteria, cb.isTrue(user.get("active")));
}
criteria = cb.and(
criteria,
cb.or(
cb.like(user.get("login"), prefix),
cb.like(user.get("email"), prefix),
cb.like(user.get("firstName"), prefix),
cb.like(user.get("lastName"), prefix),
cb.like(user.get("title"), prefix),
cb.like(user.get("company"), prefix)
)
);
c.select(user).where(criteria).orderBy(cb.asc(user.get("lastName")), cb.asc(user.get("firstName")));
return entityManager.createQuery(c).getResultList();
}
}
| IMCMS-300 - New design to superadmin-pages:
- User service now transactional.
| src/main/java/com/imcode/imcms/domain/service/api/DefaultUserService.java | IMCMS-300 - New design to superadmin-pages: - User service now transactional. | <ide><path>rc/main/java/com/imcode/imcms/domain/service/api/DefaultUserService.java
<ide> import java.util.stream.Collectors;
<ide>
<ide> @Service
<add>@Transactional
<ide> class DefaultUserService implements UserService {
<ide>
<ide> private final static Logger log = Logger.getLogger(DefaultUserService.class.getName()); |
|
Java | apache-2.0 | e047694cd074566aeb26369d2ff49c17f8044f30 | 0 | DevAhamed/MultiViewAdapter | /*
* Copyright 2017 Riyaz Ahamed
*
* 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.ahamed.sample.simple;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import com.ahamed.multiviewadapter.SimpleRecyclerAdapter;
import com.ahamed.sample.common.BaseActivity;
import com.ahamed.sample.common.model.Quote;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SimpleAdapterActivity extends BaseActivity {
private static final String TAG = "SimpleAdapterActivity";
public static void start(Context context) {
Intent starter = new Intent(context, SimpleAdapterActivity.class);
context.startActivity(starter);
}
@Override protected void setUpAdapter() {
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
recyclerView.addItemDecoration(
new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
SimpleRecyclerAdapter<Quote, QuoteBinder> adapter =
new SimpleRecyclerAdapter<>(new QuoteBinder());
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(adapter);
List<Quote> quotes = getQuotes();
adapter.setData(quotes);
}
private String loadJSONFromAsset() {
String json;
try {
InputStream is = getAssets().open("quotes.json");
int size = is.available();
byte[] buffer = new byte[size];
//noinspection ResultOfMethodCallIgnored
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
Log.e(TAG, "loadJSONFromAsset", ex);
return null;
}
return json;
}
private List<Quote> getQuotes() {
try {
JSONArray array = new JSONArray(loadJSONFromAsset());
List<Quote> quotes = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject branchObject = array.getJSONObject(i);
String quote = branchObject.getString("quote");
String author = branchObject.getString("author");
quotes.add(new Quote(author, quote));
}
return quotes;
} catch (JSONException e) {
Log.e(TAG, "getJSONFromAsset", e);
}
return null;
}
}
| sample/src/main/java/com/ahamed/sample/simple/SimpleAdapterActivity.java | /*
* Copyright 2017 Riyaz Ahamed
*
* 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.ahamed.sample.simple;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import com.ahamed.multiviewadapter.SimpleAdapter;
import com.ahamed.sample.common.BaseActivity;
import com.ahamed.sample.common.model.Quote;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SimpleAdapterActivity extends BaseActivity {
private static final String TAG = "SimpleAdapterActivity";
public static void start(Context context) {
Intent starter = new Intent(context, SimpleAdapterActivity.class);
context.startActivity(starter);
}
@Override protected void setUpAdapter() {
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
recyclerView.addItemDecoration(
new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
SimpleAdapter<Quote, QuoteBinder> adapter = new SimpleAdapter<>(new QuoteBinder());
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(adapter);
List<Quote> quotes = getQuotes();
adapter.setData(quotes);
}
private String loadJSONFromAsset() {
String json;
try {
InputStream is = getAssets().open("quotes.json");
int size = is.available();
byte[] buffer = new byte[size];
//noinspection ResultOfMethodCallIgnored
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
Log.e(TAG, "loadJSONFromAsset", ex);
return null;
}
return json;
}
private List<Quote> getQuotes() {
try {
JSONArray array = new JSONArray(loadJSONFromAsset());
List<Quote> quotes = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject branchObject = array.getJSONObject(i);
String quote = branchObject.getString("quote");
String author = branchObject.getString("author");
quotes.add(new Quote(author, quote));
}
return quotes;
} catch (JSONException e) {
Log.e(TAG, "getJSONFromAsset", e);
}
return null;
}
}
| Change reference of SimpleAdapter -> SimpleRecyclerAdapter
| sample/src/main/java/com/ahamed/sample/simple/SimpleAdapterActivity.java | Change reference of SimpleAdapter -> SimpleRecyclerAdapter | <ide><path>ample/src/main/java/com/ahamed/sample/simple/SimpleAdapterActivity.java
<ide> import android.support.v7.widget.DividerItemDecoration;
<ide> import android.support.v7.widget.LinearLayoutManager;
<ide> import android.util.Log;
<del>import com.ahamed.multiviewadapter.SimpleAdapter;
<add>import com.ahamed.multiviewadapter.SimpleRecyclerAdapter;
<ide> import com.ahamed.sample.common.BaseActivity;
<ide> import com.ahamed.sample.common.model.Quote;
<ide> import java.io.IOException;
<ide> recyclerView.addItemDecoration(
<ide> new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
<ide>
<del> SimpleAdapter<Quote, QuoteBinder> adapter = new SimpleAdapter<>(new QuoteBinder());
<add> SimpleRecyclerAdapter<Quote, QuoteBinder> adapter =
<add> new SimpleRecyclerAdapter<>(new QuoteBinder());
<ide>
<ide> recyclerView.setLayoutManager(llm);
<ide> recyclerView.setAdapter(adapter); |
|
Java | apache-2.0 | 3a635d11752803dc06d450e8c70d5c20793e5439 | 0 | caot/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,ernestp/consulo,jagguli/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,signed/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,fitermay/intellij-community,hurricup/intellij-community,dslomov/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,izonder/intellij-community,adedayo/intellij-community,fnouama/intellij-community,petteyg/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,samthor/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,vvv1559/intellij-community,allotria/intellij-community,jagguli/intellij-community,clumsy/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,joewalnes/idea-community,vladmm/intellij-community,izonder/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,ahb0327/intellij-community,ernestp/consulo,salguarnieri/intellij-community,jexp/idea2,akosyakov/intellij-community,izonder/intellij-community,apixandru/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,robovm/robovm-studio,slisson/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,hurricup/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,samthor/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,asedunov/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,izonder/intellij-community,ahb0327/intellij-community,da1z/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,slisson/intellij-community,ernestp/consulo,gnuhub/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,caot/intellij-community,consulo/consulo,FHannes/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,signed/intellij-community,diorcety/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,slisson/intellij-community,supersven/intellij-community,youdonghai/intellij-community,da1z/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,fnouama/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,semonte/intellij-community,izonder/intellij-community,semonte/intellij-community,semonte/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,robovm/robovm-studio,xfournet/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,caot/intellij-community,xfournet/intellij-community,semonte/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,slisson/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,holmes/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,jexp/idea2,SerCeMan/intellij-community,fnouama/intellij-community,izonder/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,signed/intellij-community,joewalnes/idea-community,caot/intellij-community,ol-loginov/intellij-community,caot/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,samthor/intellij-community,jexp/idea2,asedunov/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,blademainer/intellij-community,da1z/intellij-community,petteyg/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,semonte/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,hurricup/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,allotria/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,semonte/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,kool79/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,signed/intellij-community,ryano144/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,nicolargo/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,supersven/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,adedayo/intellij-community,supersven/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,da1z/intellij-community,xfournet/intellij-community,ernestp/consulo,petteyg/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,FHannes/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,fitermay/intellij-community,amith01994/intellij-community,supersven/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,signed/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,slisson/intellij-community,ernestp/consulo,ibinti/intellij-community,jagguli/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,samthor/intellij-community,caot/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,asedunov/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,supersven/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,samthor/intellij-community,FHannes/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,kdwink/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,fnouama/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,consulo/consulo,jexp/idea2,michaelgallacher/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,robovm/robovm-studio,dslomov/intellij-community,da1z/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,apixandru/intellij-community,caot/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,xfournet/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,robovm/robovm-studio,diorcety/intellij-community,kool79/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,adedayo/intellij-community,amith01994/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,kool79/intellij-community,fitermay/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,dslomov/intellij-community,retomerz/intellij-community,joewalnes/idea-community,xfournet/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,apixandru/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,holmes/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,diorcety/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,semonte/intellij-community,kool79/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,supersven/intellij-community,caot/intellij-community,hurricup/intellij-community,clumsy/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,kdwink/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,da1z/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,kool79/intellij-community,diorcety/intellij-community,fnouama/intellij-community,jexp/idea2,youdonghai/intellij-community,allotria/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,kdwink/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,blademainer/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,consulo/consulo,supersven/intellij-community,ibinti/intellij-community,clumsy/intellij-community,asedunov/intellij-community,clumsy/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,jexp/idea2,supersven/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,slisson/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,allotria/intellij-community,supersven/intellij-community,clumsy/intellij-community,allotria/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,clumsy/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,vladmm/intellij-community,signed/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,allotria/intellij-community,caot/intellij-community,vladmm/intellij-community,jexp/idea2,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,slisson/intellij-community,adedayo/intellij-community,ernestp/consulo,Distrotech/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ibinti/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,asedunov/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,da1z/intellij-community,hurricup/intellij-community,kool79/intellij-community,semonte/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,robovm/robovm-studio,semonte/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,semonte/intellij-community,retomerz/intellij-community,hurricup/intellij-community,consulo/consulo,samthor/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,samthor/intellij-community,signed/intellij-community,youdonghai/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,fnouama/intellij-community,adedayo/intellij-community,signed/intellij-community,ryano144/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,signed/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,joewalnes/idea-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,izonder/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,izonder/intellij-community,consulo/consulo,hurricup/intellij-community,allotria/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community | package com.intellij.codeInsight.generation.actions;
import com.intellij.codeInsight.generation.GenerateEqualsHandler;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiAnonymousClass;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
/**
* @author dsl
*/
public class GenerateEqualsAction extends BaseGenerateAction {
public GenerateEqualsAction() {
super(new GenerateEqualsHandler());
}
protected PsiClass getTargetClass(Editor editor, PsiFile file) {
final PsiClass targetClass = super.getTargetClass(editor, file);
if (targetClass == null || targetClass instanceof PsiAnonymousClass ||
targetClass.isEnum()) return null;
return targetClass;
}
}
| source/com/intellij/codeInsight/generation/actions/GenerateEqualsAction.java | package com.intellij.codeInsight.generation.actions;
import com.intellij.codeInsight.generation.GenerateEqualsHandler;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiClass;
/**
* @author dsl
*/
public class GenerateEqualsAction extends BaseGenerateAction {
public GenerateEqualsAction() {
super(new GenerateEqualsHandler());
}
protected PsiClass getTargetClass(Editor editor, PsiFile file) {
final PsiClass targetClass = super.getTargetClass(editor, file);
if (targetClass == null || targetClass.isEnum()) return null;
return targetClass;
}
}
| (no message) | source/com/intellij/codeInsight/generation/actions/GenerateEqualsAction.java | (no message) | <ide><path>ource/com/intellij/codeInsight/generation/actions/GenerateEqualsAction.java
<ide> package com.intellij.codeInsight.generation.actions;
<ide>
<ide> import com.intellij.codeInsight.generation.GenerateEqualsHandler;
<del>import com.intellij.openapi.project.Project;
<ide> import com.intellij.openapi.editor.Editor;
<add>import com.intellij.psi.PsiAnonymousClass;
<add>import com.intellij.psi.PsiClass;
<ide> import com.intellij.psi.PsiFile;
<del>import com.intellij.psi.PsiClass;
<ide>
<ide> /**
<ide> * @author dsl
<ide>
<ide> protected PsiClass getTargetClass(Editor editor, PsiFile file) {
<ide> final PsiClass targetClass = super.getTargetClass(editor, file);
<del> if (targetClass == null || targetClass.isEnum()) return null;
<add> if (targetClass == null || targetClass instanceof PsiAnonymousClass ||
<add> targetClass.isEnum()) return null;
<ide> return targetClass;
<ide> }
<ide> } |
|
Java | apache-2.0 | 2448875a6ad92a7c4fc62c65a82ac44d326412a9 | 0 | asaph/Handy-URI-Templates,asaph/Handy-URI-Templates | /*
*
*
*/
package com.damnhandy.uri.template;
import java.util.LinkedHashMap;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
/**
* A TestMultipleOperators.
*
* @author <a href="[email protected]">Ryan J. McDonough</a>
* @version $Revision: 1.1 $
*/
public class TestMultipleOperators
{
private static final Map<String, Object> VALUES;
static
{
VALUES = new LinkedHashMap<String, Object>();
VALUES.put("group_id", "12345");
VALUES.put("first_name", "John");
VALUES.put("item_id", "yu780");
VALUES.put("page", "5");
VALUES.put("lang", "en");
VALUES.put("format", "json");
VALUES.put("q", "URI Templates");
}
@Test
public void testMultiplePathOperators()
{
UriTemplate t = UriTemplate.fromTemplate("/base{/group_id,id}/pages{/page,lang}{?format,q}");
String uri = t.expand(VALUES);
Assert.assertEquals("/base/12345/pages/5/en?format=json&q=URI%20Templates", uri);
}
}
| src/test/java/com/damnhandy/uri/template/TestMultipleOperators.java | /*
*
*
*/
package com.damnhandy.uri.template;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
/**
* A TestMultipleOperators.
*
* @author <a href="[email protected]">Ryan J. McDonough</a>
* @version $Revision: 1.1 $
*/
public class TestMultipleOperators
{
private static final Map<String, Object> VALUES;
static
{
VALUES = new LinkedHashMap<String, Object>();
VALUES.put("group_id", "12345");
VALUES.put("first_name", "John");
VALUES.put("item_id", "yu780");
VALUES.put("page", "5");
VALUES.put("lang", "en");
VALUES.put("format", "json");
VALUES.put("q", "URI Templates");
}
@Test
public void testMultiplePathOperators()
{
String expression = "/base{/group_id,id}/pages{/page,lang}{?format,q}";
UriTemplate t = UriTemplate.fromExpression(expression);
String uri = t.expand(VALUES);
System.out.println(uri);
}
}
| Modified assertion
| src/test/java/com/damnhandy/uri/template/TestMultipleOperators.java | Modified assertion | <ide><path>rc/test/java/com/damnhandy/uri/template/TestMultipleOperators.java
<ide>
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Map;
<add>
<add>import junit.framework.Assert;
<ide>
<ide> import org.junit.Test;
<ide>
<ide> @Test
<ide> public void testMultiplePathOperators()
<ide> {
<del> String expression = "/base{/group_id,id}/pages{/page,lang}{?format,q}";
<del> UriTemplate t = UriTemplate.fromExpression(expression);
<add> UriTemplate t = UriTemplate.fromTemplate("/base{/group_id,id}/pages{/page,lang}{?format,q}");
<ide> String uri = t.expand(VALUES);
<del> System.out.println(uri);
<add> Assert.assertEquals("/base/12345/pages/5/en?format=json&q=URI%20Templates", uri);
<add>
<add>
<ide> }
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java' did not match any file(s) known to git
| ac41a8f1c5dc615e3da70f5970b1c255b4318907 | 1 | alibaba/fastjson,alibaba/fastjson,alibaba/fastjson,alibaba/fastjson | package com.alibaba.json.bvt.issue_1100;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wenshao on 19/04/2017.
*/
public class Issue1151 extends TestCase {
public void test_for_issue() throws Exception {
A a = new A();
a.list.add(new C(1001));
a.list.add(new C(1002));
String json = JSON.toJSONString(a, SerializerFeature.NotWriteRootClassName, SerializerFeature.WriteClassName);
assertEquals("{\"list\":[{\"@type\":\"com.alibaba.json.bvt.issue_1100.Issue1151$C\",\"id\":1001},{\"@type\":\"com.alibaba.json.bvt.issue_1100.Issue1151$C\",\"id\":1002}]}", json);
A a2 = JSON.parseObject(json, A.class);
assertSame(a2.list.get(0).getClass(), C.class);
}
public static class A {
public List<B> list = new ArrayList<B>();
}
public static interface B {
}
public static class C implements B {
public int id;
public C() {
}
public C(int id) {
this.id = id;
}
}
}
| src/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java | add testcase for issue #1151
| src/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java | add testcase for issue #1151 | <ide><path>rc/test/java/com/alibaba/json/bvt/issue_1100/Issue1151.java
<add>package com.alibaba.json.bvt.issue_1100;
<add>
<add>import com.alibaba.fastjson.JSON;
<add>import com.alibaba.fastjson.serializer.SerializerFeature;
<add>import junit.framework.TestCase;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>/**
<add> * Created by wenshao on 19/04/2017.
<add> */
<add>public class Issue1151 extends TestCase {
<add> public void test_for_issue() throws Exception {
<add> A a = new A();
<add> a.list.add(new C(1001));
<add> a.list.add(new C(1002));
<add>
<add> String json = JSON.toJSONString(a, SerializerFeature.NotWriteRootClassName, SerializerFeature.WriteClassName);
<add> assertEquals("{\"list\":[{\"@type\":\"com.alibaba.json.bvt.issue_1100.Issue1151$C\",\"id\":1001},{\"@type\":\"com.alibaba.json.bvt.issue_1100.Issue1151$C\",\"id\":1002}]}", json);
<add>
<add> A a2 = JSON.parseObject(json, A.class);
<add> assertSame(a2.list.get(0).getClass(), C.class);
<add> }
<add>
<add> public static class A {
<add> public List<B> list = new ArrayList<B>();
<add> }
<add>
<add> public static interface B {
<add>
<add> }
<add>
<add> public static class C implements B {
<add> public int id;
<add> public C() {
<add>
<add> }
<add>
<add> public C(int id) {
<add> this.id = id;
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | a32bb602774b1c8125f95afb6c8055bb8c7c3e7b | 0 | yukezhu/LifeGameSim,yukezhu/LifeGameSim,yukezhu/LifeGameSim,yukezhu/LifeGameSim | package ca.sfu.client;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import ca.sfu.cmpt431.facility.Board;
import ca.sfu.cmpt431.facility.BoardOperation;
import ca.sfu.cmpt431.facility.Border;
import ca.sfu.cmpt431.facility.Comrade;
import ca.sfu.cmpt431.facility.Neighbour;
import ca.sfu.cmpt431.facility.Outfits;
import ca.sfu.cmpt431.message.Message;
import ca.sfu.cmpt431.message.MessageCodeDictionary;
import ca.sfu.cmpt431.message.join.JoinOutfitsMsg;
import ca.sfu.cmpt431.message.join.JoinRequestMsg;
import ca.sfu.cmpt431.message.join.JoinSplitMsg;
import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg;
import ca.sfu.cmpt431.message.regular.RegularBorderMsg;
import ca.sfu.cmpt431.message.regular.RegularConfirmMsg;
import ca.sfu.cmpt431.message.regular.RegularUpdateNeighbourMsg;
import ca.sfu.network.MessageReceiver;
import ca.sfu.network.MessageSender;
public class Client {
private static final int SERVER_PORT = 6560;
private static final String SERVER_IP = "142.58.35.62";
private Comrade server;
private int myPort;
private String myIp;
private MessageReceiver Receiver;
private RegularConfirmMsg myConfirmMessage;
private int status;
private Outfits outfit;
private int neiUpdCount;
public boolean[] up ;
public boolean[] down;
public boolean[] left;
public boolean[] right;
public boolean upperLeft;
public boolean upperRight;
public boolean lowerLeft;
public boolean lowerRight;
private int borderCount = 0;
public Client() {
while(true){
Random r = new Random();
myPort = r.nextInt(55535)+10000;
try{
System.out.println("trying port " + myPort);
Receiver = new MessageReceiver(myPort);
System.out.println("port " + myPort + "is ok");
break;
}
catch(Exception e){
System.out.println("port " + myPort + "is occupied");
}
}
}
public void startClient(String ip) throws IOException, InterruptedException {
myIp = ip;
MessageSender svsdr = new MessageSender(SERVER_IP, SERVER_PORT);
server = new Comrade(MessageCodeDictionary.ID_SERVER, SERVER_PORT, SERVER_IP, svsdr);
JoinRequestMsg Request = new JoinRequestMsg(myPort);
server.sender.sendMsg(Request);
status = 1;
while(true){
if(!Receiver.isEmpty()){
System.out.println("status :" + status);
Message msg = (Message) Receiver.getNextMessageWithIp().extracMessage();
switch(status) {
// case 0:
// server.sender.sendMsg(new RegularConfirmMsg(-1));
// status = 1;
// break;
case 1:
repairOutfit((JoinOutfitsMsg) msg);
sendNeiUpdMsg();
if(neiUpdCount > 0)
status = 2;
else
status = 3;
break;
case 2:
neiUpdCount--;
if(neiUpdCount <= 0){
server.sender.sendMsg(myConfirmMessage);
status = 3;
}
break;
case 3:
int msgType = msg.getMessageCode();
if(msgType == MessageCodeDictionary.REGULAR_NEXTCLOCK) {
sendBorderToNeighbours();
if(isBorderMessageComplete())
computeAndReport();
else
status = 4;
}
else if (msgType == MessageCodeDictionary.REGULAR_UPDATE_NEIGHBOUR)
handleNeighbourUpdate((RegularUpdateNeighbourMsg)msg);
else if (msgType == MessageCodeDictionary.JOIN_SPLIT) {
handleSplit((JoinSplitMsg) msg);
status = 5;
}
else if (msgType == MessageCodeDictionary.REGULAR_BORDER_EXCHANGE)
handleBorderMessage((RegularBorderMsg) msg);
break;
case 4:
handleBorderMessage((RegularBorderMsg) msg);
if(isBorderMessageComplete()) {
computeAndReport();
status = 3;
}
break;
case 5:
if(msg.getMessageCode() != MessageCodeDictionary.REGULAR_CONFIRM){
System.out.println("type error, expect confirm message");
}
else
server.sender.sendMsg(myConfirmMessage);
status = 3;
break;
default:
System.out.println("Received unexpectd message.");
break;
}
}
}
}
private void repairOutfit(JoinOutfitsMsg msg) throws IOException {
System.out.println("received outfit");
outfit = msg.yourOutfits;
myConfirmMessage = new RegularConfirmMsg(outfit.myId);
if(outfit.pair == null){
server.sender.sendMsg(myConfirmMessage);
}
else {
outfit.pair.sender = new MessageSender(outfit.pair.ip, outfit.pair.port);
outfit.pair.sender.sendMsg(myConfirmMessage);
}
for(Neighbour nei: outfit.neighbour) {
if(nei.comrade.id == outfit.pair.id)
nei.comrade.sender = outfit.pair.sender;
else {
nei.comrade.sender = new MessageSender(nei.comrade.ip, nei.comrade.port);
ArrayList<Integer> mypos = (ArrayList<Integer>) ClientHelper.ClientNeighbor(nei.position);
nei.comrade.sender.sendMsg(
new RegularUpdateNeighbourMsg(outfit.myId, mypos, myPort, myIp));
}
}
up = new boolean[outfit.myBoard.width];
down = new boolean[outfit.myBoard.width];
left = new boolean[outfit.myBoard.height];
right = new boolean[outfit.myBoard.height];
}
private void sendNeiUpdMsg() throws IOException {
neiUpdCount = 0;
for(Neighbour nei: outfit.neighbour)
if(nei.comrade.id != outfit.pair.id) {
nei.comrade.sender.sendMsg(new RegularUpdateNeighbourMsg(outfit.myId,
(ArrayList<Integer>) ClientHelper.ClientNeighbor(nei.position), myPort, myIp));
neiUpdCount++;
}
}
private void sendBorderToNeighbours() throws IOException {
int neighborCount = outfit.neighbour.size();
Border sendborder;
for(int j = 0; j < neighborCount; j++)
{
sendborder = new Border();
sendborder.bits = getborder(outfit.neighbour.get(j).position);
RegularBorderMsg sendbordermsg = new RegularBorderMsg(outfit.myId, sendborder);
outfit.neighbour.get(j).comrade.sender.sendMsg(sendbordermsg);
}
}
private void handleNeighbourUpdate(RegularUpdateNeighbourMsg msg) throws IOException {
boolean isOldFriend = false;
for(Neighbour nei: outfit.neighbour){
if(nei.comrade.id == msg.getClientId()) {
nei.position.clear();
for(Integer q: msg.pos) nei.position.add(q);
isOldFriend = true;
}
else {
for (Integer p: nei.position){
for(Integer q: msg.pos)
if(p == q) nei.position.remove(q);
}
if(nei.position.size() == 0){
nei.comrade.sender.close();
outfit.neighbour.remove(nei);
}
}
}
if(!isOldFriend) {
Neighbour newnei = new Neighbour(msg.pos,
new Comrade(msg.getClientId(), msg.port, msg.ip, new MessageSender(msg.ip, msg.port)));
outfit.neighbour.add(newnei);
}
}
private void handleSplit(JoinSplitMsg msg) throws IOException {
List<Board> boards;
Outfits pout = new Outfits(msg.newcomerId, outfit.nextClock, 0, 0, null);
ArrayList<Neighbour> pnei = new ArrayList<Neighbour>();
for(Neighbour tn: outfit.neighbour)
pnei.add(new Neighbour(
new ArrayList<Integer>(tn.position),
new Comrade(tn.comrade.id, tn.comrade.port, tn.comrade.ip, null)));
pout.neighbour = pnei;
Neighbour [] pn = new Neighbour[12];
for(int i = 0; i < 12; i++)
pn[i] = findNeiWithPos(pout, i);
Neighbour [] n = new Neighbour[12];
for(int i = 0; i < 12; i++)
n[i] = findNeiWithPos(outfit, i);
ArrayList<Integer> tmp = new ArrayList<Integer>();
outfit.pair = new Comrade(msg.newcomerId, msg.newcomerPort, msg.newcomerIp,
new MessageSender(msg.newcomerIp, msg.newcomerPort));
if (msg.splitMode == MessageCodeDictionary.SPLIT_MODE_VERTICAL) {
boards = BoardOperation.VerticalCut(outfit.myBoard);
Board left, right;
left = boards.get(0);
right = boards.get(1);
outfit.myBoard = left;
pout.top = outfit.top;
pout.left = outfit.left + left.width;
pout.myBoard = right;
pout.pair = new Comrade(outfit.myId, myPort, myIp, null);
deletePos(pout, pn[10], 10);
deletePos(pout, pn[11], 11);
tmp = new ArrayList<Integer>();
tmp.add(10);
tmp.add(11);
pout.neighbour.add(
new Neighbour(tmp, new Comrade(outfit.myId, myPort, myIp, null)));
deletePos(outfit, n[4], 4);
deletePos(outfit, n[5], 5);
tmp = new ArrayList<Integer>();
tmp.add(4);
tmp.add(5);
outfit.neighbour.add(
new Neighbour(tmp, outfit.pair));
if(n[1] == n[2]) {
if(n[0] == n[1]) {
addPos(n[1], 3, false);
deletePos(outfit, n[3], 3);
}
else if(n[2] == n[3]) {
addPos(pn[1], 0, true);
deletePos(pout, pn[0], 0);
}else {
addPos(n[1], 3, false);
deletePos(outfit, n[3], 3);
addPos(pn[1], 0, true);
deletePos(pout, pn[0], 0);
}
}else {
addPos(n[1], 2, false);
addPos(n[2], 3, false);
deletePos(outfit, n[2], 2);
deletePos(outfit, n[3], 3);
addPos(pn[2], 1, true);
addPos(pn[1], 0, true);
deletePos(outfit, pn[1], 1);
deletePos(outfit, pn[0], 0);
}
if(n[8] == n[7]) {
if(n[9] == n[8]) {
addPos(n[8], 6, true);
deletePos(outfit, n[6], 6);
}
else if(n[7] == n[6]) {
addPos(pn[8], 9, false);
deletePos(pout, pn[9], 9);
}else {
addPos(n[8], 6, true);
deletePos(outfit, n[6], 6);
addPos(pn[8], 9, false);
deletePos(pout, pn[9], 9);
}
}else {
addPos(n[8], 7, true);
addPos(n[7], 6, true);
deletePos(outfit, n[7], 7);
deletePos(outfit, n[6], 6);
addPos(pn[7], 8, false);
addPos(pn[8], 9, false);
deletePos(outfit, pn[8], 8);
deletePos(outfit, pn[9], 9);
}
}
else {
boards = BoardOperation.HorizontalCut(outfit.myBoard);
Board top, bottom;
top = boards.get(0);
bottom = boards.get(1);
outfit.myBoard = top;
pout.top = outfit.top + top.height;
pout.left = outfit.left;
pout.myBoard = bottom;
pout.pair = new Comrade(outfit.myId, myPort, myIp, null);
deletePos(pout, pn[1], 1);
deletePos(pout, pn[2], 2);
tmp = new ArrayList<Integer>();
tmp.add(1);
tmp.add(2);
pout.neighbour.add(
new Neighbour(tmp, new Comrade(outfit.myId, myPort, myIp, null)));
deletePos(outfit, n[7], 7);
deletePos(outfit, n[8], 8);
tmp = new ArrayList<Integer>();
tmp.add(7);
tmp.add(8);
outfit.neighbour.add(
new Neighbour(tmp, outfit.pair));
if(n[4] == n[5]) {
if(n[3] == n[4]) {
addPos(n[4], 6, false);
deletePos(outfit, n[6], 6);
}
else if(n[5] == n[6]) {
addPos(pn[4], 3, true);
deletePos(pout, pn[3], 3);
}else {
addPos(n[4], 6, false);
deletePos(outfit, n[6], 6);
addPos(pn[4], 3, true);
deletePos(pout, pn[3], 3);
}
}else {
addPos(n[4], 5, false);
addPos(n[5], 6, false);
deletePos(outfit, n[5], 5);
deletePos(outfit, n[6], 6);
addPos(pn[5], 4, true);
addPos(pn[4], 3, true);
deletePos(outfit, pn[4], 4);
deletePos(outfit, pn[3], 3);
}
if(n[11] == n[10]) {
if(n[0] == n[11]) {
addPos(n[11], 9, true);
deletePos(outfit, n[9], 9);
}
else if(n[10] == n[9]) {
addPos(pn[11], 0, false);
deletePos(pout, pn[0], 0);
}else {
addPos(n[11], 9, true);
deletePos(outfit, n[9], 9);
addPos(pn[11], 0, false);
deletePos(pout, pn[0], 0);
}
}else {
addPos(n[11], 10, true);
addPos(n[10], 9, true);
deletePos(outfit, n[10], 10);
deletePos(outfit, n[9], 9);
addPos(pn[10], 11, false);
addPos(pn[11], 0, false);
deletePos(outfit, pn[11], 11);
deletePos(outfit, pn[0], 0);
}
}
System.out.println("My outfit after spliting:");
outiftInfo(outfit);
System.out.println("Pair's outfit after spliting:");
outiftInfo(pout);
outfit.pair.sender.sendMsg(new JoinOutfitsMsg(outfit.myId, myPort, pout));
}
private void handleBorderMessage(RegularBorderMsg msg) {
int cid = msg.getClientId();
int nei_id = -1;
borderCount++;
for(int i=0; i<outfit.neighbour.size(); i++){
if(outfit.neighbour.get(i).comrade.id == cid){
nei_id = i;
break;
}
}
//merge and update the global border array/variable
System.out.println(outfit.left);
for(Neighbour nei: outfit.neighbour){
System.out.println("neighborID:" + nei.comrade.id);
System.out.println("border size:" + msg.boarder.bits.length);
for(Integer pos: nei.position)
System.out.print("neighborPos:" + pos + " ");
System.out.println(" " );
}
mergeBorder(msg.boarder.bits, outfit.neighbour.get(nei_id).position);
}
private boolean isBorderMessageComplete() {
if(borderCount == outfit.neighbour.size())
return true;
return false;
}
private void computeAndReport() throws IOException {
BoardOperation.NextMoment(outfit.myBoard, null, null, null, null, false, false, false, false);
server.sender.sendMsg(new RegularBoardReturnMsg(outfit.myId, outfit.top, outfit.left, outfit.myBoard));
borderCount = 0;
}
private void deletePos(Outfits out, Neighbour nei, Integer pos) {
if(nei == null)
return ;
nei.position.remove(pos);
if(nei.position.size() == 0) {
if(nei.comrade.sender != null){
nei.comrade.sender.close();
out.neighbour.remove(nei);
}
}
}
private void addPos(Neighbour nei, Integer pos, boolean front) {
if(nei == null)
return;
if(front)
nei.position.add(0, pos);
else
nei.position.add(pos);
}
private void outiftInfo(Outfits out) {
System.out.println("Id: " + out.myId);
System.out.println("Clk: " + out.nextClock);
System.out.println("Top: " + out.top);
System.out.println("Left: " + out.left);
System.out.println("Width:" + out.myBoard.width);
System.out.println("Heig: " + out.myBoard.height);
System.out.println("Neighbour size: " + out.neighbour.size());
int cnt = 1;
for(Neighbour nei: out.neighbour){
System.out.print("Nei #" + cnt++ + " Id: " + nei.comrade.id +" Pos:");
for(Integer in: nei.position)
System.out.print(" " + in);
System.out.println("");
}
System.out.println("Pair Id: " + out.pair.id);
}
private Neighbour findNeiWithPos(Outfits out, int pos) {
for(Neighbour nei: out.neighbour)
for(Integer i: nei.position)
if(i == pos)
return nei;
return null;
}
protected boolean[] getborder(List<Integer> array){
Board b = outfit.myBoard;
ArrayList<Boolean> al = new ArrayList<Boolean>();
int j;
for(int i=0; i<array.size(); i++){
int a = array.get(i);
switch(a+1){
case 1:
if(al.size()!=0)
break;
al.add(b.bitmap[0][0]);
break;
case 2:
j = 0;
//if it is 1 already
if(al.size() != 0)
j = 1;
for(; j<=b.width/2; j++)
al.add(b.bitmap[0][j]);
break;
case 3:
//if it is 2 already
j = b.width/2-1;
if(al.size() != 0)
j=j+2;
for(; j<b.width; j++)
al.add(b.bitmap[0][j]);
break;
case 4:
//if it is 3 already
if(al.size() != 0)
break;
al.add(b.bitmap[0][b.width-1]);
break;
case 5:
j = 0;
//if it is 4 already
if(al.size()!=0)
j=1;
for(; j<=b.height/2; j++)
al.add(b.bitmap[j][b.width-1]);
break;
case 6:
j = b.height/2-1;
//if it is 5 already
if(al.size()!=0)
j=j+2;
for(; j<b.height; j++)
al.add(b.bitmap[j][b.width-1]);
break;
case 7:
//if it is 6 already
if(al.size()!=0)
break;
al.add(b.bitmap[b.height-1][b.width-1]);
break;
case 8:
j = b.width - 1;
//if it is 7 already
if(al.size()!=0)
j--;
for(; j>=b.width/2-1; j--)
al.add(b.bitmap[b.height-1][j]);
break;
case 9:
j = b.width/2;
if(al.size()!=0)
j=j-2;
for(; j>=0; j--)
al.add(b.bitmap[b.height-1][j]);
break;
case 10:
if(al.size()!=0)
break;
al.add(b.bitmap[b.height-1][0]);
break;
case 11:
j = b.height-1;
if(al.size()!=0)
j--;
for(; j>=b.height/2-1; j--)
al.add(b.bitmap[j][0]);
break;
case 12:
j = b.height/2;
if(al.size()!=0)
j=j-2;
for(; j>=0; j--)
al.add(b.bitmap[j][0]);
break;
}
}
boolean[] a = new boolean[al.size()];
for(int k=0; k<a.length; k++){
a[k]=(boolean)al.get(k);
}
return a;
}
//comment
protected void mergeBorder(boolean[] aa, List<Integer> array1){
ArrayList<Boolean> tmp = new ArrayList<Boolean>();
Board b = outfit.myBoard;
for(int k=0; k<aa.length; k++)
tmp.add(aa[k]);
for(int i=0; i<array1.size(); i++){
if(tmp.size()==0)
break;
int num = array1.get(i);
switch(num+1){
case 1:
upperLeft = (boolean) tmp.get(0);
tmp.remove(0);
break;
case 2:
for(int p=0; p<b.width/2; p++){
up[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 3:
for(int p=b.width/2; p<b.width; p++){
up[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 4:
upperRight = (boolean)tmp.get(0);
tmp.remove(0);
break;
case 5:
for(int p=0; p<b.height/2; p++){
right[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 6:
for(int p=b.height/2; p<b.height; p++){
right[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 7:
lowerRight = (boolean)tmp.get(0);
tmp.remove(0);
break;
case 8:
for(int p=b.width-1; p>=b.width/2; p--){
down[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 9:
for(int p=b.width/2-1; p>=0; p--){
down[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 10:
lowerLeft = (boolean)tmp.get(0);
tmp.remove(0);
break;
case 11:
for(int p=b.height-1; p>=b.height/2; p--){
left[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 12:
for(int p=b.height/2-1; p>=0; p--){
left[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
}
}
}
} | GameOfLifeClient/src/ca/sfu/client/Client.java | package ca.sfu.client;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import ca.sfu.cmpt431.facility.Board;
import ca.sfu.cmpt431.facility.BoardOperation;
import ca.sfu.cmpt431.facility.Border;
import ca.sfu.cmpt431.facility.Comrade;
import ca.sfu.cmpt431.facility.Neighbour;
import ca.sfu.cmpt431.facility.Outfits;
import ca.sfu.cmpt431.message.Message;
import ca.sfu.cmpt431.message.MessageCodeDictionary;
import ca.sfu.cmpt431.message.join.JoinOutfitsMsg;
import ca.sfu.cmpt431.message.join.JoinRequestMsg;
import ca.sfu.cmpt431.message.join.JoinSplitMsg;
import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg;
import ca.sfu.cmpt431.message.regular.RegularBorderMsg;
import ca.sfu.cmpt431.message.regular.RegularConfirmMsg;
import ca.sfu.cmpt431.message.regular.RegularUpdateNeighbourMsg;
import ca.sfu.network.MessageReceiver;
import ca.sfu.network.MessageSender;
public class Client {
private static final int SERVER_PORT = 6560;
private static final String SERVER_IP = "142.58.35.62";
private Comrade server;
private int myPort;
private String myIp;
private MessageReceiver Receiver;
private RegularConfirmMsg myConfirmMessage;
private int status;
private Outfits outfit;
private int neiUpdCount;
public boolean[] up ;
public boolean[] down;
public boolean[] left;
public boolean[] right;
public boolean upperLeft;
public boolean upperRight;
public boolean lowerLeft;
public boolean lowerRight;
private int borderCount = 0;
public Client() {
while(true){
Random r = new Random();
myPort = r.nextInt(55535)+10000;
try{
System.out.println("trying port " + myPort);
Receiver = new MessageReceiver(myPort);
System.out.println("port " + myPort + "is ok");
break;
}
catch(Exception e){
System.out.println("port " + myPort + "is occupied");
}
}
}
public void startClient(String ip) throws IOException, InterruptedException {
myIp = ip;
MessageSender svsdr = new MessageSender(SERVER_IP, SERVER_PORT);
server = new Comrade(MessageCodeDictionary.ID_SERVER, SERVER_PORT, SERVER_IP, svsdr);
JoinRequestMsg Request = new JoinRequestMsg(myPort);
server.sender.sendMsg(Request);
status = 1;
while(true){
if(!Receiver.isEmpty()){
System.out.println("status :" + status);
Message msg = (Message) Receiver.getNextMessageWithIp().extracMessage();
switch(status) {
// case 0:
// server.sender.sendMsg(new RegularConfirmMsg(-1));
// status = 1;
// break;
case 1:
repairOutfit((JoinOutfitsMsg) msg);
sendNeiUpdMsg();
if(neiUpdCount > 0)
status = 2;
else
status = 3;
break;
case 2:
neiUpdCount--;
if(neiUpdCount <= 0){
server.sender.sendMsg(myConfirmMessage);
status = 3;
}
break;
case 3:
int msgType = msg.getMessageCode();
if(msgType == MessageCodeDictionary.REGULAR_NEXTCLOCK) {
sendBorderToNeighbours();
if(isBorderMessageComplete())
computeAndReport();
else
status = 4;
}
else if (msgType == MessageCodeDictionary.REGULAR_UPDATE_NEIGHBOUR)
handleNeighbourUpdate((RegularUpdateNeighbourMsg)msg);
else if (msgType == MessageCodeDictionary.JOIN_SPLIT) {
handleSplit((JoinSplitMsg) msg);
status = 5;
}
else if (msgType == MessageCodeDictionary.REGULAR_BORDER_EXCHANGE)
handleBorderMessage((RegularBorderMsg) msg);
break;
case 4:
handleBorderMessage((RegularBorderMsg) msg);
if(isBorderMessageComplete()) {
computeAndReport();
status = 3;
}
break;
case 5:
if(msg.getMessageCode() != MessageCodeDictionary.REGULAR_CONFIRM){
System.out.println("type error, expect confirm message");
}
else
server.sender.sendMsg(myConfirmMessage);
status = 3;
break;
default:
System.out.println("Received unexpectd message.");
break;
}
}
}
}
private void repairOutfit(JoinOutfitsMsg msg) throws IOException {
System.out.println("received outfit");
outfit = msg.yourOutfits;
myConfirmMessage = new RegularConfirmMsg(outfit.myId);
if(outfit.pair == null){
server.sender.sendMsg(myConfirmMessage);
}
else {
outfit.pair.sender = new MessageSender(outfit.pair.ip, outfit.pair.port);
outfit.pair.sender.sendMsg(myConfirmMessage);
}
for(Neighbour nei: outfit.neighbour) {
if(nei.comrade.id == outfit.pair.id)
nei.comrade.sender = outfit.pair.sender;
else {
nei.comrade.sender = new MessageSender(nei.comrade.ip, nei.comrade.port);
ArrayList<Integer> mypos = (ArrayList<Integer>) ClientHelper.ClientNeighbor(nei.position);
nei.comrade.sender.sendMsg(
new RegularUpdateNeighbourMsg(outfit.myId, mypos, myPort, myIp));
}
}
up = new boolean[outfit.myBoard.width];
down = new boolean[outfit.myBoard.width];
left = new boolean[outfit.myBoard.height];
right = new boolean[outfit.myBoard.height];
}
private void sendNeiUpdMsg() throws IOException {
neiUpdCount = 0;
for(Neighbour nei: outfit.neighbour)
if(nei.comrade.id != outfit.pair.id) {
nei.comrade.sender.sendMsg(new RegularUpdateNeighbourMsg(outfit.myId,
(ArrayList<Integer>) ClientHelper.ClientNeighbor(nei.position), myPort, myIp));
neiUpdCount++;
}
}
private void sendBorderToNeighbours() throws IOException {
int neighborCount = outfit.neighbour.size();
Border sendborder;
for(int j = 0; j < neighborCount; j++)
{
sendborder = new Border();
sendborder.bits = getborder(outfit.neighbour.get(j).position);
RegularBorderMsg sendbordermsg = new RegularBorderMsg(outfit.myId, sendborder);
outfit.neighbour.get(j).comrade.sender.sendMsg(sendbordermsg);
}
}
private void handleNeighbourUpdate(RegularUpdateNeighbourMsg msg) throws IOException {
boolean isOldFriend = false;
for(Neighbour nei: outfit.neighbour){
if(nei.comrade.id == msg.getClientId()) {
nei.position.clear();
for(Integer q: msg.pos) nei.position.add(q);
isOldFriend = true;
}
else {
for (Integer p: nei.position){
for(Integer q: msg.pos)
if(p == q) nei.position.remove(q);
}
if(nei.position.size() == 0){
nei.comrade.sender.close();
outfit.neighbour.remove(nei);
}
}
}
if(!isOldFriend) {
Neighbour newnei = new Neighbour(msg.pos,
new Comrade(msg.getClientId(), msg.port, msg.ip, new MessageSender(msg.ip, msg.port)));
outfit.neighbour.add(newnei);
}
}
private void handleSplit(JoinSplitMsg msg) throws IOException {
List<Board> boards;
Outfits pout = new Outfits(msg.newcomerId, outfit.nextClock, 0, 0, null);
ArrayList<Neighbour> pnei = new ArrayList<Neighbour>();
for(Neighbour tn: outfit.neighbour)
pnei.add(new Neighbour(
new ArrayList<Integer>(tn.position),
new Comrade(tn.comrade.id, tn.comrade.port, tn.comrade.ip, null)));
pout.neighbour = pnei;
Neighbour [] pn = new Neighbour[12];
for(int i = 0; i < 12; i++)
pn[i] = findNeiWithPos(pout, i);
Neighbour [] n = new Neighbour[12];
for(int i = 0; i < 12; i++)
n[i] = findNeiWithPos(outfit, i);
ArrayList<Integer> tmp = new ArrayList<Integer>();
outfit.pair = new Comrade(msg.newcomerId, msg.newcomerPort, msg.newcomerIp,
new MessageSender(msg.newcomerIp, msg.newcomerPort));
if (msg.splitMode == MessageCodeDictionary.SPLIT_MODE_VERTICAL) {
boards = BoardOperation.VerticalCut(outfit.myBoard);
Board left, right;
left = boards.get(0);
right = boards.get(1);
outfit.myBoard = left;
pout.top = outfit.top;
pout.left = outfit.left + left.width;
pout.myBoard = right;
pout.pair = new Comrade(outfit.myId, myPort, myIp, null);
deletePos(pout, pn[10], 10);
deletePos(pout, pn[11], 11);
tmp = new ArrayList<Integer>();
tmp.add(10);
tmp.add(11);
pout.neighbour.add(
new Neighbour(tmp, new Comrade(outfit.myId, myPort, myIp, null)));
deletePos(outfit, n[4], 4);
deletePos(outfit, n[5], 5);
tmp = new ArrayList<Integer>();
tmp.add(4);
tmp.add(5);
outfit.neighbour.add(
new Neighbour(tmp, outfit.pair));
if(n[1] == n[2]) {
if(n[0] == n[1]) {
addPos(n[1], 3, false);
deletePos(outfit, n[3], 3);
}
else if(n[2] == n[3]) {
addPos(pn[1], 0, true);
deletePos(pout, pn[0], 0);
}else {
addPos(n[1], 3, false);
deletePos(outfit, n[3], 3);
addPos(pn[1], 0, true);
deletePos(pout, pn[0], 0);
}
}else {
addPos(n[1], 2, false);
addPos(n[2], 3, false);
deletePos(outfit, n[2], 2);
deletePos(outfit, n[3], 3);
addPos(pn[2], 1, true);
addPos(pn[1], 0, true);
deletePos(outfit, pn[1], 1);
deletePos(outfit, pn[0], 0);
}
if(n[8] == n[7]) {
if(n[9] == n[8]) {
addPos(n[8], 6, true);
deletePos(outfit, n[6], 6);
}
else if(n[7] == n[6]) {
addPos(pn[8], 9, false);
deletePos(pout, pn[9], 9);
}else {
addPos(n[8], 6, true);
deletePos(outfit, n[6], 6);
addPos(pn[8], 9, false);
deletePos(pout, pn[9], 9);
}
}else {
addPos(n[8], 7, true);
addPos(n[7], 6, true);
deletePos(outfit, n[7], 7);
deletePos(outfit, n[6], 6);
addPos(pn[7], 8, false);
addPos(pn[8], 9, false);
deletePos(outfit, pn[8], 8);
deletePos(outfit, pn[9], 9);
}
}
else {
boards = BoardOperation.HorizontalCut(outfit.myBoard);
Board top, bottom;
top = boards.get(0);
bottom = boards.get(1);
outfit.myBoard = top;
pout.top = outfit.top + top.height;
pout.left = outfit.left;
pout.myBoard = bottom;
pout.pair = new Comrade(outfit.myId, myPort, myIp, null);
deletePos(pout, pn[1], 1);
deletePos(pout, pn[2], 2);
tmp = new ArrayList<Integer>();
tmp.add(1);
tmp.add(2);
pout.neighbour.add(
new Neighbour(tmp, new Comrade(outfit.myId, myPort, myIp, null)));
deletePos(outfit, n[7], 7);
deletePos(outfit, n[8], 8);
tmp = new ArrayList<Integer>();
tmp.add(7);
tmp.add(8);
outfit.neighbour.add(
new Neighbour(tmp, outfit.pair));
if(n[4] == n[5]) {
if(n[3] == n[4]) {
addPos(n[4], 6, false);
deletePos(outfit, n[6], 6);
}
else if(n[5] == n[6]) {
addPos(pn[4], 3, true);
deletePos(pout, pn[3], 3);
}else {
addPos(n[4], 6, false);
deletePos(outfit, n[6], 6);
addPos(pn[4], 3, true);
deletePos(pout, pn[3], 3);
}
}else {
addPos(n[4], 5, false);
addPos(n[5], 6, false);
deletePos(outfit, n[5], 5);
deletePos(outfit, n[6], 6);
addPos(pn[5], 4, true);
addPos(pn[4], 3, true);
deletePos(outfit, pn[4], 4);
deletePos(outfit, pn[3], 3);
}
if(n[11] == n[10]) {
if(n[0] == n[11]) {
addPos(n[11], 9, true);
deletePos(outfit, n[9], 9);
}
else if(n[10] == n[9]) {
addPos(pn[11], 0, false);
deletePos(pout, pn[0], 0);
}else {
addPos(n[11], 9, true);
deletePos(outfit, n[9], 9);
addPos(pn[11], 0, false);
deletePos(pout, pn[0], 0);
}
}else {
addPos(n[11], 10, true);
addPos(n[10], 9, true);
deletePos(outfit, n[10], 10);
deletePos(outfit, n[9], 9);
addPos(pn[10], 11, false);
addPos(pn[11], 0, false);
deletePos(outfit, pn[11], 11);
deletePos(outfit, pn[0], 0);
}
}
System.out.println("My outfit after spliting:");
outiftInfo(outfit);
System.out.println("Pair's outfit after spliting:");
outiftInfo(pout);
outfit.pair.sender.sendMsg(new JoinOutfitsMsg(outfit.myId, myPort, pout));
}
private void handleBorderMessage(RegularBorderMsg msg) {
int cid = msg.getClientId();
int nei_id = -1;
borderCount++;
for(int i=0; i<outfit.neighbour.size(); i++){
if(outfit.neighbour.get(i).comrade.id == cid){
nei_id = i;
break;
}
}
//merge and update the global border array/variable
System.out.println(outfit.left);
for(Neighbour nei: outfit.neighbour){
System.out.println("neighborID:" + nei.comrade.id);
System.out.println("border size:" + msg.boarder.bits.length);
for(Integer pos: nei.position)
System.out.print("neighborPos:" + pos + " ");
System.out.println(" " );
}
mergeBorder(msg.boarder.bits, outfit.neighbour.get(nei_id).position);
}
private boolean isBorderMessageComplete() {
if(borderCount == outfit.neighbour.size())
return true;
return false;
}
private void computeAndReport() throws IOException {
BoardOperation.NextMoment(outfit.myBoard, null, null, null, null, false, false, false, false);
server.sender.sendMsg(new RegularBoardReturnMsg(outfit.myId, outfit.top, outfit.left, outfit.myBoard));
BoardOperation.Print(outfit.myBoard);
borderCount = 0;
}
private void deletePos(Outfits out, Neighbour nei, Integer pos) {
if(nei == null)
return ;
nei.position.remove(pos);
if(nei.position.size() == 0) {
if(nei.comrade.sender != null){
nei.comrade.sender.close();
out.neighbour.remove(nei);
}
}
}
private void addPos(Neighbour nei, Integer pos, boolean front) {
if(nei == null)
return;
if(front)
nei.position.add(0, pos);
else
nei.position.add(pos);
}
private void outiftInfo(Outfits out) {
System.out.println("Id: " + out.myId);
System.out.println("Clk: " + out.nextClock);
System.out.println("Top: " + out.top);
System.out.println("Left: " + out.left);
System.out.println("Width:" + out.myBoard.width);
System.out.println("Heig: " + out.myBoard.height);
System.out.println("Neighbour size: " + out.neighbour.size());
int cnt = 1;
for(Neighbour nei: out.neighbour){
System.out.print("Nei #" + cnt++ + " Id: " + nei.comrade.id +" Pos:");
for(Integer in: nei.position)
System.out.print(" " + in);
System.out.println("");
}
System.out.println("Pair Id: " + out.pair.id);
}
private Neighbour findNeiWithPos(Outfits out, int pos) {
for(Neighbour nei: out.neighbour)
for(Integer i: nei.position)
if(i == pos)
return nei;
return null;
}
protected boolean[] getborder(List<Integer> array){
Board b = outfit.myBoard;
ArrayList<Boolean> al = new ArrayList<Boolean>();
int j;
for(int i=0; i<array.size(); i++){
int a = array.get(i);
switch(a+1){
case 1:
if(al.size()!=0)
break;
al.add(b.bitmap[0][0]);
break;
case 2:
j = 0;
//if it is 1 already
if(al.size() != 0)
j = 1;
for(; j<=b.width/2; j++)
al.add(b.bitmap[0][j]);
break;
case 3:
//if it is 2 already
j = b.width/2-1;
if(al.size() != 0)
j=j+2;
for(; j<b.width; j++)
al.add(b.bitmap[0][j]);
break;
case 4:
//if it is 3 already
if(al.size() != 0)
break;
al.add(b.bitmap[0][b.width-1]);
break;
case 5:
j = 0;
//if it is 4 already
if(al.size()!=0)
j=1;
for(; j<=b.height/2; j++)
al.add(b.bitmap[j][b.width-1]);
break;
case 6:
j = b.height/2-1;
//if it is 5 already
if(al.size()!=0)
j=j+2;
for(; j<b.height; j++)
al.add(b.bitmap[j][b.width-1]);
break;
case 7:
//if it is 6 already
if(al.size()!=0)
break;
al.add(b.bitmap[b.height-1][b.width-1]);
break;
case 8:
j = b.width - 1;
//if it is 7 already
if(al.size()!=0)
j--;
for(; j>=b.width/2-1; j--)
al.add(b.bitmap[b.height-1][j]);
break;
case 9:
j = b.width/2;
if(al.size()!=0)
j=j-2;
for(; j>=0; j--)
al.add(b.bitmap[b.height-1][j]);
break;
case 10:
if(al.size()!=0)
break;
al.add(b.bitmap[b.height-1][0]);
break;
case 11:
j = b.height-1;
if(al.size()!=0)
j--;
for(; j>=b.height/2-1; j--)
al.add(b.bitmap[j][0]);
break;
case 12:
j = b.height/2;
if(al.size()!=0)
j=j-2;
for(; j>=0; j--)
al.add(b.bitmap[j][0]);
break;
}
}
boolean[] a = new boolean[al.size()];
for(int k=0; k<a.length; k++){
a[k]=(boolean)al.get(k);
}
return a;
}
//comment
protected void mergeBorder(boolean[] aa, List<Integer> array1){
ArrayList<Boolean> tmp = new ArrayList<Boolean>();
Board b = outfit.myBoard;
for(int k=0; k<aa.length; k++)
tmp.add(aa[k]);
for(int i=0; i<array1.size(); i++){
if(tmp.size()==0)
break;
int num = array1.get(i);
switch(num+1){
case 1:
upperLeft = (boolean) tmp.get(0);
tmp.remove(0);
break;
case 2:
for(int p=0; p<b.width/2; p++){
up[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 3:
for(int p=b.width/2; p<b.width; p++){
up[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 4:
upperRight = (boolean)tmp.get(0);
tmp.remove(0);
break;
case 5:
for(int p=0; p<b.height/2; p++){
right[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 6:
for(int p=b.height/2; p<b.height; p++){
right[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 7:
lowerRight = (boolean)tmp.get(0);
tmp.remove(0);
break;
case 8:
for(int p=b.width-1; p>=b.width/2; p--){
down[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 9:
for(int p=b.width/2-1; p>=0; p--){
down[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 10:
lowerLeft = (boolean)tmp.get(0);
tmp.remove(0);
break;
case 11:
for(int p=b.height-1; p>=b.height/2; p--){
left[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
case 12:
for(int p=b.height/2-1; p>=0; p--){
left[p] = (boolean)tmp.get(0);
tmp.remove(0);
}
break;
}
}
}
} | client debug
| GameOfLifeClient/src/ca/sfu/client/Client.java | client debug | <ide><path>ameOfLifeClient/src/ca/sfu/client/Client.java
<ide> private void computeAndReport() throws IOException {
<ide> BoardOperation.NextMoment(outfit.myBoard, null, null, null, null, false, false, false, false);
<ide> server.sender.sendMsg(new RegularBoardReturnMsg(outfit.myId, outfit.top, outfit.left, outfit.myBoard));
<del> BoardOperation.Print(outfit.myBoard);
<ide> borderCount = 0;
<ide> }
<ide> |
|
Java | mit | aa8b27ecd9458a34c97a50c1834b330436cf3fbd | 0 | nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server | package fi.nls.oskari.wfs.extension;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.wfs.LayerProcessor;
import fi.nls.oskari.wfs.pojo.WFSLayerStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class UserLayerProcessor implements LayerProcessor {
private static final Logger LOG = LogFactory.getLogger(UserLayerProcessor.class);
private static final String USERLAYER_PREFIX = "userlayer_";
protected static Set<String> excludedProperties = new HashSet<String>();
static {
excludedProperties.add("property_json");
excludedProperties.add("uuid");
excludedProperties.add("user_layer_id");
excludedProperties.add("feature_id");
excludedProperties.add("created");
excludedProperties.add("updated");
excludedProperties.add("attention_text");
excludedProperties.add("id");
}
private ObjectMapper mapper = new ObjectMapper();
public boolean isProcessable(WFSLayerStore layer) {
return layer.getLayerId().startsWith(USERLAYER_PREFIX);
//return layer.getId() == PropertyUtil.getOptional("userlayer.baselayer.id", -1); //layer.getId() == -1, should be userlayer.baselayer.id (e.g. 3 or 10)
}
/**
* Parse features' property_json attribute and add parsed attributes to features
*/
public FeatureCollection<SimpleFeatureType, SimpleFeature> process(FeatureCollection<SimpleFeatureType, SimpleFeature> features, WFSLayerStore layer) {
DefaultFeatureCollection result = null;
SimpleFeatureBuilder builder = null;
FeatureIterator<SimpleFeature> iterator = features.features();
try {
while (iterator.hasNext()) {
SimpleFeature simpleFeature = iterator.next();
Map<String, Object> jsonMap = getUserlayerFields(simpleFeature);
// only for first feature to build new processed/parsed feature type
if (result == null) {
FeatureDef def = getFeatureDef(simpleFeature.getFeatureType(), layer, jsonMap, features.getID());
result = def.collection;
builder = def.builder;
}
//copy attribute values
//do not add excludedProperties
for (Property property : simpleFeature.getProperties()) {
if (!excludedProperties.contains(property.getName().getLocalPart())) {
builder.set(property.getName(), property.getValue());
}
}
// add new attribute values (from property_json)
for (Map.Entry<String, Object> attribute : jsonMap.entrySet()) {
builder.set(attribute.getKey(), attribute.getValue());
}
// buildFeature calls reset() internally so we are good to go for next round
result.add(builder.buildFeature(simpleFeature.getID()));
}
} catch (Exception ex) {
throw new ServiceRuntimeException("Userlayer processing failed", ex);
} finally {
iterator.close();
}
return result;
}
protected Map<String, Object> getUserlayerFields(SimpleFeature simpleFeature) throws IOException {
Property propertyJson = simpleFeature.getProperty("property_json");
return mapper.readValue(propertyJson.getValue().toString(),
new TypeReference<HashMap<String, Object>>() {});
}
protected FeatureDef getFeatureDef(SimpleFeatureType type, WFSLayerStore layer, Map<String, Object> jsonMap, String featuresetId) {
FeatureDef p = new FeatureDef();
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
typeBuilder.setName(type.getName());
typeBuilder.setNamespaceURI(layer.getFeatureNamespaceURI());
typeBuilder.setSRS(layer.getSRSName());
//copy feature's attributes to new feature type builder
//do not add excludedProperties
for (AttributeDescriptor desc : type.getAttributeDescriptors()) {
if (!excludedProperties.contains(desc.getLocalName())) {
typeBuilder.add(desc);
}
}
typeBuilder.setName(type.getName());
// add new parsed attributes from property_json to new type builder
for (Map.Entry<String, Object> attribute : jsonMap.entrySet()) {
typeBuilder.add(attribute.getKey(), attribute.getValue().getClass());
}
SimpleFeatureType parsedFeatureType = typeBuilder.buildFeatureType();
p.collection = new DefaultFeatureCollection(featuresetId, parsedFeatureType);
p.builder = new SimpleFeatureBuilder(parsedFeatureType);
return p;
}
class FeatureDef {
DefaultFeatureCollection collection;
SimpleFeatureBuilder builder;
}
} | servlet-transport/src/main/java/fi/nls/oskari/wfs/extension/UserLayerProcessor.java | package fi.nls.oskari.wfs.extension;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.wfs.LayerProcessor;
import fi.nls.oskari.wfs.pojo.WFSLayerStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class UserLayerProcessor implements LayerProcessor {
private static final Logger LOG = LogFactory.getLogger(UserLayerProcessor.class);
private static final String USERLAYER_PREFIX = "userlayer_";
protected static Set<String> excludedProperties = new HashSet<String>();
static {
excludedProperties.add("property_json");
excludedProperties.add("uuid");
excludedProperties.add("user_layer_id");
excludedProperties.add("feature_id");
excludedProperties.add("created");
excludedProperties.add("updated");
excludedProperties.add("attention_text");
}
private ObjectMapper mapper = new ObjectMapper();
public boolean isProcessable(WFSLayerStore layer) {
return layer.getLayerId().startsWith(USERLAYER_PREFIX);
//return layer.getId() == PropertyUtil.getOptional("userlayer.baselayer.id", -1); //layer.getId() == -1, should be userlayer.baselayer.id (e.g. 3 or 10)
}
/**
* Parse features' property_json attribute and add parsed attributes to features
*/
public FeatureCollection<SimpleFeatureType, SimpleFeature> process(FeatureCollection<SimpleFeatureType, SimpleFeature> features, WFSLayerStore layer) {
DefaultFeatureCollection result = null;
SimpleFeatureBuilder builder = null;
FeatureIterator<SimpleFeature> iterator = features.features();
try {
while (iterator.hasNext()) {
SimpleFeature simpleFeature = iterator.next();
Map<String, Object> jsonMap = getUserlayerFields(simpleFeature);
// only for first feature to build new processed/parsed feature type
if (result == null) {
FeatureDef def = getFeatureDef(simpleFeature.getFeatureType(), layer, jsonMap, features.getID());
result = def.collection;
builder = def.builder;
}
//copy attribute values
//do not add excludedProperties
for (Property property : simpleFeature.getProperties()) {
if (!excludedProperties.contains(property.getName().getLocalPart())) {
builder.set(property.getName(), property.getValue());
}
}
// add new attribute values (from property_json)
for (Map.Entry<String, Object> attribute : jsonMap.entrySet()) {
builder.set(attribute.getKey(), attribute.getValue());
}
// buildFeature calls reset() internally so we are good to go for next round
result.add(builder.buildFeature(simpleFeature.getID()));
}
} catch (Exception ex) {
throw new ServiceRuntimeException("Userlayer processing failed", ex);
} finally {
iterator.close();
}
return result;
}
protected Map<String, Object> getUserlayerFields(SimpleFeature simpleFeature) throws IOException {
Property propertyJson = simpleFeature.getProperty("property_json");
return mapper.readValue(propertyJson.getValue().toString(),
new TypeReference<HashMap<String, Object>>() {});
}
protected FeatureDef getFeatureDef(SimpleFeatureType type, WFSLayerStore layer, Map<String, Object> jsonMap, String featuresetId) {
FeatureDef p = new FeatureDef();
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
typeBuilder.setName(type.getName());
typeBuilder.setNamespaceURI(layer.getFeatureNamespaceURI());
typeBuilder.setSRS(layer.getSRSName());
//copy feature's attributes to new feature type builder
//do not add excludedProperties
for (AttributeDescriptor desc : type.getAttributeDescriptors()) {
if (!excludedProperties.contains(desc.getLocalName())) {
typeBuilder.add(desc);
}
}
typeBuilder.setName(type.getName());
// add new parsed attributes from property_json to new type builder
for (Map.Entry<String, Object> attribute : jsonMap.entrySet()) {
typeBuilder.add(attribute.getKey(), attribute.getValue().getClass());
}
SimpleFeatureType parsedFeatureType = typeBuilder.buildFeatureType();
p.collection = new DefaultFeatureCollection(featuresetId, parsedFeatureType);
p.builder = new SimpleFeatureBuilder(parsedFeatureType);
return p;
}
class FeatureDef {
DefaultFeatureCollection collection;
SimpleFeatureBuilder builder;
}
} | added id to excluded properties
| servlet-transport/src/main/java/fi/nls/oskari/wfs/extension/UserLayerProcessor.java | added id to excluded properties | <ide><path>ervlet-transport/src/main/java/fi/nls/oskari/wfs/extension/UserLayerProcessor.java
<ide> excludedProperties.add("created");
<ide> excludedProperties.add("updated");
<ide> excludedProperties.add("attention_text");
<add> excludedProperties.add("id");
<ide> }
<ide>
<ide> private ObjectMapper mapper = new ObjectMapper(); |
|
Java | mit | c4bb2b86d363c4a516c8cc6e7fe12fb11f756165 | 0 | jimregan/jngramtool,jimregan/jngramtool | package ie.tcd.slscs.tools;
import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/*
* Copyright 2016 Jim O'Regan <[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.
*/
public class AKDiscardKFNGramPunct {
public static void main(String[] args) {
try {
String line;
InputStream fis = new FileInputStream(args[0]);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
OutputStream fos = new FileOutputStream(args[0] + ".filt.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8"));
BufferedWriter bw = new BufferedWriter(osw);
while ((line = br.readLine()) != null) {
boolean has_punct = false;
String[] tmpa = line.split("\\t");
String[] tmpb = tmpa[0].split(" ");
for (String s : tmpb) {
if(s == "." || s == "!" || s == "?" || s == ":" || s == ";") {
has_punct = true;
}
}
if(!has_punct) {
bw.write(line);
bw.newLine();
} else {
has_punct = false;
}
}
bw.close();
} catch (Exception e) {
System.err.println(e.getStackTrace());
}
}
}
| src/main/java/ie/tcd/slscs/tools/AKDiscardKFNGramPunct.java | package ie.tcd.slscs.tools;
import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/*
* Copyright 2016 Jim O'Regan <[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.
*/
public class AKDiscardKFNGramPunct {
public static void main(String[] args) {
try {
String line;
InputStream fis = new FileInputStream(args[0]);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
OutputStream fos = new FileOutputStream(args[0] + ".filt.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8"));
BufferedWriter bw = new BufferedWriter(osw);
while ((line = br.readLine()) != null) {
boolean has_punct = false;
String[] tmpa = line.split("\\t");
String[] tmpb = tmpa[0].split(" ");
for (String s : tmpb) {
if(s == "." || s == "!" || s == "?" || s == ":" || s == ";") {
has_punct = true;
}
}
if(!has_punct) {
bw.write(line);
bw.newLine();
}
}
bw.close();
} catch (Exception e) {
System.err.println(e.getStackTrace());
}
}
}
| state
| src/main/java/ie/tcd/slscs/tools/AKDiscardKFNGramPunct.java | state | <ide><path>rc/main/java/ie/tcd/slscs/tools/AKDiscardKFNGramPunct.java
<ide> if(!has_punct) {
<ide> bw.write(line);
<ide> bw.newLine();
<add> } else {
<add> has_punct = false;
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | c46dcd74373607d54031437132685c455d9d44e5 | 0 | ajordens/clouddriver,spinnaker/clouddriver,ajordens/clouddriver,duftler/clouddriver,spinnaker/clouddriver,duftler/clouddriver,spinnaker/clouddriver,duftler/clouddriver,ajordens/clouddriver,ajordens/clouddriver,duftler/clouddriver | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.cats.redis.cluster;
import com.netflix.spinnaker.cats.agent.Agent;
import com.netflix.spinnaker.cats.agent.AgentExecution;
import com.netflix.spinnaker.cats.agent.AgentLock;
import com.netflix.spinnaker.cats.agent.AgentScheduler;
import com.netflix.spinnaker.cats.agent.AgentSchedulerAware;
import com.netflix.spinnaker.cats.agent.ExecutionInstrumentation;
import com.netflix.spinnaker.cats.module.CatsModuleAware;
import com.netflix.spinnaker.cats.thread.NamedThreadFactory;
import com.netflix.spinnaker.kork.jedis.RedisClientDelegate;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@SuppressFBWarnings
public class ClusteredAgentScheduler extends CatsModuleAware implements AgentScheduler<AgentLock>, Runnable {
private static enum Status {
SUCCESS,
FAILURE
}
private static final Logger logger = LoggerFactory.getLogger(ClusteredAgentScheduler.class);
private final RedisClientDelegate redisClientDelegate;
private final NodeIdentity nodeIdentity;
private final AgentIntervalProvider intervalProvider;
private final ExecutorService agentExecutionPool;
private final Pattern enabledAgentPattern;
private final Map<String, AgentExecutionAction> agents = new ConcurrentHashMap<>();
private final Map<String, NextAttempt> activeAgents = new ConcurrentHashMap<>();
private final NodeStatusProvider nodeStatusProvider;
private final Integer maxConcurrentAgents;
public ClusteredAgentScheduler(RedisClientDelegate redisClientDelegate,
NodeIdentity nodeIdentity,
AgentIntervalProvider intervalProvider,
NodeStatusProvider nodeStatusProvider,
String enabledAgentPattern,
Integer maxConcurrentAgents,
Integer agentLockAcquisitionIntervalSeconds) {
this(
redisClientDelegate,
nodeIdentity,
intervalProvider,
nodeStatusProvider,
Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(ClusteredAgentScheduler.class.getSimpleName())),
Executors.newCachedThreadPool(new NamedThreadFactory(AgentExecutionAction.class.getSimpleName())),
enabledAgentPattern,
maxConcurrentAgents,
agentLockAcquisitionIntervalSeconds
);
}
public ClusteredAgentScheduler(RedisClientDelegate redisClientDelegate,
NodeIdentity nodeIdentity,
AgentIntervalProvider intervalProvider,
NodeStatusProvider nodeStatusProvider,
ScheduledExecutorService lockPollingScheduler,
ExecutorService agentExecutionPool,
String enabledAgentPattern,
Integer maxConcurrentAgents,
Integer agentLockAcquisitionIntervalSeconds) {
this.redisClientDelegate = redisClientDelegate;
this.nodeIdentity = nodeIdentity;
this.intervalProvider = intervalProvider;
this.nodeStatusProvider = nodeStatusProvider;
this.agentExecutionPool = agentExecutionPool;
this.enabledAgentPattern = Pattern.compile(enabledAgentPattern);
this.maxConcurrentAgents = maxConcurrentAgents == null ? 1000 : maxConcurrentAgents;
Integer lockInterval = agentLockAcquisitionIntervalSeconds == null ? 1 : agentLockAcquisitionIntervalSeconds;
lockPollingScheduler.scheduleAtFixedRate(this, 0, lockInterval, TimeUnit.SECONDS);
}
private Map<String, NextAttempt> acquire() {
Set<String> skip = new HashSet<>(activeAgents.keySet());
Integer availableAgents = maxConcurrentAgents - skip.size();
if (availableAgents <= 0) {
logger.debug("Not acquiring more locks (activeAgents: {}, runningAgents: {}",
skip.size(),
skip.stream().sorted().collect(Collectors.joining(","))
);
return Collections.emptyMap();
}
Map<String, NextAttempt> acquired = new HashMap<>(agents.size());
// Shuffle the list before grabbing so that we don't favor some agents accidentally
List<Map.Entry<String, AgentExecutionAction>> agentsEntrySet = new ArrayList<>(agents.entrySet());
Collections.shuffle(agentsEntrySet);
for (Map.Entry<String, AgentExecutionAction> agent : agentsEntrySet) {
if (!skip.contains(agent.getKey())) {
final String agentType = agent.getKey();
AgentIntervalProvider.Interval interval = intervalProvider.getInterval(agent.getValue().getAgent());
if (acquireRunKey(agentType, interval.getTimeout())) {
acquired.put(agentType, new NextAttempt(System.currentTimeMillis(), interval.getInterval(), interval.getErrorInterval()));
}
}
if (acquired.size() >= availableAgents) {
return acquired;
}
}
return acquired;
}
@Override
public void run() {
if (!nodeStatusProvider.isNodeEnabled()) {
return;
}
try {
runAgents();
} catch (Throwable t) {
logger.error("Unable to run agents", t);
}
}
private void runAgents() {
Map<String, NextAttempt> thisRun = acquire();
activeAgents.putAll(thisRun);
for (final Map.Entry<String, NextAttempt> toRun : thisRun.entrySet()) {
final AgentExecutionAction exec = agents.get(toRun.getKey());
agentExecutionPool.submit(new AgentJob(toRun.getValue(), exec, this));
}
}
private static final long MIN_TTL_THRESHOLD = 500L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_EXPIRE_TIME_MILLIS = "PX";
private static final String SUCCESS_RESPONSE = "OK";
private static final Long DEL_SUCCESS = 1L;
private static final String DELETE_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
private static final String TTL_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'PX', ARGV[2], 'XX') else return nil end";
private boolean acquireRunKey(String agentType, long timeout) {
return redisClientDelegate.withCommandsClient(client -> {
String response = client.set(agentType, nodeIdentity.getNodeIdentity(), SET_IF_NOT_EXIST, SET_EXPIRE_TIME_MILLIS, timeout);
return SUCCESS_RESPONSE.equals(response);
});
}
private boolean deleteLock(String agentType) {
return redisClientDelegate.withScriptingClient(client -> {
Object response = client.eval(DELETE_LOCK_KEY, Arrays.asList(agentType), Arrays.asList(nodeIdentity.getNodeIdentity()));
return DEL_SUCCESS.equals(response);
});
}
private boolean ttlLock(String agentType, long newTtl) {
return redisClientDelegate.withScriptingClient(client -> {
Object response = client.eval(TTL_LOCK_KEY, Arrays.asList(agentType), Arrays.asList(nodeIdentity.getNodeIdentity(), Long.toString(newTtl)));
return SUCCESS_RESPONSE.equals(response);
});
}
private void releaseRunKey(String agentType, long when) {
final long newTtl = when - System.currentTimeMillis();
final boolean delete = newTtl < MIN_TTL_THRESHOLD;
if (delete) {
boolean success = deleteLock(agentType);
if (!success) {
logger.debug("Delete lock was unsuccessful for " + agentType);
}
} else {
boolean success = ttlLock(agentType, newTtl);
if (!success) {
logger.debug("Ttl lock was unsuccessful for " + agentType);
}
}
}
private void agentCompleted(String agentType, long nextExecutionTime) {
try {
releaseRunKey(agentType, nextExecutionTime);
} finally {
activeAgents.remove(agentType);
}
}
@Override
public void schedule(Agent agent,
AgentExecution agentExecution,
ExecutionInstrumentation executionInstrumentation) {
if (!enabledAgentPattern.matcher(agent.getAgentType().toLowerCase()).matches()) {
logger.debug(
"Agent is not enabled (agent: {}, agentType: {}, pattern: {})",
agent.getClass().getSimpleName(),
agent.getAgentType(),
enabledAgentPattern.pattern()
);
return;
}
if (agent instanceof AgentSchedulerAware) {
((AgentSchedulerAware)agent).setAgentScheduler(this);
}
AgentExecutionAction agentExecutionAction = new AgentExecutionAction(
agent, agentExecution, executionInstrumentation
);
agents.put(agent.getAgentType(), agentExecutionAction);
}
@Override
public void unschedule(Agent agent) {
releaseRunKey(agent.getAgentType(), 0); // Delete lock key now.
agents.remove(agent.getAgentType());
}
private static class NextAttempt {
private final long currentTime;
private final long successInterval;
private final long errorInterval;
public NextAttempt(long currentTime, long successInterval, long errorInterval) {
this.currentTime = currentTime;
this.successInterval = successInterval;
this.errorInterval = errorInterval;
}
public long getNextTime(Status status) {
if (status == Status.SUCCESS) {
return currentTime + successInterval;
}
return currentTime + errorInterval;
}
}
private static class AgentJob implements Runnable {
private final NextAttempt lockReleaseTime;
private final AgentExecutionAction action;
private final ClusteredAgentScheduler scheduler;
public AgentJob(NextAttempt times, AgentExecutionAction action, ClusteredAgentScheduler scheduler) {
this.lockReleaseTime = times;
this.action = action;
this.scheduler = scheduler;
}
@Override
public void run() {
Status status = Status.FAILURE;
try {
status = action.execute();
} finally {
scheduler.agentCompleted(action.getAgent().getAgentType(), lockReleaseTime.getNextTime(status));
}
}
}
private static class AgentExecutionAction {
private final Agent agent;
private final AgentExecution agentExecution;
private final ExecutionInstrumentation executionInstrumentation;
public AgentExecutionAction(Agent agent, AgentExecution agentExecution, ExecutionInstrumentation executionInstrumentation) {
this.agent = agent;
this.agentExecution = agentExecution;
this.executionInstrumentation = executionInstrumentation;
}
public Agent getAgent() {
return agent;
}
Status execute() {
try {
executionInstrumentation.executionStarted(agent);
long startTime = System.nanoTime();
agentExecution.executeAgent(agent);
executionInstrumentation.executionCompleted(agent, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
return Status.SUCCESS;
} catch (Throwable cause) {
executionInstrumentation.executionFailed(agent, cause);
return Status.FAILURE;
}
}
}
}
| cats/cats-redis/src/main/java/com/netflix/spinnaker/cats/redis/cluster/ClusteredAgentScheduler.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.cats.redis.cluster;
import com.netflix.spinnaker.cats.agent.Agent;
import com.netflix.spinnaker.cats.agent.AgentExecution;
import com.netflix.spinnaker.cats.agent.AgentLock;
import com.netflix.spinnaker.cats.agent.AgentScheduler;
import com.netflix.spinnaker.cats.agent.AgentSchedulerAware;
import com.netflix.spinnaker.cats.agent.ExecutionInstrumentation;
import com.netflix.spinnaker.cats.module.CatsModuleAware;
import com.netflix.spinnaker.cats.thread.NamedThreadFactory;
import com.netflix.spinnaker.kork.jedis.RedisClientDelegate;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@SuppressFBWarnings
public class ClusteredAgentScheduler extends CatsModuleAware implements AgentScheduler<AgentLock>, Runnable {
private static enum Status {
SUCCESS,
FAILURE
}
private static final Logger logger = LoggerFactory.getLogger(ClusteredAgentScheduler.class);
private final RedisClientDelegate redisClientDelegate;
private final NodeIdentity nodeIdentity;
private final AgentIntervalProvider intervalProvider;
private final ExecutorService agentExecutionPool;
private final Pattern enabledAgentPattern;
private final Map<String, AgentExecutionAction> agents = new ConcurrentHashMap<>();
private final Map<String, NextAttempt> activeAgents = new ConcurrentHashMap<>();
private final NodeStatusProvider nodeStatusProvider;
private final Integer maxConcurrentAgents;
public ClusteredAgentScheduler(RedisClientDelegate redisClientDelegate,
NodeIdentity nodeIdentity,
AgentIntervalProvider intervalProvider,
NodeStatusProvider nodeStatusProvider,
String enabledAgentPattern,
Integer maxConcurrentAgents,
Integer agentLockAcquisitionIntervalSeconds) {
this(
redisClientDelegate,
nodeIdentity,
intervalProvider,
nodeStatusProvider,
Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(ClusteredAgentScheduler.class.getSimpleName())),
Executors.newCachedThreadPool(new NamedThreadFactory(AgentExecutionAction.class.getSimpleName())),
enabledAgentPattern,
maxConcurrentAgents,
agentLockAcquisitionIntervalSeconds
);
}
public ClusteredAgentScheduler(RedisClientDelegate redisClientDelegate,
NodeIdentity nodeIdentity,
AgentIntervalProvider intervalProvider,
NodeStatusProvider nodeStatusProvider,
ScheduledExecutorService lockPollingScheduler,
ExecutorService agentExecutionPool,
String enabledAgentPattern,
Integer maxConcurrentAgents,
Integer agentLockAcquisitionIntervalSeconds) {
this.redisClientDelegate = redisClientDelegate;
this.nodeIdentity = nodeIdentity;
this.intervalProvider = intervalProvider;
this.nodeStatusProvider = nodeStatusProvider;
this.agentExecutionPool = agentExecutionPool;
this.enabledAgentPattern = Pattern.compile(enabledAgentPattern);
this.maxConcurrentAgents = maxConcurrentAgents == null ? 1000 : maxConcurrentAgents;
Integer lockInterval = agentLockAcquisitionIntervalSeconds == null ? 1 : agentLockAcquisitionIntervalSeconds;
lockPollingScheduler.scheduleAtFixedRate(this, 0, lockInterval, TimeUnit.SECONDS);
}
private Map<String, NextAttempt> acquire() {
Set<String> skip = new HashSet<>(activeAgents.keySet());
Integer availableAgents = maxConcurrentAgents - skip.size();
if (availableAgents <= 0) {
logger.debug("Not acquiring more locks (activeAgents: {}, runningAgents: {}",
skip.size(),
skip.stream().sorted().collect(Collectors.joining(","))
);
return Collections.emptyMap();
}
Map<String, NextAttempt> acquired = new HashMap<>(agents.size());
// Shuffle the list before grabbing so that we don't favor some agents accidentally
List<Map.Entry<String, AgentExecutionAction>> agentsEntrySet = new ArrayList<>(agents.entrySet());
Collections.shuffle(agentsEntrySet);
for (Map.Entry<String, AgentExecutionAction> agent : agentsEntrySet) {
if (!skip.contains(agent.getKey())) {
final String agentType = agent.getKey();
AgentIntervalProvider.Interval interval = intervalProvider.getInterval(agent.getValue().getAgent());
if (acquireRunKey(agentType, interval.getTimeout())) {
acquired.put(agentType, new NextAttempt(System.currentTimeMillis(), interval.getInterval(), interval.getErrorInterval()));
}
}
if (acquired.size() >= availableAgents) {
return acquired;
}
}
return acquired;
}
@Override
public void run() {
if (!nodeStatusProvider.isNodeEnabled()) {
return;
}
try {
runAgents();
} catch (Throwable t) {
logger.error("Unable to run agents", t);
}
}
private void runAgents() {
Map<String, NextAttempt> thisRun = acquire();
activeAgents.putAll(thisRun);
for (final Map.Entry<String, NextAttempt> toRun : thisRun.entrySet()) {
final AgentExecutionAction exec = agents.get(toRun.getKey());
agentExecutionPool.submit(new AgentJob(toRun.getValue(), exec, this));
}
}
private static final long MIN_TTL_THRESHOLD = 500L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_EXPIRE_TIME_MILLIS = "PX";
private static final String SUCCESS_RESPONSE = "OK";
private static final Integer DEL_SUCCESS = 1;
private static final String DELETE_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
private static final String TTL_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'PX', ARGV[2], 'XX') else return nil end";
private boolean acquireRunKey(String agentType, long timeout) {
return redisClientDelegate.withCommandsClient(client -> {
String response = client.set(agentType, nodeIdentity.getNodeIdentity(), SET_IF_NOT_EXIST, SET_EXPIRE_TIME_MILLIS, timeout);
return SUCCESS_RESPONSE.equals(response);
});
}
private boolean deleteLock(String agentType) {
return redisClientDelegate.withScriptingClient(client -> {
Object response = client.eval(DELETE_LOCK_KEY, Arrays.asList(agentType), Arrays.asList(nodeIdentity.getNodeIdentity()));
return DEL_SUCCESS.equals(response);
});
}
private boolean ttlLock(String agentType, long newTtl) {
return redisClientDelegate.withScriptingClient(client -> {
Object response = client.eval(TTL_LOCK_KEY, Arrays.asList(agentType), Arrays.asList(nodeIdentity.getNodeIdentity(), Long.toString(newTtl)));
return SUCCESS_RESPONSE.equals(response);
});
}
private void releaseRunKey(String agentType, long when) {
final long newTtl = when - System.currentTimeMillis();
final boolean delete = newTtl < MIN_TTL_THRESHOLD;
if (delete) {
boolean success = deleteLock(agentType);
if (!success) {
logger.debug("Delete lock was unsuccessful for " + agentType);
}
} else {
boolean success = ttlLock(agentType, newTtl);
if (!success) {
logger.debug("Ttl lock was unsuccessful for " + agentType);
}
}
}
private void agentCompleted(String agentType, long nextExecutionTime) {
try {
releaseRunKey(agentType, nextExecutionTime);
} finally {
activeAgents.remove(agentType);
}
}
@Override
public void schedule(Agent agent,
AgentExecution agentExecution,
ExecutionInstrumentation executionInstrumentation) {
if (!enabledAgentPattern.matcher(agent.getAgentType().toLowerCase()).matches()) {
logger.debug(
"Agent is not enabled (agent: {}, agentType: {}, pattern: {})",
agent.getClass().getSimpleName(),
agent.getAgentType(),
enabledAgentPattern.pattern()
);
return;
}
if (agent instanceof AgentSchedulerAware) {
((AgentSchedulerAware)agent).setAgentScheduler(this);
}
AgentExecutionAction agentExecutionAction = new AgentExecutionAction(
agent, agentExecution, executionInstrumentation
);
agents.put(agent.getAgentType(), agentExecutionAction);
}
@Override
public void unschedule(Agent agent) {
releaseRunKey(agent.getAgentType(), 0); // Delete lock key now.
agents.remove(agent.getAgentType());
}
private static class NextAttempt {
private final long currentTime;
private final long successInterval;
private final long errorInterval;
public NextAttempt(long currentTime, long successInterval, long errorInterval) {
this.currentTime = currentTime;
this.successInterval = successInterval;
this.errorInterval = errorInterval;
}
public long getNextTime(Status status) {
if (status == Status.SUCCESS) {
return currentTime + successInterval;
}
return currentTime + errorInterval;
}
}
private static class AgentJob implements Runnable {
private final NextAttempt lockReleaseTime;
private final AgentExecutionAction action;
private final ClusteredAgentScheduler scheduler;
public AgentJob(NextAttempt times, AgentExecutionAction action, ClusteredAgentScheduler scheduler) {
this.lockReleaseTime = times;
this.action = action;
this.scheduler = scheduler;
}
@Override
public void run() {
Status status = Status.FAILURE;
try {
status = action.execute();
} finally {
scheduler.agentCompleted(action.getAgent().getAgentType(), lockReleaseTime.getNextTime(status));
}
}
}
private static class AgentExecutionAction {
private final Agent agent;
private final AgentExecution agentExecution;
private final ExecutionInstrumentation executionInstrumentation;
public AgentExecutionAction(Agent agent, AgentExecution agentExecution, ExecutionInstrumentation executionInstrumentation) {
this.agent = agent;
this.agentExecution = agentExecution;
this.executionInstrumentation = executionInstrumentation;
}
public Agent getAgent() {
return agent;
}
Status execute() {
try {
executionInstrumentation.executionStarted(agent);
long startTime = System.nanoTime();
agentExecution.executeAgent(agent);
executionInstrumentation.executionCompleted(agent, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
return Status.SUCCESS;
} catch (Throwable cause) {
executionInstrumentation.executionFailed(agent, cause);
return Status.FAILURE;
}
}
}
}
| fix(cats): ClusteredAgentScheduler.deleteLock
LUA call was returning a Long not an Integer, deleteLock
was always returning false.
Previously we ignored the value, now we use it to drive
a logging message.
| cats/cats-redis/src/main/java/com/netflix/spinnaker/cats/redis/cluster/ClusteredAgentScheduler.java | fix(cats): ClusteredAgentScheduler.deleteLock | <ide><path>ats/cats-redis/src/main/java/com/netflix/spinnaker/cats/redis/cluster/ClusteredAgentScheduler.java
<ide> private static final String SET_IF_NOT_EXIST = "NX";
<ide> private static final String SET_EXPIRE_TIME_MILLIS = "PX";
<ide> private static final String SUCCESS_RESPONSE = "OK";
<del> private static final Integer DEL_SUCCESS = 1;
<add> private static final Long DEL_SUCCESS = 1L;
<ide>
<ide> private static final String DELETE_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
<ide> private static final String TTL_LOCK_KEY = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('set', KEYS[1], ARGV[1], 'PX', ARGV[2], 'XX') else return nil end"; |
|
JavaScript | mpl-2.0 | 426d030aa7d28e569c863ca1c57c741dbbb71898 | 0 | JAMESAPP/JAMES,JAMESAPP/JAMES | define([
'underscore'
, 'marionette'
, 'app'
, 'views/bindingView'
, 'views/register'
, 'hideShowPassword'
], function (_, Marionette, App, BindingView, RegisterView) {
var ItemView = RegisterView.extend({
tagName: 'div',
className: 'box'
, template: 'app/templates/settings.tpl'
, objectStore: 'settings'
, events: function() {
return _.extend({}, RegisterView.prototype.events, {
'click #btnHideShowPassword': 'hideShowPassword'
, 'click #btnDeleteSettings': 'deleteSettings'
, 'click #btnCleanLocalStorage': 'cleanLocalStorage'
});
}
, hideShowPassword: function(ev) {
ev.preventDefault();
this.$el.find('#inputCloudAuthPassword').togglePassword();
}
, deleteSettings: function(ev) {
ev.preventDefault();
var self = this;
App.indexedDB.db.transaction([this.objectStore], 'readwrite').objectStore(this.objectStore).delete(1).onsuccess = function(e) {
self.$el.find('#spanMessage').removeClass();
self.$el.find('#spanMessage').addClass('col-xs-12 text-center alert alert-danger');
self.$el.find('#spanMessage').html('Settings removed!! Edit and save again!').fadeIn().delay(5000).fadeOut();
};
}
, cleanLocalStorage: function(ev) {
ev.preventDefault();
// TODO implement [] app.getEntities();
var transaction = App.indexedDB.db.transaction(['expenses', 'oils', 'refuels', 'timesheets', 'settings'], 'readwrite');
transaction.objectStore('settings').clear().onsuccess = function(event) {
console.log('Cleaned settings');
};
transaction.objectStore('expenses').clear().onsuccess = function(event) {
console.log('Cleaned expenses');
};
transaction.objectStore('oils').clear().onsuccess = function(event) {
console.log('Cleaned oils');
};
transaction.objectStore('refuels').clear().onsuccess = function(event) {
console.log('Cleaned refuels');
};
transaction.objectStore('timesheets').clear().onsuccess = function(event) {
console.log('Cleaned timesheets');
};
}
});
return ItemView;
});
| app/js/views/settings.js | define([
'underscore'
, 'marionette'
, 'app'
, 'views/bindingView'
, 'views/register'
, 'hideShowPassword'
], function (_, Marionette, App, BindingView, RegisterView) {
var ItemView = RegisterView.extend({
tagName: 'div',
className: 'box'
, template: 'app/templates/settings.tpl'
, objectStore: 'settings'
, events: function() {
return _.extend({}, RegisterView.prototype.events, {
'click #btnHideShowPassword': 'hideShowPassword'
, 'click #btnDeleteSettings': 'deleteSettings'
, 'click #btnCleanLocalStorage': 'cleanLocalStorage'
});
}
, hideShowPassword: function(ev) {
ev.preventDefault();
this.$el.find('#inputCloudAuthPassword').togglePassword();
}
, deleteSettings: function(ev) {
ev.preventDefault();
var self = this;
App.indexedDB.db.transaction([this.objectStore], 'readwrite').objectStore(this.objectStore).delete(1).onsuccess = function(e) {
self.$el.find('#spanMessage').removeClass();
self.$el.find('#spanMessage').addClass('col-xs-12 text-center alert alert-danger');
self.$el.find('#spanMessage').html('Settings removed!! Edit and save again!').fadeIn().delay(5000).fadeOut();
};
}
, cleanLocalStorage: function(ev) {
ev.preventDefault();
// TODO implement [] app.getEntities();
var transaction = App.indexedDB.db.transaction(['expenses', 'oils', 'refuels', 'timesheets', 'settings'], 'readwrite');
transaction.objectStore('settings').clear().onsuccess = function(event) {
console.log('Cleaned settings');
};
transaction.objectStore('expenses').clear().onsuccess = function(event) {
console.log('Cleaned expenses');
};
transaction.objectStore('motorcycles').clear().onsuccess = function(event) {
console.log('Cleaned motorcycles');
};
transaction.objectStore('timesheets').clear().onsuccess = function(event) {
console.log('Cleaned timesheets');
};
}
});
return ItemView;
});
| Settings
Replace motorcycle by refuel and oil;
| app/js/views/settings.js | Settings | <ide><path>pp/js/views/settings.js
<ide> console.log('Cleaned expenses');
<ide> };
<ide>
<del> transaction.objectStore('motorcycles').clear().onsuccess = function(event) {
<del> console.log('Cleaned motorcycles');
<add> transaction.objectStore('oils').clear().onsuccess = function(event) {
<add> console.log('Cleaned oils');
<add> };
<add>
<add> transaction.objectStore('refuels').clear().onsuccess = function(event) {
<add> console.log('Cleaned refuels');
<ide> };
<ide>
<ide> transaction.objectStore('timesheets').clear().onsuccess = function(event) { |
|
Java | mit | bbf9e5f6294239ddab386ab83c17eeb93a7c0ef3 | 0 | Adaptivity/JustEnoughItems,mezz/JustEnoughItems,Adaptivity/JustEnoughItems,mezz/JustEnoughItems,way2muchnoise/JustEnoughItems | package mezz.jei.gui.ingredients;
import com.google.common.base.Joiner;
import mezz.jei.Internal;
import mezz.jei.config.Config;
import mezz.jei.config.Constants;
import mezz.jei.gui.TooltipRenderer;
import mezz.jei.util.Translator;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemModelMesher;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.color.ItemColors;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.model.pipeline.LightUtil;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.*;
import java.util.Collection;
import java.util.List;
public class GuiItemStackFast {
private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private static final int blacklistItemColor = Color.yellow.getRGB();
private static final int blacklistWildColor = Color.red.getRGB();
private static final int blacklistModColor = Color.blue.getRGB();
@Nonnull
private final Rectangle area;
private final int padding;
private final ItemModelMesher itemModelMesher;
@Nullable
private ItemStack itemStack;
public GuiItemStackFast(int xPosition, int yPosition, int padding) {
this.padding = padding;
final int size = 16 + (2 * padding);
this.area = new Rectangle(xPosition, yPosition, size, size);
this.itemModelMesher = Minecraft.getMinecraft().getRenderItem().getItemModelMesher();
}
@Nonnull
public Rectangle getArea() {
return area;
}
public void setItemStack(@Nonnull ItemStack itemStack) {
this.itemStack = itemStack;
}
@Nullable
public ItemStack getItemStack() {
return itemStack;
}
public void clear() {
this.itemStack = null;
}
public boolean isMouseOver(int mouseX, int mouseY) {
return (itemStack != null) && area.contains(mouseX, mouseY);
}
public void renderItemAndEffectIntoGUI() {
if (itemStack == null) {
return;
}
IBakedModel bakedModel = itemModelMesher.getItemModel(itemStack);
if (Config.isEditModeEnabled()) {
renderEditMode();
GlStateManager.enableBlend();
}
GlStateManager.pushMatrix();
{
GlStateManager.translate(area.x + padding + 8.0f, area.y + padding + 8.0f, 150.0F);
GlStateManager.scale(16F, -16F, 16F);
bakedModel = ForgeHooksClient.handleCameraTransforms(bakedModel, ItemCameraTransforms.TransformType.GUI, false);
GlStateManager.translate(-0.5F, -0.5F, -0.5F);
renderModel(bakedModel, itemStack);
if (itemStack.hasEffect()) {
renderEffect(bakedModel);
}
}
GlStateManager.popMatrix();
}
private void renderModel(IBakedModel model, ItemStack stack) {
this.renderModel(model, -1, stack);
}
private void renderModel(IBakedModel model, int color, ItemStack stack) {
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer vertexBuffer = tessellator.getBuffer();
vertexBuffer.begin(7, DefaultVertexFormats.ITEM);
for (EnumFacing enumfacing : EnumFacing.VALUES) {
this.renderQuads(vertexBuffer, model.getQuads(null, enumfacing, 0), color, stack);
}
this.renderQuads(vertexBuffer, model.getQuads(null, null, 0), color, stack);
tessellator.draw();
}
private void renderQuads(VertexBuffer vertexBuffer, List<BakedQuad> quads, final int color, ItemStack stack) {
boolean flag = color == -1 && stack != null;
ItemColors itemColors = Minecraft.getMinecraft().getItemColors();
for (BakedQuad bakedquad : quads) {
int quadColor = color;
if (flag && bakedquad.hasTintIndex()) {
quadColor = itemColors.getColorFromItemstack(stack, bakedquad.getTintIndex());
if (EntityRenderer.anaglyphEnable) {
quadColor = TextureUtil.anaglyphColor(quadColor);
}
quadColor |= -16777216;
}
LightUtil.renderQuadColor(vertexBuffer, bakedquad, quadColor);
}
}
private void renderEffect(IBakedModel model) {
TextureManager textureManager = Minecraft.getMinecraft().getTextureManager();
GlStateManager.depthMask(false);
GlStateManager.depthFunc(514);
GlStateManager.blendFunc(768, 1);
textureManager.bindTexture(RES_ITEM_GLINT);
GlStateManager.matrixMode(5890);
GlStateManager.pushMatrix();
GlStateManager.scale(8.0F, 8.0F, 8.0F);
float f = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F;
GlStateManager.translate(f, 0.0F, 0.0F);
GlStateManager.rotate(-50.0F, 0.0F, 0.0F, 1.0F);
this.renderModel(model, -8372020);
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
GlStateManager.scale(8.0F, 8.0F, 8.0F);
float f1 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F / 8.0F;
GlStateManager.translate(-f1, 0.0F, 0.0F);
GlStateManager.rotate(10.0F, 0.0F, 0.0F, 1.0F);
this.renderModel(model, -8372020);
GlStateManager.popMatrix();
GlStateManager.matrixMode(5888);
GlStateManager.blendFunc(770, 771);
GlStateManager.depthFunc(515);
GlStateManager.depthMask(true);
textureManager.bindTexture(TextureMap.locationBlocksTexture);
}
private void renderModel(IBakedModel model, int color) {
this.renderModel(model, color, null);
}
public void renderSlow() {
if (Config.isEditModeEnabled()) {
renderEditMode();
}
Minecraft minecraft = Minecraft.getMinecraft();
RenderItem renderItem = minecraft.getRenderItem();
renderItem.renderItemAndEffectIntoGUI(itemStack, area.x + padding, area.y + padding);
GlStateManager.disableBlend();
}
public void renderOverlay(Minecraft minecraft) {
if (itemStack == null) {
return;
}
FontRenderer font = getFontRenderer(minecraft, itemStack);
RenderItem renderItem = minecraft.getRenderItem();
renderItem.renderItemOverlayIntoGUI(font, itemStack, area.x + padding, area.y + padding, null);
}
private void renderEditMode() {
if (itemStack == null) {
return;
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.ITEM)) {
GuiScreen.drawRect(area.x + padding, area.y + padding, area.x + 8 + padding, area.y + 16 + padding, blacklistItemColor);
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.WILDCARD)) {
GuiScreen.drawRect(area.x + 8 + padding, area.y + padding, area.x + 16 + padding, area.y + 16 + padding, blacklistWildColor);
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.MOD_ID)) {
GuiScreen.drawRect(area.x + padding, area.y + 8 + padding, area.x + 16 + padding, area.y + 16 + padding, blacklistModColor);
}
}
@Nonnull
public static FontRenderer getFontRenderer(@Nonnull Minecraft minecraft, @Nonnull ItemStack itemStack) {
Item item = itemStack.getItem();
FontRenderer fontRenderer = item.getFontRenderer(itemStack);
if (fontRenderer == null) {
fontRenderer = minecraft.fontRendererObj;
}
return fontRenderer;
}
public void drawHovered(Minecraft minecraft) {
if (itemStack == null) {
return;
}
renderSlow();
renderOverlay(minecraft);
GlStateManager.disableDepth();
Gui.drawRect(area.x, area.y, area.x + area.width, area.y + area.height, 0x7FFFFFFF);
GlStateManager.enableDepth();
}
public void drawTooltip(@Nonnull Minecraft minecraft, int mouseX, int mouseY) {
if (itemStack == null) {
return;
}
List<String> tooltip = getTooltip(minecraft, itemStack);
FontRenderer fontRenderer = getFontRenderer(minecraft, itemStack);
TooltipRenderer.drawHoveringText(minecraft, tooltip, mouseX, mouseY, fontRenderer);
}
@Nonnull
private static List<String> getTooltip(@Nonnull Minecraft minecraft, @Nonnull ItemStack itemStack) {
List<String> list = itemStack.getTooltip(minecraft.thePlayer, minecraft.gameSettings.advancedItemTooltips);
for (int k = 0; k < list.size(); ++k) {
if (k == 0) {
list.set(k, itemStack.getRarity().rarityColor + list.get(k));
} else {
list.set(k, TextFormatting.GRAY + list.get(k));
}
}
int maxWidth = Constants.MAX_TOOLTIP_WIDTH;
for (String tooltipLine : list) {
int width = minecraft.fontRendererObj.getStringWidth(tooltipLine);
if (width > maxWidth) {
maxWidth = width;
}
}
if (Config.isColorSearchEnabled()) {
Collection<String> colorNames = Internal.getColorNamer().getColorNames(itemStack);
if (!colorNames.isEmpty()) {
String colorNamesString = Joiner.on(", ").join(colorNames);
String colorNamesLocalizedString = TextFormatting.GRAY + Translator.translateToLocalFormatted("jei.tooltip.item.colors", colorNamesString);
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(colorNamesLocalizedString, maxWidth));
}
}
if (Config.isEditModeEnabled()) {
list.add("");
list.add(TextFormatting.ITALIC + Translator.translateToLocal("gui.jei.editMode.description"));
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.ITEM)) {
String description = TextFormatting.YELLOW + Translator.translateToLocal("gui.jei.editMode.description.show");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
} else {
String description = TextFormatting.YELLOW + Translator.translateToLocal("gui.jei.editMode.description.hide");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.WILDCARD)) {
String description = TextFormatting.RED + Translator.translateToLocal("gui.jei.editMode.description.show.wild");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
} else {
String description = TextFormatting.RED + Translator.translateToLocal("gui.jei.editMode.description.hide.wild");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.MOD_ID)) {
String description = TextFormatting.BLUE + Translator.translateToLocal("gui.jei.editMode.description.show.mod.id");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
} else {
String description = TextFormatting.BLUE + Translator.translateToLocal("gui.jei.editMode.description.hide.mod.id");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
}
}
return list;
}
}
| src/main/java/mezz/jei/gui/ingredients/GuiItemStackFast.java | package mezz.jei.gui.ingredients;
import com.google.common.base.Joiner;
import mezz.jei.Internal;
import mezz.jei.config.Config;
import mezz.jei.config.Constants;
import mezz.jei.gui.TooltipRenderer;
import mezz.jei.util.Translator;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemModelMesher;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.color.ItemColors;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.model.pipeline.LightUtil;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.*;
import java.util.Collection;
import java.util.List;
@SuppressWarnings("deprecation")
public class GuiItemStackFast {
private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private static final int blacklistItemColor = Color.yellow.getRGB();
private static final int blacklistWildColor = Color.red.getRGB();
private static final int blacklistModColor = Color.blue.getRGB();
@Nonnull
private final Rectangle area;
private final int padding;
private final ItemModelMesher itemModelMesher;
@Nullable
private ItemStack itemStack;
public GuiItemStackFast(int xPosition, int yPosition, int padding) {
this.padding = padding;
final int size = 16 + (2 * padding);
this.area = new Rectangle(xPosition, yPosition, size, size);
this.itemModelMesher = Minecraft.getMinecraft().getRenderItem().getItemModelMesher();
}
@Nonnull
public Rectangle getArea() {
return area;
}
public void setItemStack(@Nonnull ItemStack itemStack) {
this.itemStack = itemStack;
}
@Nullable
public ItemStack getItemStack() {
return itemStack;
}
public void clear() {
this.itemStack = null;
}
public boolean isMouseOver(int mouseX, int mouseY) {
return (itemStack != null) && area.contains(mouseX, mouseY);
}
public void renderItemAndEffectIntoGUI() {
if (itemStack == null) {
return;
}
IBakedModel bakedModel = itemModelMesher.getItemModel(itemStack);
if (Config.isEditModeEnabled()) {
renderEditMode();
GlStateManager.enableBlend();
}
GlStateManager.pushMatrix();
{
GlStateManager.translate(area.x + padding + 8.0f, area.y + padding + 8.0f, 150.0F);
GlStateManager.scale(16F, -16F, 16F);
bakedModel = ForgeHooksClient.handleCameraTransforms(bakedModel, ItemCameraTransforms.TransformType.GUI, false);
GlStateManager.translate(-0.5F, -0.5F, -0.5F);
renderModel(bakedModel, itemStack);
if (itemStack.hasEffect()) {
renderEffect(bakedModel);
}
}
GlStateManager.popMatrix();
}
private void renderModel(IBakedModel model, ItemStack stack) {
this.renderModel(model, -1, stack);
}
private void renderModel(IBakedModel model, int color, ItemStack stack) {
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer vertexBuffer = tessellator.getBuffer();
vertexBuffer.begin(7, DefaultVertexFormats.ITEM);
for (EnumFacing enumfacing : EnumFacing.VALUES) {
this.renderQuads(vertexBuffer, model.getQuads(null, enumfacing, 0), color, stack);
}
this.renderQuads(vertexBuffer, model.getQuads(null, null, 0), color, stack);
tessellator.draw();
}
private void renderQuads(VertexBuffer vertexBuffer, List quads, int color, ItemStack stack) {
boolean flag = color == -1 && stack != null;
BakedQuad bakedquad;
int j;
ItemColors itemColors = Minecraft.getMinecraft().getItemColors();
for (Object quad : quads) {
bakedquad = (BakedQuad) quad;
j = color;
if (flag && bakedquad.hasTintIndex()) {
j = itemColors.getColorFromItemstack(stack, bakedquad.getTintIndex());
if (EntityRenderer.anaglyphEnable) {
j = TextureUtil.anaglyphColor(j);
}
j |= -16777216;
}
LightUtil.renderQuadColor(vertexBuffer, bakedquad, j);
}
}
private void renderEffect(IBakedModel model) {
TextureManager textureManager = Minecraft.getMinecraft().getTextureManager();
GlStateManager.depthMask(false);
GlStateManager.depthFunc(514);
GlStateManager.blendFunc(768, 1);
textureManager.bindTexture(RES_ITEM_GLINT);
GlStateManager.matrixMode(5890);
GlStateManager.pushMatrix();
GlStateManager.scale(8.0F, 8.0F, 8.0F);
float f = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F;
GlStateManager.translate(f, 0.0F, 0.0F);
GlStateManager.rotate(-50.0F, 0.0F, 0.0F, 1.0F);
this.renderModel(model, -8372020);
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
GlStateManager.scale(8.0F, 8.0F, 8.0F);
float f1 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F / 8.0F;
GlStateManager.translate(-f1, 0.0F, 0.0F);
GlStateManager.rotate(10.0F, 0.0F, 0.0F, 1.0F);
this.renderModel(model, -8372020);
GlStateManager.popMatrix();
GlStateManager.matrixMode(5888);
GlStateManager.blendFunc(770, 771);
GlStateManager.depthFunc(515);
GlStateManager.depthMask(true);
textureManager.bindTexture(TextureMap.locationBlocksTexture);
}
private void renderModel(IBakedModel model, int color) {
this.renderModel(model, color, null);
}
public void renderSlow() {
if (Config.isEditModeEnabled()) {
renderEditMode();
}
Minecraft minecraft = Minecraft.getMinecraft();
RenderItem renderItem = minecraft.getRenderItem();
renderItem.renderItemAndEffectIntoGUI(itemStack, area.x + padding, area.y + padding);
GlStateManager.disableBlend();
}
public void renderOverlay(Minecraft minecraft) {
if (itemStack == null) {
return;
}
FontRenderer font = getFontRenderer(minecraft, itemStack);
RenderItem renderItem = minecraft.getRenderItem();
renderItem.renderItemOverlayIntoGUI(font, itemStack, area.x + padding, area.y + padding, null);
}
private void renderEditMode() {
if (itemStack == null) {
return;
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.ITEM)) {
GuiScreen.drawRect(area.x + padding, area.y + padding, area.x + 8 + padding, area.y + 16 + padding, blacklistItemColor);
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.WILDCARD)) {
GuiScreen.drawRect(area.x + 8 + padding, area.y + padding, area.x + 16 + padding, area.y + 16 + padding, blacklistWildColor);
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.MOD_ID)) {
GuiScreen.drawRect(area.x + padding, area.y + 8 + padding, area.x + 16 + padding, area.y + 16 + padding, blacklistModColor);
}
}
@Nonnull
public static FontRenderer getFontRenderer(@Nonnull Minecraft minecraft, @Nonnull ItemStack itemStack) {
Item item = itemStack.getItem();
FontRenderer fontRenderer = item.getFontRenderer(itemStack);
if (fontRenderer == null) {
fontRenderer = minecraft.fontRendererObj;
}
return fontRenderer;
}
public void drawHovered(Minecraft minecraft) {
if (itemStack == null) {
return;
}
renderSlow();
renderOverlay(minecraft);
GlStateManager.disableDepth();
Gui.drawRect(area.x, area.y, area.x + area.width, area.y + area.height, 0x7FFFFFFF);
GlStateManager.enableDepth();
}
public void drawTooltip(@Nonnull Minecraft minecraft, int mouseX, int mouseY) {
if (itemStack == null) {
return;
}
List<String> tooltip = getTooltip(minecraft, itemStack);
FontRenderer fontRenderer = getFontRenderer(minecraft, itemStack);
TooltipRenderer.drawHoveringText(minecraft, tooltip, mouseX, mouseY, fontRenderer);
}
@Nonnull
private static List<String> getTooltip(@Nonnull Minecraft minecraft, @Nonnull ItemStack itemStack) {
List<String> list = itemStack.getTooltip(minecraft.thePlayer, minecraft.gameSettings.advancedItemTooltips);
for (int k = 0; k < list.size(); ++k) {
if (k == 0) {
list.set(k, itemStack.getRarity().rarityColor + list.get(k));
} else {
list.set(k, TextFormatting.GRAY + list.get(k));
}
}
int maxWidth = Constants.MAX_TOOLTIP_WIDTH;
for (String tooltipLine : list) {
int width = minecraft.fontRendererObj.getStringWidth(tooltipLine);
if (width > maxWidth) {
maxWidth = width;
}
}
if (Config.isColorSearchEnabled()) {
Collection<String> colorNames = Internal.getColorNamer().getColorNames(itemStack);
if (!colorNames.isEmpty()) {
String colorNamesString = Joiner.on(", ").join(colorNames);
String colorNamesLocalizedString = TextFormatting.GRAY + Translator.translateToLocalFormatted("jei.tooltip.item.colors", colorNamesString);
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(colorNamesLocalizedString, maxWidth));
}
}
if (Config.isEditModeEnabled()) {
list.add("");
list.add(TextFormatting.ITALIC + Translator.translateToLocal("gui.jei.editMode.description"));
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.ITEM)) {
String description = TextFormatting.YELLOW + Translator.translateToLocal("gui.jei.editMode.description.show");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
} else {
String description = TextFormatting.YELLOW + Translator.translateToLocal("gui.jei.editMode.description.hide");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.WILDCARD)) {
String description = TextFormatting.RED + Translator.translateToLocal("gui.jei.editMode.description.show.wild");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
} else {
String description = TextFormatting.RED + Translator.translateToLocal("gui.jei.editMode.description.hide.wild");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
}
if (Config.isItemOnConfigBlacklist(itemStack, Config.ItemBlacklistType.MOD_ID)) {
String description = TextFormatting.BLUE + Translator.translateToLocal("gui.jei.editMode.description.show.mod.id");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
} else {
String description = TextFormatting.BLUE + Translator.translateToLocal("gui.jei.editMode.description.hide.mod.id");
list.addAll(minecraft.fontRendererObj.listFormattedStringToWidth(description, maxWidth));
}
}
return list;
}
}
| Cleanup
| src/main/java/mezz/jei/gui/ingredients/GuiItemStackFast.java | Cleanup | <ide><path>rc/main/java/mezz/jei/gui/ingredients/GuiItemStackFast.java
<ide> import java.util.Collection;
<ide> import java.util.List;
<ide>
<del>@SuppressWarnings("deprecation")
<ide> public class GuiItemStackFast {
<ide> private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
<ide> private static final int blacklistItemColor = Color.yellow.getRGB();
<ide> tessellator.draw();
<ide> }
<ide>
<del> private void renderQuads(VertexBuffer vertexBuffer, List quads, int color, ItemStack stack) {
<add> private void renderQuads(VertexBuffer vertexBuffer, List<BakedQuad> quads, final int color, ItemStack stack) {
<ide> boolean flag = color == -1 && stack != null;
<del> BakedQuad bakedquad;
<del> int j;
<ide>
<ide> ItemColors itemColors = Minecraft.getMinecraft().getItemColors();
<ide>
<del> for (Object quad : quads) {
<del> bakedquad = (BakedQuad) quad;
<del> j = color;
<add> for (BakedQuad bakedquad : quads) {
<add> int quadColor = color;
<ide>
<ide> if (flag && bakedquad.hasTintIndex()) {
<del> j = itemColors.getColorFromItemstack(stack, bakedquad.getTintIndex());
<add> quadColor = itemColors.getColorFromItemstack(stack, bakedquad.getTintIndex());
<ide> if (EntityRenderer.anaglyphEnable) {
<del> j = TextureUtil.anaglyphColor(j);
<add> quadColor = TextureUtil.anaglyphColor(quadColor);
<ide> }
<ide>
<del> j |= -16777216;
<del> }
<del> LightUtil.renderQuadColor(vertexBuffer, bakedquad, j);
<add> quadColor |= -16777216;
<add> }
<add> LightUtil.renderQuadColor(vertexBuffer, bakedquad, quadColor);
<ide> }
<ide> }
<ide> |
|
Java | epl-1.0 | 3ccbc685a69d339150a39293b0459d384c1b56f7 | 0 | debrief/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief | /*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
// $RCSfile: CreateLabel.java,v $
// @author $Author: Ian.Mayo $
// @version $Revision: 1.3 $
// $Log: CreateLabel.java,v $
// Revision 1.3 2005/12/13 09:04:52 Ian.Mayo
// Tidying - as recommended by Eclipse
//
// Revision 1.2 2005/07/08 14:18:34 Ian.Mayo
// Make utility methods more accessible
//
// Revision 1.1.1.2 2003/07/21 14:48:45 Ian.Mayo
// Re-import Java files to keep correct line spacing
//
// Revision 1.5 2003-03-19 15:37:25+00 ian_mayo
// improvements according to IntelliJ inspector
//
// Revision 1.4 2003-01-22 12:03:15+00 ian_mayo
// Create default location (centre) at zero depth
//
// Revision 1.3 2002-05-28 09:25:09+01 ian_mayo
// after switch to new system
//
// Revision 1.1 2002-05-28 09:11:48+01 ian_mayo
// Initial revision
//
// Revision 1.2 2002-05-08 16:05:36+01 ian_mayo
// Fire extended event after creation
//
// Revision 1.1 2002-04-23 12:28:49+01 ian_mayo
// Initial revision
//
// Revision 1.1 2002-01-24 14:23:37+00 administrator
// Reflect change in Layers reformat and modified events which take an indication of which layer has been modified - a step towards per-layer graphics repaints
//
// Revision 1.0 2001-07-17 08:41:16+01 administrator
// Initial revision
//
// Revision 1.1 2001-01-03 13:40:27+00 novatech
// Initial revision
//
// Revision 1.1.1.1 2000/12/12 20:48:56 ianmayo
// initial import of files
//
// Revision 1.6 2000-11-24 10:54:28+00 ian_mayo
// handle the image for the button, and check that we have a working plot (with bounds) before we add shape
//
// Revision 1.5 2000-11-22 10:51:16+00 ian_mayo
// stop it being abstract, make use of it
//
// Revision 1.4 2000-11-02 16:45:50+00 ian_mayo
// changing Layer into Interface, replaced by BaseLayer, also changed TrackWrapper so that it implements Layer, and as we read in files, we put them into track and add Track to Layers, not to Layer then Layers
//
// Revision 1.3 1999-11-26 15:51:40+00 ian_mayo
// tidying up
//
// Revision 1.2 1999-11-11 18:23:03+00 ian_mayo
// new classes, to allow creation of shapes from palette
//
package Debrief.Tools.Palette;
import javax.swing.JOptionPane;
import Debrief.Wrappers.LabelWrapper;
import MWC.GUI.BaseLayer;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.ToolParent;
import MWC.GUI.Properties.PropertiesPanel;
import MWC.GUI.Tools.Action;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldLocation;
public final class CreateLabel extends CoreCreateShape
{
/////////////////////////////////////////////////////////////
// member variables
////////////////////////////////////////////////////////////
/** the properties panel
*/
private PropertiesPanel _thePanel;
/////////////////////////////////////////////////////////////
// constructor
////////////////////////////////////////////////////////////
/** constructor for label
* @param theParent parent where we can change cursor
* @param thePanel panel
*/
public CreateLabel(final ToolParent theParent,
final PropertiesPanel thePanel,
final Layers theData,
final BoundsProvider bounds,
final String theName,
final String theImage)
{
super(theParent, theName, theImage,theData,bounds);
_thePanel = thePanel;
}
/** get the current visible data area
*
*/
/////////////////////////////////////////////////////////////
// member functions
////////////////////////////////////////////////////////////
public final Action getData()
{
final Action res;
final WorldArea wa = getBounds();
boolean userSelected=false;
if(wa != null)
{
// put the label in the centre of the plot (at the surface)
final WorldLocation centre = wa.getCentreAtSurface();
final LabelWrapper theWrapper = new LabelWrapper("blank label",
centre,
MWC.GUI.Properties.DebriefColors.ORANGE);
final Layer theLayer;
String layerToAddTo = getSelectedLayer();
final boolean wantsUserSelected =
CoreCreateShape.USER_SELECTED_LAYER_COMMAND.equals(layerToAddTo);
if (wantsUserSelected || Layers.NEW_LAYER_COMMAND.equals(layerToAddTo))
{
userSelected = true;
if (wantsUserSelected)
{
layerToAddTo = getLayerName();
}
else
{
String txt = JOptionPane.showInputDialog(null,
"Enter name for new layer");
// check there's something there
if (txt != null && !txt.isEmpty())
{
layerToAddTo = txt;
// create base layer
final Layer newLayer = new BaseLayer();
newLayer.setName(layerToAddTo);
// add to layers object
_theData.addThisLayer(newLayer);
}
}
}
// do we know the target layer name?
if (layerToAddTo != null)
{
theLayer = _theData.findLayer(layerToAddTo);
}
else
{
theLayer = null;
}
// do we know the target layer?
if(theLayer == null)
{
// no, did the user choose to not select a layer?
if(userSelected)
{
// works for debrief-legacy
// user cancelled.
JOptionPane.showMessageDialog(null,
"A layer can only be created if a name is provided. "
+ "The shape has not been created", "Error",
JOptionPane.ERROR_MESSAGE);
res = null;
}
else
{
// create a default layer, for the item to go into
final BaseLayer tmpLayer = new BaseLayer();
tmpLayer.setName("Misc");
_theData.addThisLayer(tmpLayer);
// action to put the shape into this new layer
res = new CreateLabelAction(_thePanel, tmpLayer, theWrapper, _theData);
}
}
else
{
res = new CreateLabelAction(_thePanel, theLayer, theWrapper, _theData);
}
}
else
{
// we haven't got an area, inform the user
MWC.GUI.Dialogs.DialogFactory.showMessage("Create Feature",
"Sorry, we can't create a shape until the area is defined. Try adding a coastline first");
res = null;
}
return res;
}
///////////////////////////////////////////////////////
// store action information
///////////////////////////////////////////////////////
static public final class CreateLabelAction implements Action
{
/** the panel we are going to show the initial editor in
*/
final PropertiesPanel _thePanel;
final Layer _theLayer;
final Debrief.Wrappers.LabelWrapper _theShape;
final private Layers _theData;
public CreateLabelAction(final PropertiesPanel thePanel,
final Layer theLayer,
final LabelWrapper theShape,
final Layers theData)
{
_thePanel = thePanel;
_theLayer = theLayer;
_theShape = theShape;
_theData = theData;
}
/** specify is this is an operation which can be undone
*/
public final boolean isUndoable()
{
return true;
}
/** specify is this is an operation which can be redone
*/
public final boolean isRedoable()
{
return true;
}
/** return string describing this operation
* @return String describing this operation
*/
public final String toString()
{
return "New shape:" + _theShape.getName();
}
/** take the shape away from the layer
*/
public final void undo()
{
_theLayer.removeElement(_theShape);
// and fire the extended event
_theData.fireExtended();
}
/** make it so!
*/
public final void execute()
{
// add the Shape to the layer, and put it
// in the property editor
_theLayer.add(_theShape);
if(_thePanel != null)
_thePanel.addEditor(_theShape.getInfo(), _theLayer);
// and fire the extended event
_theData.fireExtended(_theShape, _theLayer);
}
}
}
| org.mwc.debrief.legacy/src/Debrief/Tools/Palette/CreateLabel.java | /*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
// $RCSfile: CreateLabel.java,v $
// @author $Author: Ian.Mayo $
// @version $Revision: 1.3 $
// $Log: CreateLabel.java,v $
// Revision 1.3 2005/12/13 09:04:52 Ian.Mayo
// Tidying - as recommended by Eclipse
//
// Revision 1.2 2005/07/08 14:18:34 Ian.Mayo
// Make utility methods more accessible
//
// Revision 1.1.1.2 2003/07/21 14:48:45 Ian.Mayo
// Re-import Java files to keep correct line spacing
//
// Revision 1.5 2003-03-19 15:37:25+00 ian_mayo
// improvements according to IntelliJ inspector
//
// Revision 1.4 2003-01-22 12:03:15+00 ian_mayo
// Create default location (centre) at zero depth
//
// Revision 1.3 2002-05-28 09:25:09+01 ian_mayo
// after switch to new system
//
// Revision 1.1 2002-05-28 09:11:48+01 ian_mayo
// Initial revision
//
// Revision 1.2 2002-05-08 16:05:36+01 ian_mayo
// Fire extended event after creation
//
// Revision 1.1 2002-04-23 12:28:49+01 ian_mayo
// Initial revision
//
// Revision 1.1 2002-01-24 14:23:37+00 administrator
// Reflect change in Layers reformat and modified events which take an indication of which layer has been modified - a step towards per-layer graphics repaints
//
// Revision 1.0 2001-07-17 08:41:16+01 administrator
// Initial revision
//
// Revision 1.1 2001-01-03 13:40:27+00 novatech
// Initial revision
//
// Revision 1.1.1.1 2000/12/12 20:48:56 ianmayo
// initial import of files
//
// Revision 1.6 2000-11-24 10:54:28+00 ian_mayo
// handle the image for the button, and check that we have a working plot (with bounds) before we add shape
//
// Revision 1.5 2000-11-22 10:51:16+00 ian_mayo
// stop it being abstract, make use of it
//
// Revision 1.4 2000-11-02 16:45:50+00 ian_mayo
// changing Layer into Interface, replaced by BaseLayer, also changed TrackWrapper so that it implements Layer, and as we read in files, we put them into track and add Track to Layers, not to Layer then Layers
//
// Revision 1.3 1999-11-26 15:51:40+00 ian_mayo
// tidying up
//
// Revision 1.2 1999-11-11 18:23:03+00 ian_mayo
// new classes, to allow creation of shapes from palette
//
package Debrief.Tools.Palette;
import javax.swing.JOptionPane;
import Debrief.Wrappers.LabelWrapper;
import MWC.GUI.BaseLayer;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.ToolParent;
import MWC.GUI.Properties.PropertiesPanel;
import MWC.GUI.Tools.Action;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldLocation;
public final class CreateLabel extends CoreCreateShape
{
/////////////////////////////////////////////////////////////
// member variables
////////////////////////////////////////////////////////////
/** the properties panel
*/
private PropertiesPanel _thePanel;
/////////////////////////////////////////////////////////////
// constructor
////////////////////////////////////////////////////////////
/** constructor for label
* @param theParent parent where we can change cursor
* @param thePanel panel
*/
public CreateLabel(final ToolParent theParent,
final PropertiesPanel thePanel,
final Layers theData,
final BoundsProvider bounds,
final String theName,
final String theImage)
{
super(theParent, theName, theImage,theData,bounds);
_thePanel = thePanel;
}
/** get the current visible data area
*
*/
/////////////////////////////////////////////////////////////
// member functions
////////////////////////////////////////////////////////////
public final Action getData()
{
Action res = null;
WorldArea wa = getBounds();
boolean userSelected=false;
if(wa != null)
{
// put the label in the centre of the plot (at the surface)
final WorldLocation centre = wa.getCentreAtSurface();
final LabelWrapper theWrapper = new LabelWrapper("blank label",
centre,
MWC.GUI.Properties.DebriefColors.ORANGE);
Layer theLayer = null;
String layerToAddTo = getSelectedLayer();
final boolean wantsUserSelected =
CoreCreateShape.USER_SELECTED_LAYER_COMMAND.equals(layerToAddTo);
if (wantsUserSelected || Layers.NEW_LAYER_COMMAND.equals(layerToAddTo))
{
userSelected = true;
if (wantsUserSelected)
{
layerToAddTo = getLayerName();
}
else
{
String txt = JOptionPane.showInputDialog(null,
"Enter name for new layer");
// check there's something there
if (txt != null && !txt.isEmpty())
{
layerToAddTo = txt;
// create base layer
final Layer newLayer = new BaseLayer();
newLayer.setName(layerToAddTo);
// add to layers object
_theData.addThisLayer(newLayer);
}
}
if (layerToAddTo != null)
{
theLayer = _theData.findLayer(layerToAddTo);
}
}
if (layerToAddTo != null)
{
theLayer = _theData.findLayer(layerToAddTo);
}
if (userSelected && theLayer == null)
{
// user cancelled.
JOptionPane.showMessageDialog(null,
"A layer can only be created if a name is provided. "
+ "The shape has not been created", "Error",
JOptionPane.ERROR_MESSAGE);
}
// works for debrief-legacy
else
{
if (theLayer == null)
{
theLayer = new BaseLayer();
theLayer.setName("Misc");
_theData.addThisLayer(theLayer);
}
}
if(theLayer!=null) {
res = new CreateLabelAction(_thePanel,
theLayer,
theWrapper,
_theData);
res = new CreateLabelAction(_thePanel, theLayer, theWrapper, _theData);
}
}
else
{
// we haven't got an area, inform the user
MWC.GUI.Dialogs.DialogFactory.showMessage("Create Feature",
"Sorry, we can't create a shape until the area is defined. Try adding a coastline first");
}
return res;
}
///////////////////////////////////////////////////////
// store action information
///////////////////////////////////////////////////////
static public final class CreateLabelAction implements Action
{
/** the panel we are going to show the initial editor in
*/
final PropertiesPanel _thePanel;
final Layer _theLayer;
final Debrief.Wrappers.LabelWrapper _theShape;
final private Layers _theData;
public CreateLabelAction(final PropertiesPanel thePanel,
final Layer theLayer,
final LabelWrapper theShape,
final Layers theData)
{
_thePanel = thePanel;
_theLayer = theLayer;
_theShape = theShape;
_theData = theData;
}
/** specify is this is an operation which can be undone
*/
public final boolean isUndoable()
{
return true;
}
/** specify is this is an operation which can be redone
*/
public final boolean isRedoable()
{
return true;
}
/** return string describing this operation
* @return String describing this operation
*/
public final String toString()
{
return "New shape:" + _theShape.getName();
}
/** take the shape away from the layer
*/
public final void undo()
{
_theLayer.removeElement(_theShape);
// and fire the extended event
_theData.fireExtended();
}
/** make it so!
*/
public final void execute()
{
// add the Shape to the layer, and put it
// in the property editor
_theLayer.add(_theShape);
if(_thePanel != null)
_thePanel.addEditor(_theShape.getInfo(), _theLayer);
// and fire the extended event
_theData.fireExtended(_theShape, _theLayer);
}
}
}
| refactor to streamline logic
| org.mwc.debrief.legacy/src/Debrief/Tools/Palette/CreateLabel.java | refactor to streamline logic | <ide><path>rg.mwc.debrief.legacy/src/Debrief/Tools/Palette/CreateLabel.java
<ide>
<ide> public final Action getData()
<ide> {
<del> Action res = null;
<del> WorldArea wa = getBounds();
<add> final Action res;
<add> final WorldArea wa = getBounds();
<ide> boolean userSelected=false;
<ide> if(wa != null)
<ide> {
<ide> final LabelWrapper theWrapper = new LabelWrapper("blank label",
<ide> centre,
<ide> MWC.GUI.Properties.DebriefColors.ORANGE);
<del> Layer theLayer = null;
<add> final Layer theLayer;
<ide> String layerToAddTo = getSelectedLayer();
<ide> final boolean wantsUserSelected =
<ide> CoreCreateShape.USER_SELECTED_LAYER_COMMAND.equals(layerToAddTo);
<ide> // add to layers object
<ide> _theData.addThisLayer(newLayer);
<ide> }
<add> }
<add> }
<add>
<add> // do we know the target layer name?
<add> if (layerToAddTo != null)
<add> {
<add> theLayer = _theData.findLayer(layerToAddTo);
<add> }
<add> else
<add> {
<add> theLayer = null;
<add> }
<add>
<add> // do we know the target layer?
<add> if(theLayer == null)
<add> {
<add> // no, did the user choose to not select a layer?
<add> if(userSelected)
<add> {
<add> // works for debrief-legacy
<add> // user cancelled.
<add> JOptionPane.showMessageDialog(null,
<add> "A layer can only be created if a name is provided. "
<add> + "The shape has not been created", "Error",
<add> JOptionPane.ERROR_MESSAGE);
<add> res = null;
<ide> }
<del> if (layerToAddTo != null)
<del> {
<del> theLayer = _theData.findLayer(layerToAddTo);
<add> else
<add> {
<add> // create a default layer, for the item to go into
<add> final BaseLayer tmpLayer = new BaseLayer();
<add> tmpLayer.setName("Misc");
<add> _theData.addThisLayer(tmpLayer);
<add>
<add> // action to put the shape into this new layer
<add> res = new CreateLabelAction(_thePanel, tmpLayer, theWrapper, _theData);
<ide> }
<ide> }
<del> if (layerToAddTo != null)
<del> {
<del> theLayer = _theData.findLayer(layerToAddTo);
<del> }
<del>
<del> if (userSelected && theLayer == null)
<del> {
<del> // user cancelled.
<del> JOptionPane.showMessageDialog(null,
<del> "A layer can only be created if a name is provided. "
<del> + "The shape has not been created", "Error",
<del> JOptionPane.ERROR_MESSAGE);
<del>
<del> }
<del> // works for debrief-legacy
<ide> else
<ide> {
<del> if (theLayer == null)
<del> {
<del> theLayer = new BaseLayer();
<del> theLayer.setName("Misc");
<del> _theData.addThisLayer(theLayer);
<del> }
<del> }
<del> if(theLayer!=null) {
<del> res = new CreateLabelAction(_thePanel,
<del> theLayer,
<del> theWrapper,
<del> _theData);
<ide> res = new CreateLabelAction(_thePanel, theLayer, theWrapper, _theData);
<ide> }
<ide> }
<ide> // we haven't got an area, inform the user
<ide> MWC.GUI.Dialogs.DialogFactory.showMessage("Create Feature",
<ide> "Sorry, we can't create a shape until the area is defined. Try adding a coastline first");
<add> res = null;
<ide> }
<ide> return res;
<ide> } |
|
Java | apache-2.0 | 8bdeb9aa2e3da013edcd7641dcd1a041b179b106 | 0 | futurice/freesound-android,futurice/freesound-android | /*
* Copyright 2016 Futurice GmbH
*
* 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.futurice.freesound.utils;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.Objects;
/**
* Static class that provides helper methods to check preconditions.
*/
public final class Preconditions {
/**
* Checks if the reference is not null.
*
* @param reference an object reference
* @return the non-null reference
* @throws NullPointerException if {@code reference} is null
*/
@NonNull
public static <T> T get(@Nullable final T reference) {
if (reference == null) {
throw new NullPointerException("Assertion for a nonnull object failed.");
}
return reference;
}
/**
* Checks if the reference is not null.
*
* @param reference object reference
* @return non-null reference
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(final T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Checks if the reference is not null.
*
* @param reference object reference
* @param errorMessage message used if the check fails
* @return non-null reference
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(final T reference, @NonNull final String errorMessage) {
if (reference == null) {
throw new NullPointerException(get(errorMessage));
}
return reference;
}
/**
* Checks the truth of an expression for an argument.
*
* @param expression a boolean expression
* @param errorMessage message used if the check fails
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, @NonNull final String errorMessage) {
if (!expression) {
throw new IllegalArgumentException(get(errorMessage));
}
}
/**
* Asserts that the current thread is a worker thread.
*/
public static void assertWorkerThread() {
if (isMainThread()) {
throw new IllegalStateException(
"This task must be run on a worker thread and not on the Main thread.");
}
}
/**
* Asserts that the current thread is the Main Thread.
*/
public static void assertUiThread() {
if (!isMainThread()) {
throw new IllegalStateException(
"This task must be run on the Main thread and not on a worker thread.");
}
}
private static boolean isMainThread() {
return Objects.equals(Looper.getMainLooper(), Looper.myLooper());
}
private Preconditions() {
throw new AssertionError("No instances allowed");
}
}
| app/src/main/java/com/futurice/freesound/utils/Preconditions.java | /*
* Copyright 2016 Futurice GmbH
*
* 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.futurice.freesound.utils;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.Objects;
/**
* Static class that provides helper methods to check preconditions.
*/
public final class Preconditions {
private Preconditions() {
throw new AssertionError("Don't create instances of this object");
}
/**
* Checks if the reference is not null.
*
* @param reference an object reference
* @return the non-null reference
* @throws NullPointerException if {@code reference} is null
*/
@NonNull
public static <T> T get(@Nullable final T reference) {
if (reference == null) {
throw new NullPointerException("Assertion for a nonnull object failed.");
}
return reference;
}
/**
* Checks if the reference is not null.
*
* @param reference object reference
* @return non-null reference
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(final T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Checks if the reference is not null.
*
* @param reference object reference
* @param errorMessage message used if the check fails
* @return non-null reference
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(final T reference, @NonNull final String errorMessage) {
if (reference == null) {
throw new NullPointerException(get(errorMessage));
}
return reference;
}
/**
* Checks the truth of an expression for an argument.
*
* @param expression a boolean expression
* @param errorMessage message used if the check fails
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, @NonNull final String errorMessage) {
if (!expression) {
throw new IllegalArgumentException(get(errorMessage));
}
}
/**
* Asserts that the current thread is a worker thread.
*/
public static void assertWorkerThread() {
if (isMainThread()) {
throw new IllegalStateException(
"This task must be run on a worker thread and not on the Main thread.");
}
}
/**
* Asserts that the current thread is the Main Thread.
*/
public static void assertUiThread() {
if (!isMainThread()) {
throw new IllegalStateException(
"This task must be run on the Main thread and not on a worker thread.");
}
}
private static boolean isMainThread() {
return Objects.equals(Looper.getMainLooper(), Looper.myLooper());
}
}
| Move the private constructor to the bottom of the class in Preconditions
| app/src/main/java/com/futurice/freesound/utils/Preconditions.java | Move the private constructor to the bottom of the class in Preconditions | <ide><path>pp/src/main/java/com/futurice/freesound/utils/Preconditions.java
<ide> * Static class that provides helper methods to check preconditions.
<ide> */
<ide> public final class Preconditions {
<del>
<del> private Preconditions() {
<del> throw new AssertionError("Don't create instances of this object");
<del> }
<ide>
<ide> /**
<ide> * Checks if the reference is not null.
<ide> private static boolean isMainThread() {
<ide> return Objects.equals(Looper.getMainLooper(), Looper.myLooper());
<ide> }
<add>
<add> private Preconditions() {
<add> throw new AssertionError("No instances allowed");
<add> }
<ide> } |
|
Java | apache-2.0 | 6d33d57821f32bbb21ea303685e2df3452c3949f | 0 | SciGaP/seagrid-rich-client,SciGaP/seagrid-rich-client,SciGaP/seagrid-rich-client | package org.seagrid.desktop.ui.login;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class LoginWindow extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("/views/login/login.fxml"));
primaryStage.setTitle("SEAGrid Desktop Client - Login");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(true);
primaryStage.setOnCloseRequest(t -> {
Platform.exit();
System.exit(0);
});
primaryStage.show();
}
public void displayLoginAndWait() throws IOException {
Stage primaryStage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/views/login/login.fxml"));
primaryStage.setTitle("SEAGrid Desktop Client - Login");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(true);
primaryStage.setAlwaysOnTop(true);
primaryStage.setOnCloseRequest(t -> {
Platform.exit();
System.exit(0);
});
primaryStage.showAndWait();
}
public static void main(String[] args) {
launch(args);
}
}
| src/main/java/org/seagrid/desktop/ui/login/LoginWindow.java | package org.seagrid.desktop.ui.login;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class LoginWindow extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("/views/login/login.fxml"));
primaryStage.setTitle("SEAGrid Desktop Client - Login");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(true);
primaryStage.setOnCloseRequest(t -> {
Platform.exit();
System.exit(0);
});
primaryStage.show();
}
public void displayLoginAndWait() throws IOException {
Stage primaryStage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/views/login/login.fxml"));
primaryStage.setTitle("SEAGrid Desktop Client - Login");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(true);
primaryStage.setOnCloseRequest(t -> {
Platform.exit();
System.exit(0);
});
primaryStage.showAndWait();
}
public static void main(String[] args) {
launch(args);
}
}
| not showing error in refresh token retreival AIRAVATA-2206
| src/main/java/org/seagrid/desktop/ui/login/LoginWindow.java | not showing error in refresh token retreival AIRAVATA-2206 | <ide><path>rc/main/java/org/seagrid/desktop/ui/login/LoginWindow.java
<ide> primaryStage.setTitle("SEAGrid Desktop Client - Login");
<ide> primaryStage.setScene(new Scene(root));
<ide> primaryStage.setResizable(true);
<add> primaryStage.setAlwaysOnTop(true);
<ide> primaryStage.setOnCloseRequest(t -> {
<ide> Platform.exit();
<ide> System.exit(0); |
|
Java | apache-2.0 | 531ebe8fe085c5fe5605b0e02ca11c415d29a544 | 0 | binarytemple/mybatis-all-syncing-test,ekirkilevics/iBatis | /*
* Copyright 2009-2012 The MyBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.jdbc;
import org.apache.ibatis.BaseDataTest;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.io.Resources;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class ScriptRunnerTest extends BaseDataTest {
@Test
@Ignore("This fails with HSQLDB 2.0 due to the create index statements in the schema script")
public void shouldRunScriptsBySendingFullScriptAtOnce() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setSendFullScript(true);
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runJPetStoreScripts(runner);
assertProductsTableExistsAndLoaded();
}
@Test
public void shouldRunScriptsUsingConnection() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runJPetStoreScripts(runner);
assertProductsTableExistsAndLoaded();
}
@Test
public void shouldRunScriptsUsingProperties() throws Exception {
Properties props = Resources.getResourceAsProperties(JPETSTORE_PROPERTIES);
DataSource dataSource = new UnpooledDataSource(
props.getProperty("driver"),
props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runJPetStoreScripts(runner);
assertProductsTableExistsAndLoaded();
}
@Test
public void shouldReturnWarningIfEndOfLineTerminatorNotFound() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
String resource = "org/apache/ibatis/jdbc/ScriptMissingEOLTerminator.sql";
Reader reader = Resources.getResourceAsReader(resource);
try {
runner.runScript(reader);
fail("Expected script runner to fail due to missing end of line terminator.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("end-of-line terminator"));
}
}
@Test
public void commentAferStatementDelimiterShouldNotCauseRunnerFail() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setAutoCommit(true);
runner.setStopOnError(true);
String resource = "org/apache/ibatis/jdbc/ScriptCommentAfterEOLTerminator.sql";
Reader reader = Resources.getResourceAsReader(resource);
try {
runner.runScript(reader);
} catch (Exception e) {
fail(e.getMessage());
}
}
private void runJPetStoreScripts(ScriptRunner runner) throws IOException, SQLException {
runScript(runner, JPETSTORE_DDL);
runScript(runner, JPETSTORE_DATA);
}
private void assertProductsTableExistsAndLoaded() throws IOException, SQLException {
PooledDataSource ds = createPooledDataSource(JPETSTORE_PROPERTIES);
try {
Connection conn = ds.getConnection();
SqlRunner executor = new SqlRunner(conn);
List<Map<String, Object>> products = executor.selectAll("SELECT * FROM PRODUCT");
assertEquals(16, products.size());
} finally {
ds.forceCloseAll();
}
}
}
| src/test/java/org/apache/ibatis/jdbc/ScriptRunnerTest.java | /*
* Copyright 2009-2012 The MyBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.jdbc;
import org.apache.ibatis.BaseDataTest;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.io.Resources;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class ScriptRunnerTest extends BaseDataTest {
@Test
@Ignore("This fails with HSQLDB 2.0 due to the create index statements in the schema script")
public void shouldRunScriptsBySendingFullScriptAtOnce() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setSendFullScript(true);
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runJPetStoreScripts(runner);
assertProductsTableExistsAndLoaded();
}
@Test
public void shouldRunScriptsUsingConnection() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runJPetStoreScripts(runner);
assertProductsTableExistsAndLoaded();
}
@Test
public void shouldRunScriptsUsingProperties() throws Exception {
Properties props = Resources.getResourceAsProperties(JPETSTORE_PROPERTIES);
DataSource dataSource = new UnpooledDataSource(
props.getProperty("driver"),
props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runJPetStoreScripts(runner);
assertProductsTableExistsAndLoaded();
}
@Test
public void shouldReturnWarningIfEndOfLineTerminatorNotFound() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
String resource = "org/apache/ibatis/jdbc/ScriptMissingEOLTerminator.sql";
Reader reader = Resources.getResourceAsReader(resource);
try {
runner.runScript(reader);
fail("Expected script runner to fail due to missing end of line terminator.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("end-of-line terminator"));
}
}
@Test
public void commentAferStatementDelimiterShouldNotCauseRunnerFail() throws Exception {
DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
Connection conn = ds.getConnection();
ScriptRunner runner = new ScriptRunner(conn);
runner.setAutoCommit(true);
runner.setStopOnError(true);
String resource = "org/apache/ibatis/jdbc/ScriptCommentAfterEOLTerminator.sql";
Reader reader = Resources.getResourceAsReader(resource);
try {
runner.runScript(reader);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private void runJPetStoreScripts(ScriptRunner runner) throws IOException, SQLException {
runScript(runner, JPETSTORE_DDL);
runScript(runner, JPETSTORE_DATA);
}
private void assertProductsTableExistsAndLoaded() throws IOException, SQLException {
PooledDataSource ds = createPooledDataSource(JPETSTORE_PROPERTIES);
try {
Connection conn = ds.getConnection();
SqlRunner executor = new SqlRunner(conn);
List<Map<String, Object>> products = executor.selectAll("SELECT * FROM PRODUCT");
assertEquals(16, products.size());
} finally {
ds.forceCloseAll();
}
}
}
| dropped useless testcase
git-svn-id: 38b70485df25d5e096a1845b40b72a0bf0ca9ea6@5177 6a4a4fef-ff2a-56b0-fee9-946765563393
| src/test/java/org/apache/ibatis/jdbc/ScriptRunnerTest.java | dropped useless testcase | <ide><path>rc/test/java/org/apache/ibatis/jdbc/ScriptRunnerTest.java
<ide> try {
<ide> runner.runScript(reader);
<ide> } catch (Exception e) {
<del> e.printStackTrace();
<ide> fail(e.getMessage());
<ide> }
<ide> } |
|
Java | apache-2.0 | 7463017a27b6c9ea3be1a1fb14b4e7c5efacf804 | 0 | metaborg/jsglr,metaborg/jsglr,metaborg/jsglr,metaborg/jsglr | package org.spoofax.jsglr2.inputstack;
import org.spoofax.jsglr2.inputstack.incremental.AbstractInputStack;
public class InputStack extends AbstractInputStack {
int currentChar; // Current ASCII char in range [0, 256]
public InputStack(String inputString) {
super(inputString);
currentChar = getChar(currentOffset);
}
@Override public InputStack clone() {
InputStack clone = new InputStack(inputString);
clone.currentChar = currentChar;
clone.currentOffset = currentOffset;
return clone;
}
@Override public boolean hasNext() {
return currentOffset <= inputLength;
}
@Override public void next() {
currentOffset++;
currentChar = getChar(currentOffset);
}
@Override public int getChar() {
return currentChar;
}
}
| org.spoofax.jsglr2/src/main/java/org/spoofax/jsglr2/inputstack/InputStack.java | package org.spoofax.jsglr2.inputstack;
import org.spoofax.jsglr2.inputstack.incremental.AbstractInputStack;
public class InputStack extends AbstractInputStack {
int currentChar; // Current ASCII char in range [0, 256]
public InputStack(String inputString) {
super(inputString);
}
@Override public InputStack clone() {
InputStack clone = new InputStack(inputString);
clone.currentChar = currentChar;
clone.currentOffset = currentOffset;
return clone;
}
@Override public boolean hasNext() {
return currentOffset <= inputLength;
}
@Override public void next() {
currentOffset++;
currentChar = getChar(currentOffset);
}
@Override public int getChar() {
return currentChar;
}
}
| Correctly set `currentChar` for first character in InputStack
| org.spoofax.jsglr2/src/main/java/org/spoofax/jsglr2/inputstack/InputStack.java | Correctly set `currentChar` for first character in InputStack | <ide><path>rg.spoofax.jsglr2/src/main/java/org/spoofax/jsglr2/inputstack/InputStack.java
<ide>
<ide> public InputStack(String inputString) {
<ide> super(inputString);
<add> currentChar = getChar(currentOffset);
<ide> }
<ide>
<ide> @Override public InputStack clone() { |
|
Java | apache-2.0 | c9f94e3dfd9a9d078e1a78446b6526330d84e725 | 0 | carlphilipp/chicago-commutes,carlphilipp/chicago-commutes,carlphilipp/chicago-commutes | /**
* Copyright 2016 Carl-Philipp Harmant
* <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.
*/
package fr.cph.chicago.app.activity;
import android.app.Activity;
import android.app.FragmentManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.annimon.stream.Stream;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindDrawable;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.cph.chicago.R;
import fr.cph.chicago.app.App;
import fr.cph.chicago.app.listener.TrainMapOnCameraChangeListener;
import fr.cph.chicago.app.task.LoadTrainFollowTask;
import fr.cph.chicago.app.task.LoadTrainPositionTask;
import fr.cph.chicago.data.DataHolder;
import fr.cph.chicago.data.TrainData;
import fr.cph.chicago.entity.Position;
import fr.cph.chicago.entity.Train;
import fr.cph.chicago.entity.enumeration.TrainLine;
import fr.cph.chicago.util.Util;
/**
* @author Carl-Philipp Harmant
* @version 1
*/
public class TrainMapActivity extends Activity {
@BindView(android.R.id.content) ViewGroup viewGroup;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.map) RelativeLayout layout;
@BindString(R.string.bundle_train_line) String bundleTrainLine;
@BindString(R.string.analytics_train_map) String analyticsTrainMap;
@BindDrawable(R.drawable.ic_arrow_back_white_24dp) Drawable arrowBackWhite;
private MapFragment mapFragment;
private Marker selectedMarker;
private Map<Marker, View> views;
private String line;
private Map<Marker, Boolean> status;
private List<Marker> markers;
private TrainData trainData;
private TrainMapOnCameraChangeListener trainListener;
private boolean centerMap = true;
private boolean refreshingInfoWindow = false;
private boolean drawLine = true;
public TrainMapActivity() {
this.views = new HashMap<>();
}
@Override
public final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.checkTrainData(this);
if (!this.isFinishing()) {
MapsInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
if (savedInstanceState != null) {
line = savedInstanceState.getString(bundleTrainLine);
} else {
line = getIntent().getExtras().getString(bundleTrainLine);
}
// Init data
initData();
// Init toolbar
setToolbar();
// Google analytics
Util.trackScreen(getApplicationContext(), analyticsTrainMap);
}
}
private void initData() {
// Load data
final DataHolder dataHolder = DataHolder.getInstance();
trainData = dataHolder.getTrainData();
markers = new ArrayList<>();
status = new HashMap<>();
trainListener = new TrainMapOnCameraChangeListener(getApplicationContext());
}
private void setToolbar() {
toolbar.inflateMenu(R.menu.main);
toolbar.setOnMenuItemClickListener((item -> {
new LoadTrainPositionTask(TrainMapActivity.this, line, trainData).execute(false, true);
return false;
}));
final TrainLine trainLine = TrainLine.fromXmlString(line);
Util.setWindowsColor(this, toolbar, trainLine);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setElevation(4);
}
toolbar.setNavigationIcon(arrowBackWhite);
toolbar.setOnClickListener(v -> finish());
toolbar.setTitle(trainLine.toStringWithLine());
}
@Override
public final void onStart() {
super.onStart();
if (mapFragment == null) {
final FragmentManager fm = getFragmentManager();
mapFragment = (MapFragment) fm.findFragmentById(R.id.map);
final GoogleMapOptions options = new GoogleMapOptions();
final CameraPosition camera = new CameraPosition(Util.CHICAGO, 10, 0, 0);
options.camera(camera);
mapFragment = MapFragment.newInstance(options);
mapFragment.setRetainInstance(true);
fm.beginTransaction().replace(R.id.map, mapFragment).commit();
}
}
@Override
public final void onStop() {
super.onStop();
centerMap = false;
}
@Override
public final void onResume() {
super.onResume();
mapFragment.getMapAsync(googleMap -> {
Util.setLocationOnMap(this, googleMap);
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(final Marker marker) {
return null;
}
@Override
public View getInfoContents(final Marker marker) {
if (!"".equals(marker.getSnippet())) {
final View view = views.get(marker);
if (!refreshingInfoWindow) {
selectedMarker = marker;
final String runNumber = marker.getSnippet();
new LoadTrainFollowTask(TrainMapActivity.this, view, false, trainData).execute(runNumber);
status.put(marker, false);
}
return view;
} else {
return null;
}
}
});
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(final Marker marker) {
if (!"".equals(marker.getSnippet())) {
final View view = views.get(marker);
if (!refreshingInfoWindow) {
selectedMarker = marker;
final String runNumber = marker.getSnippet();
final Boolean current = status.get(marker);
new LoadTrainFollowTask(TrainMapActivity.this, view, !current, trainData).execute(runNumber);
status.put(marker, !current);
}
}
}
});
if (Util.isNetworkAvailable(getApplicationContext())) {
new LoadTrainPositionTask(TrainMapActivity.this, line, trainData).execute(centerMap, true);
} else {
Util.showNetworkErrorMessage(layout);
}
});
}
@Override
public void onRestoreInstanceState(final Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
line = savedInstanceState.getString(bundleTrainLine);
}
@Override
public void onSaveInstanceState(final Bundle savedInstanceState) {
savedInstanceState.putString(bundleTrainLine, line);
super.onSaveInstanceState(savedInstanceState);
}
public void refreshInfoWindow() {
if (selectedMarker == null) {
return;
}
refreshingInfoWindow = true;
selectedMarker.showInfoWindow();
refreshingInfoWindow = false;
}
public void centerMapOnTrain(@NonNull final List<Train> result) {
mapFragment.getMapAsync(googleMap -> {
final Position position;
final int zoom;
if (result.size() == 1) {
position = result.get(0).getPosition();
zoom = 15;
} else {
position = Train.getBestPosition(result);
zoom = 11;
}
final LatLng latLng = new LatLng(position.getLatitude(), position.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
});
}
public void drawTrains(@NonNull final List<Train> trains) {
mapFragment.getMapAsync(googleMap -> {
if (views == null) {
views = new HashMap<>();
} else {
views.clear();
}
Stream.of(markers).peek(Marker::remove);
markers.clear();
final BitmapDescriptor bitmapDescr = trainListener.getCurrentBitmapDescriptor();
for (final Train train : trains) {
final LatLng point = new LatLng(train.getPosition().getLatitude(), train.getPosition().getLongitude());
final String title = "To " + train.getDestName();
final String snippet = Integer.toString(train.getRouteNumber());
final Marker marker = googleMap.addMarker(new MarkerOptions().position(point).title(title).snippet(snippet).icon(bitmapDescr).anchor(0.5f, 0.5f).rotation(train.getHeading()).flat(true));
markers.add(marker);
final View view = TrainMapActivity.this.getLayoutInflater().inflate(R.layout.marker_train, viewGroup, false);
final TextView title2 = (TextView) view.findViewById(R.id.title);
title2.setText(title);
final TextView color = (TextView) view.findViewById(R.id.route_color_value);
color.setBackgroundColor(TrainLine.fromXmlString(line).getColor());
views.put(marker, view);
}
trainListener.setTrainMarkers(markers);
googleMap.setOnCameraChangeListener(trainListener);
});
}
public void drawLine(@NonNull final List<Position> positions) {
if (drawLine) {
mapFragment.getMapAsync(googleMap -> {
final PolylineOptions poly = new PolylineOptions();
poly.width(7f);
poly.geodesic(true).color(TrainLine.fromXmlString(line).getColor());
Stream.of(positions)
.map(position -> new LatLng(position.getLatitude(), position.getLongitude()))
.forEach(poly::add);
googleMap.addPolyline(poly);
});
drawLine = false;
}
}
}
| src/fr/cph/chicago/app/activity/TrainMapActivity.java | /**
* Copyright 2016 Carl-Philipp Harmant
* <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.
*/
package fr.cph.chicago.app.activity;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.annimon.stream.Stream;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.cph.chicago.app.App;
import fr.cph.chicago.R;
import fr.cph.chicago.data.DataHolder;
import fr.cph.chicago.data.TrainData;
import fr.cph.chicago.entity.Position;
import fr.cph.chicago.entity.Train;
import fr.cph.chicago.entity.enumeration.TrainLine;
import fr.cph.chicago.app.listener.TrainMapOnCameraChangeListener;
import fr.cph.chicago.app.task.LoadTrainFollowTask;
import fr.cph.chicago.app.task.LoadTrainPositionTask;
import fr.cph.chicago.util.Util;
/**
* @author Carl-Philipp Harmant
* @version 1
*/
public class TrainMapActivity extends Activity {
@BindView(android.R.id.content) ViewGroup viewGroup;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.map) RelativeLayout layout;
private MapFragment mapFragment;
private Marker selectedMarker;
private Map<Marker, View> views;
private String line;
private Map<Marker, Boolean> status;
private List<Marker> markers;
private TrainData trainData;
private TrainMapOnCameraChangeListener trainListener;
private boolean centerMap = true;
private boolean refreshingInfoWindow = false;
private boolean drawLine = true;
public TrainMapActivity() {
this.views = new HashMap<>();
}
@Override
public final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.checkTrainData(this);
if (!this.isFinishing()) {
MapsInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
if (savedInstanceState != null) {
line = savedInstanceState.getString(getString(R.string.bundle_train_line));
} else {
line = getIntent().getExtras().getString(getString(R.string.bundle_train_line));
}
// Init data
initData();
// Init toolbar
setToolbar();
// Google analytics
Util.trackScreen(getApplicationContext(), getString(R.string.analytics_train_map));
}
}
private void initData() {
// Load data
final DataHolder dataHolder = DataHolder.getInstance();
trainData = dataHolder.getTrainData();
markers = new ArrayList<>();
status = new HashMap<>();
trainListener = new TrainMapOnCameraChangeListener(getApplicationContext());
}
private void setToolbar() {
toolbar.inflateMenu(R.menu.main);
toolbar.setOnMenuItemClickListener((item -> {
new LoadTrainPositionTask(TrainMapActivity.this, line, trainData).execute(false, true);
return false;
}));
final TrainLine trainLine = TrainLine.fromXmlString(line);
Util.setWindowsColor(this, toolbar, trainLine);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setElevation(4);
}
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
toolbar.setOnClickListener(v -> finish());
toolbar.setTitle(trainLine.toStringWithLine());
}
@Override
public final void onStart() {
super.onStart();
if (mapFragment == null) {
final FragmentManager fm = getFragmentManager();
mapFragment = (MapFragment) fm.findFragmentById(R.id.map);
final GoogleMapOptions options = new GoogleMapOptions();
final CameraPosition camera = new CameraPosition(Util.CHICAGO, 10, 0, 0);
options.camera(camera);
mapFragment = MapFragment.newInstance(options);
mapFragment.setRetainInstance(true);
fm.beginTransaction().replace(R.id.map, mapFragment).commit();
}
}
@Override
public final void onStop() {
super.onStop();
centerMap = false;
}
@Override
public final void onResume() {
super.onResume();
mapFragment.getMapAsync(googleMap -> {
Util.setLocationOnMap(this, googleMap);
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(final Marker marker) {
return null;
}
@Override
public View getInfoContents(final Marker marker) {
if (!"".equals(marker.getSnippet())) {
final View view = views.get(marker);
if (!refreshingInfoWindow) {
selectedMarker = marker;
final String runNumber = marker.getSnippet();
new LoadTrainFollowTask(TrainMapActivity.this, view, false, trainData).execute(runNumber);
status.put(marker, false);
}
return view;
} else {
return null;
}
}
});
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(final Marker marker) {
if (!"".equals(marker.getSnippet())) {
final View view = views.get(marker);
if (!refreshingInfoWindow) {
selectedMarker = marker;
final String runNumber = marker.getSnippet();
final Boolean current = status.get(marker);
new LoadTrainFollowTask(TrainMapActivity.this, view, !current, trainData).execute(runNumber);
status.put(marker, !current);
}
}
}
});
if (Util.isNetworkAvailable(getApplicationContext())) {
new LoadTrainPositionTask(TrainMapActivity.this, line, trainData).execute(centerMap, true);
} else {
Util.showNetworkErrorMessage(layout);
}
});
}
@Override
public void onRestoreInstanceState(final Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
line = savedInstanceState.getString(getString(R.string.bundle_train_line));
}
@Override
public void onSaveInstanceState(final Bundle savedInstanceState) {
savedInstanceState.putString(getString(R.string.bundle_train_line), line);
super.onSaveInstanceState(savedInstanceState);
}
public void refreshInfoWindow() {
if (selectedMarker == null) {
return;
}
refreshingInfoWindow = true;
selectedMarker.showInfoWindow();
refreshingInfoWindow = false;
}
public void centerMapOnTrain(@NonNull final List<Train> result) {
mapFragment.getMapAsync(googleMap -> {
final Position position;
final int zoom;
if (result.size() == 1) {
position = result.get(0).getPosition();
zoom = 15;
} else {
position = Train.getBestPosition(result);
zoom = 11;
}
final LatLng latLng = new LatLng(position.getLatitude(), position.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
});
}
public void drawTrains(@NonNull final List<Train> trains) {
mapFragment.getMapAsync(googleMap -> {
if (views == null) {
views = new HashMap<>();
} else {
views.clear();
}
for (final Marker marker : markers) {
marker.remove();
}
markers.clear();
final BitmapDescriptor bitmapDescr = trainListener.getCurrentBitmapDescriptor();
for (final Train train : trains) {
final LatLng point = new LatLng(train.getPosition().getLatitude(), train.getPosition().getLongitude());
final String title = "To " + train.getDestName();
final String snippet = Integer.toString(train.getRouteNumber());
final Marker marker = googleMap.addMarker(new MarkerOptions().position(point).title(title).snippet(snippet).icon(bitmapDescr).anchor(0.5f, 0.5f).rotation(train.getHeading()).flat(true));
markers.add(marker);
final View view = TrainMapActivity.this.getLayoutInflater().inflate(R.layout.marker_train, viewGroup, false);
final TextView title2 = (TextView) view.findViewById(R.id.title);
title2.setText(title);
final TextView color = (TextView) view.findViewById(R.id.route_color_value);
color.setBackgroundColor(TrainLine.fromXmlString(line).getColor());
views.put(marker, view);
}
trainListener.setTrainMarkers(markers);
googleMap.setOnCameraChangeListener(trainListener);
});
}
public void drawLine(@NonNull final List<Position> positions) {
if (drawLine) {
mapFragment.getMapAsync(googleMap -> {
final PolylineOptions poly = new PolylineOptions();
poly.width(7f);
poly.geodesic(true).color(TrainLine.fromXmlString(line).getColor());
Stream.of(positions)
.map(position -> new LatLng(position.getLatitude(), position.getLongitude()))
.forEach(poly::add);
googleMap.addPolyline(poly);
});
drawLine = false;
}
}
}
| More butterknife in train map activity
| src/fr/cph/chicago/app/activity/TrainMapActivity.java | More butterknife in train map activity | <ide><path>rc/fr/cph/chicago/app/activity/TrainMapActivity.java
<ide>
<ide> import android.app.Activity;
<ide> import android.app.FragmentManager;
<add>import android.graphics.drawable.Drawable;
<ide> import android.os.Build;
<ide> import android.os.Bundle;
<ide> import android.support.annotation.NonNull;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import butterknife.BindDrawable;
<add>import butterknife.BindString;
<ide> import butterknife.BindView;
<ide> import butterknife.ButterKnife;
<add>import fr.cph.chicago.R;
<ide> import fr.cph.chicago.app.App;
<del>import fr.cph.chicago.R;
<add>import fr.cph.chicago.app.listener.TrainMapOnCameraChangeListener;
<add>import fr.cph.chicago.app.task.LoadTrainFollowTask;
<add>import fr.cph.chicago.app.task.LoadTrainPositionTask;
<ide> import fr.cph.chicago.data.DataHolder;
<ide> import fr.cph.chicago.data.TrainData;
<ide> import fr.cph.chicago.entity.Position;
<ide> import fr.cph.chicago.entity.Train;
<ide> import fr.cph.chicago.entity.enumeration.TrainLine;
<del>import fr.cph.chicago.app.listener.TrainMapOnCameraChangeListener;
<del>import fr.cph.chicago.app.task.LoadTrainFollowTask;
<del>import fr.cph.chicago.app.task.LoadTrainPositionTask;
<ide> import fr.cph.chicago.util.Util;
<ide>
<ide> /**
<ide> @BindView(android.R.id.content) ViewGroup viewGroup;
<ide> @BindView(R.id.toolbar) Toolbar toolbar;
<ide> @BindView(R.id.map) RelativeLayout layout;
<add>
<add> @BindString(R.string.bundle_train_line) String bundleTrainLine;
<add> @BindString(R.string.analytics_train_map) String analyticsTrainMap;
<add>
<add> @BindDrawable(R.drawable.ic_arrow_back_white_24dp) Drawable arrowBackWhite;
<ide>
<ide> private MapFragment mapFragment;
<ide> private Marker selectedMarker;
<ide> ButterKnife.bind(this);
<ide>
<ide> if (savedInstanceState != null) {
<del> line = savedInstanceState.getString(getString(R.string.bundle_train_line));
<add> line = savedInstanceState.getString(bundleTrainLine);
<ide> } else {
<del> line = getIntent().getExtras().getString(getString(R.string.bundle_train_line));
<add> line = getIntent().getExtras().getString(bundleTrainLine);
<ide> }
<ide>
<ide> // Init data
<ide> setToolbar();
<ide>
<ide> // Google analytics
<del> Util.trackScreen(getApplicationContext(), getString(R.string.analytics_train_map));
<add> Util.trackScreen(getApplicationContext(), analyticsTrainMap);
<ide> }
<ide> }
<ide>
<ide> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
<ide> toolbar.setElevation(4);
<ide> }
<del> toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
<add> toolbar.setNavigationIcon(arrowBackWhite);
<ide> toolbar.setOnClickListener(v -> finish());
<ide>
<ide> toolbar.setTitle(trainLine.toStringWithLine());
<ide> @Override
<ide> public void onRestoreInstanceState(final Bundle savedInstanceState) {
<ide> super.onRestoreInstanceState(savedInstanceState);
<del> line = savedInstanceState.getString(getString(R.string.bundle_train_line));
<add> line = savedInstanceState.getString(bundleTrainLine);
<ide> }
<ide>
<ide> @Override
<ide> public void onSaveInstanceState(final Bundle savedInstanceState) {
<del> savedInstanceState.putString(getString(R.string.bundle_train_line), line);
<add> savedInstanceState.putString(bundleTrainLine, line);
<ide> super.onSaveInstanceState(savedInstanceState);
<ide> }
<ide>
<ide> } else {
<ide> views.clear();
<ide> }
<del> for (final Marker marker : markers) {
<del> marker.remove();
<del> }
<add> Stream.of(markers).peek(Marker::remove);
<ide> markers.clear();
<ide> final BitmapDescriptor bitmapDescr = trainListener.getCurrentBitmapDescriptor();
<ide> for (final Train train : trains) { |
|
JavaScript | mit | b2d3e3e85cdcdf91b8d880a5fadc2958cdc399aa | 0 | cloudmine/cloudmine-js,cloudmine/cloudmine-js,cloudmine/CloudMineSDK-JavaScript,cloudmine/CloudMineSDK-JavaScript,cloudmine/cloudmine-js,cloudmine/CloudMineSDK-JavaScript | /* CloudMine JavaScript Library v0.10.x cloudmineinc.com | https://github.com/cloudmine/cloudmine-js/blob/master/LICENSE */
(function() {
var version = '0.9.20';
/**
* Construct a new WebService instance
*
* <p>Each method on the WebService instance will return an APICall object which may be used to
* access the results of the method called. You can chain multiple events together with the
* returned object (an APICall instance).
*
* <p>All events are at least guaranteed to have the callback signature: function(data, apicall).
* supported events:
* <p> 200, 201, 400, 401, 404, 409, ok, created, badrequest, unauthorized, notfound, conflict,
* success, error, complete, meta, result, abort
* <p>Event order: success callbacks, meta callbacks, result callbacks, error callbacks, complete
* callbacks
*
* <p>Example:
* <pre class='code'>
* var ws = new cloudmine.WebService({appid: "abc", apikey: "abc", appname: 'SampleApp', appversion: '1.0'});
* ws.get("MyKey").on("success", function(data, apicall) {
* console.log("MyKey value: %o", data["MyKey"]);
* }).on("error", function(data, apicall) {
* console.log("Failed to get MyKey: %o", apicall.status);
* }).on("unauthorized", function(data, apicall) {
* console.log("I'm not authorized to access 'appid'");
* }).on(404, function(data, apicall) {
* console.log("Could not find 'MyKey'");
* }).on("complete", function(data, apicall) {
* console.log("Finished get on 'MyKey':", data);
* });
* </pre>
* <p>Refer to APICall's documentation for further information on events.
*
* @param {object} Default configuration for this WebService
* @config {string} [appid] The application id for requests (Required)
* @config {string} [apikey] The api key for requests (Required)
* @config {string} [appname] An alphanumeric identifier for your app, used for stats purposes
* @config {string} [appversion] A version identifier for you app, used for stats purposes
* @config {boolean} [applevel] If true, always send requests to application.
* If false, always send requests to user-level, trigger error if not logged in.
* Otherwise, send requests to user-level if logged in.
* @config {boolean} [savelogin] If true, session token and email / username will be persisted between logins.
* @config {integer} [limit] Set the default result limit for requests
* @config {string} [sort] Set the field on which to sort results
* @config {integer} [skip] Set the default number of results to skip for requests
* @config {boolean} [count] Return the count of results for request.
* @config {string} [snippet] Run the specified code snippet during the request.
* @config {string|object} [params] Parameters to give the code snippet (applies only for code snippets)
* @config {boolean} [dontwait] Don't wait for the result of the code snippet (applies only for code snippets)
* @config {boolean} [resultsonly] Only return results from the code snippet (applies only for code snippets)
* @name WebService
* @constructor
*/
function WebService(options) {
this.options = opts(this, options);
if(!this.options.apiroot) this.options.apiroot = "https://api.cloudmine.io";
var src = this.options.appid;
if (options.savelogin) {
if (!this.options.email) this.options.email = retrieve('email', src);
if (!this.options.username) this.options.username = retrieve('username', src);
if (!this.options.session_token) this.options.session_token = retrieve('session_token', src);
}
this.options.user_token = retrieve('ut', src) || store('ut', this.keygen(), src);
}
/** @namespace WebService.prototype */
WebService.prototype = {
/**
* generic function for calling the api with a minimal set of logic and optons
* @param {string} action Action endpoint - 'text', 'data', etc
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @param {object} [data] Request body (optional). If present, will be automatically stringified.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name api
* @memberOf WebService.prototype
*/
api: function(action, options, data) {
options = opts(this, options);
var method = options.method || 'GET';
var args = {
action: action,
type: method,
options: options
};
if (options.query) {
args.query = options.query;
delete args.options.query;
}
if (data !== undefined) {
args.data = JSON.stringify(data);
}
return new APICall(args);
},
/**
* Get data from CloudMine.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|string[]|null} [keys] If set, return the specified keys, otherwise return all keys.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
get: function(keys, options) {
if (isArray(keys)) keys = keys.join(',');
else if (isObject(keys)) {
options = keys;
keys = null;
}
options = opts(this, options);
var query = keys ? server_params(options, {keys: keys}) : null;
return new APICall({
action: 'text',
type: 'GET',
options: options,
query: query
});
},
/**
* Create new data, and merge existing data.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} data An object hash where the top level properties are the keys.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name update
* @memberOf WebService.prototype
*/
/**
* Create new data, and merge existing data.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|null} key The key to affect. If given null, a random key will be assigned.
* @param {string|number|object} value The value of the object
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name update^2
* @memberOf WebService.prototype
*/
update: function(key, value, options) {
if (isObject(key)) options = value;
else {
if (!key) key = this.keygen();
var out = {};
out[key] = value;
key = out;
}
options = opts(this, options);
return new APICall({
action: 'text',
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(key)
});
},
/**
* Create or overwrite existing objects in CloudMine with the given key or keys.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} data An object hash where the top level properties are the keys.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name set
* @memberOf WebService.prototype
*/
/**
* Create or overwrite existing objects in CloudMine with the given key or keys.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|null} key The key to affect. If given null, a random key will be assigned.
* @param {string|number|object} value The object to store.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name set^2
* @memberOf WebService.prototype
*/
set: function(key, value, options) {
if (isObject(key)) options = value;
else {
if (!key) key = this.keygen();
var out = {};
out[key] = value;
key = out;
}
options = opts(this, options);
return new APICall({
action: 'text',
type: 'PUT',
options: options,
query: server_params(options),
data: JSON.stringify(key)
});
},
/**
* Destroy one or more keys on the server.
* If given null and options.all is true, delete all objects on the server.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|string[]|null} keys The keys to delete on the server.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters. Pass all:true with null keys to really delete all values, or query with a query object or string to delete objects matching query. WARNING: using the query is DANGEROUS. Triple check your query!
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
destroy: function(keys, options) {
options = opts(this, options);
var params = {};
if (keys == null && options.all === true) params = {all: true};
else if (options.query){
params = {q: convertQueryInput(options.query)};
delete options.query;
} else {
params = {keys: (isArray(keys) ? keys.join(',') : keys)};
}
return new APICall({
action: 'data',
type: 'DELETE',
options: options,
query: server_params(options, params)
});
},
/**
* Run a code snippet directly.
* Default http method is 'GET', to change the method set the method option for options.
* @param {string} snippet The name of the code snippet to run.
* @param {object} params Data to send to the code snippet (optional).
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
run: function(snippet, parameters, options) {
options = opts(this, options);
parameters = merge({}, options.params, parameters);
options.params = null;
options.snippet = null;
var call_opts = {
action: 'run/' + snippet,
type: options.method || 'GET',
options: options
};
if(call_opts.type === 'GET')
call_opts.query = parameters;
else {
call_opts.data = JSON.stringify(parameters);
}
return new APICall(call_opts);
},
/**
* Search CloudMine for text objects.
* Results may be affected by defaults and/or by the options parameter.
* @param {string} query Query parameters to search for.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
search: function(query, options) {
options = opts(this, options);
query = {q: query != null ? convertQueryInput(query) : ''}
var data = undefined;
if(options.method === "POST"){
data = JSON.stringify(query);
query = {}; // don't send q in URL
}
return new APICall({
action: 'search',
type: options.method || 'GET',
query: server_params(options, query),
data: data,
options: options
});
},
/**
* Search CloudMine for text objects.
* Results may be affected by defaults and/or by the options parameter.
* @param {string} klass The Elasticsearch __class__ you want to query.
* @param {string} query The Elasticsearch query to be executed.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
search_es: function(klass, query, options) {
options = opts(this, options);
options.version = 'v2';
return new APICall({
action: 'class/' + klass + '/elasticsearch',
type: 'POST',
data: query,
options: options
});
},
/**
* Search CloudMine explicitly querying for files.
* Note: This does not search the contents of files.
* Results may be affected by defaults and/or by the options parameter.
* @param {string} query Additional query parameters to search for.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
searchFiles: function (query, options) {
query = convertQueryInput(query);
var newQuery = '[__type__ = "file"';
if (!query || query.replace(/\s+/, '').length == 0) {
newQuery += ']';
} else if (query[0] != '[') {
newQuery += '].' + query;
} else {
newQuery += (query[1] == ']' ? '' : ', ') + query.substring(1);
}
return this.search(newQuery, options);
},
/**
* Search CloudMine user objects by custom attributes.
* Results may be affected by defaults and/or by the options parameter.
* @param {string} query Additional query parameters to search for in [key="value", key="value"] format.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name searchUsers
* @memberOf WebService.prototype
*/
/**
* Search CloudMine user objects by custom attributes.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} query Additional query parameters to search for in {key: value, key: value} format.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name searchUsers^2
* @memberOf WebService.prototype
*/
searchUsers: function(query, options) {
query = {p: query != null ? convertQueryInput(query) : ''}
options = opts(this, options);
return new APICall({
action: 'account/search',
type: 'GET',
query: server_params(options, query),
options: options
});
},
/**
* Get all user objects.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
allUsers: function(options) {
options = opts(this, options);
return new APICall({
action: 'account',
type: 'GET',
query: server_params(options),
options: options
});
},
/**
* Sends a push notification to your users.
* This requires an API key with push permission.
* @param {object} [notification] A notification object. This object can have one or more fields for dispatching the notification.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
pushNotification: function(notification, options) {
options = opts(this, options);
return new APICall({
action: 'push',
type: 'POST',
query: server_params(options),
options: options,
data: JSON.stringify(notification)
});
},
/**
* Get specific user by id.
* @param {string} id User id being requested.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* Results may be affected by defaults and/or by the options parameter.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
getUser: function(id, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + id,
type: 'GET',
query: server_params(options),
options: options
});
},
/**
* Search using CloudMine's geoquery API.
* @param {string} field Field to search on.
* @param {number} longitude The longitude to search for objects at.
* @param {number} latitude The latitude to search for objects at.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @param {string} [options.units = 'km'] The unit to use when not specified for. Can be 'km', 'mi', 'm', 'ft'.
* @param {boolean} [options.distance = false] If true, include distance calculations in the meta result for objects.
* @param {string|number} [options.radius] Distance around the target. If string, include units. If number, specify the unit in options.unit.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
/**
* Search using CloudMine's geoquery API.
* @param {string} field Field to search on.
* @param {object} target A reference object that has geo-location data.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @param {string} [options.units = 'km'] The unit to use when not specified for. Can be 'km', 'mi', 'm', 'ft'.
* @param {boolean} [options.distance = false] If true, include distance calculations in the meta result for objects.
* @param {string|number} [options.radius] Distance around the target. If string, include units. If number, specify the unit in options.unit.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name searchGeo^2
* @memberOf WebService.prototype
*/
searchGeo: function(field, longitude, latitude, options) {
var geo, options;
// Source is 1 argument for object, 2 for lat/long
if (isObject(longitude)) {
options = latitude || {};
geo = extractGeo(longitude, field);
} else {
if (!options) options = {};
geo = extractGeo(longitude, latitude);
}
if (!geo) throw new TypeError('Parameters given do not provide geolocation data');
// Handle radius formats
var radius = options.radius;
if (isNumber(radius)) radius = ', ' + radius + (options && options.units ? options.units : 'km');
else if (isString(radius) && radius.length) {
radius = ', ' + radius;
if (!options.units) options.units = radius.match(/mi?|km|ft/)[0];
}
else radius = '';
var locTerms = (field || 'location') + ' near (' + geo.longitude + ', ' + geo.latitude + ')' + radius;
return this.search('[' + locTerms + ']', options);
},
/**
* Upload a file stored in CloudMine.
* @param {string} key The binary file's object key.
* @param {file|string} file FileAPI: A HTML5 FileAPI File object, Node.js: The filename to upload.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
upload: function(key, file, options) {
options = opts(this, options);
if (!key) key = this.keygen();
if (!options.filename) options.filename = key;
// Warning: may not necessarily use ajax to perform upload.
var apicall = new APICall({
action: 'binary/' + key,
type: 'post',
later: true,
encoding: 'binary',
options: options,
processResponse: APICall.basicResponse
});
function upload(data, type) {
if (!options.contentType) options.contentType = type || defaultType;
APICall.binaryUpload(apicall, data, options.filename, options.contentType).done();
}
if (isString(file) || (Buffer && file instanceof Buffer)) {
// Upload by filename
if (isNode) {
if (isString(file)) file = fs.readFileSync(file);
upload(file);
}
else NotSupported();
} else if (file.toDataURL) {
// Canvas will have a toDataURL function.
upload(file, 'image/png');
} else if (CanvasRenderingContext2D && file instanceof CanvasRenderingContext2D) {
upload(file.canvas, 'image/png');
} else if (isBinary(file)) {
// Binary files are base64 encoded from a buffer.
var reader = new FileReader();
/** @private */
reader.onabort = function() {
apicall.setData("FileReader aborted").abort();
}
/** @private */
reader.onerror = function(e) {
apicall.setData(e.target.error).abort();
}
/** @private */
reader.onload = function(e) {
upload(e.target.result);
}
// Don't need to transform Files to Blobs.
if (File && file instanceof File) {
if (!options.contentType && file.type != "") options.contentType = file.type;
} else {
file = new Blob([ new Uint8Array(file) ], {type: options.contentType || defaultType});
}
reader.readAsDataURL(file);
} else NotSupported();
return apicall;
},
/**
* Download a file stored in CloudMine.
* @param {string} key The binary file's object key.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {string} [filename] If present, the file will be downloaded directly to the computer with the
* filename given. This does not validate the filename given!
* @config {string} [mode] If buffer, automatically move returning data to either an ArrayBuffer or Buffer
* if supported. Otherwise the result will be a standard string.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
download: function(key, options) {
options = opts(this, options);
var response = {success: {}}, query;
if (options.filename) {
query = {
force_download: true,
apikey: options.apikey,
session_token: options.session_token,
filename: options.filename
}
}
var apicall = new APICall({
action: 'binary/' + key,
type: 'GET',
later: true,
encoding: 'binary',
options: options,
query: query
});
// Download file directly to computer if given a filename.
if (options.filename) {
if (isNode) {
apicall.setProcessor(function(data) {
response.success[key] = fs.writeFileSync(options.filename, data, 'binary');
return response;
}).done();
} else {
function detach() {
if (iframe.parentNode) document.body.removeChild(iframe);
}
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
setTimeout(function() { iframe.src = apicall.url; }, 25);
iframe.onload = function() {
clearTimeout(detach.timer);
detach.timer = setTimeout(detach, 5000);
};
detach.timer = setTimeout(detach, 60000);
response.success[key] = iframe;
}
apicall.done(response);
} else if (options.mode === 'buffer' && (ArrayBuffer || Buffer)) {
apicall.setProcessor(function(data) {
var buffer;
if (Buffer) {
buffer = new Buffer(data, 'binary');
} else {
buffer = new ArrayBuffer(data.length);
var charView = new Uint8Array(buffer);
for (var i = 0; i < data.length; ++i) {
charView[i] = data[i] & 0xFF;
}
}
response.success[key] = buffer;
return response;
}).done();
} else {
// Raw data return. Do not attempt to process the result.
apicall.setProcessor(function(data) {
response.success[key] = data;
return response;
}).done();
}
return apicall;
},
/**
* Create a new user.
* @param {object} data An object with an email, username, and password field.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {object} [options.profile] Create a user with the given user profile.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name createUser
* @memberOf WebService.prototype
*/
/**
* Create a new user.
* @param {string} auth The email to login as.
* @param {string} password The password to login as.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {object} [options.profile] Create a user with the given user profile.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name createUser^2
* @memberOf WebService.prototype
*/
createUser: function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password};
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
credentials: {
email: auth.email,
username: auth.username,
password: auth.password
},
profile: options.profile
});
return new APICall({
action: 'account/create',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
},
/**
* Update user object of logged in user.
* @param {object} data An object to merge into the logged in user object.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateUser
* @memberOf WebService.prototype
*/
/**
* Update user object of logged in user.
* @param {string} field The field to merge into the logged in user object.
* @param {string} value The value to set the field to.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateUser^2
* @memberOf WebService.prototype
*/
updateUser: function(field, value, options) {
if (isObject(field)) options = value;
else {
var out = {};
out[field] = value;
field = out;
}
options = opts(this, options);
return new APICall({
action: 'account',
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(field)
});
},
/**
* Update a user object without having a session token. Requires the use of the master key
* @param {string} user_id the user id of the user to update.
* @param {object} profile a JSON object representing the profile
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
*/
updateUserMaster: function(user_id, profile, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + user_id,
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(profile)
});
},
/**
* Change a user's password
* @param {object} data An object with email, password, and oldpassword fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name changePassword
* @memberOf WebService.prototype
*/
/**
* Change a user's password
* @param {string} user The email to change the password.
* @param {string} oldpassword The existing password for the user.
* @param {string} password The new password for the user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name changePassword^2
* @memberOf WebService.prototype
*/
changePassword: function(auth, oldpassword, password, options) {
if (isObject(auth)) options = oldpassword;
else auth = {email: auth, oldpassword: oldpassword, password: password};
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.oldpassword,
credentials: {
password: auth.password
}
});
return new APICall({
action: 'account/password/change',
type: 'POST',
data: payload,
options: options,
processResponse: APICall.basicResponse
});
},
/**
* Update a user password without having a session token. Requires the use of the master key
* @param {string} user_id The id of the user to change the password.
* @param {string} password The new password for the user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
changePasswordMaster: function(user_id, password, options) {
options = opts(this, options);
var payload = JSON.stringify({
password: password
});
return new APICall({
action: 'account/' + user_id + '/password/change',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
},
/**
* Change a user's credentials: user/email and/or password
* @param {object} auth An object with email, username, password, and new_password, new_email, new_username fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name changeCredentials
* @memberOf WebService.prototype
*/
changeCredentials: function(auth, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.password,
credentials: {
password: auth.new_password,
username: auth.new_username,
email: auth.new_email
}
});
return new APICall({
action: 'account/credentials',
type: 'POST',
data: payload,
options: options,
processResponse: APICall.basicResponse
});
},
/**
* Initiate a password reset request.
* @param {string} email The email to send a reset password email to.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
resetPassword: function(email, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: email
});
return new APICall({
action: 'account/password/reset',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
},
/**
* Change the password for an account from the token received from password reset.
* @param {string} token The token for password reset. Usually received by email.
* @param {string} newPassword The password to assign to the user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
confirmReset: function(token, newPassword, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
password: newPassword
});
return new APICall({
action: "account/password/reset/" + token,
type: 'POST',
data: payload,
processResponse: APICall.basicResponse,
options: options
});
},
/**
* Login as a user to access user-level data.
* @param {object} data An object hash with email / username, and password fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name login
* @memberOf WebService.prototype
*/
/**
* Login as a user to access user-level data.
* @param {string} auth The email of the user to login as
* @param {string} password The password for the user
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name login^2
* @memberOf WebService.prototype
*/
login: function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password};
options = opts(this, options);
options.applevel = true;
// Wipe out existing login information.
this.options.email = null;
this.options.username = null;
this.options.session_token = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', null, this.options.appid);
}
var payload = JSON.stringify({
username: auth.username,
email: auth.email,
password: auth.password
})
var self = this;
return new APICall({
action: 'account/login',
type: 'POST',
options: options,
data: payload,
processResponse: APICall.basicResponse
}).on('success', function(data) {
if (options.savelogin) {
store('email', auth.email, self.options.appid);
store('username', auth.username, self.options.appid);
store('session_token', data.session_token, self.options.appid);
}
self.options.email = auth.email;
self.options.username = auth.username;
self.options.session_token = data.session_token;
});
},
/**
* Login a user via a social network credentials.
* This only works for browsers (i.e. not in a node.js environment) and requires user interaction (a browser window).
* @param {string} network A network to authenticate against. @see WebService.SocialNetworks
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {string} [options.link] If false, do not link social network to currently logged in user.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
loginSocial: function(network, options) {
// This does not work with Node.JS, or unrecognized services.
if (isNode) NotSupported();
options = opts(this, options);
options.applevel = true;
var challenge = uuid(), self = this;
var apicall = new APICall({
action: 'account/social/login/status/'+challenge,
options: options,
later: true,
processResponse: function(data) {
if (data.finished) {
self.options.session_token = data.session_token;
self.options.userid = data.profile.__id__;
data = { success: data }
}
else {
self.options.session_token = null;
self.options.userid = null;
data = { errors: [ "Login unsuccessful." ] }
}
if (options.savelogin) {
store('session_token', data.success.session_token, self.options.appid);
store('userid', data.success.profile.__id__, self.options.appid);
}
return data;
}
});
var url = this.options.apiroot+"/v1/app/"+options.appid+"/account/social/login";
var urlParams = {
service: network,
apikey: options.apikey,
challenge: challenge
};
if (this.options.session_token && options.link !== false) {
urlParams.session_token = this.options.session_token;
}
if (options.scope) urlParams.scope = options.scope;
var sep = url.indexOf("?") === -1 ? "?" : "&";
url = url + sep + stringify(urlParams);
var win = window.open(url, challenge, "width=600,height=400,menubar=0,location=0,toolbar=0,status=0");
function checkOpen() {
if (win.closed) {
clearTimeout(checkOpen.interval);
apicall.done();
}
}
checkOpen.interval = setInterval(checkOpen, 50);
return apicall;
},
/**
* Query a social network.
* Must be logged in as a user who has logged in to a social network.
* @param {object} query An object with the parameters of the query.
* @config {string} query.network A network to authenticate against. @see WebService.SocialNetworks
* @config {string} query.endpoint The endpoint to hit, on the social network side. See the social network's documentation for more details.
* @config {string} query.method HTTP verb to use when querying.
* @config {object} query.headers Extra headers to pass in the HTTP request to the social network.
* @config {object} query.params Extra parameters to pass in the HTTP request to the social network.
* @config {string} query.data Data to pass in the body of the HTTP request.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @throws {Error} If the user is not logged in.
* @throws {Error} If query.headers is truthy and not an object.
* @throws {Error} If query.params is truthy and not an object.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
socialQuery: function(query, options) {
options = opts(this, options);
if(!options.session_token) throw new Error("Must be logged in to perform a social query");
if(query.headers && !isObject(query.headers)) throw new Error("Headers must be an object");
if(query.params && !isObject(query.params)) throw new Error("Extra parameters must be an object");
var url = "social/"+query.network+"/"+query.endpoint;
var urlParams = {};
if(query.headers) urlParams.headers = query.headers;
if(query.params) urlParams.params = query.params;
var apicall = new APICall({
action: url,
type: query.method,
query: urlParams,
options: options,
data: query.data,
contentType: 'application/octet-stream'
});
return apicall;
},
/**
* Logout the current user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
logout: function(options) {
options = opts(this, options);
options.applevel = true;
var token = this.options.session_token;
this.options.email = null;
this.options.username = null;
this.options.session_token = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', this.options.appid);
}
return new APICall({
action: 'account/logout',
type: 'POST',
processResponse: APICall.basicResponse,
headers: {
'X-CloudMine-SessionToken': token
},
options: options
});
},
/**
* Verify if the given login and password is valid.
* @param {object} data An object with email / username, and password fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name verify
* @memberOf WebService.prototype
*/
/**
* Verify if the given email and password is valid.
* @param {string} auth The email to login
* @param {string} password The password of the user to login
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name verify^2
* @memberOf WebService.prototype
*/
verify: function(auth, password, options) {
if (isObject(auth)) opts = password;
else auth = {email: auth, password: password};
options = opts(this, options);
options.applevel = true;
return new APICall({
action: 'account/login',
type: 'POST',
processResponse: APICall.basicResponse,
data: JSON.stringify(auth),
options: options
});
},
/**
* Delete a user.
* If you are using the master api key, omit the user password to delete the user.
* If you are not using the master api key, provide the user name and password in the corresponding
* email and password fields.
*
* @param {object} data An object that may contain email / username fields and optionally a password field.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name deleteUser
* @memberOf WebService.prototype
*/
/**
* Delete a user.
* If you are using the master api key, omit the user password to delete the user.
* If you are not using the master api key, provide the user name and password in the corresponding
* email and password fields.
*
* @param {string} email The email of the user to delete. If using a master key use a user id.
* @param {string} password The password for the account. Omit if using a master key.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name deleteUser^2
* @memberOf WebService.prototype
*/
deleteUser: function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password}
options = opts(this, options);
options.applevel = true;
var config = {
action: 'account',
type: 'DELETE',
options: options,
processResponse: APICall.basicResponse
};
// Drop session if we are referring to ourselves.
if (auth.email == this.options.email) {
this.options.session_token = null;
this.options.email = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', null, this.options.appid);
}
}
if (auth.password) {
// Non-master key access
config.data = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.password
})
} else {
// Master key access
config.action += '/' + auth.email;
}
return new APICall(config);
},
/**
* Create or update an ACL rule for user-level objects. The API will automatically generate
* an id field if an __id__ attribute is not present. If it is, the ACL rule is updated.
*
* @param {object} acl The ACL object. See CloudMine documentation for reference. Example:
* {
* "__id__": "a4f84f89b2f14a87a3faa87289d72f98",
* "members": ["8490e9c8d6d64e6f8d18df334ae4f4fb", "ecced9c0c4bd41f0ab0dcb93d2840fd8"],
* "permissions": ["r", "u"],
* "segments": {
* "public": true,
* "logged_in": true
* },
* "my_extra_info": 12345
* }
*
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateACL
* @memberOf WebService.prototype
*/
updateACL: function(acl, options){
options = opts(this, options);
return new APICall({
action: 'access',
type: 'PUT',
processResponse: APICall.basicResponse,
data: JSON.stringify(acl),
options: options
});
},
/**
* Get an ACL rule for user-level objects by id.
*
* @param {string} aclid The id of the ACL object to fetch.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateACL
* @memberOf WebService.prototype
*/
getACL: function(aclid, options){
options = opts(this, options);
return new APICall({
action: 'access/' + aclid,
type: 'GET',
processResponse: APICall.basicResponse,
options: options
});
},
/**
* Check if the store has a logged in user.
* @return {boolean} True if the user is logged in, false otherwise.
*/
isLoggedIn: function() {
return !!this.options.session_token;
},
/**
* Get the current userid
* @return {string} The logged in userid, if applicable.
*/
getUserID: function() {
return this.options.email;
},
/**
* Get the current session token.
* @return {string} The current session token, if logged in.
*/
getSessionToken: function() {
return this.options.session_token;
},
/**
* Get the current email.
* @return {string} The logged in email, if logged in.
*/
getEmail: function() {
return this.options.email;
},
/**
* Get the current username.
* @return {string} The logged in username, if logged in.
*/
getUsername: function() {
return this.options.username;
},
/**
* Get a default option that is sent to the server.
* @param {string} option A default parameter to send to the server.
* @return {*} The value of the default parameter.
*/
getOption: function(option) {
return (valid_params[option] ? this.options[option] : null);
},
/**
* Set a default option that is sent to the server
* @param {string} option A default parameter to send to the server.
* @param {string} value The value of the option to set.
* @return {boolean} true if the option was set, false for invalid options.
*/
setOption: function(option, value) {
if (valid_params[option]) {
this.options[option] = value;
return true;
}
return false;
},
/**
* Set the application or user-level data mode for this store.
* @param {boolean|undefined} state If true, this store will only operate in application data.
* If false, this store will only operate in user-level data.
* If null/undefined, this store will use user-level data if logged in,
* application data otherwise.
*/
useApplicationData: function(state) {
this.options.applevel = (state === true || state === false) ? state : undefined;
},
/**
* Determine if this store is using application data.
* @return {boolean} true if this store is using application data, false if is using user-level data.
*/
isApplicationData: function() {
if (this.options.applevel === true || this.options.applevel === false) return this.options.applevel;
return this.options.session_token == null;
},
keygen: uuid
};
WebService.VERSION = version;
// Supported Social Networks
WebService.SocialNetworks = [
'bodymedia',
'dropbox',
'facebook',
'fitbit',
'flickr',
'foursquare',
'gcontacts',
'gdocs',
'github',
'gmail',
'google',
'gplus',
'instagram',
'linkedin',
'meetup',
'runkeeper',
'tumblr',
'twitter',
'withings',
'wordpress',
'yammer',
'zeo'
];
/**
* Set the X-Unique-ID to be used in all WebService requests. This function allows it to be set
* on before the WebService object is instantiated.
*/
WebService.setXUniqueID = function(xUniqueID) {
global._$XUniqueID = xUniqueID;
}
/**
* <p>WebService will return an instance of this class that should be used to interact with
* the API. Upon completion of the AJAX call, this object will fire the event handlers based on
* what were attached.
*
* <p>You may chain event creation.
*
* <p><b>Note:</b> It is recommended to avoid referring directly to the ajax implementation used by this
* function. Depending on environment, features on it may vary since this library only
* requires a small subset of jQuery-like AJAX functionality.
*
* <p>Event firing order:
* <div>Successes: HTTP Code String, HTTP Code Number, 'success'</div>
* <div>Meta: 'meta' - This is for operations that can write meta data.</div>
* <div>Result: 'result' - This is results from code snippets if used.</div>
* <div>Errors: HTTP Code String, HTTP Code Number, 'error'</div>
*
* <p>Event callback signatures:
* <div>HTTP Codes: function(keys, responseObject, statusCode)</div>
* <div>'error': function(keys, responesObject)</div>
* <div>'success': function(keys, responseObject)</div>
* <div>'meta': function(keys, responseObject)</div>
* <div>'result: function(keys, responseObject)</div>
* <div>'abort': function(keys, responseObject)</div>
* @class
* @name APICall
*/
function APICall(config) {
this.config = merge({}, defaultConfig, config);
this._events = {};
var agent = 'JS/' + version;
var opts = this.config.options;
if (opts.appname) {
agent += ' ' + opts.appname.replace(agentInvalid, '_');
if (opts.appversion) {
agent += '/' + opts.appversion.replace(agentInvalid, '_');
}
}
// Fields that are available at the completion of the api call.
this.additionalData = this.config.callbackData;
this.data = null;
this.hasErrors = false;
this.requestData = this.config.data;
this.requestHeaders = {
'X-CloudMine-ApiKey': opts.apikey,
'X-CloudMine-Agent': agent,
'X-CloudMine-UT': opts.user_token
};
if (typeof(global) != 'undefined' && typeof global._$XUniqueID != 'undefined') {
this.requestHeaders['X-Unique-Id'] = global._$XUniqueID
}
this.responseHeaders = {};
this.responseText = null;
this.status = null;
this.type = this.config.type || 'GET';
// Build the URL and headers
var query = stringify(server_params(opts, this.config.query));
var root = '/', session = opts.session_token, applevel = opts.applevel;
if (applevel === false || (applevel !== true && session != null)) {
if (config.action.split('/')[0] !== 'account'){
root = '/user/';
}
if (session != null) this.requestHeaders['X-CloudMine-SessionToken'] = session;
}
// Merge in headers in case-insensitive (if necessary) manner.
for (var key in this.config.headers) {
mapInsensitive(this.requestHeaders, key, this.config.headers[key]);
}
this.config.headers = this.requestHeaders;
if (!isEmptyObject(perfComplete)) {
this.config.headers['X-CloudMine-UT'] += ';' + stringify(perfComplete, ':', ',', null, PERF_HEADER_LIMIT);
perfComplete = {};
}
this.setContentType(config.contentType || 'application/json');
var endpointVersion = this.config.options.version || 'v1';
var versionPath = '/' + endpointVersion + '/app/';
this.url = [this.config.options.apiroot, versionPath, this.config.options.appid, root, this.config.action].join("");
var sep = this.url.indexOf('?') === -1 ? '?' : '&';
this.url = [this.url, (query ? sep + query : "")].join("");
var self = this, sConfig = this.config, timestamp = +(new Date);
/** @private */
this.config.complete = function(xhr, status) {
var data;
if (xhr) {
data = xhr.responseText
self.status = xhr.status;
self.responseText = data;
self.responseHeaders = unstringify(xhr.getAllResponseHeaders(), /:\s*/, /(?:\r|\n)?\n/);
// Performance metrics, if applicable.
var requestId = mapInsensitive(self.responseHeaders, 'X-Request-Id');
if (requestId) perfComplete[requestId] = +(new Date) - timestamp;
// If we can parse the data as JSON or store the original data.
try {
self.data = JSON.parse(data || "{}");
} catch (e) {
self.data = data;
}
} else {
self.status = 'abort';
self.data = [ sConfig.data ];
}
// Parse the response only if a safe status
if (status == 'success' && self.status >= 200 && self.status < 300) {
// Preprocess data coming in to hash-hash: [success/errors].[httpcode]
data = sConfig.processResponse.call(self, self.data, xhr, self);
} else {
data = {errors: {}};
if (isString(self.data)) {
self.data = { errors: [ self.data ] } // This way, we can rely on this structure data[statuscode].errors to always be an Array of one or more errors
}
data.errors[self.status] = self.data;
}
setTimeout(function() {
APICall.complete(self, data);
}, 1);
}
// Let script continue before triggering ajax call
if (!this.config.later && this.config.async) {
setTimeout(function() {
if(!self.config.cancel)
self.xhr = ajax(self.url, sConfig);
}, 1);
}
}
/** @namespace APICall.prototype */
APICall.prototype = {
/**
* Attach an event listener to this APICall object.
* @param {string|number} eventType The event to listen to. Can be an http code as number or string,
* success, meta, result, error.
* @param {function} callback Callback to call upon event trigger.
* @param {object} context Context to call the callback in.
* @return {APICall} The current APICall object
*/
on: function(eventType, callback, context) {
if (isFunction(callback)) {
context = context || this;
if (!this._events[eventType]) this._events[eventType] = [];
// normal callback not called.
var self = this;
this._events[eventType].push([callback, context, function() {
self.off(eventType, callback, context);
callback.apply(this, arguments);
}]);
}
return this;
},
/**
* Trigger an event on this APICall object. This will call all event handlers in order.
* All parameters following event will be sent to the event handlers.
* @param {string|number} event The event to trigger.
* @return {APICall} The current APICall object
*/
trigger: function(event/*, arg1...*/) {
var events = this._events[event];
if (events != null) {
var args = slice(arguments, 1);
each(events, function(event) {
event[2].apply(event[1], args);
});
}
return this;
},
/**
* Remove event handlers.
* Event handlers will be removed based on the parameters given. If no parameters are given, all
* event handlers will be removed.
* @param {string|number} eventType The event type which can be an http code as number or string,
* or can be success, error, meta, result, abort.
* @param {function} callback The function that was used to create the callback.
* @param {object} context The context to call the callback in.
* @return {APICall} The current APICall object
*/
off: function(eventType, callback, context) {
if (eventType == null && callback == null && context == null) {
this._events = {};
} else if (eventType == null) {
each(this._events, function(value, key, collection) {
collection._events[key] = removeCallbacks(value, callback, context);
});
} else {
this._events[eventType] = removeCallbacks(this._events[eventType], callback, context);
}
return this;
},
/**
* Set the content-type for a waiting APICall.
* Note: this has no effect if the APICall has completed.
* @param {string} type The content-type to set. If not specified, this will use 'application/octet-stream'.
* @return {APICall} The current APICall object
*/
setContentType: function(type) {
type = type || defaultType;
if (this.config) {
this.config.contentType = type;
mapInsensitive(this.requestHeaders, 'content-type', type);
mapInsensitive(this.config.headers, 'content-type', type);
}
return this;
},
/**
* Aborts the current connection. This is ineffective for running synchronous calls or completed
* calls. Synchronous calls can be achieved by setting async to false in WebService.
* @return {APICall} The current APICall object
*/
abort: function() {
if (this.xhr) {
this.xhr.abort();
} else if (this.config) {
this.config.complete.call(this, this.xhr, 'abort');
}
// Cleanup leftover state.
if (this.xhr) {
this.xhr = undefined;
delete this.xhr;
}
if (this.config) {
this.config = undefined;
delete this.config;
}
return this;
},
/**
* Set data to send to the server. This is ineffective for running ajax calls.
* @return {APICall} The current APICall object
*/
setData: function(data) {
if (!this.xhr && this.config) {
this.config.data = data;
}
return this;
},
/**
* Set the data processor for the APICall. This is ineffective for running ajax calls.
* @return {APICall} The current APICall object
*/
setProcessor: function(func) {
if (!this.xhr && this.config) {
this.config.processResponse = func;
}
return this;
},
/**
* If a synchronous ajax call is done (via setting: options.async = false), you must call this function
* after you have attached all your event handlers. You should not attach event handlers after this
* is called.
*/
done: function(response) {
if (!this.xhr && this.config) {
if (response) {
this.xhr = true;
var self = this;
setTimeout(function() {
APICall.complete(self, response);
}, 1);
} else {
this.xhr = ajax(this.url, this.config);
}
}
return this;
},
/**
* Get a response header using case insensitive searching
* Note: It is faster to use the exact casing as no searching is necessary when matching.
* @param {string} key The header to retrieve, case insensitive.
* @return {string|null} The value of the header, or null
*/
getHeader: function(key) {
return mapInsensitive(this.responseHeaders, key);
}
};
/**
* Complete the given API Call, usually called after completed processing of data, though can be
* used to circumvent the standard AJAX call functionality for calls that are not currently running.
* @param {APICall} apicall The api call to affect. Can be either a completed request or a deferred request.
* @param {object} data Processed data where the top level keys are: success, errors, meta, result.
*
* @private
* @function
* @memberOf APICall
*/
APICall.complete = function(apicall, data) {
// Success results may have errors for certain keys
if (data.errors) apicall.hasErrors = true;
// Clean up temporary state.
if (apicall.config) {
apicall.config = undefined;
delete apicall.config;
}
if (apicall.xhr) {
apicall.xhr = undefined;
delete apicall.xhr;
}
// Data has been processed by this point and should exist in success, errors, meta, or results hashes.
// Event firing order: http status (e.g. ok, created), http status (e.g. 200, 201), success, meta, result, error.
if (data.success) {
// Callback signature: function(keys, response, statusCode)
if (httpcode[apicall.status]) apicall.trigger(httpcode[apicall.status], data.success, apicall, apicall.status);
apicall.trigger(apicall.status, data.success, apicall, apicall.status);
// Callback signature: function(keys, response);
apicall.trigger('success', data.success, apicall);
}
// Callback signature: function(keys, response)
if (data.meta) apicall.trigger('meta', data.meta, apicall);
// Callback signature: function(keys, response)
if (data.result) apicall.trigger('result', data.result, apicall);
// Errors needs to fire groups of errors depending on code result.
if (data.errors) {
// Callback signature: function(keys, reponse, statusCode)
for (var k in data.errors) {
if (httpcode[k]) apicall.trigger(httpcode[k], data.errors[k], apicall, k);
apicall.trigger(k, data.errors[k], apicall, k);
}
// Callback signature: function(keys, response)
apicall.trigger('error', data.errors, apicall);
}
// Callback signature: function(responseData, response)
apicall.trigger('complete', data, apicall);
}
/**
* Standard CloudMine response for the 200-299 range responses.
* This will transform the response so that APICall.complete will trigger the appropriate handlers.
*
* @private
* @function
* @memberOf APICall
*/
APICall.textResponse = function(data, xhr, response) {
var out = {};
if (data.success || data.errors || data.meta || data.result) {
if (data.count != null) response.count = data.count;
if (!isEmptyObject(data.success)) out.success = data.success;
if (!isEmptyObject(data.meta)) out.meta = data.meta;
if (!isEmptyObject(data.result)) out.result = data.result;
if (!isEmptyObject(data.errors)) {
out.errors = {};
for (var k in data.errors) {
var error = data.errors[k], code = 400;
// Unfortunately, errors are a bit inconsistent.
if (error.code) {
code = error.code;
error = error.message || error;
} else if (isString(error)) {
code = errors[error.toLowerCase()] || 400;
}
if (!out.errors[code]) out.errors[code] = {}
out.errors[code][k] = {errors: [ error ]};
}
}
// At least guarantee a success callback.
if (isEmptyObject(out)) {
if (this.config.options && this.config.options.snippet) out.result = {};
else out.success = {};
}
} else {
// Non-standard response. Just pass back the data we were given.
out = {success: data};
}
return out;
}
/**
* Minimal processing of data so that the success handler is called upon completion.
* This assumes any response in the 200-299 range is a success.
*
* @private
* @function
* @memberOf APICall
*/
APICall.basicResponse = function(data, xhr, response) {
return {success: data || {}};
}
/**
* Convert binary data in browsers to a transmitable version and assign it to the given
* api call.
* @param {APICall} apicall The APICall to affect, it should have later: true.
* @param {object|string} data The data to send to the server. Strings are expected to be base64 encoded.
* @param {string} filename The filename to upload as.
* @param {string} contentType The content-type of the file. If not specified, it will guess if possible,
* otherwise assume application/octet-stream.
* @return {APICall} The apicall object that was given.
*
* @private
* @function
* @memberOf APICall
*/
APICall.binaryUpload = function(apicall, data, filename, contentType) {
var boundary = uuid();
if (Buffer && data instanceof Buffer) {
data = data.toString('base64');
if (!contentType) contentType = defaultType;
} else {
if (data.toDataURL) data = data.toDataURL(contentType);
data = data.replace(/^data:(.*?);?base64,/, '');
if (!contentType) contentType = RegExp.$1 || defaultType;
}
apicall.setContentType('multipart/form-data; boundary=' + boundary);
return apicall.setData([
'--' + boundary,
'Content-Disposition: form-data; name="file"; filename="' + filename + '"',
'Content-Type: ' + contentType,
'Content-Transfer-Encoding: base64',
'',
data,
'--' + boundary + '--'
].join('\r\n'));
}
// Cache ids for perfAPICall
var perfComplete = {};
/**
* Node.JS jQuery-like ajax adapter.
* This is an internal class that is not exposed.
*
* @param {string} uri The complete url to hit.
* @param {object} config Parameters for the ajax request.
* @config {string} [contentType] The Content Type of the request.
* @config {string} [type] The type of request, e.g. 'get', 'post'
* @config {object} [headers] Request headers to send to the client.
* @config {boolean} [processData] If true, process the data given.
* @config {string|Array|Object} [data] Data to send to the server.
* @name HttpRequest
* @constructor
*/
function HttpRequest(uri, config) {
config = config || {};
this.status = 400;
this.responseText = [];
this._headers = {};
// disable connection pooling
// disable chunked transfer-encoding which nginx doesn't support
var opts = url.parse(uri);
opts.agent = false;
opts.method = config.type;
opts.headers = config.headers || {};
// Preprocess data if it is JSON data.
if (isObject(config.data) && config.processData) {
config.data = JSON.stringify(config.data);
}
// Authenticate request if we have authentication information.
if (config.username || config.password) {
opts.headers.Authorization = "Basic " + btoa(config.username + ':' + config.password);
}
// Attach a content-length
// Prevent node.js from sending transfer-encoding:chunked when there is no body
config.data = config.data || '';
if (isArray(config.data)) opts.headers['content-length'] = Buffer.byteLength(config.data);
else if (isString(config.data)) opts.headers['content-length'] = Buffer.byteLength(config.data);
// Fire request.
var self = this, cbContext = config.context || this;
this._textStatus = 'success';
this._request = (opts.protocol === "http:" ? http : https).request(opts, function(response) {
response.setEncoding(config.encoding || 'utf8');
response.on('data', function(chunk) {
self.responseText.push(chunk);
});
response.on('end', function () {
self._headers = stringify(response.headers, ': ', '\n', true) || "";
self.status = response.statusCode;
var data;
try {
// Process data if necessary.
data = self.responseText = self.responseText.join('');
if (config.dataType == 'json' || (config.dataType != 'text' && response.headers['content-type'].match(/\bapplication\/json\b/i))) {
data = JSON.parse(data);
}
} catch(e)
{
self._textStatus = 'parsererror';
}
if (self._textStatus == 'success' && self.status >= 200 && self.status < 300) {
if (config.success) config.success.call(cbContext, data, 'success', self);
} else if (config.error) {
config.error.call(cbContext, self, 'error', self.responseText);
}
if (config.complete) config.complete.call(cbContext, self, self._textStatus);
});
});
// Handle request errors.
this._request.on('error', function(e) {
self.status = e.status;
self.responseText = e.message;
self._textStatus = 'error';
if (config.error) config.error.call(cbContext, self, 'error', e.message);
if (config.complete) config.complete.call(cbContext, self, 'error');
});
// Send data (if present) and fire the request.
this._request.end(config.data);
}
/** @namespace HttpRequest.prototype */
HttpRequest.prototype = {
/**
* Return a given response header
* @param {string} The header field to retreive.
* @return {string|null} The value of that header, if it exists.
*/
getResponseHeader: function(header) {
return this._headers[header];
},
/**
* Get all the response headers.
* @return {object} An object representing all the response headers.
*/
getAllResponseHeaders: function() {
return this._headers;
},
/**
* Abort the current connection. This has no effect if the request is already completed.
* This will trigger an abort error event.
*/
abort: function() {
if (this._request) {
this._textStatus = 'abort';
this._request.abort();
this._request = undefined;
delete this._request;
}
}
};
// Remap some of the CloudMine API query parameters.
var valid_params = {
limit: 'limit',
sort: 'sort',
skip: 'skip',
snippet: 'f', // Run code snippet on the data
params: 'params', // Only applies to code snippets, parameters for the code snippet (JSON).
dontwait: 'async', // Only applies to code snippets, don't wait for results.
resultsonly: 'result_only', // Only applies to code snippets, only show results from code snippet.
shared: 'shared',
shared_only: 'shared_only',
userid: 'userid',
count: 'count',
distance: 'distance', // Only applies to geo-query searches
units: 'units', // Only applies to geo-query searches
extended_responses: 'extended_responses' // Only applies to atomic operations
};
// Default jQuery ajax configuration.
var defaultConfig = {
async: true,
later: false,
processData: false,
dataType: 'text',
processResponse: APICall.textResponse,
crossDomain: true,
cache: false
};
// Map HTTP codes that could come from CloudMine
var httpcode = {
200: 'ok',
201: 'created',
400: 'badrequest',
401: 'unauthorized',
404: 'notfound',
409: 'conflict',
500: 'servererror'
};
// Sometimes we only get a string back as an error.
var errors = {
'bad request': 400,
'permission denied': 401,
'unauthorized': 401,
'key does not exist': 404,
'not found': 404,
'conflict': 409
};
var PERF_HEADER_LIMIT = 20;
// Scope external dependencies, if necessary.
var base = this.window ? window : root;
var defaultType = 'application/octet-stream';
var File = base.File;
var FileReader = base.FileReader;
var ArrayBuffer = base.ArrayBuffer;
var Buffer = base.Buffer;
var CanvasRenderingContext2D = base.CanvasRenderingContext2D;
var BinaryClasses = [ File, Buffer, CanvasRenderingContext2D, ArrayBuffer, base.Uint8Array, base.Uint8ClampedArray, base.Uint16Array, base.Uint32Array, base.Int8Array, base.Int16Array, base.Int32Array, base.Float32Array, base.Float64Array ];
var agentInvalid = /[^a-zA-Z0-9._-]/g;
// Utility functions.
function hex() { return Math.round(Math.random() * 15).toString(16); }
function uuid() {
var out = Array(32), i;
out[14] = 4;
out[19] = ((Math.round(Math.random() * 16) & 3) | 8).toString(16);
for (i = 0; i < 14; ++i) { out[i] = hex(); }
for (i = 15; i < 19; ++i) { out[i] = hex(); }
for (i = 20; i < 32; ++i) { out[i] = hex(); }
return out.join('');
}
function opts(scope, options) {
// email used to be called userid. set email to userid if they're still using that.
if(options && options.userid && !options.email) options.email = options.userid;
return merge({}, scope.options, options);
}
var propCache = {};
var ROOT_COLLECTION = 'base';
function retrieve(key, collection) {
var col = getCollection(collection);
return col[key];
}
function store(key, value, collection) {
var col = getCollection(collection);
if (col[key] != value) {
col[key] = value;
saveCollection(collection);
}
return value;
}
function server_params(options, map) {
var key, value;
if (map == null) map = {};
for (key in valid_params) {
value = valid_params[key];
if (options[key] != null) {
map[value] = options[key];
}
}
return map;
}
// Callbacks stored as: [originalCallback, context, wrappedCallback]
function removeCallbacks(src, callback, context) {
return filter(src, function(event) {
return (!callback || event[0] == callback) && (!context || context == event[1]);
});
}
function slice(array, x, y) {
return Array.prototype.slice.call(array, x || 0, y || array.length);
}
function each(item, callback, context) {
context = context || this
if (isArray(item)) {
if (item.forEach) item.forEach(callback, context);
else {
for (var i = 0; i < item.length; ++i) {
var obj = item[i];
if (obj != null) callback.call(context, obj, k, context);
}
}
} else if (isObject(item)) {
for (var k in item) {
var obj = item[k];
if (obj != null) callback.call(context, obj, k, context);
}
}
}
function filter(item, callback, context) {
var out = null;
context = context || this;
if (isArray(item)) {
if (item.filter) {
out = item.filter(callback, context);
} else {
out = [];
each(item, function(value, key, collection) {
if (callback.apply(this, arguments)) out.push(value);
});
}
} else {
out = {};
each(item, function(value, key, collection) {
if (callback.apply(this, arguments)) out[key] = value;
});
}
return out;
}
function mapInsensitive(map, name, value) {
// Find the closest name if we haven't referenced it directly.
if (map[name] == null) {
var lower = name.toLowerCase();
for (var k in map) {
if (k.toLowerCase() === lower) {
name = k;
break;
}
}
}
if (value !== undefined) map[name] = value;
return map[name];
}
function isObject(item) {
return item && typeof item === "object"
}
function isString(item) {
return typeof item === "string"
}
function isNumber(item) {
return typeof item === "number" && !isNaN(item);
}
function isBinary(item) {
return isObject(item) && BinaryClasses.indexOf(item.constructor) > -1
}
function isArray(item) {
if (item === null) return false;
return isObject(item) && item.length != null
}
function isFunction(item) {
return typeof item === 'function';
}
function isGeopoint(item) {
return isObject(item) && item.__type__ === 'geopoint';
}
function extractGeo(x, y) {
if (isNumber(x) && isNumber(y)) {
return {latitude: y, longitude: x};
} else if (isObject(x)) {
// Got a field? try to extract from there.
if (y && isGeopoint(x[y])) return extractGeo(x[y]);
else {
// Search current object since we didn't specify a field as y.
var out = {
latitude: x.latitude || x.lat || x.y,
longitude: x.longitude || x.lng || x.x
};
if (isNumber(out.latitude) && isNumber(out.longitude)) return out;
// Search first level objects since we haven't found location data yet.
for (var key in x) {
if (isGeopoint(x[key])) {
return {
latitude: x.latitude || x.lat || x.y,
longitude: x.longitude || x.lng || x.x
};
}
}
}
}
return null;
}
function isEmptyObject(item) {
if (item) {
if (item % 1 === 0) {
return false;
}
else {
for (var k in item) {
if (item.hasOwnProperty(k)) {
return false;
}
}
}
}
return true;
}
function stringify(map, sep, eol, ignore, limit) {
sep = sep || '=';
limit = limit == undefined ? -1 : limit;
var out = [], val, escape = ignore ? nop : encodeURIComponent;
var numMapped = 0;
for (var k in map) {
if (map[k] != null && !isFunction(map[k])){
if(isArray(map[k])){
map[k].forEach(function(val){
out.push(escape(k) + sep + escape(val));
});
} else {
val = isObject(map[k]) ? JSON.stringify(map[k]) : map[k];
out.push(escape(k) + sep + escape(val));
}
}
numMapped++;
if (numMapped === limit) break;
}
return out.join(eol || '&');
}
function unstringify(input, sep, eol, ignore) {
var out = {};
if(isString(input)){
input = input.split(eol || '&');
var unescape = ignore ? nop : decodeURIComponent;
for (var i = 0; i < input.length; ++i) {
var str = input[i].split(sep);
out[unescape(str.shift())] = unescape(str.join(sep));
}
} else {
// error case - input is already an object
out = input;
}
return out;
}
function merge(obj/*, in...*/) {
for (var i = 1; i < arguments.length; ++i) {
each(arguments[i], function(value, key, collection) {
if (value != null) obj[key] = value;
});
}
return obj;
}
function convertQueryInput(input) {
if (isObject(input)) {
var out = [];
for (var key in input) {
out.push(key + " = " + JSON.stringify(input[key]));
}
return "[" + out.join(', ') + "]";
}
return input;
}
function NotSupported() { throw new Error("Unsupported operation"); }
function nop(s) { return s; }
// Export CloudMine objects.
var http, btoa, https, ajax, isNode, fs, url, getCollection, saveCollection;
if (!this.window) {
isNode = true;
url = require('url');
http = require('http');
https = require('https');
// in node lower than 0.12, this defaults to 5
https.globalAgent.maxSockets = 50;
http.globalAgent.maxSockets = 50;
fs = require('fs');
module.exports = { WebService: WebService };
// Wrap the HttpRequest constructor so it operates the same as jQuery/Zepto.
ajax = function(url, config) {
return new HttpRequest(url, config);
}
// Node.JS adapter to support base64 encoding.
btoa = function(str, encoding) {
return new Buffer(str, encoding || 'utf8').toString('base64');
}
/**
* Retreive JSON data from the given collection. This will attempt to load a .cm.(collection).json file first
* from the current directory, and on any error, try to load the same name from the home directory.
* @param {string} [collection="base"] The collection to retreive data from.
* @return An object from the stored JSON data.
* @private
*/
getCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
// Load the collection if it hasn't already been loaded. Try current directory, or $HOME.
if (!propCache[collection]) {
var locations = ['.', process.env.HOME + "/."], loc;
while ((loc = locations.shift()) != null) {
try {
propCache[collection] = JSON.parse(fs.readFileSync(loc + collection + '.json', 'UTF8'));
break;
} catch (e) {}
}
if (!loc) propCache[collection] = {};
}
return propCache[collection];
}
/**
* Save JSON data to the given collection. This will attempt to save to .cm.(collection).json file first
* in the current directory, and on any error, try to save to the same name in the home directory.
* @param {string} [collection="base"] The collection to save data from.
* @throws {Error} If the file could not be saved.
* @private
*/
saveCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
// Attempt to save to the current directory, or load from $HOME.
var locations = ['.', process.env.HOME + "/."], loc;
while ((loc = locations.shift()) != null) {
try {
fs.writeFileSync(loc + collection + '.json', JSON.stringify(propCache[collection] || {}), 'UTF8');
break;
} catch (e) {}
}
if (!loc) throw new Error("Could not save CloudMine session data");
}
} else {
isNode = false;
window.cloudmine = window.cloudmine || {};
window.cloudmine.WebService = WebService;
btoa = window.btoa;
// Require the use of jQuery or Zepto.
if (($ = this.jQuery || this.Zepto) != null) {
ajax = $.ajax;
if ($.support) $.support.cors = true
}
else throw new Error("Missing jQuery-compatible ajax implementation");
/**
* Retreive JSON data from the given collection in html5 local storage.
* @param {string} [collection="base"] The collection to retreive data from.
* @return An object from the stored JSON data.
* @private
*/
getCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
if (!propCache[collection]) {
try {
propCache[collection] = JSON.parse(localStorage.getItem(collection)) || {};
} catch (e) {
propCache[collection] = {};
}
}
return propCache[collection];
}
/**
* Save JSON data to the given collection in html5 local storage.
* @param {string} [collection="base"] The collection to save data from.
* @private
*/
saveCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
localStorage.setItem(collection, JSON.stringify(propCache[collection] || {}));
}
}
})();
| js/cloudmine.js | /* CloudMine JavaScript Library v0.10.x cloudmineinc.com | https://github.com/cloudmine/cloudmine-js/blob/master/LICENSE */
(function() {
var version = '0.9.18';
/**
* Construct a new WebService instance
*
* <p>Each method on the WebService instance will return an APICall object which may be used to
* access the results of the method called. You can chain multiple events together with the
* returned object (an APICall instance).
*
* <p>All events are at least guaranteed to have the callback signature: function(data, apicall).
* supported events:
* <p> 200, 201, 400, 401, 404, 409, ok, created, badrequest, unauthorized, notfound, conflict,
* success, error, complete, meta, result, abort
* <p>Event order: success callbacks, meta callbacks, result callbacks, error callbacks, complete
* callbacks
*
* <p>Example:
* <pre class='code'>
* var ws = new cloudmine.WebService({appid: "abc", apikey: "abc", appname: 'SampleApp', appversion: '1.0'});
* ws.get("MyKey").on("success", function(data, apicall) {
* console.log("MyKey value: %o", data["MyKey"]);
* }).on("error", function(data, apicall) {
* console.log("Failed to get MyKey: %o", apicall.status);
* }).on("unauthorized", function(data, apicall) {
* console.log("I'm not authorized to access 'appid'");
* }).on(404, function(data, apicall) {
* console.log("Could not find 'MyKey'");
* }).on("complete", function(data, apicall) {
* console.log("Finished get on 'MyKey':", data);
* });
* </pre>
* <p>Refer to APICall's documentation for further information on events.
*
* @param {object} Default configuration for this WebService
* @config {string} [appid] The application id for requests (Required)
* @config {string} [apikey] The api key for requests (Required)
* @config {string} [appname] An alphanumeric identifier for your app, used for stats purposes
* @config {string} [appversion] A version identifier for you app, used for stats purposes
* @config {boolean} [applevel] If true, always send requests to application.
* If false, always send requests to user-level, trigger error if not logged in.
* Otherwise, send requests to user-level if logged in.
* @config {boolean} [savelogin] If true, session token and email / username will be persisted between logins.
* @config {integer} [limit] Set the default result limit for requests
* @config {string} [sort] Set the field on which to sort results
* @config {integer} [skip] Set the default number of results to skip for requests
* @config {boolean} [count] Return the count of results for request.
* @config {string} [snippet] Run the specified code snippet during the request.
* @config {string|object} [params] Parameters to give the code snippet (applies only for code snippets)
* @config {boolean} [dontwait] Don't wait for the result of the code snippet (applies only for code snippets)
* @config {boolean} [resultsonly] Only return results from the code snippet (applies only for code snippets)
* @name WebService
* @constructor
*/
function WebService(options) {
this.options = opts(this, options);
if(!this.options.apiroot) this.options.apiroot = "https://api.cloudmine.io";
var src = this.options.appid;
if (options.savelogin) {
if (!this.options.email) this.options.email = retrieve('email', src);
if (!this.options.username) this.options.username = retrieve('username', src);
if (!this.options.session_token) this.options.session_token = retrieve('session_token', src);
}
this.options.user_token = retrieve('ut', src) || store('ut', this.keygen(), src);
}
/** @namespace WebService.prototype */
WebService.prototype = {
/**
* generic function for calling the api with a minimal set of logic and optons
* @param {string} action Action endpoint - 'text', 'data', etc
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @param {object} [data] Request body (optional). If present, will be automatically stringified.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name api
* @memberOf WebService.prototype
*/
api: function(action, options, data) {
options = opts(this, options);
var method = options.method || 'GET';
var args = {
action: action,
type: method,
options: options
};
if (options.query) {
args.query = options.query;
delete args.options.query;
}
if (data !== undefined) {
args.data = JSON.stringify(data);
}
return new APICall(args);
},
/**
* Get data from CloudMine.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|string[]|null} [keys] If set, return the specified keys, otherwise return all keys.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
get: function(keys, options) {
if (isArray(keys)) keys = keys.join(',');
else if (isObject(keys)) {
options = keys;
keys = null;
}
options = opts(this, options);
var query = keys ? server_params(options, {keys: keys}) : null;
return new APICall({
action: 'text',
type: 'GET',
options: options,
query: query
});
},
/**
* Create new data, and merge existing data.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} data An object hash where the top level properties are the keys.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name update
* @memberOf WebService.prototype
*/
/**
* Create new data, and merge existing data.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|null} key The key to affect. If given null, a random key will be assigned.
* @param {string|number|object} value The value of the object
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name update^2
* @memberOf WebService.prototype
*/
update: function(key, value, options) {
if (isObject(key)) options = value;
else {
if (!key) key = this.keygen();
var out = {};
out[key] = value;
key = out;
}
options = opts(this, options);
return new APICall({
action: 'text',
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(key)
});
},
/**
* Create or overwrite existing objects in CloudMine with the given key or keys.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} data An object hash where the top level properties are the keys.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name set
* @memberOf WebService.prototype
*/
/**
* Create or overwrite existing objects in CloudMine with the given key or keys.
* The data must be convertable to JSON.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|null} key The key to affect. If given null, a random key will be assigned.
* @param {string|number|object} value The object to store.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name set^2
* @memberOf WebService.prototype
*/
set: function(key, value, options) {
if (isObject(key)) options = value;
else {
if (!key) key = this.keygen();
var out = {};
out[key] = value;
key = out;
}
options = opts(this, options);
return new APICall({
action: 'text',
type: 'PUT',
options: options,
query: server_params(options),
data: JSON.stringify(key)
});
},
/**
* Destroy one or more keys on the server.
* If given null and options.all is true, delete all objects on the server.
* Results may be affected by defaults and/or by the options parameter.
* @param {string|string[]|null} keys The keys to delete on the server.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters. Pass all:true with null keys to really delete all values, or query with a query object or string to delete objects matching query. WARNING: using the query is DANGEROUS. Triple check your query!
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
destroy: function(keys, options) {
options = opts(this, options);
var params = {};
if (keys == null && options.all === true) params = {all: true};
else if (options.query){
params = {q: convertQueryInput(options.query)};
delete options.query;
} else {
params = {keys: (isArray(keys) ? keys.join(',') : keys)};
}
return new APICall({
action: 'data',
type: 'DELETE',
options: options,
query: server_params(options, params)
});
},
/**
* Run a code snippet directly.
* Default http method is 'GET', to change the method set the method option for options.
* @param {string} snippet The name of the code snippet to run.
* @param {object} params Data to send to the code snippet (optional).
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
run: function(snippet, parameters, options) {
options = opts(this, options);
parameters = merge({}, options.params, parameters);
options.params = null;
options.snippet = null;
var call_opts = {
action: 'run/' + snippet,
type: options.method || 'GET',
options: options
};
if(call_opts.type === 'GET')
call_opts.query = parameters;
else {
call_opts.data = JSON.stringify(parameters);
}
return new APICall(call_opts);
},
/**
* Search CloudMine for text objects.
* Results may be affected by defaults and/or by the options parameter.
* @param {string} query Query parameters to search for.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
search: function(query, options) {
options = opts(this, options);
query = {q: query != null ? convertQueryInput(query) : ''}
var data = undefined;
if(options.method === "POST"){
data = JSON.stringify(query);
query = {}; // don't send q in URL
}
return new APICall({
action: 'search',
type: options.method || 'GET',
query: server_params(options, query),
data: data,
options: options
});
},
/**
* Search the CloudMine ElasticSearch endpoint. Must pass a valid
* ElasticSearch query in.
*/
search_es: function(klass, query, options) {
options = opts(this, options);
options.version = 'v2';
return new APICall({
action: 'class/' + klass + '/elasticsearch',
type: 'POST',
data: query,
options: options
});
},
/**
* Search CloudMine explicitly querying for files.
* Note: This does not search the contents of files.
* Results may be affected by defaults and/or by the options parameter.
* @param {string} query Additional query parameters to search for.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
searchFiles: function (query, options) {
query = convertQueryInput(query);
var newQuery = '[__type__ = "file"';
if (!query || query.replace(/\s+/, '').length == 0) {
newQuery += ']';
} else if (query[0] != '[') {
newQuery += '].' + query;
} else {
newQuery += (query[1] == ']' ? '' : ', ') + query.substring(1);
}
return this.search(newQuery, options);
},
/**
* Search CloudMine user objects by custom attributes.
* Results may be affected by defaults and/or by the options parameter.
* @param {string} query Additional query parameters to search for in [key="value", key="value"] format.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name searchUsers
* @memberOf WebService.prototype
*/
/**
* Search CloudMine user objects by custom attributes.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} query Additional query parameters to search for in {key: value, key: value} format.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name searchUsers^2
* @memberOf WebService.prototype
*/
searchUsers: function(query, options) {
query = {p: query != null ? convertQueryInput(query) : ''}
options = opts(this, options);
return new APICall({
action: 'account/search',
type: 'GET',
query: server_params(options, query),
options: options
});
},
/**
* Get all user objects.
* Results may be affected by defaults and/or by the options parameter.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
allUsers: function(options) {
options = opts(this, options);
return new APICall({
action: 'account',
type: 'GET',
query: server_params(options),
options: options
});
},
/**
* Sends a push notification to your users.
* This requires an API key with push permission.
* @param {object} [notification] A notification object. This object can have one or more fields for dispatching the notification.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
pushNotification: function(notification, options) {
options = opts(this, options);
return new APICall({
action: 'push',
type: 'POST',
query: server_params(options),
options: options,
data: JSON.stringify(notification)
});
},
/**
* Get specific user by id.
* @param {string} id User id being requested.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* Results may be affected by defaults and/or by the options parameter.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
getUser: function(id, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + id,
type: 'GET',
query: server_params(options),
options: options
});
},
/**
* Search using CloudMine's geoquery API.
* @param {string} field Field to search on.
* @param {number} longitude The longitude to search for objects at.
* @param {number} latitude The latitude to search for objects at.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @param {string} [options.units = 'km'] The unit to use when not specified for. Can be 'km', 'mi', 'm', 'ft'.
* @param {boolean} [options.distance = false] If true, include distance calculations in the meta result for objects.
* @param {string|number} [options.radius] Distance around the target. If string, include units. If number, specify the unit in options.unit.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
/**
* Search using CloudMine's geoquery API.
* @param {string} field Field to search on.
* @param {object} target A reference object that has geo-location data.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @param {string} [options.units = 'km'] The unit to use when not specified for. Can be 'km', 'mi', 'm', 'ft'.
* @param {boolean} [options.distance = false] If true, include distance calculations in the meta result for objects.
* @param {string|number} [options.radius] Distance around the target. If string, include units. If number, specify the unit in options.unit.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name searchGeo^2
* @memberOf WebService.prototype
*/
searchGeo: function(field, longitude, latitude, options) {
var geo, options;
// Source is 1 argument for object, 2 for lat/long
if (isObject(longitude)) {
options = latitude || {};
geo = extractGeo(longitude, field);
} else {
if (!options) options = {};
geo = extractGeo(longitude, latitude);
}
if (!geo) throw new TypeError('Parameters given do not provide geolocation data');
// Handle radius formats
var radius = options.radius;
if (isNumber(radius)) radius = ', ' + radius + (options && options.units ? options.units : 'km');
else if (isString(radius) && radius.length) {
radius = ', ' + radius;
if (!options.units) options.units = radius.match(/mi?|km|ft/)[0];
}
else radius = '';
var locTerms = (field || 'location') + ' near (' + geo.longitude + ', ' + geo.latitude + ')' + radius;
return this.search('[' + locTerms + ']', options);
},
/**
* Upload a file stored in CloudMine.
* @param {string} key The binary file's object key.
* @param {file|string} file FileAPI: A HTML5 FileAPI File object, Node.js: The filename to upload.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
upload: function(key, file, options) {
options = opts(this, options);
if (!key) key = this.keygen();
if (!options.filename) options.filename = key;
// Warning: may not necessarily use ajax to perform upload.
var apicall = new APICall({
action: 'binary/' + key,
type: 'post',
later: true,
encoding: 'binary',
options: options,
processResponse: APICall.basicResponse
});
function upload(data, type) {
if (!options.contentType) options.contentType = type || defaultType;
APICall.binaryUpload(apicall, data, options.filename, options.contentType).done();
}
if (isString(file) || (Buffer && file instanceof Buffer)) {
// Upload by filename
if (isNode) {
if (isString(file)) file = fs.readFileSync(file);
upload(file);
}
else NotSupported();
} else if (file.toDataURL) {
// Canvas will have a toDataURL function.
upload(file, 'image/png');
} else if (CanvasRenderingContext2D && file instanceof CanvasRenderingContext2D) {
upload(file.canvas, 'image/png');
} else if (isBinary(file)) {
// Binary files are base64 encoded from a buffer.
var reader = new FileReader();
/** @private */
reader.onabort = function() {
apicall.setData("FileReader aborted").abort();
}
/** @private */
reader.onerror = function(e) {
apicall.setData(e.target.error).abort();
}
/** @private */
reader.onload = function(e) {
upload(e.target.result);
}
// Don't need to transform Files to Blobs.
if (File && file instanceof File) {
if (!options.contentType && file.type != "") options.contentType = file.type;
} else {
file = new Blob([ new Uint8Array(file) ], {type: options.contentType || defaultType});
}
reader.readAsDataURL(file);
} else NotSupported();
return apicall;
},
/**
* Download a file stored in CloudMine.
* @param {string} key The binary file's object key.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {string} [filename] If present, the file will be downloaded directly to the computer with the
* filename given. This does not validate the filename given!
* @config {string} [mode] If buffer, automatically move returning data to either an ArrayBuffer or Buffer
* if supported. Otherwise the result will be a standard string.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
download: function(key, options) {
options = opts(this, options);
var response = {success: {}}, query;
if (options.filename) {
query = {
force_download: true,
apikey: options.apikey,
session_token: options.session_token,
filename: options.filename
}
}
var apicall = new APICall({
action: 'binary/' + key,
type: 'GET',
later: true,
encoding: 'binary',
options: options,
query: query
});
// Download file directly to computer if given a filename.
if (options.filename) {
if (isNode) {
apicall.setProcessor(function(data) {
response.success[key] = fs.writeFileSync(options.filename, data, 'binary');
return response;
}).done();
} else {
function detach() {
if (iframe.parentNode) document.body.removeChild(iframe);
}
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
setTimeout(function() { iframe.src = apicall.url; }, 25);
iframe.onload = function() {
clearTimeout(detach.timer);
detach.timer = setTimeout(detach, 5000);
};
detach.timer = setTimeout(detach, 60000);
response.success[key] = iframe;
}
apicall.done(response);
} else if (options.mode === 'buffer' && (ArrayBuffer || Buffer)) {
apicall.setProcessor(function(data) {
var buffer;
if (Buffer) {
buffer = new Buffer(data, 'binary');
} else {
buffer = new ArrayBuffer(data.length);
var charView = new Uint8Array(buffer);
for (var i = 0; i < data.length; ++i) {
charView[i] = data[i] & 0xFF;
}
}
response.success[key] = buffer;
return response;
}).done();
} else {
// Raw data return. Do not attempt to process the result.
apicall.setProcessor(function(data) {
response.success[key] = data;
return response;
}).done();
}
return apicall;
},
/**
* Create a new user.
* @param {object} data An object with an email, username, and password field.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {object} [options.profile] Create a user with the given user profile.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name createUser
* @memberOf WebService.prototype
*/
/**
* Create a new user.
* @param {string} auth The email to login as.
* @param {string} password The password to login as.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {object} [options.profile] Create a user with the given user profile.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name createUser^2
* @memberOf WebService.prototype
*/
createUser: function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password};
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
credentials: {
email: auth.email,
username: auth.username,
password: auth.password
},
profile: options.profile
});
return new APICall({
action: 'account/create',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
},
/**
* Update user object of logged in user.
* @param {object} data An object to merge into the logged in user object.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateUser
* @memberOf WebService.prototype
*/
/**
* Update user object of logged in user.
* @param {string} field The field to merge into the logged in user object.
* @param {string} value The value to set the field to.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateUser^2
* @memberOf WebService.prototype
*/
updateUser: function(field, value, options) {
if (isObject(field)) options = value;
else {
var out = {};
out[field] = value;
field = out;
}
options = opts(this, options);
return new APICall({
action: 'account',
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(field)
});
},
/**
* Update a user object without having a session token. Requires the use of the master key
* @param {string} user_id the user id of the user to update.
* @param {object} profile a JSON object representing the profile
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
*/
updateUserMaster: function(user_id, profile, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + user_id,
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(profile)
});
},
/**
* Change a user's password
* @param {object} data An object with email, password, and oldpassword fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name changePassword
* @memberOf WebService.prototype
*/
/**
* Change a user's password
* @param {string} user The email to change the password.
* @param {string} oldpassword The existing password for the user.
* @param {string} password The new password for the user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name changePassword^2
* @memberOf WebService.prototype
*/
changePassword: function(auth, oldpassword, password, options) {
if (isObject(auth)) options = oldpassword;
else auth = {email: auth, oldpassword: oldpassword, password: password};
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.oldpassword,
credentials: {
password: auth.password
}
});
return new APICall({
action: 'account/password/change',
type: 'POST',
data: payload,
options: options,
processResponse: APICall.basicResponse
});
},
/**
* Update a user password without having a session token. Requires the use of the master key
* @param {string} user_id The id of the user to change the password.
* @param {string} password The new password for the user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
changePasswordMaster: function(user_id, password, options) {
options = opts(this, options);
var payload = JSON.stringify({
password: password
});
return new APICall({
action: 'account/' + user_id + '/password/change',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
},
/**
* Change a user's credentials: user/email and/or password
* @param {object} auth An object with email, username, password, and new_password, new_email, new_username fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name changeCredentials
* @memberOf WebService.prototype
*/
changeCredentials: function(auth, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.password,
credentials: {
password: auth.new_password,
username: auth.new_username,
email: auth.new_email
}
});
return new APICall({
action: 'account/credentials',
type: 'POST',
data: payload,
options: options,
processResponse: APICall.basicResponse
});
},
/**
* Initiate a password reset request.
* @param {string} email The email to send a reset password email to.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
resetPassword: function(email, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: email
});
return new APICall({
action: 'account/password/reset',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
},
/**
* Change the password for an account from the token received from password reset.
* @param {string} token The token for password reset. Usually received by email.
* @param {string} newPassword The password to assign to the user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
confirmReset: function(token, newPassword, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
password: newPassword
});
return new APICall({
action: "account/password/reset/" + token,
type: 'POST',
data: payload,
processResponse: APICall.basicResponse,
options: options
});
},
/**
* Login as a user to access user-level data.
* @param {object} data An object hash with email / username, and password fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name login
* @memberOf WebService.prototype
*/
/**
* Login as a user to access user-level data.
* @param {string} auth The email of the user to login as
* @param {string} password The password for the user
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name login^2
* @memberOf WebService.prototype
*/
login: function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password};
options = opts(this, options);
options.applevel = true;
// Wipe out existing login information.
this.options.email = null;
this.options.username = null;
this.options.session_token = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', null, this.options.appid);
}
var payload = JSON.stringify({
username: auth.username,
email: auth.email,
password: auth.password
})
var self = this;
return new APICall({
action: 'account/login',
type: 'POST',
options: options,
data: payload,
processResponse: APICall.basicResponse
}).on('success', function(data) {
if (options.savelogin) {
store('email', auth.email, self.options.appid);
store('username', auth.username, self.options.appid);
store('session_token', data.session_token, self.options.appid);
}
self.options.email = auth.email;
self.options.username = auth.username;
self.options.session_token = data.session_token;
});
},
/**
* Login a user via a social network credentials.
* This only works for browsers (i.e. not in a node.js environment) and requires user interaction (a browser window).
* @param {string} network A network to authenticate against. @see WebService.SocialNetworks
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @config {string} [options.link] If false, do not link social network to currently logged in user.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
loginSocial: function(network, options) {
// This does not work with Node.JS, or unrecognized services.
if (isNode) NotSupported();
options = opts(this, options);
options.applevel = true;
var challenge = uuid(), self = this;
var apicall = new APICall({
action: 'account/social/login/status/'+challenge,
options: options,
later: true,
processResponse: function(data) {
if (data.finished) {
self.options.session_token = data.session_token;
self.options.userid = data.profile.__id__;
data = { success: data }
}
else {
self.options.session_token = null;
self.options.userid = null;
data = { errors: [ "Login unsuccessful." ] }
}
if (options.savelogin) {
store('session_token', data.success.session_token, self.options.appid);
store('userid', data.success.profile.__id__, self.options.appid);
}
return data;
}
});
var url = this.options.apiroot+"/v1/app/"+options.appid+"/account/social/login";
var urlParams = {
service: network,
apikey: options.apikey,
challenge: challenge
};
if (this.options.session_token && options.link !== false) {
urlParams.session_token = this.options.session_token;
}
if (options.scope) urlParams.scope = options.scope;
var sep = url.indexOf("?") === -1 ? "?" : "&";
url = url + sep + stringify(urlParams);
var win = window.open(url, challenge, "width=600,height=400,menubar=0,location=0,toolbar=0,status=0");
function checkOpen() {
if (win.closed) {
clearTimeout(checkOpen.interval);
apicall.done();
}
}
checkOpen.interval = setInterval(checkOpen, 50);
return apicall;
},
/**
* Query a social network.
* Must be logged in as a user who has logged in to a social network.
* @param {object} query An object with the parameters of the query.
* @config {string} query.network A network to authenticate against. @see WebService.SocialNetworks
* @config {string} query.endpoint The endpoint to hit, on the social network side. See the social network's documentation for more details.
* @config {string} query.method HTTP verb to use when querying.
* @config {object} query.headers Extra headers to pass in the HTTP request to the social network.
* @config {object} query.params Extra parameters to pass in the HTTP request to the social network.
* @config {string} query.data Data to pass in the body of the HTTP request.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @throws {Error} If the user is not logged in.
* @throws {Error} If query.headers is truthy and not an object.
* @throws {Error} If query.params is truthy and not an object.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
socialQuery: function(query, options) {
options = opts(this, options);
if(!options.session_token) throw new Error("Must be logged in to perform a social query");
if(query.headers && !isObject(query.headers)) throw new Error("Headers must be an object");
if(query.params && !isObject(query.params)) throw new Error("Extra parameters must be an object");
var url = "social/"+query.network+"/"+query.endpoint;
var urlParams = {};
if(query.headers) urlParams.headers = query.headers;
if(query.params) urlParams.params = query.params;
var apicall = new APICall({
action: url,
type: query.method,
query: urlParams,
options: options,
data: query.data,
contentType: 'application/octet-stream'
});
return apicall;
},
/**
* Logout the current user.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*/
logout: function(options) {
options = opts(this, options);
options.applevel = true;
var token = this.options.session_token;
this.options.email = null;
this.options.username = null;
this.options.session_token = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', this.options.appid);
}
return new APICall({
action: 'account/logout',
type: 'POST',
processResponse: APICall.basicResponse,
headers: {
'X-CloudMine-SessionToken': token
},
options: options
});
},
/**
* Verify if the given login and password is valid.
* @param {object} data An object with email / username, and password fields.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name verify
* @memberOf WebService.prototype
*/
/**
* Verify if the given email and password is valid.
* @param {string} auth The email to login
* @param {string} password The password of the user to login
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name verify^2
* @memberOf WebService.prototype
*/
verify: function(auth, password, options) {
if (isObject(auth)) opts = password;
else auth = {email: auth, password: password};
options = opts(this, options);
options.applevel = true;
return new APICall({
action: 'account/login',
type: 'POST',
processResponse: APICall.basicResponse,
data: JSON.stringify(auth),
options: options
});
},
/**
* Delete a user.
* If you are using the master api key, omit the user password to delete the user.
* If you are not using the master api key, provide the user name and password in the corresponding
* email and password fields.
*
* @param {object} data An object that may contain email / username fields and optionally a password field.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name deleteUser
* @memberOf WebService.prototype
*/
/**
* Delete a user.
* If you are using the master api key, omit the user password to delete the user.
* If you are not using the master api key, provide the user name and password in the corresponding
* email and password fields.
*
* @param {string} email The email of the user to delete. If using a master key use a user id.
* @param {string} password The password for the account. Omit if using a master key.
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name deleteUser^2
* @memberOf WebService.prototype
*/
deleteUser: function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password}
options = opts(this, options);
options.applevel = true;
var config = {
action: 'account',
type: 'DELETE',
options: options,
processResponse: APICall.basicResponse
};
// Drop session if we are referring to ourselves.
if (auth.email == this.options.email) {
this.options.session_token = null;
this.options.email = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', null, this.options.appid);
}
}
if (auth.password) {
// Non-master key access
config.data = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.password
})
} else {
// Master key access
config.action += '/' + auth.email;
}
return new APICall(config);
},
/**
* Create or update an ACL rule for user-level objects. The API will automatically generate
* an id field if an __id__ attribute is not present. If it is, the ACL rule is updated.
*
* @param {object} acl The ACL object. See CloudMine documentation for reference. Example:
* {
* "__id__": "a4f84f89b2f14a87a3faa87289d72f98",
* "members": ["8490e9c8d6d64e6f8d18df334ae4f4fb", "ecced9c0c4bd41f0ab0dcb93d2840fd8"],
* "permissions": ["r", "u"],
* "segments": {
* "public": true,
* "logged_in": true
* },
* "my_extra_info": 12345
* }
*
* @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateACL
* @memberOf WebService.prototype
*/
updateACL: function(acl, options){
options = opts(this, options);
return new APICall({
action: 'access',
type: 'PUT',
processResponse: APICall.basicResponse,
data: JSON.stringify(acl),
options: options
});
},
/**
* Get an ACL rule for user-level objects by id.
*
* @param {string} aclid The id of the ACL object to fetch.
* @return {APICall} An APICall instance for the web service request used to attach events.
*
* @function
* @name updateACL
* @memberOf WebService.prototype
*/
getACL: function(aclid, options){
options = opts(this, options);
return new APICall({
action: 'access/' + aclid,
type: 'GET',
processResponse: APICall.basicResponse,
options: options
});
},
/**
* Check if the store has a logged in user.
* @return {boolean} True if the user is logged in, false otherwise.
*/
isLoggedIn: function() {
return !!this.options.session_token;
},
/**
* Get the current userid
* @return {string} The logged in userid, if applicable.
*/
getUserID: function() {
return this.options.email;
},
/**
* Get the current session token.
* @return {string} The current session token, if logged in.
*/
getSessionToken: function() {
return this.options.session_token;
},
/**
* Get the current email.
* @return {string} The logged in email, if logged in.
*/
getEmail: function() {
return this.options.email;
},
/**
* Get the current username.
* @return {string} The logged in username, if logged in.
*/
getUsername: function() {
return this.options.username;
},
/**
* Get a default option that is sent to the server.
* @param {string} option A default parameter to send to the server.
* @return {*} The value of the default parameter.
*/
getOption: function(option) {
return (valid_params[option] ? this.options[option] : null);
},
/**
* Set a default option that is sent to the server
* @param {string} option A default parameter to send to the server.
* @param {string} value The value of the option to set.
* @return {boolean} true if the option was set, false for invalid options.
*/
setOption: function(option, value) {
if (valid_params[option]) {
this.options[option] = value;
return true;
}
return false;
},
/**
* Set the application or user-level data mode for this store.
* @param {boolean|undefined} state If true, this store will only operate in application data.
* If false, this store will only operate in user-level data.
* If null/undefined, this store will use user-level data if logged in,
* application data otherwise.
*/
useApplicationData: function(state) {
this.options.applevel = (state === true || state === false) ? state : undefined;
},
/**
* Determine if this store is using application data.
* @return {boolean} true if this store is using application data, false if is using user-level data.
*/
isApplicationData: function() {
if (this.options.applevel === true || this.options.applevel === false) return this.options.applevel;
return this.options.session_token == null;
},
keygen: uuid
};
WebService.VERSION = version;
// Supported Social Networks
WebService.SocialNetworks = [
'bodymedia',
'dropbox',
'facebook',
'fitbit',
'flickr',
'foursquare',
'gcontacts',
'gdocs',
'github',
'gmail',
'google',
'gplus',
'instagram',
'linkedin',
'meetup',
'runkeeper',
'tumblr',
'twitter',
'withings',
'wordpress',
'yammer',
'zeo'
];
/**
* Set the X-Unique-ID to be used in all WebService requests. This function allows it to be set
* on before the WebService object is instantiated.
*/
WebService.setXUniqueID = function(xUniqueID) {
global._$XUniqueID = xUniqueID;
}
/**
* <p>WebService will return an instance of this class that should be used to interact with
* the API. Upon completion of the AJAX call, this object will fire the event handlers based on
* what were attached.
*
* <p>You may chain event creation.
*
* <p><b>Note:</b> It is recommended to avoid referring directly to the ajax implementation used by this
* function. Depending on environment, features on it may vary since this library only
* requires a small subset of jQuery-like AJAX functionality.
*
* <p>Event firing order:
* <div>Successes: HTTP Code String, HTTP Code Number, 'success'</div>
* <div>Meta: 'meta' - This is for operations that can write meta data.</div>
* <div>Result: 'result' - This is results from code snippets if used.</div>
* <div>Errors: HTTP Code String, HTTP Code Number, 'error'</div>
*
* <p>Event callback signatures:
* <div>HTTP Codes: function(keys, responseObject, statusCode)</div>
* <div>'error': function(keys, responesObject)</div>
* <div>'success': function(keys, responseObject)</div>
* <div>'meta': function(keys, responseObject)</div>
* <div>'result: function(keys, responseObject)</div>
* <div>'abort': function(keys, responseObject)</div>
* @class
* @name APICall
*/
function APICall(config) {
this.config = merge({}, defaultConfig, config);
this._events = {};
var agent = 'JS/' + version;
var opts = this.config.options;
if (opts.appname) {
agent += ' ' + opts.appname.replace(agentInvalid, '_');
if (opts.appversion) {
agent += '/' + opts.appversion.replace(agentInvalid, '_');
}
}
// Fields that are available at the completion of the api call.
this.additionalData = this.config.callbackData;
this.data = null;
this.hasErrors = false;
this.requestData = this.config.data;
this.requestHeaders = {
'X-CloudMine-ApiKey': opts.apikey,
'X-CloudMine-Agent': agent,
'X-CloudMine-UT': opts.user_token
};
if (typeof(global) != 'undefined' && typeof global._$XUniqueID != 'undefined') {
this.requestHeaders['X-Unique-Id'] = global._$XUniqueID
}
this.responseHeaders = {};
this.responseText = null;
this.status = null;
this.type = this.config.type || 'GET';
// Build the URL and headers
var query = stringify(server_params(opts, this.config.query));
var root = '/', session = opts.session_token, applevel = opts.applevel;
if (applevel === false || (applevel !== true && session != null)) {
if (config.action.split('/')[0] !== 'account'){
root = '/user/';
}
if (session != null) this.requestHeaders['X-CloudMine-SessionToken'] = session;
}
// Merge in headers in case-insensitive (if necessary) manner.
for (var key in this.config.headers) {
mapInsensitive(this.requestHeaders, key, this.config.headers[key]);
}
this.config.headers = this.requestHeaders;
if (!isEmptyObject(perfComplete)) {
this.config.headers['X-CloudMine-UT'] += ';' + stringify(perfComplete, ':', ',', null, PERF_HEADER_LIMIT);
perfComplete = {};
}
this.setContentType(config.contentType || 'application/json');
var endpointVersion = this.config.options.version || 'v1';
var versionPath = '/' + endpointVersion + '/app/';
this.url = [this.config.options.apiroot, versionPath, this.config.options.appid, root, this.config.action].join("");
var sep = this.url.indexOf('?') === -1 ? '?' : '&';
this.url = [this.url, (query ? sep + query : "")].join("");
var self = this, sConfig = this.config, timestamp = +(new Date);
/** @private */
this.config.complete = function(xhr, status) {
var data;
if (xhr) {
data = xhr.responseText
self.status = xhr.status;
self.responseText = data;
self.responseHeaders = unstringify(xhr.getAllResponseHeaders(), /:\s*/, /(?:\r|\n)?\n/);
// Performance metrics, if applicable.
var requestId = mapInsensitive(self.responseHeaders, 'X-Request-Id');
if (requestId) perfComplete[requestId] = +(new Date) - timestamp;
// If we can parse the data as JSON or store the original data.
try {
self.data = JSON.parse(data || "{}");
} catch (e) {
self.data = data;
}
} else {
self.status = 'abort';
self.data = [ sConfig.data ];
}
// Parse the response only if a safe status
if (status == 'success' && self.status >= 200 && self.status < 300) {
// Preprocess data coming in to hash-hash: [success/errors].[httpcode]
data = sConfig.processResponse.call(self, self.data, xhr, self);
} else {
data = {errors: {}};
if (isString(self.data)) {
self.data = { errors: [ self.data ] } // This way, we can rely on this structure data[statuscode].errors to always be an Array of one or more errors
}
data.errors[self.status] = self.data;
}
setTimeout(function() {
APICall.complete(self, data);
}, 1);
}
// Let script continue before triggering ajax call
if (!this.config.later && this.config.async) {
setTimeout(function() {
if(!self.config.cancel)
self.xhr = ajax(self.url, sConfig);
}, 1);
}
}
/** @namespace APICall.prototype */
APICall.prototype = {
/**
* Attach an event listener to this APICall object.
* @param {string|number} eventType The event to listen to. Can be an http code as number or string,
* success, meta, result, error.
* @param {function} callback Callback to call upon event trigger.
* @param {object} context Context to call the callback in.
* @return {APICall} The current APICall object
*/
on: function(eventType, callback, context) {
if (isFunction(callback)) {
context = context || this;
if (!this._events[eventType]) this._events[eventType] = [];
// normal callback not called.
var self = this;
this._events[eventType].push([callback, context, function() {
self.off(eventType, callback, context);
callback.apply(this, arguments);
}]);
}
return this;
},
/**
* Trigger an event on this APICall object. This will call all event handlers in order.
* All parameters following event will be sent to the event handlers.
* @param {string|number} event The event to trigger.
* @return {APICall} The current APICall object
*/
trigger: function(event/*, arg1...*/) {
var events = this._events[event];
if (events != null) {
var args = slice(arguments, 1);
each(events, function(event) {
event[2].apply(event[1], args);
});
}
return this;
},
/**
* Remove event handlers.
* Event handlers will be removed based on the parameters given. If no parameters are given, all
* event handlers will be removed.
* @param {string|number} eventType The event type which can be an http code as number or string,
* or can be success, error, meta, result, abort.
* @param {function} callback The function that was used to create the callback.
* @param {object} context The context to call the callback in.
* @return {APICall} The current APICall object
*/
off: function(eventType, callback, context) {
if (eventType == null && callback == null && context == null) {
this._events = {};
} else if (eventType == null) {
each(this._events, function(value, key, collection) {
collection._events[key] = removeCallbacks(value, callback, context);
});
} else {
this._events[eventType] = removeCallbacks(this._events[eventType], callback, context);
}
return this;
},
/**
* Set the content-type for a waiting APICall.
* Note: this has no effect if the APICall has completed.
* @param {string} type The content-type to set. If not specified, this will use 'application/octet-stream'.
* @return {APICall} The current APICall object
*/
setContentType: function(type) {
type = type || defaultType;
if (this.config) {
this.config.contentType = type;
mapInsensitive(this.requestHeaders, 'content-type', type);
mapInsensitive(this.config.headers, 'content-type', type);
}
return this;
},
/**
* Aborts the current connection. This is ineffective for running synchronous calls or completed
* calls. Synchronous calls can be achieved by setting async to false in WebService.
* @return {APICall} The current APICall object
*/
abort: function() {
if (this.xhr) {
this.xhr.abort();
} else if (this.config) {
this.config.complete.call(this, this.xhr, 'abort');
}
// Cleanup leftover state.
if (this.xhr) {
this.xhr = undefined;
delete this.xhr;
}
if (this.config) {
this.config = undefined;
delete this.config;
}
return this;
},
/**
* Set data to send to the server. This is ineffective for running ajax calls.
* @return {APICall} The current APICall object
*/
setData: function(data) {
if (!this.xhr && this.config) {
this.config.data = data;
}
return this;
},
/**
* Set the data processor for the APICall. This is ineffective for running ajax calls.
* @return {APICall} The current APICall object
*/
setProcessor: function(func) {
if (!this.xhr && this.config) {
this.config.processResponse = func;
}
return this;
},
/**
* If a synchronous ajax call is done (via setting: options.async = false), you must call this function
* after you have attached all your event handlers. You should not attach event handlers after this
* is called.
*/
done: function(response) {
if (!this.xhr && this.config) {
if (response) {
this.xhr = true;
var self = this;
setTimeout(function() {
APICall.complete(self, response);
}, 1);
} else {
this.xhr = ajax(this.url, this.config);
}
}
return this;
},
/**
* Get a response header using case insensitive searching
* Note: It is faster to use the exact casing as no searching is necessary when matching.
* @param {string} key The header to retrieve, case insensitive.
* @return {string|null} The value of the header, or null
*/
getHeader: function(key) {
return mapInsensitive(this.responseHeaders, key);
}
};
/**
* Complete the given API Call, usually called after completed processing of data, though can be
* used to circumvent the standard AJAX call functionality for calls that are not currently running.
* @param {APICall} apicall The api call to affect. Can be either a completed request or a deferred request.
* @param {object} data Processed data where the top level keys are: success, errors, meta, result.
*
* @private
* @function
* @memberOf APICall
*/
APICall.complete = function(apicall, data) {
// Success results may have errors for certain keys
if (data.errors) apicall.hasErrors = true;
// Clean up temporary state.
if (apicall.config) {
apicall.config = undefined;
delete apicall.config;
}
if (apicall.xhr) {
apicall.xhr = undefined;
delete apicall.xhr;
}
// Data has been processed by this point and should exist in success, errors, meta, or results hashes.
// Event firing order: http status (e.g. ok, created), http status (e.g. 200, 201), success, meta, result, error.
if (data.success) {
// Callback signature: function(keys, response, statusCode)
if (httpcode[apicall.status]) apicall.trigger(httpcode[apicall.status], data.success, apicall, apicall.status);
apicall.trigger(apicall.status, data.success, apicall, apicall.status);
// Callback signature: function(keys, response);
apicall.trigger('success', data.success, apicall);
}
// Callback signature: function(keys, response)
if (data.meta) apicall.trigger('meta', data.meta, apicall);
// Callback signature: function(keys, response)
if (data.result) apicall.trigger('result', data.result, apicall);
// Errors needs to fire groups of errors depending on code result.
if (data.errors) {
// Callback signature: function(keys, reponse, statusCode)
for (var k in data.errors) {
if (httpcode[k]) apicall.trigger(httpcode[k], data.errors[k], apicall, k);
apicall.trigger(k, data.errors[k], apicall, k);
}
// Callback signature: function(keys, response)
apicall.trigger('error', data.errors, apicall);
}
// Callback signature: function(responseData, response)
apicall.trigger('complete', data, apicall);
}
/**
* Standard CloudMine response for the 200-299 range responses.
* This will transform the response so that APICall.complete will trigger the appropriate handlers.
*
* @private
* @function
* @memberOf APICall
*/
APICall.textResponse = function(data, xhr, response) {
var out = {};
if (data.success || data.errors || data.meta || data.result) {
if (data.count != null) response.count = data.count;
if (!isEmptyObject(data.success)) out.success = data.success;
if (!isEmptyObject(data.meta)) out.meta = data.meta;
if (!isEmptyObject(data.result)) out.result = data.result;
if (!isEmptyObject(data.errors)) {
out.errors = {};
for (var k in data.errors) {
var error = data.errors[k], code = 400;
// Unfortunately, errors are a bit inconsistent.
if (error.code) {
code = error.code;
error = error.message || error;
} else if (isString(error)) {
code = errors[error.toLowerCase()] || 400;
}
if (!out.errors[code]) out.errors[code] = {}
out.errors[code][k] = {errors: [ error ]};
}
}
// At least guarantee a success callback.
if (isEmptyObject(out)) {
if (this.config.options && this.config.options.snippet) out.result = {};
else out.success = {};
}
} else {
// Non-standard response. Just pass back the data we were given.
out = {success: data};
}
return out;
}
/**
* Minimal processing of data so that the success handler is called upon completion.
* This assumes any response in the 200-299 range is a success.
*
* @private
* @function
* @memberOf APICall
*/
APICall.basicResponse = function(data, xhr, response) {
return {success: data || {}};
}
/**
* Convert binary data in browsers to a transmitable version and assign it to the given
* api call.
* @param {APICall} apicall The APICall to affect, it should have later: true.
* @param {object|string} data The data to send to the server. Strings are expected to be base64 encoded.
* @param {string} filename The filename to upload as.
* @param {string} contentType The content-type of the file. If not specified, it will guess if possible,
* otherwise assume application/octet-stream.
* @return {APICall} The apicall object that was given.
*
* @private
* @function
* @memberOf APICall
*/
APICall.binaryUpload = function(apicall, data, filename, contentType) {
var boundary = uuid();
if (Buffer && data instanceof Buffer) {
data = data.toString('base64');
if (!contentType) contentType = defaultType;
} else {
if (data.toDataURL) data = data.toDataURL(contentType);
data = data.replace(/^data:(.*?);?base64,/, '');
if (!contentType) contentType = RegExp.$1 || defaultType;
}
apicall.setContentType('multipart/form-data; boundary=' + boundary);
return apicall.setData([
'--' + boundary,
'Content-Disposition: form-data; name="file"; filename="' + filename + '"',
'Content-Type: ' + contentType,
'Content-Transfer-Encoding: base64',
'',
data,
'--' + boundary + '--'
].join('\r\n'));
}
// Cache ids for perfAPICall
var perfComplete = {};
/**
* Node.JS jQuery-like ajax adapter.
* This is an internal class that is not exposed.
*
* @param {string} uri The complete url to hit.
* @param {object} config Parameters for the ajax request.
* @config {string} [contentType] The Content Type of the request.
* @config {string} [type] The type of request, e.g. 'get', 'post'
* @config {object} [headers] Request headers to send to the client.
* @config {boolean} [processData] If true, process the data given.
* @config {string|Array|Object} [data] Data to send to the server.
* @name HttpRequest
* @constructor
*/
function HttpRequest(uri, config) {
config = config || {};
this.status = 400;
this.responseText = [];
this._headers = {};
// disable connection pooling
// disable chunked transfer-encoding which nginx doesn't support
var opts = url.parse(uri);
opts.agent = false;
opts.method = config.type;
opts.headers = config.headers || {};
// Preprocess data if it is JSON data.
if (isObject(config.data) && config.processData) {
config.data = JSON.stringify(config.data);
}
// Authenticate request if we have authentication information.
if (config.username || config.password) {
opts.headers.Authorization = "Basic " + btoa(config.username + ':' + config.password);
}
// Attach a content-length
// Prevent node.js from sending transfer-encoding:chunked when there is no body
config.data = config.data || '';
if (isArray(config.data)) opts.headers['content-length'] = Buffer.byteLength(config.data);
else if (isString(config.data)) opts.headers['content-length'] = Buffer.byteLength(config.data);
// Fire request.
var self = this, cbContext = config.context || this;
this._textStatus = 'success';
this._request = (opts.protocol === "http:" ? http : https).request(opts, function(response) {
response.setEncoding(config.encoding || 'utf8');
response.on('data', function(chunk) {
self.responseText.push(chunk);
});
response.on('end', function () {
self._headers = stringify(response.headers, ': ', '\n', true) || "";
self.status = response.statusCode;
var data;
try {
// Process data if necessary.
data = self.responseText = self.responseText.join('');
if (config.dataType == 'json' || (config.dataType != 'text' && response.headers['content-type'].match(/\bapplication\/json\b/i))) {
data = JSON.parse(data);
}
} catch(e)
{
self._textStatus = 'parsererror';
}
if (self._textStatus == 'success' && self.status >= 200 && self.status < 300) {
if (config.success) config.success.call(cbContext, data, 'success', self);
} else if (config.error) {
config.error.call(cbContext, self, 'error', self.responseText);
}
if (config.complete) config.complete.call(cbContext, self, self._textStatus);
});
});
// Handle request errors.
this._request.on('error', function(e) {
self.status = e.status;
self.responseText = e.message;
self._textStatus = 'error';
if (config.error) config.error.call(cbContext, self, 'error', e.message);
if (config.complete) config.complete.call(cbContext, self, 'error');
});
// Send data (if present) and fire the request.
this._request.end(config.data);
}
/** @namespace HttpRequest.prototype */
HttpRequest.prototype = {
/**
* Return a given response header
* @param {string} The header field to retreive.
* @return {string|null} The value of that header, if it exists.
*/
getResponseHeader: function(header) {
return this._headers[header];
},
/**
* Get all the response headers.
* @return {object} An object representing all the response headers.
*/
getAllResponseHeaders: function() {
return this._headers;
},
/**
* Abort the current connection. This has no effect if the request is already completed.
* This will trigger an abort error event.
*/
abort: function() {
if (this._request) {
this._textStatus = 'abort';
this._request.abort();
this._request = undefined;
delete this._request;
}
}
};
// Remap some of the CloudMine API query parameters.
var valid_params = {
limit: 'limit',
sort: 'sort',
skip: 'skip',
snippet: 'f', // Run code snippet on the data
params: 'params', // Only applies to code snippets, parameters for the code snippet (JSON).
dontwait: 'async', // Only applies to code snippets, don't wait for results.
resultsonly: 'result_only', // Only applies to code snippets, only show results from code snippet.
shared: 'shared',
shared_only: 'shared_only',
userid: 'userid',
count: 'count',
distance: 'distance', // Only applies to geo-query searches
units: 'units', // Only applies to geo-query searches
extended_responses: 'extended_responses' // Only applies to atomic operations
};
// Default jQuery ajax configuration.
var defaultConfig = {
async: true,
later: false,
processData: false,
dataType: 'text',
processResponse: APICall.textResponse,
crossDomain: true,
cache: false
};
// Map HTTP codes that could come from CloudMine
var httpcode = {
200: 'ok',
201: 'created',
400: 'badrequest',
401: 'unauthorized',
404: 'notfound',
409: 'conflict',
500: 'servererror'
};
// Sometimes we only get a string back as an error.
var errors = {
'bad request': 400,
'permission denied': 401,
'unauthorized': 401,
'key does not exist': 404,
'not found': 404,
'conflict': 409
};
var PERF_HEADER_LIMIT = 20;
// Scope external dependencies, if necessary.
var base = this.window ? window : root;
var defaultType = 'application/octet-stream';
var File = base.File;
var FileReader = base.FileReader;
var ArrayBuffer = base.ArrayBuffer;
var Buffer = base.Buffer;
var CanvasRenderingContext2D = base.CanvasRenderingContext2D;
var BinaryClasses = [ File, Buffer, CanvasRenderingContext2D, ArrayBuffer, base.Uint8Array, base.Uint8ClampedArray, base.Uint16Array, base.Uint32Array, base.Int8Array, base.Int16Array, base.Int32Array, base.Float32Array, base.Float64Array ];
var agentInvalid = /[^a-zA-Z0-9._-]/g;
// Utility functions.
function hex() { return Math.round(Math.random() * 15).toString(16); }
function uuid() {
var out = Array(32), i;
out[14] = 4;
out[19] = ((Math.round(Math.random() * 16) & 3) | 8).toString(16);
for (i = 0; i < 14; ++i) { out[i] = hex(); }
for (i = 15; i < 19; ++i) { out[i] = hex(); }
for (i = 20; i < 32; ++i) { out[i] = hex(); }
return out.join('');
}
function opts(scope, options) {
// email used to be called userid. set email to userid if they're still using that.
if(options && options.userid && !options.email) options.email = options.userid;
return merge({}, scope.options, options);
}
var propCache = {};
var ROOT_COLLECTION = 'base';
function retrieve(key, collection) {
var col = getCollection(collection);
return col[key];
}
function store(key, value, collection) {
var col = getCollection(collection);
if (col[key] != value) {
col[key] = value;
saveCollection(collection);
}
return value;
}
function server_params(options, map) {
var key, value;
if (map == null) map = {};
for (key in valid_params) {
value = valid_params[key];
if (options[key] != null) {
map[value] = options[key];
}
}
return map;
}
// Callbacks stored as: [originalCallback, context, wrappedCallback]
function removeCallbacks(src, callback, context) {
return filter(src, function(event) {
return (!callback || event[0] == callback) && (!context || context == event[1]);
});
}
function slice(array, x, y) {
return Array.prototype.slice.call(array, x || 0, y || array.length);
}
function each(item, callback, context) {
context = context || this
if (isArray(item)) {
if (item.forEach) item.forEach(callback, context);
else {
for (var i = 0; i < item.length; ++i) {
var obj = item[i];
if (obj != null) callback.call(context, obj, k, context);
}
}
} else if (isObject(item)) {
for (var k in item) {
var obj = item[k];
if (obj != null) callback.call(context, obj, k, context);
}
}
}
function filter(item, callback, context) {
var out = null;
context = context || this;
if (isArray(item)) {
if (item.filter) {
out = item.filter(callback, context);
} else {
out = [];
each(item, function(value, key, collection) {
if (callback.apply(this, arguments)) out.push(value);
});
}
} else {
out = {};
each(item, function(value, key, collection) {
if (callback.apply(this, arguments)) out[key] = value;
});
}
return out;
}
function mapInsensitive(map, name, value) {
// Find the closest name if we haven't referenced it directly.
if (map[name] == null) {
var lower = name.toLowerCase();
for (var k in map) {
if (k.toLowerCase() === lower) {
name = k;
break;
}
}
}
if (value !== undefined) map[name] = value;
return map[name];
}
function isObject(item) {
return item && typeof item === "object"
}
function isString(item) {
return typeof item === "string"
}
function isNumber(item) {
return typeof item === "number" && !isNaN(item);
}
function isBinary(item) {
return isObject(item) && BinaryClasses.indexOf(item.constructor) > -1
}
function isArray(item) {
if (item === null) return false;
return isObject(item) && item.length != null
}
function isFunction(item) {
return typeof item === 'function';
}
function isGeopoint(item) {
return isObject(item) && item.__type__ === 'geopoint';
}
function extractGeo(x, y) {
if (isNumber(x) && isNumber(y)) {
return {latitude: y, longitude: x};
} else if (isObject(x)) {
// Got a field? try to extract from there.
if (y && isGeopoint(x[y])) return extractGeo(x[y]);
else {
// Search current object since we didn't specify a field as y.
var out = {
latitude: x.latitude || x.lat || x.y,
longitude: x.longitude || x.lng || x.x
};
if (isNumber(out.latitude) && isNumber(out.longitude)) return out;
// Search first level objects since we haven't found location data yet.
for (var key in x) {
if (isGeopoint(x[key])) {
return {
latitude: x.latitude || x.lat || x.y,
longitude: x.longitude || x.lng || x.x
};
}
}
}
}
return null;
}
function isEmptyObject(item) {
if (item) {
if (item % 1 === 0) {
return false;
}
else {
for (var k in item) {
if (item.hasOwnProperty(k)) {
return false;
}
}
}
}
return true;
}
function stringify(map, sep, eol, ignore, limit) {
sep = sep || '=';
limit = limit == undefined ? -1 : limit;
var out = [], val, escape = ignore ? nop : encodeURIComponent;
var numMapped = 0;
for (var k in map) {
if (map[k] != null && !isFunction(map[k])){
if(isArray(map[k])){
map[k].forEach(function(val){
out.push(escape(k) + sep + escape(val));
});
} else {
val = isObject(map[k]) ? JSON.stringify(map[k]) : map[k];
out.push(escape(k) + sep + escape(val));
}
}
numMapped++;
if (numMapped === limit) break;
}
return out.join(eol || '&');
}
function unstringify(input, sep, eol, ignore) {
var out = {};
if(isString(input)){
input = input.split(eol || '&');
var unescape = ignore ? nop : decodeURIComponent;
for (var i = 0; i < input.length; ++i) {
var str = input[i].split(sep);
out[unescape(str.shift())] = unescape(str.join(sep));
}
} else {
// error case - input is already an object
out = input;
}
return out;
}
function merge(obj/*, in...*/) {
for (var i = 1; i < arguments.length; ++i) {
each(arguments[i], function(value, key, collection) {
if (value != null) obj[key] = value;
});
}
return obj;
}
function convertQueryInput(input) {
if (isObject(input)) {
var out = [];
for (var key in input) {
out.push(key + " = " + JSON.stringify(input[key]));
}
return "[" + out.join(', ') + "]";
}
return input;
}
function NotSupported() { throw new Error("Unsupported operation"); }
function nop(s) { return s; }
// Export CloudMine objects.
var http, btoa, https, ajax, isNode, fs, url, getCollection, saveCollection;
if (!this.window) {
isNode = true;
url = require('url');
http = require('http');
https = require('https');
// in node lower than 0.12, this defaults to 5
https.globalAgent.maxSockets = 50;
http.globalAgent.maxSockets = 50;
fs = require('fs');
module.exports = { WebService: WebService };
// Wrap the HttpRequest constructor so it operates the same as jQuery/Zepto.
ajax = function(url, config) {
return new HttpRequest(url, config);
}
// Node.JS adapter to support base64 encoding.
btoa = function(str, encoding) {
return new Buffer(str, encoding || 'utf8').toString('base64');
}
/**
* Retreive JSON data from the given collection. This will attempt to load a .cm.(collection).json file first
* from the current directory, and on any error, try to load the same name from the home directory.
* @param {string} [collection="base"] The collection to retreive data from.
* @return An object from the stored JSON data.
* @private
*/
getCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
// Load the collection if it hasn't already been loaded. Try current directory, or $HOME.
if (!propCache[collection]) {
var locations = ['.', process.env.HOME + "/."], loc;
while ((loc = locations.shift()) != null) {
try {
propCache[collection] = JSON.parse(fs.readFileSync(loc + collection + '.json', 'UTF8'));
break;
} catch (e) {}
}
if (!loc) propCache[collection] = {};
}
return propCache[collection];
}
/**
* Save JSON data to the given collection. This will attempt to save to .cm.(collection).json file first
* in the current directory, and on any error, try to save to the same name in the home directory.
* @param {string} [collection="base"] The collection to save data from.
* @throws {Error} If the file could not be saved.
* @private
*/
saveCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
// Attempt to save to the current directory, or load from $HOME.
var locations = ['.', process.env.HOME + "/."], loc;
while ((loc = locations.shift()) != null) {
try {
fs.writeFileSync(loc + collection + '.json', JSON.stringify(propCache[collection] || {}), 'UTF8');
break;
} catch (e) {}
}
if (!loc) throw new Error("Could not save CloudMine session data");
}
} else {
isNode = false;
window.cloudmine = window.cloudmine || {};
window.cloudmine.WebService = WebService;
btoa = window.btoa;
// Require the use of jQuery or Zepto.
if (($ = this.jQuery || this.Zepto) != null) {
ajax = $.ajax;
if ($.support) $.support.cors = true
}
else throw new Error("Missing jQuery-compatible ajax implementation");
/**
* Retreive JSON data from the given collection in html5 local storage.
* @param {string} [collection="base"] The collection to retreive data from.
* @return An object from the stored JSON data.
* @private
*/
getCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
if (!propCache[collection]) {
try {
propCache[collection] = JSON.parse(localStorage.getItem(collection)) || {};
} catch (e) {
propCache[collection] = {};
}
}
return propCache[collection];
}
/**
* Save JSON data to the given collection in html5 local storage.
* @param {string} [collection="base"] The collection to save data from.
* @private
*/
saveCollection = function(collection) {
collection = 'cm.' + (collection || ROOT_COLLECTION);
localStorage.setItem(collection, JSON.stringify(propCache[collection] || {}));
}
}
})();
| updating version number in code and cleaning up search_es pre reqs
| js/cloudmine.js | updating version number in code and cleaning up search_es pre reqs | <ide><path>s/cloudmine.js
<ide> /* CloudMine JavaScript Library v0.10.x cloudmineinc.com | https://github.com/cloudmine/cloudmine-js/blob/master/LICENSE */
<ide> (function() {
<del> var version = '0.9.18';
<add> var version = '0.9.20';
<ide>
<ide> /**
<ide> * Construct a new WebService instance
<ide> });
<ide> },
<ide>
<del> /**
<del> * Search the CloudMine ElasticSearch endpoint. Must pass a valid
<del> * ElasticSearch query in.
<del> */
<add> /**
<add> * Search CloudMine for text objects.
<add> * Results may be affected by defaults and/or by the options parameter.
<add> * @param {string} klass The Elasticsearch __class__ you want to query.
<add> * @param {string} query The Elasticsearch query to be executed.
<add> * @param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
<add> * @return {APICall} An APICall instance for the web service request used to attach events.
<add> */
<ide> search_es: function(klass, query, options) {
<ide> options = opts(this, options);
<ide> options.version = 'v2'; |
|
Java | lgpl-2.1 | d7528d8cf3ba13cca6020e208fc43ea62fe25e6b | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* Copyright (C) 2002-2004 David Pavlis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.interpreter;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.primitive.CloverDouble;
import org.jetel.data.primitive.CloverInteger;
import org.jetel.data.primitive.CloverLong;
import org.jetel.data.primitive.DecimalFactory;
import org.jetel.data.primitive.HugeDecimal;
import org.jetel.data.primitive.Numeric;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.TransformationGraph;
import org.jetel.interpreter.node.*;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.Compare;
import org.jetel.util.StringUtils;
/**
* Executor of FilterExpression parse tree.
*
* @author dpavlis
* @since 16.9.2004
*
* Executor of FilterExpression parse tree
*/
public class TransformLangExecutor implements TransformLangParserVisitor,
TransformLangParserConstants{
public static final int BREAK_BREAK=1;
public static final int BREAK_CONTINUE=2;
public static final int BREAK_RETURN=3;
protected Stack stack;
protected boolean breakFlag;
protected int breakType;
protected Properties globalParameters;
protected DataRecord[] inputRecords;
protected DataRecord[] outputRecords;
protected Node emptyNode; // used as replacement for empty statements
protected TransformationGraph graph;
protected Log runtimeLogger;
static Log logger = LogFactory.getLog(TransformLangExecutor.class);
/**
* Constructor
*/
public TransformLangExecutor(Properties globalParameters) {
stack = new Stack();
breakFlag = false;
this.globalParameters=globalParameters;
emptyNode = new SimpleNode(Integer.MAX_VALUE);
}
public TransformLangExecutor() {
this(null);
}
public TransformationGraph getGraph() {
return graph;
}
public void setGraph(TransformationGraph graph) {
this.graph = graph;
}
public Log getRuntimeLogger() {
return runtimeLogger;
}
public void setRuntimeLogger(Log runtimeLogger) {
this.runtimeLogger = runtimeLogger;
}
/**
* Set input data records for processing.<br>
* Referenced input data fields will be resolved from
* these data records.
*
* @param inputRecords array of input data records carrying values
*/
public void setInputRecords(DataRecord[] inputRecords){
this.inputRecords=inputRecords;
}
/**
* Set output data records for processing.<br>
* Referenced output data fields will be resolved from
* these data records - assignment (in code) to output data field
* will result in assignment to one of these data records.
*
* @param outputRecords array of output data records for setting values
*/
public void setOutputRecords(DataRecord[] outputRecords){
this.outputRecords=outputRecords;
}
/**
* Set global parameters which may be reference from within the
* transformation source code
*
* @param parameters
*/
public void setGlobalParameters(Properties parameters){
this.globalParameters=parameters;
}
/**
* Allows to store parameter/value on stack from
* where it can be read by executed script/function.
* @param obj Object/value to be stored
* @since 10.12.2006
*/
public void setParameter(Object obj){
stack.push(obj);
}
/**
* Method which returns result of executing parse tree.<br>
* Basically, it returns whatever object was left on top of executor's
* stack (usually as a result of last executed expression/operation).<br>
* It can be called repetitively in order to read all objects from stack.
*
* @return Object saved on stack or NULL if no more objects are available
*/
public Object getResult() {
return stack.pop();
}
/**
* Return value of globally defined variable determined by slot number.
* Slot can be obtained by calling <code>TransformLangParser.getGlobalVariableSlot(<i>varname</i>)</code>
*
* @param varSlot
* @return Object - depending of Global variable type
* @since 6.12.2006
*/
public Object getGlobalVariable(int varSlot){
return stack.getGlobalVar(varSlot);
}
/**
* Allows to set value of defined global variable.
*
* @param varSlot
* @param value
* @since 6.12.2006
*/
public void setGlobalVariable(int varSlot,Object value){
stack.storeGlobalVar(varSlot,value);
}
/* *********************************************************** */
/* implementation of visit methods for each class of AST node */
/* *********************************************************** */
/* it seems to be necessary to define a visit() method for SimpleNode */
public Object visit(SimpleNode node, Object data) {
// throw new TransformLangExecutorRuntimeException(node,
// "Error: Call to visit for SimpleNode");
return data;
}
public Object visit(CLVFStart node, Object data) {
int i, k = node.jjtGetNumChildren();
for (i = 0; i < k; i++)
node.jjtGetChild(i).jjtAccept(this, data);
return data; // this value is ignored in this example
}
public Object visit(CLVFStartExpression node, Object data) {
int i, k = node.jjtGetNumChildren();
for (i = 0; i < k; i++)
node.jjtGetChild(i).jjtAccept(this, data);
return data; // this value is ignored in this example
}
public Object visit(CLVFOr node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}else{
if (((Boolean)a).booleanValue()){
stack.push(Stack.TRUE_VAL);
return data;
}
}
node.jjtGetChild(1).jjtAccept(this, data);
a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}
if (((Boolean) a).booleanValue()) {
stack.push(Stack.TRUE_VAL);
} else {
stack.push(Stack.FALSE_VAL);
}
return data;
}
public Object visit(CLVFAnd node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}else{
if (!((Boolean)a).booleanValue()){
stack.push(Stack.FALSE_VAL);
return data;
}
}
node.jjtGetChild(1).jjtAccept(this, data);
a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}
if (!((Boolean)a).booleanValue()) {
stack.push(Stack.FALSE_VAL);
return data;
} else {
stack.push(Stack.TRUE_VAL);
return data;
}
}
public Object visit(CLVFComparison node, Object data) {
int cmpResult = 2;
boolean lValue = false;
// special handling for Regular expression
if (node.cmpType == REGEX_EQUAL) {
node.jjtGetChild(0).jjtAccept(this, data);
Object field1 = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object field2 = stack.pop();
if (field1 instanceof CharSequence && field2 instanceof Matcher) {
Matcher regex = (Matcher) field2;
regex.reset(((CharSequence) field1));
if (regex.matches()) {
lValue = true;
} else {
lValue = false;
}
} else {
Object[] arguments = { field1, field2 };
throw new TransformLangExecutorRuntimeException(node,arguments,
"regex equal - wrong type of literal(s)");
}
// other types of comparison
} else {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
try {
if (a instanceof Numeric && b instanceof Numeric) {
cmpResult = ((Numeric) a).compareTo((Numeric) b);
/*
* }else if (a instanceof Number && b instanceof Number){
* cmpResult=Compare.compare((Number)a,(Number)b);
*/
} else if (a instanceof Date && b instanceof Date) {
cmpResult = ((Date) a).compareTo((Date) b);
} else if (a instanceof CharSequence
&& b instanceof CharSequence) {
cmpResult = Compare.compare((CharSequence) a,
(CharSequence) b);
} else if (a instanceof Boolean && b instanceof Boolean) {
if (node.cmpType==EQUAL || node.cmpType==NON_EQUAL){
cmpResult = ((Boolean) a).equals(b) ? 0 : -1;
}else{
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"compare - unsupported comparison operator ["+tokenImage[node.cmpType]+"] for literals/expressions");
}
} else {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"compare - incompatible literals/expressions");
}
} catch (ClassCastException ex) {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"compare - incompatible literals/expressions");
}
switch (node.cmpType) {
case EQUAL:
if (cmpResult == 0) {
lValue = true;
}
break;// equal
case LESS_THAN:
if (cmpResult == -1) {
lValue = true;
}
break;// less than
case GREATER_THAN:
if (cmpResult == 1) {
lValue = true;
}
break;// grater than
case LESS_THAN_EQUAL:
if (cmpResult <= 0) {
lValue = true;
}
break;// less than equal
case GREATER_THAN_EQUAL:
if (cmpResult >= 0) {
lValue = true;
}
break;// greater than equal
case NON_EQUAL:
if (cmpResult != 0) {
lValue = true;
}
break;
default:
// this should never happen !!!
logger.fatal("Internal error: Unsupported comparison operator !");
throw new RuntimeException("Internal error - Unsupported comparison operator !");
}
}
stack.push(lValue ? Stack.TRUE_VAL : Stack.FALSE_VAL);
return data;
}
public Object visit(CLVFAddNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"add - NULL value not allowed");
}
// if (!(b instanceof Numeric || b instanceof CharSequence)) {
// throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
// "add - wrong type of literal");
// }
try {
if (a instanceof Numeric && b instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.add((Numeric) b);
stack.push(result);
} else if (a instanceof Date && b instanceof Numeric) {
Calendar result = Calendar.getInstance();
result.setTime((Date) a);
result.add(Calendar.DATE, ((Numeric) b).getInt());
stack.push(result.getTime());
} else if (a instanceof CharSequence) {
CharSequence a1 = (CharSequence) a;
StringBuilder buf=new StringBuilder(a1.length()*2);
StringUtils.strBuffAppend(buf,a1);
if (b instanceof CharSequence) {
StringUtils.strBuffAppend(buf,(CharSequence)b);
} else {
buf.append(b);
}
stack.push(buf);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"add - wrong type of literal(s)");
}
} catch (ClassCastException ex) {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"add - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFSubNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"sub - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"sub - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.sub((Numeric) b);
stack.push(result);
} else if (a instanceof Date) {
Calendar result = Calendar.getInstance();
result.setTime((Date) a);
result.add(Calendar.DATE, ((Numeric) b).getInt() * -1);
stack.push(result.getTime());
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"sub - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFMulNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"mul - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"mul - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.mul((Numeric) b);
stack.push(result);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"mul - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFDivNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"div - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"div - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
try{
result.div((Numeric) b);
}catch(ArithmeticException ex){
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,"div - arithmetic exception - "+ex.getMessage());
}
stack.push(result);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"div - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFModNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"mod - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"mod - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.mod((Numeric) b);
stack.push(result);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"mod - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFNegation node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value instanceof Boolean) {
stack.push(((Boolean) value).booleanValue() ? Stack.FALSE_VAL
: Stack.TRUE_VAL);
} else {
throw new TransformLangExecutorRuntimeException(node, new Object[] { value },
"logical condition does not evaluate to BOOLEAN value");
}
return data;
}
public Object visit(CLVFSubStrNode node, Object data) {
int length, from;
node.jjtGetChild(0).jjtAccept(this, data);
Object str = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object fromO = stack.pop();
node.jjtGetChild(2).jjtAccept(this, data);
Object lengthO = stack.pop();
if (lengthO == null || fromO == null || str == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { lengthO,
fromO, str }, "substring - NULL value not allowed");
}
try {
length = ((Numeric) lengthO).getInt();
from = ((Numeric) fromO).getInt();
} catch (Exception ex) {
Object arguments[] = { lengthO, fromO, str };
throw new TransformLangExecutorRuntimeException(node,arguments, "substring - "
+ ex.getMessage());
}
if (str instanceof CharSequence) {
stack.push(((CharSequence) str).subSequence(from, from + length));
} else {
Object[] arguments = { lengthO, fromO, str };
throw new TransformLangExecutorRuntimeException(node,arguments,
"substring - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFUppercaseNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
CharSequence seq = (CharSequence) a;
node.strBuf.setLength(0);
node.strBuf.ensureCapacity(seq.length());
for (int i = 0; i < seq.length(); i++) {
node.strBuf.append(Character.toUpperCase(seq.charAt(i)));
}
stack.push(node.strBuf);
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"uppercase - wrong type of literal");
}
return data;
}
public Object visit(CLVFLowercaseNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
CharSequence seq = (CharSequence) a;
node.strBuf.setLength(0);
node.strBuf.ensureCapacity(seq.length());
for (int i = 0; i < seq.length(); i++) {
node.strBuf.append(Character.toLowerCase(seq.charAt(i)));
}
stack.push(node.strBuf);
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"lowercase - wrong type of literal");
}
return data;
}
public Object visit(CLVFTrimNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
int start, end;
if (a instanceof CharSequence) {
CharSequence seq = (CharSequence) a;
int length = seq.length();
for (start = 0; start < length; start++) {
if (seq.charAt(start) != ' ' && seq.charAt(start) != '\t') {
break;
}
}
for (end = length - 1; end >= 0; end--) {
if (seq.charAt(end) != ' ' && seq.charAt(end) != '\t') {
break;
}
}
if (start > end)
stack.push("");
else
stack.push(seq.subSequence(start, end + 1));
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"trim - wrong type of literal");
}
return data;
}
public Object visit(CLVFLengthNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
stack.push(new CloverInteger(((CharSequence) a).length()));
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"length - wrong type of literal");
}
return data;
}
public Object visit(CLVFTodayNode node, Object data) {
stack.push(stack.calendar.getTime() );
return data;
}
public Object visit(CLVFIsNullNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value == null) {
stack.push(Stack.TRUE_VAL);
} else {
if (value instanceof CharSequence) {
stack.push( ((CharSequence)value).length()==0 ? Stack.TRUE_VAL : Stack.FALSE_VAL);
}else {
stack.push(Stack.FALSE_VAL);
}
}
return data;
}
public Object visit(CLVFNVLNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value == null) {
node.jjtGetChild(1).jjtAccept(this, data);
// not necessary: stack.push(stack.pop());
} else {
if ((value instanceof CharSequence) && (((CharSequence)value).length()==0)) {
node.jjtGetChild(1).jjtAccept(this, data);
}else {
stack.push(value);
}
}
return data;
}
public Object visit(CLVFLiteral node, Object data) {
stack.push(node.value);
return data;
}
public Object visit(CLVFInputFieldLiteral node, Object data) {
DataRecord record = inputRecords[node.recordNo];
if (record == null) {
stack.push(null);
} else {
DataField field = record.getField(node.fieldNo);
if (field instanceof Numeric) {
stack.push(((Numeric) field).duplicateNumeric());
} else {
stack.push(field.getValue());
}
}
// old
// stack.push(inputRecords[node.recordNo].getField(node.fieldNo).getValue());
// we return reference to DataField so we can
// perform extra checking in special cases
return node.field;
}
public Object visit(CLVFOutputFieldLiteral node, Object data) {
//stack.push(inputRecords[node.recordNo].getField(node.fieldNo));
// we return reference to DataField so we can
// perform extra checking in special cases
return data;
}
public Object visit(CLVFGlobalParameterLiteral node, Object data) {
stack.push(globalParameters!=null ? globalParameters.getProperty(node.name) : null);
return data;
}
public Object visit(CLVFRegexLiteral node, Object data) {
stack.push(node.matcher);
return data;
}
public Object visit(CLVFConcatNode node, Object data) {
Object a;
StringBuilder strBuf = new StringBuilder(40);
int numChildren = node.jjtGetNumChildren();
for (int i = 0; i < numChildren; i++) {
node.jjtGetChild(i).jjtAccept(this, data);
a = stack.pop();
if (a instanceof CharSequence) {
StringUtils.strBuffAppend(strBuf,(CharSequence) a);
} else {
if (a != null) {
strBuf.append(a);
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"concat - wrong type of literal(s)");
}
}
}
stack.push(strBuf);
return data;
}
public Object visit(CLVFDateAddNode node, Object data) {
int shiftAmount;
node.jjtGetChild(0).jjtAccept(this, data);
Object date = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object amount = stack.pop();
try {
shiftAmount = ((Numeric) amount).getInt();
} catch (Exception ex) {
Object arguments[] = { amount };
throw new TransformLangExecutorRuntimeException(node,arguments, "dateadd - "
+ ex.getMessage());
}
if (date instanceof Date) {
node.calendar.setTime((Date) date);
node.calendar.add(node.calendarField, shiftAmount);
stack.push(node.calendar.getTime());
} else {
Object arguments[] = { date };
throw new TransformLangExecutorRuntimeException(node,arguments,
"dateadd - no Date expression");
}
return data;
}
public Object visit(CLVFDate2NumNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object date = stack.pop();
if (date instanceof Date) {
node.calendar.setTime((Date) date);
stack.push(new CloverInteger(node.calendar.get(node.calendarField)));
} else {
Object arguments[] = { date };
throw new TransformLangExecutorRuntimeException(node,arguments,
"date2num - no Date expression");
}
return data;
}
public Object visit(CLVFDateDiffNode node, Object data) {
Object date1, date2;
node.jjtGetChild(0).jjtAccept(this, data);
date1 = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
date2 = stack.pop();
if (date1 instanceof Date && date2 instanceof Date) {
long diffSec = (((Date) date1).getTime() - ((Date) date2).getTime()) / 1000;
int diff = 0;
switch (node.calendarField) {
case Calendar.SECOND:
// we have the difference in seconds
diff = (int) diffSec;
break;
case Calendar.MINUTE:
// how many minutes'
diff = (int) diffSec / 60;
break;
case Calendar.HOUR_OF_DAY:
diff = (int) diffSec / 3600;
break;
case Calendar.DAY_OF_MONTH:
// how many days is the difference
diff = (int) diffSec / 86400;
break;
case Calendar.WEEK_OF_YEAR:
// how many weeks
diff = (int) diffSec / 604800;
break;
case Calendar.MONTH:
node.start.setTime((Date) date1);
node.end.setTime((Date) date2);
diff = (node.start.get(Calendar.MONTH) + node.start
.get(Calendar.YEAR) * 12)
- (node.end.get(Calendar.MONTH) + node.end
.get(Calendar.YEAR) * 12);
break;
case Calendar.YEAR:
node.start.setTime((Date) date1);
node.end.setTime((Date) date2);
diff = node.start.get(node.calendarField)
- node.end.get(node.calendarField);
break;
default:
Object arguments[] = { new Integer(node.calendarField) };
throw new TransformLangExecutorRuntimeException(node,arguments,
"datediff - wrong difference unit");
}
stack.push(new CloverInteger(diff));
} else {
Object arguments[] = { date1, date2 };
throw new TransformLangExecutorRuntimeException(node,arguments,
"datediff - no Date expression");
}
return data;
}
public Object visit(CLVFMinusNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value instanceof Numeric) {
Numeric result = ((Numeric) value).duplicateNumeric();
result.mul(Stack.NUM_MINUS_ONE);
stack.push(result);
} else {
Object arguments[] = { value };
throw new TransformLangExecutorRuntimeException(node,arguments,
"minus - not a number");
}
return data;
}
public Object visit(CLVFReplaceNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object str = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object regexO = stack.pop();
node.jjtGetChild(2).jjtAccept(this, data);
Object withO = stack.pop();
if (withO == null || regexO == null || str == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { withO,
regexO, str }, "NULL value not allowed");
}
if (str instanceof CharSequence && withO instanceof CharSequence
&& regexO instanceof CharSequence) {
if (node.pattern == null || !node.stored.equals(regexO)) {
node.pattern = Pattern.compile(((CharSequence) regexO)
.toString());
node.matcher = node.pattern.matcher((CharSequence) str);
node.stored = regexO;
} else {
node.matcher.reset((CharSequence) str);
}
stack.push(node.matcher.replaceAll(((CharSequence) withO)
.toString()));
} else {
Object[] arguments = { withO, regexO, str };
throw new TransformLangExecutorRuntimeException(node,arguments,
"replace - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFNum2StrNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
if (node.radix == 10) {
stack.push(((Numeric) a).toString());
} else {
if (a instanceof CloverInteger) {
stack.push(Integer.toString(((CloverInteger) a).getInt(),
node.radix));
} else if (a instanceof CloverLong) {
stack.push(Long.toString(((CloverLong) a).getLong(),
node.radix));
} else if (a instanceof CloverDouble && node.radix == 16) {
stack.push(Double.toHexString(((CloverDouble) a)
.getDouble()));
} else {
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"num2str - can't convert number to string using specified radix");
}
}
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node, arguments,
"num2str - wrong type of literal");
}
return data;
}
public Object visit(CLVFStr2NumNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
try {
Object value = null;
switch (node.numType) {
case INT_VAR:
value = new CloverInteger(Integer.parseInt(
((CharSequence) a).toString(), node.radix));
break;
case LONG_VAR:
value = new CloverLong(Long.parseLong(((CharSequence) a)
.toString(), node.radix));
break;
case DECIMAL_VAR:
if (node.radix == 10) {
value = DecimalFactory.getDecimal(((CharSequence) a)
.toString());
} else {
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"str2num - can't convert string to decimal number using specified radix");
}
break;
default:
// get double/number type
switch (node.radix) {
case 10:
case 16:
value = new CloverDouble(Double
.parseDouble(((CharSequence) a).toString()));
break;
default:
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"str2num - can't convert string to number/double number using specified radix");
}
}
stack.push(value);
} catch (NumberFormatException ex) {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,
arguments, "str2num - can't convert \"" + a + "\"");
}
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node, arguments,
"str2num - wrong type of literal");
}
return data;
}
public Object visit(CLVFDate2StrNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Date) {
stack.push(node.dateFormat.format((Date)a));
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"date2str - wrong type of literal");
}
return data;
}
public Object visit(CLVFStr2DateNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
try {
stack.push(node.dateFormat.parse(((CharSequence)a).toString()));
} catch (java.text.ParseException ex) {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"str2date - can't convert \"" + a + "\"");
}
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"str2date - wrong type of literal");
}
return data;
}
public Object visit(CLVFIffNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object condition = stack.pop();
if (condition instanceof Boolean) {
if (((Boolean) condition).booleanValue()) {
node.jjtGetChild(1).jjtAccept(this, data);
} else {
node.jjtGetChild(2).jjtAccept(this, data);
}
stack.push(stack.pop());
} else {
Object[] arguments = { condition };
throw new TransformLangExecutorRuntimeException(node,arguments,
"iif - condition does not evaluate to BOOLEAN value");
}
return data;
}
public Object visit(CLVFPrintErrNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (node.printLine){
StringBuilder buf=new StringBuilder((a != null ? a.toString() : "<null>"));
buf.append(" (on line: ").append(node.getLineNumber());
buf.append(" col: ").append(node.getColumnNumber()).append(")");
System.err.println(buf);
}else{
System.err.println(a != null ? a : "<null>");
}
return data;
}
public Object visit(CLVFPrintStackNode node, Object data) {
for (int i=stack.top;i>=0;i--){
System.err.println("["+i+"] : "+stack.stack[i]);
}
return data;
}
/***************************************************************************
* Transformation Language executor starts here.
**************************************************************************/
public Object visit(CLVFForStatement node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data); // set up of the loop
boolean condition = false;
Node loopCondition = node.jjtGetChild(1);
Node increment = node.jjtGetChild(2);
Node body;
try{
body=node.jjtGetChild(3);
}catch(ArrayIndexOutOfBoundsException ex){
body=emptyNode;
}
try {
loopCondition.jjtAccept(this, data); // evaluate the condition
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// loop execution
while (condition) {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) {
return data;
}
}
increment.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}
}
return data;
}
public Object visit(CLVFWhileStatement node, Object data) {
boolean condition = false;
Node loopCondition = node.jjtGetChild(0);
Node body;
try{
body=node.jjtGetChild(1);
}catch(ArrayIndexOutOfBoundsException ex){
body=emptyNode;
}
try {
loopCondition.jjtAccept(this, data); // evaluate the condition
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// loop execution
while (condition) {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data;
}
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}
}
return data;
}
public Object visit(CLVFIfStatement node, Object data) {
boolean condition = false;
try {
node.jjtGetChild(0).jjtAccept(this, data); // evaluate the
// condition
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"condition does not evaluate to BOOLEAN value");
} catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// first if
if (condition) {
node.jjtGetChild(1).jjtAccept(this, data);
} else { // if else part exists
if (node.jjtGetNumChildren() > 2) {
node.jjtGetChild(2).jjtAccept(this, data);
}
}
return data;
}
public Object visit(CLVFDoStatement node, Object data) {
boolean condition = false;
Node loopCondition = node.jjtGetChild(1);
Node body = node.jjtGetChild(0);
// loop execution
do {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data;
}
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = ((Boolean) stack.pop()).booleanValue();
}catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
} while (condition);
return data;
}
public Object visit(CLVFSwitchStatement node, Object data) {
// get value of switch && push/leave it on stack
boolean match=false;
node.jjtGetChild(0).jjtAccept(this, data);
Object switchVal=stack.pop();
int numChildren = node.jjtGetNumChildren();
int numCases = node.hasDefaultClause ? numChildren-1 : numChildren;
// loop over remaining case statements
for (int i = 1; i < numCases; i++) {
stack.push(switchVal);
if (node.jjtGetChild(i).jjtAccept(this, data)==Stack.TRUE_VAL){
match=true;
}
if (breakFlag) {
if (breakType == BREAK_BREAK) {
breakFlag = false;
}
break;
}
}
// test whether execute default branch
if (node.hasDefaultClause && !match){
node.jjtGetChild(numChildren-1).jjtAccept(this, data);
}
return data;
}
public Object visit(CLVFCaseExpression node, Object data) {
// test if literal (as child 0) is equal to data on stack
// if so, execute block (child 1)
boolean match = false;
Object switchVal = stack.pop();
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
try {
if (switchVal instanceof Numeric) {
match = (((Numeric) value).compareTo((Numeric) switchVal) == 0);
} else if (switchVal instanceof CharSequence) {
match = (Compare.compare((CharSequence) switchVal,
(CharSequence) value) == 0);
} else if (switchVal instanceof Date) {
match = (((Date) switchVal).compareTo((Date) value) == 0);
} else if (switchVal instanceof Boolean) {
match = ((Boolean) switchVal).equals((Boolean) value);
}
} catch (ClassCastException ex) {
Object[] args=new Object[] {switchVal,value};
throw new TransformLangExecutorRuntimeException(node,args,"incompatible literals in case clause");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid case value");
}
if (match){
node.jjtGetChild(1).jjtAccept(this, data);
return Stack.TRUE_VAL;
}else{
return Stack.FALSE_VAL;
}
}
public Object visit(CLVFPlusPlusNode node, Object data) {
Node childNode = node.jjtGetChild(0);
if (childNode instanceof CLVFVariableLiteral) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode;
Object var=stack.getVar(varNode.localVar, varNode.varSlot);
if (var instanceof Numeric){
((Numeric)var).add(Stack.NUM_ONE);
stack.push(((Numeric)var).duplicateNumeric());
}else if (var instanceof Date){
stack.calendar.setTime((Date)var);
stack.calendar.add(Calendar.DATE, 1);
stack.push(stack.calendar.getTime());
}else{
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
} else {
childNode.jjtAccept(this, data);
try {
Numeric num = ((Numeric) stack.pop()).duplicateNumeric();
num.add(Stack.NUM_ONE);
stack.push(num);
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"expression is not of numeric type");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid numeric expression");
}
}
return data;
}
public Object visit(CLVFMinusMinusNode node, Object data) {
Node childNode = node.jjtGetChild(0);
if (childNode instanceof CLVFVariableLiteral) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode;
Object var=stack.getVar(varNode.localVar, varNode.varSlot);
if (var instanceof Numeric){
((Numeric)var).sub(Stack.NUM_ONE);
stack.push(((Numeric)var).duplicateNumeric());
}else if (var instanceof Date){
stack.calendar.setTime((Date)var);
stack.calendar.add(Calendar.DATE, 1);
stack.push(stack.calendar.getTime());
}else{
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
} else {
childNode.jjtAccept(this, data);
try {
Numeric num = ((Numeric) stack.pop()).duplicateNumeric();
num.add(Stack.NUM_ONE);
stack.push(num);
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"expression is not of numeric type");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid numeric expression");
}
}
return data;
}
public Object visit(CLVFBlock node, Object data) {
int childern = node.jjtGetNumChildren();
for (int i = 0; i < childern; i++) {
node.jjtGetChild(i).jjtAccept(this, data);
// have we seen contiue/break/return statement ??
if (breakFlag){
if (breakType!=BREAK_RETURN)
stack.pop();
return data;
}
stack.pop();
}
return data;
}
/*
* Loop & block & function control nodes
*/
public Object visit(CLVFBreakStatement node, Object data) {
breakFlag = true; // we encountered break statement;
breakType=BREAK_BREAK;
return data;
}
public Object visit(CLVFContinueStatement node, Object data) {
breakFlag = true; // we encountered continue statement;
breakType= BREAK_CONTINUE;
return data;
}
public Object visit(CLVFReturnStatement node, Object data) {
if (node.jjtHasChildren()){
node.jjtGetChild(0).jjtAccept(this, data);
}
breakFlag = true;
breakType = BREAK_RETURN;
return data;
}
public Object visit(CLVFBreakpointNode node, Object data) {
// list all variables
System.err.println("** list of global variables ***");
for (int i=0;i<stack.globalVarSlot.length;System.out.println(stack.globalVarSlot[i++]));
System.err.println("** list of local variables ***");
for (int i=0;i<stack.localVarCounter;i++)
System.out.println(stack.localVarSlot[stack.localVarSlotOffset+i]);
return data;
}
/*
* Variable declarations
*/
public Object visit(CLVFVarDeclaration node, Object data) {
// test for duplicite declaration - should have been done before
/*
* if (stack.symtab.containsKey(node.name)) { throw new
* TransformLangExecutorRuntimeException(node, "variable already
* declared - \"" + node.name + "\""); }
*/
Object value;
// create global/local variable
switch (node.type) {
case INT_VAR:
value = new CloverInteger(0);
break;
case LONG_VAR:
value = new CloverLong(0);
break;
case DOUBLE_VAR:
value = new CloverDouble(0);
break;
case DECIMAL_VAR:
if (node.length > 0) {
if (node.precision > 0) {
value = DecimalFactory.getDecimal(node.length,
node.precision);
} else {
value = DecimalFactory.getDecimal(node.length, 0);
}
} else {
value = DecimalFactory.getDecimal();
}
break;
case STRING_VAR:
value = new StringBuilder();
break;
case DATE_VAR:
value = new Date();
break;
case BOOLEAN_VAR:
value = Stack.FALSE_VAL;
break;
default:
throw new TransformLangExecutorRuntimeException(node,
"variable declaration - "
+ "unknown variable type for variable \""
+ node.name + "\"");
}
stack.storeVar(node.localVar, node.varSlot, value);
if (node.jjtHasChildren()) {
node.jjtGetChild(0).jjtAccept(this, data);
Object initValue = stack.pop();
try {
switch (node.type) {
case INT_VAR:
case LONG_VAR:
case DOUBLE_VAR:
case DECIMAL_VAR:
((Numeric) value).setValue((Numeric) initValue);
break;
case STRING_VAR:
if (initValue != null)
StringUtils.strBuffAppend((StringBuilder) value,
(CharSequence) initValue);
break;
case DATE_VAR:
((Date) value).setTime(((Date) initValue).getTime());
break;
case BOOLEAN_VAR:
stack.storeVar(node.localVar, node.varSlot,
(Boolean) initValue);
// boolean is not updatable - we replace the reference
break;
}
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + initValue
+ "\" to variable \"" + node.name
+ "\" - incompatible data types");
} catch (NumberFormatException ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of number \"" + initValue
+ "\" to variable \"" + node.name + "\" : "
+ ex.getMessage());
} catch (TransformLangExecutorRuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + value
+ "\" to variable \"" + node.name + "\" : "
+ ex.getMessage());
}
}
return data;
}
public Object visit(CLVFVariableLiteral node, Object data) {
Object var = stack.getVar(node.localVar, node.varSlot);
// variable can be null
stack.push(var);
/*
if (var != null) {
stack.push(var);
} else {
throw new TransformLangExecutorRuntimeException(node, "unknown variable \""
+ node.varName + "\"");
}
*/
return data;
}
public Object visit(CLVFAssignment node, Object data) {
//TODO: proper handling of NULL value assignment
CLVFVariableLiteral childNode=(CLVFVariableLiteral) node.jjtGetChild(0);
Object variable = stack.getVar(childNode.localVar,childNode.varSlot);
node.jjtGetChild(1).jjtAccept(this, data);
Object value = stack.pop();
try {
if (variable instanceof Numeric) {
((Numeric) variable).setValue((Numeric) value);
} else if (variable instanceof StringBuilder) {
StringBuilder var = (StringBuilder) variable;
var.setLength(0);
if (value !=null) StringUtils.strBuffAppend(var,(CharSequence) value);
} else if (variable instanceof Boolean) {
stack.storeVar(childNode.localVar,childNode.varSlot, (Boolean)value); // boolean is not updatable - we replace the reference
// stack.put(varName,((Boolean)value).booleanValue() ?
// Stack.TRUE_VAL : Stack.FALSE_VAL);
} else if (variable instanceof Date) {
((Date) variable).setTime(((Date) value).getTime());
} else {
throw new TransformLangExecutorRuntimeException(node,
"unknown variable \"" + childNode.varName + "\"");
}
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + value + "\" to variable \""
+ childNode.varName + "\" - incompatible data types");
} catch (NumberFormatException ex){
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of number \"" + value + "\" to variable \"" + childNode.varName + "\" : "+ex.getMessage());
} catch (TransformLangExecutorRuntimeException ex){
throw ex;
} catch (Exception ex){
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + value + "\" to variable \"" + childNode.varName + "\" : "+ex.getMessage());
}
return data;
}
public Object visit(CLVFMapping node, Object data) {
DataField field=outputRecords[node.recordNo].getField(node.fieldNo);
int arity=node.jjtGetNumChildren(); // how many children we have defined
Object value=null;
try{
// we try till success or no more options
for (int i=0;i<arity;i++){
node.jjtGetChild(i).jjtAccept(this, data);
value=stack.pop();
try{
// TODO: small hack
if (field instanceof Numeric){
((Numeric)field).setValue((Numeric)value);
}else{
field.setValue(value);
}
break; // success during assignment, finish looping
}catch(Exception ex){
if (i == arity-1)
throw ex;
}
}
}catch(BadDataFormatException ex){
if (!outputRecords[node.recordNo].getField(node.fieldNo).getMetadata().isNullable()){
throw new TransformLangExecutorRuntimeException(node,"can't assign NULL to \"" + node.fieldName + "\"");
}else{
throw new TransformLangExecutorRuntimeException(node,"data format exception when mapping \"" + node.fieldName + "\" - assigning \""
+ value + "\"");
}
}catch(TransformLangExecutorRuntimeException ex){
throw ex;
}catch(Exception ex){
String msg=ex.getMessage();
throw new TransformLangExecutorRuntimeException(node,
(msg!=null ? msg : "") +
" when mapping \"" + node.fieldName + "\" ("+DataFieldMetadata.type2Str(field.getType())
+") - assigning \"" + value + "\" ("+(value!=null ? value.getClass(): "unknown class" )+")");
}
return data;
}
/*
* Declaration & calling of Functions here
*/
public Object visit(CLVFFunctionCallStatement node, Object data) {
//put call parameters on stack
node.childrenAccept(this,data);
CLVFFunctionDeclaration executionNode=node.callNode;
// open call frame
stack.pushFuncCallFrame();
// store call parameters from stack as local variables
for (int i=executionNode.numParams-1;i>=0; stack.storeLocalVar(i--,stack.pop()));
// execute function body
// loop execution
Object returnData;
int numChildren=executionNode.jjtGetNumChildren();
for (int i=0;i<numChildren;i++){
executionNode.jjtGetChild(i).jjtAccept(this,data);
returnData=stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_RETURN){
if (returnData!=null)
stack.push(returnData);
break;
}
}
}
stack.popFuncCallFrame();
return data;
}
public Object visit(CLVFFunctionDeclaration node, Object data) {
return data;
}
public Object visit(CLVFStatementExpression node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
return data;
}
public Object executeFunction(CLVFFunctionDeclaration executionNode, Object[] data) {
//put call parameters on stack
if (data==null){
data=new Object[0];
}
// open call frame
stack.pushFuncCallFrame();
// store call parameters from stack as local variables
for (int i=executionNode.numParams-1;i>=0; i--) {
stack.storeLocalVar(i, data[i]);
}
// execute function body
// loop execution
Object returnData;
int numChildren=executionNode.jjtGetNumChildren();
for (int i=0;i<numChildren;i++){
executionNode.jjtGetChild(i).jjtAccept(this,data);
returnData=stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_RETURN){
if (returnData!=null)
stack.push(returnData);
break;
}
}
}
stack.popFuncCallFrame();
return data;
}
/*
* MATH functions log,log10,exp,pow,sqrt,round
*/
public Object visit(CLVFSqrtNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble(Math.sqrt(((Numeric)a).getDouble()) ));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing SQRT function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"sqrt - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFLogNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble(Math.log(((Numeric)a).getDouble()) ));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"log - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFLog10Node node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble( Math.log10(((Numeric)a).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG10 function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"log10 - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFExpNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble( Math.exp(((Numeric)a).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing EXP function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"exp - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFRoundNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverLong(Math.round(((Numeric)a).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing ROUND function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"round - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFPowNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a instanceof Numeric && b instanceof Numeric) {
try{
stack.push(new CloverDouble(Math.pow(((Numeric)a).getDouble(),
((Numeric)b).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing POW function",ex);
}
}else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"pow - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFPINode node, Object data) {
stack.push(Stack.NUM_PI);
return data;
}
public Object visit(CLVFTruncNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Date ) {
stack.calendar.setTime((Date)a);
stack.calendar.set(Calendar.HOUR_OF_DAY, 0);
stack.calendar.set(Calendar.MINUTE , 0);
stack.calendar.set(Calendar.SECOND , 0);
stack.calendar.set(Calendar.MILLISECOND , 0);
stack.push( stack.calendar.getTime() );
}else if (a instanceof Numeric){
stack.push(new CloverLong(((Numeric)a).getLong()));
}else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"trunc - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFRaiseErrorNode node,Object data){
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
throw new TransformLangExecutorRuntimeException(node,null,
"!!! Exception raised by user: "+((a!=null) ? a.toString() : "no message"));
}
public Object visit(CLVFSequenceNode node, Object data) {
Object seqVal = null;
if (node.sequence == null) {
if (graph != null) {
node.sequence = graph.getSequence(node.sequenceName);
} else {
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain Sequence \"" + node.sequenceName
+ "\" from graph - graph is not assigned");
}
if (node.sequence == null) {
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain Sequence \"" + node.sequenceName
+ "\" from graph \"" + graph.getName() + "\"");
}
}
switch (node.opType) {
case CLVFSequenceNode.OP_RESET:
node.sequence.reset();
seqVal = Stack.NUM_ZERO;
break;
case CLVFSequenceNode.OP_CURRENT:
switch (node.retType) {
case LONG_VAR:
seqVal = new CloverLong(node.sequence.currentValueLong());
break;
case STRING_VAR:
seqVal = node.sequence.currentValueString();
default:
seqVal = new CloverInteger(node.sequence.currentValueInt());
}
break;
default: // default is next value from sequence
switch (node.retType) {
case LONG_VAR:
seqVal = new CloverLong(node.sequence.nextValueLong());
break;
case STRING_VAR:
seqVal = node.sequence.nextValueString();
default:
seqVal = new CloverInteger(node.sequence.nextValueInt());
}
}
stack.push(seqVal);
return data;
}
public Object visit(CLVFLookupNode node,Object data){
DataRecord record=null;
if (node.lookup == null) {
node.lookup = graph.getLookupTable(node.lookupName);
if (node.lookup == null) {
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain LookupTable \"" + node.lookupName
+ "\" from graph \"" + graph.getName() + "\"");
}
if (node.opType == CLVFLookupNode.OP_GET) {
node.fieldNum = node.lookup.getMetadata().getFieldPosition(
node.fieldName);
if (node.fieldNum < 0) {
throw new TransformLangExecutorRuntimeException(node,
"Invalid field name \"" + node.fieldName
+ "\" at LookupTable \"" + node.lookupName
+ "\" in graph \"" + graph.getName() + "\"");
}
node.lookup.setLookupKey(new Object[node.jjtGetNumChildren()]);
}
}
switch(node.opType){
case CLVFLookupNode.OP_INIT:
try{
node.lookup.init();
}catch(ComponentNotReadyException ex){
throw new TransformLangExecutorRuntimeException(node,
"Error when initializing lookup table \""+node.lookupName+"\" :",
ex);
}
return data;
case CLVFLookupNode.OP_FREE:
node.lookup.free();
return data;
case CLVFLookupNode.OP_NUM_FOUND:
stack.push(new CloverInteger(node.lookup.getNumFound()));
return data;
case CLVFLookupNode.OP_GET:
Object keys[]=new Object[node.jjtGetNumChildren()];
for(int i=0;i<node.jjtGetNumChildren();i++){
node.jjtGetChild(i).jjtAccept(this, data);
keys[i]=stack.pop();
}
record=node.lookup.get(keys);
break;
case CLVFLookupNode.OP_NEXT:
record=node.lookup.getNext();
}
if(record!=null){
stack.push(record.getField(node.fieldNum).getValue());
}else{
stack.push(null);
}
return data;
}
public Object visit(CLVFPrintLogNode node, Object data) {
if (runtimeLogger == null) {
throw new TransformLangExecutorRuntimeException(node,
"Can NOT perform logging operation - no logger defined");
}
node.jjtGetChild(0).jjtAccept(this, data);
Object msg = stack.pop();
switch (node.level) {
case 1: //| "debug"
runtimeLogger.debug(msg);
break;
case 2: //| "info"
runtimeLogger.info(msg);
break;
case 3: //| "warn"
runtimeLogger.warn(msg);
break;
case 4: //| "error"
runtimeLogger.error(msg);
break;
case 5: //| "fatal"
runtimeLogger.fatal(msg);
break;
default:
runtimeLogger.trace(msg);
}
return data;
}
} | cloveretl.engine/src/org/jetel/interpreter/TransformLangExecutor.java | /*
* Copyright (C) 2002-2004 David Pavlis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.interpreter;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.primitive.CloverDouble;
import org.jetel.data.primitive.CloverInteger;
import org.jetel.data.primitive.CloverLong;
import org.jetel.data.primitive.DecimalFactory;
import org.jetel.data.primitive.HugeDecimal;
import org.jetel.data.primitive.Numeric;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.TransformationGraph;
import org.jetel.interpreter.node.*;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.Compare;
import org.jetel.util.StringUtils;
/**
* Executor of FilterExpression parse tree.
*
* @author dpavlis
* @since 16.9.2004
*
* Executor of FilterExpression parse tree
*/
public class TransformLangExecutor implements TransformLangParserVisitor,
TransformLangParserConstants{
public static final int BREAK_BREAK=1;
public static final int BREAK_CONTINUE=2;
public static final int BREAK_RETURN=3;
protected Stack stack;
protected boolean breakFlag;
protected int breakType;
protected Properties globalParameters;
protected DataRecord[] inputRecords;
protected DataRecord[] outputRecords;
protected Node emptyNode; // used as replacement for empty statements
protected TransformationGraph graph;
protected Log runtimeLogger;
static Log logger = LogFactory.getLog(TransformLangExecutor.class);
/**
* Constructor
*/
public TransformLangExecutor(Properties globalParameters) {
stack = new Stack();
breakFlag = false;
this.globalParameters=globalParameters;
emptyNode = new SimpleNode(Integer.MAX_VALUE);
}
public TransformLangExecutor() {
this(null);
}
public TransformationGraph getGraph() {
return graph;
}
public void setGraph(TransformationGraph graph) {
this.graph = graph;
}
public Log getRuntimeLogger() {
return runtimeLogger;
}
public void setRuntimeLogger(Log runtimeLogger) {
this.runtimeLogger = runtimeLogger;
}
/**
* Set input data records for processing.<br>
* Referenced input data fields will be resolved from
* these data records.
*
* @param inputRecords array of input data records carrying values
*/
public void setInputRecords(DataRecord[] inputRecords){
this.inputRecords=inputRecords;
}
/**
* Set output data records for processing.<br>
* Referenced output data fields will be resolved from
* these data records - assignment (in code) to output data field
* will result in assignment to one of these data records.
*
* @param outputRecords array of output data records for setting values
*/
public void setOutputRecords(DataRecord[] outputRecords){
this.outputRecords=outputRecords;
}
/**
* Set global parameters which may be reference from within the
* transformation source code
*
* @param parameters
*/
public void setGlobalParameters(Properties parameters){
this.globalParameters=parameters;
}
/**
* Allows to store parameter/value on stack from
* where it can be read by executed script/function.
* @param obj Object/value to be stored
* @since 10.12.2006
*/
public void setParameter(Object obj){
stack.push(obj);
}
/**
* Method which returns result of executing parse tree.<br>
* Basically, it returns whatever object was left on top of executor's
* stack (usually as a result of last executed expression/operation).<br>
* It can be called repetitively in order to read all objects from stack.
*
* @return Object saved on stack or NULL if no more objects are available
*/
public Object getResult() {
return stack.pop();
}
/**
* Return value of globally defined variable determined by slot number.
* Slot can be obtained by calling <code>TransformLangParser.getGlobalVariableSlot(<i>varname</i>)</code>
*
* @param varSlot
* @return Object - depending of Global variable type
* @since 6.12.2006
*/
public Object getGlobalVariable(int varSlot){
return stack.getGlobalVar(varSlot);
}
/**
* Allows to set value of defined global variable.
*
* @param varSlot
* @param value
* @since 6.12.2006
*/
public void setGlobalVariable(int varSlot,Object value){
stack.storeGlobalVar(varSlot,value);
}
/* *********************************************************** */
/* implementation of visit methods for each class of AST node */
/* *********************************************************** */
/* it seems to be necessary to define a visit() method for SimpleNode */
public Object visit(SimpleNode node, Object data) {
// throw new TransformLangExecutorRuntimeException(node,
// "Error: Call to visit for SimpleNode");
return data;
}
public Object visit(CLVFStart node, Object data) {
int i, k = node.jjtGetNumChildren();
for (i = 0; i < k; i++)
node.jjtGetChild(i).jjtAccept(this, data);
return data; // this value is ignored in this example
}
public Object visit(CLVFStartExpression node, Object data) {
int i, k = node.jjtGetNumChildren();
for (i = 0; i < k; i++)
node.jjtGetChild(i).jjtAccept(this, data);
return data; // this value is ignored in this example
}
public Object visit(CLVFOr node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}else{
if (((Boolean)a).booleanValue()){
stack.push(Stack.TRUE_VAL);
return data;
}
}
node.jjtGetChild(1).jjtAccept(this, data);
a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}
if (((Boolean) a).booleanValue()) {
stack.push(Stack.TRUE_VAL);
} else {
stack.push(Stack.FALSE_VAL);
}
return data;
}
public Object visit(CLVFAnd node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}else{
if (!((Boolean)a).booleanValue()){
stack.push(Stack.FALSE_VAL);
return data;
}
}
node.jjtGetChild(1).jjtAccept(this, data);
a=stack.pop();
if (! (a instanceof Boolean)){
Object params[]=new Object[]{a};
throw new TransformLangExecutorRuntimeException(node,params,"logical condition does not evaluate to BOOLEAN value");
}
if (!((Boolean)a).booleanValue()) {
stack.push(Stack.FALSE_VAL);
return data;
} else {
stack.push(Stack.TRUE_VAL);
return data;
}
}
public Object visit(CLVFComparison node, Object data) {
int cmpResult = 2;
boolean lValue = false;
// special handling for Regular expression
if (node.cmpType == REGEX_EQUAL) {
node.jjtGetChild(0).jjtAccept(this, data);
Object field1 = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object field2 = stack.pop();
if (field1 instanceof CharSequence && field2 instanceof Matcher) {
Matcher regex = (Matcher) field2;
regex.reset(((CharSequence) field1));
if (regex.matches()) {
lValue = true;
} else {
lValue = false;
}
} else {
Object[] arguments = { field1, field2 };
throw new TransformLangExecutorRuntimeException(node,arguments,
"regex equal - wrong type of literal(s)");
}
// other types of comparison
} else {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
try {
if (a instanceof Numeric && b instanceof Numeric) {
cmpResult = ((Numeric) a).compareTo((Numeric) b);
/*
* }else if (a instanceof Number && b instanceof Number){
* cmpResult=Compare.compare((Number)a,(Number)b);
*/
} else if (a instanceof Date && b instanceof Date) {
cmpResult = ((Date) a).compareTo((Date) b);
} else if (a instanceof CharSequence
&& b instanceof CharSequence) {
cmpResult = Compare.compare((CharSequence) a,
(CharSequence) b);
} else if (a instanceof Boolean && b instanceof Boolean) {
if (node.cmpType==EQUAL || node.cmpType==NON_EQUAL){
cmpResult = ((Boolean) a).equals(b) ? 0 : -1;
}else{
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"compare - unsupported comparison operator ["+tokenImage[node.cmpType]+"] for literals/expressions");
}
} else {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"compare - incompatible literals/expressions");
}
} catch (ClassCastException ex) {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"compare - incompatible literals/expressions");
}
switch (node.cmpType) {
case EQUAL:
if (cmpResult == 0) {
lValue = true;
}
break;// equal
case LESS_THAN:
if (cmpResult == -1) {
lValue = true;
}
break;// less than
case GREATER_THAN:
if (cmpResult == 1) {
lValue = true;
}
break;// grater than
case LESS_THAN_EQUAL:
if (cmpResult <= 0) {
lValue = true;
}
break;// less than equal
case GREATER_THAN_EQUAL:
if (cmpResult >= 0) {
lValue = true;
}
break;// greater than equal
case NON_EQUAL:
if (cmpResult != 0) {
lValue = true;
}
break;
default:
// this should never happen !!!
logger.fatal("Internal error: Unsupported comparison operator !");
throw new RuntimeException("Internal error - Unsupported comparison operator !");
}
}
stack.push(lValue ? Stack.TRUE_VAL : Stack.FALSE_VAL);
return data;
}
public Object visit(CLVFAddNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"add - NULL value not allowed");
}
// if (!(b instanceof Numeric || b instanceof CharSequence)) {
// throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
// "add - wrong type of literal");
// }
try {
if (a instanceof Numeric && b instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.add((Numeric) b);
stack.push(result);
} else if (a instanceof Date && b instanceof Numeric) {
Calendar result = Calendar.getInstance();
result.setTime((Date) a);
result.add(Calendar.DATE, ((Numeric) b).getInt());
stack.push(result.getTime());
} else if (a instanceof CharSequence) {
CharSequence a1 = (CharSequence) a;
StringBuilder buf=new StringBuilder(a1.length()*2);
StringUtils.strBuffAppend(buf,a1);
if (b instanceof CharSequence) {
StringUtils.strBuffAppend(buf,(CharSequence)b);
} else {
buf.append(b);
}
stack.push(buf);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"add - wrong type of literal(s)");
}
} catch (ClassCastException ex) {
Object arguments[] = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"add - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFSubNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"sub - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"sub - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.sub((Numeric) b);
stack.push(result);
} else if (a instanceof Date) {
Calendar result = Calendar.getInstance();
result.setTime((Date) a);
result.add(Calendar.DATE, ((Numeric) b).getInt() * -1);
stack.push(result.getTime());
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"sub - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFMulNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"mul - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"mul - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.mul((Numeric) b);
stack.push(result);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"mul - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFDivNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"div - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"div - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
try{
result.div((Numeric) b);
}catch(ArithmeticException ex){
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,"div - arithmetic exception - "+ex.getMessage());
}
stack.push(result);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"div - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFModNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a == null || b == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { a, b },
"mod - NULL value not allowed");
}
if (!(b instanceof Numeric)) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { b },
"mod - wrong type of literal");
}
if (a instanceof Numeric) {
Numeric result = ((Numeric) a).duplicateNumeric();
result.mod((Numeric) b);
stack.push(result);
} else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"mod - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFNegation node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value instanceof Boolean) {
stack.push(((Boolean) value).booleanValue() ? Stack.FALSE_VAL
: Stack.TRUE_VAL);
} else {
throw new TransformLangExecutorRuntimeException(node, new Object[] { value },
"logical condition does not evaluate to BOOLEAN value");
}
return data;
}
public Object visit(CLVFSubStrNode node, Object data) {
int length, from;
node.jjtGetChild(0).jjtAccept(this, data);
Object str = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object fromO = stack.pop();
node.jjtGetChild(2).jjtAccept(this, data);
Object lengthO = stack.pop();
if (lengthO == null || fromO == null || str == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { lengthO,
fromO, str }, "substring - NULL value not allowed");
}
try {
length = ((Numeric) lengthO).getInt();
from = ((Numeric) fromO).getInt();
} catch (Exception ex) {
Object arguments[] = { lengthO, fromO, str };
throw new TransformLangExecutorRuntimeException(node,arguments, "substring - "
+ ex.getMessage());
}
if (str instanceof CharSequence) {
stack.push(((CharSequence) str).subSequence(from, from + length));
} else {
Object[] arguments = { lengthO, fromO, str };
throw new TransformLangExecutorRuntimeException(node,arguments,
"substring - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFUppercaseNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
CharSequence seq = (CharSequence) a;
node.strBuf.setLength(0);
node.strBuf.ensureCapacity(seq.length());
for (int i = 0; i < seq.length(); i++) {
node.strBuf.append(Character.toUpperCase(seq.charAt(i)));
}
stack.push(node.strBuf);
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"uppercase - wrong type of literal");
}
return data;
}
public Object visit(CLVFLowercaseNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
CharSequence seq = (CharSequence) a;
node.strBuf.setLength(0);
node.strBuf.ensureCapacity(seq.length());
for (int i = 0; i < seq.length(); i++) {
node.strBuf.append(Character.toLowerCase(seq.charAt(i)));
}
stack.push(node.strBuf);
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"lowercase - wrong type of literal");
}
return data;
}
public Object visit(CLVFTrimNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
int start, end;
if (a instanceof CharSequence) {
CharSequence seq = (CharSequence) a;
int length = seq.length();
for (start = 0; start < length; start++) {
if (seq.charAt(start) != ' ' && seq.charAt(start) != '\t') {
break;
}
}
for (end = length - 1; end >= 0; end--) {
if (seq.charAt(end) != ' ' && seq.charAt(end) != '\t') {
break;
}
}
if (start > end)
stack.push("");
else
stack.push(seq.subSequence(start, end + 1));
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"trim - wrong type of literal");
}
return data;
}
public Object visit(CLVFLengthNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
stack.push(new CloverInteger(((CharSequence) a).length()));
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"length - wrong type of literal");
}
return data;
}
public Object visit(CLVFTodayNode node, Object data) {
stack.push(stack.calendar.getTime() );
return data;
}
public Object visit(CLVFIsNullNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value == null) {
stack.push(Stack.TRUE_VAL);
} else {
if (value instanceof CharSequence) {
stack.push( ((CharSequence)value).length()==0 ? Stack.TRUE_VAL : Stack.FALSE_VAL);
}else {
stack.push(Stack.FALSE_VAL);
}
}
return data;
}
public Object visit(CLVFNVLNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value == null) {
node.jjtGetChild(1).jjtAccept(this, data);
// not necessary: stack.push(stack.pop());
} else {
if ((value instanceof CharSequence) && (((CharSequence)value).length()==0)) {
node.jjtGetChild(1).jjtAccept(this, data);
}else {
stack.push(value);
}
}
return data;
}
public Object visit(CLVFLiteral node, Object data) {
stack.push(node.value);
return data;
}
public Object visit(CLVFInputFieldLiteral node, Object data) {
DataRecord record = inputRecords[node.recordNo];
if (record == null) {
stack.push(null);
} else {
DataField field = record.getField(node.fieldNo);
if (field instanceof Numeric) {
stack.push(((Numeric) field).duplicateNumeric());
} else {
stack.push(field.getValue());
}
}
// old
// stack.push(inputRecords[node.recordNo].getField(node.fieldNo).getValue());
// we return reference to DataField so we can
// perform extra checking in special cases
return node.field;
}
public Object visit(CLVFOutputFieldLiteral node, Object data) {
//stack.push(inputRecords[node.recordNo].getField(node.fieldNo));
// we return reference to DataField so we can
// perform extra checking in special cases
return data;
}
public Object visit(CLVFGlobalParameterLiteral node, Object data) {
stack.push(globalParameters!=null ? globalParameters.getProperty(node.name) : null);
return data;
}
public Object visit(CLVFRegexLiteral node, Object data) {
stack.push(node.matcher);
return data;
}
public Object visit(CLVFConcatNode node, Object data) {
Object a;
StringBuilder strBuf = new StringBuilder(40);
int numChildren = node.jjtGetNumChildren();
for (int i = 0; i < numChildren; i++) {
node.jjtGetChild(i).jjtAccept(this, data);
a = stack.pop();
if (a instanceof CharSequence) {
StringUtils.strBuffAppend(strBuf,(CharSequence) a);
} else {
if (a != null) {
strBuf.append(a);
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"concat - wrong type of literal(s)");
}
}
}
stack.push(strBuf);
return data;
}
public Object visit(CLVFDateAddNode node, Object data) {
int shiftAmount;
node.jjtGetChild(0).jjtAccept(this, data);
Object date = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object amount = stack.pop();
try {
shiftAmount = ((Numeric) amount).getInt();
} catch (Exception ex) {
Object arguments[] = { amount };
throw new TransformLangExecutorRuntimeException(node,arguments, "dateadd - "
+ ex.getMessage());
}
if (date instanceof Date) {
node.calendar.setTime((Date) date);
node.calendar.add(node.calendarField, shiftAmount);
stack.push(node.calendar.getTime());
} else {
Object arguments[] = { date };
throw new TransformLangExecutorRuntimeException(node,arguments,
"dateadd - no Date expression");
}
return data;
}
public Object visit(CLVFDate2NumNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object date = stack.pop();
if (date instanceof Date) {
node.calendar.setTime((Date) date);
stack.push(new CloverInteger(node.calendar.get(node.calendarField)));
} else {
Object arguments[] = { date };
throw new TransformLangExecutorRuntimeException(node,arguments,
"date2num - no Date expression");
}
return data;
}
public Object visit(CLVFDateDiffNode node, Object data) {
Object date1, date2;
node.jjtGetChild(0).jjtAccept(this, data);
date1 = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
date2 = stack.pop();
if (date1 instanceof Date && date2 instanceof Date) {
long diffSec = (((Date) date1).getTime() - ((Date) date2).getTime()) / 1000;
int diff = 0;
switch (node.calendarField) {
case Calendar.SECOND:
// we have the difference in seconds
diff = (int) diffSec;
break;
case Calendar.MINUTE:
// how many minutes'
diff = (int) diffSec / 60;
break;
case Calendar.HOUR_OF_DAY:
diff = (int) diffSec / 3600;
break;
case Calendar.DAY_OF_MONTH:
// how many days is the difference
diff = (int) diffSec / 86400;
break;
case Calendar.WEEK_OF_YEAR:
// how many weeks
diff = (int) diffSec / 604800;
break;
case Calendar.MONTH:
node.start.setTime((Date) date1);
node.end.setTime((Date) date2);
diff = (node.start.get(Calendar.MONTH) + node.start
.get(Calendar.YEAR) * 12)
- (node.end.get(Calendar.MONTH) + node.end
.get(Calendar.YEAR) * 12);
break;
case Calendar.YEAR:
node.start.setTime((Date) date1);
node.end.setTime((Date) date2);
diff = node.start.get(node.calendarField)
- node.end.get(node.calendarField);
break;
default:
Object arguments[] = { new Integer(node.calendarField) };
throw new TransformLangExecutorRuntimeException(node,arguments,
"datediff - wrong difference unit");
}
stack.push(new CloverInteger(diff));
} else {
Object arguments[] = { date1, date2 };
throw new TransformLangExecutorRuntimeException(node,arguments,
"datediff - no Date expression");
}
return data;
}
public Object visit(CLVFMinusNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
if (value instanceof Numeric) {
Numeric result = ((Numeric) value).duplicateNumeric();
result.mul(Stack.NUM_MINUS_ONE);
stack.push(result);
} else {
Object arguments[] = { value };
throw new TransformLangExecutorRuntimeException(node,arguments,
"minus - not a number");
}
return data;
}
public Object visit(CLVFReplaceNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object str = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object regexO = stack.pop();
node.jjtGetChild(2).jjtAccept(this, data);
Object withO = stack.pop();
if (withO == null || regexO == null || str == null) {
throw new TransformLangExecutorRuntimeException(node, new Object[] { withO,
regexO, str }, "NULL value not allowed");
}
if (str instanceof CharSequence && withO instanceof CharSequence
&& regexO instanceof CharSequence) {
if (node.pattern == null || !node.stored.equals(regexO)) {
node.pattern = Pattern.compile(((CharSequence) regexO)
.toString());
node.matcher = node.pattern.matcher((CharSequence) str);
node.stored = regexO;
} else {
node.matcher.reset((CharSequence) str);
}
stack.push(node.matcher.replaceAll(((CharSequence) withO)
.toString()));
} else {
Object[] arguments = { withO, regexO, str };
throw new TransformLangExecutorRuntimeException(node,arguments,
"replace - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFNum2StrNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
if (node.radix == 10) {
stack.push(((Numeric) a).toString());
} else {
if (a instanceof CloverInteger) {
stack.push(Integer.toString(((CloverInteger) a).getInt(),
node.radix));
} else if (a instanceof CloverLong) {
stack.push(Long.toString(((CloverLong) a).getLong(),
node.radix));
} else if (a instanceof CloverDouble && node.radix == 16) {
stack.push(Double.toHexString(((CloverDouble) a)
.getDouble()));
} else {
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"num2str - can't convert number to string using specified radix");
}
}
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node, arguments,
"num2str - wrong type of literal");
}
return data;
}
public Object visit(CLVFStr2NumNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
try {
Object value = null;
switch (node.numType) {
case INT_VAR:
value = new CloverInteger(Integer.parseInt(
((CharSequence) a).toString(), node.radix));
break;
case LONG_VAR:
value = new CloverLong(Long.parseLong(((CharSequence) a)
.toString(), node.radix));
break;
case DECIMAL_VAR:
if (node.radix == 10) {
value = DecimalFactory.getDecimal(((CharSequence) a)
.toString());
} else {
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"str2num - can't convert string to decimal number using specified radix");
}
break;
default:
// get double/number type
switch (node.radix) {
case 10:
case 16:
value = new CloverDouble(Double
.parseDouble(((CharSequence) a).toString()));
break;
default:
Object[] arguments = { a, new Integer(node.radix) };
throw new TransformLangExecutorRuntimeException(node,
arguments,
"str2num - can't convert string to number/double number using specified radix");
}
}
stack.push(value);
} catch (NumberFormatException ex) {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,
arguments, "str2num - can't convert \"" + a + "\"");
}
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node, arguments,
"str2num - wrong type of literal");
}
return data;
}
public Object visit(CLVFDate2StrNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Date) {
stack.push(node.dateFormat.format((Date)a));
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"date2str - wrong type of literal");
}
return data;
}
public Object visit(CLVFStr2DateNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof CharSequence) {
try {
stack.push(node.dateFormat.parse(((CharSequence)a).toString()));
} catch (java.text.ParseException ex) {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"str2date - can't convert \"" + a + "\"");
}
} else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"str2date - wrong type of literal");
}
return data;
}
public Object visit(CLVFIffNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object condition = stack.pop();
if (condition instanceof Boolean) {
if (((Boolean) condition).booleanValue()) {
node.jjtGetChild(1).jjtAccept(this, data);
} else {
node.jjtGetChild(2).jjtAccept(this, data);
}
stack.push(stack.pop());
} else {
Object[] arguments = { condition };
throw new TransformLangExecutorRuntimeException(node,arguments,
"iif - condition does not evaluate to BOOLEAN value");
}
return data;
}
public Object visit(CLVFPrintErrNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (node.printLine){
StringBuilder buf=new StringBuilder((a != null ? a.toString() : "<null>"));
buf.append(" (on line: ").append(node.getLineNumber());
buf.append(" col: ").append(node.getColumnNumber()).append(")");
System.err.println(buf);
}else{
System.err.println(a != null ? a : "<null>");
}
return data;
}
public Object visit(CLVFPrintStackNode node, Object data) {
for (int i=stack.top;i>=0;i--){
System.err.println("["+i+"] : "+stack.stack[i]);
}
return data;
}
/***************************************************************************
* Transformation Language executor starts here.
**************************************************************************/
public Object visit(CLVFForStatement node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data); // set up of the loop
boolean condition = false;
Node loopCondition = node.jjtGetChild(1);
Node increment = node.jjtGetChild(2);
Node body;
try{
body=node.jjtGetChild(3);
}catch(ArrayIndexOutOfBoundsException ex){
body=emptyNode;
}
try {
loopCondition.jjtAccept(this, data); // evaluate the condition
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// loop execution
while (condition) {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) {
return data;
}
}
increment.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}
}
return data;
}
public Object visit(CLVFWhileStatement node, Object data) {
boolean condition = false;
Node loopCondition = node.jjtGetChild(0);
Node body;
try{
body=node.jjtGetChild(1);
}catch(ArrayIndexOutOfBoundsException ex){
body=emptyNode;
}
try {
loopCondition.jjtAccept(this, data); // evaluate the condition
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// loop execution
while (condition) {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data;
}
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}
}
return data;
}
public Object visit(CLVFIfStatement node, Object data) {
boolean condition = false;
try {
node.jjtGetChild(0).jjtAccept(this, data); // evaluate the
// condition
condition = ((Boolean) stack.pop()).booleanValue();
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"condition does not evaluate to BOOLEAN value");
} catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
// first if
if (condition) {
node.jjtGetChild(1).jjtAccept(this, data);
} else { // if else part exists
if (node.jjtGetNumChildren() > 2) {
node.jjtGetChild(2).jjtAccept(this, data);
}
}
return data;
}
public Object visit(CLVFDoStatement node, Object data) {
boolean condition = false;
Node loopCondition = node.jjtGetChild(1);
Node body = node.jjtGetChild(0);
// loop execution
do {
body.jjtAccept(this, data);
stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_BREAK || breakType==BREAK_RETURN) return data;
}
// evaluate the condition
loopCondition.jjtAccept(this, data);
try {
condition = ((Boolean) stack.pop()).booleanValue();
}catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"loop condition does not evaluate to BOOLEAN value");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid condition");
}
} while (condition);
return data;
}
public Object visit(CLVFSwitchStatement node, Object data) {
// get value of switch && push/leave it on stack
boolean match=false;
node.jjtGetChild(0).jjtAccept(this, data);
Object switchVal=stack.pop();
int numChildren = node.jjtGetNumChildren();
int numCases = node.hasDefaultClause ? numChildren-1 : numChildren;
// loop over remaining case statements
for (int i = 1; i < numCases; i++) {
stack.push(switchVal);
if (node.jjtGetChild(i).jjtAccept(this, data)==Stack.TRUE_VAL){
match=true;
}
if (breakFlag) {
if (breakType == BREAK_BREAK) {
breakFlag = false;
}
break;
}
}
// test whether execute default branch
if (node.hasDefaultClause && !match){
node.jjtGetChild(numChildren-1).jjtAccept(this, data);
}
return data;
}
public Object visit(CLVFCaseExpression node, Object data) {
// test if literal (as child 0) is equal to data on stack
// if so, execute block (child 1)
boolean match = false;
Object switchVal = stack.pop();
node.jjtGetChild(0).jjtAccept(this, data);
Object value = stack.pop();
try {
if (switchVal instanceof Numeric) {
match = (((Numeric) value).compareTo((Numeric) switchVal) == 0);
} else if (switchVal instanceof CharSequence) {
match = (Compare.compare((CharSequence) switchVal,
(CharSequence) value) == 0);
} else if (switchVal instanceof Date) {
match = (((Date) switchVal).compareTo((Date) value) == 0);
} else if (switchVal instanceof Boolean) {
match = ((Boolean) switchVal).equals((Boolean) value);
}
} catch (ClassCastException ex) {
Object[] args=new Object[] {switchVal,value};
throw new TransformLangExecutorRuntimeException(node,args,"incompatible literals in case clause");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid case value");
}
if (match){
node.jjtGetChild(1).jjtAccept(this, data);
return Stack.TRUE_VAL;
}else{
return Stack.FALSE_VAL;
}
}
public Object visit(CLVFPlusPlusNode node, Object data) {
Node childNode = node.jjtGetChild(0);
if (childNode instanceof CLVFVariableLiteral) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode;
Object var=stack.getVar(varNode.localVar, varNode.varSlot);
if (var instanceof Numeric){
((Numeric)var).add(Stack.NUM_ONE);
stack.push(((Numeric)var).duplicateNumeric());
}else if (var instanceof Date){
stack.calendar.setTime((Date)var);
stack.calendar.add(Calendar.DATE, 1);
stack.push(stack.calendar.getTime());
}else{
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
} else {
childNode.jjtAccept(this, data);
try {
Numeric num = ((Numeric) stack.pop()).duplicateNumeric();
num.add(Stack.NUM_ONE);
stack.push(num);
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"expression is not of numeric type");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid numeric expression");
}
}
return data;
}
public Object visit(CLVFMinusMinusNode node, Object data) {
Node childNode = node.jjtGetChild(0);
if (childNode instanceof CLVFVariableLiteral) {
CLVFVariableLiteral varNode=(CLVFVariableLiteral) childNode;
Object var=stack.getVar(varNode.localVar, varNode.varSlot);
if (var instanceof Numeric){
((Numeric)var).sub(Stack.NUM_ONE);
stack.push(((Numeric)var).duplicateNumeric());
}else if (var instanceof Date){
stack.calendar.setTime((Date)var);
stack.calendar.add(Calendar.DATE, 1);
stack.push(stack.calendar.getTime());
}else{
throw new TransformLangExecutorRuntimeException(node,"variable is not of numeric or date type");
}
} else {
childNode.jjtAccept(this, data);
try {
Numeric num = ((Numeric) stack.pop()).duplicateNumeric();
num.add(Stack.NUM_ONE);
stack.push(num);
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,"expression is not of numeric type");
}catch (NullPointerException ex){
throw new TransformLangExecutorRuntimeException(node,"missing or invalid numeric expression");
}
}
return data;
}
public Object visit(CLVFBlock node, Object data) {
int childern = node.jjtGetNumChildren();
for (int i = 0; i < childern; i++) {
node.jjtGetChild(i).jjtAccept(this, data);
// have we seen contiue/break/return statement ??
if (breakFlag){
if (breakType!=BREAK_RETURN)
stack.pop();
return data;
}
stack.pop();
}
return data;
}
/*
* Loop & block & function control nodes
*/
public Object visit(CLVFBreakStatement node, Object data) {
breakFlag = true; // we encountered break statement;
breakType=BREAK_BREAK;
return data;
}
public Object visit(CLVFContinueStatement node, Object data) {
breakFlag = true; // we encountered continue statement;
breakType= BREAK_CONTINUE;
return data;
}
public Object visit(CLVFReturnStatement node, Object data) {
if (node.jjtHasChildren()){
node.jjtGetChild(0).jjtAccept(this, data);
}
breakFlag = true;
breakType = BREAK_RETURN;
return data;
}
public Object visit(CLVFBreakpointNode node, Object data) {
// list all variables
System.err.println("** list of global variables ***");
for (int i=0;i<stack.globalVarSlot.length;System.out.println(stack.globalVarSlot[i++]));
System.err.println("** list of local variables ***");
for (int i=0;i<stack.localVarCounter;i++)
System.out.println(stack.localVarSlot[stack.localVarSlotOffset+i]);
return data;
}
/*
* Variable declarations
*/
public Object visit(CLVFVarDeclaration node, Object data) {
// test for duplicite declaration - should have been done before
/*
* if (stack.symtab.containsKey(node.name)) { throw new
* TransformLangExecutorRuntimeException(node, "variable already
* declared - \"" + node.name + "\""); }
*/
Object value;
// create global/local variable
switch (node.type) {
case INT_VAR:
value = new CloverInteger(0);
break;
case LONG_VAR:
value = new CloverLong(0);
break;
case DOUBLE_VAR:
value = new CloverDouble(0);
break;
case DECIMAL_VAR:
if (node.length > 0) {
if (node.precision > 0) {
value = DecimalFactory.getDecimal(node.length,
node.precision);
} else {
value = DecimalFactory.getDecimal(node.length, 0);
}
} else {
value = DecimalFactory.getDecimal();
}
break;
case STRING_VAR:
value = new StringBuilder();
break;
case DATE_VAR:
value = new Date();
break;
case BOOLEAN_VAR:
value = Stack.FALSE_VAL;
break;
default:
throw new TransformLangExecutorRuntimeException(node,
"variable declaration - "
+ "unknown variable type for variable \""
+ node.name + "\"");
}
stack.storeVar(node.localVar, node.varSlot, value);
if (node.jjtHasChildren()) {
node.jjtGetChild(0).jjtAccept(this, data);
Object initValue = stack.pop();
try {
switch (node.type) {
case INT_VAR:
case LONG_VAR:
case DOUBLE_VAR:
case DECIMAL_VAR:
((Numeric) value).setValue((Numeric) initValue);
break;
case STRING_VAR:
if (initValue != null)
StringUtils.strBuffAppend((StringBuilder) value,
(CharSequence) initValue);
break;
case DATE_VAR:
((Date) value).setTime(((Date) initValue).getTime());
break;
case BOOLEAN_VAR:
stack.storeVar(node.localVar, node.varSlot,
(Boolean) initValue);
// boolean is not updatable - we replace the reference
break;
}
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + initValue
+ "\" to variable \"" + node.name
+ "\" - incompatible data types");
} catch (NumberFormatException ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of number \"" + initValue
+ "\" to variable \"" + node.name + "\" : "
+ ex.getMessage());
} catch (TransformLangExecutorRuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + value
+ "\" to variable \"" + node.name + "\" : "
+ ex.getMessage());
}
}
return data;
}
public Object visit(CLVFVariableLiteral node, Object data) {
Object var = stack.getVar(node.localVar, node.varSlot);
// variable can be null
stack.push(var);
/*
if (var != null) {
stack.push(var);
} else {
throw new TransformLangExecutorRuntimeException(node, "unknown variable \""
+ node.varName + "\"");
}
*/
return data;
}
public Object visit(CLVFAssignment node, Object data) {
//TODO: proper handling of NULL value assignment
CLVFVariableLiteral childNode=(CLVFVariableLiteral) node.jjtGetChild(0);
Object variable = stack.getVar(childNode.localVar,childNode.varSlot);
node.jjtGetChild(1).jjtAccept(this, data);
Object value = stack.pop();
try {
if (variable instanceof Numeric) {
((Numeric) variable).setValue((Numeric) value);
} else if (variable instanceof StringBuilder) {
StringBuilder var = (StringBuilder) variable;
var.setLength(0);
if (value !=null) StringUtils.strBuffAppend(var,(CharSequence) value);
} else if (variable instanceof Boolean) {
stack.storeVar(childNode.localVar,childNode.varSlot, (Boolean)value); // boolean is not updatable - we replace the reference
// stack.put(varName,((Boolean)value).booleanValue() ?
// Stack.TRUE_VAL : Stack.FALSE_VAL);
} else if (variable instanceof Date) {
((Date) variable).setTime(((Date) value).getTime());
} else {
throw new TransformLangExecutorRuntimeException(node,
"unknown variable \"" + childNode.varName + "\"");
}
} catch (ClassCastException ex) {
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + value + "\" to variable \""
+ childNode.varName + "\" - incompatible data types");
} catch (NumberFormatException ex){
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of number \"" + value + "\" to variable \"" + childNode.varName + "\" : "+ex.getMessage());
} catch (TransformLangExecutorRuntimeException ex){
throw ex;
} catch (Exception ex){
throw new TransformLangExecutorRuntimeException(node,
"invalid assignment of \"" + value + "\" to variable \"" + childNode.varName + "\" : "+ex.getMessage());
}
return data;
}
public Object visit(CLVFMapping node, Object data) {
DataField field=outputRecords[node.recordNo].getField(node.fieldNo);
int arity=node.jjtGetNumChildren(); // how many children we have defined
Object value=null;
try{
// we try till success or no more options
for (int i=0;i<arity;i++){
node.jjtGetChild(i).jjtAccept(this, data);
value=stack.pop();
try{
// TODO: small hack
if (field instanceof Numeric){
((Numeric)field).setValue((Numeric)value);
}else{
field.setValue(value);
}
break; // success during assignment, finish looping
}catch(Exception ex){
if (i == arity-1)
throw ex;
}
}
}catch(BadDataFormatException ex){
if (!outputRecords[node.recordNo].getField(node.fieldNo).getMetadata().isNullable()){
throw new TransformLangExecutorRuntimeException(node,"can't assign NULL to \"" + node.fieldName + "\"");
}else{
throw new TransformLangExecutorRuntimeException(node,"data format exception when mapping \"" + node.fieldName + "\" - assigning \""
+ value + "\"");
}
}catch(TransformLangExecutorRuntimeException ex){
throw ex;
}catch(Exception ex){
String msg=ex.getMessage();
throw new TransformLangExecutorRuntimeException(node,
(msg!=null ? msg : "") +
" when mapping \"" + node.fieldName + "\" ("+DataFieldMetadata.type2Str(field.getType())
+") - assigning \"" + value + "\" ("+(value!=null ? value.getClass(): "unknown class" )+")");
}
return data;
}
/*
* Declaration & calling of Functions here
*/
public Object visit(CLVFFunctionCallStatement node, Object data) {
//put call parameters on stack
node.childrenAccept(this,data);
CLVFFunctionDeclaration executionNode=node.callNode;
// open call frame
stack.pushFuncCallFrame();
// store call parameters from stack as local variables
for (int i=executionNode.numParams-1;i>=0; stack.storeLocalVar(i--,stack.pop()));
// execute function body
// loop execution
Object returnData;
int numChildren=executionNode.jjtGetNumChildren();
for (int i=0;i<numChildren;i++){
executionNode.jjtGetChild(i).jjtAccept(this,data);
returnData=stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_RETURN){
if (returnData!=null)
stack.push(returnData);
break;
}
}
}
stack.popFuncCallFrame();
return data;
}
public Object visit(CLVFFunctionDeclaration node, Object data) {
return data;
}
public Object visit(CLVFStatementExpression node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
return data;
}
public Object executeFunction(CLVFFunctionDeclaration executionNode, Object[] data) {
//put call parameters on stack
if (data==null){
data=new Object[0];
}
// open call frame
stack.pushFuncCallFrame();
// store call parameters from stack as local variables
for (int i=executionNode.numParams-1;i>=0; i--) {
stack.storeLocalVar(i, data[i]);
}
// execute function body
// loop execution
Object returnData;
int numChildren=executionNode.jjtGetNumChildren();
for (int i=0;i<numChildren;i++){
executionNode.jjtGetChild(i).jjtAccept(this,data);
returnData=stack.pop(); // in case there is anything on top of stack
// check for break or continue statements
if (breakFlag){
breakFlag=false;
if (breakType==BREAK_RETURN){
if (returnData!=null)
stack.push(returnData);
break;
}
}
}
stack.popFuncCallFrame();
return data;
}
/*
* MATH functions log,log10,exp,pow,sqrt,round
*/
public Object visit(CLVFSqrtNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble(Math.sqrt(((Numeric)a).getDouble()) ));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing SQRT function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"sqrt - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFLogNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble(Math.log(((Numeric)a).getDouble()) ));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"log - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFLog10Node node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble( Math.log10(((Numeric)a).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing LOG10 function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"log10 - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFExpNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverDouble( Math.exp(((Numeric)a).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing EXP function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"exp - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFRoundNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Numeric) {
try{
stack.push(new CloverLong(Math.round(((Numeric)a).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing ROUND function",ex);
}
}else {
Object[] arguments = { a};
throw new TransformLangExecutorRuntimeException(node,arguments,
"round - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFPowNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
node.jjtGetChild(1).jjtAccept(this, data);
Object b = stack.pop();
if (a instanceof Numeric && b instanceof Numeric) {
try{
stack.push(new CloverDouble(Math.pow(((Numeric)a).getDouble(),
((Numeric)b).getDouble())));
}catch(Exception ex){
throw new TransformLangExecutorRuntimeException(node,"Error when executing POW function",ex);
}
}else {
Object[] arguments = { a, b };
throw new TransformLangExecutorRuntimeException(node,arguments,
"pow - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFPINode node, Object data) {
stack.push(Stack.NUM_PI);
return data;
}
public Object visit(CLVFTruncNode node, Object data) {
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
if (a instanceof Date ) {
stack.calendar.setTime((Date)a);
stack.calendar.set(Calendar.HOUR_OF_DAY, 0);
stack.calendar.set(Calendar.MINUTE , 0);
stack.calendar.set(Calendar.SECOND , 0);
stack.calendar.set(Calendar.MILLISECOND , 0);
stack.push( stack.calendar.getTime() );
}else if (a instanceof Numeric){
stack.push(new CloverLong(((Numeric)a).getLong()));
}else {
Object[] arguments = { a };
throw new TransformLangExecutorRuntimeException(node,arguments,
"trunc - wrong type of literal(s)");
}
return data;
}
public Object visit(CLVFRaiseErrorNode node,Object data){
node.jjtGetChild(0).jjtAccept(this, data);
Object a = stack.pop();
throw new TransformLangExecutorRuntimeException(node,null,
"!!! Exception raised by user: "+((a!=null) ? a.toString() : "no message"));
}
public Object visit(CLVFSequenceNode node, Object data) {
Object seqVal = null;
if (node.sequence == null) {
if (graph != null) {
node.sequence = graph.getSequence(node.sequenceName);
} else {
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain Sequence \"" + node.sequenceName
+ "\" from graph - graph is not assigned");
}
if (node.sequence == null) {
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain Sequence \"" + node.sequenceName
+ "\" from graph \"" + graph.getName() + "\"");
}
}
switch (node.opType) {
case CLVFSequenceNode.OP_RESET:
node.sequence.reset();
seqVal = Stack.NUM_ZERO;
break;
case CLVFSequenceNode.OP_CURRENT:
switch (node.retType) {
case LONG_VAR:
seqVal = new CloverLong(node.sequence.currentValueLong());
break;
case STRING_VAR:
seqVal = node.sequence.currentValueString();
default:
seqVal = new CloverInteger(node.sequence.currentValueInt());
}
break;
default: // default is next value from sequence
switch (node.retType) {
case LONG_VAR:
seqVal = new CloverLong(node.sequence.nextValueLong());
break;
case STRING_VAR:
seqVal = node.sequence.nextValueString();
default:
seqVal = new CloverInteger(node.sequence.nextValueInt());
}
}
stack.push(seqVal);
return data;
}
public Object visit(CLVFLookupNode node,Object data){
DataRecord record=null;
if (node.lookup==null){
node.lookup=graph.getLookupTable(node.lookupName);
if (node.lookup==null){
throw new TransformLangExecutorRuntimeException(node,
"Can't obtain LookupTable \""+node.lookupName+
"\" from graph \""+graph.getName()+"\"");
}
node.fieldNum=node.lookup.getMetadata().getFieldPosition(node.fieldName);
if (node.fieldNum<0){
throw new TransformLangExecutorRuntimeException(node,
"Invalid field name \""+node.fieldName+"\" at LookupTable \""+node.lookupName+
"\" in graph \""+graph.getName()+"\"");
}
node.lookup.setLookupKey(new Object[node.jjtGetNumChildren()]);
}
switch(node.opType){
case CLVFLookupNode.OP_INIT:
try{
node.lookup.init();
}catch(ComponentNotReadyException ex){
throw new TransformLangExecutorRuntimeException(node,
"Error when initializing lookup table \""+node.lookupName+"\" :",
ex);
}
return data;
case CLVFLookupNode.OP_FREE:
node.lookup.free();
return data;
case CLVFLookupNode.OP_NUM_FOUND:
stack.push(new CloverInteger(node.lookup.getNumFound()));
return data;
case CLVFLookupNode.OP_GET:
Object keys[]=new Object[node.jjtGetNumChildren()];
for(int i=0;i<node.jjtGetNumChildren();i++){
node.jjtGetChild(i).jjtAccept(this, data);
keys[i]=stack.pop();
}
record=node.lookup.get(keys);
break;
case CLVFLookupNode.OP_NEXT:
record=node.lookup.getNext();
}
if(record!=null){
stack.push(record.getField(node.fieldNum).getValue());
}else{
stack.push(null);
}
return data;
}
public Object visit(CLVFPrintLogNode node, Object data) {
if (runtimeLogger == null) {
throw new TransformLangExecutorRuntimeException(node,
"Can NOT perform logging operation - no logger defined");
}
node.jjtGetChild(0).jjtAccept(this, data);
Object msg = stack.pop();
switch (node.level) {
case 1: //| "debug"
runtimeLogger.debug(msg);
break;
case 2: //| "info"
runtimeLogger.info(msg);
break;
case 3: //| "warn"
runtimeLogger.warn(msg);
break;
case 4: //| "error"
runtimeLogger.error(msg);
break;
case 5: //| "fatal"
runtimeLogger.fatal(msg);
break;
default:
runtimeLogger.trace(msg);
}
return data;
}
} | FIX:fixed lookup_found,lookup_admin,lookup_next
git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@2738 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/src/org/jetel/interpreter/TransformLangExecutor.java | FIX:fixed lookup_found,lookup_admin,lookup_next | <ide><path>loveretl.engine/src/org/jetel/interpreter/TransformLangExecutor.java
<ide>
<ide> public Object visit(CLVFLookupNode node,Object data){
<ide> DataRecord record=null;
<del> if (node.lookup==null){
<del> node.lookup=graph.getLookupTable(node.lookupName);
<del> if (node.lookup==null){
<add> if (node.lookup == null) {
<add> node.lookup = graph.getLookupTable(node.lookupName);
<add> if (node.lookup == null) {
<ide> throw new TransformLangExecutorRuntimeException(node,
<del> "Can't obtain LookupTable \""+node.lookupName+
<del> "\" from graph \""+graph.getName()+"\"");
<del> }
<del> node.fieldNum=node.lookup.getMetadata().getFieldPosition(node.fieldName);
<del> if (node.fieldNum<0){
<del> throw new TransformLangExecutorRuntimeException(node,
<del> "Invalid field name \""+node.fieldName+"\" at LookupTable \""+node.lookupName+
<del> "\" in graph \""+graph.getName()+"\"");
<del> }
<del> node.lookup.setLookupKey(new Object[node.jjtGetNumChildren()]);
<add> "Can't obtain LookupTable \"" + node.lookupName
<add> + "\" from graph \"" + graph.getName() + "\"");
<add> }
<add> if (node.opType == CLVFLookupNode.OP_GET) {
<add> node.fieldNum = node.lookup.getMetadata().getFieldPosition(
<add> node.fieldName);
<add> if (node.fieldNum < 0) {
<add> throw new TransformLangExecutorRuntimeException(node,
<add> "Invalid field name \"" + node.fieldName
<add> + "\" at LookupTable \"" + node.lookupName
<add> + "\" in graph \"" + graph.getName() + "\"");
<add> }
<add> node.lookup.setLookupKey(new Object[node.jjtGetNumChildren()]);
<add> }
<ide> }
<ide> switch(node.opType){
<ide> case CLVFLookupNode.OP_INIT: |
|
JavaScript | mit | fa6e489db69784fffce3133e2f06a03be4e17b3c | 0 | alcedo-ui/alcedo-ui | /**
* @file Calculation vendor
* @author liangxiaojun([email protected])
*/
import isArray from 'lodash/isArray';
import Valid from './Valid';
import SelectMode from '../_statics/SelectMode';
import Util from './Util';
function pageSize(pageSize, pageSizes, defaultValue) {
if (pageSize) {
return pageSize;
}
if (pageSizes && pageSizes.length > 0) {
for (let item of pageSizes) {
if (item > 0) {
return item;
}
}
}
return defaultValue;
}
function displayIndexByScrollTop(data, listHeight, itemHeight, scrollTop = 0, buffer = 0) {
if (!data || !listHeight || !itemHeight) {
return {
start: 0,
stop: 0,
startWithBuffer: 0,
stopWithBuffer: 0
};
}
const len = data.length,
start = Math.floor(scrollTop / itemHeight),
stop = start + Math.ceil(listHeight / itemHeight);
return {
start: Valid.range(start, 0, len - 1),
stop: Valid.range(stop, 0, len - 1),
startWithBuffer: Valid.range(start - buffer, 0, len - 1),
stopWithBuffer: Valid.range(stop + buffer, 0, len - 1)
};
}
function displayIndexByScrollTopMulColumns(data, listHeight, itemHeight, column, scrollTop = 0, buffer = 0) {
if (!data || !listHeight || !itemHeight) {
return {
start: 0,
stop: 0,
startWithBuffer: 0,
stopWithBuffer: 0
};
}
const len = data.length,
start = Math.floor(scrollTop / itemHeight) * column,
stop = start + Math.ceil(listHeight / itemHeight) * column;
return {
start: Valid.range(start, 0, len - 1),
stop: Valid.range(stop, 0, len - 1),
startWithBuffer: Valid.range(Valid.range(start, 0, len - 1) - buffer, 0, len - 1),
stopWithBuffer: Valid.range(stop + buffer, 0, len - 1)
};
}
function getInitValue(props) {
if (!props) {
return;
}
const {value, selectMode} = props;
if (!selectMode) {
return;
}
if (value) {
return value;
}
switch (selectMode) {
case SelectMode.MULTI_SELECT:
return [];
case SelectMode.SINGLE_SELECT:
return null;
default:
return value;
}
}
function getMultiSelectItemIndex(item, value, {selectMode, valueField, displayField}) {
if (selectMode !== SelectMode.MULTI_SELECT || !item || !value) {
return -1;
}
if (!isArray(value)) {
return -1;
}
return value.findIndex(valueItem => Util.isValueEqual(valueItem, item, valueField, displayField));
}
function isItemChecked(item, value, {selectMode, valueField, displayField}) {
if (!item || !value) {
return false;
}
if (selectMode === SelectMode.MULTI_SELECT) {
return isArray(value) && value.filter(valueItem =>
Util.isValueEqual(valueItem, item, valueField, displayField)
).length > 0;
} else if (selectMode === SelectMode.SINGLE_SELECT) {
return Util.isValueEqual(value, item, valueField, displayField);
}
}
function isNodeIndeterminate(node, value, {valueField, displayField}) {
if (!node || !node.children || node.children.length < 1
|| !value || !value.length || value.length < 1) {
return false;
}
let total = 0,
count = 0;
Util.preOrderTraverse(node, nodeItem => {
total++;
if (value.findIndex(item =>
Util.getValueByValueField(item, valueField, displayField)
=== Util.getValueByValueField(nodeItem, valueField, displayField)) > -1) {
count++;
}
});
return count > 0 && total !== count;
}
function filterLocalAutoCompleteData(filter, props) {
const {data, minFilterLength} = props;
if (!filter || filter.length < minFilterLength) {
return data;
}
const {valueField, displayField, renderer, filterCallback} = props;
if (filterCallback) {
return filterCallback(filter, data);
}
return data && data.filter(item => {
if (!item) {
return false;
}
if (renderer) {
return renderer(item).toString().toUpperCase().includes(filter.toUpperCase());
}
if (typeof item === 'object') {
const itemDisplay = Util.getTextByDisplayField(item, displayField, valueField);
if (itemDisplay) {
return itemDisplay.toString().toUpperCase().includes(filter.toUpperCase());
}
}
return item.toString().toUpperCase().includes(filter.toUpperCase());
});
}
function sortTableData(data, sort, sortFunc) {
if (!sort) {
return data;
}
let copyData = data.slice();
if (sortFunc) {
copyData = sortFunc(copyData, sort);
} else {
copyData.sort((a, b) => {
if (!isNaN(a[sort.prop]) && !isNaN(b[sort.prop])) {
return (Number(a[sort.prop]) - Number(b[sort.prop])) * sort.type;
} else {
return (a[sort.prop] + '').localeCompare(b[sort.prop] + '') * sort.type;
}
});
}
return copyData;
};
export default {
pageSize,
displayIndexByScrollTop,
getInitValue,
getMultiSelectItemIndex,
displayIndexByScrollTopMulColumns,
isItemChecked,
isNodeIndeterminate,
filterLocalAutoCompleteData,
sortTableData
};
| src/_vendors/Calculation.js | /**
* @file Calculation vendor
* @author liangxiaojun([email protected])
*/
import isArray from 'lodash/isArray';
import Valid from './Valid';
import SelectMode from '../_statics/SelectMode';
import Util from './Util';
function pageSize(pageSize, pageSizes, defaultValue) {
if (pageSize) {
return pageSize;
}
if (pageSizes && pageSizes.length > 0) {
for (let item of pageSizes) {
if (item > 0) {
return item;
}
}
}
return defaultValue;
}
function displayIndexByScrollTop(data, listHeight, itemHeight, scrollTop = 0, buffer = 0) {
if (!data || !listHeight || !itemHeight) {
return {
start: 0,
stop: 0,
startWithBuffer: 0,
stopWithBuffer: 0
};
}
const len = data.length,
start = Math.floor(scrollTop / itemHeight),
stop = start + Math.ceil(listHeight / itemHeight);
return {
start: Valid.range(start, 0, len - 1),
stop: Valid.range(stop, 0, len - 1),
startWithBuffer: Valid.range(start - buffer, 0, len - 1),
stopWithBuffer: Valid.range(stop + buffer, 0, len - 1)
};
}
function displayIndexByScrollTopMulColumns(data, listHeight, itemHeight, column, scrollTop = 0, buffer = 0) {
if (!data || !listHeight || !itemHeight) {
return {
start: 0,
stop: 0,
startWithBuffer: 0,
stopWithBuffer: 0
};
}
const len = data.length,
start = Math.floor(scrollTop / itemHeight) * column,
stop = start + Math.ceil(listHeight / itemHeight) * column;
return {
start: Valid.range(start, 0, len - 1),
stop: Valid.range(stop, 0, len - 1),
startWithBuffer: Valid.range(Valid.range(start, 0, len - 1) - buffer, 0, len - 1),
stopWithBuffer: Valid.range(stop + buffer, 0, len - 1)
};
}
function getInitValue(props) {
if (!props) {
return;
}
const {value, selectMode} = props;
if (!selectMode) {
return;
}
if (value) {
return value;
}
switch (selectMode) {
case SelectMode.MULTI_SELECT:
return [];
case SelectMode.SINGLE_SELECT:
return null;
default:
return value;
}
}
function getMultiSelectItemIndex(item, value, {selectMode, valueField, displayField}) {
if (selectMode !== SelectMode.MULTI_SELECT || !item || !value) {
return -1;
}
if (!isArray(value)) {
return -1;
}
return value.findIndex(valueItem => Util.isValueEqual(valueItem, item, valueField, displayField));
}
function isItemChecked(item, value, {selectMode, valueField, displayField}) {
if (!item || !value) {
return false;
}
if (selectMode === SelectMode.MULTI_SELECT) {
return isArray(value) && value.filter(valueItem =>
Util.isValueEqual(valueItem, item, valueField, displayField)
).length > 0;
} else if (selectMode === SelectMode.SINGLE_SELECT) {
return Util.isValueEqual(value, item, valueField, displayField);
}
}
function isNodeIndeterminate(node, value, {valueField, displayField}) {
if (!node || !node.children || node.children.length < 1
|| !value || !value.length || value.length < 1) {
return false;
}
let total = 0,
count = 0;
Util.preOrderTraverse(node, nodeItem => {
total++;
if (value.findIndex(item =>
Util.getValueByValueField(item, valueField, displayField)
=== Util.getValueByValueField(nodeItem, valueField, displayField)) > -1) {
count++;
}
});
return count > 0 && total !== count;
}
export default {
pageSize,
displayIndexByScrollTop,
getInitValue,
getMultiSelectItemIndex,
displayIndexByScrollTopMulColumns,
isItemChecked,
isNodeIndeterminate
}; | update Calculation
| src/_vendors/Calculation.js | update Calculation | <ide><path>rc/_vendors/Calculation.js
<ide> Util.preOrderTraverse(node, nodeItem => {
<ide> total++;
<ide> if (value.findIndex(item =>
<del> Util.getValueByValueField(item, valueField, displayField)
<del> === Util.getValueByValueField(nodeItem, valueField, displayField)) > -1) {
<add> Util.getValueByValueField(item, valueField, displayField)
<add> === Util.getValueByValueField(nodeItem, valueField, displayField)) > -1) {
<ide> count++;
<ide> }
<ide> });
<ide> return count > 0 && total !== count;
<ide>
<ide> }
<add>
<add>function filterLocalAutoCompleteData(filter, props) {
<add>
<add> const {data, minFilterLength} = props;
<add>
<add> if (!filter || filter.length < minFilterLength) {
<add> return data;
<add> }
<add>
<add> const {valueField, displayField, renderer, filterCallback} = props;
<add>
<add> if (filterCallback) {
<add> return filterCallback(filter, data);
<add> }
<add>
<add> return data && data.filter(item => {
<add>
<add> if (!item) {
<add> return false;
<add> }
<add>
<add> if (renderer) {
<add> return renderer(item).toString().toUpperCase().includes(filter.toUpperCase());
<add> }
<add>
<add> if (typeof item === 'object') {
<add>
<add> const itemDisplay = Util.getTextByDisplayField(item, displayField, valueField);
<add>
<add> if (itemDisplay) {
<add> return itemDisplay.toString().toUpperCase().includes(filter.toUpperCase());
<add> }
<add>
<add> }
<add>
<add> return item.toString().toUpperCase().includes(filter.toUpperCase());
<add>
<add> });
<add>
<add>}
<add>
<add>function sortTableData(data, sort, sortFunc) {
<add>
<add> if (!sort) {
<add> return data;
<add> }
<add>
<add> let copyData = data.slice();
<add>
<add> if (sortFunc) {
<add> copyData = sortFunc(copyData, sort);
<add> } else {
<add> copyData.sort((a, b) => {
<add> if (!isNaN(a[sort.prop]) && !isNaN(b[sort.prop])) {
<add> return (Number(a[sort.prop]) - Number(b[sort.prop])) * sort.type;
<add> } else {
<add> return (a[sort.prop] + '').localeCompare(b[sort.prop] + '') * sort.type;
<add> }
<add> });
<add> }
<add>
<add> return copyData;
<add>
<add>};
<ide>
<ide> export default {
<ide> pageSize,
<ide> getMultiSelectItemIndex,
<ide> displayIndexByScrollTopMulColumns,
<ide> isItemChecked,
<del> isNodeIndeterminate
<add> isNodeIndeterminate,
<add> filterLocalAutoCompleteData,
<add> sortTableData
<ide> }; |
|
Java | apache-2.0 | 102ec87e6af7ee13eafa0510daff6a04ace9061b | 0 | mjuhasz/BDSup2Sub,mjuhasz/BDSup2Sub | /*
* Copyright 2012 Miklos Juhasz (mjuhasz)
*
* 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 bdsup2sub.core;
import bdsup2sub.tools.Props;
import bdsup2sub.utils.FilenameUtils;
import bdsup2sub.utils.PlatformUtils;
import bdsup2sub.utils.SubtitleUtils;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
public final class Configuration {
public static final Color OK_BACKGROUND = UIManager.getColor("TextField.background");
public static final Color WARN_BACKGROUND = new Color(0xffffffc0);
public static final Color ERROR_BACKGROUND = new Color(0xffe1acac);
public static final boolean CONVERT_RESOLUTION_BY_DEFAULT = false;
public static final boolean CONVERT_FRAMERATE_BY_DEFAULT = false;
public static final int DEFAULT_PTS_DELAY = 0;
public static final boolean FIX_SHORT_FRAMES_BY_DEFAULT = false;
public static final int DEFAULT_MIN_DISPLAY_TIME_PTS = 90 * 500;
public static final boolean APPLY_FREE_SCALE_BY_DEFAULT = false;
public static final double DEFAULT_FREE_SCALE_FACTOR_X = 1.0;
public static final double DEFAULT_FREE_SCALE_FACTOR_Y = 1.0;
public static final double MIN_FREE_SCALE_FACTOR = 0.5;
public static final double MAX_FREE_SCALE_FACTOR = 2.0;
public static final double DEFAULT_SOURCE_FRAMERATE = Framerate.FPS_23_976.getValue(); //TODO: dumb default
public static final double DEFAULT_TARGET_FRAMERATE = Framerate.PAL.getValue(); //TODO: dumb default
public static final Resolution DEFAULT_TARGET_RESOLUTION = Resolution.PAL; //TODO: dumb default
public static final int DEFAULT_ALPHA_CROP_THRESHOLD = 14;
public static final int DEFAULT_ALPHA_THRESHOLD = 80;
public static final int DEFAULT_LUMINANCE_MED_HIGH_THRESHOLD = 210;
public static final int DEFAULT_LUMINANCE_LOW_MED_THRESHOLD = 160;
public static final int DEFAULT_MOVE_Y_OFFSET = 10;
public static final int DEFAULT_MOVE_X_OFFSET = 10;
public static final int DEFAULT_CROP_LINE_COUNT = 0;
//Two equal captions are merged of they are closer than 200ms (0.2*90000 = 18000)
public static final int DEFAULT_MERGE_PTS_DIFF = 18000;
public static final OutputMode DEFAULT_OUTPUT_MODE = OutputMode.VOBSUB;
private boolean convertResolution = CONVERT_RESOLUTION_BY_DEFAULT;
private boolean convertFPS = CONVERT_FRAMERATE_BY_DEFAULT;
private int delayPTS = DEFAULT_PTS_DELAY;
private boolean cliMode = true;
private boolean fixShortFrames = FIX_SHORT_FRAMES_BY_DEFAULT;
private int minTimePTS = DEFAULT_MIN_DISPLAY_TIME_PTS;
private boolean applyFreeScale = APPLY_FREE_SCALE_BY_DEFAULT;
private double freeScaleFactorX = DEFAULT_FREE_SCALE_FACTOR_X;
private double freeScaleFactorY = DEFAULT_FREE_SCALE_FACTOR_Y;
private double fpsSrc = DEFAULT_SOURCE_FRAMERATE;
private double fpsTrg = DEFAULT_TARGET_FRAMERATE;
private boolean fpsSrcCertain;
private Resolution outputResolution = DEFAULT_TARGET_RESOLUTION;
private int languageIdx;
private boolean exportForced;
private int cropOffsetY = DEFAULT_CROP_LINE_COUNT;
private ForcedFlagState forceAll = ForcedFlagState.KEEP;
private boolean swapCrCb;
private CaptionMoveModeX moveModeX = CaptionMoveModeX.KEEP_POSITION;
private CaptionMoveModeY moveModeY = CaptionMoveModeY.KEEP_POSITION;
private int moveOffsetX = DEFAULT_MOVE_X_OFFSET;
private int moveOffsetY = DEFAULT_MOVE_Y_OFFSET;
private boolean moveCaptions;
/** Factor to calculate height of one cinemascope bar from screen height */
private double cineBarFactor = 5.0/42;
private StreamID currentStreamID = StreamID.UNKNOWN;
private boolean keepFps;
private static final int RECENT_FILE_COUNT = 5;
private static final String CONFIG_FILE = "bdsup2sup.ini";
private static final Configuration INSTANCE = new Configuration();
private final String configFilePath;
private List<String> recentFiles;
private int[] luminanceThreshold = {DEFAULT_LUMINANCE_MED_HIGH_THRESHOLD, DEFAULT_LUMINANCE_LOW_MED_THRESHOLD};
private int alphaThreshold = DEFAULT_ALPHA_THRESHOLD;
private Props props;
private Configuration() {
configFilePath = workOutConfigFilePath();
props = new Props();
}
public void load() {
readConfigFile();
loadConfig();
}
private void readConfigFile() {
props.clear();
props.setHeader(Constants.APP_NAME + " " + Constants.APP_VERSION + " settings - don't modify manually");
props.load(configFilePath);
}
private void loadConfig() {
loadRecentFiles();
convertResolution = loadConvertResolution();
outputResolution = loadOutputResolution();
convertFPS = loadConvertFPS();
fpsSrc = loadFpsSrc();
fpsTrg = loadFpsTrg();
delayPTS = loadDelayPTS();
fixShortFrames = loadFixShortFrames();
minTimePTS = loadMinTimePTS();
applyFreeScale = loadApplyFreeScale();
freeScaleFactorX = loadFreeScaleFactorX();
freeScaleFactorY = loadFreeScaleFactorY();
}
public void storeConfig() {
if (!cliMode) {
props.save(configFilePath);
}
}
private void loadRecentFiles() {
recentFiles = new ArrayList<String>();
int i = 0;
String filename;
while (i < RECENT_FILE_COUNT && (filename = props.get("recent_" + i, "")).length() > 0) {
if (new File(filename).exists()) {
recentFiles.add(filename);
}
i++;
}
}
public static Configuration getInstance() {
return INSTANCE;
}
private String workOutConfigFilePath() {
if (PlatformUtils.isLinux()) {
String xdgConfigHome = System.getenv("XDG_CONFIG_HOME");
File configFileDir = new File((xdgConfigHome != null ? xdgConfigHome : System.getProperty("user.home") + "/.config") + "/bdsup2sub");
if (!configFileDir.exists()) {
configFileDir.mkdir();
}
return configFileDir + "/" + CONFIG_FILE;
} else if (PlatformUtils.isMac()) {
File configFileDir = new File(System.getProperty("user.home") + "/Library/Application Support/bdsup2sub");
if (!configFileDir.exists()) {
configFileDir.mkdir();
}
return configFileDir + "/" + CONFIG_FILE;
} else {
File configFileDir = new File(System.getProperty("user.home") + "/bdsup2sub");
if (!configFileDir.exists()) {
configFileDir.mkdir();
}
return configFileDir + "/" + CONFIG_FILE;
}
}
public boolean isCliMode() {
return cliMode;
}
public void setCliMode(boolean cliMode) {
this.cliMode = cliMode;
}
public boolean isVerbose() {
return props.get("verbose", false);
}
public void setVerbose(boolean verbose) {
props.set("verbose", verbose);
}
/**
* Write PGCEdit palette file on export.
*/
public boolean getWritePGCEditPalette() {
return props.get("writePGCEditPal", false);
}
public void setWritePGCEditPalette(boolean writePGCEditPalette) {
props.set("writePGCEditPal", writePGCEditPalette);
}
/**
* Get maximum time difference for merging captions.
*/
public int getMergePTSdiff() {
return props.get("mergePTSdiff", DEFAULT_MERGE_PTS_DIFF);
}
public void setMergePTSdiff(int mergePTSdiff) {
props.set("mergePTSdiff", mergePTSdiff);
}
/**
* Get alpha threshold for cropping.
*/
public int getAlphaCrop() {
return props.get("alphaCrop", DEFAULT_ALPHA_CROP_THRESHOLD);
}
public void setAlphaCrop(int alphaCrop) {
props.set("alphaCrop", alphaCrop);
}
/**
* Fix completely invisible subtitles due to alpha=0 (SUB/IDX and SUP/IFO import only).
*/
public boolean getFixZeroAlpha() {
return props.get("fixZeroAlpha", false);
}
public void setFixZeroAlpha(boolean fixZeroAlpha) {
props.set("fixZeroAlpha", fixZeroAlpha);
}
public ScalingFilter getScalingFilter() {
ScalingFilter defaultScalingFilter = ScalingFilter.BILINEAR;
try {
return ScalingFilter.valueOf(props.get("filter", defaultScalingFilter.name()));
} catch (IllegalArgumentException ex) {
return defaultScalingFilter;
}
}
public void setScalingFilter(ScalingFilter filter) {
props.set("filter", filter.name());
}
/**
* Get palette creation mode.
*/
public PaletteMode getPaletteMode() {
PaletteMode defaultPaletteMode = PaletteMode.CREATE_NEW;
try {
return PaletteMode.valueOf(props.get("paletteMode", defaultPaletteMode.name()));
} catch (IllegalArgumentException ex) {
return defaultPaletteMode;
}
}
public void setPaletteMode(PaletteMode paletteMode) {
props.set("paletteMode", paletteMode.name());
}
public OutputMode getOutputMode() {
try {
return OutputMode.valueOf(props.get("outputMode", DEFAULT_OUTPUT_MODE.name()));
} catch (IllegalArgumentException ex) {
return DEFAULT_OUTPUT_MODE;
}
}
public void setOutputMode(OutputMode outputMode) {
props.set("outputMode", outputMode.name());
}
public String getLoadPath() {
return props.get("loadPath", "");
}
public void setLoadPath(String loadPath) {
props.set("loadPath", loadPath);
}
public String getColorProfilePath() {
return props.get("colorPath", "");
}
public void setColorProfilePath(String colorProfilePath) {
props.set("colorPath", colorProfilePath);
}
public Dimension getMainWindowSize() {
return new Dimension(props.get("frameWidth", 800), props.get("frameHeight", 600));
}
public void setMainWindowSize(Dimension dimension) {
props.set("frameWidth", dimension.width);
props.set("frameHeight", dimension.height);
}
public Point getMainWindowLocation() {
return new Point(props.get("framePosX", -1), props.get("framePosY", -1));
}
public void setMainWindowLocation(Point location) {
props.set("framePosX", location.x);
props.set("framePosY", location.y);
}
public List<String> getRecentFiles() {
return recentFiles;
}
public void addToRecentFiles(String filename) {
int index = recentFiles.indexOf(filename);
if (index != -1) {
recentFiles.remove(index);
recentFiles.add(0, filename);
} else {
recentFiles.add(0, filename);
if (recentFiles.size() > RECENT_FILE_COUNT) {
recentFiles.remove(recentFiles.size() - 1);
}
}
for (int i=0; i < recentFiles.size(); i++) {
props.set("recent_" + i, recentFiles.get(i));
}
}
public boolean getConvertResolution() {
return convertResolution;
}
public void setConvertResolution(boolean convertResolution) {
this.convertResolution = convertResolution;
}
public boolean loadConvertResolution() {
return props.get("convertResolution", CONVERT_RESOLUTION_BY_DEFAULT);
}
public void storeConvertResolution(boolean convertResolution) {
props.set("convertResolution", convertResolution);
}
/**
* Get flag that tells whether or not to convert the frame rate.
*/
public boolean getConvertFPS() {
return convertFPS;
}
public void setConvertFPS(boolean convertFPS) {
this.convertFPS = convertFPS;
}
public boolean loadConvertFPS() {
return props.get("convertFPS", CONVERT_FRAMERATE_BY_DEFAULT);
}
public void storeConvertFPS(boolean convertFPS) {
props.set("convertFPS", convertFPS);
}
/**
* Get Delay to apply to target in 90kHz resolution.
*/
public int getDelayPTS() {
return delayPTS;
}
public void setDelayPTS(int delayPTS) {
this.delayPTS = delayPTS;
}
public int loadDelayPTS() {
return props.get("delayPTS", DEFAULT_PTS_DELAY);
}
public void storeDelayPTS(int delayPTS) {
props.set("delayPTS", delayPTS);
}
/**
* Set flag that tells whether to fix subpictures with a display time shorter than minTimePTS.
*/
public boolean getFixShortFrames() {
return fixShortFrames;
}
public void setFixShortFrames(boolean fixShortFrames) {
this.fixShortFrames = fixShortFrames;
}
public boolean loadFixShortFrames() {
return props.get("fixShortFrames", FIX_SHORT_FRAMES_BY_DEFAULT);
}
public void storeFixShortFrames(boolean fixShortFrames) {
props.set("fixShortFrames", fixShortFrames);
}
/**
* Get minimum display time for subpictures in 90kHz resolution
*/
public int getMinTimePTS() {
return minTimePTS;
}
public void setMinTimePTS(int minTimePTS) {
this.minTimePTS = minTimePTS;
}
public int loadMinTimePTS() {
return props.get("minTimePTS", DEFAULT_MIN_DISPLAY_TIME_PTS);
}
public void storeMinTimePTS(int minTimePTS) {
props.set("minTimePTS", minTimePTS);
}
public boolean getApplyFreeScale() {
return applyFreeScale;
}
public void setApplyFreeScale(boolean applyFreeScale) {
this.applyFreeScale = applyFreeScale;
}
public boolean loadApplyFreeScale() {
return props.get("applyFreeScale", APPLY_FREE_SCALE_BY_DEFAULT);
}
public void storeApplyFreeScale(boolean applyFreeScale) {
props.set("applyFreeScale", applyFreeScale);
}
public double getFreeScaleFactorX() {
return freeScaleFactorX;
}
public double getFreeScaleFactorY() {
return freeScaleFactorY;
}
public void setFreeScaleFactor(double x, double y) {
if (x < MIN_FREE_SCALE_FACTOR) {
x = MIN_FREE_SCALE_FACTOR;
} else if (x > MAX_FREE_SCALE_FACTOR) {
x = MAX_FREE_SCALE_FACTOR;
}
freeScaleFactorX = x;
if (y < MIN_FREE_SCALE_FACTOR) {
y = MIN_FREE_SCALE_FACTOR;
} else if (y > MAX_FREE_SCALE_FACTOR) {
y = MAX_FREE_SCALE_FACTOR;
}
freeScaleFactorY = y;
}
public double loadFreeScaleFactorX() {
return props.get("freeScaleX", DEFAULT_FREE_SCALE_FACTOR_X);
}
public double loadFreeScaleFactorY() {
return props.get("freeScaleY", DEFAULT_FREE_SCALE_FACTOR_Y);
}
public void storeFreeScaleFactor(double x, double y) {
if (x < MIN_FREE_SCALE_FACTOR) {
x = MIN_FREE_SCALE_FACTOR;
} else if (x > MAX_FREE_SCALE_FACTOR) {
x = MAX_FREE_SCALE_FACTOR;
}
props.set("freeScaleX", x);
if (y < MIN_FREE_SCALE_FACTOR) {
y = MIN_FREE_SCALE_FACTOR;
} else if (y > MAX_FREE_SCALE_FACTOR) {
y = MAX_FREE_SCALE_FACTOR;
}
props.set("freeScaleY", y);
}
public double getFPSSrc() {
return fpsSrc;
}
public void setFpsSrc(double fpsSrc) {
this.fpsSrc = fpsSrc;
}
public double loadFpsSrc() {
return SubtitleUtils.getFps(props.get("fpsSrc", String.valueOf(DEFAULT_SOURCE_FRAMERATE)));
}
public void storeFPSSrc(double fpsSrc) {
props.set("fpsSrc", fpsSrc);
}
public double getFpsTrg() {
return fpsTrg;
}
public void setFpsTrg(double fpsTrg) {
this.fpsTrg = fpsTrg;
setDelayPTS((int)SubtitleUtils.syncTimePTS(getDelayPTS(), fpsTrg, fpsTrg));
setMinTimePTS((int)SubtitleUtils.syncTimePTS(getMinTimePTS(), fpsTrg, fpsTrg));
}
public double loadFpsTrg() {
return SubtitleUtils.getFps(props.get("fpsTrg", String.valueOf(DEFAULT_TARGET_FRAMERATE)));
}
public void storeFpsTrg(double fpsTrg) {
props.set("fpsTrg", fpsTrg);
}
public boolean isFpsSrcCertain() {
return fpsSrcCertain;
}
public void setFpsSrcCertain(boolean fpsSrcCertain) {
this.fpsSrcCertain = fpsSrcCertain;
}
public Resolution getOutputResolution() {
return outputResolution;
}
public void setOutputResolution(Resolution outputResolution) {
this.outputResolution = outputResolution;
}
public Resolution loadOutputResolution() {
try {
return Resolution.valueOf(props.get("resolutionTrg", DEFAULT_TARGET_RESOLUTION.name()));
} catch (IllegalArgumentException e) {
return DEFAULT_TARGET_RESOLUTION;
}
}
public void storeOutputResolution(Resolution outputResolution) {
props.set("resolutionTrg", outputResolution.name());
}
public int getAlphaThreshold() {
return alphaThreshold;
}
public void setAlphaThreshold(int alphaThreshold) {
this.alphaThreshold = alphaThreshold;
}
/**
* Array of luminance thresholds ( 0: med/high, 1: low/med )
*/
public int[] getLuminanceThreshold() {
return luminanceThreshold;
}
public void setLuminanceThreshold(int[] luminanceThreshold) {
this.luminanceThreshold = luminanceThreshold;
}
/**
* Index of language to be used for SUB/IDX export (also used for XML export)
*/
public int getLanguageIdx() {
return languageIdx;
}
public void setLanguageIdx(int languageIdx) {
this.languageIdx = languageIdx;
}
/**
* Flag that defines whether to export only subpictures marked as "forced"
*/
public boolean isExportForced() {
return exportForced;
}
public void setExportForced(boolean exportForced) {
this.exportForced = exportForced;
}
public int getCropOffsetY() {
return cropOffsetY;
}
public void setCropOffsetY(int cropOffsetY) {
this.cropOffsetY = cropOffsetY;
}
public ForcedFlagState getForceAll() {
return forceAll;
}
public void setForceAll(ForcedFlagState forceAll) {
this.forceAll = forceAll;
}
public boolean isSwapCrCb() {
return swapCrCb;
}
public void setSwapCrCb(boolean swapCrCb) {
this.swapCrCb = swapCrCb;
}
public void setMoveModeY(CaptionMoveModeY moveModeY) {
this.moveModeY = moveModeY;
this.moveCaptions = (moveModeY != CaptionMoveModeY.KEEP_POSITION) || (moveModeX != CaptionMoveModeX.KEEP_POSITION);
}
public CaptionMoveModeY getMoveModeY() {
return moveModeY;
}
public void setMoveModeX(CaptionMoveModeX moveModeX) {
this.moveModeX = moveModeX;
this.moveCaptions = (moveModeY != CaptionMoveModeY.KEEP_POSITION) || (moveModeX != CaptionMoveModeX.KEEP_POSITION);
}
public CaptionMoveModeX getMoveModeX() {
return moveModeX;
}
public void setMoveOffsetY(int moveOffsetY) {
this.moveOffsetY = moveOffsetY;
}
public int getMoveOffsetY() {
return moveOffsetY;
}
public void setMoveOffsetX(int moveOffsetX) {
this.moveOffsetX = moveOffsetX;
}
public int getMoveOffsetX() {
return moveOffsetX;
}
/**
* Get: keep move settings after loading a new stream
* @return true: keep settings, false: ignore settings
*/
public boolean getMoveCaptions() {
return moveCaptions;
}
/**
* Set: keep move settings after loading a new stream
* @param moveCaptions true: keep settings, false; ignore settings
*/
public void setMoveCaptions(boolean moveCaptions) {
this.moveCaptions = moveCaptions;
}
public double getCineBarFactor() {
return cineBarFactor;
}
public void setCineBarFactor(double cineBarFactor) {
this.cineBarFactor = cineBarFactor;
}
public StreamID getCurrentStreamID() {
return currentStreamID;
}
public void setCurrentStreamID(StreamID currentStreamID) {
this.currentStreamID = currentStreamID;
}
public boolean isKeepFps() {
return keepFps;
}
public void setKeepFps(boolean keepFps) {
this.keepFps = keepFps;
}
}
| src/main/java/bdsup2sub/core/Configuration.java | /*
* Copyright 2012 Miklos Juhasz (mjuhasz)
*
* 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 bdsup2sub.core;
import bdsup2sub.tools.Props;
import bdsup2sub.utils.FilenameUtils;
import bdsup2sub.utils.PlatformUtils;
import bdsup2sub.utils.SubtitleUtils;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
public final class Configuration {
public static final Color OK_BACKGROUND = UIManager.getColor("TextField.background");
public static final Color WARN_BACKGROUND = new Color(0xffffffc0);
public static final Color ERROR_BACKGROUND = new Color(0xffe1acac);
public static final boolean CONVERT_RESOLUTION_BY_DEFAULT = false;
public static final boolean CONVERT_FRAMERATE_BY_DEFAULT = false;
public static final int DEFAULT_PTS_DELAY = 0;
public static final boolean FIX_SHORT_FRAMES_BY_DEFAULT = false;
public static final int DEFAULT_MIN_DISPLAY_TIME_PTS = 90 * 500;
public static final boolean APPLY_FREE_SCALE_BY_DEFAULT = false;
public static final double DEFAULT_FREE_SCALE_FACTOR_X = 1.0;
public static final double DEFAULT_FREE_SCALE_FACTOR_Y = 1.0;
public static final double MIN_FREE_SCALE_FACTOR = 0.5;
public static final double MAX_FREE_SCALE_FACTOR = 2.0;
public static final double DEFAULT_SOURCE_FRAMERATE = Framerate.FPS_23_976.getValue(); //TODO: dumb default
public static final double DEFAULT_TARGET_FRAMERATE = Framerate.PAL.getValue(); //TODO: dumb default
public static final Resolution DEFAULT_TARGET_RESOLUTION = Resolution.PAL; //TODO: dumb default
public static final int DEFAULT_ALPHA_CROP_THRESHOLD = 14;
public static final int DEFAULT_ALPHA_THRESHOLD = 80;
public static final int DEFAULT_LUMINANCE_MED_HIGH_THRESHOLD = 210;
public static final int DEFAULT_LUMINANCE_LOW_MED_THRESHOLD = 160;
public static final int DEFAULT_MOVE_Y_OFFSET = 10;
public static final int DEFAULT_MOVE_X_OFFSET = 10;
public static final int DEFAULT_CROP_LINE_COUNT = 0;
//Two equal captions are merged of they are closer than 200ms (0.2*90000 = 18000)
public static final int DEFAULT_MERGE_PTS_DIFF = 18000;
public static final OutputMode DEFAULT_OUTPUT_MODE = OutputMode.VOBSUB;
private boolean convertResolution = CONVERT_RESOLUTION_BY_DEFAULT;
private boolean convertFPS = CONVERT_FRAMERATE_BY_DEFAULT;
private int delayPTS = DEFAULT_PTS_DELAY;
private boolean cliMode = true;
private boolean fixShortFrames = FIX_SHORT_FRAMES_BY_DEFAULT;
private int minTimePTS = DEFAULT_MIN_DISPLAY_TIME_PTS;
private boolean applyFreeScale = APPLY_FREE_SCALE_BY_DEFAULT;
private double freeScaleFactorX = DEFAULT_FREE_SCALE_FACTOR_X;
private double freeScaleFactorY = DEFAULT_FREE_SCALE_FACTOR_Y;
private double fpsSrc = DEFAULT_SOURCE_FRAMERATE;
private double fpsTrg = DEFAULT_TARGET_FRAMERATE;
private boolean fpsSrcCertain;
private Resolution outputResolution = DEFAULT_TARGET_RESOLUTION;
private int languageIdx;
private boolean exportForced;
private int cropOffsetY = DEFAULT_CROP_LINE_COUNT;
private ForcedFlagState forceAll = ForcedFlagState.KEEP;
private boolean swapCrCb;
private CaptionMoveModeX moveModeX = CaptionMoveModeX.KEEP_POSITION;
private CaptionMoveModeY moveModeY = CaptionMoveModeY.KEEP_POSITION;
private int moveOffsetX = DEFAULT_MOVE_X_OFFSET;
private int moveOffsetY = DEFAULT_MOVE_Y_OFFSET;
private boolean moveCaptions;
/** Factor to calculate height of one cinemascope bar from screen height */
private double cineBarFactor = 5.0/42;
private StreamID currentStreamID = StreamID.UNKNOWN;
private boolean keepFps;
private static final int RECENT_FILE_COUNT = 5;
private static final String CONFIG_FILE = "bdsup2sup.ini";
private static final Configuration INSTANCE = new Configuration();
private final String configFilePath;
private List<String> recentFiles;
private int[] luminanceThreshold = {DEFAULT_LUMINANCE_MED_HIGH_THRESHOLD, DEFAULT_LUMINANCE_LOW_MED_THRESHOLD};
private int alphaThreshold = DEFAULT_ALPHA_THRESHOLD;
private Props props;
private Configuration() {
configFilePath = workOutConfigFilePath();
props = new Props();
}
public void load() {
readConfigFile();
loadConfig();
}
private void readConfigFile() {
props.clear();
props.setHeader(Constants.APP_NAME + " " + Constants.APP_VERSION + " settings - don't modify manually");
props.load(configFilePath);
}
private void loadConfig() {
loadRecentFiles();
convertResolution = loadConvertResolution();
outputResolution = loadOutputResolution();
convertFPS = loadConvertFPS();
fpsSrc = loadFpsSrc();
fpsTrg = loadFpsTrg();
delayPTS = loadDelayPTS();
fixShortFrames = loadFixShortFrames();
minTimePTS = loadMinTimePTS();
applyFreeScale = loadApplyFreeScale();
freeScaleFactorX = loadFreeScaleFactorX();
freeScaleFactorY = loadFreeScaleFactorY();
}
public void storeConfig() {
if (!cliMode) {
props.save(configFilePath);
}
}
private void loadRecentFiles() {
recentFiles = new ArrayList<String>();
int i = 0;
String filename;
while (i < RECENT_FILE_COUNT && (filename = props.get("recent_" + i, "")).length() > 0) {
if (new File(filename).exists()) {
recentFiles.add(filename);
}
i++;
}
}
public static Configuration getInstance() {
return INSTANCE;
}
private String workOutConfigFilePath() {
if (PlatformUtils.isLinux()) {
String xdgConfigHome = System.getenv("XDG_CONFIG_HOME");
File configFileDir = new File((xdgConfigHome != null ? xdgConfigHome : System.getProperty("user.home") + "/.config") + "/bdsup2sub");
if (!configFileDir.exists()) {
configFileDir.mkdir();
}
return configFileDir + "/" + CONFIG_FILE;
} else {
String relPathToClassFile = Configuration.class.getName().replace('.','/') + ".class";
String absPathToClassFile = Configuration.class.getClassLoader().getResource(relPathToClassFile).getPath();
int pos = absPathToClassFile.toLowerCase().indexOf(relPathToClassFile.toLowerCase());
String configFileDir = absPathToClassFile.substring(0, pos);
if (configFileDir.startsWith("file:")) {
configFileDir = configFileDir.substring("file:".length());
}
configFileDir = FilenameUtils.separatorsToUnix(configFileDir);
pos = configFileDir.lastIndexOf(".jar");
if (pos != -1) {
pos = configFileDir.substring(0, pos).lastIndexOf('/');
if (pos != -1) {
configFileDir = configFileDir.substring(0, pos + 1);
}
}
return configFileDir + CONFIG_FILE;
}
}
public boolean isCliMode() {
return cliMode;
}
public void setCliMode(boolean cliMode) {
this.cliMode = cliMode;
}
public boolean isVerbose() {
return props.get("verbose", false);
}
public void setVerbose(boolean verbose) {
props.set("verbose", verbose);
}
/**
* Write PGCEdit palette file on export.
*/
public boolean getWritePGCEditPalette() {
return props.get("writePGCEditPal", false);
}
public void setWritePGCEditPalette(boolean writePGCEditPalette) {
props.set("writePGCEditPal", writePGCEditPalette);
}
/**
* Get maximum time difference for merging captions.
*/
public int getMergePTSdiff() {
return props.get("mergePTSdiff", DEFAULT_MERGE_PTS_DIFF);
}
public void setMergePTSdiff(int mergePTSdiff) {
props.set("mergePTSdiff", mergePTSdiff);
}
/**
* Get alpha threshold for cropping.
*/
public int getAlphaCrop() {
return props.get("alphaCrop", DEFAULT_ALPHA_CROP_THRESHOLD);
}
public void setAlphaCrop(int alphaCrop) {
props.set("alphaCrop", alphaCrop);
}
/**
* Fix completely invisible subtitles due to alpha=0 (SUB/IDX and SUP/IFO import only).
*/
public boolean getFixZeroAlpha() {
return props.get("fixZeroAlpha", false);
}
public void setFixZeroAlpha(boolean fixZeroAlpha) {
props.set("fixZeroAlpha", fixZeroAlpha);
}
public ScalingFilter getScalingFilter() {
ScalingFilter defaultScalingFilter = ScalingFilter.BILINEAR;
try {
return ScalingFilter.valueOf(props.get("filter", defaultScalingFilter.name()));
} catch (IllegalArgumentException ex) {
return defaultScalingFilter;
}
}
public void setScalingFilter(ScalingFilter filter) {
props.set("filter", filter.name());
}
/**
* Get palette creation mode.
*/
public PaletteMode getPaletteMode() {
PaletteMode defaultPaletteMode = PaletteMode.CREATE_NEW;
try {
return PaletteMode.valueOf(props.get("paletteMode", defaultPaletteMode.name()));
} catch (IllegalArgumentException ex) {
return defaultPaletteMode;
}
}
public void setPaletteMode(PaletteMode paletteMode) {
props.set("paletteMode", paletteMode.name());
}
public OutputMode getOutputMode() {
try {
return OutputMode.valueOf(props.get("outputMode", DEFAULT_OUTPUT_MODE.name()));
} catch (IllegalArgumentException ex) {
return DEFAULT_OUTPUT_MODE;
}
}
public void setOutputMode(OutputMode outputMode) {
props.set("outputMode", outputMode.name());
}
public String getLoadPath() {
return props.get("loadPath", "");
}
public void setLoadPath(String loadPath) {
props.set("loadPath", loadPath);
}
public String getColorProfilePath() {
return props.get("colorPath", "");
}
public void setColorProfilePath(String colorProfilePath) {
props.set("colorPath", colorProfilePath);
}
public Dimension getMainWindowSize() {
return new Dimension(props.get("frameWidth", 800), props.get("frameHeight", 600));
}
public void setMainWindowSize(Dimension dimension) {
props.set("frameWidth", dimension.width);
props.set("frameHeight", dimension.height);
}
public Point getMainWindowLocation() {
return new Point(props.get("framePosX", -1), props.get("framePosY", -1));
}
public void setMainWindowLocation(Point location) {
props.set("framePosX", location.x);
props.set("framePosY", location.y);
}
public List<String> getRecentFiles() {
return recentFiles;
}
public void addToRecentFiles(String filename) {
int index = recentFiles.indexOf(filename);
if (index != -1) {
recentFiles.remove(index);
recentFiles.add(0, filename);
} else {
recentFiles.add(0, filename);
if (recentFiles.size() > RECENT_FILE_COUNT) {
recentFiles.remove(recentFiles.size() - 1);
}
}
for (int i=0; i < recentFiles.size(); i++) {
props.set("recent_" + i, recentFiles.get(i));
}
}
public boolean getConvertResolution() {
return convertResolution;
}
public void setConvertResolution(boolean convertResolution) {
this.convertResolution = convertResolution;
}
public boolean loadConvertResolution() {
return props.get("convertResolution", CONVERT_RESOLUTION_BY_DEFAULT);
}
public void storeConvertResolution(boolean convertResolution) {
props.set("convertResolution", convertResolution);
}
/**
* Get flag that tells whether or not to convert the frame rate.
*/
public boolean getConvertFPS() {
return convertFPS;
}
public void setConvertFPS(boolean convertFPS) {
this.convertFPS = convertFPS;
}
public boolean loadConvertFPS() {
return props.get("convertFPS", CONVERT_FRAMERATE_BY_DEFAULT);
}
public void storeConvertFPS(boolean convertFPS) {
props.set("convertFPS", convertFPS);
}
/**
* Get Delay to apply to target in 90kHz resolution.
*/
public int getDelayPTS() {
return delayPTS;
}
public void setDelayPTS(int delayPTS) {
this.delayPTS = delayPTS;
}
public int loadDelayPTS() {
return props.get("delayPTS", DEFAULT_PTS_DELAY);
}
public void storeDelayPTS(int delayPTS) {
props.set("delayPTS", delayPTS);
}
/**
* Set flag that tells whether to fix subpictures with a display time shorter than minTimePTS.
*/
public boolean getFixShortFrames() {
return fixShortFrames;
}
public void setFixShortFrames(boolean fixShortFrames) {
this.fixShortFrames = fixShortFrames;
}
public boolean loadFixShortFrames() {
return props.get("fixShortFrames", FIX_SHORT_FRAMES_BY_DEFAULT);
}
public void storeFixShortFrames(boolean fixShortFrames) {
props.set("fixShortFrames", fixShortFrames);
}
/**
* Get minimum display time for subpictures in 90kHz resolution
*/
public int getMinTimePTS() {
return minTimePTS;
}
public void setMinTimePTS(int minTimePTS) {
this.minTimePTS = minTimePTS;
}
public int loadMinTimePTS() {
return props.get("minTimePTS", DEFAULT_MIN_DISPLAY_TIME_PTS);
}
public void storeMinTimePTS(int minTimePTS) {
props.set("minTimePTS", minTimePTS);
}
public boolean getApplyFreeScale() {
return applyFreeScale;
}
public void setApplyFreeScale(boolean applyFreeScale) {
this.applyFreeScale = applyFreeScale;
}
public boolean loadApplyFreeScale() {
return props.get("applyFreeScale", APPLY_FREE_SCALE_BY_DEFAULT);
}
public void storeApplyFreeScale(boolean applyFreeScale) {
props.set("applyFreeScale", applyFreeScale);
}
public double getFreeScaleFactorX() {
return freeScaleFactorX;
}
public double getFreeScaleFactorY() {
return freeScaleFactorY;
}
public void setFreeScaleFactor(double x, double y) {
if (x < MIN_FREE_SCALE_FACTOR) {
x = MIN_FREE_SCALE_FACTOR;
} else if (x > MAX_FREE_SCALE_FACTOR) {
x = MAX_FREE_SCALE_FACTOR;
}
freeScaleFactorX = x;
if (y < MIN_FREE_SCALE_FACTOR) {
y = MIN_FREE_SCALE_FACTOR;
} else if (y > MAX_FREE_SCALE_FACTOR) {
y = MAX_FREE_SCALE_FACTOR;
}
freeScaleFactorY = y;
}
public double loadFreeScaleFactorX() {
return props.get("freeScaleX", DEFAULT_FREE_SCALE_FACTOR_X);
}
public double loadFreeScaleFactorY() {
return props.get("freeScaleY", DEFAULT_FREE_SCALE_FACTOR_Y);
}
public void storeFreeScaleFactor(double x, double y) {
if (x < MIN_FREE_SCALE_FACTOR) {
x = MIN_FREE_SCALE_FACTOR;
} else if (x > MAX_FREE_SCALE_FACTOR) {
x = MAX_FREE_SCALE_FACTOR;
}
props.set("freeScaleX", x);
if (y < MIN_FREE_SCALE_FACTOR) {
y = MIN_FREE_SCALE_FACTOR;
} else if (y > MAX_FREE_SCALE_FACTOR) {
y = MAX_FREE_SCALE_FACTOR;
}
props.set("freeScaleY", y);
}
public double getFPSSrc() {
return fpsSrc;
}
public void setFpsSrc(double fpsSrc) {
this.fpsSrc = fpsSrc;
}
public double loadFpsSrc() {
return SubtitleUtils.getFps(props.get("fpsSrc", String.valueOf(DEFAULT_SOURCE_FRAMERATE)));
}
public void storeFPSSrc(double fpsSrc) {
props.set("fpsSrc", fpsSrc);
}
public double getFpsTrg() {
return fpsTrg;
}
public void setFpsTrg(double fpsTrg) {
this.fpsTrg = fpsTrg;
setDelayPTS((int)SubtitleUtils.syncTimePTS(getDelayPTS(), fpsTrg, fpsTrg));
setMinTimePTS((int)SubtitleUtils.syncTimePTS(getMinTimePTS(), fpsTrg, fpsTrg));
}
public double loadFpsTrg() {
return SubtitleUtils.getFps(props.get("fpsTrg", String.valueOf(DEFAULT_TARGET_FRAMERATE)));
}
public void storeFpsTrg(double fpsTrg) {
props.set("fpsTrg", fpsTrg);
}
public boolean isFpsSrcCertain() {
return fpsSrcCertain;
}
public void setFpsSrcCertain(boolean fpsSrcCertain) {
this.fpsSrcCertain = fpsSrcCertain;
}
public Resolution getOutputResolution() {
return outputResolution;
}
public void setOutputResolution(Resolution outputResolution) {
this.outputResolution = outputResolution;
}
public Resolution loadOutputResolution() {
try {
return Resolution.valueOf(props.get("resolutionTrg", DEFAULT_TARGET_RESOLUTION.name()));
} catch (IllegalArgumentException e) {
return DEFAULT_TARGET_RESOLUTION;
}
}
public void storeOutputResolution(Resolution outputResolution) {
props.set("resolutionTrg", outputResolution.name());
}
public int getAlphaThreshold() {
return alphaThreshold;
}
public void setAlphaThreshold(int alphaThreshold) {
this.alphaThreshold = alphaThreshold;
}
/**
* Array of luminance thresholds ( 0: med/high, 1: low/med )
*/
public int[] getLuminanceThreshold() {
return luminanceThreshold;
}
public void setLuminanceThreshold(int[] luminanceThreshold) {
this.luminanceThreshold = luminanceThreshold;
}
/**
* Index of language to be used for SUB/IDX export (also used for XML export)
*/
public int getLanguageIdx() {
return languageIdx;
}
public void setLanguageIdx(int languageIdx) {
this.languageIdx = languageIdx;
}
/**
* Flag that defines whether to export only subpictures marked as "forced"
*/
public boolean isExportForced() {
return exportForced;
}
public void setExportForced(boolean exportForced) {
this.exportForced = exportForced;
}
public int getCropOffsetY() {
return cropOffsetY;
}
public void setCropOffsetY(int cropOffsetY) {
this.cropOffsetY = cropOffsetY;
}
public ForcedFlagState getForceAll() {
return forceAll;
}
public void setForceAll(ForcedFlagState forceAll) {
this.forceAll = forceAll;
}
public boolean isSwapCrCb() {
return swapCrCb;
}
public void setSwapCrCb(boolean swapCrCb) {
this.swapCrCb = swapCrCb;
}
public void setMoveModeY(CaptionMoveModeY moveModeY) {
this.moveModeY = moveModeY;
this.moveCaptions = (moveModeY != CaptionMoveModeY.KEEP_POSITION) || (moveModeX != CaptionMoveModeX.KEEP_POSITION);
}
public CaptionMoveModeY getMoveModeY() {
return moveModeY;
}
public void setMoveModeX(CaptionMoveModeX moveModeX) {
this.moveModeX = moveModeX;
this.moveCaptions = (moveModeY != CaptionMoveModeY.KEEP_POSITION) || (moveModeX != CaptionMoveModeX.KEEP_POSITION);
}
public CaptionMoveModeX getMoveModeX() {
return moveModeX;
}
public void setMoveOffsetY(int moveOffsetY) {
this.moveOffsetY = moveOffsetY;
}
public int getMoveOffsetY() {
return moveOffsetY;
}
public void setMoveOffsetX(int moveOffsetX) {
this.moveOffsetX = moveOffsetX;
}
public int getMoveOffsetX() {
return moveOffsetX;
}
/**
* Get: keep move settings after loading a new stream
* @return true: keep settings, false: ignore settings
*/
public boolean getMoveCaptions() {
return moveCaptions;
}
/**
* Set: keep move settings after loading a new stream
* @param moveCaptions true: keep settings, false; ignore settings
*/
public void setMoveCaptions(boolean moveCaptions) {
this.moveCaptions = moveCaptions;
}
public double getCineBarFactor() {
return cineBarFactor;
}
public void setCineBarFactor(double cineBarFactor) {
this.cineBarFactor = cineBarFactor;
}
public StreamID getCurrentStreamID() {
return currentStreamID;
}
public void setCurrentStreamID(StreamID currentStreamID) {
this.currentStreamID = currentStreamID;
}
public boolean isKeepFps() {
return keepFps;
}
public void setKeepFps(boolean keepFps) {
this.keepFps = keepFps;
}
}
| Store the configuration in the user's home on Mac and Windows.
| src/main/java/bdsup2sub/core/Configuration.java | Store the configuration in the user's home on Mac and Windows. | <ide><path>rc/main/java/bdsup2sub/core/Configuration.java
<ide> configFileDir.mkdir();
<ide> }
<ide> return configFileDir + "/" + CONFIG_FILE;
<add> } else if (PlatformUtils.isMac()) {
<add> File configFileDir = new File(System.getProperty("user.home") + "/Library/Application Support/bdsup2sub");
<add> if (!configFileDir.exists()) {
<add> configFileDir.mkdir();
<add> }
<add> return configFileDir + "/" + CONFIG_FILE;
<ide> } else {
<del> String relPathToClassFile = Configuration.class.getName().replace('.','/') + ".class";
<del> String absPathToClassFile = Configuration.class.getClassLoader().getResource(relPathToClassFile).getPath();
<del>
<del> int pos = absPathToClassFile.toLowerCase().indexOf(relPathToClassFile.toLowerCase());
<del> String configFileDir = absPathToClassFile.substring(0, pos);
<del>
<del> if (configFileDir.startsWith("file:")) {
<del> configFileDir = configFileDir.substring("file:".length());
<add> File configFileDir = new File(System.getProperty("user.home") + "/bdsup2sub");
<add> if (!configFileDir.exists()) {
<add> configFileDir.mkdir();
<ide> }
<del>
<del> configFileDir = FilenameUtils.separatorsToUnix(configFileDir);
<del> pos = configFileDir.lastIndexOf(".jar");
<del> if (pos != -1) {
<del> pos = configFileDir.substring(0, pos).lastIndexOf('/');
<del> if (pos != -1) {
<del> configFileDir = configFileDir.substring(0, pos + 1);
<del> }
<del> }
<del> return configFileDir + CONFIG_FILE;
<add> return configFileDir + "/" + CONFIG_FILE;
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 978a4d857a436788249b0c439929109d09d9ddb8 | 0 | Movile/movile-exoplayer,anton46/ExoPlayer,jcable/ExoPlayer,piterwilson/ExoPlayer,souji1103/ExoPlayer,tieusangaka/ExoPlayer,satorufujiwara/ExoPlayer,ziyaozou/ExoPlayer,MaTriXy/ExoPlayer,KiminRyu/ExoPlayer,sunfeiXjoyin/ExoPlayer,rodrigodzf/ExoPlayer,TheWeatherCompany/ExoPlayer,saki4510t/ExoPlayer,julo15/ExoPlayer,JasonFengHot/ExoPlayerSource,Plumzi/ExoPlayer,satorufujiwara/ExoPlayer,kiall/ExoPlayer,pittenga/ExoPlayer,michalliu/ExoPlayer,kstv/ExoPlayer,khj0704/ExoPlayer,ened/ExoPlayer,kiall/ExoPlayer,rodrigodzf/ExoPlayer,sshuvro58/ExoPlayer,ClubCom/AndroidExoPlayer,Octavianus/Close-Loop-Visual-Stimulus-Display-System,luckcoolla/ExoPlayer,tresvecesseis/ExoPlayer,ppamorim/ExoPlayer,Zo2m4bie/ExoPlayer,RizalMahesh/ExoPlayer,androidx/media,ziyaozou/ExoPlayer,gitanuj/ExoPlayer,FinalLevel/ExoPlayer,julo15/ExoPlayer,jcable/ExoPlayer,androidx/media,hgl888/ExoPlayer,ppamorim/ExoPlayer,Mozhuowen/ExoPlayer,sshuvro58/ExoPlayer,barbarian/ExoPlayer,pakerfeldt/ExoPlayer,ened/ExoPlayer,aravinds03/ExoPlayer,Movile/movile-exoplayer,UIKit0/ExoPlayer,jeoliva/ExoPlayer,tikaPahadi/ExoPlayer,Ood-Tsen/ExoPlayer,tntcrowd/ExoPlayer,julo15/ExoPlayer,souji1103/ExoPlayer,YouKim/ExoPlayer,ZaneSummer/ExoPlayer,fanhattan/ExoPlayer,treejames/ExoPlayer,bhnath/ExoPlayer,treejames/ExoPlayer,kiall/ExoPlayer,YouKim/ExoPlayer,aravinds03/ExoPlayer,tieusangaka/ExoPlayer,satorufujiwara/ExoPlayer,hgl888/ExoPlayer,rubensousa/exoplayer-amazon-port,RizalMahesh/ExoPlayer,finch0219/ExoPlayer,natez0r/ExoPlayer,reid-mcpherson/ExoPlayerDebug,reid-mcpherson/ExoPlayerDebug,castlabs/ExoPlayer,pajatopmr/ExoPlayer,bongole/ExoPlayer,flipagram/ExoPlayer,amikey/ExoPlayer,martinbonnin/ExoPlayer,sergiomartinez4/ExoPlayer,amzn/exoplayer-amazon-port,tresvecesseis/ExoPlayer,eriuzo/ExoPlayer,sshuvro58/ExoPlayer,bongole/ExoPlayer,rtsmb/ExoPlayer,Cheers-Dev/ExoPlayer,rtsmb/ExoPlayer,FinalLevel/ExoPlayer,seventhmoon/ExoPlayer,sunfeiXjoyin/ExoPlayer,PavelSynek/ExoPlayer,ZaneSummer/ExoPlayer,Octavianus/Close-Loop-Visual-Stimulus-Display-System,tieusangaka/ExoPlayer,moicorp/ExoPlayer,martinbonnin/ExoPlayer,bhnath/ExoPlayer,sunfeiXjoyin/ExoPlayer,Ood-Tsen/ExoPlayer,tresvecesseis/ExoPlayer,mstarvid/ExoPlayer,souji1103/ExoPlayer,anton46/ExoPlayer,murat8505/ExoPlayer,Furystorm/ExoPlayer,galihrepo/ExoPlayer,androidx/media,martinbonnin/ExoPlayer,sergiomartinez4/ExoPlayer,moicorp/ExoPlayer,reid-mcpherson/ExoPlayerDebug,khj0704/ExoPlayer,jeoliva/ExoPlayer,KiminRyu/ExoPlayer,Mozhuowen/ExoPlayer,MaTriXy/ExoPlayer,RizalMahesh/ExoPlayer,hgl888/ExoPlayer,seventhmoon/ExoPlayer,FinalLevel/ExoPlayer,Octavianus/Close-Loop-Visual-Stimulus-Display-System,PavelSynek/ExoPlayer,algrid/ExoPlayer,michalliu/ExoPlayer,gitanuj/ExoPlayer,b95505017/ExoPlayer,pittenga/ExoPlayer,Movile/movile-exoplayer,piterwilson/ExoPlayer,Dysonics/ExoPlayer,ajju4455/ExoPlayer,bhnath/ExoPlayer,hanyoungpark/ExoPlayer,amikey/ExoPlayer,rtsmb/ExoPlayer,luckcoolla/ExoPlayer,hanyoungpark/ExoPlayer,tntcrowd/ExoPlayer,ppamorim/ExoPlayer,Plumzi/ExoPlayer,yangwuan55/ExoPlayer,ebr11/ExoPlayer,b95505017/ExoPlayer,ajju4455/ExoPlayer,prashant31191/ExoPlayer,algrid/ExoPlayer,anton46/ExoPlayer,Plumzi/ExoPlayer,barbarian/ExoPlayer,saki4510t/ExoPlayer,saki4510t/ExoPlayer,pittenga/ExoPlayer,WeiChungChang/ExoPlayer,galihrepo/ExoPlayer,ferrytanu/ExoPlayer,flipagram/ExoPlayer,UIKit0/ExoPlayer,b95505017/ExoPlayer,ahmashour1/ExoPlayer,YouKim/ExoPlayer,WeiChungChang/ExoPlayer,finch0219/ExoPlayer,piterwilson/ExoPlayer,natez0r/ExoPlayer,tikaPahadi/ExoPlayer,ened/ExoPlayer,seventhmoon/ExoPlayer,google/ExoPlayer,ahmashour1/ExoPlayer,0359xiaodong/ExoPlayer,ziyaozou/ExoPlayer,rodrigodzf/ExoPlayer,pakerfeldt/ExoPlayer,danikula/ExoPlayer,mingfai/ExoPlayer,ebr11/ExoPlayer,superbderrick/ExoPlayer,raphanda/ExoPlayer,mingfai/ExoPlayer,murat8505/ExoPlayer,Dysonics/ExoPlayer,ebr11/ExoPlayer,treejames/ExoPlayer,galihrepo/ExoPlayer,yangwuan55/ExoPlayer,0359xiaodong/ExoPlayer,rubensousa/exoplayer-amazon-port,finch0219/ExoPlayer,pakerfeldt/ExoPlayer,barbarian/ExoPlayer,zhouweiguo2017/ExoPlayer,Cheers-Dev/ExoPlayer,rubensousa/exoplayer-amazon-port,danikula/ExoPlayer,mingfai/ExoPlayer,tntcrowd/ExoPlayer,castlabs/ExoPlayer,mstarvid/ExoPlayer,yangwuan55/ExoPlayer,moicorp/ExoPlayer,tikaPahadi/ExoPlayer,murat8505/ExoPlayer,mstarvid/ExoPlayer,jcable/ExoPlayer,eriuzo/ExoPlayer,stari4ek/ExoPlayer,stari4ek/ExoPlayer,amikey/ExoPlayer,prashant31191/ExoPlayer,luckcoolla/ExoPlayer,ajju4455/ExoPlayer,gitanuj/ExoPlayer,zhouweiguo2017/ExoPlayer,flipagram/ExoPlayer,nickooms/ExoPlayer,Mozhuowen/ExoPlayer,google/ExoPlayer,fanhattan/ExoPlayer,PavelSynek/ExoPlayer,ahmashour1/ExoPlayer,superbderrick/ExoPlayer,TheWeatherCompany/ExoPlayer,YouKim/ExoPlayer,Cheers-Dev/ExoPlayer,Furystorm/ExoPlayer,aravinds03/ExoPlayer,stari4ek/ExoPlayer,pajatopmr/ExoPlayer,Ood-Tsen/ExoPlayer,UIKit0/ExoPlayer,prashant31191/ExoPlayer,algrid/ExoPlayer,WeiChungChang/ExoPlayer,michalliu/ExoPlayer,amzn/exoplayer-amazon-port,sergiomartinez4/ExoPlayer,JasonFengHot/ExoPlayerSource,eriuzo/ExoPlayer,natez0r/ExoPlayer,raphanda/ExoPlayer,zhouweiguo2017/ExoPlayer,google/ExoPlayer,khj0704/ExoPlayer,Furystorm/ExoPlayer,raphanda/ExoPlayer,castlabs/ExoPlayer,danikula/ExoPlayer,TheWeatherCompany/ExoPlayer,amzn/exoplayer-amazon-port,ajrulez/ExoPlayer,0359xiaodong/ExoPlayer,ZaneSummer/ExoPlayer,superbderrick/ExoPlayer,bongole/ExoPlayer,fanhattan/ExoPlayer,ferrytanu/ExoPlayer,ClubCom/AndroidExoPlayer,hanyoungpark/ExoPlayer,Dysonics/ExoPlayer,ferrytanu/ExoPlayer,pajatopmr/ExoPlayer,JasonFengHot/ExoPlayerSource,ClubCom/AndroidExoPlayer,jeoliva/ExoPlayer,KiminRyu/ExoPlayer,MaTriXy/ExoPlayer | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer.audio;
import com.google.android.exoplayer.C;
import com.google.android.exoplayer.util.Assertions;
import com.google.android.exoplayer.util.Util;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTimestamp;
import android.media.MediaFormat;
import android.os.ConditionVariable;
import android.util.Log;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
/**
* Plays audio data. The implementation delegates to an {@link android.media.AudioTrack} and handles
* playback position smoothing, non-blocking writes and reconfiguration.
*
* <p>If {@link #isInitialized} returns {@code false}, the instance can be {@link #initialize}d.
* After initialization, start playback by calling {@link #play}.
*
* <p>Call {@link #handleBuffer} to write data for playback.
*
* <p>Call {@link #handleDiscontinuity} when a buffer is skipped.
*
* <p>Call {@link #reconfigure} when the output format changes.
*
* <p>Call {@link #reset} to free resources. It is safe to re-{@link #initialize} the instance.
*/
@TargetApi(16)
public final class AudioTrack {
/**
* Thrown when a failure occurs instantiating an {@link android.media.AudioTrack}.
*/
public static class InitializationException extends Exception {
/** The state as reported by {@link android.media.AudioTrack#getState()}. */
public final int audioTrackState;
public InitializationException(
int audioTrackState, int sampleRate, int channelConfig, int bufferSize) {
super("AudioTrack init failed: " + audioTrackState + ", Config(" + sampleRate + ", "
+ channelConfig + ", " + bufferSize + ")");
this.audioTrackState = audioTrackState;
}
}
/** Returned in the result of {@link #handleBuffer} if the buffer was discontinuous. */
public static final int RESULT_POSITION_DISCONTINUITY = 1;
/** Returned in the result of {@link #handleBuffer} if the buffer can be released. */
public static final int RESULT_BUFFER_CONSUMED = 2;
/** Represents an unset {@link android.media.AudioTrack} session identifier. */
public static final int SESSION_ID_NOT_SET = 0;
/** The default multiplication factor used when determining the size of the track's buffer. */
public static final float DEFAULT_MIN_BUFFER_MULTIPLICATION_FACTOR = 4;
/** Returned by {@link #getCurrentPositionUs} when the position is not set. */
public static final long CURRENT_POSITION_NOT_SET = Long.MIN_VALUE;
private static final String TAG = "AudioTrack";
/**
* AudioTrack timestamps are deemed spurious if they are offset from the system clock by more
* than this amount.
*
* <p>This is a fail safe that should not be required on correctly functioning devices.
*/
private static final long MAX_AUDIO_TIMESTAMP_OFFSET_US = 10 * C.MICROS_PER_SECOND;
/**
* AudioTrack latencies are deemed impossibly large if they are greater than this amount.
*
* <p>This is a fail safe that should not be required on correctly functioning devices.
*/
private static final long MAX_LATENCY_US = 10 * C.MICROS_PER_SECOND;
/** Value for ac3Bitrate before the bitrate has been calculated. */
private static final int UNKNOWN_AC3_BITRATE = 0;
private static final int START_NOT_SET = 0;
private static final int START_IN_SYNC = 1;
private static final int START_NEED_SYNC = 2;
private static final int MAX_PLAYHEAD_OFFSET_COUNT = 10;
private static final int MIN_PLAYHEAD_OFFSET_SAMPLE_INTERVAL_US = 30000;
private static final int MIN_TIMESTAMP_SAMPLE_INTERVAL_US = 500000;
private final ConditionVariable releasingConditionVariable;
private final AudioTimestampCompat audioTimestampCompat;
private final long[] playheadOffsets;
private final float minBufferMultiplicationFactor;
private android.media.AudioTrack audioTrack;
private int sampleRate;
private int channelConfig;
private int encoding;
private int frameSize;
private int minBufferSize;
private int bufferSize;
private int nextPlayheadOffsetIndex;
private int playheadOffsetCount;
private long smoothedPlayheadOffsetUs;
private long lastPlayheadSampleTimeUs;
private boolean audioTimestampSet;
private long lastTimestampSampleTimeUs;
private long lastRawPlaybackHeadPosition;
private long rawPlaybackHeadWrapCount;
private Method getLatencyMethod;
private long submittedBytes;
private int startMediaTimeState;
private long startMediaTimeUs;
private long resumeSystemTimeUs;
private long latencyUs;
private float volume;
private byte[] temporaryBuffer;
private int temporaryBufferOffset;
private int temporaryBufferSize;
private boolean isAc3;
/** Bitrate measured in kilobits per second, if {@link #isAc3} is true. */
private int ac3Bitrate;
/** Constructs an audio track using the default minimum buffer size multiplier. */
public AudioTrack() {
this(DEFAULT_MIN_BUFFER_MULTIPLICATION_FACTOR);
}
/** Constructs an audio track using the specified minimum buffer size multiplier. */
public AudioTrack(float minBufferMultiplicationFactor) {
Assertions.checkArgument(minBufferMultiplicationFactor >= 1);
this.minBufferMultiplicationFactor = minBufferMultiplicationFactor;
releasingConditionVariable = new ConditionVariable(true);
if (Util.SDK_INT >= 19) {
audioTimestampCompat = new AudioTimestampCompatV19();
} else {
audioTimestampCompat = new NoopAudioTimestampCompat();
}
if (Util.SDK_INT >= 18) {
try {
getLatencyMethod =
android.media.AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
} catch (NoSuchMethodException e) {
// There's no guarantee this method exists. Do nothing.
}
}
playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
volume = 1.0f;
startMediaTimeState = START_NOT_SET;
}
/**
* Returns whether the audio track has been successfully initialized via {@link #initialize} and
* not yet {@link #reset}.
*/
public boolean isInitialized() {
return audioTrack != null;
}
/**
* Returns the playback position in the stream starting at zero, in microseconds, or
* {@link #CURRENT_POSITION_NOT_SET} if it is not yet available.
*
* <p>If the device supports it, the method uses the playback timestamp from
* {@link android.media.AudioTrack#getTimestamp}. Otherwise, it derives a smoothed position by
* sampling the {@link android.media.AudioTrack}'s frame position.
*
* @param sourceEnded Specify {@code true} if no more input buffers will be provided.
* @return The playback position relative to the start of playback, in microseconds.
*/
public long getCurrentPositionUs(boolean sourceEnded) {
if (!hasCurrentPositionUs()) {
return CURRENT_POSITION_NOT_SET;
}
if (audioTrack.getPlayState() == android.media.AudioTrack.PLAYSTATE_PLAYING) {
maybeSampleSyncParams();
}
long systemClockUs = System.nanoTime() / 1000;
long currentPositionUs;
if (audioTimestampSet) {
// How long ago in the past the audio timestamp is (negative if it's in the future).
long presentationDiff = systemClockUs - (audioTimestampCompat.getNanoTime() / 1000);
long framesDiff = durationUsToFrames(presentationDiff);
// The position of the frame that's currently being presented.
long currentFramePosition = audioTimestampCompat.getFramePosition() + framesDiff;
currentPositionUs = framesToDurationUs(currentFramePosition) + startMediaTimeUs;
} else {
if (playheadOffsetCount == 0) {
// The AudioTrack has started, but we don't have any samples to compute a smoothed position.
currentPositionUs = getPlaybackPositionUs() + startMediaTimeUs;
} else {
// getPlayheadPositionUs() only has a granularity of ~20ms, so we base the position off the
// system clock (and a smoothed offset between it and the playhead position) so as to
// prevent jitter in the reported positions.
currentPositionUs = systemClockUs + smoothedPlayheadOffsetUs + startMediaTimeUs;
}
if (!sourceEnded) {
currentPositionUs -= latencyUs;
}
}
return currentPositionUs;
}
/**
* Initializes the audio track for writing new buffers using {@link #handleBuffer}.
*
* @return The audio track session identifier.
*/
public int initialize() throws InitializationException {
return initialize(SESSION_ID_NOT_SET);
}
/**
* Initializes the audio track for writing new buffers using {@link #handleBuffer}.
*
* @param sessionId Audio track session identifier to re-use, or {@link #SESSION_ID_NOT_SET} to
* create a new one.
* @return The new (or re-used) session identifier.
*/
public int initialize(int sessionId) throws InitializationException {
// If we're asynchronously releasing a previous audio track then we block until it has been
// released. This guarantees that we cannot end up in a state where we have multiple audio
// track instances. Without this guarantee it would be possible, in extreme cases, to exhaust
// the shared memory that's available for audio track buffers. This would in turn cause the
// initialization of the audio track to fail.
releasingConditionVariable.block();
if (sessionId == SESSION_ID_NOT_SET) {
audioTrack = new android.media.AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, encoding, bufferSize, android.media.AudioTrack.MODE_STREAM);
} else {
// Re-attach to the same audio session.
audioTrack = new android.media.AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, encoding, bufferSize, android.media.AudioTrack.MODE_STREAM, sessionId);
}
checkAudioTrackInitialized();
setVolume(volume);
return audioTrack.getAudioSessionId();
}
/**
* Reconfigures the audio track to play back media in {@code format}. The encoding is assumed to
* be {@link AudioFormat#ENCODING_PCM_16BIT}.
*/
public void reconfigure(MediaFormat format) {
reconfigure(format, AudioFormat.ENCODING_PCM_16BIT, 0);
}
/**
* Reconfigures the audio track to play back media in {@code format}. Buffers passed to
* {@link #handleBuffer} must using the specified {@code encoding}, which should be a constant
* from {@link AudioFormat}.
*
* @param format Specifies the channel count and sample rate to play back.
* @param encoding The format in which audio is represented.
* @param bufferSize The total size of the playback buffer in bytes. Specify 0 to use a buffer
* size based on the minimum for format.
*/
@SuppressLint("InlinedApi")
public void reconfigure(MediaFormat format, int encoding, int bufferSize) {
int channelCount = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
int channelConfig;
switch (channelCount) {
case 1:
channelConfig = AudioFormat.CHANNEL_OUT_MONO;
break;
case 2:
channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
break;
case 6:
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1;
break;
case 8:
channelConfig = AudioFormat.CHANNEL_OUT_7POINT1;
break;
default:
throw new IllegalArgumentException("Unsupported channel count: " + channelCount);
}
int sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
// TODO: Does channelConfig determine channelCount?
boolean isAc3 = encoding == AudioFormat.ENCODING_AC3 || encoding == AudioFormat.ENCODING_E_AC3;
if (audioTrack != null && this.sampleRate == sampleRate
&& this.channelConfig == channelConfig && !this.isAc3 && !isAc3) {
// We already have an existing audio track with the correct sample rate and channel config.
return;
}
reset();
minBufferSize = android.media.AudioTrack.getMinBufferSize(sampleRate, channelConfig, encoding);
this.encoding = encoding;
this.bufferSize =
bufferSize == 0 ? (int) (minBufferMultiplicationFactor * minBufferSize) : bufferSize;
this.sampleRate = sampleRate;
this.channelConfig = channelConfig;
this.isAc3 = isAc3;
ac3Bitrate = UNKNOWN_AC3_BITRATE; // Calculated on receiving the first buffer if isAc3 is true.
frameSize = 2 * channelCount; // 2 bytes per 16 bit sample * number of channels.
}
/** Starts/resumes playing audio if the audio track has been initialized. */
public void play() {
if (isInitialized()) {
resumeSystemTimeUs = System.nanoTime() / 1000;
audioTrack.play();
}
}
/** Signals to the audio track that the next buffer is discontinuous with the previous buffer. */
public void handleDiscontinuity() {
// Force resynchronization after a skipped buffer.
if (startMediaTimeState == START_IN_SYNC) {
startMediaTimeState = START_NEED_SYNC;
}
}
/**
* Attempts to write {@code size} bytes from {@code buffer} at {@code offset} to the audio track.
* Returns a bit field containing {@link #RESULT_BUFFER_CONSUMED} if the buffer can be released
* (due to having been written), and {@link #RESULT_POSITION_DISCONTINUITY} if the buffer was
* discontinuous with previously written data.
*
* @param buffer The buffer containing audio data to play back.
* @param offset The offset in the buffer from which to consume data.
* @param size The number of bytes to consume from {@code buffer}.
* @param presentationTimeUs Presentation timestamp of the next buffer in microseconds.
* @return A bit field with {@link #RESULT_BUFFER_CONSUMED} if the buffer can be released, and
* {@link #RESULT_POSITION_DISCONTINUITY} if the buffer was not contiguous with previously
* written data.
*/
public int handleBuffer(ByteBuffer buffer, int offset, int size, long presentationTimeUs) {
int result = 0;
if (temporaryBufferSize == 0 && size != 0) {
if (isAc3 && ac3Bitrate == UNKNOWN_AC3_BITRATE) {
// Each AC-3 buffer contains 1536 frames of audio, so the AudioTrack playback position
// advances by 1536 per buffer (32 ms at 48 kHz). Calculate the bitrate in kbit/s.
int unscaledAc3Bitrate = size * 8 * sampleRate;
int divisor = 1000 * 1536;
ac3Bitrate = (unscaledAc3Bitrate + divisor / 2) / divisor;
}
// This is the first time we've seen this {@code buffer}.
// Note: presentationTimeUs corresponds to the end of the sample, not the start.
long bufferStartTime = presentationTimeUs - framesToDurationUs(bytesToFrames(size));
if (startMediaTimeUs == START_NOT_SET) {
startMediaTimeUs = Math.max(0, bufferStartTime);
startMediaTimeState = START_IN_SYNC;
} else {
// Sanity check that bufferStartTime is consistent with the expected value.
long expectedBufferStartTime = startMediaTimeUs
+ framesToDurationUs(bytesToFrames(submittedBytes));
if (startMediaTimeState == START_IN_SYNC
&& Math.abs(expectedBufferStartTime - bufferStartTime) > 200000) {
Log.e(TAG, "Discontinuity detected [expected " + expectedBufferStartTime + ", got "
+ bufferStartTime + "]");
startMediaTimeState = START_NEED_SYNC;
}
if (startMediaTimeState == START_NEED_SYNC) {
// Adjust startMediaTimeUs to be consistent with the current buffer's start time and the
// number of bytes submitted.
startMediaTimeUs += (bufferStartTime - expectedBufferStartTime);
startMediaTimeState = START_IN_SYNC;
result = RESULT_POSITION_DISCONTINUITY;
}
}
}
if (size == 0) {
return result;
}
if (temporaryBufferSize == 0) {
temporaryBufferSize = size;
buffer.position(offset);
if (Util.SDK_INT < 21) {
// Copy {@code buffer} into {@code temporaryBuffer}.
if (temporaryBuffer == null || temporaryBuffer.length < size) {
temporaryBuffer = new byte[size];
}
buffer.get(temporaryBuffer, 0, size);
temporaryBufferOffset = 0;
}
}
int bytesWritten = 0;
if (Util.SDK_INT < 21) {
// Work out how many bytes we can write without the risk of blocking.
int bytesPending = (int) (submittedBytes - framesToBytes(getPlaybackPositionFrames()));
int bytesToWrite = bufferSize - bytesPending;
if (bytesToWrite > 0) {
bytesToWrite = Math.min(temporaryBufferSize, bytesToWrite);
bytesWritten = audioTrack.write(temporaryBuffer, temporaryBufferOffset, bytesToWrite);
if (bytesWritten < 0) {
Log.w(TAG, "AudioTrack.write returned error code: " + bytesWritten);
} else {
temporaryBufferOffset += bytesWritten;
}
}
} else {
bytesWritten = writeNonBlockingV21(audioTrack, buffer, temporaryBufferSize);
}
temporaryBufferSize -= bytesWritten;
submittedBytes += bytesWritten;
if (temporaryBufferSize == 0) {
result |= RESULT_BUFFER_CONSUMED;
}
return result;
}
@TargetApi(21)
private static int writeNonBlockingV21(
android.media.AudioTrack audioTrack, ByteBuffer buffer, int size) {
return audioTrack.write(buffer, size, android.media.AudioTrack.WRITE_NON_BLOCKING);
}
/** Returns whether the audio track has more data pending that will be played back. */
public boolean hasPendingData() {
return audioTrack != null && bytesToFrames(submittedBytes) > getPlaybackPositionFrames();
}
/** Returns whether enough data has been supplied via {@link #handleBuffer} to begin playback. */
public boolean hasEnoughDataToBeginPlayback() {
return submittedBytes >= minBufferSize;
}
/** Sets the playback volume. */
public void setVolume(float volume) {
this.volume = volume;
if (audioTrack != null) {
if (Util.SDK_INT >= 21) {
setVolumeV21(audioTrack, volume);
} else {
setVolumeV3(audioTrack, volume);
}
}
}
@TargetApi(21)
private static void setVolumeV21(android.media.AudioTrack audioTrack, float volume) {
audioTrack.setVolume(volume);
}
@SuppressWarnings("deprecation")
private static void setVolumeV3(android.media.AudioTrack audioTrack, float volume) {
audioTrack.setStereoVolume(volume, volume);
}
/** Pauses playback. */
public void pause() {
if (audioTrack != null) {
resetSyncParams();
audioTrack.pause();
}
}
/**
* Releases resources associated with this instance asynchronously. Calling {@link #initialize}
* will block until the audio track has been released, so it is safe to initialize immediately
* after resetting.
*/
public void reset() {
if (audioTrack != null) {
submittedBytes = 0;
temporaryBufferSize = 0;
lastRawPlaybackHeadPosition = 0;
rawPlaybackHeadWrapCount = 0;
startMediaTimeUs = START_NOT_SET;
resetSyncParams();
int playState = audioTrack.getPlayState();
if (playState == android.media.AudioTrack.PLAYSTATE_PLAYING) {
audioTrack.pause();
}
// AudioTrack.release can take some time, so we call it on a background thread.
final android.media.AudioTrack toRelease = audioTrack;
audioTrack = null;
releasingConditionVariable.close();
new Thread() {
@Override
public void run() {
try {
toRelease.release();
} finally {
releasingConditionVariable.open();
}
}
}.start();
}
}
/** Returns whether {@link #getCurrentPositionUs} can return the current playback position. */
private boolean hasCurrentPositionUs() {
return isInitialized() && startMediaTimeUs != START_NOT_SET;
}
/** Updates the audio track latency and playback position parameters. */
private void maybeSampleSyncParams() {
long playbackPositionUs = getPlaybackPositionUs();
if (playbackPositionUs == 0) {
// The AudioTrack hasn't output anything yet.
return;
}
long systemClockUs = System.nanoTime() / 1000;
if (systemClockUs - lastPlayheadSampleTimeUs >= MIN_PLAYHEAD_OFFSET_SAMPLE_INTERVAL_US) {
// Take a new sample and update the smoothed offset between the system clock and the playhead.
playheadOffsets[nextPlayheadOffsetIndex] = playbackPositionUs - systemClockUs;
nextPlayheadOffsetIndex = (nextPlayheadOffsetIndex + 1) % MAX_PLAYHEAD_OFFSET_COUNT;
if (playheadOffsetCount < MAX_PLAYHEAD_OFFSET_COUNT) {
playheadOffsetCount++;
}
lastPlayheadSampleTimeUs = systemClockUs;
smoothedPlayheadOffsetUs = 0;
for (int i = 0; i < playheadOffsetCount; i++) {
smoothedPlayheadOffsetUs += playheadOffsets[i] / playheadOffsetCount;
}
}
if (systemClockUs - lastTimestampSampleTimeUs >= MIN_TIMESTAMP_SAMPLE_INTERVAL_US) {
audioTimestampSet = audioTimestampCompat.update(audioTrack);
if (audioTimestampSet) {
// Perform sanity checks on the timestamp.
long audioTimestampUs = audioTimestampCompat.getNanoTime() / 1000;
if (audioTimestampUs < resumeSystemTimeUs) {
// The timestamp corresponds to a time before the track was most recently resumed.
audioTimestampSet = false;
} else if (Math.abs(audioTimestampUs - systemClockUs) > MAX_AUDIO_TIMESTAMP_OFFSET_US) {
// The timestamp time base is probably wrong.
audioTimestampSet = false;
Log.w(TAG, "Spurious audio timestamp: " + audioTimestampCompat.getFramePosition() + ", "
+ audioTimestampUs + ", " + systemClockUs);
}
}
if (getLatencyMethod != null) {
try {
// Compute the audio track latency, excluding the latency due to the buffer (leaving
// latency due to the mixer and audio hardware driver).
latencyUs = (Integer) getLatencyMethod.invoke(audioTrack, (Object[]) null) * 1000L
- framesToDurationUs(bytesToFrames(bufferSize));
// Sanity check that the latency is non-negative.
latencyUs = Math.max(latencyUs, 0);
// Sanity check that the latency isn't too large.
if (latencyUs > MAX_LATENCY_US) {
Log.w(TAG, "Ignoring impossibly large audio latency: " + latencyUs);
latencyUs = 0;
}
} catch (Exception e) {
// The method existed, but doesn't work. Don't try again.
getLatencyMethod = null;
}
}
lastTimestampSampleTimeUs = systemClockUs;
}
}
/**
* Checks that {@link #audioTrack} has been successfully initialized. If it has then calling this
* method is a no-op. If it hasn't then {@link #audioTrack} is released and set to null, and an
* exception is thrown.
*
* @throws InitializationException If {@link #audioTrack} has not been successfully initialized.
*/
private void checkAudioTrackInitialized() throws InitializationException {
int state = audioTrack.getState();
if (state == android.media.AudioTrack.STATE_INITIALIZED) {
return;
}
// The track is not successfully initialized. Release and null the track.
try {
audioTrack.release();
} catch (Exception e) {
// The track has already failed to initialize, so it wouldn't be that surprising if release
// were to fail too. Swallow the exception.
} finally {
audioTrack = null;
}
throw new InitializationException(state, sampleRate, channelConfig, bufferSize);
}
/**
* {@link android.media.AudioTrack#getPlaybackHeadPosition()} returns a value intended to be
* interpreted as an unsigned 32 bit integer, which also wraps around periodically. This method
* returns the playback head position as a long that will only wrap around if the value exceeds
* {@link Long#MAX_VALUE} (which in practice will never happen).
*
* @return {@link android.media.AudioTrack#getPlaybackHeadPosition()} of {@link #audioTrack}
* expressed as a long.
*/
private long getPlaybackPositionFrames() {
long rawPlaybackHeadPosition = 0xFFFFFFFFL & audioTrack.getPlaybackHeadPosition();
if (lastRawPlaybackHeadPosition > rawPlaybackHeadPosition) {
// The value must have wrapped around.
rawPlaybackHeadWrapCount++;
}
lastRawPlaybackHeadPosition = rawPlaybackHeadPosition;
return rawPlaybackHeadPosition + (rawPlaybackHeadWrapCount << 32);
}
private long getPlaybackPositionUs() {
return framesToDurationUs(getPlaybackPositionFrames());
}
private long framesToBytes(long frameCount) {
// This method is unused on SDK >= 21.
return frameCount * frameSize;
}
private long bytesToFrames(long byteCount) {
if (isAc3) {
return
ac3Bitrate == UNKNOWN_AC3_BITRATE ? 0L : byteCount * 8 * sampleRate / (1000 * ac3Bitrate);
} else {
return byteCount / frameSize;
}
}
private long framesToDurationUs(long frameCount) {
return (frameCount * C.MICROS_PER_SECOND) / sampleRate;
}
private long durationUsToFrames(long durationUs) {
return (durationUs * sampleRate) / C.MICROS_PER_SECOND;
}
private void resetSyncParams() {
smoothedPlayheadOffsetUs = 0;
playheadOffsetCount = 0;
nextPlayheadOffsetIndex = 0;
lastPlayheadSampleTimeUs = 0;
audioTimestampSet = false;
lastTimestampSampleTimeUs = 0;
}
/**
* Interface exposing the {@link android.media.AudioTimestamp} methods we need that were added in
* SDK 19.
*/
private interface AudioTimestampCompat {
/**
* Returns true if the audioTimestamp was retrieved from the audioTrack.
*/
boolean update(android.media.AudioTrack audioTrack);
long getNanoTime();
long getFramePosition();
}
/**
* The AudioTimestampCompat implementation for SDK < 19 that does nothing or throws an exception.
*/
private static final class NoopAudioTimestampCompat implements AudioTimestampCompat {
@Override
public boolean update(android.media.AudioTrack audioTrack) {
return false;
}
@Override
public long getNanoTime() {
// Should never be called if initTimestamp() returned false.
throw new UnsupportedOperationException();
}
@Override
public long getFramePosition() {
// Should never be called if initTimestamp() returned false.
throw new UnsupportedOperationException();
}
}
/**
* The AudioTimestampCompat implementation for SDK >= 19 that simply calls through to the actual
* implementations added in SDK 19.
*/
@TargetApi(19)
private static final class AudioTimestampCompatV19 implements AudioTimestampCompat {
private final AudioTimestamp audioTimestamp;
public AudioTimestampCompatV19() {
audioTimestamp = new AudioTimestamp();
}
@Override
public boolean update(android.media.AudioTrack audioTrack) {
return audioTrack.getTimestamp(audioTimestamp);
}
@Override
public long getNanoTime() {
return audioTimestamp.nanoTime;
}
@Override
public long getFramePosition() {
return audioTimestamp.framePosition;
}
}
}
| library/src/main/java/com/google/android/exoplayer/audio/AudioTrack.java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer.audio;
import com.google.android.exoplayer.C;
import com.google.android.exoplayer.util.Assertions;
import com.google.android.exoplayer.util.Util;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTimestamp;
import android.media.MediaFormat;
import android.os.ConditionVariable;
import android.util.Log;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
/**
* Plays audio data. The implementation delegates to an {@link android.media.AudioTrack} and handles
* playback position smoothing, non-blocking writes and reconfiguration.
*
* <p>If {@link #isInitialized} returns {@code false}, the instance can be {@link #initialize}d.
* After initialization, start playback by calling {@link #play}.
*
* <p>Call {@link #handleBuffer} to write data for playback.
*
* <p>Call {@link #handleDiscontinuity} when a buffer is skipped.
*
* <p>Call {@link #reconfigure} when the output format changes.
*
* <p>Call {@link #reset} to free resources. It is safe to re-{@link #initialize} the instance.
*/
@TargetApi(16)
public final class AudioTrack {
/**
* Thrown when a failure occurs instantiating an {@link android.media.AudioTrack}.
*/
public static class InitializationException extends Exception {
/** The state as reported by {@link android.media.AudioTrack#getState()}. */
public final int audioTrackState;
public InitializationException(
int audioTrackState, int sampleRate, int channelConfig, int bufferSize) {
super("AudioTrack init failed: " + audioTrackState + ", Config(" + sampleRate + ", "
+ channelConfig + ", " + bufferSize + ")");
this.audioTrackState = audioTrackState;
}
}
/** Returned in the result of {@link #handleBuffer} if the buffer was discontinuous. */
public static final int RESULT_POSITION_DISCONTINUITY = 1;
/** Returned in the result of {@link #handleBuffer} if the buffer can be released. */
public static final int RESULT_BUFFER_CONSUMED = 2;
/** Represents an unset {@link android.media.AudioTrack} session identifier. */
public static final int SESSION_ID_NOT_SET = 0;
/** The default multiplication factor used when determining the size of the track's buffer. */
public static final float DEFAULT_MIN_BUFFER_MULTIPLICATION_FACTOR = 4;
/** Returned by {@link #getCurrentPositionUs} when the position is not set. */
public static final long CURRENT_POSITION_NOT_SET = Long.MIN_VALUE;
private static final String TAG = "AudioTrack";
/**
* AudioTrack timestamps are deemed spurious if they are offset from the system clock by more
* than this amount.
*
* <p>This is a fail safe that should not be required on correctly functioning devices.
*/
private static final long MAX_AUDIO_TIMESTAMP_OFFSET_US = 10 * C.MICROS_PER_SECOND;
/**
* AudioTrack latencies are deemed impossibly large if they are greater than this amount.
*
* <p>This is a fail safe that should not be required on correctly functioning devices.
*/
private static final long MAX_LATENCY_US = 10 * C.MICROS_PER_SECOND;
/** Value for ac3Bitrate before the bitrate has been calculated. */
private static final int UNKNOWN_AC3_BITRATE = 0;
private static final int START_NOT_SET = 0;
private static final int START_IN_SYNC = 1;
private static final int START_NEED_SYNC = 2;
private static final int MAX_PLAYHEAD_OFFSET_COUNT = 10;
private static final int MIN_PLAYHEAD_OFFSET_SAMPLE_INTERVAL_US = 30000;
private static final int MIN_TIMESTAMP_SAMPLE_INTERVAL_US = 500000;
private final ConditionVariable releasingConditionVariable;
private final AudioTimestampCompat audioTimestampCompat;
private final long[] playheadOffsets;
private final float minBufferMultiplicationFactor;
private android.media.AudioTrack audioTrack;
private int sampleRate;
private int channelConfig;
private int encoding;
private int frameSize;
private int minBufferSize;
private int bufferSize;
private int nextPlayheadOffsetIndex;
private int playheadOffsetCount;
private long smoothedPlayheadOffsetUs;
private long lastPlayheadSampleTimeUs;
private boolean audioTimestampSet;
private long lastTimestampSampleTimeUs;
private long lastRawPlaybackHeadPosition;
private long rawPlaybackHeadWrapCount;
private Method getLatencyMethod;
private long submittedBytes;
private int startMediaTimeState;
private long startMediaTimeUs;
private long resumeSystemTimeUs;
private long latencyUs;
private float volume;
private byte[] temporaryBuffer;
private int temporaryBufferOffset;
private int temporaryBufferSize;
private boolean isAc3;
/** Bitrate measured in kilobits per second, if {@link #isAc3} is true. */
private int ac3Bitrate;
/** Constructs an audio track using the default minimum buffer size multiplier. */
public AudioTrack() {
this(DEFAULT_MIN_BUFFER_MULTIPLICATION_FACTOR);
}
/** Constructs an audio track using the specified minimum buffer size multiplier. */
public AudioTrack(float minBufferMultiplicationFactor) {
Assertions.checkArgument(minBufferMultiplicationFactor >= 1);
this.minBufferMultiplicationFactor = minBufferMultiplicationFactor;
releasingConditionVariable = new ConditionVariable(true);
if (Util.SDK_INT >= 19) {
audioTimestampCompat = new AudioTimestampCompatV19();
} else {
audioTimestampCompat = new NoopAudioTimestampCompat();
}
if (Util.SDK_INT >= 18) {
try {
getLatencyMethod =
android.media.AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
} catch (NoSuchMethodException e) {
// There's no guarantee this method exists. Do nothing.
}
}
playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT];
volume = 1.0f;
startMediaTimeState = START_NOT_SET;
}
/**
* Returns whether the audio track has been successfully initialized via {@link #initialize} and
* not yet {@link #reset}.
*/
public boolean isInitialized() {
return audioTrack != null;
}
/**
* Returns the playback position in the stream starting at zero, in microseconds, or
* {@link #CURRENT_POSITION_NOT_SET} if it is not yet available.
*
* <p>If the device supports it, the method uses the playback timestamp from
* {@link android.media.AudioTrack#getTimestamp}. Otherwise, it derives a smoothed position by
* sampling the {@link android.media.AudioTrack}'s frame position.
*
* @param sourceEnded Specify {@code true} if no more input buffers will be provided.
* @return The playback position relative to the start of playback, in microseconds.
*/
public long getCurrentPositionUs(boolean sourceEnded) {
if (!hasCurrentPositionUs()) {
return CURRENT_POSITION_NOT_SET;
}
if (audioTrack.getPlayState() == android.media.AudioTrack.PLAYSTATE_PLAYING) {
maybeSampleSyncParams();
}
long systemClockUs = System.nanoTime() / 1000;
long currentPositionUs;
if (audioTimestampSet) {
// How long ago in the past the audio timestamp is (negative if it's in the future).
long presentationDiff = systemClockUs - (audioTimestampCompat.getNanoTime() / 1000);
long framesDiff = durationUsToFrames(presentationDiff);
// The position of the frame that's currently being presented.
long currentFramePosition = audioTimestampCompat.getFramePosition() + framesDiff;
currentPositionUs = framesToDurationUs(currentFramePosition) + startMediaTimeUs;
} else {
if (playheadOffsetCount == 0) {
// The AudioTrack has started, but we don't have any samples to compute a smoothed position.
currentPositionUs = getPlaybackPositionUs() + startMediaTimeUs;
} else {
// getPlayheadPositionUs() only has a granularity of ~20ms, so we base the position off the
// system clock (and a smoothed offset between it and the playhead position) so as to
// prevent jitter in the reported positions.
currentPositionUs = systemClockUs + smoothedPlayheadOffsetUs + startMediaTimeUs;
}
if (!sourceEnded) {
currentPositionUs -= latencyUs;
}
}
return currentPositionUs;
}
/**
* Initializes the audio track for writing new buffers using {@link #handleBuffer}.
*
* @return The audio track session identifier.
*/
public int initialize() throws InitializationException {
return initialize(SESSION_ID_NOT_SET);
}
/**
* Initializes the audio track for writing new buffers using {@link #handleBuffer}.
*
* @param sessionId Audio track session identifier to re-use, or {@link #SESSION_ID_NOT_SET} to
* create a new one.
* @return The new (or re-used) session identifier.
*/
public int initialize(int sessionId) throws InitializationException {
// If we're asynchronously releasing a previous audio track then we block until it has been
// released. This guarantees that we cannot end up in a state where we have multiple audio
// track instances. Without this guarantee it would be possible, in extreme cases, to exhaust
// the shared memory that's available for audio track buffers. This would in turn cause the
// initialization of the audio track to fail.
releasingConditionVariable.block();
if (sessionId == SESSION_ID_NOT_SET) {
audioTrack = new android.media.AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, encoding, bufferSize, android.media.AudioTrack.MODE_STREAM);
} else {
// Re-attach to the same audio session.
audioTrack = new android.media.AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, encoding, bufferSize, android.media.AudioTrack.MODE_STREAM, sessionId);
}
checkAudioTrackInitialized();
setVolume(volume);
return audioTrack.getAudioSessionId();
}
/**
* Reconfigures the audio track to play back media in {@code format}. The encoding is assumed to
* be {@link AudioFormat#ENCODING_PCM_16BIT}.
*/
public void reconfigure(MediaFormat format) {
reconfigure(format, AudioFormat.ENCODING_PCM_16BIT, 0);
}
/**
* Reconfigures the audio track to play back media in {@code format}. Buffers passed to
* {@link #handleBuffer} must using the specified {@code encoding}, which should be a constant
* from {@link AudioFormat}.
*
* @param format Specifies the channel count and sample rate to play back.
* @param encoding The format in which audio is represented.
* @param bufferSize The total size of the playback buffer in bytes. Specify 0 to use a buffer
* size based on the minimum for format.
*/
@SuppressLint("InlinedApi")
public void reconfigure(MediaFormat format, int encoding, int bufferSize) {
int channelCount = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
int channelConfig;
switch (channelCount) {
case 1:
channelConfig = AudioFormat.CHANNEL_OUT_MONO;
break;
case 2:
channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
break;
case 6:
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1;
break;
case 8:
channelConfig = AudioFormat.CHANNEL_OUT_7POINT1;
break;
default:
throw new IllegalArgumentException("Unsupported channel count: " + channelCount);
}
int sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
// TODO: Does channelConfig determine channelCount?
boolean isAc3 = encoding == AudioFormat.ENCODING_AC3 || encoding == AudioFormat.ENCODING_E_AC3;
if (audioTrack != null && this.sampleRate == sampleRate
&& this.channelConfig == channelConfig && !this.isAc3 && !isAc3) {
// We already have an existing audio track with the correct sample rate and channel config.
return;
}
reset();
minBufferSize = android.media.AudioTrack.getMinBufferSize(sampleRate, channelConfig, encoding);
this.encoding = encoding;
this.bufferSize =
bufferSize == 0 ? (int) (minBufferMultiplicationFactor * minBufferSize) : bufferSize;
this.sampleRate = sampleRate;
this.channelConfig = channelConfig;
this.isAc3 = isAc3;
ac3Bitrate = UNKNOWN_AC3_BITRATE; // Calculated on receiving the first buffer if isAc3 is true.
frameSize = 2 * channelCount; // 2 bytes per 16 bit sample * number of channels.
}
/** Starts/resumes playing audio if the audio track has been initialized. */
public void play() {
if (isInitialized()) {
resumeSystemTimeUs = System.nanoTime() / 1000;
audioTrack.play();
}
}
/** Signals to the audio track that the next buffer is discontinuous with the previous buffer. */
public void handleDiscontinuity() {
// Force resynchronization after a skipped buffer.
if (startMediaTimeState == START_IN_SYNC) {
startMediaTimeState = START_NEED_SYNC;
}
}
/**
* Attempts to write {@code size} bytes from {@code buffer} at {@code offset} to the audio track.
* Returns a bit field containing {@link #RESULT_BUFFER_CONSUMED} if the buffer can be released
* (due to having been written), and {@link #RESULT_POSITION_DISCONTINUITY} if the buffer was
* discontinuous with previously written data.
*
* @param buffer The buffer containing audio data to play back.
* @param offset The offset in the buffer from which to consume data.
* @param size The number of bytes to consume from {@code buffer}.
* @param presentationTimeUs Presentation timestamp of the next buffer in microseconds.
* @return A bit field with {@link #RESULT_BUFFER_CONSUMED} if the buffer can be released, and
* {@link #RESULT_POSITION_DISCONTINUITY} if the buffer was not contiguous with previously
* written data.
*/
public int handleBuffer(ByteBuffer buffer, int offset, int size, long presentationTimeUs) {
int result = 0;
if (temporaryBufferSize == 0 && size != 0) {
if (isAc3 && ac3Bitrate == UNKNOWN_AC3_BITRATE) {
// Each AC-3 buffer contains 1536 frames of audio, so the AudioTrack playback position
// advances by 1536 per buffer (32 ms at 48 kHz). Calculate the bitrate in kbit/s.
int unscaledAc3Bitrate = size * 8 * sampleRate;
int divisor = 1000 * 1536;
ac3Bitrate = (unscaledAc3Bitrate + divisor / 2) / divisor;
}
// This is the first time we've seen this {@code buffer}.
// Note: presentationTimeUs corresponds to the end of the sample, not the start.
long bufferStartTime = presentationTimeUs - framesToDurationUs(bytesToFrames(size));
if (startMediaTimeUs == START_NOT_SET) {
startMediaTimeUs = Math.max(0, bufferStartTime);
startMediaTimeState = START_IN_SYNC;
} else {
// Sanity check that bufferStartTime is consistent with the expected value.
long expectedBufferStartTime = startMediaTimeUs
+ framesToDurationUs(bytesToFrames(submittedBytes));
if (startMediaTimeState == START_IN_SYNC
&& Math.abs(expectedBufferStartTime - bufferStartTime) > 200000) {
Log.e(TAG, "Discontinuity detected [expected " + expectedBufferStartTime + ", got "
+ bufferStartTime + "]");
startMediaTimeState = START_NEED_SYNC;
}
if (startMediaTimeState == START_NEED_SYNC) {
// Adjust startMediaTimeUs to be consistent with the current buffer's start time and the
// number of bytes submitted.
startMediaTimeUs += (bufferStartTime - expectedBufferStartTime);
startMediaTimeState = START_IN_SYNC;
result = RESULT_POSITION_DISCONTINUITY;
}
}
}
if (size == 0) {
return result;
}
if (temporaryBufferSize == 0) {
temporaryBufferSize = size;
buffer.position(offset);
if (Util.SDK_INT < 21) {
// Copy {@code buffer} into {@code temporaryBuffer}.
if (temporaryBuffer == null || temporaryBuffer.length < size) {
temporaryBuffer = new byte[size];
}
buffer.get(temporaryBuffer, 0, size);
temporaryBufferOffset = 0;
}
}
int bytesWritten = 0;
if (Util.SDK_INT < 21) {
// Work out how many bytes we can write without the risk of blocking.
int bytesPending = (int) (submittedBytes - framesToBytes(getPlaybackPositionFrames()));
int bytesToWrite = bufferSize - bytesPending;
if (bytesToWrite > 0) {
bytesToWrite = Math.min(temporaryBufferSize, bytesToWrite);
bytesWritten = audioTrack.write(temporaryBuffer, temporaryBufferOffset, bytesToWrite);
if (bytesWritten < 0) {
Log.w(TAG, "AudioTrack.write returned error code: " + bytesWritten);
} else {
temporaryBufferOffset += bytesWritten;
}
}
} else {
bytesWritten = writeNonBlockingV21(audioTrack, buffer, temporaryBufferSize);
}
temporaryBufferSize -= bytesWritten;
submittedBytes += bytesWritten;
if (temporaryBufferSize == 0) {
result |= RESULT_BUFFER_CONSUMED;
}
return result;
}
@TargetApi(21)
private static int writeNonBlockingV21(
android.media.AudioTrack audioTrack, ByteBuffer buffer, int size) {
return audioTrack.write(buffer, size, android.media.AudioTrack.WRITE_NON_BLOCKING);
}
/** Returns whether the audio track has more data pending that will be played back. */
public boolean hasPendingData() {
return audioTrack != null && bytesToFrames(submittedBytes) > getPlaybackPositionFrames();
}
/** Returns whether enough data has been supplied via {@link #handleBuffer} to begin playback. */
public boolean hasEnoughDataToBeginPlayback() {
return submittedBytes >= minBufferSize;
}
/** Sets the playback volume. */
public void setVolume(float volume) {
this.volume = volume;
if (audioTrack != null) {
if (Util.SDK_INT >= 21) {
setVolumeV21(audioTrack, volume);
} else {
setVolumeV3(audioTrack, volume);
}
}
}
@TargetApi(21)
private static void setVolumeV21(android.media.AudioTrack audioTrack, float volume) {
audioTrack.setVolume(volume);
}
@SuppressWarnings("deprecation")
private static void setVolumeV3(android.media.AudioTrack audioTrack, float volume) {
audioTrack.setStereoVolume(volume, volume);
}
/** Pauses playback. */
public void pause() {
if (audioTrack != null) {
resetSyncParams();
audioTrack.pause();
}
}
/**
* Releases resources associated with this instance asynchronously. Calling {@link #initialize}
* will block until the audio track has been released, so it is safe to initialize immediately
* after resetting.
*/
public void reset() {
if (audioTrack != null) {
submittedBytes = 0;
temporaryBufferSize = 0;
lastRawPlaybackHeadPosition = 0;
rawPlaybackHeadWrapCount = 0;
startMediaTimeUs = START_NOT_SET;
resetSyncParams();
int playState = audioTrack.getPlayState();
if (playState == android.media.AudioTrack.PLAYSTATE_PLAYING) {
audioTrack.pause();
}
// AudioTrack.release can take some time, so we call it on a background thread.
final android.media.AudioTrack toRelease = audioTrack;
audioTrack = null;
releasingConditionVariable.close();
new Thread() {
@Override
public void run() {
try {
toRelease.release();
} finally {
releasingConditionVariable.open();
}
}
}.start();
}
}
/** Returns whether {@link #getCurrentPositionUs} can return the current playback position. */
private boolean hasCurrentPositionUs() {
return isInitialized() && startMediaTimeUs != START_NOT_SET;
}
/** Updates the audio track latency and playback position parameters. */
private void maybeSampleSyncParams() {
long playbackPositionUs = getPlaybackPositionUs();
if (playbackPositionUs == 0) {
// The AudioTrack hasn't output anything yet.
return;
}
long systemClockUs = System.nanoTime() / 1000;
if (systemClockUs - lastPlayheadSampleTimeUs >= MIN_PLAYHEAD_OFFSET_SAMPLE_INTERVAL_US) {
// Take a new sample and update the smoothed offset between the system clock and the playhead.
playheadOffsets[nextPlayheadOffsetIndex] = playbackPositionUs - systemClockUs;
nextPlayheadOffsetIndex = (nextPlayheadOffsetIndex + 1) % MAX_PLAYHEAD_OFFSET_COUNT;
if (playheadOffsetCount < MAX_PLAYHEAD_OFFSET_COUNT) {
playheadOffsetCount++;
}
lastPlayheadSampleTimeUs = systemClockUs;
smoothedPlayheadOffsetUs = 0;
for (int i = 0; i < playheadOffsetCount; i++) {
smoothedPlayheadOffsetUs += playheadOffsets[i] / playheadOffsetCount;
}
}
if (systemClockUs - lastTimestampSampleTimeUs >= MIN_TIMESTAMP_SAMPLE_INTERVAL_US) {
audioTimestampSet = audioTimestampCompat.update(audioTrack);
if (audioTimestampSet) {
// Perform sanity checks on the timestamp.
long audioTimestampUs = audioTimestampCompat.getNanoTime() / 1000;
if (audioTimestampUs < resumeSystemTimeUs) {
// The timestamp corresponds to a time before the track was most recently resumed.
audioTimestampSet = false;
} else if (Math.abs(audioTimestampUs - systemClockUs) > MAX_AUDIO_TIMESTAMP_OFFSET_US) {
// The timestamp time base is probably wrong.
audioTimestampSet = false;
Log.w(TAG, "Spurious audio timestamp: " + audioTimestampCompat.getFramePosition() + ", "
+ audioTimestampUs + ", " + systemClockUs);
}
}
if (getLatencyMethod != null) {
try {
// Compute the audio track latency, excluding the latency due to the buffer (leaving
// latency due to the mixer and audio hardware driver).
latencyUs = (Integer) getLatencyMethod.invoke(audioTrack, (Object[]) null) * 1000L
- framesToDurationUs(bytesToFrames(bufferSize));
// Sanity check that the latency is non-negative.
latencyUs = Math.max(latencyUs, 0);
// Sanity check that the latency isn't too large.
if (latencyUs > MAX_LATENCY_US) {
Log.w(TAG, "Ignoring impossibly large audio latency: " + latencyUs);
latencyUs = 0;
}
} catch (Exception e) {
// The method existed, but doesn't work. Don't try again.
getLatencyMethod = null;
}
}
lastTimestampSampleTimeUs = systemClockUs;
}
}
/**
* Checks that {@link #audioTrack} has been successfully initialized. If it has then calling this
* method is a no-op. If it hasn't then {@link #audioTrack} is released and set to null, and an
* exception is thrown.
*
* @throws InitializationException If {@link #audioTrack} has not been successfully initialized.
*/
private void checkAudioTrackInitialized() throws InitializationException {
int state = audioTrack.getState();
if (state == android.media.AudioTrack.STATE_INITIALIZED) {
return;
}
// The track is not successfully initialized. Release and null the track.
try {
audioTrack.release();
} catch (Exception e) {
// The track has already failed to initialize, so it wouldn't be that surprising if release
// were to fail too. Swallow the exception.
} finally {
audioTrack = null;
}
throw new InitializationException(state, sampleRate, channelConfig, bufferSize);
}
/**
* {@link android.media.AudioTrack#getPlaybackHeadPosition()} returns a value intended to be
* interpreted as an unsigned 32 bit integer, which also wraps around periodically. This method
* returns the playback head position as a long that will only wrap around if the value exceeds
* {@link Long#MAX_VALUE} (which in practice will never happen).
*
* @return {@link android.media.AudioTrack#getPlaybackHeadPosition()} of {@link #audioTrack}
* expressed as a long.
*/
private long getPlaybackPositionFrames() {
long rawPlaybackHeadPosition = 0xFFFFFFFFL & audioTrack.getPlaybackHeadPosition();
if (lastRawPlaybackHeadPosition > rawPlaybackHeadPosition) {
// The value must have wrapped around.
rawPlaybackHeadWrapCount++;
}
lastRawPlaybackHeadPosition = rawPlaybackHeadPosition;
return rawPlaybackHeadPosition + (rawPlaybackHeadWrapCount << 32);
}
private long getPlaybackPositionUs() {
return framesToDurationUs(getPlaybackPositionFrames());
}
private long framesToBytes(long frameCount) {
// This method is unused on SDK >= 21.
return frameCount * frameSize;
}
private long bytesToFrames(long byteCount) {
if (isAc3) {
return byteCount * 8 * sampleRate / (1000 * ac3Bitrate);
} else {
return byteCount / frameSize;
}
}
private long framesToDurationUs(long frameCount) {
return (frameCount * C.MICROS_PER_SECOND) / sampleRate;
}
private long durationUsToFrames(long durationUs) {
return (durationUs * sampleRate) / C.MICROS_PER_SECOND;
}
private void resetSyncParams() {
smoothedPlayheadOffsetUs = 0;
playheadOffsetCount = 0;
nextPlayheadOffsetIndex = 0;
lastPlayheadSampleTimeUs = 0;
audioTimestampSet = false;
lastTimestampSampleTimeUs = 0;
}
/**
* Interface exposing the {@link android.media.AudioTimestamp} methods we need that were added in
* SDK 19.
*/
private interface AudioTimestampCompat {
/**
* Returns true if the audioTimestamp was retrieved from the audioTrack.
*/
boolean update(android.media.AudioTrack audioTrack);
long getNanoTime();
long getFramePosition();
}
/**
* The AudioTimestampCompat implementation for SDK < 19 that does nothing or throws an exception.
*/
private static final class NoopAudioTimestampCompat implements AudioTimestampCompat {
@Override
public boolean update(android.media.AudioTrack audioTrack) {
return false;
}
@Override
public long getNanoTime() {
// Should never be called if initTimestamp() returned false.
throw new UnsupportedOperationException();
}
@Override
public long getFramePosition() {
// Should never be called if initTimestamp() returned false.
throw new UnsupportedOperationException();
}
}
/**
* The AudioTimestampCompat implementation for SDK >= 19 that simply calls through to the actual
* implementations added in SDK 19.
*/
@TargetApi(19)
private static final class AudioTimestampCompatV19 implements AudioTimestampCompat {
private final AudioTimestamp audioTimestamp;
public AudioTimestampCompatV19() {
audioTimestamp = new AudioTimestamp();
}
@Override
public boolean update(android.media.AudioTrack audioTrack) {
return audioTrack.getTimestamp(audioTimestamp);
}
@Override
public long getNanoTime() {
return audioTimestamp.nanoTime;
}
@Override
public long getFramePosition() {
return audioTimestamp.framePosition;
}
}
}
| Handle getting the audio track's position before the first AC-3 buffer.
ac3Bitrate is set only after the first buffer is handled, which meant that
getting the playback position would cause a divide by zero before then.
When playing back AC-3 content, the ac3Bitrate will always be set after the
first buffer is handled, so return a 0 position if it is not set.
| library/src/main/java/com/google/android/exoplayer/audio/AudioTrack.java | Handle getting the audio track's position before the first AC-3 buffer. | <ide><path>ibrary/src/main/java/com/google/android/exoplayer/audio/AudioTrack.java
<ide>
<ide> private long bytesToFrames(long byteCount) {
<ide> if (isAc3) {
<del> return byteCount * 8 * sampleRate / (1000 * ac3Bitrate);
<add> return
<add> ac3Bitrate == UNKNOWN_AC3_BITRATE ? 0L : byteCount * 8 * sampleRate / (1000 * ac3Bitrate);
<ide> } else {
<ide> return byteCount / frameSize;
<ide> } |
|
Java | mit | 794d5873edf4d5cbbbb80a590539527e22270471 | 0 | Brian-Wuest/MC-Prefab | package com.wuest.prefab.Structures.Config;
import com.wuest.prefab.Structures.Items.StructureItem;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.server.ServerWorld;
/**
* This is the base configuration class used by all structures.
*
* @author WuestMan
*/
@SuppressWarnings("WeakerAccess")
public class StructureConfiguration {
public static String houseFacingName = "House Facing";
private static String hitXTag = "hitX";
private static String hitYTag = "hitY";
private static String hitZTag = "hitZ";
private static String houseFacingTag = "wareHouseFacing";
/**
* The structure facing property.
*/
public Direction houseFacing;
/**
* The position of the structure.
*/
public BlockPos pos;
/**
* Initializes a new instance of the StructureConfiguration class.
*/
public StructureConfiguration() {
this.Initialize();
}
/**
* Initializes any properties for this class.
*/
public void Initialize() {
this.houseFacing = Direction.NORTH;
}
/**
* Writes the properties to an CompoundNBT.
*
* @return An CompoundNBT with the updated properties.
*/
public CompoundNBT WriteToCompoundNBT() {
CompoundNBT tag = new CompoundNBT();
if (this.pos != null) {
tag.putInt(StructureConfiguration.hitXTag, this.pos.getX());
tag.putInt(StructureConfiguration.hitYTag, this.pos.getY());
tag.putInt(StructureConfiguration.hitZTag, this.pos.getZ());
}
tag.putString(StructureConfiguration.houseFacingTag, this.houseFacing.getSerializedName());
tag = this.CustomWriteToCompoundNBT(tag);
return tag;
}
/**
* Reads CompoundNBT to create a StructureConfiguration object from.
*
* @param messageTag The CompoundNBT to read the properties from.
* @return The updated StructureConfiguration instance.
*/
public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag) {
return null;
}
/**
* Reads CompoundNBT to create a StructureConfiguration object from.
*
* @param messageTag The CompoundNBT to read the properties from.
* @param config The existing StructureConfiguration instance to fill the properties in for.
* @return The updated StructureConfiguration instance.
*/
public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag, StructureConfiguration config) {
if (messageTag != null) {
if (messageTag.contains(StructureConfiguration.hitXTag)) {
config.pos = new BlockPos(
messageTag.getInt(StructureConfiguration.hitXTag),
messageTag.getInt(StructureConfiguration.hitYTag),
messageTag.getInt(StructureConfiguration.hitZTag));
}
if (messageTag.contains(StructureConfiguration.houseFacingTag)) {
config.houseFacing = Direction.byName(messageTag.getString(StructureConfiguration.houseFacingTag));
}
this.CustomReadFromNBTTag(messageTag, config);
}
return config;
}
/**
* Generic method to start the building of the structure.
*
* @param player The player which requested the build.
* @param world The world instance where the build will occur.
*/
public void BuildStructure(PlayerEntity player, ServerWorld world) {
// This is always on the server.
BlockPos hitBlockPos = this.pos;
this.ConfigurationSpecificBuildStructure(player, world, hitBlockPos);
}
/**
* This is used to actually build the structure as it creates the structure instance and calls build structure.
*
* @param player The player which requested the build.
* @param world The world instance where the build will occur.
* @param hitBlockPos This hit block position.
*/
protected void ConfigurationSpecificBuildStructure(PlayerEntity player, ServerWorld world, BlockPos hitBlockPos) {
}
/**
* Custom method which can be overridden to write custom properties to the tag.
*
* @param tag The CompoundNBT to write the custom properties too.
* @return The updated tag.
*/
protected CompoundNBT CustomWriteToCompoundNBT(CompoundNBT tag) {
return tag;
}
/**
* Custom method to read the CompoundNBT message.
*
* @param messageTag The message to create the configuration from.
* @param config The configuration to read the settings into.
*/
protected void CustomReadFromNBTTag(CompoundNBT messageTag, StructureConfiguration config) {
}
/**
* This method will remove 1 structure item from the player's inventory, it is expected that the item is in the
* player's hand.
*
* @param player The player to remove the item from.
* @param item the structure item to find.
*/
protected void RemoveStructureItemFromPlayer(PlayerEntity player, StructureItem item) {
ItemStack stack = player.getMainHandItem();
if (stack.getItem() != item) {
stack = player.getOffhandItem();
stack.shrink(1);
if (stack.isEmpty()) {
player.inventory.offhand.set(0, ItemStack.EMPTY);
}
} else {
int slot = this.getSlotFor(player.inventory, stack);
if (slot != -1) {
stack.shrink(1);
if (stack.isEmpty()) {
player.inventory.setItem(slot, ItemStack.EMPTY);
}
}
}
player.containerMenu.broadcastChanges();
}
protected void DamageHeldItem(PlayerEntity player, StructureItem item) {
ItemStack stack = player.getMainHandItem().getItem() == item ? player.getMainHandItem() : player.getOffhandItem();
Hand hand = player.getMainHandItem().getItem() == item ? Hand.MAIN_HAND : Hand.OFF_HAND;
ItemStack copy = stack.copy();
stack.hurtAndBreak(1, player, (player1) ->
{
player1.broadcastBreakEvent(hand);
});
if (stack.isEmpty()) {
net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, copy, hand);
EquipmentSlotType slotType = hand == Hand.MAIN_HAND ? EquipmentSlotType.MAINHAND : EquipmentSlotType.OFFHAND;
player.setItemSlot(slotType, ItemStack.EMPTY);
}
player.containerMenu.broadcastChanges();
}
/**
* Checks item, NBT, and meta if the item is not damageable
*/
private boolean stackEqualExact(ItemStack stack1, ItemStack stack2) {
return stack1.getItem() == stack2.getItem() && ItemStack.tagMatches(stack1, stack2);
}
/**
* Get's the first slot which contains the item in the supplied item stack in the player's main inventory.
* This method was copied directly from teh player inventory class since it was needed server side.
*
* @param playerInventory The player's inventory to try and find a slot.
* @param stack The stack to find an associated slot.
* @return The slot index or -1 if the item wasn't found.
*/
public int getSlotFor(PlayerInventory playerInventory, ItemStack stack) {
for (int i = 0; i < playerInventory.items.size(); ++i) {
if (!playerInventory.items.get(i).isEmpty() && this.stackEqualExact(stack, playerInventory.items.get(i))) {
return i;
}
}
return -1;
}
}
| src/main/java/com/wuest/prefab/Structures/Config/StructureConfiguration.java | package com.wuest.prefab.Structures.Config;
import com.wuest.prefab.Structures.Items.StructureItem;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.server.ServerWorld;
/**
* This is the base configuration class used by all structures.
*
* @author WuestMan
*/
@SuppressWarnings("WeakerAccess")
public class StructureConfiguration {
public static String houseFacingName = "House Facing";
private static String hitXTag = "hitX";
private static String hitYTag = "hitY";
private static String hitZTag = "hitZ";
private static String houseFacingTag = "wareHouseFacing";
/**
* The structure facing property.
*/
public Direction houseFacing;
/**
* The position of the structure.
*/
public BlockPos pos;
/**
* Initializes a new instance of the StructureConfiguration class.
*/
public StructureConfiguration() {
this.Initialize();
}
/**
* Initializes any properties for this class.
*/
public void Initialize() {
this.houseFacing = Direction.NORTH;
}
/**
* Writes the properties to an CompoundNBT.
*
* @return An CompoundNBT with the updated properties.
*/
public CompoundNBT WriteToCompoundNBT() {
CompoundNBT tag = new CompoundNBT();
if (this.pos != null) {
tag.putInt(StructureConfiguration.hitXTag, this.pos.getX());
tag.putInt(StructureConfiguration.hitYTag, this.pos.getY());
tag.putInt(StructureConfiguration.hitZTag, this.pos.getZ());
}
tag.putString(StructureConfiguration.houseFacingTag, this.houseFacing.getSerializedName());
tag = this.CustomWriteToCompoundNBT(tag);
return tag;
}
/**
* Reads CompoundNBT to create a StructureConfiguration object from.
*
* @param messageTag The CompoundNBT to read the properties from.
* @return The updated StructureConfiguration instance.
*/
public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag) {
return null;
}
/**
* Reads CompoundNBT to create a StructureConfiguration object from.
*
* @param messageTag The CompoundNBT to read the properties from.
* @param config The existing StructureConfiguration instance to fill the properties in for.
* @return The updated StructureConfiguration instance.
*/
public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag, StructureConfiguration config) {
if (messageTag != null) {
if (messageTag.contains(StructureConfiguration.hitXTag)) {
config.pos = new BlockPos(
messageTag.getInt(StructureConfiguration.hitXTag),
messageTag.getInt(StructureConfiguration.hitYTag),
messageTag.getInt(StructureConfiguration.hitZTag));
}
if (messageTag.contains(StructureConfiguration.houseFacingTag)) {
config.houseFacing = Direction.byName(messageTag.getString(StructureConfiguration.houseFacingTag));
}
this.CustomReadFromNBTTag(messageTag, config);
}
return config;
}
/**
* Generic method to start the building of the structure.
*
* @param player The player which requested the build.
* @param world The world instance where the build will occur.
*/
public void BuildStructure(PlayerEntity player, ServerWorld world) {
// This is always on the server.
BlockPos hitBlockPos = this.pos;
this.ConfigurationSpecificBuildStructure(player, world, hitBlockPos);
}
/**
* This is used to actually build the structure as it creates the structure instance and calls build structure.
*
* @param player The player which requested the build.
* @param world The world instance where the build will occur.
* @param hitBlockPos This hit block position.
*/
protected void ConfigurationSpecificBuildStructure(PlayerEntity player, ServerWorld world, BlockPos hitBlockPos) {
}
/**
* Custom method which can be overridden to write custom properties to the tag.
*
* @param tag The CompoundNBT to write the custom properties too.
* @return The updated tag.
*/
protected CompoundNBT CustomWriteToCompoundNBT(CompoundNBT tag) {
return tag;
}
/**
* Custom method to read the CompoundNBT message.
*
* @param messageTag The message to create the configuration from.
* @param config The configuration to read the settings into.
*/
protected void CustomReadFromNBTTag(CompoundNBT messageTag, StructureConfiguration config) {
}
/**
* This method will remove 1 structure item from the player's inventory, it is expected that the item is in the
* player's hand.
*
* @param player The player to remove the item from.
* @param item the structure item to find.
*/
protected void RemoveStructureItemFromPlayer(PlayerEntity player, StructureItem item) {
ItemStack stack = player.getMainHandItem();
if (stack.getItem() != item) {
stack = player.getOffhandItem();
}
int slot = this.getSlotFor(player.inventory, stack);
if (slot != -1) {
stack.shrink(1);
if (stack.isEmpty()) {
player.inventory.setItem(slot, ItemStack.EMPTY);
}
player.containerMenu.broadcastChanges();
}
}
protected void DamageHeldItem(PlayerEntity player, StructureItem item) {
ItemStack stack = player.getMainHandItem().getItem() == item ? player.getMainHandItem() : player.getOffhandItem();
Hand hand = player.getMainHandItem().getItem() == item ? Hand.MAIN_HAND : Hand.OFF_HAND;
ItemStack copy = stack.copy();
stack.hurtAndBreak(1, player, (player1) ->
{
player1.broadcastBreakEvent(hand);
});
if (stack.isEmpty()) {
net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, copy, hand);
EquipmentSlotType slotType = hand == Hand.MAIN_HAND ? EquipmentSlotType.MAINHAND : EquipmentSlotType.OFFHAND;
player.setItemSlot(slotType, ItemStack.EMPTY);
}
player.containerMenu.broadcastChanges();
}
/**
* Checks item, NBT, and meta if the item is not damageable
*/
private boolean stackEqualExact(ItemStack stack1, ItemStack stack2) {
return stack1.getItem() == stack2.getItem() && ItemStack.tagMatches(stack1, stack2);
}
/**
* Get's the first slot which contains the item in the supplied item stack in the player's main inventory.
* This method was copied directly from teh player inventory class since it was needed server side.
*
* @param playerInventory The player's inventory to try and find a slot.
* @param stack The stack to find an associated slot.
* @return The slot index or -1 if the item wasn't found.
*/
public int getSlotFor(PlayerInventory playerInventory, ItemStack stack) {
for (int i = 0; i < playerInventory.items.size(); ++i) {
if (!playerInventory.items.get(i).isEmpty() && this.stackEqualExact(stack, playerInventory.items.get(i))) {
return i;
}
}
return -1;
}
}
| Fixing issue where a player could get infinite structures
| src/main/java/com/wuest/prefab/Structures/Config/StructureConfiguration.java | Fixing issue where a player could get infinite structures | <ide><path>rc/main/java/com/wuest/prefab/Structures/Config/StructureConfiguration.java
<ide> */
<ide> @SuppressWarnings("WeakerAccess")
<ide> public class StructureConfiguration {
<del> public static String houseFacingName = "House Facing";
<del>
<del> private static String hitXTag = "hitX";
<del> private static String hitYTag = "hitY";
<del> private static String hitZTag = "hitZ";
<del> private static String houseFacingTag = "wareHouseFacing";
<del>
<del> /**
<del> * The structure facing property.
<del> */
<del> public Direction houseFacing;
<del>
<del> /**
<del> * The position of the structure.
<del> */
<del> public BlockPos pos;
<del>
<del> /**
<del> * Initializes a new instance of the StructureConfiguration class.
<del> */
<del> public StructureConfiguration() {
<del> this.Initialize();
<del> }
<del>
<del> /**
<del> * Initializes any properties for this class.
<del> */
<del> public void Initialize() {
<del> this.houseFacing = Direction.NORTH;
<del> }
<del>
<del> /**
<del> * Writes the properties to an CompoundNBT.
<del> *
<del> * @return An CompoundNBT with the updated properties.
<del> */
<del> public CompoundNBT WriteToCompoundNBT() {
<del> CompoundNBT tag = new CompoundNBT();
<del>
<del> if (this.pos != null) {
<del> tag.putInt(StructureConfiguration.hitXTag, this.pos.getX());
<del> tag.putInt(StructureConfiguration.hitYTag, this.pos.getY());
<del> tag.putInt(StructureConfiguration.hitZTag, this.pos.getZ());
<del> }
<del>
<del> tag.putString(StructureConfiguration.houseFacingTag, this.houseFacing.getSerializedName());
<del>
<del> tag = this.CustomWriteToCompoundNBT(tag);
<del>
<del> return tag;
<del> }
<del>
<del> /**
<del> * Reads CompoundNBT to create a StructureConfiguration object from.
<del> *
<del> * @param messageTag The CompoundNBT to read the properties from.
<del> * @return The updated StructureConfiguration instance.
<del> */
<del> public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag) {
<del> return null;
<del> }
<del>
<del> /**
<del> * Reads CompoundNBT to create a StructureConfiguration object from.
<del> *
<del> * @param messageTag The CompoundNBT to read the properties from.
<del> * @param config The existing StructureConfiguration instance to fill the properties in for.
<del> * @return The updated StructureConfiguration instance.
<del> */
<del> public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag, StructureConfiguration config) {
<del> if (messageTag != null) {
<del> if (messageTag.contains(StructureConfiguration.hitXTag)) {
<del> config.pos = new BlockPos(
<del> messageTag.getInt(StructureConfiguration.hitXTag),
<del> messageTag.getInt(StructureConfiguration.hitYTag),
<del> messageTag.getInt(StructureConfiguration.hitZTag));
<del> }
<del>
<del> if (messageTag.contains(StructureConfiguration.houseFacingTag)) {
<del> config.houseFacing = Direction.byName(messageTag.getString(StructureConfiguration.houseFacingTag));
<del> }
<del>
<del> this.CustomReadFromNBTTag(messageTag, config);
<del> }
<del>
<del> return config;
<del> }
<del>
<del> /**
<del> * Generic method to start the building of the structure.
<del> *
<del> * @param player The player which requested the build.
<del> * @param world The world instance where the build will occur.
<del> */
<del> public void BuildStructure(PlayerEntity player, ServerWorld world) {
<del> // This is always on the server.
<del> BlockPos hitBlockPos = this.pos;
<del>
<del> this.ConfigurationSpecificBuildStructure(player, world, hitBlockPos);
<del> }
<del>
<del> /**
<del> * This is used to actually build the structure as it creates the structure instance and calls build structure.
<del> *
<del> * @param player The player which requested the build.
<del> * @param world The world instance where the build will occur.
<del> * @param hitBlockPos This hit block position.
<del> */
<del> protected void ConfigurationSpecificBuildStructure(PlayerEntity player, ServerWorld world, BlockPos hitBlockPos) {
<del> }
<del>
<del> /**
<del> * Custom method which can be overridden to write custom properties to the tag.
<del> *
<del> * @param tag The CompoundNBT to write the custom properties too.
<del> * @return The updated tag.
<del> */
<del> protected CompoundNBT CustomWriteToCompoundNBT(CompoundNBT tag) {
<del> return tag;
<del> }
<del>
<del> /**
<del> * Custom method to read the CompoundNBT message.
<del> *
<del> * @param messageTag The message to create the configuration from.
<del> * @param config The configuration to read the settings into.
<del> */
<del> protected void CustomReadFromNBTTag(CompoundNBT messageTag, StructureConfiguration config) {
<del> }
<del>
<del> /**
<del> * This method will remove 1 structure item from the player's inventory, it is expected that the item is in the
<del> * player's hand.
<del> *
<del> * @param player The player to remove the item from.
<del> * @param item the structure item to find.
<del> */
<del> protected void RemoveStructureItemFromPlayer(PlayerEntity player, StructureItem item) {
<del> ItemStack stack = player.getMainHandItem();
<del>
<del> if (stack.getItem() != item) {
<del> stack = player.getOffhandItem();
<del> }
<del>
<del> int slot = this.getSlotFor(player.inventory, stack);
<del>
<del> if (slot != -1) {
<del> stack.shrink(1);
<del>
<del> if (stack.isEmpty()) {
<del> player.inventory.setItem(slot, ItemStack.EMPTY);
<del> }
<del>
<del> player.containerMenu.broadcastChanges();
<del> }
<del> }
<del>
<del> protected void DamageHeldItem(PlayerEntity player, StructureItem item) {
<del> ItemStack stack = player.getMainHandItem().getItem() == item ? player.getMainHandItem() : player.getOffhandItem();
<del> Hand hand = player.getMainHandItem().getItem() == item ? Hand.MAIN_HAND : Hand.OFF_HAND;
<del>
<del> ItemStack copy = stack.copy();
<del>
<del> stack.hurtAndBreak(1, player, (player1) ->
<del> {
<del> player1.broadcastBreakEvent(hand);
<del> });
<del>
<del> if (stack.isEmpty()) {
<del> net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, copy, hand);
<del> EquipmentSlotType slotType = hand == Hand.MAIN_HAND ? EquipmentSlotType.MAINHAND : EquipmentSlotType.OFFHAND;
<del>
<del> player.setItemSlot(slotType, ItemStack.EMPTY);
<del> }
<del>
<del> player.containerMenu.broadcastChanges();
<del> }
<del>
<del> /**
<del> * Checks item, NBT, and meta if the item is not damageable
<del> */
<del> private boolean stackEqualExact(ItemStack stack1, ItemStack stack2) {
<del> return stack1.getItem() == stack2.getItem() && ItemStack.tagMatches(stack1, stack2);
<del> }
<del>
<del> /**
<del> * Get's the first slot which contains the item in the supplied item stack in the player's main inventory.
<del> * This method was copied directly from teh player inventory class since it was needed server side.
<del> *
<del> * @param playerInventory The player's inventory to try and find a slot.
<del> * @param stack The stack to find an associated slot.
<del> * @return The slot index or -1 if the item wasn't found.
<del> */
<del> public int getSlotFor(PlayerInventory playerInventory, ItemStack stack) {
<del> for (int i = 0; i < playerInventory.items.size(); ++i) {
<del> if (!playerInventory.items.get(i).isEmpty() && this.stackEqualExact(stack, playerInventory.items.get(i))) {
<del> return i;
<del> }
<del> }
<del>
<del> return -1;
<del> }
<add> public static String houseFacingName = "House Facing";
<add>
<add> private static String hitXTag = "hitX";
<add> private static String hitYTag = "hitY";
<add> private static String hitZTag = "hitZ";
<add> private static String houseFacingTag = "wareHouseFacing";
<add>
<add> /**
<add> * The structure facing property.
<add> */
<add> public Direction houseFacing;
<add>
<add> /**
<add> * The position of the structure.
<add> */
<add> public BlockPos pos;
<add>
<add> /**
<add> * Initializes a new instance of the StructureConfiguration class.
<add> */
<add> public StructureConfiguration() {
<add> this.Initialize();
<add> }
<add>
<add> /**
<add> * Initializes any properties for this class.
<add> */
<add> public void Initialize() {
<add> this.houseFacing = Direction.NORTH;
<add> }
<add>
<add> /**
<add> * Writes the properties to an CompoundNBT.
<add> *
<add> * @return An CompoundNBT with the updated properties.
<add> */
<add> public CompoundNBT WriteToCompoundNBT() {
<add> CompoundNBT tag = new CompoundNBT();
<add>
<add> if (this.pos != null) {
<add> tag.putInt(StructureConfiguration.hitXTag, this.pos.getX());
<add> tag.putInt(StructureConfiguration.hitYTag, this.pos.getY());
<add> tag.putInt(StructureConfiguration.hitZTag, this.pos.getZ());
<add> }
<add>
<add> tag.putString(StructureConfiguration.houseFacingTag, this.houseFacing.getSerializedName());
<add>
<add> tag = this.CustomWriteToCompoundNBT(tag);
<add>
<add> return tag;
<add> }
<add>
<add> /**
<add> * Reads CompoundNBT to create a StructureConfiguration object from.
<add> *
<add> * @param messageTag The CompoundNBT to read the properties from.
<add> * @return The updated StructureConfiguration instance.
<add> */
<add> public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag) {
<add> return null;
<add> }
<add>
<add> /**
<add> * Reads CompoundNBT to create a StructureConfiguration object from.
<add> *
<add> * @param messageTag The CompoundNBT to read the properties from.
<add> * @param config The existing StructureConfiguration instance to fill the properties in for.
<add> * @return The updated StructureConfiguration instance.
<add> */
<add> public StructureConfiguration ReadFromCompoundNBT(CompoundNBT messageTag, StructureConfiguration config) {
<add> if (messageTag != null) {
<add> if (messageTag.contains(StructureConfiguration.hitXTag)) {
<add> config.pos = new BlockPos(
<add> messageTag.getInt(StructureConfiguration.hitXTag),
<add> messageTag.getInt(StructureConfiguration.hitYTag),
<add> messageTag.getInt(StructureConfiguration.hitZTag));
<add> }
<add>
<add> if (messageTag.contains(StructureConfiguration.houseFacingTag)) {
<add> config.houseFacing = Direction.byName(messageTag.getString(StructureConfiguration.houseFacingTag));
<add> }
<add>
<add> this.CustomReadFromNBTTag(messageTag, config);
<add> }
<add>
<add> return config;
<add> }
<add>
<add> /**
<add> * Generic method to start the building of the structure.
<add> *
<add> * @param player The player which requested the build.
<add> * @param world The world instance where the build will occur.
<add> */
<add> public void BuildStructure(PlayerEntity player, ServerWorld world) {
<add> // This is always on the server.
<add> BlockPos hitBlockPos = this.pos;
<add>
<add> this.ConfigurationSpecificBuildStructure(player, world, hitBlockPos);
<add> }
<add>
<add> /**
<add> * This is used to actually build the structure as it creates the structure instance and calls build structure.
<add> *
<add> * @param player The player which requested the build.
<add> * @param world The world instance where the build will occur.
<add> * @param hitBlockPos This hit block position.
<add> */
<add> protected void ConfigurationSpecificBuildStructure(PlayerEntity player, ServerWorld world, BlockPos hitBlockPos) {
<add> }
<add>
<add> /**
<add> * Custom method which can be overridden to write custom properties to the tag.
<add> *
<add> * @param tag The CompoundNBT to write the custom properties too.
<add> * @return The updated tag.
<add> */
<add> protected CompoundNBT CustomWriteToCompoundNBT(CompoundNBT tag) {
<add> return tag;
<add> }
<add>
<add> /**
<add> * Custom method to read the CompoundNBT message.
<add> *
<add> * @param messageTag The message to create the configuration from.
<add> * @param config The configuration to read the settings into.
<add> */
<add> protected void CustomReadFromNBTTag(CompoundNBT messageTag, StructureConfiguration config) {
<add> }
<add>
<add> /**
<add> * This method will remove 1 structure item from the player's inventory, it is expected that the item is in the
<add> * player's hand.
<add> *
<add> * @param player The player to remove the item from.
<add> * @param item the structure item to find.
<add> */
<add> protected void RemoveStructureItemFromPlayer(PlayerEntity player, StructureItem item) {
<add> ItemStack stack = player.getMainHandItem();
<add>
<add> if (stack.getItem() != item) {
<add> stack = player.getOffhandItem();
<add>
<add> stack.shrink(1);
<add>
<add> if (stack.isEmpty()) {
<add> player.inventory.offhand.set(0, ItemStack.EMPTY);
<add> }
<add> } else {
<add> int slot = this.getSlotFor(player.inventory, stack);
<add>
<add> if (slot != -1) {
<add> stack.shrink(1);
<add>
<add> if (stack.isEmpty()) {
<add> player.inventory.setItem(slot, ItemStack.EMPTY);
<add> }
<add> }
<add> }
<add>
<add> player.containerMenu.broadcastChanges();
<add> }
<add>
<add> protected void DamageHeldItem(PlayerEntity player, StructureItem item) {
<add> ItemStack stack = player.getMainHandItem().getItem() == item ? player.getMainHandItem() : player.getOffhandItem();
<add> Hand hand = player.getMainHandItem().getItem() == item ? Hand.MAIN_HAND : Hand.OFF_HAND;
<add>
<add> ItemStack copy = stack.copy();
<add>
<add> stack.hurtAndBreak(1, player, (player1) ->
<add> {
<add> player1.broadcastBreakEvent(hand);
<add> });
<add>
<add> if (stack.isEmpty()) {
<add> net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, copy, hand);
<add> EquipmentSlotType slotType = hand == Hand.MAIN_HAND ? EquipmentSlotType.MAINHAND : EquipmentSlotType.OFFHAND;
<add>
<add> player.setItemSlot(slotType, ItemStack.EMPTY);
<add> }
<add>
<add> player.containerMenu.broadcastChanges();
<add> }
<add>
<add> /**
<add> * Checks item, NBT, and meta if the item is not damageable
<add> */
<add> private boolean stackEqualExact(ItemStack stack1, ItemStack stack2) {
<add> return stack1.getItem() == stack2.getItem() && ItemStack.tagMatches(stack1, stack2);
<add> }
<add>
<add> /**
<add> * Get's the first slot which contains the item in the supplied item stack in the player's main inventory.
<add> * This method was copied directly from teh player inventory class since it was needed server side.
<add> *
<add> * @param playerInventory The player's inventory to try and find a slot.
<add> * @param stack The stack to find an associated slot.
<add> * @return The slot index or -1 if the item wasn't found.
<add> */
<add> public int getSlotFor(PlayerInventory playerInventory, ItemStack stack) {
<add> for (int i = 0; i < playerInventory.items.size(); ++i) {
<add> if (!playerInventory.items.get(i).isEmpty() && this.stackEqualExact(stack, playerInventory.items.get(i))) {
<add> return i;
<add> }
<add> }
<add>
<add> return -1;
<add> }
<ide> } |
|
Java | apache-2.0 | fd4a178cdf5f7c81463938f6909fafb41f54fe9c | 0 | apache/incubator-kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/kylin,apache/kylin | /*
* 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.kylin.metadata.model;
import java.io.Serializable;
import java.util.Comparator;
/**
* SegmentRange and TSRange seem similar but are different concepts.
*
* - SegmentRange defines the range of a segment.
* - TSRange is the time series range of the segment data.
* - When segment range is defined by time, the two can be the same, in that case TSRange is a kind of SegmentRange.
* - Duration segment creation (build/refresh/merge), a new segment is defined by either one of the two, not both.
* - And the choice must be consistent across all following segment creation.
*/
@SuppressWarnings("serial")
public class SegmentRange<T extends Comparable> implements Serializable {
public final Endpoint<T> start;
public final Endpoint<T> end;
public SegmentRange(Endpoint start, Endpoint end) {
this.start = start;
this.end = end;
checkState();
}
public SegmentRange(T start, T end) {
if (start != null && end != null && start.getClass() != end.getClass())
throw new IllegalArgumentException();
this.start = new Endpoint(start, start == null, false);
this.end = new Endpoint(end, false, end == null);
checkState();
}
private void checkState() {
if (start.compareTo(end) > 0)
throw new IllegalStateException();
}
public boolean isInfinite() {
return start.isMin && end.isMax;
}
public boolean contains(SegmentRange o) {
return this.start.compareTo(o.start) <= 0 && o.end.compareTo(this.end) <= 0;
}
public boolean overlaps(SegmentRange o) {
return this.start.compareTo(o.end) < 0 && o.start.compareTo(this.end) < 0;
}
public boolean connects(SegmentRange o) {
return this.end.compareTo(o.start) == 0;
}
public boolean apartBefore(SegmentRange o) {
return this.end.compareTo(o.start) < 0;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + "[" + start + "," + end + ")";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((end == null) ? 0 : end.hashCode());
result = prime * result + ((start == null) ? 0 : start.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SegmentRange other = (SegmentRange) obj;
if (end == null) {
if (other.end != null)
return false;
} else if (!end.equals(other.end))
return false;
if (start == null) {
if (other.start != null)
return false;
} else if (!start.equals(other.start))
return false;
return true;
}
// ============================================================================
public static class TSRange extends SegmentRange<Long> {
public TSRange(Long start, Long end) {
// [0, Long.MAX_VALUE) is full build (for historic reason)
super(new Endpoint(isInfinite(start, end) ? 0 : start, isInfinite(start, end), false), //
new Endpoint(isInfinite(start, end) ? Long.MAX_VALUE : end, false, isInfinite(start, end)));
}
private static boolean isInfinite(Long start, Long end) {
return (start == null || start <= 0) && (end == null || end == Long.MAX_VALUE);
}
public long duration() {
return end.v - start.v;
}
}
// ============================================================================
// immutable
public static class Endpoint<T extends Comparable> implements Comparable<Endpoint>, Serializable {
public static final Comparator<Endpoint> comparator = getComparator(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
}
});
public static Comparator<Endpoint> getComparator(final Comparator valueComparator) {
return new Comparator<Endpoint>() {
@Override
public int compare(Endpoint a, Endpoint b) {
if (a == null || b == null)
throw new IllegalStateException();
if (a.isMin) {
return b.isMin ? 0 : -1;
} else if (b.isMin) {
return a.isMin ? 0 : 1;
} else if (a.isMax) {
return b.isMax ? 0 : 1;
} else if (b.isMax) {
return a.isMax ? 0 : -1;
} else {
return valueComparator.compare(a.v, b.v);
}
}
};
}
public final T v;
public final boolean isMin;
public final boolean isMax;
private Endpoint(T v, boolean isMin, boolean isMax) {
this.v = v;
this.isMin = isMin;
this.isMax = isMax;
}
@Override
public int compareTo(Endpoint o) {
return comparator.compare(this, o);
}
@Override
public String toString() {
String s = "" + v;
if (isMin)
s += "[min]";
if (isMax)
s += "[max]";
return s;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (isMax ? 1231 : 1237);
result = prime * result + (isMin ? 1231 : 1237);
result = prime * result + ((v == null) ? 0 : v.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Endpoint other = (Endpoint) obj;
if (isMax != other.isMax)
return false;
if (isMin != other.isMin)
return false;
return comparator.compare(this, other) == 0;
}
}
}
| core-metadata/src/main/java/org/apache/kylin/metadata/model/SegmentRange.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.kylin.metadata.model;
import java.io.Serializable;
import java.util.Comparator;
/**
* SegmentRange and TSRange seem similar but are different concepts.
*
* - SegmentRange defines the range of a segment.
* - TSRange is the time series range of the segment data.
* - When segment range is defined by time, the two can be the same, in that case TSRange is a kind of SegmentRange.
* - Duration segment creation (build/refresh/merge), a new segment is defined by either one of the two, not both.
* - And the choice must be consistent across all following segment creation.
*/
@SuppressWarnings("serial")
public class SegmentRange<T extends Comparable> implements Serializable {
public final Endpoint<T> start;
public final Endpoint<T> end;
public SegmentRange(Endpoint start, Endpoint end) {
this.start = start;
this.end = end;
checkState();
}
public SegmentRange(T start, T end) {
if (start != null && end != null && start.getClass() != end.getClass())
throw new IllegalArgumentException();
this.start = new Endpoint(start, start == null, false);
this.end = new Endpoint(end, false, end == null);
checkState();
}
private void checkState() {
if (start.compareTo(end) > 0)
throw new IllegalStateException();
}
public boolean isInfinite() {
return start.isMin && end.isMax;
}
public boolean contains(SegmentRange o) {
return this.start.compareTo(o.start) <= 0 && o.end.compareTo(this.end) <= 0;
}
public boolean overlaps(SegmentRange o) {
return this.start.compareTo(o.end) < 0 && o.start.compareTo(this.end) < 0;
}
public boolean connects(SegmentRange o) {
return this.end.compareTo(o.start) == 0;
}
public boolean apartBefore(SegmentRange o) {
return this.end.compareTo(o.start) < 0;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + "[" + start + "," + end + ")";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((end == null) ? 0 : end.hashCode());
result = prime * result + ((start == null) ? 0 : start.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SegmentRange other = (SegmentRange) obj;
if (end == null) {
if (other.end != null)
return false;
} else if (!end.equals(other.end))
return false;
if (start == null) {
if (other.start != null)
return false;
} else if (!start.equals(other.start))
return false;
return true;
}
// ============================================================================
public static class TSRange extends SegmentRange<Long> {
public TSRange(Long start, Long end) {
// [0, Long.MAX_VALUE) is full build (for historic reason)
super(new Endpoint(isInfinite(start, end) ? 0 : start, isInfinite(start, end), false), //
new Endpoint(isInfinite(start, end) ? Long.MAX_VALUE : end, false, isInfinite(start, end)));
}
private static boolean isInfinite(Long start, Long end) {
return (start == null || start <= 0) && (end == null || end == Long.MAX_VALUE);
}
public long duration() {
return end.v - start.v;
}
}
// ============================================================================
// immutable
public static class Endpoint<T extends Comparable> implements Comparable<Endpoint>, Serializable {
public static final Comparator<Endpoint> comparator = getComparator(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
}
});
public static Comparator<Endpoint> getComparator(final Comparator valueComparator) {
return new Comparator<Endpoint>() {
@Override
public int compare(Endpoint a, Endpoint b) {
if (a.isMin) {
return b.isMin ? 0 : -1;
} else if (b.isMin) {
return a.isMin ? 0 : 1;
} else if (a.isMax) {
return b.isMax ? 0 : 1;
} else if (b.isMax) {
return a.isMax ? 0 : -1;
} else {
if (a == null || b == null)
throw new IllegalStateException();
return valueComparator.compare(a.v, b.v);
}
}
};
}
public final T v;
public final boolean isMin;
public final boolean isMax;
private Endpoint(T v, boolean isMin, boolean isMax) {
this.v = v;
this.isMin = isMin;
this.isMax = isMax;
}
@Override
public int compareTo(Endpoint o) {
return comparator.compare(this, o);
}
@Override
public String toString() {
String s = "" + v;
if (isMin)
s += "[min]";
if (isMax)
s += "[max]";
return s;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (isMax ? 1231 : 1237);
result = prime * result + (isMin ? 1231 : 1237);
result = prime * result + ((v == null) ? 0 : v.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Endpoint other = (Endpoint) obj;
if (isMax != other.isMax)
return false;
if (isMin != other.isMin)
return false;
return comparator.compare(this, other) == 0;
}
}
}
| KYLIN-2871, fix ineffective null check
| core-metadata/src/main/java/org/apache/kylin/metadata/model/SegmentRange.java | KYLIN-2871, fix ineffective null check | <ide><path>ore-metadata/src/main/java/org/apache/kylin/metadata/model/SegmentRange.java
<ide> return new Comparator<Endpoint>() {
<ide> @Override
<ide> public int compare(Endpoint a, Endpoint b) {
<add> if (a == null || b == null)
<add> throw new IllegalStateException();
<ide> if (a.isMin) {
<ide> return b.isMin ? 0 : -1;
<ide> } else if (b.isMin) {
<ide> } else if (b.isMax) {
<ide> return a.isMax ? 0 : -1;
<ide> } else {
<del> if (a == null || b == null)
<del> throw new IllegalStateException();
<del>
<ide> return valueComparator.compare(a.v, b.v);
<ide> }
<ide> } |
|
Java | apache-2.0 | 0024efe87c44c3b9eba4e0e188a59ed819407f31 | 0 | SimonVT/cathode,SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/util/SelectionBuilder.java | /*
* Copyright (C) 2013 Simon Vig Therkildsen
*
* 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.
*/
/*
* Modifications:
* -Imported from AOSP frameworks/base/core/java/com/android/internal/content
* -Changed package name
*/
package net.simonvt.cathode.util;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Helper for building selection clauses for {@link SQLiteDatabase}. Each
* appended clause is combined using {@code AND}. This class is <em>not</em>
* thread safe.
*/
public class SelectionBuilder {
private static final String TAG = "SelectionBuilder";
private static final boolean LOGV = false;
private String table = null;
private Map<String, String> projectionMap = new HashMap<>();
private StringBuilder selection = new StringBuilder();
private ArrayList<String> selectionArgs = new ArrayList<>();
/** Reset any internal state, allowing this builder to be recycled. */
public SelectionBuilder reset() {
table = null;
selection.setLength(0);
selectionArgs.clear();
return this;
}
/**
* Append the given selection clause to the internal state. Each clause is
* surrounded with parenthesis and combined using {@code AND}.
*/
public SelectionBuilder where(String selection, String... selectionArgs) {
if (TextUtils.isEmpty(selection)) {
if (selectionArgs != null && selectionArgs.length > 0) {
throw new IllegalArgumentException("Valid selection required when including arguments=");
}
// Shortcut when clause is empty
return this;
}
if (this.selection.length() > 0) {
this.selection.append(" AND ");
}
this.selection.append("(").append(selection).append(")");
if (selectionArgs != null) {
for (String arg : selectionArgs) {
this.selectionArgs.add(arg);
}
}
return this;
}
public SelectionBuilder table(String table) {
this.table = table;
return this;
}
private void assertTable() {
if (table == null) {
throw new IllegalStateException("Table not specified");
}
}
public SelectionBuilder mapToTable(String column, String table) {
projectionMap.put(column, table + "." + column);
return this;
}
public SelectionBuilder map(String fromColumn, String toClause) {
projectionMap.put(fromColumn, toClause + " AS " + fromColumn);
return this;
}
/**
* Return selection string for current internal state.
*
* @see #getSelectionArgs()
*/
public String getSelection() {
return selection.toString();
}
/**
* Return selection arguments for current internal state.
*
* @see #getSelection()
*/
public String[] getSelectionArgs() {
return selectionArgs.toArray(new String[selectionArgs.size()]);
}
private void mapColumns(String[] columns) {
for (int i = 0; i < columns.length; i++) {
final String target = projectionMap.get(columns[i]);
if (target != null) {
columns[i] = target;
}
}
}
@Override public String toString() {
return "SelectionBuilder[table="
+ table
+ ", selection="
+ getSelection()
+ ", selectionArgs="
+ Arrays.toString(getSelectionArgs())
+ "]";
}
/** Execute query using the current internal state as {@code WHERE} clause. */
public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {
return query(db, columns, null, null, orderBy, null);
}
/** Execute query using the current internal state as {@code WHERE} clause. */
public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, String having,
String orderBy, String limit) {
assertTable();
if (columns != null) mapColumns(columns);
if (LOGV) Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);
return db.query(table, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy,
limit);
}
/** Execute update using the current internal state as {@code WHERE} clause. */
public int update(SQLiteDatabase db, ContentValues values) {
assertTable();
if (LOGV) Log.v(TAG, "update() " + this);
return db.update(table, values, getSelection(), getSelectionArgs());
}
/** Execute delete using the current internal state as {@code WHERE} clause. */
public int delete(SQLiteDatabase db) {
assertTable();
if (LOGV) Log.v(TAG, "delete() " + this);
return db.delete(table, getSelection(), getSelectionArgs());
}
}
| Remove unused class.
| cathode/src/main/java/net/simonvt/cathode/util/SelectionBuilder.java | Remove unused class. | <ide><path>athode/src/main/java/net/simonvt/cathode/util/SelectionBuilder.java
<del>/*
<del> * Copyright (C) 2013 Simon Vig Therkildsen
<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>/*
<del> * Modifications:
<del> * -Imported from AOSP frameworks/base/core/java/com/android/internal/content
<del> * -Changed package name
<del> */
<del>
<del>package net.simonvt.cathode.util;
<del>
<del>import android.content.ContentValues;
<del>import android.database.Cursor;
<del>import android.database.sqlite.SQLiteDatabase;
<del>import android.text.TextUtils;
<del>import android.util.Log;
<del>import java.util.ArrayList;
<del>import java.util.Arrays;
<del>import java.util.HashMap;
<del>import java.util.Map;
<del>
<del>/**
<del> * Helper for building selection clauses for {@link SQLiteDatabase}. Each
<del> * appended clause is combined using {@code AND}. This class is <em>not</em>
<del> * thread safe.
<del> */
<del>public class SelectionBuilder {
<del>
<del> private static final String TAG = "SelectionBuilder";
<del> private static final boolean LOGV = false;
<del>
<del> private String table = null;
<del> private Map<String, String> projectionMap = new HashMap<>();
<del> private StringBuilder selection = new StringBuilder();
<del> private ArrayList<String> selectionArgs = new ArrayList<>();
<del>
<del> /** Reset any internal state, allowing this builder to be recycled. */
<del> public SelectionBuilder reset() {
<del> table = null;
<del> selection.setLength(0);
<del> selectionArgs.clear();
<del> return this;
<del> }
<del>
<del> /**
<del> * Append the given selection clause to the internal state. Each clause is
<del> * surrounded with parenthesis and combined using {@code AND}.
<del> */
<del> public SelectionBuilder where(String selection, String... selectionArgs) {
<del> if (TextUtils.isEmpty(selection)) {
<del> if (selectionArgs != null && selectionArgs.length > 0) {
<del> throw new IllegalArgumentException("Valid selection required when including arguments=");
<del> }
<del>
<del> // Shortcut when clause is empty
<del> return this;
<del> }
<del>
<del> if (this.selection.length() > 0) {
<del> this.selection.append(" AND ");
<del> }
<del>
<del> this.selection.append("(").append(selection).append(")");
<del> if (selectionArgs != null) {
<del> for (String arg : selectionArgs) {
<del> this.selectionArgs.add(arg);
<del> }
<del> }
<del>
<del> return this;
<del> }
<del>
<del> public SelectionBuilder table(String table) {
<del> this.table = table;
<del> return this;
<del> }
<del>
<del> private void assertTable() {
<del> if (table == null) {
<del> throw new IllegalStateException("Table not specified");
<del> }
<del> }
<del>
<del> public SelectionBuilder mapToTable(String column, String table) {
<del> projectionMap.put(column, table + "." + column);
<del> return this;
<del> }
<del>
<del> public SelectionBuilder map(String fromColumn, String toClause) {
<del> projectionMap.put(fromColumn, toClause + " AS " + fromColumn);
<del> return this;
<del> }
<del>
<del> /**
<del> * Return selection string for current internal state.
<del> *
<del> * @see #getSelectionArgs()
<del> */
<del> public String getSelection() {
<del> return selection.toString();
<del> }
<del>
<del> /**
<del> * Return selection arguments for current internal state.
<del> *
<del> * @see #getSelection()
<del> */
<del> public String[] getSelectionArgs() {
<del> return selectionArgs.toArray(new String[selectionArgs.size()]);
<del> }
<del>
<del> private void mapColumns(String[] columns) {
<del> for (int i = 0; i < columns.length; i++) {
<del> final String target = projectionMap.get(columns[i]);
<del> if (target != null) {
<del> columns[i] = target;
<del> }
<del> }
<del> }
<del>
<del> @Override public String toString() {
<del> return "SelectionBuilder[table="
<del> + table
<del> + ", selection="
<del> + getSelection()
<del> + ", selectionArgs="
<del> + Arrays.toString(getSelectionArgs())
<del> + "]";
<del> }
<del>
<del> /** Execute query using the current internal state as {@code WHERE} clause. */
<del> public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {
<del> return query(db, columns, null, null, orderBy, null);
<del> }
<del>
<del> /** Execute query using the current internal state as {@code WHERE} clause. */
<del> public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, String having,
<del> String orderBy, String limit) {
<del> assertTable();
<del> if (columns != null) mapColumns(columns);
<del> if (LOGV) Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);
<del> return db.query(table, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy,
<del> limit);
<del> }
<del>
<del> /** Execute update using the current internal state as {@code WHERE} clause. */
<del> public int update(SQLiteDatabase db, ContentValues values) {
<del> assertTable();
<del> if (LOGV) Log.v(TAG, "update() " + this);
<del> return db.update(table, values, getSelection(), getSelectionArgs());
<del> }
<del>
<del> /** Execute delete using the current internal state as {@code WHERE} clause. */
<del> public int delete(SQLiteDatabase db) {
<del> assertTable();
<del> if (LOGV) Log.v(TAG, "delete() " + this);
<del> return db.delete(table, getSelection(), getSelectionArgs());
<del> }
<del>} |
||
Java | apache-2.0 | b0e7daf047799d8e696f09d477c045d9db48289a | 0 | maobaolong/alluxio,maobaolong/alluxio,bf8086/alluxio,Reidddddd/alluxio,PasaLab/tachyon,bf8086/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,calvinjia/tachyon,PasaLab/tachyon,EvilMcJerkface/alluxio,wwjiang007/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,calvinjia/tachyon,wwjiang007/alluxio,maobaolong/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,bf8086/alluxio,Reidddddd/alluxio,calvinjia/tachyon,Alluxio/alluxio,wwjiang007/alluxio,Alluxio/alluxio,madanadit/alluxio,madanadit/alluxio,Alluxio/alluxio,bf8086/alluxio,madanadit/alluxio,Reidddddd/alluxio,aaudiber/alluxio,maboelhassan/alluxio,apc999/alluxio,Alluxio/alluxio,wwjiang007/alluxio,madanadit/alluxio,aaudiber/alluxio,PasaLab/tachyon,calvinjia/tachyon,madanadit/alluxio,aaudiber/alluxio,Alluxio/alluxio,calvinjia/tachyon,maobaolong/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,madanadit/alluxio,apc999/alluxio,bf8086/alluxio,madanadit/alluxio,maobaolong/alluxio,calvinjia/tachyon,maobaolong/alluxio,aaudiber/alluxio,wwjiang007/alluxio,bf8086/alluxio,Reidddddd/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,bf8086/alluxio,madanadit/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,aaudiber/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,PasaLab/tachyon,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,maobaolong/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,PasaLab/tachyon,Alluxio/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,Reidddddd/alluxio,aaudiber/alluxio,PasaLab/tachyon,aaudiber/alluxio,apc999/alluxio,wwjiang007/alluxio,PasaLab/tachyon | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.underfs.swift;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import javax.annotation.concurrent.NotThreadSafe;
/**
* A stream for writing data to Swift API based object store.
*/
@NotThreadSafe
public class SwiftOutputStream extends OutputStream {
private static final Logger LOG = LoggerFactory.getLogger(SwiftOutputStream.class);
private OutputStream mOutputStream;
private HttpURLConnection mHttpCon;
/**
* Creates a new instance of {@link SwiftOutputStream}.
*
* @param httpCon connection to Swift
*/
public SwiftOutputStream(HttpURLConnection httpCon) throws IOException {
try {
mOutputStream = httpCon.getOutputStream();
mHttpCon = httpCon;
} catch (Exception e) {
LOG.error(e.getMessage());
throw new IOException(e);
}
}
@Override
public void write(int b) throws IOException {
mOutputStream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
mOutputStream.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
mOutputStream.write(b);
}
@Override
public void close() throws IOException {
mOutputStream.close();
InputStream is = null;
try {
// Status 400 and up should be read from error stream.
// Expecting here 201 Create or 202 Accepted.
if (mHttpCon.getResponseCode() >= 400) {
LOG.error("Failed to write data to Swift with error code: " + mHttpCon.getResponseCode());
is = mHttpCon.getErrorStream();
} else {
is = mHttpCon.getInputStream();
}
is.close();
} catch (Exception e) {
LOG.error(e.getMessage());
if (is != null) {
is.close();
}
}
mHttpCon.disconnect();
}
@Override
public void flush() throws IOException {
mOutputStream.flush();
}
}
| underfs/swift/src/main/java/alluxio/underfs/swift/SwiftOutputStream.java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.underfs.swift;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import javax.annotation.concurrent.NotThreadSafe;
/**
* A stream for writing data to Swift API based object store.
*/
@NotThreadSafe
public class SwiftOutputStream extends OutputStream {
private static final Logger LOG = LoggerFactory.getLogger(SwiftOutputStream.class);
private OutputStream mOutputStream;
private HttpURLConnection mHttpCon;
/**
* Creates a new instance of {@link SwiftOutputStream}.
*
* @param httpCon connection to Swift
*/
public SwiftOutputStream(HttpURLConnection httpCon) throws IOException {
try {
mOutputStream = httpCon.getOutputStream();
mHttpCon = httpCon;
} catch (Exception e) {
LOG.error(e.getMessage());
throw new IOException(e);
}
}
@Override
public void write(int b) throws IOException {
mOutputStream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
mOutputStream.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
mOutputStream.write(b);
}
@Override
public void close() throws IOException {
mOutputStream.close();
InputStream is = null;
try {
// Status 400 and up should be read from error stream
// Expecting here 201 Create or 202 Accepted
if (mHttpCon.getResponseCode() >= 400) {
LOG.error("Failed to write data to Swift with error code: " + mHttpCon.getResponseCode());
is = mHttpCon.getErrorStream();
} else {
is = mHttpCon.getInputStream();
}
is.close();
} catch (Exception e) {
LOG.error(e.getMessage());
if (is != null) {
is.close();
}
}
mHttpCon.disconnect();
}
@Override
public void flush() throws IOException {
mOutputStream.flush();
}
}
| Improved comment style in SwiftOutputStream.java (#6899)
| underfs/swift/src/main/java/alluxio/underfs/swift/SwiftOutputStream.java | Improved comment style in SwiftOutputStream.java (#6899) | <ide><path>nderfs/swift/src/main/java/alluxio/underfs/swift/SwiftOutputStream.java
<ide> mOutputStream.close();
<ide> InputStream is = null;
<ide> try {
<del> // Status 400 and up should be read from error stream
<del> // Expecting here 201 Create or 202 Accepted
<add> // Status 400 and up should be read from error stream.
<add> // Expecting here 201 Create or 202 Accepted.
<ide> if (mHttpCon.getResponseCode() >= 400) {
<ide> LOG.error("Failed to write data to Swift with error code: " + mHttpCon.getResponseCode());
<ide> is = mHttpCon.getErrorStream(); |
|
Java | apache-2.0 | acc47c0e13a9a7dbd6028ed1ff33f1d4963cc6d2 | 0 | jaceksokol/postgres-async-driver | /*
* 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.github.pgasync.impl.protocol;
import com.github.pgasync.DatabaseConfig;
import com.github.pgasync.SqlException;
import com.github.pgasync.impl.NettyScheduler;
import com.github.pgasync.impl.message.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.*;
import rx.Observable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import static com.nurkiewicz.typeof.TypeOf.whenTypeOf;
import static rx.subscriptions.Subscriptions.create;
/**
* Protocol stream handler.
*
* @author Jacek Sokol
*/
public class ProtocolStream {
private static final Logger LOG = LoggerFactory.getLogger(ProtocolStream.class);
abstract class PgConsumer implements Consumer<Message> {
final String query;
PgConsumer(String query) {
this.query = query;
}
abstract void error(Throwable throwable);
void closeStream() {
LOG.warn("Closing channel due to premature cancellation [{}]", query);
subscribers.remove(this);
dirty = true;
ctx.channel().close();
}
}
abstract class ProtocolConsumer<T> extends PgConsumer {
final SingleSubscriber<T> subscriber;
final AtomicBoolean done = new AtomicBoolean();
@SuppressWarnings("unchecked")
ProtocolConsumer(SingleSubscriber<?> subscriber, String query) {
super(query);
this.subscriber = (SingleSubscriber<T>) subscriber;
subscriber.add(create(ProtocolConsumer.this::unsubscribe));
}
void complete(T value) {
if (!done.get()) {
done.set(true);
subscriber.onSuccess(value);
}
}
void complete() {
complete(null);
}
void error(Throwable throwable) {
done.set(true);
subscriber.onError(throwable);
}
void unsubscribe() {
if (!done.get()) closeStream();
}
}
abstract class StreamConsumer<T> extends PgConsumer {
final Emitter<T> subscriber;
final AtomicBoolean done = new AtomicBoolean();
@SuppressWarnings("unchecked")
StreamConsumer(Emitter<T> subscriber, String query) {
super(query);
this.subscriber = subscriber;
subscriber.setSubscription(create(StreamConsumer.this::unsubscribe));
}
void complete() {
if (!done.get()) {
done.set(true);
subscriber.onCompleted();
}
}
public void error(Throwable throwable) {
done.set(true);
subscriber.onError(throwable);
}
void unsubscribe() {
if (!done.get()) closeStream();
}
}
private final EventLoopGroup group;
private final DatabaseConfig config;
private final GenericFutureListener<Future<? super Object>> onError;
private final Queue<PgConsumer> subscribers = new LinkedBlockingDeque<>(); // TODO: limit pipeline queue depth
private final ConcurrentMap<String, List<StreamConsumer<String>>> listeners = new ConcurrentHashMap<>();
private ChannelHandlerContext ctx;
private boolean dirty;
private Scheduler scheduler;
public ProtocolStream(EventLoopGroup group, DatabaseConfig config) {
this.group = group;
this.config = config;
this.onError = future -> {
if (!future.isSuccess()) {
handleError(future.cause());
}
};
}
public Single<Authentication> connect(StartupMessage startup) {
return Single.create(subscriber -> {
ProtocolConsumer<Authentication> consumer = new ProtocolConsumer<Authentication>(subscriber, "CONNECT") {
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(e -> error(toSqlException(e)))
.is(ReadyForQuery.class).then(r -> complete(new Authentication(true, null)))
.is(Authentication.class).then(this::handleAuthRequest)
.orElse(m -> error(new SqlException("Unexpected message at startup stage: " + m)));
}
private void handleAuthRequest(Authentication auth) {
if (!auth.success()) {
subscribers.remove();
complete(auth);
}
}
};
subscribers.add(consumer);
InboundChannelInitializer inboundChannelInitializer = new InboundChannelInitializer(startup);
ProtocolHandler protocolHandler = new ProtocolHandler(subscribers, listeners, this::handleError);
new Bootstrap()
.group(group)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeout())
.channel(NioSocketChannel.class)
.handler(new ProtocolInitializer(config, inboundChannelInitializer, protocolHandler))
.connect(config.address())
.addListener(onError);
});
}
public Completable authenticate(PasswordMessage password) {
return Single
.create(subscriber -> {
ProtocolConsumer<Void> consumer = new ProtocolConsumer<Void>(subscriber, "AUTHENTICATE") {
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(e -> error(toSqlException(e)))
.is(Authentication.class).then(this::handleAuthResponse)
.is(ReadyForQuery.class).then(r -> complete());
}
private void handleAuthResponse(Authentication a) {
if (!a.success())
error(new SqlException("Failed to authenticate"));
}
};
subscribers.add(consumer);
write(password);
})
.subscribeOn(scheduler)
.toCompletable();
}
public Observable<Message> command(Message... messages) {
if (messages.length == 0)
return Observable.error(new IllegalArgumentException("No messages to send"));
else if (!isConnected())
return Observable.error(new IllegalStateException("Channel is closed [" + messages[0] + "]"));
return Observable.unsafeCreate(BackPressuredEmitter.<Message>create(emitter -> {
StreamConsumer<Message> consumer = new StreamConsumer<Message>(emitter, messages[0].toString()) {
SqlException exception;
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(this::handleError)
.is(ReadyForQuery.class).then(r -> handleReady())
.is(CommandComplete.class).then(this::handleCompletion)
.is(Message.class).then(emitter::onNext);
}
private void handleCompletion(CommandComplete commandComplete) {
enableAutoRead();
emitter.onNext(commandComplete);
}
private void handleReady() {
if (exception == null)
complete();
else
error(exception);
}
private void handleError(ErrorResponse e) {
exception = toSqlException(e);
enableAutoRead();
}
};
ensureInLoop(() -> {
subscribers.add(consumer);
write(messages);
disableAutoRead();
readNext();
});
}, this::readNext));
}
public Observable<String> listen(String channel) {
if (!isConnected())
return Observable.error(new IllegalStateException("Channel is closed [LISTEN]"));
return Observable.unsafeCreate(BackPressuredEmitter.<String>create(emitter -> {
StreamConsumer<String> consumer = new StreamConsumer<String>(emitter, "LISTEN") {
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(this::handleError)
.is(CommandComplete.class).then(commandComplete -> enableAutoRead())
.is(NotificationResponse.class).then(notificationResponse -> emitter.onNext(notificationResponse.payload()));
}
private void handleError(ErrorResponse e) {
emitter.onError(toSqlException(e));
enableAutoRead();
}
@Override
protected void unsubscribe() {
enableAutoRead();
ctx.executor().submit(() ->
Optional.of(listeners.get(channel)).ifPresent(list -> {
list.remove(this);
if (list.isEmpty())
listeners.remove(channel);
})
);
}
};
ensureInLoop(() -> {
List<StreamConsumer<String>> consumers = listeners.getOrDefault(channel, new LinkedList<>());
consumers.add(consumer);
listeners.put(channel, consumers);
disableAutoRead();
readNext();
});
}, this::readNext));
}
public boolean isConnected() {
return !dirty && Optional
.ofNullable(ctx)
.map(c -> c.channel().isOpen())
.orElse(false);
}
public Completable close() {
return Completable
.create(subscriber -> {
dirty = true;
handleError(new RuntimeException("Closing connection"));
ctx.writeAndFlush(Terminate.INSTANCE)
.addListener(closed -> {
if (closed.isSuccess())
subscriber.onCompleted();
else
subscriber.onError(closed.cause());
});
}
)
.subscribeOn(scheduler);
}
private void ensureInLoop(Runnable runnable) {
if (ctx.executor().inEventLoop())
runnable.run();
else
ctx.executor().submit(runnable);
}
private void write(Message... messages) {
for (Message message : messages) {
LOG.trace("Writing: {}", message);
ctx.write(message).addListener(onError);
}
ctx.flush();
}
private void readNext() {
ctx.channel().read();
}
private void enableAutoRead() {
ctx.channel().config().setAutoRead(true);
}
private void disableAutoRead() {
ctx.channel().config().setAutoRead(false);
}
private void handleError(Throwable throwable) {
if (!isConnected()) {
subscribers.forEach(subscriber -> subscriber.error(throwable));
subscribers.clear();
listeners.values().stream().flatMap(Collection::stream).forEach(consumer -> consumer.error(throwable));
listeners.clear();
} else
Optional.ofNullable(subscribers.poll()).ifPresent(s -> s.error(throwable));
dirty = true;
}
private SqlException toSqlException(ErrorResponse error) {
return new SqlException(error.level().name(), error.code(), error.message());
}
private class InboundChannelInitializer extends ChannelInboundHandlerAdapter {
private final StartupMessage startup;
InboundChannelInitializer(StartupMessage startup) {
this.startup = startup;
}
@Override
public void channelActive(ChannelHandlerContext context) {
ProtocolStream.this.ctx = context;
scheduler = NettyScheduler.forEventExecutor(ctx.executor());
if (config.useSsl())
write(SSLHandshake.INSTANCE);
else
writeStartupAndFixPipeline(context);
}
@Override
public void userEventTriggered(ChannelHandlerContext context, Object evt) {
whenTypeOf(evt).is(SslHandshakeCompletionEvent.class).then(e -> {
if (e.isSuccess())
writeStartupAndFixPipeline(context);
else
context.fireExceptionCaught(new SqlException("Failed to initialise SSL"));
});
}
private void writeStartupAndFixPipeline(ChannelHandlerContext context) {
write(startup);
context.pipeline().remove(this);
}
}
}
| src/main/java/com/github/pgasync/impl/protocol/ProtocolStream.java | /*
* 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.github.pgasync.impl.protocol;
import com.github.pgasync.DatabaseConfig;
import com.github.pgasync.SqlException;
import com.github.pgasync.impl.NettyScheduler;
import com.github.pgasync.impl.message.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.*;
import rx.Observable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import static com.nurkiewicz.typeof.TypeOf.whenTypeOf;
import static rx.subscriptions.Subscriptions.create;
/**
* Protocol stream handler.
*
* @author Jacek Sokol
*/
public class ProtocolStream {
private static final Logger LOG = LoggerFactory.getLogger(ProtocolStream.class);
abstract class PgConsumer implements Consumer<Message> {
final String query;
PgConsumer(String query) {
this.query = query;
}
abstract void error(Throwable throwable);
void closeStream() {
LOG.warn("Closing channel due to premature cancellation [{}]", query);
subscribers.remove(this);
dirty = true;
ctx.channel().close();
}
}
abstract class ProtocolConsumer<T> extends PgConsumer {
final SingleSubscriber<T> subscriber;
final AtomicBoolean done = new AtomicBoolean();
@SuppressWarnings("unchecked")
ProtocolConsumer(SingleSubscriber<?> subscriber, String query) {
super(query);
this.subscriber = (SingleSubscriber<T>) subscriber;
subscriber.add(create(ProtocolConsumer.this::unsubscribe));
}
void complete(T value) {
if (!done.get()) {
done.set(true);
subscriber.onSuccess(value);
}
}
void complete() {
complete(null);
}
void error(Throwable throwable) {
done.set(true);
subscriber.onError(throwable);
}
void unsubscribe() {
if (!done.get()) closeStream();
}
}
abstract class StreamConsumer<T> extends PgConsumer {
final Emitter<T> subscriber;
final AtomicBoolean done = new AtomicBoolean();
@SuppressWarnings("unchecked")
StreamConsumer(Emitter<T> subscriber, String query) {
super(query);
this.subscriber = subscriber;
subscriber.setSubscription(create(StreamConsumer.this::unsubscribe));
}
void complete() {
if (!done.get()) {
done.set(true);
subscriber.onCompleted();
}
}
public void error(Throwable throwable) {
done.set(true);
subscriber.onError(throwable);
}
void unsubscribe() {
if (!done.get()) closeStream();
}
}
private final EventLoopGroup group;
private final DatabaseConfig config;
private final GenericFutureListener<Future<? super Object>> onError;
private final Queue<PgConsumer> subscribers = new LinkedBlockingDeque<>(); // TODO: limit pipeline queue depth
private final ConcurrentMap<String, List<StreamConsumer<String>>> listeners = new ConcurrentHashMap<>();
private ChannelHandlerContext ctx;
private boolean dirty;
private Scheduler scheduler;
public ProtocolStream(EventLoopGroup group, DatabaseConfig config) {
this.group = group;
this.config = config;
this.onError = future -> {
if (!future.isSuccess()) {
handleError(future.cause());
}
};
}
public Single<Authentication> connect(StartupMessage startup) {
return Single.create(subscriber -> {
ProtocolConsumer<Authentication> consumer = new ProtocolConsumer<Authentication>(subscriber, "CONNECT") {
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(e -> error(toSqlException(e)))
.is(ReadyForQuery.class).then(r -> complete(new Authentication(true, null)))
.is(Authentication.class).then(this::handleAuthRequest)
.orElse(m -> error(new SqlException("Unexpected message at startup stage: " + m)));
}
private void handleAuthRequest(Authentication auth) {
if (!auth.success()) {
subscribers.remove();
complete(auth);
}
}
};
subscribers.add(consumer);
InboundChannelInitializer inboundChannelInitializer = new InboundChannelInitializer(startup);
ProtocolHandler protocolHandler = new ProtocolHandler(subscribers, listeners, this::handleError);
new Bootstrap()
.group(group)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeout())
.channel(NioSocketChannel.class)
.handler(new ProtocolInitializer(config, inboundChannelInitializer, protocolHandler))
.connect(config.address())
.addListener(onError);
});
}
public Completable authenticate(PasswordMessage password) {
return Single
.create(subscriber -> {
ProtocolConsumer<Void> consumer = new ProtocolConsumer<Void>(subscriber, "AUTHENTICATE") {
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(e -> error(toSqlException(e)))
.is(Authentication.class).then(this::handleAuthResponse)
.is(ReadyForQuery.class).then(r -> complete());
}
private void handleAuthResponse(Authentication a) {
if (!a.success())
error(new SqlException("Failed to authenticate"));
}
};
subscribers.add(consumer);
write(password);
})
.subscribeOn(scheduler)
.toCompletable();
}
public Observable<Message> command(Message... messages) {
if (messages.length == 0)
return Observable.error(new IllegalArgumentException("No messages to send"));
else if (!isConnected())
Observable.error(new IllegalStateException("Channel is closed [" + messages[0] + "]"));
return Observable.unsafeCreate(BackPressuredEmitter.<Message>create(emitter -> {
StreamConsumer<Message> consumer = new StreamConsumer<Message>(emitter, messages[0].toString()) {
SqlException exception;
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(this::handleError)
.is(ReadyForQuery.class).then(r -> handleReady())
.is(CommandComplete.class).then(this::handleCompletion)
.is(Message.class).then(emitter::onNext);
}
private void handleCompletion(CommandComplete commandComplete) {
enableAutoRead();
emitter.onNext(commandComplete);
}
private void handleReady() {
if (exception == null)
complete();
else
error(exception);
}
private void handleError(ErrorResponse e) {
exception = toSqlException(e);
enableAutoRead();
}
};
ensureInLoop(() -> {
subscribers.add(consumer);
write(messages);
disableAutoRead();
readNext();
});
}, this::readNext));
}
public Observable<String> listen(String channel) {
if (!isConnected())
Observable.error(new IllegalStateException("Channel is closed [LISTEN]"));
return Observable.unsafeCreate(BackPressuredEmitter.<String>create(emitter -> {
StreamConsumer<String> consumer = new StreamConsumer<String>(emitter, "LISTEN") {
@Override
public void accept(Message message) {
whenTypeOf(message)
.is(ErrorResponse.class).then(this::handleError)
.is(CommandComplete.class).then(commandComplete -> enableAutoRead())
.is(NotificationResponse.class).then(notificationResponse -> emitter.onNext(notificationResponse.payload()));
}
private void handleError(ErrorResponse e) {
emitter.onError(toSqlException(e));
enableAutoRead();
}
@Override
protected void unsubscribe() {
enableAutoRead();
ctx.executor().submit(() ->
Optional.of(listeners.get(channel)).ifPresent(list -> {
list.remove(this);
if (list.isEmpty())
listeners.remove(channel);
})
);
}
};
ensureInLoop(() -> {
List<StreamConsumer<String>> consumers = listeners.getOrDefault(channel, new LinkedList<>());
consumers.add(consumer);
listeners.put(channel, consumers);
disableAutoRead();
readNext();
});
}, this::readNext));
}
public boolean isConnected() {
return !dirty && Optional
.ofNullable(ctx)
.map(c -> c.channel().isOpen())
.orElse(false);
}
public Completable close() {
return Completable
.create(subscriber -> {
dirty = true;
handleError(new RuntimeException("Closing connection"));
ctx.writeAndFlush(Terminate.INSTANCE)
.addListener(closed -> {
if (closed.isSuccess())
subscriber.onCompleted();
else
subscriber.onError(closed.cause());
});
}
)
.subscribeOn(scheduler);
}
private void ensureInLoop(Runnable runnable) {
if (ctx.executor().inEventLoop())
runnable.run();
else
ctx.executor().submit(runnable);
}
private void write(Message... messages) {
for (Message message : messages) {
LOG.trace("Writing: {}", message);
ctx.write(message).addListener(onError);
}
ctx.flush();
}
private void readNext() {
ctx.channel().read();
}
private void enableAutoRead() {
ctx.channel().config().setAutoRead(true);
}
private void disableAutoRead() {
ctx.channel().config().setAutoRead(false);
}
private void handleError(Throwable throwable) {
if (!isConnected()) {
subscribers.forEach(subscriber -> subscriber.error(throwable));
subscribers.clear();
listeners.values().stream().flatMap(Collection::stream).forEach(consumer -> consumer.error(throwable));
listeners.clear();
} else
Optional.ofNullable(subscribers.poll()).ifPresent(s -> s.error(throwable));
dirty = true;
}
private SqlException toSqlException(ErrorResponse error) {
return new SqlException(error.level().name(), error.code(), error.message());
}
private class InboundChannelInitializer extends ChannelInboundHandlerAdapter {
private final StartupMessage startup;
InboundChannelInitializer(StartupMessage startup) {
this.startup = startup;
}
@Override
public void channelActive(ChannelHandlerContext context) {
ProtocolStream.this.ctx = context;
scheduler = NettyScheduler.forEventExecutor(ctx.executor());
if (config.useSsl())
write(SSLHandshake.INSTANCE);
else
writeStartupAndFixPipeline(context);
}
@Override
public void userEventTriggered(ChannelHandlerContext context, Object evt) {
whenTypeOf(evt).is(SslHandshakeCompletionEvent.class).then(e -> {
if (e.isSuccess())
writeStartupAndFixPipeline(context);
else
context.fireExceptionCaught(new SqlException("Failed to initialise SSL"));
});
}
private void writeStartupAndFixPipeline(ChannelHandlerContext context) {
write(startup);
context.pipeline().remove(this);
}
}
}
| Fix ProtocolStream
| src/main/java/com/github/pgasync/impl/protocol/ProtocolStream.java | Fix ProtocolStream | <ide><path>rc/main/java/com/github/pgasync/impl/protocol/ProtocolStream.java
<ide> if (messages.length == 0)
<ide> return Observable.error(new IllegalArgumentException("No messages to send"));
<ide> else if (!isConnected())
<del> Observable.error(new IllegalStateException("Channel is closed [" + messages[0] + "]"));
<add> return Observable.error(new IllegalStateException("Channel is closed [" + messages[0] + "]"));
<ide>
<ide> return Observable.unsafeCreate(BackPressuredEmitter.<Message>create(emitter -> {
<ide> StreamConsumer<Message> consumer = new StreamConsumer<Message>(emitter, messages[0].toString()) {
<ide>
<ide> public Observable<String> listen(String channel) {
<ide> if (!isConnected())
<del> Observable.error(new IllegalStateException("Channel is closed [LISTEN]"));
<add> return Observable.error(new IllegalStateException("Channel is closed [LISTEN]"));
<ide>
<ide> return Observable.unsafeCreate(BackPressuredEmitter.<String>create(emitter -> {
<ide> StreamConsumer<String> consumer = new StreamConsumer<String>(emitter, "LISTEN") { |
|
JavaScript | apache-2.0 | d8449d1a83828922ee151c538b581cf2e09c24ff | 0 | EchoAppsTeam/js-sdk,EchoAppsTeam/js-sdk | (function(jQuery) {
"use strict";
var $ = jQuery;
var canvas = Echo.Control.manifest("Echo.Canvas");
if (Echo.Control.isDefined(canvas)) return;
/**
* @class Echo.Canvas
* Class which implements Canvas mechanics on the client side.
* The instance of this class is created for each Canvas found on the page by
* the Echo.Loader. The instance of the class can also be created manually in
* case the Canvas data already exists on the page.
*
* @package environment.pack.js
*
* @extends Echo.Control
*
* @constructor
* Canvas object constructor to initialize the Echo.Canvas instance
*
* @param {Object} config
* Configuration options
*/
/** @hide @method getRelativeTime */
/** @hide @echo_label today */
/** @hide @echo_label yesterday */
/** @hide @echo_label lastWeek */
/** @hide @echo_label lastMonth */
/** @hide @echo_label secondAgo */
/** @hide @echo_label secondsAgo */
/** @hide @echo_label minuteAgo */
/** @hide @echo_label minutesAgo */
/** @hide @echo_label hourAgo */
/** @hide @echo_label hoursAgo */
/** @hide @echo_label dayAgo */
/** @hide @echo_label daysAgo */
/** @hide @echo_label weekAgo */
/** @hide @echo_label weeksAgo */
/** @hide @echo_label monthAgo */
/** @hide @echo_label monthsAgo */
/** @hide @echo_label loading */
/** @hide @echo_label retrying */
/** @hide @echo_label error_busy */
/** @hide @echo_label error_timeout */
/** @hide @echo_label error_waiting */
/** @hide @echo_label error_view_limit */
/** @hide @echo_label error_view_update_capacity_exceeded */
/** @hide @echo_label error_result_too_large */
/** @hide @echo_label error_wrong_query */
/** @hide @echo_label error_incorrect_appkey */
/** @hide @echo_label error_internal_error */
/** @hide @echo_label error_quota_exceeded */
/** @hide @echo_label error_incorrect_user_id */
/** @hide @echo_label error_unknown */
canvas.init = function() {
var ids, cssClass;
var self = this, target = this.config.get("target");
// parent init function takes care about init finalization (rendering
// and the "onReady" event firing)
var parent = $.proxy(this.parent, this);
// check if the canvas was already initialized
if (target.data("echo-canvas-initialized")) {
this._error({
"args": {"target": target},
"code": "canvas_already_initialized"
});
return;
}
// define initialized state for the canvas
// to prevent multiple initialization of the same canvas
target.data("echo-canvas-initialized", true);
// extending Canvas config with the parameters defined in the target
var overrides = this._getOverrides(target, ["id", "useSecureAPI", "mode"]);
if (!$.isEmptyObject(overrides)) {
this.config.extend(overrides);
}
// exit if no "id" is defined for the canvas,
// skip this validation in case the "data" is defined explicitly in the config
if (!this._isManuallyConfigured() && !this.config.get("id")) {
this._error({
"args": {"target": target},
"code": "invalid_canvas_config"
});
return;
}
// apply our canvas id as a CSS class if we aren't manually configured
if (this.config.get("id")) {
ids = this._getIds().normalized;
// adding a primary canvas ID and unique page identifier
// as a CSS class if provided
cssClass = Echo.Utils.foldl("", ["main", "unique"], function(type, acc) {
return (acc += ids[type] ? self.get("cssPrefix") + ids[type] + " " : "");
});
target.addClass(cssClass);
}
// fetch canvas config from remote storage
this._fetchConfig(function() {
if (self.get("data.backplane")) Backplane.init(this.get("data.backplane"));
self._loadAppResources(parent);
});
};
canvas.config = {
/**
* @cfg {String} [id]
* Unique ID of the Canvas, used by the Echo.Canvas instance
* to retrieve the data from the Canvases data storage.
*/
"id": "",
/**
* @cfg {Object} [data]
* Object which contains the Canvas data in the format
* used to store the Canvas config in the Canvas storage.
*/
"data": {},
/**
* @cfg {String} target(required)
* Specifies the DOM element where the control will be displayed.
*
* Note: if only the "target" config parameter is defined, the target DOM element
* should contain the following HTML attribute:
*
* + "data-canvas-id" with the unique Canvas ID which should be initialized
*
* The values of the HTML parameters override the "id" parameter value
* (respectively) passed via the Canvas config.
*/
/**
* @cfg {Object} [overrides]
* Object which contains the overrides applied for this Canvas on the page
* via Echo.Loader.override function call.
*/
"overrides": {},
/**
* @cfg {String} [mode]
* This parameter specifies the mode in which Canvas works.
* There are two possible values for this parameter:
*
* + "dev" - in this case the Canvas works with the development configuration storage
* + "prod" - in this case the Canvas works with the production configuration storage
*
* More information about defference between production and development configuration
* storages can be found in the ["How to deploy an App using a Canvas guide"](#!/guide/how_to_deploy_an_app_using_a_canvas)
*
* The value of this parameter can be overridden by specifying the "data-canvas-mode"
* target DOM element attribute.
* More information about HTML attributes of the target DOM element can be found [here](#!/guide/how_to_deploy_an_app_using_a_canvas)
*/
"mode": "dev"
};
canvas.vars = {
"apps": []
};
canvas.labels = {
/**
* @echo_label
*/
"error_no_apps": "No applications defined for this canvas",
/**
* @echo_label
*/
"error_no_config": "Unable to retrieve Canvas config",
/**
* @echo_label
*/
"error_no_suitable_app_class": "Unable to init an app, no suitable JS class found",
/**
* @echo_label
*/
"error_unable_to_retrieve_app_config": "Unable to retrieve Canvas config from the storage",
/**
* @echo_label
*/
"error_incomplete_app_config": "Unable to init an app, config is incomplete",
/**
* @echo_label
*/
"error_canvas_already_initialized": "Canvas has been initialized already",
/**
* @echo_label
*/
"error_invalid_canvas_config": "Canvas with invalid configuration found"
};
/**
* @echo_template
*/
canvas.templates.main =
'<div class="{class:container}"></div>';
/**
* @echo_template
*/
canvas.templates.app =
'<div class="{class:appContainer}">' +
'<div class="{class:appHeader}">{data:caption}</div>' +
'<div class="{class:appBody}"></div>' +
'</div>';
canvas.destroy = function() {
$.map(this.get("apps"), $.proxy(this._destroyApp, this));
this.config.get("target").data("echo-canvas-initialized", false);
};
/**
* @echo_renderer
*/
canvas.renderers.container = function(element) {
var self = this;
$.map(this.get("data.apps"), function(app, id) {
self._initApp(app, element, id);
});
return element;
};
canvas.methods._initApp = function(app, element, id) {
var self = this;
var Application = Echo.Utils.getComponent(app.component);
if (!Application) {
this._error({
"args": {"app": app},
"code": "no_suitable_app_class"
});
return;
}
app.id = app.id || id; // define app position in array as id if not specified
app.config = app.config || {};
app.config.canvasId = this.config.get('id');
var view = this.view.fork({
"renderer": null,
"renderers": {
"appHeader": function(element) {
// show|hide app header depending on the caption existance
return element[app.caption ? "show" : "hide"]();
},
"appBody": function(element) {
var className = self.get("cssPrefix") + "appId-" + app.id;
return element.addClass(className);
}
}
});
element.append(view.render({
"data": app,
"template": this.templates.app
}));
app.config.target = view.get("appBody");
var overrides = this.config.get("overrides")[app.id];
var config = overrides
? $.extend(true, app.config, overrides)
: app.config;
this.apps.push(new Application(config));
};
canvas.methods._destroyApp = function(app) {
if (app && $.isFunction(app.destroy)) app.destroy();
};
canvas.methods._isManuallyConfigured = function() {
return !$.isEmptyObject(this.get("data"));
};
canvas.methods._getAppScriptURL = function(config) {
if (!config.scripts) return config.script;
var isSecure, script = {
"dev": config.scripts.dev || config.scripts.prod,
"prod": config.scripts.prod || config.scripts.dev
}[Echo.Loader.isDebug() ? "dev" : "prod"];
if (typeof script === "string") return script;
isSecure = /^https/.test(window.location.protocol);
return script[isSecure ? "secure" : "regular"];
};
canvas.methods._loadAppResources = function(callback) {
var self = this, resources = [], isManual = this._isManuallyConfigured();
$.map(this.get("data.apps"), function(app) {
var script = self._getAppScriptURL(app);
if (!app.component || !script || !(isManual || app.id)) {
self._error({
"args": {"app": app},
"code": "incomplete_app_config"
});
return;
}
resources.push({
"url": script,
"loaded": function() {
return Echo.Control.isDefined(app.component);
}
});
});
Echo.Loader.download(resources, callback);
};
canvas.methods._getOverrides = function(target, spec) {
return Echo.Utils.foldl({}, spec || [], function(item, acc) {
// We should convert spec item to lower case because of jQuery
// HTML5 data attributes implementation http://api.jquery.com/data/#data-html5
// Since we have config keys in camel case representation like "useSecureAPI",
// we should follow to these rules.
var key = "canvas-" + item.toLowerCase();
var value = target.data(key);
if (typeof value !== "undefined") {
acc[item] = value;
}
});
};
canvas.methods._error = function(args) {
args.message = args.message || this.labels.get("error_" + args.code);
/**
* @echo_event Echo.Canvas.onError
* Event which is triggered in case of errors such as invalid configuration,
* problems fetching the data from the server side, etc.
*
* @param {String} topic
* Name of the event produced.
*
* @param {Object} data
* Object which contains debug information regarding the error.
*/
Echo.Events.publish({
"topic": "Echo.Canvas.onError",
"data": args
});
Echo.Utils.log($.extend(args, {"type": "error", "component": "Echo.Canvas"}));
if (args.renderError) {
this.showMessage({
"type": "error",
"message": args.message
});
}
};
canvas.methods._getIds = function() {
var id = this.config.get("id");
var parts = id.split("#");
var normalize = function(s) { return s.replace(/[^a-z\d]/ig, "-"); };
return {
"unique": id,
"main": parts[0],
"normalized": {
"unique": normalize(id),
"main": normalize(parts[0])
}
};
};
canvas.methods._fetchConfig = function(callback) {
var self = this, target = this.config.get("target");
var isManual = this._isManuallyConfigured();
// no need to perform server side request in case
// we already have all the data on the client side
if (isManual) {
callback.call(this);
return;
}
(new Echo.API.Request({
"apiBaseURL": Echo.Loader.config.storageURL[this.config.get("mode")],
"secure": this.config.get("useSecureAPI"),
// taking care of the Canvas unique identifier on the page,
// specified as "#XXX" in the Canvas ID. We don't need to send this
// unique page identifier, we send only the primary Canvas ID.
"endpoint": this._getIds().main,
"data": this.config.get("mode") === "dev" ? {"_": Math.random()} : {},
"onData": function(config) {
if (!config || !config.apps || !config.apps.length) {
var message = self.labels.get("error_no_" + (config ? "apps" : "config"));
self._error({
"args": {"config": config, "target": target},
"code": "invalid_canvas_config",
"renderError": true,
"message": message
});
return;
}
self.set("data", config); // store Canvas data into the instance
callback.call(self);
},
"onError": function(response) {
self._error({
"args": response,
"code": "unable_to_retrieve_app_config",
"renderError": true
});
}
})).request();
};
Echo.Control.create(canvas);
})(Echo.jQuery);
| src/canvas.js | (function(jQuery) {
"use strict";
var $ = jQuery;
var canvas = Echo.Control.manifest("Echo.Canvas");
if (Echo.Control.isDefined(canvas)) return;
/**
* @class Echo.Canvas
* Class which implements Canvas mechanics on the client side.
* The instance of this class is created for each Canvas found on the page by
* the Echo.Loader. The instance of the class can also be created manually in
* case the Canvas data already exists on the page.
*
* @package environment.pack.js
*
* @extends Echo.Control
*
* @constructor
* Canvas object constructor to initialize the Echo.Canvas instance
*
* @param {Object} config
* Configuration options
*/
/** @hide @method getRelativeTime */
/** @hide @echo_label today */
/** @hide @echo_label yesterday */
/** @hide @echo_label lastWeek */
/** @hide @echo_label lastMonth */
/** @hide @echo_label secondAgo */
/** @hide @echo_label secondsAgo */
/** @hide @echo_label minuteAgo */
/** @hide @echo_label minutesAgo */
/** @hide @echo_label hourAgo */
/** @hide @echo_label hoursAgo */
/** @hide @echo_label dayAgo */
/** @hide @echo_label daysAgo */
/** @hide @echo_label weekAgo */
/** @hide @echo_label weeksAgo */
/** @hide @echo_label monthAgo */
/** @hide @echo_label monthsAgo */
/** @hide @echo_label loading */
/** @hide @echo_label retrying */
/** @hide @echo_label error_busy */
/** @hide @echo_label error_timeout */
/** @hide @echo_label error_waiting */
/** @hide @echo_label error_view_limit */
/** @hide @echo_label error_view_update_capacity_exceeded */
/** @hide @echo_label error_result_too_large */
/** @hide @echo_label error_wrong_query */
/** @hide @echo_label error_incorrect_appkey */
/** @hide @echo_label error_internal_error */
/** @hide @echo_label error_quota_exceeded */
/** @hide @echo_label error_incorrect_user_id */
/** @hide @echo_label error_unknown */
canvas.init = function() {
var ids, cssClass;
var self = this, target = this.config.get("target");
// parent init function takes care about init finalization (rendering
// and the "onReady" event firing)
var parent = $.proxy(this.parent, this);
// check if the canvas was already initialized
if (target.data("echo-canvas-initialized")) {
this._error({
"args": {"target": target},
"code": "canvas_already_initialized"
});
return;
}
// define initialized state for the canvas
// to prevent multiple initialization of the same canvas
target.data("echo-canvas-initialized", true);
// extending Canvas config with the parameters defined in the target
var overrides = this._getOverrides(target, ["id", "useSecureAPI", "mode"]);
if (!$.isEmptyObject(overrides)) {
this.config.extend(overrides);
}
// exit if no "id" is defined for the canvas,
// skip this validation in case the "data" is defined explicitly in the config
if (!this._isManuallyConfigured() && !this.config.get("id")) {
this._error({
"args": {"target": target},
"code": "invalid_canvas_config"
});
return;
}
// apply our canvas id as a CSS class if we aren't manually configured
if (this.config.get("id")) {
ids = this._getIds().normalized;
// adding a primary canvas ID and unique page identifier
// as a CSS class if provided
cssClass = Echo.Utils.foldl("", ["main", "unique"], function(type, acc) {
return (acc += ids[type] ? self.get("cssPrefix") + ids[type] + " " : "");
});
target.addClass(cssClass);
}
// fetch canvas config from remove storage
this._fetchConfig(function() {
if (self.get("data.backplane")) Backplane.init(this.get("data.backplane"));
self._loadAppResources(parent);
});
};
canvas.config = {
/**
* @cfg {String} [id]
* Unique ID of the Canvas, used by the Echo.Canvas instance
* to retrieve the data from the Canvases data storage.
*/
"id": "",
/**
* @cfg {Object} [data]
* Object which contains the Canvas data in the format
* used to store the Canvas config in the Canvas storage.
*/
"data": {},
/**
* @cfg {String} target(required)
* Specifies the DOM element where the control will be displayed.
*
* Note: if only the "target" config parameter is defined, the target DOM element
* should contain the following HTML attribute:
*
* + "data-canvas-id" with the unique Canvas ID which should be initialized
*
* The values of the HTML parameters override the "id" parameter value
* (respectively) passed via the Canvas config.
*/
/**
* @cfg {Object} [overrides]
* Object which contains the overrides applied for this Canvas on the page
* via Echo.Loader.override function call.
*/
"overrides": {},
/**
* @cfg {String} [mode]
* This parameter specifies the mode in which Canvas works.
* There are two possible values for this parameter:
*
* + "dev" - in this case the Canvas works with the development configuration storage
* + "prod" - in this case the Canvas works with the production configuration storage
*
* More information about defference between production and development configuration
* storages can be found in the ["How to deploy an App using a Canvas guide"](#!/guide/how_to_deploy_an_app_using_a_canvas)
*
* The value of this parameter can be overridden by specifying the "data-canvas-mode"
* target DOM element attribute.
* More information about HTML attributes of the target DOM element can be found [here](#!/guide/how_to_deploy_an_app_using_a_canvas)
*/
"mode": "dev"
};
canvas.vars = {
"apps": []
};
canvas.labels = {
/**
* @echo_label
*/
"error_no_apps": "No applications defined for this canvas",
/**
* @echo_label
*/
"error_no_config": "Unable to retrieve Canvas config",
/**
* @echo_label
*/
"error_no_suitable_app_class": "Unable to init an app, no suitable JS class found",
/**
* @echo_label
*/
"error_unable_to_retrieve_app_config": "Unable to retrieve Canvas config from the storage",
/**
* @echo_label
*/
"error_incomplete_app_config": "Unable to init an app, config is incomplete",
/**
* @echo_label
*/
"error_canvas_already_initialized": "Canvas has been initialized already",
/**
* @echo_label
*/
"error_invalid_canvas_config": "Canvas with invalid configuration found"
};
/**
* @echo_template
*/
canvas.templates.main =
'<div class="{class:container}"></div>';
/**
* @echo_template
*/
canvas.templates.app =
'<div class="{class:appContainer}">' +
'<div class="{class:appHeader}">{data:caption}</div>' +
'<div class="{class:appBody}"></div>' +
'</div>';
canvas.destroy = function() {
$.map(this.get("apps"), $.proxy(this._destroyApp, this));
this.config.get("target").data("echo-canvas-initialized", false);
};
/**
* @echo_renderer
*/
canvas.renderers.container = function(element) {
var self = this;
$.map(this.get("data.apps"), function(app, id) {
self._initApp(app, element, id);
});
return element;
};
canvas.methods._initApp = function(app, element, id) {
var self = this;
var Application = Echo.Utils.getComponent(app.component);
if (!Application) {
this._error({
"args": {"app": app},
"code": "no_suitable_app_class"
});
return;
}
app.id = app.id || id; // define app position in array as id if not specified
app.config = app.config || {};
app.config.canvasId = this.config.get('id');
var view = this.view.fork({
"renderer": null,
"renderers": {
"appHeader": function(element) {
// show|hide app header depending on the caption existance
return element[app.caption ? "show" : "hide"]();
},
"appBody": function(element) {
var className = self.get("cssPrefix") + "appId-" + app.id;
return element.addClass(className);
}
}
});
element.append(view.render({
"data": app,
"template": this.templates.app
}));
app.config.target = view.get("appBody");
var overrides = this.config.get("overrides")[app.id];
var config = overrides
? $.extend(true, app.config, overrides)
: app.config;
this.apps.push(new Application(config));
};
canvas.methods._destroyApp = function(app) {
if (app && $.isFunction(app.destroy)) app.destroy();
};
canvas.methods._isManuallyConfigured = function() {
return !$.isEmptyObject(this.get("data"));
};
canvas.methods._getAppScriptURL = function(config) {
if (!config.scripts) return config.script;
var isSecure, script = {
"dev": config.scripts.dev || config.scripts.prod,
"prod": config.scripts.prod || config.scripts.dev
}[Echo.Loader.isDebug() ? "dev" : "prod"];
if (typeof script === "string") return script;
isSecure = /^https/.test(window.location.protocol);
return script[isSecure ? "secure" : "regular"];
};
canvas.methods._loadAppResources = function(callback) {
var self = this, resources = [], isManual = this._isManuallyConfigured();
$.map(this.get("data.apps"), function(app) {
var script = self._getAppScriptURL(app);
if (!app.component || !script || !(isManual || app.id)) {
self._error({
"args": {"app": app},
"code": "incomplete_app_config"
});
return;
}
resources.push({
"url": script,
"loaded": function() {
return Echo.Control.isDefined(app.component);
}
});
});
Echo.Loader.download(resources, callback);
};
canvas.methods._getOverrides = function(target, spec) {
return Echo.Utils.foldl({}, spec || [], function(item, acc) {
// We should convert spec item to lower case because of jQuery
// HTML5 data attributes implementation http://api.jquery.com/data/#data-html5
// Since we have config keys in camel case representation like "useSecureAPI",
// we should follow to these rules.
var key = "canvas-" + item.toLowerCase();
var value = target.data(key);
if (typeof value !== "undefined") {
acc[item] = value;
}
});
};
canvas.methods._error = function(args) {
args.message = args.message || this.labels.get("error_" + args.code);
/**
* @echo_event Echo.Canvas.onError
* Event which is triggered in case of errors such as invalid configuration,
* problems fetching the data from the server side, etc.
*
* @param {String} topic
* Name of the event produced.
*
* @param {Object} data
* Object which contains debug information regarding the error.
*/
Echo.Events.publish({
"topic": "Echo.Canvas.onError",
"data": args
});
Echo.Utils.log($.extend(args, {"type": "error", "component": "Echo.Canvas"}));
if (args.renderError) {
this.showMessage({
"type": "error",
"message": args.message
});
}
};
canvas.methods._getIds = function() {
var id = this.config.get("id");
var parts = id.split("#");
var normalize = function(s) { return s.replace(/[^a-z\d]/ig, "-"); };
return {
"unique": id,
"main": parts[0],
"normalized": {
"unique": normalize(id),
"main": normalize(parts[0])
}
};
};
canvas.methods._fetchConfig = function(callback) {
var self = this, target = this.config.get("target");
var isManual = this._isManuallyConfigured();
// no need to perform server side request in case
// we already have all the data on the client side
if (isManual) {
callback.call(this);
return;
}
(new Echo.API.Request({
"apiBaseURL": Echo.Loader.config.storageURL[this.config.get("mode")],
"secure": this.config.get("useSecureAPI"),
// taking care of the Canvas unique identifier on the page,
// specified as "#XXX" in the Canvas ID. We don't need to send this
// unique page identifier, we send only the primary Canvas ID.
"endpoint": this._getIds().main,
"data": this.config.get("mode") === "dev" ? {"_": Math.random()} : {},
"onData": function(config) {
if (!config || !config.apps || !config.apps.length) {
var message = self.labels.get("error_no_" + (config ? "apps" : "config"));
self._error({
"args": {"config": config, "target": target},
"code": "invalid_canvas_config",
"renderError": true,
"message": message
});
return;
}
self.set("data", config); // store Canvas data into the instance
callback.call(self);
},
"onError": function(response) {
self._error({
"args": response,
"code": "unable_to_retrieve_app_config",
"renderError": true
});
}
})).request();
};
Echo.Control.create(canvas);
})(Echo.jQuery);
| Typo fixed
| src/canvas.js | Typo fixed | <ide><path>rc/canvas.js
<ide> target.addClass(cssClass);
<ide> }
<ide>
<del> // fetch canvas config from remove storage
<add> // fetch canvas config from remote storage
<ide> this._fetchConfig(function() {
<ide> if (self.get("data.backplane")) Backplane.init(this.get("data.backplane"));
<ide> self._loadAppResources(parent); |
|
Java | apache-2.0 | ad3b6affb492f55405e29038f0adb745bd19315a | 0 | dslomov/intellij-community,samthor/intellij-community,semonte/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,robovm/robovm-studio,ibinti/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,apixandru/intellij-community,jagguli/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,robovm/robovm-studio,signed/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,asedunov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,kdwink/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,adedayo/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,caot/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,fitermay/intellij-community,da1z/intellij-community,ryano144/intellij-community,apixandru/intellij-community,jagguli/intellij-community,asedunov/intellij-community,petteyg/intellij-community,slisson/intellij-community,akosyakov/intellij-community,supersven/intellij-community,tmpgit/intellij-community,kool79/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,slisson/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,allotria/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,diorcety/intellij-community,ibinti/intellij-community,holmes/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,caot/intellij-community,blademainer/intellij-community,semonte/intellij-community,fitermay/intellij-community,hurricup/intellij-community,retomerz/intellij-community,dslomov/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,adedayo/intellij-community,slisson/intellij-community,fitermay/intellij-community,jagguli/intellij-community,allotria/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,diorcety/intellij-community,ryano144/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,tmpgit/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,caot/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,apixandru/intellij-community,izonder/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,robovm/robovm-studio,hurricup/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,da1z/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,signed/intellij-community,dslomov/intellij-community,vladmm/intellij-community,kdwink/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,kdwink/intellij-community,adedayo/intellij-community,blademainer/intellij-community,signed/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,vladmm/intellij-community,apixandru/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,allotria/intellij-community,izonder/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,semonte/intellij-community,blademainer/intellij-community,kool79/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,kool79/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,signed/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fnouama/intellij-community,kdwink/intellij-community,supersven/intellij-community,signed/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,caot/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,semonte/intellij-community,ahb0327/intellij-community,semonte/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,allotria/intellij-community,samthor/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,supersven/intellij-community,supersven/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,slisson/intellij-community,allotria/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,jagguli/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,supersven/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,signed/intellij-community,orekyuu/intellij-community,holmes/intellij-community,clumsy/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,signed/intellij-community,kool79/intellij-community,youdonghai/intellij-community,semonte/intellij-community,supersven/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,dslomov/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,allotria/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,holmes/intellij-community,retomerz/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,asedunov/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,semonte/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,fitermay/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,vladmm/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,allotria/intellij-community,ibinti/intellij-community,allotria/intellij-community,kool79/intellij-community,supersven/intellij-community,da1z/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,fitermay/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,ryano144/intellij-community,xfournet/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,ahb0327/intellij-community,semonte/intellij-community,adedayo/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,da1z/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,fnouama/intellij-community,xfournet/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,robovm/robovm-studio,fnouama/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,clumsy/intellij-community,semonte/intellij-community,samthor/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,caot/intellij-community,retomerz/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,signed/intellij-community,allotria/intellij-community,izonder/intellij-community,petteyg/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,da1z/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,apixandru/intellij-community,hurricup/intellij-community,FHannes/intellij-community,izonder/intellij-community,slisson/intellij-community,vladmm/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,FHannes/intellij-community,robovm/robovm-studio,amith01994/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,asedunov/intellij-community,kool79/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,slisson/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,dslomov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,petteyg/intellij-community,ibinti/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,slisson/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,supersven/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,kool79/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,caot/intellij-community,blademainer/intellij-community,amith01994/intellij-community,dslomov/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,xfournet/intellij-community,robovm/robovm-studio,apixandru/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,caot/intellij-community,holmes/intellij-community,supersven/intellij-community,nicolargo/intellij-community,caot/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ryano144/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,holmes/intellij-community,fnouama/intellij-community,fnouama/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,kdwink/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.skeletons;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.execution.ExecutionException;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.ZipUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil;
import com.jetbrains.python.packaging.PyExternalProcessException;
import com.jetbrains.python.packaging.PyPackageManager;
import com.jetbrains.python.packaging.PyPackageManagerImpl;
import com.jetbrains.python.psi.resolve.PythonSdkPathCache;
import com.jetbrains.python.remote.PythonRemoteInterpreterManager;
import com.jetbrains.python.sdk.InvalidSdkException;
import com.jetbrains.python.sdk.PySdkUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.jetbrains.python.sdk.skeletons.SkeletonVersionChecker.fromVersionString;
/**
* Handles a refresh of SDK's skeletons.
* Does all the heavy lifting calling skeleton generator, managing blacklists, etc.
* One-time, non-reusable instances.
* <br/>
* User: dcheryasov
* Date: 4/15/11 5:38 PM
*/
public class PySkeletonRefresher {
private static final Logger LOG = Logger.getInstance("#" + PySkeletonRefresher.class.getName());
@Nullable private Project myProject;
private @Nullable final ProgressIndicator myIndicator;
@NotNull private final Sdk mySdk;
private String mySkeletonsPath;
@NonNls public static final String BLACKLIST_FILE_NAME = ".blacklist";
private final static Pattern BLACKLIST_LINE = Pattern.compile("^([^=]+) = (\\d+\\.\\d+) (\\d+)\\s*$");
// we use the equals sign after filename so that we can freely include space in the filename
// Path (the first component) may contain spaces, this header spec is deprecated
private static final Pattern VERSION_LINE_V1 = Pattern.compile("# from (\\S+) by generator (\\S+)\\s*");
// Skeleton header spec v2
private static final Pattern FROM_LINE_V2 = Pattern.compile("# from (.*)$");
private static final Pattern BY_LINE_V2 = Pattern.compile("# by generator (.*)$");
private static int ourGeneratingCount = 0;
private String myExtraSyspath;
private VirtualFile myPregeneratedSkeletons;
private int myGeneratorVersion;
private Map<String, Pair<Integer, Long>> myBlacklist;
private SkeletonVersionChecker myVersionChecker;
private PySkeletonGenerator mySkeletonsGenerator;
public static synchronized boolean isGeneratingSkeletons() {
return ourGeneratingCount > 0;
}
private static synchronized void changeGeneratingSkeletons(int increment) {
ourGeneratingCount += increment;
}
public static void refreshSkeletonsOfSdk(@Nullable Project project,
Component ownerComponent,
String skeletonsPath,
@Nullable Ref<Boolean> migrationFlag,
@NotNull Sdk sdk)
throws InvalidSdkException {
final Map<String, List<String>> errors = new TreeMap<String, List<String>>();
final List<String> failedSdks = new SmartList<String>();
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
final String homePath = sdk.getHomePath();
if (skeletonsPath == null) {
LOG.info("Could not find skeletons path for SDK path " + homePath);
}
else {
LOG.info("Refreshing skeletons for " + homePath);
SkeletonVersionChecker checker = new SkeletonVersionChecker(0); // this default version won't be used
final PySkeletonRefresher refresher = new PySkeletonRefresher(project, ownerComponent, sdk, skeletonsPath, indicator, null);
changeGeneratingSkeletons(1);
try {
List<String> sdkErrors = refresher.regenerateSkeletons(checker, migrationFlag);
if (sdkErrors.size() > 0) {
String sdkName = sdk.getName();
List<String> knownErrors = errors.get(sdkName);
if (knownErrors == null) {
errors.put(sdkName, sdkErrors);
}
else {
knownErrors.addAll(sdkErrors);
}
}
}
finally {
changeGeneratingSkeletons(-1);
}
}
if (failedSdks.size() > 0 || errors.size() > 0) {
int module_errors = 0;
for (String sdk_name : errors.keySet()) module_errors += errors.get(sdk_name).size();
String message;
if (failedSdks.size() > 0) {
message = PyBundle.message("sdk.errorlog.$0.mods.fail.in.$1.sdks.$2.completely", module_errors, errors.size(), failedSdks.size());
}
else {
message = PyBundle.message("sdk.errorlog.$0.mods.fail.in.$1.sdks", module_errors, errors.size());
}
logErrors(errors, failedSdks, message);
}
}
private static void logErrors(@NotNull final Map<String, List<String>> errors, @NotNull final List<String> failedSdks,
@NotNull final String message) {
LOG.warn(PyBundle.message("sdk.some.skeletons.failed"));
LOG.warn(message);
if (failedSdks.size() > 0) {
LOG.warn(PyBundle.message("sdk.error.dialog.failed.sdks"));
LOG.warn(StringUtil.join(failedSdks, ", "));
}
if (errors.size() > 0) {
LOG.warn(PyBundle.message("sdk.error.dialog.failed.modules"));
for (String sdkName : errors.keySet()) {
for (String moduleName : errors.get(sdkName)) {
LOG.warn(moduleName);
}
}
}
}
/**
* Creates a new object that refreshes skeletons of given SDK.
*
* @param sdk a Python SDK
* @param skeletonsPath if known; null means 'determine and create as needed'.
* @param indicator to report progress of long operations
*/
public PySkeletonRefresher(@Nullable Project project,
@Nullable Component ownerComponent,
@NotNull Sdk sdk,
@Nullable String skeletonsPath,
@Nullable ProgressIndicator indicator,
@Nullable String folder)
throws InvalidSdkException {
myProject = project;
myIndicator = indicator;
mySdk = sdk;
mySkeletonsPath = skeletonsPath;
final PythonRemoteInterpreterManager remoteInterpreterManager = PythonRemoteInterpreterManager.getInstance();
if (PySdkUtil.isRemote(sdk) && remoteInterpreterManager != null) {
try {
mySkeletonsGenerator = remoteInterpreterManager.createRemoteSkeletonGenerator(myProject, ownerComponent, sdk, getSkeletonsPath());
}
catch (ExecutionException e) {
throw new InvalidSdkException(e.getMessage(), e.getCause());
}
}
else {
mySkeletonsGenerator = new PySkeletonGenerator(getSkeletonsPath(), mySdk, folder);
}
}
private void indicate(String msg) {
if (myIndicator != null) {
myIndicator.checkCanceled();
myIndicator.setText(msg);
myIndicator.setText2("");
}
}
private void indicateMinor(String msg) {
if (myIndicator != null) {
myIndicator.setText2(msg);
}
}
private void checkCanceled() {
if (myIndicator != null) {
myIndicator.checkCanceled();
}
}
private static String calculateExtraSysPath(@NotNull final Sdk sdk, @Nullable final String skeletonsPath) {
final File skeletons = skeletonsPath != null ? new File(skeletonsPath) : null;
final VirtualFile userSkeletonsDir = PyUserSkeletonsUtil.getUserSkeletonsDirectory();
final File userSkeletons = userSkeletonsDir != null ? new File(userSkeletonsDir.getPath()) : null;
final VirtualFile remoteSourcesDir = PySdkUtil.findAnyRemoteLibrary(sdk);
final File remoteSources = remoteSourcesDir != null ? new File(remoteSourcesDir.getPath()) : null;
final VirtualFile[] classDirs = sdk.getRootProvider().getFiles(OrderRootType.CLASSES);
return Joiner.on(File.pathSeparator).join(ContainerUtil.mapNotNull(classDirs, new Function<VirtualFile, Object>() {
@Override
public Object fun(VirtualFile file) {
if (file.isInLocalFileSystem()) {
// We compare canonical files, not strings because "c:/some/folder" equals "c:\\some\\bin\\..\\folder\\"
final File canonicalFile = new File(file.getPath());
if (canonicalFile.exists() &&
!FileUtil.filesEqual(canonicalFile, skeletons) &&
!FileUtil.filesEqual(canonicalFile, userSkeletons) &&
!FileUtil.filesEqual(canonicalFile, remoteSources)) {
return file.getPath();
}
}
return null;
}
}));
}
/**
* Creates if needed all path(s) used to store skeletons of its SDK.
*
* @return path name of skeleton dir for the SDK, guaranteed to be already created.
*/
@NotNull
public String getSkeletonsPath() throws InvalidSdkException {
if (mySkeletonsPath == null) {
mySkeletonsPath = PythonSdkType.getSkeletonsPath(PathManager.getSystemPath(), mySdk.getHomePath());
final File skeletonsDir = new File(mySkeletonsPath);
if (!skeletonsDir.exists() && !skeletonsDir.mkdirs()) {
throw new InvalidSdkException("Can't create skeleton dir " + String.valueOf(mySkeletonsPath));
}
}
return mySkeletonsPath;
}
public List<String> regenerateSkeletons(@Nullable SkeletonVersionChecker cachedChecker,
@Nullable Ref<Boolean> migrationFlag) throws InvalidSdkException {
final List<String> errorList = new SmartList<String>();
final String homePath = mySdk.getHomePath();
final String skeletonsPath = getSkeletonsPath();
final File skeletonsDir = new File(skeletonsPath);
if (!skeletonsDir.exists()) {
//noinspection ResultOfMethodCallIgnored
skeletonsDir.mkdirs();
}
final String readablePath = FileUtil.getLocationRelativeToUserHome(homePath);
mySkeletonsGenerator.prepare();
myBlacklist = loadBlacklist();
indicate(PyBundle.message("sdk.gen.querying.$0", readablePath));
// get generator version and binary libs list in one go
final PySkeletonGenerator.ListBinariesResult binaries =
mySkeletonsGenerator.listBinaries(mySdk, calculateExtraSysPath(mySdk, getSkeletonsPath()));
myGeneratorVersion = binaries.generatorVersion;
myPregeneratedSkeletons = findPregeneratedSkeletons();
indicate(PyBundle.message("sdk.gen.reading.versions.file"));
if (cachedChecker != null) {
myVersionChecker = cachedChecker.withDefaultVersionIfUnknown(myGeneratorVersion);
}
else {
myVersionChecker = new SkeletonVersionChecker(myGeneratorVersion);
}
// check builtins
final String builtinsFileName = PythonSdkType.getBuiltinsFileName(mySdk);
final File builtinsFile = new File(skeletonsPath, builtinsFileName);
final SkeletonHeader oldHeader = readSkeletonHeader(builtinsFile);
final boolean oldOrNonExisting = oldHeader == null || oldHeader.getVersion() == 0;
if (migrationFlag != null && !migrationFlag.get() && oldOrNonExisting) {
migrationFlag.set(true);
Notifications.Bus.notify(
new Notification(
PythonSdkType.SKELETONS_TOPIC, PyBundle.message("sdk.gen.notify.converting.old.skels"),
PyBundle.message("sdk.gen.notify.converting.text"),
NotificationType.INFORMATION
)
);
}
if (myPregeneratedSkeletons != null && oldOrNonExisting) {
indicate("Unpacking pregenerated skeletons...");
try {
final VirtualFile jar = JarFileSystem.getInstance().getVirtualFileForJar(myPregeneratedSkeletons);
if (jar != null) {
ZipUtil.extract(new File(jar.getPath()),
new File(getSkeletonsPath()), null);
}
}
catch (IOException e) {
LOG.info("Error unpacking pregenerated skeletons", e);
}
}
if (oldOrNonExisting) {
final Sdk base = PythonSdkType.getInstance().getVirtualEnvBaseSdk(mySdk);
if (base != null) {
indicate("Copying base SDK skeletons for virtualenv...");
final String baseSkeletonsPath = PythonSdkType.getSkeletonsPath(PathManager.getSystemPath(), base.getHomePath());
final PySkeletonGenerator.ListBinariesResult baseBinaries =
mySkeletonsGenerator.listBinaries(base, calculateExtraSysPath(base, baseSkeletonsPath));
for (Map.Entry<String, PyBinaryItem> entry : binaries.modules.entrySet()) {
final String module = entry.getKey();
final PyBinaryItem binary = entry.getValue();
final PyBinaryItem baseBinary = baseBinaries.modules.get(module);
final File fromFile = getSkeleton(module, baseSkeletonsPath);
if (baseBinaries.modules.containsKey(module) &&
fromFile.exists() &&
binary.length() == baseBinary.length()) { // Weak binary modules equality check
final File toFile = fromFile.isDirectory() ?
getPackageSkeleton(module, skeletonsPath) :
getModuleSkeleton(module, skeletonsPath);
try {
FileUtil.copy(fromFile, toFile);
}
catch (IOException e) {
LOG.info("Error copying base virtualenv SDK skeleton for " + module, e);
}
}
}
}
}
final SkeletonHeader newHeader = readSkeletonHeader(builtinsFile);
final boolean mustUpdateBuiltins = myPregeneratedSkeletons == null &&
(newHeader == null || newHeader.getVersion() < myVersionChecker.getBuiltinVersion());
if (mustUpdateBuiltins) {
indicate(PyBundle.message("sdk.gen.updating.builtins.$0", readablePath));
mySkeletonsGenerator.generateBuiltinSkeletons(mySdk);
if (myProject != null) {
PythonSdkPathCache.getInstance(myProject, mySdk).clearBuiltins();
}
}
if (!binaries.modules.isEmpty()) {
indicate(PyBundle.message("sdk.gen.updating.$0", readablePath));
List<UpdateResult> updateErrors = updateOrCreateSkeletons(binaries.modules); //Skeletons regeneration
if (updateErrors.size() > 0) {
indicateMinor(BLACKLIST_FILE_NAME);
for (UpdateResult error : updateErrors) {
if (error.isFresh()) errorList.add(error.getName());
myBlacklist.put(error.getPath(), new Pair<Integer, Long>(myGeneratorVersion, error.getTimestamp()));
}
storeBlacklist(skeletonsDir, myBlacklist);
}
else {
removeBlacklist(skeletonsDir);
}
}
indicate(PyBundle.message("sdk.gen.reloading"));
mySkeletonsGenerator.refreshGeneratedSkeletons();
if (!oldOrNonExisting) {
indicate(PyBundle.message("sdk.gen.cleaning.$0", readablePath));
cleanUpSkeletons(skeletonsDir);
}
if (PySdkUtil.isRemote(mySdk)) {
try {
((PyPackageManagerImpl)PyPackageManager.getInstance(mySdk)).loadPackages();
}
catch (PyExternalProcessException e) {
// ignore - already logged
}
}
if ((mustUpdateBuiltins || PySdkUtil.isRemote(mySdk)) && myProject != null) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
DaemonCodeAnalyzer.getInstance(myProject).restart();
}
}, myProject.getDisposed());
}
return errorList;
}
@Nullable
public static SkeletonHeader readSkeletonHeader(@NotNull File file) {
try {
final LineNumberReader reader = new LineNumberReader(new FileReader(file));
try {
String line = null;
// Read 3 lines, skip first 2: encoding, module name
for (int i = 0; i < 3; i++) {
line = reader.readLine();
if (line == null) {
return null;
}
}
// Try the old whitespace-unsafe header format v1 first
final Matcher v1Matcher = VERSION_LINE_V1.matcher(line);
if (v1Matcher.matches()) {
return new SkeletonHeader(v1Matcher.group(1), fromVersionString(v1Matcher.group(2)));
}
final Matcher fromMatcher = FROM_LINE_V2.matcher(line);
if (fromMatcher.matches()) {
final String binaryFile = fromMatcher.group(1);
line = reader.readLine();
if (line != null) {
final Matcher byMatcher = BY_LINE_V2.matcher(line);
if (byMatcher.matches()) {
final int version = fromVersionString(byMatcher.group(1));
return new SkeletonHeader(binaryFile, version);
}
}
}
}
finally {
reader.close();
}
}
catch (IOException ignored) {
}
return null;
}
public static class SkeletonHeader {
@NotNull private final String myFile;
private final int myVersion;
public SkeletonHeader(@NotNull String binaryFile, int version) {
myFile = binaryFile;
myVersion = version;
}
@NotNull
public String getBinaryFile() {
return myFile;
}
public int getVersion() {
return myVersion;
}
}
private Map<String, Pair<Integer, Long>> loadBlacklist() {
Map<String, Pair<Integer, Long>> ret = new HashMap<String, Pair<Integer, Long>>();
File blacklistFile = new File(mySkeletonsPath, BLACKLIST_FILE_NAME);
if (blacklistFile.exists() && blacklistFile.canRead()) {
Reader input;
try {
input = new FileReader(blacklistFile);
LineNumberReader lines = new LineNumberReader(input);
try {
String line;
do {
line = lines.readLine();
if (line != null && line.length() > 0 && line.charAt(0) != '#') { // '#' begins a comment
Matcher matcher = BLACKLIST_LINE.matcher(line);
boolean notParsed = true;
if (matcher.matches()) {
final int version = fromVersionString(matcher.group(2));
if (version > 0) {
try {
final long timestamp = Long.parseLong(matcher.group(3));
final String filename = matcher.group(1);
ret.put(filename, new Pair<Integer, Long>(version, timestamp));
notParsed = false;
}
catch (NumberFormatException ignore) {
}
}
}
if (notParsed) LOG.warn("In blacklist at " + mySkeletonsPath + " strange line '" + line + "'");
}
}
while (line != null);
}
catch (IOException ex) {
LOG.warn("Failed to read blacklist in " + mySkeletonsPath, ex);
}
finally {
lines.close();
}
}
catch (IOException ignore) {
}
}
return ret;
}
private static void storeBlacklist(File skeletonDir, Map<String, Pair<Integer, Long>> blacklist) {
File blacklistFile = new File(skeletonDir, BLACKLIST_FILE_NAME);
PrintWriter output;
try {
output = new PrintWriter(blacklistFile);
try {
output.println("# PyCharm failed to generate skeletons for these modules.");
output.println("# These skeletons will be re-generated automatically");
output.println("# when a newer module version or an updated generator becomes available.");
// each line: filename = version.string timestamp
for (String fname : blacklist.keySet()) {
Pair<Integer, Long> data = blacklist.get(fname);
output.print(fname);
output.print(" = ");
output.print(SkeletonVersionChecker.toVersionString(data.getFirst()));
output.print(" ");
output.print(data.getSecond());
output.println();
}
}
finally {
output.close();
}
}
catch (IOException ex) {
LOG.warn("Failed to store blacklist in " + skeletonDir.getPath(), ex);
}
}
private static void removeBlacklist(File skeletonDir) {
File blacklistFile = new File(skeletonDir, BLACKLIST_FILE_NAME);
if (blacklistFile.exists()) {
boolean okay = blacklistFile.delete();
if (!okay) LOG.warn("Could not delete blacklist file in " + skeletonDir.getPath());
}
}
/**
* For every existing skeleton file, take its module file name,
* and remove the skeleton if the module file does not exist.
* Works recursively starting from dir. Removes dirs that become empty.
*/
private void cleanUpSkeletons(final File dir) {
indicateMinor(dir.getPath());
final File[] files = dir.listFiles();
if (files == null) {
return;
}
for (File item : files) {
if (item.isDirectory()) {
cleanUpSkeletons(item);
// was the dir emptied?
File[] remaining = item.listFiles();
if (remaining != null && remaining.length == 0) {
mySkeletonsGenerator.deleteOrLog(item);
}
else if (remaining != null && remaining.length == 1) { //clean also if contains only __init__.py
File lastFile = remaining[0];
if (PyNames.INIT_DOT_PY.equals(lastFile.getName()) && lastFile.length() == 0) {
boolean deleted = mySkeletonsGenerator.deleteOrLog(lastFile);
if (deleted) mySkeletonsGenerator.deleteOrLog(item);
}
}
}
else if (item.isFile()) {
// clean up an individual file
final String itemName = item.getName();
if (PyNames.INIT_DOT_PY.equals(itemName) && item.length() == 0) continue; // these are versionless
if (BLACKLIST_FILE_NAME.equals(itemName)) continue; // don't touch the blacklist
if (PythonSdkType.getBuiltinsFileName(mySdk).equals(itemName)) {
continue;
}
final SkeletonHeader header = readSkeletonHeader(item);
boolean canLive = header != null;
if (canLive) {
final String binaryFile = header.getBinaryFile();
canLive = SkeletonVersionChecker.BUILTIN_NAME.equals(binaryFile) || mySkeletonsGenerator.exists(binaryFile);
}
if (!canLive) {
mySkeletonsGenerator.deleteOrLog(item);
}
}
}
}
private static class UpdateResult {
private final String myPath;
private final String myName;
private final long myTimestamp;
public boolean isFresh() {
return myIsFresh;
}
private final boolean myIsFresh;
private UpdateResult(String name, String path, long timestamp, boolean fresh) {
myName = name;
myPath = path;
myTimestamp = timestamp;
myIsFresh = fresh;
}
public String getName() {
return myName;
}
public String getPath() {
return myPath;
}
public Long getTimestamp() {
return myTimestamp;
}
}
/**
* (Re-)generates skeletons for all binary python modules. Up-to-date skeletons are not regenerated.
* Does one module at a time: slower, but avoids certain conflicts.
*
* @param modules output of generator3 -L
* @return blacklist data; whatever was not generated successfully is put here.
*/
private List<UpdateResult> updateOrCreateSkeletons(Map<String, PyBinaryItem> modules) throws InvalidSdkException {
long startTime = System.currentTimeMillis();
final List<String> names = Lists.newArrayList(modules.keySet());
Collections.sort(names);
final List<UpdateResult> results = new ArrayList<UpdateResult>();
final int count = names.size();
for (int i = 0; i < count; i++) {
checkCanceled();
if (myIndicator != null) {
myIndicator.setFraction((double)i / count);
}
final String name = names.get(i);
final PyBinaryItem module = modules.get(name);
if (module != null) {
updateOrCreateSkeleton(module, results);
}
}
finishSkeletonsGeneration();
long doneInMs = System.currentTimeMillis() - startTime;
LOG.info("Rebuilding skeletons for binaries took " + doneInMs + " ms");
return results;
}
private void finishSkeletonsGeneration() {
mySkeletonsGenerator.finishSkeletonsGeneration();
}
private static File getSkeleton(String moduleName, String skeletonsPath) {
final File module = getModuleSkeleton(moduleName, skeletonsPath);
return module.exists() ? module : getPackageSkeleton(moduleName, skeletonsPath);
}
private static File getModuleSkeleton(String module, String skeletonsPath) {
final String modulePath = module.replace('.', '/');
return new File(skeletonsPath, modulePath + ".py");
}
private static File getPackageSkeleton(String pkg, String skeletonsPath) {
final String packagePath = pkg.replace('.', '/');
return new File(new File(skeletonsPath, packagePath), PyNames.INIT_DOT_PY);
}
private boolean updateOrCreateSkeleton(final PyBinaryItem binaryItem,
final List<UpdateResult> errorList) throws InvalidSdkException {
final String moduleName = binaryItem.getModule();
final File skeleton = getSkeleton(moduleName, getSkeletonsPath());
final SkeletonHeader header = readSkeletonHeader(skeleton);
boolean mustRebuild = true; // guilty unless proven fresh enough
if (header != null) {
int requiredVersion = myVersionChecker.getRequiredVersion(moduleName);
mustRebuild = header.getVersion() < requiredVersion;
}
if (!mustRebuild) { // ...but what if the lib was updated?
mustRebuild = (skeleton.exists() && binaryItem.lastModified() > skeleton.lastModified());
// really we can omit both exists() calls but I keep these to make the logic clear
}
if (myBlacklist != null) {
Pair<Integer, Long> versionInfo = myBlacklist.get(binaryItem.getPath());
if (versionInfo != null) {
int failedGeneratorVersion = versionInfo.getFirst();
long failedTimestamp = versionInfo.getSecond();
mustRebuild &= failedGeneratorVersion < myGeneratorVersion || failedTimestamp < binaryItem.lastModified();
if (!mustRebuild) { // we're still failing to rebuild, it, keep it in blacklist
errorList.add(new UpdateResult(moduleName, binaryItem.getPath(), binaryItem.lastModified(), false));
}
}
}
if (mustRebuild) {
indicateMinor(moduleName);
if (myPregeneratedSkeletons != null && copyPregeneratedSkeleton(moduleName)) {
return true;
}
LOG.info("Skeleton for " + moduleName);
generateSkeleton(moduleName, binaryItem.getPath(), null, new Consumer<Boolean>() {
@Override
public void consume(Boolean generated) {
if (!generated) {
errorList.add(new UpdateResult(moduleName, binaryItem.getPath(), binaryItem.lastModified(), true));
}
}
});
}
return false;
}
public static class PyBinaryItem {
private String myPath;
private String myModule;
private long myLength;
private long myLastModified;
PyBinaryItem(String module, String path, long length, long lastModified) {
myPath = path;
myModule = module;
myLength = length;
myLastModified = lastModified * 1000;
}
public String getPath() {
return myPath;
}
public String getModule() {
return myModule;
}
public long length() {
return myLength;
}
public long lastModified() {
return myLastModified;
}
}
private boolean copyPregeneratedSkeleton(String moduleName) throws InvalidSdkException {
File targetDir;
final String modulePath = moduleName.replace('.', '/');
File skeletonsDir = new File(getSkeletonsPath());
VirtualFile pregenerated = myPregeneratedSkeletons.findFileByRelativePath(modulePath + ".py");
if (pregenerated == null) {
pregenerated = myPregeneratedSkeletons.findFileByRelativePath(modulePath + "/" + PyNames.INIT_DOT_PY);
targetDir = new File(skeletonsDir, modulePath);
}
else {
int pos = modulePath.lastIndexOf('/');
if (pos < 0) {
targetDir = skeletonsDir;
}
else {
final String moduleParentPath = modulePath.substring(0, pos);
targetDir = new File(skeletonsDir, moduleParentPath);
}
}
if (pregenerated != null && (targetDir.exists() || targetDir.mkdirs())) {
LOG.info("Pregenerated skeleton for " + moduleName);
File target = new File(targetDir, pregenerated.getName());
try {
FileOutputStream fos = new FileOutputStream(target);
try {
FileUtil.copy(pregenerated.getInputStream(), fos);
}
finally {
fos.close();
}
}
catch (IOException e) {
LOG.info("Error copying pregenerated skeleton", e);
return false;
}
return true;
}
return false;
}
@Nullable
private VirtualFile findPregeneratedSkeletons() {
final File root = findPregeneratedSkeletonsRoot();
if (root == null) {
return null;
}
LOG.info("Pregenerated skeletons root is " + root);
final String versionString = mySdk.getVersionString();
if (versionString == null) {
return null;
}
if (PySdkUtil.isRemote(mySdk)) {
return null;
}
String version = versionString.toLowerCase().replace(" ", "-");
File f;
if (SystemInfo.isMac) {
String osVersion = SystemInfo.OS_VERSION;
int dot = osVersion.indexOf('.');
if (dot >= 0) {
int secondDot = osVersion.indexOf('.', dot + 1);
if (secondDot >= 0) {
osVersion = osVersion.substring(0, secondDot);
}
}
f = new File(root, "skeletons-mac-" + myGeneratorVersion + "-" + osVersion + "-" + version + ".zip");
}
else {
String os = SystemInfo.isWindows ? "win" : "nix";
f = new File(root, "skeletons-" + os + "-" + myGeneratorVersion + "-" + version + ".zip");
}
if (f.exists()) {
LOG.info("Found pregenerated skeletons at " + f.getPath());
final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
if (virtualFile == null) {
LOG.info("Could not find pregenerated skeletons in VFS");
return null;
}
return JarFileSystem.getInstance().getJarRootForLocalFile(virtualFile);
}
else {
LOG.info("Not found pregenerated skeletons at " + f.getPath());
return null;
}
}
@Nullable
private static File findPregeneratedSkeletonsRoot() {
final String path = PathManager.getHomePath();
LOG.info("Home path is " + path);
File f = new File(path, "python/skeletons"); // from sources
if (f.exists()) return f;
f = new File(path, "skeletons"); // compiled binary
if (f.exists()) return f;
return null;
}
/**
* Generates a skeleton for a particular binary module.
*
* @param modname name of the binary module as known to Python (e.g. 'foo.bar')
* @param modfilename name of file which defines the module, null for built-in modules
* @param assemblyRefs refs that generator wants to know in .net environment, if applicable
* @param resultConsumer accepts true if generation completed successfully
*/
public void generateSkeleton(@NotNull String modname, @Nullable String modfilename,
@Nullable List<String> assemblyRefs, Consumer<Boolean> resultConsumer) throws InvalidSdkException {
mySkeletonsGenerator.generateSkeleton(modname, modfilename, assemblyRefs, getExtraSyspath(), mySdk.getHomePath(), resultConsumer);
}
private String getExtraSyspath() {
if (myExtraSyspath == null) {
myExtraSyspath = calculateExtraSysPath(mySdk, mySkeletonsPath);
}
return myExtraSyspath;
}
}
| python/src/com/jetbrains/python/sdk/skeletons/PySkeletonRefresher.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.skeletons;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.execution.ExecutionException;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.ZipUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil;
import com.jetbrains.python.packaging.PyExternalProcessException;
import com.jetbrains.python.packaging.PyPackageManager;
import com.jetbrains.python.packaging.PyPackageManagerImpl;
import com.jetbrains.python.psi.resolve.PythonSdkPathCache;
import com.jetbrains.python.remote.PythonRemoteInterpreterManager;
import com.jetbrains.python.sdk.InvalidSdkException;
import com.jetbrains.python.sdk.PySdkUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.jetbrains.python.sdk.skeletons.SkeletonVersionChecker.fromVersionString;
/**
* Handles a refresh of SDK's skeletons.
* Does all the heavy lifting calling skeleton generator, managing blacklists, etc.
* One-time, non-reusable instances.
* <br/>
* User: dcheryasov
* Date: 4/15/11 5:38 PM
*/
public class PySkeletonRefresher {
private static final Logger LOG = Logger.getInstance("#" + PySkeletonRefresher.class.getName());
@Nullable private Project myProject;
private @Nullable final ProgressIndicator myIndicator;
@NotNull private final Sdk mySdk;
private String mySkeletonsPath;
@NonNls public static final String BLACKLIST_FILE_NAME = ".blacklist";
private final static Pattern BLACKLIST_LINE = Pattern.compile("^([^=]+) = (\\d+\\.\\d+) (\\d+)\\s*$");
// we use the equals sign after filename so that we can freely include space in the filename
// Path (the first component) may contain spaces, this header spec is deprecated
private static final Pattern VERSION_LINE_V1 = Pattern.compile("# from (\\S+) by generator (\\S+)\\s*");
// Skeleton header spec v2
private static final Pattern FROM_LINE_V2 = Pattern.compile("# from (.*)$");
private static final Pattern BY_LINE_V2 = Pattern.compile("# by generator (.*)$");
private static int ourGeneratingCount = 0;
private String myExtraSyspath;
private VirtualFile myPregeneratedSkeletons;
private int myGeneratorVersion;
private Map<String, Pair<Integer, Long>> myBlacklist;
private SkeletonVersionChecker myVersionChecker;
private PySkeletonGenerator mySkeletonsGenerator;
public static void refreshSkeletonsOfSdk(@NotNull Project project, @NotNull Sdk sdk) throws InvalidSdkException {
refreshSkeletonsOfSdk(project, null, PythonSdkType.findSkeletonsPath(sdk), new Ref<Boolean>(false), sdk);
}
public static synchronized boolean isGeneratingSkeletons() {
return ourGeneratingCount > 0;
}
private static synchronized void changeGeneratingSkeletons(int increment) {
ourGeneratingCount += increment;
}
public static void refreshSkeletonsOfSdk(@Nullable Project project,
Component ownerComponent,
String skeletonsPath,
@Nullable Ref<Boolean> migrationFlag,
@NotNull Sdk sdk)
throws InvalidSdkException {
final Map<String, List<String>> errors = new TreeMap<String, List<String>>();
final List<String> failedSdks = new SmartList<String>();
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
final String homePath = sdk.getHomePath();
if (skeletonsPath == null) {
LOG.info("Could not find skeletons path for SDK path " + homePath);
}
else {
LOG.info("Refreshing skeletons for " + homePath);
SkeletonVersionChecker checker = new SkeletonVersionChecker(0); // this default version won't be used
final PySkeletonRefresher refresher = new PySkeletonRefresher(project, ownerComponent, sdk, skeletonsPath, indicator, null);
changeGeneratingSkeletons(1);
try {
List<String> sdkErrors = refresher.regenerateSkeletons(checker, migrationFlag);
if (sdkErrors.size() > 0) {
String sdkName = sdk.getName();
List<String> knownErrors = errors.get(sdkName);
if (knownErrors == null) {
errors.put(sdkName, sdkErrors);
}
else {
knownErrors.addAll(sdkErrors);
}
}
}
finally {
changeGeneratingSkeletons(-1);
}
}
if (failedSdks.size() > 0 || errors.size() > 0) {
int module_errors = 0;
for (String sdk_name : errors.keySet()) module_errors += errors.get(sdk_name).size();
String message;
if (failedSdks.size() > 0) {
message = PyBundle.message("sdk.errorlog.$0.mods.fail.in.$1.sdks.$2.completely", module_errors, errors.size(), failedSdks.size());
}
else {
message = PyBundle.message("sdk.errorlog.$0.mods.fail.in.$1.sdks", module_errors, errors.size());
}
logErrors(errors, failedSdks, message);
}
}
private static void logErrors(@NotNull final Map<String, List<String>> errors, @NotNull final List<String> failedSdks,
@NotNull final String message) {
LOG.warn(PyBundle.message("sdk.some.skeletons.failed"));
LOG.warn(message);
if (failedSdks.size() > 0) {
LOG.warn(PyBundle.message("sdk.error.dialog.failed.sdks"));
LOG.warn(StringUtil.join(failedSdks, ", "));
}
if (errors.size() > 0) {
LOG.warn(PyBundle.message("sdk.error.dialog.failed.modules"));
for (String sdkName : errors.keySet()) {
for (String moduleName : errors.get(sdkName)) {
LOG.warn(moduleName);
}
}
}
}
/**
* Creates a new object that refreshes skeletons of given SDK.
*
* @param sdk a Python SDK
* @param skeletonsPath if known; null means 'determine and create as needed'.
* @param indicator to report progress of long operations
*/
public PySkeletonRefresher(@Nullable Project project,
@Nullable Component ownerComponent,
@NotNull Sdk sdk,
@Nullable String skeletonsPath,
@Nullable ProgressIndicator indicator,
@Nullable String folder)
throws InvalidSdkException {
myProject = project;
myIndicator = indicator;
mySdk = sdk;
mySkeletonsPath = skeletonsPath;
final PythonRemoteInterpreterManager remoteInterpreterManager = PythonRemoteInterpreterManager.getInstance();
if (PySdkUtil.isRemote(sdk) && remoteInterpreterManager != null) {
try {
mySkeletonsGenerator = remoteInterpreterManager.createRemoteSkeletonGenerator(myProject, ownerComponent, sdk, getSkeletonsPath());
}
catch (ExecutionException e) {
throw new InvalidSdkException(e.getMessage(), e.getCause());
}
}
else {
mySkeletonsGenerator = new PySkeletonGenerator(getSkeletonsPath(), mySdk, folder);
}
}
private void indicate(String msg) {
if (myIndicator != null) {
myIndicator.checkCanceled();
myIndicator.setText(msg);
myIndicator.setText2("");
}
}
private void indicateMinor(String msg) {
if (myIndicator != null) {
myIndicator.setText2(msg);
}
}
private void checkCanceled() {
if (myIndicator != null) {
myIndicator.checkCanceled();
}
}
private static String calculateExtraSysPath(@NotNull final Sdk sdk, @Nullable final String skeletonsPath) {
final File skeletons = skeletonsPath != null ? new File(skeletonsPath) : null;
final VirtualFile userSkeletonsDir = PyUserSkeletonsUtil.getUserSkeletonsDirectory();
final File userSkeletons = userSkeletonsDir != null ? new File(userSkeletonsDir.getPath()) : null;
final VirtualFile remoteSourcesDir = PySdkUtil.findAnyRemoteLibrary(sdk);
final File remoteSources = remoteSourcesDir != null ? new File(remoteSourcesDir.getPath()) : null;
final VirtualFile[] classDirs = sdk.getRootProvider().getFiles(OrderRootType.CLASSES);
return Joiner.on(File.pathSeparator).join(ContainerUtil.mapNotNull(classDirs, new Function<VirtualFile, Object>() {
@Override
public Object fun(VirtualFile file) {
if (file.isInLocalFileSystem()) {
// We compare canonical files, not strings because "c:/some/folder" equals "c:\\some\\bin\\..\\folder\\"
final File canonicalFile = new File(file.getPath());
if (canonicalFile.exists() &&
!FileUtil.filesEqual(canonicalFile, skeletons) &&
!FileUtil.filesEqual(canonicalFile, userSkeletons) &&
!FileUtil.filesEqual(canonicalFile, remoteSources)) {
return file.getPath();
}
}
return null;
}
}));
}
/**
* Creates if needed all path(s) used to store skeletons of its SDK.
*
* @return path name of skeleton dir for the SDK, guaranteed to be already created.
*/
@NotNull
public String getSkeletonsPath() throws InvalidSdkException {
if (mySkeletonsPath == null) {
mySkeletonsPath = PythonSdkType.getSkeletonsPath(PathManager.getSystemPath(), mySdk.getHomePath());
final File skeletonsDir = new File(mySkeletonsPath);
if (!skeletonsDir.exists() && !skeletonsDir.mkdirs()) {
throw new InvalidSdkException("Can't create skeleton dir " + String.valueOf(mySkeletonsPath));
}
}
return mySkeletonsPath;
}
public List<String> regenerateSkeletons(@Nullable SkeletonVersionChecker cachedChecker,
@Nullable Ref<Boolean> migrationFlag) throws InvalidSdkException {
final List<String> errorList = new SmartList<String>();
final String homePath = mySdk.getHomePath();
final String skeletonsPath = getSkeletonsPath();
final File skeletonsDir = new File(skeletonsPath);
if (!skeletonsDir.exists()) {
//noinspection ResultOfMethodCallIgnored
skeletonsDir.mkdirs();
}
final String readablePath = FileUtil.getLocationRelativeToUserHome(homePath);
mySkeletonsGenerator.prepare();
myBlacklist = loadBlacklist();
indicate(PyBundle.message("sdk.gen.querying.$0", readablePath));
// get generator version and binary libs list in one go
final PySkeletonGenerator.ListBinariesResult binaries =
mySkeletonsGenerator.listBinaries(mySdk, calculateExtraSysPath(mySdk, getSkeletonsPath()));
myGeneratorVersion = binaries.generatorVersion;
myPregeneratedSkeletons = findPregeneratedSkeletons();
indicate(PyBundle.message("sdk.gen.reading.versions.file"));
if (cachedChecker != null) {
myVersionChecker = cachedChecker.withDefaultVersionIfUnknown(myGeneratorVersion);
}
else {
myVersionChecker = new SkeletonVersionChecker(myGeneratorVersion);
}
// check builtins
final String builtinsFileName = PythonSdkType.getBuiltinsFileName(mySdk);
final File builtinsFile = new File(skeletonsPath, builtinsFileName);
final SkeletonHeader oldHeader = readSkeletonHeader(builtinsFile);
final boolean oldOrNonExisting = oldHeader == null || oldHeader.getVersion() == 0;
if (migrationFlag != null && !migrationFlag.get() && oldOrNonExisting) {
migrationFlag.set(true);
Notifications.Bus.notify(
new Notification(
PythonSdkType.SKELETONS_TOPIC, PyBundle.message("sdk.gen.notify.converting.old.skels"),
PyBundle.message("sdk.gen.notify.converting.text"),
NotificationType.INFORMATION
)
);
}
if (myPregeneratedSkeletons != null && oldOrNonExisting) {
indicate("Unpacking pregenerated skeletons...");
try {
final VirtualFile jar = JarFileSystem.getInstance().getVirtualFileForJar(myPregeneratedSkeletons);
if (jar != null) {
ZipUtil.extract(new File(jar.getPath()),
new File(getSkeletonsPath()), null);
}
}
catch (IOException e) {
LOG.info("Error unpacking pregenerated skeletons", e);
}
}
if (oldOrNonExisting) {
final Sdk base = PythonSdkType.getInstance().getVirtualEnvBaseSdk(mySdk);
if (base != null) {
indicate("Copying base SDK skeletons for virtualenv...");
final String baseSkeletonsPath = PythonSdkType.getSkeletonsPath(PathManager.getSystemPath(), base.getHomePath());
final PySkeletonGenerator.ListBinariesResult baseBinaries =
mySkeletonsGenerator.listBinaries(base, calculateExtraSysPath(base, baseSkeletonsPath));
for (Map.Entry<String, PyBinaryItem> entry : binaries.modules.entrySet()) {
final String module = entry.getKey();
final PyBinaryItem binary = entry.getValue();
final PyBinaryItem baseBinary = baseBinaries.modules.get(module);
final File fromFile = getSkeleton(module, baseSkeletonsPath);
if (baseBinaries.modules.containsKey(module) &&
fromFile.exists() &&
binary.length() == baseBinary.length()) { // Weak binary modules equality check
final File toFile = fromFile.isDirectory() ?
getPackageSkeleton(module, skeletonsPath) :
getModuleSkeleton(module, skeletonsPath);
try {
FileUtil.copy(fromFile, toFile);
}
catch (IOException e) {
LOG.info("Error copying base virtualenv SDK skeleton for " + module, e);
}
}
}
}
}
final SkeletonHeader newHeader = readSkeletonHeader(builtinsFile);
final boolean mustUpdateBuiltins = myPregeneratedSkeletons == null &&
(newHeader == null || newHeader.getVersion() < myVersionChecker.getBuiltinVersion());
if (mustUpdateBuiltins) {
indicate(PyBundle.message("sdk.gen.updating.builtins.$0", readablePath));
mySkeletonsGenerator.generateBuiltinSkeletons(mySdk);
if (myProject != null) {
PythonSdkPathCache.getInstance(myProject, mySdk).clearBuiltins();
}
}
if (!binaries.modules.isEmpty()) {
indicate(PyBundle.message("sdk.gen.updating.$0", readablePath));
List<UpdateResult> updateErrors = updateOrCreateSkeletons(binaries.modules); //Skeletons regeneration
if (updateErrors.size() > 0) {
indicateMinor(BLACKLIST_FILE_NAME);
for (UpdateResult error : updateErrors) {
if (error.isFresh()) errorList.add(error.getName());
myBlacklist.put(error.getPath(), new Pair<Integer, Long>(myGeneratorVersion, error.getTimestamp()));
}
storeBlacklist(skeletonsDir, myBlacklist);
}
else {
removeBlacklist(skeletonsDir);
}
}
indicate(PyBundle.message("sdk.gen.reloading"));
mySkeletonsGenerator.refreshGeneratedSkeletons();
if (!oldOrNonExisting) {
indicate(PyBundle.message("sdk.gen.cleaning.$0", readablePath));
cleanUpSkeletons(skeletonsDir);
}
if (PySdkUtil.isRemote(mySdk)) {
try {
((PyPackageManagerImpl)PyPackageManager.getInstance(mySdk)).loadPackages();
}
catch (PyExternalProcessException e) {
// ignore - already logged
}
}
if ((mustUpdateBuiltins || PySdkUtil.isRemote(mySdk)) && myProject != null) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
DaemonCodeAnalyzer.getInstance(myProject).restart();
}
}, myProject.getDisposed());
}
return errorList;
}
@Nullable
public static SkeletonHeader readSkeletonHeader(@NotNull File file) {
try {
final LineNumberReader reader = new LineNumberReader(new FileReader(file));
try {
String line = null;
// Read 3 lines, skip first 2: encoding, module name
for (int i = 0; i < 3; i++) {
line = reader.readLine();
if (line == null) {
return null;
}
}
// Try the old whitespace-unsafe header format v1 first
final Matcher v1Matcher = VERSION_LINE_V1.matcher(line);
if (v1Matcher.matches()) {
return new SkeletonHeader(v1Matcher.group(1), fromVersionString(v1Matcher.group(2)));
}
final Matcher fromMatcher = FROM_LINE_V2.matcher(line);
if (fromMatcher.matches()) {
final String binaryFile = fromMatcher.group(1);
line = reader.readLine();
if (line != null) {
final Matcher byMatcher = BY_LINE_V2.matcher(line);
if (byMatcher.matches()) {
final int version = fromVersionString(byMatcher.group(1));
return new SkeletonHeader(binaryFile, version);
}
}
}
}
finally {
reader.close();
}
}
catch (IOException ignored) {
}
return null;
}
public static class SkeletonHeader {
@NotNull private final String myFile;
private final int myVersion;
public SkeletonHeader(@NotNull String binaryFile, int version) {
myFile = binaryFile;
myVersion = version;
}
@NotNull
public String getBinaryFile() {
return myFile;
}
public int getVersion() {
return myVersion;
}
}
private Map<String, Pair<Integer, Long>> loadBlacklist() {
Map<String, Pair<Integer, Long>> ret = new HashMap<String, Pair<Integer, Long>>();
File blacklistFile = new File(mySkeletonsPath, BLACKLIST_FILE_NAME);
if (blacklistFile.exists() && blacklistFile.canRead()) {
Reader input;
try {
input = new FileReader(blacklistFile);
LineNumberReader lines = new LineNumberReader(input);
try {
String line;
do {
line = lines.readLine();
if (line != null && line.length() > 0 && line.charAt(0) != '#') { // '#' begins a comment
Matcher matcher = BLACKLIST_LINE.matcher(line);
boolean notParsed = true;
if (matcher.matches()) {
final int version = fromVersionString(matcher.group(2));
if (version > 0) {
try {
final long timestamp = Long.parseLong(matcher.group(3));
final String filename = matcher.group(1);
ret.put(filename, new Pair<Integer, Long>(version, timestamp));
notParsed = false;
}
catch (NumberFormatException ignore) {
}
}
}
if (notParsed) LOG.warn("In blacklist at " + mySkeletonsPath + " strange line '" + line + "'");
}
}
while (line != null);
}
catch (IOException ex) {
LOG.warn("Failed to read blacklist in " + mySkeletonsPath, ex);
}
finally {
lines.close();
}
}
catch (IOException ignore) {
}
}
return ret;
}
private static void storeBlacklist(File skeletonDir, Map<String, Pair<Integer, Long>> blacklist) {
File blacklistFile = new File(skeletonDir, BLACKLIST_FILE_NAME);
PrintWriter output;
try {
output = new PrintWriter(blacklistFile);
try {
output.println("# PyCharm failed to generate skeletons for these modules.");
output.println("# These skeletons will be re-generated automatically");
output.println("# when a newer module version or an updated generator becomes available.");
// each line: filename = version.string timestamp
for (String fname : blacklist.keySet()) {
Pair<Integer, Long> data = blacklist.get(fname);
output.print(fname);
output.print(" = ");
output.print(SkeletonVersionChecker.toVersionString(data.getFirst()));
output.print(" ");
output.print(data.getSecond());
output.println();
}
}
finally {
output.close();
}
}
catch (IOException ex) {
LOG.warn("Failed to store blacklist in " + skeletonDir.getPath(), ex);
}
}
private static void removeBlacklist(File skeletonDir) {
File blacklistFile = new File(skeletonDir, BLACKLIST_FILE_NAME);
if (blacklistFile.exists()) {
boolean okay = blacklistFile.delete();
if (!okay) LOG.warn("Could not delete blacklist file in " + skeletonDir.getPath());
}
}
/**
* For every existing skeleton file, take its module file name,
* and remove the skeleton if the module file does not exist.
* Works recursively starting from dir. Removes dirs that become empty.
*/
private void cleanUpSkeletons(final File dir) {
indicateMinor(dir.getPath());
final File[] files = dir.listFiles();
if (files == null) {
return;
}
for (File item : files) {
if (item.isDirectory()) {
cleanUpSkeletons(item);
// was the dir emptied?
File[] remaining = item.listFiles();
if (remaining != null && remaining.length == 0) {
mySkeletonsGenerator.deleteOrLog(item);
}
else if (remaining != null && remaining.length == 1) { //clean also if contains only __init__.py
File lastFile = remaining[0];
if (PyNames.INIT_DOT_PY.equals(lastFile.getName()) && lastFile.length() == 0) {
boolean deleted = mySkeletonsGenerator.deleteOrLog(lastFile);
if (deleted) mySkeletonsGenerator.deleteOrLog(item);
}
}
}
else if (item.isFile()) {
// clean up an individual file
final String itemName = item.getName();
if (PyNames.INIT_DOT_PY.equals(itemName) && item.length() == 0) continue; // these are versionless
if (BLACKLIST_FILE_NAME.equals(itemName)) continue; // don't touch the blacklist
if (PythonSdkType.getBuiltinsFileName(mySdk).equals(itemName)) {
continue;
}
final SkeletonHeader header = readSkeletonHeader(item);
boolean canLive = header != null;
if (canLive) {
final String binaryFile = header.getBinaryFile();
canLive = SkeletonVersionChecker.BUILTIN_NAME.equals(binaryFile) || mySkeletonsGenerator.exists(binaryFile);
}
if (!canLive) {
mySkeletonsGenerator.deleteOrLog(item);
}
}
}
}
private static class UpdateResult {
private final String myPath;
private final String myName;
private final long myTimestamp;
public boolean isFresh() {
return myIsFresh;
}
private final boolean myIsFresh;
private UpdateResult(String name, String path, long timestamp, boolean fresh) {
myName = name;
myPath = path;
myTimestamp = timestamp;
myIsFresh = fresh;
}
public String getName() {
return myName;
}
public String getPath() {
return myPath;
}
public Long getTimestamp() {
return myTimestamp;
}
}
/**
* (Re-)generates skeletons for all binary python modules. Up-to-date skeletons are not regenerated.
* Does one module at a time: slower, but avoids certain conflicts.
*
* @param modules output of generator3 -L
* @return blacklist data; whatever was not generated successfully is put here.
*/
private List<UpdateResult> updateOrCreateSkeletons(Map<String, PyBinaryItem> modules) throws InvalidSdkException {
long startTime = System.currentTimeMillis();
final List<String> names = Lists.newArrayList(modules.keySet());
Collections.sort(names);
final List<UpdateResult> results = new ArrayList<UpdateResult>();
final int count = names.size();
for (int i = 0; i < count; i++) {
checkCanceled();
if (myIndicator != null) {
myIndicator.setFraction((double)i / count);
}
final String name = names.get(i);
final PyBinaryItem module = modules.get(name);
if (module != null) {
updateOrCreateSkeleton(module, results);
}
}
finishSkeletonsGeneration();
long doneInMs = System.currentTimeMillis() - startTime;
LOG.info("Rebuilding skeletons for binaries took " + doneInMs + " ms");
return results;
}
private void finishSkeletonsGeneration() {
mySkeletonsGenerator.finishSkeletonsGeneration();
}
private static File getSkeleton(String moduleName, String skeletonsPath) {
final File module = getModuleSkeleton(moduleName, skeletonsPath);
return module.exists() ? module : getPackageSkeleton(moduleName, skeletonsPath);
}
private static File getModuleSkeleton(String module, String skeletonsPath) {
final String modulePath = module.replace('.', '/');
return new File(skeletonsPath, modulePath + ".py");
}
private static File getPackageSkeleton(String pkg, String skeletonsPath) {
final String packagePath = pkg.replace('.', '/');
return new File(new File(skeletonsPath, packagePath), PyNames.INIT_DOT_PY);
}
private boolean updateOrCreateSkeleton(final PyBinaryItem binaryItem,
final List<UpdateResult> errorList) throws InvalidSdkException {
final String moduleName = binaryItem.getModule();
final File skeleton = getSkeleton(moduleName, getSkeletonsPath());
final SkeletonHeader header = readSkeletonHeader(skeleton);
boolean mustRebuild = true; // guilty unless proven fresh enough
if (header != null) {
int requiredVersion = myVersionChecker.getRequiredVersion(moduleName);
mustRebuild = header.getVersion() < requiredVersion;
}
if (!mustRebuild) { // ...but what if the lib was updated?
mustRebuild = (skeleton.exists() && binaryItem.lastModified() > skeleton.lastModified());
// really we can omit both exists() calls but I keep these to make the logic clear
}
if (myBlacklist != null) {
Pair<Integer, Long> versionInfo = myBlacklist.get(binaryItem.getPath());
if (versionInfo != null) {
int failedGeneratorVersion = versionInfo.getFirst();
long failedTimestamp = versionInfo.getSecond();
mustRebuild &= failedGeneratorVersion < myGeneratorVersion || failedTimestamp < binaryItem.lastModified();
if (!mustRebuild) { // we're still failing to rebuild, it, keep it in blacklist
errorList.add(new UpdateResult(moduleName, binaryItem.getPath(), binaryItem.lastModified(), false));
}
}
}
if (mustRebuild) {
indicateMinor(moduleName);
if (myPregeneratedSkeletons != null && copyPregeneratedSkeleton(moduleName)) {
return true;
}
LOG.info("Skeleton for " + moduleName);
generateSkeleton(moduleName, binaryItem.getPath(), null, new Consumer<Boolean>() {
@Override
public void consume(Boolean generated) {
if (!generated) {
errorList.add(new UpdateResult(moduleName, binaryItem.getPath(), binaryItem.lastModified(), true));
}
}
});
}
return false;
}
public static class PyBinaryItem {
private String myPath;
private String myModule;
private long myLength;
private long myLastModified;
PyBinaryItem(String module, String path, long length, long lastModified) {
myPath = path;
myModule = module;
myLength = length;
myLastModified = lastModified * 1000;
}
public String getPath() {
return myPath;
}
public String getModule() {
return myModule;
}
public long length() {
return myLength;
}
public long lastModified() {
return myLastModified;
}
}
private boolean copyPregeneratedSkeleton(String moduleName) throws InvalidSdkException {
File targetDir;
final String modulePath = moduleName.replace('.', '/');
File skeletonsDir = new File(getSkeletonsPath());
VirtualFile pregenerated = myPregeneratedSkeletons.findFileByRelativePath(modulePath + ".py");
if (pregenerated == null) {
pregenerated = myPregeneratedSkeletons.findFileByRelativePath(modulePath + "/" + PyNames.INIT_DOT_PY);
targetDir = new File(skeletonsDir, modulePath);
}
else {
int pos = modulePath.lastIndexOf('/');
if (pos < 0) {
targetDir = skeletonsDir;
}
else {
final String moduleParentPath = modulePath.substring(0, pos);
targetDir = new File(skeletonsDir, moduleParentPath);
}
}
if (pregenerated != null && (targetDir.exists() || targetDir.mkdirs())) {
LOG.info("Pregenerated skeleton for " + moduleName);
File target = new File(targetDir, pregenerated.getName());
try {
FileOutputStream fos = new FileOutputStream(target);
try {
FileUtil.copy(pregenerated.getInputStream(), fos);
}
finally {
fos.close();
}
}
catch (IOException e) {
LOG.info("Error copying pregenerated skeleton", e);
return false;
}
return true;
}
return false;
}
@Nullable
private VirtualFile findPregeneratedSkeletons() {
final File root = findPregeneratedSkeletonsRoot();
if (root == null) {
return null;
}
LOG.info("Pregenerated skeletons root is " + root);
final String versionString = mySdk.getVersionString();
if (versionString == null) {
return null;
}
if (PySdkUtil.isRemote(mySdk)) {
return null;
}
String version = versionString.toLowerCase().replace(" ", "-");
File f;
if (SystemInfo.isMac) {
String osVersion = SystemInfo.OS_VERSION;
int dot = osVersion.indexOf('.');
if (dot >= 0) {
int secondDot = osVersion.indexOf('.', dot + 1);
if (secondDot >= 0) {
osVersion = osVersion.substring(0, secondDot);
}
}
f = new File(root, "skeletons-mac-" + myGeneratorVersion + "-" + osVersion + "-" + version + ".zip");
}
else {
String os = SystemInfo.isWindows ? "win" : "nix";
f = new File(root, "skeletons-" + os + "-" + myGeneratorVersion + "-" + version + ".zip");
}
if (f.exists()) {
LOG.info("Found pregenerated skeletons at " + f.getPath());
final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
if (virtualFile == null) {
LOG.info("Could not find pregenerated skeletons in VFS");
return null;
}
return JarFileSystem.getInstance().getJarRootForLocalFile(virtualFile);
}
else {
LOG.info("Not found pregenerated skeletons at " + f.getPath());
return null;
}
}
@Nullable
private static File findPregeneratedSkeletonsRoot() {
final String path = PathManager.getHomePath();
LOG.info("Home path is " + path);
File f = new File(path, "python/skeletons"); // from sources
if (f.exists()) return f;
f = new File(path, "skeletons"); // compiled binary
if (f.exists()) return f;
return null;
}
/**
* Generates a skeleton for a particular binary module.
*
* @param modname name of the binary module as known to Python (e.g. 'foo.bar')
* @param modfilename name of file which defines the module, null for built-in modules
* @param assemblyRefs refs that generator wants to know in .net environment, if applicable
* @param resultConsumer accepts true if generation completed successfully
*/
public void generateSkeleton(@NotNull String modname, @Nullable String modfilename,
@Nullable List<String> assemblyRefs, Consumer<Boolean> resultConsumer) throws InvalidSdkException {
mySkeletonsGenerator.generateSkeleton(modname, modfilename, assemblyRefs, getExtraSyspath(), mySdk.getHomePath(), resultConsumer);
}
private String getExtraSyspath() {
if (myExtraSyspath == null) {
myExtraSyspath = calculateExtraSysPath(mySdk, mySkeletonsPath);
}
return myExtraSyspath;
}
}
| Removed unused method
| python/src/com/jetbrains/python/sdk/skeletons/PySkeletonRefresher.java | Removed unused method | <ide><path>ython/src/com/jetbrains/python/sdk/skeletons/PySkeletonRefresher.java
<ide>
<ide> private PySkeletonGenerator mySkeletonsGenerator;
<ide>
<del> public static void refreshSkeletonsOfSdk(@NotNull Project project, @NotNull Sdk sdk) throws InvalidSdkException {
<del> refreshSkeletonsOfSdk(project, null, PythonSdkType.findSkeletonsPath(sdk), new Ref<Boolean>(false), sdk);
<del> }
<del>
<ide> public static synchronized boolean isGeneratingSkeletons() {
<ide> return ourGeneratingCount > 0;
<ide> } |
|
JavaScript | mit | 8ad97a4ddfd0e6dd142c76540a65e6b87a7b85c9 | 0 | sbarton272/WebGremlin | /* Web Gremlin
* Tartan Hacks 2015
* CMU
* Carson, Adam, Billy and Spencer
*/
// TODO
// add audio
//
//---------------------------------------------
// Gremlin engine
//---------------------------------------------
function WebGremlin(animations) {
//----------- Constants -----------------------
// Constants
this.MAX_DELAY = 1000;
this.AE = new AnimationEngine();
// Load animations
// TODO move animations folder elsewhere
this.animations = animations;
//----------- Methods -----------------------
// Perform actions randomly
this.start = function() {
console.log('Your web gremlin is awake');
// Action after certain delay
var delayMs = Math.floor(Math.random() * this.MAX_DELAY);
setTimeout(function() {
// TODO load
this.AE.animate(this.animations['inplace_bird']);
}.bind(this), delayMs);
};
};
//---------------------------------------------
// Animation engine
//---------------------------------------------
function AnimationEngine() {
//----------- Constants -----------------------
this.Z_SCORE = 9999999;
// Defined animations
this.MOVEMENT = "ANIMATION_MOVE";
this.IN_PLACE = "ANIMATION_IN_PLACE";
//----------- Actions -----------------------
// Animation object used to play animation
this.animate = function(animation) {
// Case on animation type
switch(animation.type) {
case this.MOVEMENT:
this.runMove(animation);
break;
case this.IN_PLACE:
this.runInPlace(animation);
break;
default:
console.log('Unrecognized animation type [' +
animation.type + ']');
break;
}
};
//----------- Animations -----------------------
// In place animation
this.runInPlace = function(animation) {
var topPerc = Math.floor(Math.random() * 80) + 10;
var leftPerc = Math.floor(Math.random() * 80) + 10;
var $sprite = this.drawSprite(animation.width, animation.height,
topPerc+'%', leftPerc+'%', animation.img);
$sprite.sprite({fps: animation.fps, no_of_frames: animation.no_of_frames});
this.playSound(animation);
};
// Move across screen in straight line
this.runMove = function(animation) {
var topPerc = Math.floor(Math.random() * 80) + 10;
var $sprite = this.drawSprite(animation.width, animation.height,
topPerc+'%', '-50%', animation.img);
$sprite.sprite({fps: animation.fps, no_of_frames: animation.no_of_frames});
$sprite.pan({});
this.playSound(animation);
};
//------------Playing Sound------------------
this.playSound = function(animation) {
var sound = chrome.extension.getURL(animation.sound);
(new buzz.sound(sound)).play();
}
//----------- Drawing -----------------------
/*
* PARAMS:
* width (str) width of base animation frame
* height (str) height of base animation frame
* posTop (str) position of top of div
* posLeft (str) position of left of div
* backgroundImg (str) file path
* RETURNS:
* spriteObject
*/
this.drawSprite = function(width, height, posTop, posLeft, backgroundImg) {
var url = 'url(' + chrome.extension.getURL(backgroundImg) + ')';
// Define sprite as div
var $sprite = $('<div/>', {
'width': width.toString(),
'height': height.toString()
})
.css({
'position': 'absolute',
'top': posTop,
'left': posLeft,
'background-image': url,
'background-repeat': 'no-repeat',
'background-color': 'transparent',
'z-index': this.Z_SCORE
});
$('body').append($sprite);
return $sprite;
}
};
//---------------------------------------------
// Run
//---------------------------------------------
var webGremlin = new WebGremlin(ANIMATIONS);
webGremlin.start();
| app/js/webGremlin.js | /* Web Gremlin
* Tartan Hacks 2015
* CMU
* Carson, Adam, Billy and Spencer
*/
// TODO
// add audio
//
//---------------------------------------------
// Gremlin engine
//---------------------------------------------
function WebGremlin(animations) {
//----------- Constants -----------------------
// Constants
this.MAX_DELAY = 1000;
this.AE = new AnimationEngine();
// Load animations
// TODO move animations folder elsewhere
this.animations = animations;
//----------- Methods -----------------------
// Perform actions randomly
this.start = function() {
console.log('Your web gremlin is awake');
// Action after certain delay
var delayMs = Math.floor(Math.random() * this.MAX_DELAY);
setTimeout(function() {
// TODO load
this.AE.animate(this.animations['inplace_bird']);
}.bind(this), delayMs);
};
};
//---------------------------------------------
// Animation engine
//---------------------------------------------
function AnimationEngine() {
//----------- Constants -----------------------
this.Z_SCORE = 9999999;
// Defined animations
this.MOVEMENT = "ANIMATION_MOVE";
this.IN_PALCE = "ANIMATION_IN_PLACE";
//----------- Actions -----------------------
// Animation object used to play animation
this.animate = function(animation) {
// Case on animation type
switch(animation.type) {
case this.MOVEMENT:
this.runMove(animation);
break;
case this.IN_PALCE:
this.runInPlace(animation);
break;
default:
console.log('Unrecognized animation type [' +
animation.type + ']');
break;
}
};
//----------- Animations -----------------------
// In place animation
this.runInPlace = function(animation) {
var topPerc = Math.floor(Math.random() * 80) + 10;
var leftPerc = Math.floor(Math.random() * 80) + 10;
var $sprite = this.drawSprite(animation.width, animation.height,
topPerc+'%', leftPerc+'%', animation.img);
$sprite.sprite({fps: animation.fps, no_of_frames: animation.no_of_frames});
this.playSound(animation);
};
// Move across screen in straight line
this.runMove = function(animation) {
var topPerc = Math.floor(Math.random() * 80) + 10;
var $sprite = this.drawSprite(animation.width, animation.height,
topPerc+'%', '-50%', animation.img);
$sprite.sprite({fps: animation.fps, no_of_frames: animation.no_of_frames});
$sprite.pan({});
this.playSound(animation);
};
//------------Playing Sound------------------
this.playSound = function(animation) {
var sound = chrome.extension.getURL(animation.sound);
(new buzz.sound(sound)).play();
}
//----------- Drawing -----------------------
/*
* PARAMS:
* width (str) width of base animation frame
* height (str) height of base animation frame
* posTop (str) position of top of div
* posLeft (str) position of left of div
* backgroundImg (str) file path
* RETURNS:
* spriteObject
*/
this.drawSprite = function(width, height, posTop, posLeft, backgroundImg) {
var url = 'url(' + chrome.extension.getURL(backgroundImg) + ')';
// Define sprite as div
var $sprite = $('<div/>', {
'width': width.toString(),
'height': height.toString()
})
.css({
'position': 'absolute',
'top': posTop,
'left': posLeft,
'background-image': url,
'background-repeat': 'no-repeat',
'background-color': 'transparent',
'z-index': this.Z_SCORE
});
$('body').append($sprite);
return $sprite;
}
};
//---------------------------------------------
// Run
//---------------------------------------------
var webGremlin = new WebGremlin(ANIMATIONS);
webGremlin.start();
| IN_PALCE => IN_PLACE
| app/js/webGremlin.js | IN_PALCE => IN_PLACE | <ide><path>pp/js/webGremlin.js
<ide>
<ide> // Defined animations
<ide> this.MOVEMENT = "ANIMATION_MOVE";
<del> this.IN_PALCE = "ANIMATION_IN_PLACE";
<add> this.IN_PLACE = "ANIMATION_IN_PLACE";
<ide>
<ide> //----------- Actions -----------------------
<ide>
<ide> case this.MOVEMENT:
<ide> this.runMove(animation);
<ide> break;
<del> case this.IN_PALCE:
<add> case this.IN_PLACE:
<ide> this.runInPlace(animation);
<ide> break;
<ide> default: |
|
Java | unlicense | 2a61312a7c0d8517c28e1ac48ed953d033c240a6 | 0 | rctillotson25/cs-fundamentals | package bits;
public class Practice {
public static int ON = 1;
public static int OFF = 0;
public static void main(String[] args) {
// getBit tests
System.out.println("1,0 " + getBit(1,0));
System.out.println("1,1 " + getBit(1,1));
System.out.println("2,1 " + getBit(2,1));
System.out.println("256,8 " + getBit(256,8));
// getBitValue tests
System.out.println("Value 1,0 " + getBitValue(1,0));
System.out.println("Value 1,1 " + getBitValue(1,1));
System.out.println("Value 2,1 " + getBitValue(2,1));
System.out.println("Value 256,8 " + getBitValue(256,8));
// clearBit tests
System.out.println("Clear 2,1 " + clearBit(2,1));
System.out.println("Clear 3,1 " + clearBit(3,1));
// setBit tests
System.out.println("Set 0,8 " + setBit(0,8));
System.out.println("Set 1,1 " + setBit(1,1));
// updateBit tests
System.out.println("Set 0,8,ON " + Integer.toBinaryString(updateBit(0,8,ON)));
System.out.println("Set 1,0,OFF " + Integer.toBinaryString(updateBit(1,0,OFF)));
// insertMN tests
System.out.println("insertMN 128,7,0,3 " + insertMN(128,7,0,3) + " = 135");
}
public static boolean getBit(int num, int i) {
return ((num & (1 << i)) != 0);
}
public static int getBitValue(int num, int i) {
return (num >> i) & 1;
}
public static int clearBit(int num, int i) {
int mask = ~(1 << i);
return num & mask;
}
public static int setBit(int num, int i) {
return num | (1 << i);
}
public static int updateBit(int num, int i, int v) {
int mask = ~(1 << i);
return (num & mask) | (v << i);
}
public static int insertMN(int n, int m, int i, int j) {
for (int k = 0; k < j-i; k++) {
n = updateBit(n, k+i, getBitValue(m, k));
}
return n;
}
}
| bits/Practice.java | package bits;
public class Practice {
public static int ON = 1;
public static int OFF = 0;
public static void main(String[] args) {
// getBit tests
System.out.println("1,0 " + getBit(1,0));
System.out.println("1,1 " + getBit(1,1));
System.out.println("2,1 " + getBit(2,1));
System.out.println("256,8 " + getBit(256,8));
// clearBit tests
System.out.println("Clear 2,1 " + clearBit(2,1));
System.out.println("Clear 3,1 " + clearBit(3,1));
// setBit tests
System.out.println("Set 0,8 " + setBit(0,8));
System.out.println("Set 1,1 " + setBit(1,1));
// updateBit tests
System.out.println("Set 0,8,ON " + Integer.toBinaryString(updateBit(0,8,ON)));
System.out.println("Set 1,0,OFF " + Integer.toBinaryString(updateBit(1,0,OFF)));
}
public static boolean getBit(int num, int i) {
return ((num & (1 << i)) != 0);
}
public static int clearBit(int num, int i) {
int mask = ~(1 << i);
return num & mask;
}
public static int setBit(int num, int i) {
return num | (1 << i);
}
public static int updateBit(int num, int i, int v) {
int mask = ~(1 << i);
return (num & mask) | (v << i);
}
}
| Added function that will binary insert a number into another called insertMN in the bit classes.
| bits/Practice.java | Added function that will binary insert a number into another called insertMN in the bit classes. | <ide><path>its/Practice.java
<ide> System.out.println("2,1 " + getBit(2,1));
<ide> System.out.println("256,8 " + getBit(256,8));
<ide>
<add> // getBitValue tests
<add> System.out.println("Value 1,0 " + getBitValue(1,0));
<add> System.out.println("Value 1,1 " + getBitValue(1,1));
<add> System.out.println("Value 2,1 " + getBitValue(2,1));
<add> System.out.println("Value 256,8 " + getBitValue(256,8));
<add>
<ide> // clearBit tests
<ide> System.out.println("Clear 2,1 " + clearBit(2,1));
<ide> System.out.println("Clear 3,1 " + clearBit(3,1));
<ide> // updateBit tests
<ide> System.out.println("Set 0,8,ON " + Integer.toBinaryString(updateBit(0,8,ON)));
<ide> System.out.println("Set 1,0,OFF " + Integer.toBinaryString(updateBit(1,0,OFF)));
<add>
<add> // insertMN tests
<add> System.out.println("insertMN 128,7,0,3 " + insertMN(128,7,0,3) + " = 135");
<ide> }
<ide>
<ide> public static boolean getBit(int num, int i) {
<ide> return ((num & (1 << i)) != 0);
<add> }
<add>
<add> public static int getBitValue(int num, int i) {
<add> return (num >> i) & 1;
<ide> }
<ide>
<ide> public static int clearBit(int num, int i) {
<ide> return (num & mask) | (v << i);
<ide> }
<ide>
<add> public static int insertMN(int n, int m, int i, int j) {
<add> for (int k = 0; k < j-i; k++) {
<add> n = updateBit(n, k+i, getBitValue(m, k));
<add> }
<add> return n;
<add> }
<add>
<ide> } |
|
Java | agpl-3.0 | b74d26acb45b86809568eaad68e1aad4bbf085d0 | 0 | DJmaxZPL4Y/Photon-Server | package org.mcphoton.impl.network;
import com.electronwill.utils.IndexMap;
import com.electronwill.utils.SimpleBag;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.mcphoton.Photon;
import org.mcphoton.impl.server.PhotonServer;
import org.mcphoton.network.Client;
import org.mcphoton.network.ConnectionState;
import org.mcphoton.network.Packet;
import org.mcphoton.network.PacketHandler;
import org.mcphoton.network.PacketsManager;
import org.mcphoton.network.ProtocolHelper;
import org.mcphoton.network.handshaking.serverbound.HandshakePacket;
import org.mcphoton.network.status.clientbound.PongPacket;
import org.mcphoton.network.status.clientbound.ResponsePacket;
import org.mcphoton.network.status.serverbound.PingPacket;
import org.mcphoton.network.status.serverbound.RequestPacket;
/**
* Implementation of the PacketsManager.
*
* @author TheElectronWill
*/
public final class PhotonPacketsManager implements PacketsManager {
private final PhotonServer server;
//--- ServerBound ---
private final IndexMap<Class<? extends Packet>> serverInitPackets, serverStatusPackets, serverLoginPackets, serverPlayPackets;
private final IndexMap<Collection<PacketHandler>> serverInitHandlers, serverStatusHandlers, serverLoginHandlers, serverPlayHandlers;
//--- ClientBound ---
private final IndexMap<Class<? extends Packet>> clientInitPackets, clientStatusPackets, clientLoginPackets, clientPlayPackets;
private final IndexMap<Collection<PacketHandler>> clientInitHandlers, clientStatusHandlers, clientLoginHandlers, clientPlayHandlers;
public PhotonPacketsManager(PhotonServer server) {
this.server = server;
//TODO set the correct sizes
this.serverInitPackets = new IndexMap<>();
this.serverStatusPackets = new IndexMap<>();
this.serverLoginPackets = new IndexMap<>();
this.serverPlayPackets = new IndexMap<>();
this.serverInitHandlers = new IndexMap<>();
this.serverStatusHandlers = new IndexMap<>();
this.serverLoginHandlers = new IndexMap<>();
this.serverPlayHandlers = new IndexMap<>();
this.clientInitPackets = new IndexMap<>();
this.clientStatusPackets = new IndexMap<>();
this.clientLoginPackets = new IndexMap<>();
this.clientPlayPackets = new IndexMap<>();
this.clientInitHandlers = new IndexMap<>();
this.clientStatusHandlers = new IndexMap<>();
this.clientLoginHandlers = new IndexMap<>();
this.clientPlayHandlers = new IndexMap<>();
}
private IndexMap<Class<? extends Packet>> getPacketsMap(ConnectionState state, boolean serverBound) {
if (serverBound) {
switch (state) {
case LOGIN:
return serverLoginPackets;
case PLAY:
return serverPlayPackets;
case STATUS:
return serverStatusPackets;
default:
return serverInitPackets;
}
} else {
switch (state) {
case LOGIN:
return clientLoginPackets;
case PLAY:
return clientPlayPackets;
case STATUS:
return clientStatusPackets;
default:
return clientInitPackets;
}
}
}
private IndexMap<Collection<PacketHandler>> getHandlersMap(ConnectionState state, boolean serverBound) {
if (serverBound) {
switch (state) {
case LOGIN:
return serverLoginHandlers;
case PLAY:
return serverPlayHandlers;
case STATUS:
return serverStatusHandlers;
default:
return serverInitHandlers;
}
} else {
switch (state) {
case LOGIN:
return clientLoginHandlers;
case PLAY:
return clientPlayHandlers;
case STATUS:
return clientStatusHandlers;
default:
return clientInitHandlers;
}
}
}
@Override
public void registerPacket(ConnectionState state, boolean serverBound, int packetId, Class<? extends Packet> packetClass) {
IndexMap<Class<? extends Packet>> map = getPacketsMap(state, serverBound);
synchronized (map) {
map.put(packetId, packetClass);
}
}
@Override
public void registerHandler(ConnectionState state, boolean serverBound, int packetId, PacketHandler<? extends Packet> handler) {
IndexMap<Collection<PacketHandler>> map = getHandlersMap(state, serverBound);
synchronized (map) {
Collection<PacketHandler> handlers = map.get(packetId);
if (handlers == null) {
handlers = new SimpleBag<>();
map.put(packetId, handlers);
}
handlers.add(handler);
}
}
@Override
public void unregisterPacket(ConnectionState state, boolean serverBound, int packetId) {
IndexMap<Class<? extends Packet>> map = getPacketsMap(state, serverBound);
synchronized (map) {
map.remove(packetId);
}
}
@Override
public void unregisterHandler(ConnectionState state, boolean serverBound, int packetId, PacketHandler<? extends Packet> handler) {
IndexMap<Collection<PacketHandler>> map = getHandlersMap(state, serverBound);
synchronized (map) {
Collection<PacketHandler> handlers = map.get(packetId);
if (handlers != null) {
handlers.remove(handler);
}
}
}
@Override
public Class<? extends Packet> getRegisteredPacket(ConnectionState state, boolean serverBound, int packetId) {
IndexMap<Class<? extends Packet>> map = getPacketsMap(state, serverBound);
synchronized (map) {
return map.get(packetId);
}
}
@Override
public Collection<PacketHandler> getRegisteredHandlers(ConnectionState state, boolean serverBound, int packetId) {
IndexMap<Collection<PacketHandler>> map = getHandlersMap(state, serverBound);
synchronized (map) {
return map.get(packetId);
}
}
@Override
public void sendPacket(Packet packet, Client client) {
server.networkOutputThread.enqueue(new PacketSending(packet, (PhotonClient) client));
}
@Override
public void sendPacket(Packet packet, Client... clients) {
List clientList = Arrays.asList(clients);
server.networkOutputThread.enqueue(new PacketSending(packet, clientList));
}
@Override
public void sendPacket(Packet packet, Client client, Runnable onSendingCompleted) {
//TODO
throw new UnsupportedOperationException("Not yet implemented, sorry");
}
@Override
public Packet parsePacket(ByteBuffer data, ConnectionState connState, boolean serverBound) {
server.logger.debug("parse packet: {}, state: {}, serverBound: {}" + serverBound, data, connState, serverBound);
int packetId = ProtocolHelper.readVarInt(data);
try {
Class<? extends Packet> packetClass = getRegisteredPacket(connState, serverBound, 0);
Packet packet = packetClass.newInstance();
return packet.readFrom(data);
} catch (InstantiationException | IllegalAccessException | NullPointerException ex) {
server.logger.error("Cannot create packet object with id {}", packetId, ex);
}
return null;
}
@Override
public void handle(Packet packet, Client client) {
server.logger.debug("Handling packet {} from {}", packet.toString(), client.getAddress().toString());
IndexMap<Collection<PacketHandler>> map = getHandlersMap(client.getConnectionState(), packet.isServerBound());
synchronized (map) {
Collection<PacketHandler> handlers = map.get(packet.getId());
if (handlers != null) {
for (PacketHandler handler : handlers) {
handler.handle(packet, client);
}
}
}
}
public void registerGamePackets() {
synchronized (serverInitPackets) {
serverInitPackets.put(0, org.mcphoton.network.handshaking.serverbound.HandshakePacket.class);
}
synchronized (serverStatusPackets) {
serverStatusPackets.put(0, org.mcphoton.network.status.serverbound.RequestPacket.class);
serverStatusPackets.put(1, org.mcphoton.network.status.serverbound.PingPacket.class);
}
synchronized (serverLoginPackets) {
serverLoginPackets.put(0, org.mcphoton.network.login.serverbound.LoginStartPacket.class);
serverLoginPackets.put(1, org.mcphoton.network.login.serverbound.EncryptionResponsePacket.class);
}
/* TODO
* synchronized(serverPlayPackets){
*
* }
*/
synchronized (clientStatusPackets) {
clientStatusPackets.put(0, org.mcphoton.network.status.clientbound.ResponsePacket.class);
clientStatusPackets.put(1, org.mcphoton.network.status.clientbound.PongPacket.class);
}
synchronized (clientLoginPackets) {
clientLoginPackets.put(0, org.mcphoton.network.login.clientbound.DisconnectPacket.class);
clientLoginPackets.put(1, org.mcphoton.network.login.clientbound.EncryptionRequestPacket.class);
clientLoginPackets.put(2, org.mcphoton.network.login.clientbound.LoginSuccessPacket.class);
clientLoginPackets.put(3, org.mcphoton.network.login.clientbound.SetCompressionPacket.class);
}
synchronized (clientPlayPackets) {
clientPlayPackets.put(0x20, org.mcphoton.network.play.clientbound.ChunkDataPacket.class);
clientPlayPackets.put(0x03, org.mcphoton.network.play.clientbound.ClientStatusPacket.class);
clientPlayPackets.put(0x23, org.mcphoton.network.play.clientbound.JoinGamePacket.class);
clientPlayPackets.put(0x2E, org.mcphoton.network.play.clientbound.PlayerPositionAndLookPacket.class);
clientPlayPackets.put(0x18, org.mcphoton.network.play.clientbound.PluginMessagePacket.class);
clientPlayPackets.put(0x0D, org.mcphoton.network.play.clientbound.ServerDifficultyPacket.class);
clientPlayPackets.put(0x43, org.mcphoton.network.play.clientbound.SpawnPositionPacket.class);
}
}
public void registerPacketHandlers() {
registerHandler(ConnectionState.INIT, true, 0, (HandshakePacket packet, Client client) -> {
server.logger.debug("Set client state to " + packet.nextState);
if (packet.nextState == 1) {
client.setConnectionState(ConnectionState.STATUS);
} else if (packet.nextState == 2) {
client.setConnectionState(ConnectionState.LOGIN);
} else {
//invalid
}
});
registerHandler(ConnectionState.STATUS, true, 0, (RequestPacket packet, Client client) -> {
ResponsePacket response = new ResponsePacket();
StringBuilder jsonBuilder = new StringBuilder("{");
jsonBuilder.append("\"version\":{");
jsonBuilder.append("\"name\":\"").append(Photon.getMinecraftVersion()).append("\",");
jsonBuilder.append("\"protocol\":").append(HandshakePacket.CURRENT_PROTOCOL_VERSION);
jsonBuilder.append("},");
jsonBuilder.append("\"players\":{");
jsonBuilder.append("\"max\":").append(server.maxPlayers).append(',');
jsonBuilder.append("\"online\":").append(server.onlinePlayers.size());
jsonBuilder.append("},");
jsonBuilder.append("\"description\":{");
jsonBuilder.append("\"text\":\"").append(server.motd).append("\"");
jsonBuilder.append("}}");
response.jsonResponse = jsonBuilder.toString();
server.logger.debug("Sending ResponsePacket to the client: {}", jsonBuilder);
sendPacket(response, client);
});
registerHandler(ConnectionState.STATUS, true, 1, (PingPacket packet, Client client) -> {
PongPacket pong = new PongPacket();
pong.payload = System.currentTimeMillis();
sendPacket(pong, client);
});
}
}
| src/main/java/org/mcphoton/impl/network/PhotonPacketsManager.java | package org.mcphoton.impl.network;
import com.electronwill.utils.IndexMap;
import com.electronwill.utils.SimpleBag;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.mcphoton.impl.server.PhotonServer;
import org.mcphoton.network.Client;
import org.mcphoton.network.ConnectionState;
import org.mcphoton.network.Packet;
import org.mcphoton.network.PacketHandler;
import org.mcphoton.network.PacketsManager;
import org.mcphoton.network.ProtocolHelper;
/**
* Implementation of the PacketsManager.
*
* @author TheElectronWill
*/
public final class PhotonPacketsManager implements PacketsManager {
private final PhotonServer server;
//--- ServerBound ---
private final IndexMap<Class<? extends Packet>> serverInitPackets, serverStatusPackets, serverLoginPackets, serverPlayPackets;
private final IndexMap<Collection<PacketHandler>> serverInitHandlers, serverStatusHandlers, serverLoginHandlers, serverPlayHandlers;
//--- ClientBound ---
private final IndexMap<Class<? extends Packet>> clientInitPackets, clientStatusPackets, clientLoginPackets, clientPlayPackets;
private final IndexMap<Collection<PacketHandler>> clientInitHandlers, clientStatusHandlers, clientLoginHandlers, clientPlayHandlers;
public PhotonPacketsManager(PhotonServer server) {
this.server = server;
//TODO set the correct sizes
this.serverInitPackets = new IndexMap<>();
this.serverStatusPackets = new IndexMap<>();
this.serverLoginPackets = new IndexMap<>();
this.serverPlayPackets = new IndexMap<>();
this.serverInitHandlers = new IndexMap<>();
this.serverStatusHandlers = new IndexMap<>();
this.serverLoginHandlers = new IndexMap<>();
this.serverPlayHandlers = new IndexMap<>();
this.clientInitPackets = new IndexMap<>();
this.clientStatusPackets = new IndexMap<>();
this.clientLoginPackets = new IndexMap<>();
this.clientPlayPackets = new IndexMap<>();
this.clientInitHandlers = new IndexMap<>();
this.clientStatusHandlers = new IndexMap<>();
this.clientLoginHandlers = new IndexMap<>();
this.clientPlayHandlers = new IndexMap<>();
}
private IndexMap<Class<? extends Packet>> getPacketsMap(ConnectionState state, boolean serverBound) {
if (serverBound) {
switch (state) {
case LOGIN:
return serverLoginPackets;
case PLAY:
return serverPlayPackets;
case STATUS:
return serverStatusPackets;
default:
return serverInitPackets;
}
} else {
switch (state) {
case LOGIN:
return clientLoginPackets;
case PLAY:
return clientPlayPackets;
case STATUS:
return clientStatusPackets;
default:
return clientInitPackets;
}
}
}
private IndexMap<Collection<PacketHandler>> getHandlersMap(ConnectionState state, boolean serverBound) {
if (serverBound) {
switch (state) {
case LOGIN:
return serverLoginHandlers;
case PLAY:
return serverPlayHandlers;
case STATUS:
return serverStatusHandlers;
default:
return serverInitHandlers;
}
} else {
switch (state) {
case LOGIN:
return clientLoginHandlers;
case PLAY:
return clientPlayHandlers;
case STATUS:
return clientStatusHandlers;
default:
return clientInitHandlers;
}
}
}
@Override
public void registerPacket(ConnectionState state, boolean serverBound, int packetId, Class<? extends Packet> packetClass) {
IndexMap<Class<? extends Packet>> map = getPacketsMap(state, serverBound);
synchronized (map) {
map.put(packetId, packetClass);
}
}
@Override
public void registerHandler(ConnectionState state, boolean serverBound, int packetId, PacketHandler<? extends Packet> handler) {
IndexMap<Collection<PacketHandler>> map = getHandlersMap(state, serverBound);
synchronized (map) {
Collection<PacketHandler> handlers = map.get(packetId);
if (handlers == null) {
handlers = new SimpleBag<>();
}
handlers.add(handler);
}
}
@Override
public void unregisterPacket(ConnectionState state, boolean serverBound, int packetId) {
IndexMap<Class<? extends Packet>> map = getPacketsMap(state, serverBound);
synchronized (map) {
map.remove(packetId);
}
}
@Override
public void unregisterHandler(ConnectionState state, boolean serverBound, int packetId, PacketHandler<? extends Packet> handler) {
IndexMap<Collection<PacketHandler>> map = getHandlersMap(state, serverBound);
synchronized (map) {
Collection<PacketHandler> handlers = map.get(packetId);
if (handlers != null) {
handlers.remove(handler);
}
}
}
@Override
public Class<? extends Packet> getRegisteredPacket(ConnectionState state, boolean serverBound, int packetId) {
IndexMap<Class<? extends Packet>> map = getPacketsMap(state, serverBound);
synchronized (map) {
return map.get(packetId);
}
}
@Override
public Collection<PacketHandler> getRegisteredHandlers(ConnectionState state, boolean serverBound, int packetId) {
IndexMap<Collection<PacketHandler>> map = getHandlersMap(state, serverBound);
synchronized (map) {
return map.get(packetId);
}
}
@Override
public void sendPacket(Packet packet, Client client) {
server.networkOutputThread.enqueue(new PacketSending(packet, (PhotonClient) client));
}
@Override
public void sendPacket(Packet packet, Client... clients) {
List clientList = Arrays.asList(clients);
server.networkOutputThread.enqueue(new PacketSending(packet, clientList));
}
@Override
public void sendPacket(Packet packet, Client client, Runnable onSendingCompleted) {
//TODO
throw new UnsupportedOperationException("Not yet implemented, sorry");
}
@Override
public Packet parsePacket(ByteBuffer data, ConnectionState connState, boolean serverBound) {
int packetId = ProtocolHelper.readVarInt(data);
try {
Class<? extends Packet> packetClass = getRegisteredPacket(connState, serverBound, 0);
Packet packet = packetClass.newInstance();
return packet.readFrom(data);
} catch (InstantiationException | IllegalAccessException | NullPointerException ex) {
server.logger.error("Cannot create packet object with id {}", packetId, ex);
}
return null;
}
@Override
public void handle(Packet packet, Client client) {
server.logger.debug("Handling packet {} from {}", packet.toString(), client.getAddress().toString());
IndexMap<Collection<PacketHandler>> map = getHandlersMap(client.getConnectionState(), packet.isServerBound());
synchronized (map) {
Collection<PacketHandler> handlers = map.get(packet.getId());
if (handlers != null) {
for (PacketHandler handler : handlers) {
handler.handle(packet, client);
}
}
}
}
public void registerGamePackets() {
synchronized (serverInitPackets) {
serverInitPackets.put(0, org.mcphoton.network.handshaking.serverbound.HandshakePacket.class);
}
synchronized (serverStatusPackets) {
serverStatusPackets.put(0, org.mcphoton.network.status.serverbound.RequestPacket.class);
serverStatusPackets.put(1, org.mcphoton.network.status.serverbound.PingPacket.class);
}
synchronized (serverLoginPackets) {
serverLoginPackets.put(0, org.mcphoton.network.login.serverbound.LoginStartPacket.class);
serverLoginPackets.put(1, org.mcphoton.network.login.serverbound.EncryptionResponsePacket.class);
}
/* TODO
* synchronized(serverPlayPackets){
*
* }
*/
synchronized (clientStatusPackets) {
clientStatusPackets.put(0, org.mcphoton.network.status.clientbound.ResponsePacket.class);
clientStatusPackets.put(1, org.mcphoton.network.status.clientbound.PongPacket.class);
}
synchronized (clientLoginPackets) {
clientLoginPackets.put(0, org.mcphoton.network.login.clientbound.DisconnectPacket.class);
clientLoginPackets.put(1, org.mcphoton.network.login.clientbound.EncryptionRequestPacket.class);
clientLoginPackets.put(2, org.mcphoton.network.login.clientbound.LoginSuccessPacket.class);
clientLoginPackets.put(3, org.mcphoton.network.login.clientbound.SetCompressionPacket.class);
}
synchronized (clientPlayPackets) {
clientPlayPackets.put(0x20, org.mcphoton.network.play.clientbound.ChunkDataPacket.class);
clientPlayPackets.put(0x03, org.mcphoton.network.play.clientbound.ClientStatusPacket.class);
clientPlayPackets.put(0x23, org.mcphoton.network.play.clientbound.JoinGamePacket.class);
clientPlayPackets.put(0x2E, org.mcphoton.network.play.clientbound.PlayerPositionAndLookPacket.class);
clientPlayPackets.put(0x18, org.mcphoton.network.play.clientbound.PluginMessagePacket.class);
clientPlayPackets.put(0x0D, org.mcphoton.network.play.clientbound.ServerDifficultyPacket.class);
clientPlayPackets.put(0x43, org.mcphoton.network.play.clientbound.SpawnPositionPacket.class);
}
}
}
| Add a method for registering necessary packets' handlers
| src/main/java/org/mcphoton/impl/network/PhotonPacketsManager.java | Add a method for registering necessary packets' handlers | <ide><path>rc/main/java/org/mcphoton/impl/network/PhotonPacketsManager.java
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> import java.util.List;
<add>import org.mcphoton.Photon;
<ide> import org.mcphoton.impl.server.PhotonServer;
<ide> import org.mcphoton.network.Client;
<ide> import org.mcphoton.network.ConnectionState;
<ide> import org.mcphoton.network.PacketHandler;
<ide> import org.mcphoton.network.PacketsManager;
<ide> import org.mcphoton.network.ProtocolHelper;
<add>import org.mcphoton.network.handshaking.serverbound.HandshakePacket;
<add>import org.mcphoton.network.status.clientbound.PongPacket;
<add>import org.mcphoton.network.status.clientbound.ResponsePacket;
<add>import org.mcphoton.network.status.serverbound.PingPacket;
<add>import org.mcphoton.network.status.serverbound.RequestPacket;
<ide>
<ide> /**
<ide> * Implementation of the PacketsManager.
<ide> Collection<PacketHandler> handlers = map.get(packetId);
<ide> if (handlers == null) {
<ide> handlers = new SimpleBag<>();
<add> map.put(packetId, handlers);
<ide> }
<ide> handlers.add(handler);
<ide> }
<ide>
<ide> @Override
<ide> public Packet parsePacket(ByteBuffer data, ConnectionState connState, boolean serverBound) {
<add> server.logger.debug("parse packet: {}, state: {}, serverBound: {}" + serverBound, data, connState, serverBound);
<ide> int packetId = ProtocolHelper.readVarInt(data);
<ide> try {
<ide> Class<? extends Packet> packetClass = getRegisteredPacket(connState, serverBound, 0);
<ide>
<ide> }
<ide>
<add> public void registerPacketHandlers() {
<add> registerHandler(ConnectionState.INIT, true, 0, (HandshakePacket packet, Client client) -> {
<add> server.logger.debug("Set client state to " + packet.nextState);
<add> if (packet.nextState == 1) {
<add> client.setConnectionState(ConnectionState.STATUS);
<add> } else if (packet.nextState == 2) {
<add> client.setConnectionState(ConnectionState.LOGIN);
<add> } else {
<add> //invalid
<add> }
<add> });
<add> registerHandler(ConnectionState.STATUS, true, 0, (RequestPacket packet, Client client) -> {
<add> ResponsePacket response = new ResponsePacket();
<add> StringBuilder jsonBuilder = new StringBuilder("{");
<add> jsonBuilder.append("\"version\":{");
<add> jsonBuilder.append("\"name\":\"").append(Photon.getMinecraftVersion()).append("\",");
<add> jsonBuilder.append("\"protocol\":").append(HandshakePacket.CURRENT_PROTOCOL_VERSION);
<add> jsonBuilder.append("},");
<add> jsonBuilder.append("\"players\":{");
<add> jsonBuilder.append("\"max\":").append(server.maxPlayers).append(',');
<add> jsonBuilder.append("\"online\":").append(server.onlinePlayers.size());
<add> jsonBuilder.append("},");
<add> jsonBuilder.append("\"description\":{");
<add> jsonBuilder.append("\"text\":\"").append(server.motd).append("\"");
<add> jsonBuilder.append("}}");
<add> response.jsonResponse = jsonBuilder.toString();
<add> server.logger.debug("Sending ResponsePacket to the client: {}", jsonBuilder);
<add> sendPacket(response, client);
<add> });
<add> registerHandler(ConnectionState.STATUS, true, 1, (PingPacket packet, Client client) -> {
<add> PongPacket pong = new PongPacket();
<add> pong.payload = System.currentTimeMillis();
<add> sendPacket(pong, client);
<add> });
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | 8aa6e5bfea2c7314deaa1b432554e9e914b09ee7 | 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.web.reactive.socket.client;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import io.undertow.connector.ByteBufferPool;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.client.WebSocketClient.ConnectionBuilder;
import io.undertow.websockets.client.WebSocketClientNegotiation;
import io.undertow.websockets.core.WebSocketChannel;
import org.xnio.IoFuture;
import org.xnio.XnioWorker;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoProcessor;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter;
import org.springframework.web.reactive.socket.adapter.UndertowWebSocketSession;
/**
* Undertow based implementation of {@link WebSocketClient}.
*
* @author Violeta Georgieva
* @author Rossen Stoyanchev
* @since 5.0
*/
public class UndertowWebSocketClient extends WebSocketClientSupport implements WebSocketClient {
private static final int DEFAULT_POOL_BUFFER_SIZE = 8192;
private final XnioWorker worker;
private ByteBufferPool byteBufferPool;
private final Consumer<ConnectionBuilder> builderConsumer;
private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
/**
* Constructor with the {@link XnioWorker} to pass to
* {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder}
* @param worker the Xnio worker
*/
public UndertowWebSocketClient(XnioWorker worker) {
this(worker, builder -> {});
}
/**
* Alternate constructor providing additional control over the
* {@link ConnectionBuilder} for each WebSocket connection.
* @param worker the Xnio worker to use to create {@code ConnectionBuilder}'s
* @param builderConsumer a consumer to configure {@code ConnectionBuilder}'s
*/
public UndertowWebSocketClient(XnioWorker worker, Consumer<ConnectionBuilder> builderConsumer) {
this(worker, new DefaultByteBufferPool(false, DEFAULT_POOL_BUFFER_SIZE), builderConsumer);
}
/**
* Alternate constructor providing additional control over the
* {@link ConnectionBuilder} for each WebSocket connection.
* @param worker the Xnio worker to use to create {@code ConnectionBuilder}'s
* @param byteBufferPool the ByteBufferPool to use to create {@code ConnectionBuilder}'s
* @param builderConsumer a consumer to configure {@code ConnectionBuilder}'s
* @since 5.0.8
*/
public UndertowWebSocketClient(XnioWorker worker, ByteBufferPool byteBufferPool,
Consumer<ConnectionBuilder> builderConsumer) {
Assert.notNull(worker, "XnioWorker must not be null");
Assert.notNull(byteBufferPool, "ByteBufferPool must not be null");
this.worker = worker;
this.byteBufferPool = byteBufferPool;
this.builderConsumer = builderConsumer;
}
/**
* Return the configured {@link XnioWorker}.
*/
public XnioWorker getXnioWorker() {
return this.worker;
}
/**
* Set the {@link io.undertow.connector.ByteBufferPool ByteBufferPool} to pass to
* {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder}.
* <p>By default an indirect {@link io.undertow.server.DefaultByteBufferPool} with a buffer size
* of {@value #DEFAULT_POOL_BUFFER_SIZE} is used.
* @since 5.0.8
*/
public void setByteBufferPool(ByteBufferPool byteBufferPool) {
Assert.notNull(byteBufferPool, "ByteBufferPool must not be null");
this.byteBufferPool = byteBufferPool;
}
/**
* @return the {@link io.undertow.connector.ByteBufferPool} currently used
* for newly created WebSocket sessions by this client
* @since 5.0.8
*/
public ByteBufferPool getByteBufferPool() {
return this.byteBufferPool;
}
/**
* Return the configured {@code Consumer<ConnectionBuilder}.
*/
public Consumer<ConnectionBuilder> getConnectionBuilderConsumer() {
return this.builderConsumer;
}
@Override
public Mono<Void> execute(URI url, WebSocketHandler handler) {
return execute(url, new HttpHeaders(), handler);
}
@Override
public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler) {
return executeInternal(url, headers, handler);
}
private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) {
MonoProcessor<Void> completion = MonoProcessor.create();
return Mono.fromCallable(
() -> {
ConnectionBuilder builder = createConnectionBuilder(url);
List<String> protocols = beforeHandshake(url, headers, handler);
DefaultNegotiation negotiation = new DefaultNegotiation(protocols, headers, builder);
builder.setClientNegotiation(negotiation);
return builder.connect().addNotifier(
new IoFuture.HandlingNotifier<WebSocketChannel, Object>() {
@Override
public void handleDone(WebSocketChannel channel, Object attachment) {
handleChannel(url, handler, completion, negotiation, channel);
}
@Override
public void handleFailed(IOException ex, Object attachment) {
completion.onError(new IllegalStateException("Failed to connect", ex));
}
}, null);
})
.then(completion);
}
/**
* Create a {@link ConnectionBuilder} for the given URI.
* <p>The default implementation creates a builder with the configured
* {@link #getXnioWorker() XnioWorker} and {@link #getByteBufferPool() ByteBufferPool} and
* then passes it to the {@link #getConnectionBuilderConsumer() consumer}
* provided at construction time.
*/
protected ConnectionBuilder createConnectionBuilder(URI url) {
ConnectionBuilder builder = io.undertow.websockets.client.WebSocketClient
.connectionBuilder(getXnioWorker(), getByteBufferPool(), url);
this.builderConsumer.accept(builder);
return builder;
}
private void handleChannel(URI url, WebSocketHandler handler, MonoProcessor<Void> completion,
DefaultNegotiation negotiation, WebSocketChannel channel) {
HandshakeInfo info = afterHandshake(url, negotiation.getResponseHeaders());
UndertowWebSocketSession session = new UndertowWebSocketSession(channel, info, bufferFactory, completion);
UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session);
channel.getReceiveSetter().set(adapter);
channel.resumeReceives();
handler.handle(session).subscribe(session);
}
private static final class DefaultNegotiation extends WebSocketClientNegotiation {
private final HttpHeaders requestHeaders;
private final HttpHeaders responseHeaders = new HttpHeaders();
@Nullable
private final WebSocketClientNegotiation delegate;
public DefaultNegotiation(List<String> protocols, HttpHeaders requestHeaders,
ConnectionBuilder connectionBuilder) {
super(protocols, Collections.emptyList());
this.requestHeaders = requestHeaders;
this.delegate = connectionBuilder.getClientNegotiation();
}
public HttpHeaders getResponseHeaders() {
return this.responseHeaders;
}
@Override
public void beforeRequest(Map<String, List<String>> headers) {
this.requestHeaders.forEach(headers::put);
if (this.delegate != null) {
this.delegate.beforeRequest(headers);
}
}
@Override
public void afterRequest(Map<String, List<String>> headers) {
headers.forEach(this.responseHeaders::put);
if (this.delegate != null) {
this.delegate.afterRequest(headers);
}
}
}
}
| spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/UndertowWebSocketClient.java | /*
* Copyright 2002-2017 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.web.reactive.socket.client;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.client.WebSocketClient.ConnectionBuilder;
import io.undertow.websockets.client.WebSocketClientNegotiation;
import io.undertow.websockets.core.WebSocketChannel;
import org.xnio.IoFuture;
import org.xnio.XnioWorker;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoProcessor;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter;
import org.springframework.web.reactive.socket.adapter.UndertowWebSocketSession;
/**
* Undertow based implementation of {@link WebSocketClient}.
*
* @author Violeta Georgieva
* @author Rossen Stoyanchev
* @since 5.0
*/
public class UndertowWebSocketClient extends WebSocketClientSupport implements WebSocketClient {
private static final int DEFAULT_POOL_BUFFER_SIZE = 8192;
private final XnioWorker worker;
private final Consumer<ConnectionBuilder> builderConsumer;
private int poolBufferSize = DEFAULT_POOL_BUFFER_SIZE;
private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
/**
* Constructor with the {@link XnioWorker} to pass to
* {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder}
* @param worker the Xnio worker
*/
public UndertowWebSocketClient(XnioWorker worker) {
this(worker, builder -> {});
}
/**
* Alternate constructor providing additional control over the
* {@link ConnectionBuilder} for each WebSocket connection.
* @param worker the Xnio worker to use to create {@code ConnectionBuilder}'s
* @param builderConsumer a consumer to configure {@code ConnectionBuilder}'s
*/
public UndertowWebSocketClient(XnioWorker worker, Consumer<ConnectionBuilder> builderConsumer) {
Assert.notNull(worker, "XnioWorker is required");
this.worker = worker;
this.builderConsumer = builderConsumer;
}
/**
* Return the configured {@link XnioWorker}.
*/
public XnioWorker getXnioWorker() {
return this.worker;
}
/**
* Return the configured {@code Consumer<ConnectionBuilder}.
*/
public Consumer<ConnectionBuilder> getConnectionBuilderConsumer() {
return this.builderConsumer;
}
/**
* Configure the size of the {@link io.undertow.connector.ByteBufferPool
* ByteBufferPool} to pass to
* {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder}.
* <p>By default the buffer size is set to 8192.
*/
public void setPoolBufferSize(int poolBufferSize) {
this.poolBufferSize = poolBufferSize;
}
/**
* Return the size for Undertow's WebSocketClient {@code ByteBufferPool}.
*/
public int getPoolBufferSize() {
return this.poolBufferSize;
}
@Override
public Mono<Void> execute(URI url, WebSocketHandler handler) {
return execute(url, new HttpHeaders(), handler);
}
@Override
public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler) {
return executeInternal(url, headers, handler);
}
private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) {
MonoProcessor<Void> completion = MonoProcessor.create();
return Mono.fromCallable(
() -> {
ConnectionBuilder builder = createConnectionBuilder(url);
List<String> protocols = beforeHandshake(url, headers, handler);
DefaultNegotiation negotiation = new DefaultNegotiation(protocols, headers, builder);
builder.setClientNegotiation(negotiation);
return builder.connect().addNotifier(
new IoFuture.HandlingNotifier<WebSocketChannel, Object>() {
@Override
public void handleDone(WebSocketChannel channel, Object attachment) {
handleChannel(url, handler, completion, negotiation, channel);
}
@Override
public void handleFailed(IOException ex, Object attachment) {
completion.onError(new IllegalStateException("Failed to connect", ex));
}
}, null);
})
.then(completion);
}
/**
* Create a {@link ConnectionBuilder} for the given URI.
* <p>The default implementation creates a builder with the configured
* {@link #getXnioWorker() XnioWorker} and {@link #getPoolBufferSize()} and
* then passes it to the {@link #getConnectionBuilderConsumer() consumer}
* provided at construction time.
*/
protected ConnectionBuilder createConnectionBuilder(URI url) {
ConnectionBuilder builder = io.undertow.websockets.client.WebSocketClient
.connectionBuilder(getXnioWorker(),
new DefaultByteBufferPool(false, getPoolBufferSize()), url);
this.builderConsumer.accept(builder);
return builder;
}
private void handleChannel(URI url, WebSocketHandler handler, MonoProcessor<Void> completion,
DefaultNegotiation negotiation, WebSocketChannel channel) {
HandshakeInfo info = afterHandshake(url, negotiation.getResponseHeaders());
UndertowWebSocketSession session = new UndertowWebSocketSession(channel, info, bufferFactory, completion);
UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session);
channel.getReceiveSetter().set(adapter);
channel.resumeReceives();
handler.handle(session).subscribe(session);
}
private static final class DefaultNegotiation extends WebSocketClientNegotiation {
private final HttpHeaders requestHeaders;
private final HttpHeaders responseHeaders = new HttpHeaders();
@Nullable
private final WebSocketClientNegotiation delegate;
public DefaultNegotiation(List<String> protocols, HttpHeaders requestHeaders,
ConnectionBuilder connectionBuilder) {
super(protocols, Collections.emptyList());
this.requestHeaders = requestHeaders;
this.delegate = connectionBuilder.getClientNegotiation();
}
public HttpHeaders getResponseHeaders() {
return this.responseHeaders;
}
@Override
public void beforeRequest(Map<String, List<String>> headers) {
this.requestHeaders.forEach(headers::put);
if (this.delegate != null) {
this.delegate.beforeRequest(headers);
}
}
@Override
public void afterRequest(Map<String, List<String>> headers) {
headers.forEach(this.responseHeaders::put);
if (this.delegate != null) {
this.delegate.afterRequest(headers);
}
}
}
}
| Undertow WebSocket sessions use shared ByteBufferPool
Issues: SPR-16957
| spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/UndertowWebSocketClient.java | Undertow WebSocket sessions use shared ByteBufferPool | <ide><path>pring-webflux/src/main/java/org/springframework/web/reactive/socket/client/UndertowWebSocketClient.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.util.Map;
<ide> import java.util.function.Consumer;
<ide>
<add>import io.undertow.connector.ByteBufferPool;
<ide> import io.undertow.server.DefaultByteBufferPool;
<ide> import io.undertow.websockets.client.WebSocketClient.ConnectionBuilder;
<ide> import io.undertow.websockets.client.WebSocketClientNegotiation;
<ide>
<ide> private final XnioWorker worker;
<ide>
<add> private ByteBufferPool byteBufferPool;
<add>
<ide> private final Consumer<ConnectionBuilder> builderConsumer;
<del>
<del> private int poolBufferSize = DEFAULT_POOL_BUFFER_SIZE;
<ide>
<ide> private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
<ide>
<ide> * @param builderConsumer a consumer to configure {@code ConnectionBuilder}'s
<ide> */
<ide> public UndertowWebSocketClient(XnioWorker worker, Consumer<ConnectionBuilder> builderConsumer) {
<del> Assert.notNull(worker, "XnioWorker is required");
<add> this(worker, new DefaultByteBufferPool(false, DEFAULT_POOL_BUFFER_SIZE), builderConsumer);
<add> }
<add>
<add> /**
<add> * Alternate constructor providing additional control over the
<add> * {@link ConnectionBuilder} for each WebSocket connection.
<add> * @param worker the Xnio worker to use to create {@code ConnectionBuilder}'s
<add> * @param byteBufferPool the ByteBufferPool to use to create {@code ConnectionBuilder}'s
<add> * @param builderConsumer a consumer to configure {@code ConnectionBuilder}'s
<add> * @since 5.0.8
<add> */
<add> public UndertowWebSocketClient(XnioWorker worker, ByteBufferPool byteBufferPool,
<add> Consumer<ConnectionBuilder> builderConsumer) {
<add>
<add> Assert.notNull(worker, "XnioWorker must not be null");
<add> Assert.notNull(byteBufferPool, "ByteBufferPool must not be null");
<ide> this.worker = worker;
<add> this.byteBufferPool = byteBufferPool;
<ide> this.builderConsumer = builderConsumer;
<ide> }
<ide>
<ide> }
<ide>
<ide> /**
<add> * Set the {@link io.undertow.connector.ByteBufferPool ByteBufferPool} to pass to
<add> * {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder}.
<add> * <p>By default an indirect {@link io.undertow.server.DefaultByteBufferPool} with a buffer size
<add> * of {@value #DEFAULT_POOL_BUFFER_SIZE} is used.
<add> * @since 5.0.8
<add> */
<add> public void setByteBufferPool(ByteBufferPool byteBufferPool) {
<add> Assert.notNull(byteBufferPool, "ByteBufferPool must not be null");
<add> this.byteBufferPool = byteBufferPool;
<add> }
<add>
<add> /**
<add> * @return the {@link io.undertow.connector.ByteBufferPool} currently used
<add> * for newly created WebSocket sessions by this client
<add> * @since 5.0.8
<add> */
<add> public ByteBufferPool getByteBufferPool() {
<add> return this.byteBufferPool;
<add> }
<add>
<add> /**
<ide> * Return the configured {@code Consumer<ConnectionBuilder}.
<ide> */
<ide> public Consumer<ConnectionBuilder> getConnectionBuilderConsumer() {
<ide> return this.builderConsumer;
<del> }
<del>
<del> /**
<del> * Configure the size of the {@link io.undertow.connector.ByteBufferPool
<del> * ByteBufferPool} to pass to
<del> * {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder}.
<del> * <p>By default the buffer size is set to 8192.
<del> */
<del> public void setPoolBufferSize(int poolBufferSize) {
<del> this.poolBufferSize = poolBufferSize;
<del> }
<del>
<del> /**
<del> * Return the size for Undertow's WebSocketClient {@code ByteBufferPool}.
<del> */
<del> public int getPoolBufferSize() {
<del> return this.poolBufferSize;
<ide> }
<ide>
<ide>
<ide> /**
<ide> * Create a {@link ConnectionBuilder} for the given URI.
<ide> * <p>The default implementation creates a builder with the configured
<del> * {@link #getXnioWorker() XnioWorker} and {@link #getPoolBufferSize()} and
<add> * {@link #getXnioWorker() XnioWorker} and {@link #getByteBufferPool() ByteBufferPool} and
<ide> * then passes it to the {@link #getConnectionBuilderConsumer() consumer}
<ide> * provided at construction time.
<ide> */
<ide> protected ConnectionBuilder createConnectionBuilder(URI url) {
<ide> ConnectionBuilder builder = io.undertow.websockets.client.WebSocketClient
<del> .connectionBuilder(getXnioWorker(),
<del> new DefaultByteBufferPool(false, getPoolBufferSize()), url);
<add> .connectionBuilder(getXnioWorker(), getByteBufferPool(), url);
<ide> this.builderConsumer.accept(builder);
<ide> return builder;
<ide> } |
|
Java | apache-2.0 | 0d236b502538a674cfb032a5cfbbe2f4e859ce9d | 0 | mozafari/verdict,mozafari/verdict,mozafari/verdict,mozafari/verdict,mozafari/verdict | package org.verdictdb.core.querying.simplifier;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Optional;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.spark.sql.catalyst.expressions.Alias;
import org.verdictdb.connection.DbmsQueryResult;
import org.verdictdb.core.execplan.ExecutionInfoToken;
import org.verdictdb.core.querying.*;
import org.verdictdb.core.sqlobject.*;
import org.verdictdb.exception.VerdictDBException;
/**
* Used for simplifying two nodes into one. This class may be used in a recursively way to simplify
* an arbitrary deep nodes into a single node (as long as the condition is satisfied).
* <p>
* Assumptions:
* <ol>
* <li>
* The token of a child node must not rely on its query results. Nodes like CreateTableAsSelect
* is supposed to pass the name of a temporary table, which doesn't depend on the its query result.
* </li>
* </ol>
* <p>
* The logic based on the above assumption can be found in the createQuery() method.
* Traditionally, createToken() must use the result of createQuery(); however, based on the
* assumption, the token of the child is created without actually running its query. Note that the
* child's select query is consolidated into the parent query as a subquery.
*
* @author Yongjoo Park
*/
public class ConsolidatedExecutionNode extends QueryNodeWithPlaceHolders {
private static final long serialVersionUID = -561220173745897906L;
private QueryNodeWithPlaceHolders parentNode;
private CreateTableAsSelectNode childNode;
// This records the alias of selectQuery of ConsolidatedExecutionNode.
// It is used to resolve the case of asterisk column.
private List<String> selectQueryColumnAlias = new ArrayList<>();
private final String asteriskAlias = "verdictdb_asterisk_alias";
public ConsolidatedExecutionNode(
SelectQuery selectQuery, QueryNodeWithPlaceHolders parent, CreateTableAsSelectNode child) {
super(parent.getId(), selectQuery);
parentNode = parent;
childNode = child;
// for (PlaceHolderRecord record : parentNode.getPlaceholderRecords()) {
// addPlaceholderRecord(record);
// }
// for (PlaceHolderRecord record : childNode.getPlaceholderRecords()) {
// addPlaceholderRecord(record);
// }
}
public ExecutableNodeBase getParentNode() {
return parentNode;
}
public ExecutableNodeBase getChildNode() {
return childNode;
}
@Override
public PlaceHolderRecord removePlaceholderRecordForChannel(int channel) {
PlaceHolderRecord record = parentNode.removePlaceholderRecordForChannel(channel);
if (record != null) {
return record;
}
record = childNode.removePlaceholderRecordForChannel(channel);
return record;
}
public static ConsolidatedExecutionNode create(
QueryNodeWithPlaceHolders parent, CreateTableAsSelectNode child) {
SelectQuery parentQuery = parent.getSelectQuery();
// find placeholders in the parent query and replace with the child query
int childChannel = parent.getChannelForSource(child);
PlaceHolderRecord placeHolderToRemove = parent.removePlaceholderRecordForChannel(childChannel);
BaseTable baseTableToRemove = placeHolderToRemove.getPlaceholderTable();
// replace in the source list
parentQuery = (SelectQuery) consolidateSource(parentQuery, child, baseTableToRemove);
// filter: replace the placeholder BaseTable (in the filter list) with
// the SelectQuery of the child
Optional<UnnamedColumn> parentFilterOptional = parentQuery.getFilter();
if (parentFilterOptional.isPresent()) {
UnnamedColumn originalFilter = parentFilterOptional.get();
UnnamedColumn newFilter = consolidateFilter(originalFilter, child, baseTableToRemove);
parentQuery.clearFilter();
parentQuery.addFilterByAnd(newFilter);
}
ConsolidatedExecutionNode node =
new ConsolidatedExecutionNode(parentQuery, parent, child);
return node;
}
/**
* May consonlidate a single source with `child`. This is a helper function for simplify2().
*
* @param originalSource The original source
* @param child The child node
* @param baseTableToRemove The placeholder to be replaced
* @return A new source
*/
private static AbstractRelation consolidateSource(
AbstractRelation originalSource, ExecutableNodeBase child, BaseTable baseTableToRemove) {
// exception
if (!(child instanceof QueryNodeBase)) {
return originalSource;
}
SelectQuery childQuery = ((QueryNodeBase) child).getSelectQuery();
if (originalSource instanceof BaseTable) {
BaseTable baseTableSource = (BaseTable) originalSource;
if (baseTableSource.equals(baseTableToRemove)) {
childQuery.setAliasName(baseTableToRemove.getAliasName().get());
return childQuery;
} else {
return originalSource;
}
} else if (originalSource instanceof JoinTable) {
JoinTable joinTableSource = (JoinTable) originalSource;
List<AbstractRelation> joinSourceList = joinTableSource.getJoinList();
List<AbstractRelation> newJoinSourceList = new ArrayList<>();
for (AbstractRelation joinSource : joinSourceList) {
newJoinSourceList.add(consolidateSource(joinSource, child, baseTableToRemove));
}
joinTableSource.setJoinList(newJoinSourceList);
return joinTableSource;
} else if (originalSource instanceof SelectQuery) {
SelectQuery selectQuerySource = (SelectQuery) originalSource;
List<AbstractRelation> originalFromList = selectQuerySource.getFromList();
List<AbstractRelation> newFromList = new ArrayList<>();
for (AbstractRelation source : originalFromList) {
AbstractRelation newSource = consolidateSource(source, child, baseTableToRemove);
newFromList.add(newSource);
}
selectQuerySource.setFromList(newFromList);
return selectQuerySource;
} else {
return originalSource;
}
}
/**
* May consolidate a single filter with `child`. This is a helper function for simplify2().
*
* @param originalFilter The original filter
* @param child The child node
* @param baseTableToRemove The placeholder to be replaced
* @return
*/
private static UnnamedColumn consolidateFilter(
UnnamedColumn originalFilter, ExecutableNodeBase child, BaseTable baseTableToRemove) {
// exception
if (!(child instanceof QueryNodeBase)) {
return originalFilter;
}
SelectQuery childSelectQuery = ((QueryNodeBase) child).getSelectQuery();
if (originalFilter instanceof ColumnOp) {
ColumnOp originalColumnOp = (ColumnOp) originalFilter;
List<UnnamedColumn> newOperands = new ArrayList<>();
for (UnnamedColumn o : originalColumnOp.getOperands()) {
newOperands.add(consolidateFilter(o, child, baseTableToRemove));
}
ColumnOp newColumnOp = new ColumnOp(originalColumnOp.getOpType(), newOperands);
return newColumnOp;
} else if (originalFilter instanceof SubqueryColumn) {
SubqueryColumn originalSubquery = (SubqueryColumn) originalFilter;
SelectQuery subquery = originalSubquery.getSubquery();
List<AbstractRelation> subqueryFromList = subquery.getFromList();
if (subqueryFromList.size() == 1 && subqueryFromList.get(0).equals(baseTableToRemove)) {
originalSubquery.setSubquery(childSelectQuery);
}
return originalSubquery;
}
return originalFilter;
}
@Override
public SqlConvertible createQuery(List<ExecutionInfoToken> tokens) throws VerdictDBException {
// this will replace the placeholders contained the subquery.
childNode.createQuery(tokens);
ExecutionInfoToken childToken = childNode.createToken(null);
// also pass the tokens possibly created by child.
List<ExecutionInfoToken> newTokens = new ArrayList<>();
newTokens.addAll(tokens);
newTokens.add(childToken);
// this is a bad trick to use the createQuery function of the parent node.
// we set the consolidated query (of this node) to the parentNode, and let the parent node
// create a new query using the consolidated select query.
// for now, the only use case is that the parent node creates a "create table ..." query that
// contains the consolidated select query.
parentNode.setSelectQuery(selectQuery);
SqlConvertible consolidatedQuery = parentNode.createQuery(newTokens);
// Distinguish aggregated column
if (parentNode instanceof SelectAllExecutionNode) {
List<Boolean> isAggregated = new ArrayList<>();
for (SelectItem sel : selectQuery.getSelectList()) {
if (sel.isAggregateColumn()) {
isAggregated.add(true);
} else {
isAggregated.add(false);
}
if (sel instanceof AliasedColumn) {
selectQueryColumnAlias.add(((AliasedColumn) sel).getAliasName());
} else {
selectQueryColumnAlias.add(asteriskAlias);
}
}
((SelectAllExecutionNode) parentNode).setAggregateColumn(isAggregated);
}
return consolidatedQuery;
}
@Override
public ExecutionInfoToken createToken(DbmsQueryResult result) {
// pass the information from the internal parent node
ExecutionInfoToken token = parentNode.createToken(result);
// Addition check that the query is a query contains Asterisk column that without asyncAggExecutionNode.
// For instance, query like 'select * from lineitem'. In that case, all the values of isAggregate field
// are false.
if (token.containsKey("queryResult")) {
DbmsQueryResult queryResult = (DbmsQueryResult) token.getValue("queryResult");
if (queryResult.getColumnCount() != queryResult.getMetaData().isAggregate.size()) {
List<Boolean> isAggregate = new ArrayList<>();
for (int i = 0; i < queryResult.getColumnCount(); i++) {
isAggregate.add(false);
}
for (int i = 0; i < queryResult.getMetaData().isAggregate.size(); i++) {
if (!selectQueryColumnAlias.get(i).equals(asteriskAlias)) {
int idx = 0;
// Get the index of the alias name in the columnName field of the queryResult.
while (!selectQueryColumnAlias.get(i).equals(queryResult.getColumnName(idx))) {
idx++;
}
isAggregate.set(idx, queryResult.getMetaData().isAggregate.get(i));
}
}
queryResult.getMetaData().isAggregate = isAggregate;
}
}
return token;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
.append("subscriberCount", getSubscribers().size())
.append("sourceCount", getSources().size())
.append("parent", parentNode)
.append("child", childNode)
.toString();
}
}
| src/main/java/org/verdictdb/core/querying/simplifier/ConsolidatedExecutionNode.java | package org.verdictdb.core.querying.simplifier;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Optional;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.spark.sql.catalyst.expressions.Alias;
import org.verdictdb.connection.DbmsQueryResult;
import org.verdictdb.core.execplan.ExecutionInfoToken;
import org.verdictdb.core.querying.*;
import org.verdictdb.core.sqlobject.*;
import org.verdictdb.exception.VerdictDBException;
/**
* Used for simplifying two nodes into one. This class may be used in a recursively way to simplify
* an arbitrary deep nodes into a single node (as long as the condition is satisfied).
* <p>
* Assumptions:
* <ol>
* <li>
* The token of a child node must not rely on its query results. Nodes like CreateTableAsSelect
* is supposed to pass the name of a temporary table, which doesn't depend on the its query result.
* </li>
* </ol>
* <p>
* The logic based on the above assumption can be found in the createQuery() method.
* Traditionally, createToken() must use the result of createQuery(); however, based on the
* assumption, the token of the child is created without actually running its query. Note that the
* child's select query is consolidated into the parent query as a subquery.
*
* @author Yongjoo Park
*/
public class ConsolidatedExecutionNode extends QueryNodeWithPlaceHolders {
private static final long serialVersionUID = -561220173745897906L;
private QueryNodeWithPlaceHolders parentNode;
private CreateTableAsSelectNode childNode;
// This records the alias of selectQuery of ConsolidatedExecutionNode.
// It is used to resolve the case of asterisk column.
private List<String> selectQueryColumnAlias = new ArrayList<>();
private final String asteriskAlias = "verdictdb_asterisk_alias";
public ConsolidatedExecutionNode(
SelectQuery selectQuery, QueryNodeWithPlaceHolders parent, CreateTableAsSelectNode child) {
super(parent.getId(), selectQuery);
parentNode = parent;
childNode = child;
// for (PlaceHolderRecord record : parentNode.getPlaceholderRecords()) {
// addPlaceholderRecord(record);
// }
// for (PlaceHolderRecord record : childNode.getPlaceholderRecords()) {
// addPlaceholderRecord(record);
// }
}
public ExecutableNodeBase getParentNode() {
return parentNode;
}
public ExecutableNodeBase getChildNode() {
return childNode;
}
@Override
public PlaceHolderRecord removePlaceholderRecordForChannel(int channel) {
PlaceHolderRecord record = parentNode.removePlaceholderRecordForChannel(channel);
if (record != null) {
return record;
}
record = childNode.removePlaceholderRecordForChannel(channel);
return record;
}
public static ConsolidatedExecutionNode create(
QueryNodeWithPlaceHolders parent, CreateTableAsSelectNode child) {
SelectQuery parentQuery = parent.getSelectQuery();
// find placeholders in the parent query and replace with the child query
int childChannel = parent.getChannelForSource(child);
PlaceHolderRecord placeHolderToRemove = parent.removePlaceholderRecordForChannel(childChannel);
BaseTable baseTableToRemove = placeHolderToRemove.getPlaceholderTable();
// replace in the source list
parentQuery = (SelectQuery) consolidateSource(parentQuery, child, baseTableToRemove);
// filter: replace the placeholder BaseTable (in the filter list) with
// the SelectQuery of the child
Optional<UnnamedColumn> parentFilterOptional = parentQuery.getFilter();
if (parentFilterOptional.isPresent()) {
UnnamedColumn originalFilter = parentFilterOptional.get();
UnnamedColumn newFilter = consolidateFilter(originalFilter, child, baseTableToRemove);
parentQuery.clearFilter();
parentQuery.addFilterByAnd(newFilter);
}
ConsolidatedExecutionNode node =
new ConsolidatedExecutionNode(parentQuery, parent, child);
return node;
}
/**
* May consonlidate a single source with `child`. This is a helper function for simplify2().
*
* @param originalSource The original source
* @param child The child node
* @param baseTableToRemove The placeholder to be replaced
* @return A new source
*/
private static AbstractRelation consolidateSource(
AbstractRelation originalSource, ExecutableNodeBase child, BaseTable baseTableToRemove) {
// exception
if (!(child instanceof QueryNodeBase)) {
return originalSource;
}
SelectQuery childQuery = ((QueryNodeBase) child).getSelectQuery();
if (originalSource instanceof BaseTable) {
BaseTable baseTableSource = (BaseTable) originalSource;
if (baseTableSource.equals(baseTableToRemove)) {
childQuery.setAliasName(baseTableToRemove.getAliasName().get());
return childQuery;
} else {
return originalSource;
}
} else if (originalSource instanceof JoinTable) {
JoinTable joinTableSource = (JoinTable) originalSource;
List<AbstractRelation> joinSourceList = joinTableSource.getJoinList();
List<AbstractRelation> newJoinSourceList = new ArrayList<>();
for (AbstractRelation joinSource : joinSourceList) {
newJoinSourceList.add(consolidateSource(joinSource, child, baseTableToRemove));
}
joinTableSource.setJoinList(newJoinSourceList);
return joinTableSource;
} else if (originalSource instanceof SelectQuery) {
SelectQuery selectQuerySource = (SelectQuery) originalSource;
List<AbstractRelation> originalFromList = selectQuerySource.getFromList();
List<AbstractRelation> newFromList = new ArrayList<>();
for (AbstractRelation source : originalFromList) {
AbstractRelation newSource = consolidateSource(source, child, baseTableToRemove);
newFromList.add(newSource);
}
selectQuerySource.setFromList(newFromList);
return selectQuerySource;
} else {
return originalSource;
}
}
/**
* May consolidate a single filter with `child`. This is a helper function for simplify2().
*
* @param originalFilter The original filter
* @param child The child node
* @param baseTableToRemove The placeholder to be replaced
* @return
*/
private static UnnamedColumn consolidateFilter(
UnnamedColumn originalFilter, ExecutableNodeBase child, BaseTable baseTableToRemove) {
// exception
if (!(child instanceof QueryNodeBase)) {
return originalFilter;
}
SelectQuery childSelectQuery = ((QueryNodeBase) child).getSelectQuery();
if (originalFilter instanceof ColumnOp) {
ColumnOp originalColumnOp = (ColumnOp) originalFilter;
List<UnnamedColumn> newOperands = new ArrayList<>();
for (UnnamedColumn o : originalColumnOp.getOperands()) {
newOperands.add(consolidateFilter(o, child, baseTableToRemove));
}
ColumnOp newColumnOp = new ColumnOp(originalColumnOp.getOpType(), newOperands);
return newColumnOp;
} else if (originalFilter instanceof SubqueryColumn) {
SubqueryColumn originalSubquery = (SubqueryColumn) originalFilter;
SelectQuery subquery = originalSubquery.getSubquery();
List<AbstractRelation> subqueryFromList = subquery.getFromList();
if (subqueryFromList.size() == 1 && subqueryFromList.get(0).equals(baseTableToRemove)) {
originalSubquery.setSubquery(childSelectQuery);
}
return originalSubquery;
}
return originalFilter;
}
@Override
public SqlConvertible createQuery(List<ExecutionInfoToken> tokens) throws VerdictDBException {
// this will replace the placeholders contained the subquery.
childNode.createQuery(tokens);
ExecutionInfoToken childToken = childNode.createToken(null);
// also pass the tokens possibly created by child.
List<ExecutionInfoToken> newTokens = new ArrayList<>();
newTokens.addAll(tokens);
newTokens.add(childToken);
// this is a bad trick to use the createQuery function of the parent node.
// we set the consolidated query (of this node) to the parentNode, and let the parent node
// create a new query using the consolidated select query.
// for now, the only use case is that the parent node creates a "create table ..." query that
// contains the consolidated select query.
parentNode.setSelectQuery(selectQuery);
SqlConvertible consolidatedQuery = parentNode.createQuery(newTokens);
// Distinguish aggregated column
if (parentNode instanceof SelectAllExecutionNode) {
List<Boolean> isAggregated = new ArrayList<>();
for (SelectItem sel : selectQuery.getSelectList()) {
if (sel.isAggregateColumn()) {
isAggregated.add(true);
} else {
isAggregated.add(false);
}
if (sel instanceof AliasedColumn) {
selectQueryColumnAlias.add(((AliasedColumn) sel).getAliasName());
} else {
selectQueryColumnAlias.add(asteriskAlias);
}
}
((SelectAllExecutionNode) parentNode).setAggregateColumn(isAggregated);
}
return consolidatedQuery;
}
@Override
public ExecutionInfoToken createToken(DbmsQueryResult result) {
// pass the information from the internal parent node
ExecutionInfoToken token = parentNode.createToken(result);
// Addition check that the query is a query contains Asterisk column that without asyncAggExecutionNode.
// For instance, query like 'select * from lineitem'. In that case, all the values of isAggregate field
// are false.
if (token.containsKey("queryResult")) {
DbmsQueryResult queryResult = (DbmsQueryResult) token.getValue("queryResult");
if (queryResult.getColumnCount() != queryResult.getMetaData().isAggregate.size()) {
List<Boolean> isAggregate = new ArrayList<>();
for (int i = 0; i < queryResult.getColumnCount(); i++) {
isAggregate.add(false);
}
for (int i = 0; i < queryResult.getMetaData().isAggregate.size(); i++) {
if (!selectQueryColumnAlias.get(i).equals(asteriskAlias)) {
int idx = 0;
while (!selectQueryColumnAlias.get(i).equals(queryResult.getColumnName(idx))) {
idx++;
}
isAggregate.set(idx, queryResult.getMetaData().isAggregate.get(i));
}
}
queryResult.getMetaData().isAggregate = isAggregate;
}
}
return token;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
.append("subscriberCount", getSubscribers().size())
.append("sourceCount", getSources().size())
.append("parent", parentNode)
.append("child", childNode)
.toString();
}
}
| add comment
| src/main/java/org/verdictdb/core/querying/simplifier/ConsolidatedExecutionNode.java | add comment | <ide><path>rc/main/java/org/verdictdb/core/querying/simplifier/ConsolidatedExecutionNode.java
<ide> for (int i = 0; i < queryResult.getMetaData().isAggregate.size(); i++) {
<ide> if (!selectQueryColumnAlias.get(i).equals(asteriskAlias)) {
<ide> int idx = 0;
<add> // Get the index of the alias name in the columnName field of the queryResult.
<ide> while (!selectQueryColumnAlias.get(i).equals(queryResult.getColumnName(idx))) {
<ide> idx++;
<ide> } |
|
Java | apache-2.0 | c58788f1d4e84b9e5f2da7fee56edb453134473a | 0 | parker20121/nxcore,parker20121/nxcore,parker20121/nxcore,parker20121/nxcore,parker20121/nxcore | package mil.darpa.nxcore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
/**
* MapReduce class used to split the NXCore Windows output running on Linux.
*
* @author Matt Parker ([email protected])
*
*/
public class SplitFiles {
/**
* Spilt the file data into the four separate data types.
*/
public static class SplitFilesMapper extends Mapper<LongWritable, Text, Text, Text>{
public static final int RECORD_TYPE = 0;
public static final int RECORD = 1;
@Override
protected void map( LongWritable key, Text value, Context context ) throws IOException, InterruptedException {
//Go from 20140101.XA.nvc.txt.bz2 -> 20140101
String filekey = ((FileSplit) context.getInputSplit()).getPath().getName().substring(0,8);
//Split record type, record
String[] components = value.toString().split(",",1);
//Segment data by file.
Text filesplit = new Text( filekey + "-" + components[RECORD_TYPE] );
context.write( filesplit, new Text(components[RECORD]) );
}
}
/**
* Aggregate records into files by day and record type.
*/
public static class SplitFilesReducer extends Reducer<Text,Text,NullWritable,Text> {
public static final int RECORD_TYPE = 1;
public static final int RECORD_DATE = 0;
MultipleOutputs<NullWritable,Text> mos;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
mos = new MultipleOutputs<NullWritable,Text>(context);
}
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
String[] components = key.toString().split("-",1);
String year = components[RECORD_DATE].substring(0,4);
String month = components[RECORD_DATE].substring(4,6);
StringBuffer outfile = new StringBuffer();
outfile.append("/")
.append( components[RECORD_TYPE] )
.append("/")
.append( year )
.append("/")
.append( month )
.append("/")
.append( components[RECORD_DATE]); //date
for ( Text value : values ){
mos.write( NullWritable.get(), value, outfile.toString() );
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
super.cleanup(context);
mos.close();
}
}
/**
* Set the MapReduce job configuration.
*
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception {
Configuration conf = new Configuration();
GenericOptionsParser optionParser = new GenericOptionsParser(conf, args);
String[] remainingArgs = optionParser.getRemainingArgs();
if (!(remainingArgs.length != 2)) {
System.err.println("Usage: SplitFiles <in> <out>");
System.exit(0);
}
Job job = Job.getInstance(conf,"split-nxcore-files");
job.setJarByClass(SplitFiles.class);
job.setMapperClass(SplitFiles.SplitFilesMapper.class);
job.setReducerClass(SplitFiles.SplitFilesReducer.class);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(Text.class);
List<String> otherArgs = new ArrayList<String>();
for (int i=0; i < remainingArgs.length; ++i) {
otherArgs.add(remainingArgs[i]);
}
FileInputFormat.addInputPath(job, new Path( otherArgs.get(0) ));
FileOutputFormat.setOutputPath(job, new Path( otherArgs.get(1) ));
TextOutputFormat.setCompressOutput(job, true);
TextOutputFormat.setOutputCompressorClass(job, BZip2Codec.class );
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| nxcore-split/src/main/java/mil/darpa/nxcore/SplitFiles.java | package mil.darpa.nxcore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
/**
* MapReduce class used to split the NXCore Windows output running on Linux.
*
* @author Matt Parker ([email protected])
*
*/
public class SplitFiles {
/**
* Spilt the file data into the four separate data types.
*/
public static class SplitFilesMapper extends Mapper<LongWritable, Text, Text, Text>{
public static final int RECORD_TYPE = 0;
public static final int RECORD = 1;
@Override
protected void map( LongWritable key, Text value, Context context ) throws IOException, InterruptedException {
//Go from 20140101.XA.nvc.txt.bz2 -> 20140101
String filekey = ((FileSplit) context.getInputSplit()).getPath().getName().substring(0,8);
//Split record type, record
String[] components = value.toString().split(",",1);
//Segment data by file.
Text filesplit = new Text( filekey + "-" + components[RECORD_TYPE] );
context.write( filesplit, new Text(components[RECORD]) );
}
}
/**
* Aggregate records into files by day and record type.
*/
public static class SplitFilesReducer extends Reducer<Text,Text,NullWritable,Text> {
MultipleOutputs<NullWritable,Text> mos;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
mos = new MultipleOutputs<NullWritable,Text>(context);
}
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
String[] components = key.toString().split("-",1);
String year = components[0].substring(0,4);
String month = components[0].substring(4,6);
StringBuffer outfile = new StringBuffer();
outfile.append("/")
.append( components[1] )
.append("/")
.append( year )
.append("/")
.append( month )
.append("/")
.append( components[0 ]);
for ( Text value : values ){
mos.write( NullWritable.get(), value, outfile.toString() );
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
super.cleanup(context);
mos.close();
}
}
/**
* Set the MapReduce job configuration.
*
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception {
Configuration conf = new Configuration();
GenericOptionsParser optionParser = new GenericOptionsParser(conf, args);
String[] remainingArgs = optionParser.getRemainingArgs();
if (!(remainingArgs.length != 2)) {
System.err.println("Usage: SplitFiles <in> <out>");
System.exit(2);
}
Job job = Job.getInstance(conf,"split-nxcore-files");
job.setJarByClass(SplitFiles.class);
job.setMapperClass(SplitFiles.SplitFilesMapper.class);
job.setReducerClass(SplitFiles.SplitFilesReducer.class);
job.setOutputKeyClass(LongWritable.class);
job.setOutputValueClass(Text.class);
List<String> otherArgs = new ArrayList<String>();
for (int i=0; i < remainingArgs.length; ++i) {
otherArgs.add(remainingArgs[i]);
}
FileInputFormat.addInputPath(job, new Path( otherArgs.get(0) ));
FileOutputFormat.setOutputPath(job, new Path( otherArgs.get(1) ));
TextOutputFormat.setCompressOutput(job, true);
TextOutputFormat.setOutputCompressorClass(job, BZip2Codec.class );
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| Added constants
| nxcore-split/src/main/java/mil/darpa/nxcore/SplitFiles.java | Added constants | <ide><path>xcore-split/src/main/java/mil/darpa/nxcore/SplitFiles.java
<ide> */
<ide> public static class SplitFilesReducer extends Reducer<Text,Text,NullWritable,Text> {
<ide>
<add> public static final int RECORD_TYPE = 1;
<add> public static final int RECORD_DATE = 0;
<add>
<ide> MultipleOutputs<NullWritable,Text> mos;
<ide>
<ide> @Override
<ide> protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
<ide>
<ide> String[] components = key.toString().split("-",1);
<del> String year = components[0].substring(0,4);
<del> String month = components[0].substring(4,6);
<add> String year = components[RECORD_DATE].substring(0,4);
<add> String month = components[RECORD_DATE].substring(4,6);
<ide>
<ide> StringBuffer outfile = new StringBuffer();
<ide> outfile.append("/")
<del> .append( components[1] )
<add> .append( components[RECORD_TYPE] )
<ide> .append("/")
<ide> .append( year )
<ide> .append("/")
<ide> .append( month )
<ide> .append("/")
<del> .append( components[0 ]);
<add> .append( components[RECORD_DATE]); //date
<ide>
<ide> for ( Text value : values ){
<ide> mos.write( NullWritable.get(), value, outfile.toString() );
<ide> String[] remainingArgs = optionParser.getRemainingArgs();
<ide> if (!(remainingArgs.length != 2)) {
<ide> System.err.println("Usage: SplitFiles <in> <out>");
<del> System.exit(2);
<add> System.exit(0);
<ide> }
<ide>
<ide> Job job = Job.getInstance(conf,"split-nxcore-files"); |
|
Java | apache-2.0 | d336b4da57e2eae549267bb94b201cf579e5949d | 0 | jlinn/quartz-redis-jobstore | package net.joelinn.quartz;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.joelinn.quartz.jobstore.RedisJobStoreSchema;
import net.joelinn.quartz.jobstore.AbstractRedisStorage;
import net.joelinn.quartz.jobstore.RedisStorage;
import net.joelinn.quartz.jobstore.RedisTriggerState;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.quartz.*;
import org.quartz.impl.calendar.WeeklyCalendar;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.spi.OperableTrigger;
import org.quartz.spi.SchedulerSignaler;
import org.quartz.spi.TriggerFiredResult;
import java.util.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
/**
* Joe Linn
* 7/15/2014
*/
public class StoreTriggerTest extends BaseTest{
@Test
public void storeTrigger() throws Exception {
CronTriggerImpl trigger = getCronTrigger();
trigger.getJobDataMap().put("foo", "bar");
jobStore.storeTrigger(trigger, false);
final String triggerHashKey = schema.triggerHashKey(trigger.getKey());
Map<String, String> triggerMap = jedis.hgetAll(triggerHashKey);
assertThat(triggerMap, hasKey("description"));
assertEquals(trigger.getDescription(), triggerMap.get("description"));
assertThat(triggerMap, hasKey("trigger_class"));
assertEquals(trigger.getClass().getName(), triggerMap.get("trigger_class"));
assertTrue("The trigger hash key is not a member of the triggers set.", jedis.sismember(schema.triggersSet(), triggerHashKey));
assertTrue("The trigger group set key is not a member of the trigger group set.", jedis.sismember(schema.triggerGroupsSet(), schema.triggerGroupSetKey(trigger.getKey())));
assertTrue(jedis.sismember(schema.triggerGroupSetKey(trigger.getKey()), triggerHashKey));
assertTrue(jedis.sismember(schema.jobTriggersSetKey(trigger.getJobKey()), triggerHashKey));
String triggerDataMapHashKey = schema.triggerDataMapHashKey(trigger.getKey());
MatcherAssert.assertThat(jedis.exists(triggerDataMapHashKey), equalTo(true));
MatcherAssert.assertThat(jedis.hget(triggerDataMapHashKey, "foo"), equalTo("bar"));
}
@Test(expected = JobPersistenceException.class)
public void storeTriggerNoReplace() throws Exception {
jobStore.storeTrigger(getCronTrigger(), false);
jobStore.storeTrigger(getCronTrigger(), false);
}
@Test
public void storeTriggerWithReplace() throws Exception {
jobStore.storeTrigger(getCronTrigger(), true);
jobStore.storeTrigger(getCronTrigger(), true);
}
@Test
public void retrieveTrigger() throws Exception {
CronTriggerImpl cronTrigger = getCronTrigger();
jobStore.storeJob(getJobDetail(), false);
jobStore.storeTrigger(cronTrigger, false);
OperableTrigger operableTrigger = jobStore.retrieveTrigger(cronTrigger.getKey());
assertThat(operableTrigger, instanceOf(CronTriggerImpl.class));
CronTriggerImpl retrievedTrigger = (CronTriggerImpl) operableTrigger;
assertEquals(cronTrigger.getCronExpression(), retrievedTrigger.getCronExpression());
assertEquals(cronTrigger.getTimeZone(), retrievedTrigger.getTimeZone());
assertEquals(cronTrigger.getStartTime(), retrievedTrigger.getStartTime());
}
@Test
public void removeTrigger() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "triggerGroup", job.getKey());
trigger1.getJobDataMap().put("foo", "bar");
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "triggerGroup", job.getKey());
jobStore.storeJob(job, false);
jobStore.storeTrigger(trigger1, false);
jobStore.storeTrigger(trigger2, false);
jobStore.removeTrigger(trigger1.getKey());
// ensure that the trigger was removed, but the job was not
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
assertThat(jobStore.retrieveJob(job.getKey()), not(nullValue()));
// remove the second trigger
jobStore.removeTrigger(trigger2.getKey());
// ensure that both the trigger and job were removed
assertThat(jobStore.retrieveTrigger(trigger2.getKey()), nullValue());
assertThat(jobStore.retrieveJob(job.getKey()), nullValue());
MatcherAssert.assertThat(jedis.exists(schema.triggerDataMapHashKey(trigger1.getKey())), equalTo(false));
}
@Test
public void getTriggersForJob() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "triggerGroup", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "triggerGroup", job.getKey());
jobStore.storeJob(job, false);
jobStore.storeTrigger(trigger1, false);
jobStore.storeTrigger(trigger2, false);
List<OperableTrigger> triggers = jobStore.getTriggersForJob(job.getKey());
assertThat(triggers, hasSize(2));
}
@Test
public void getNumberOfTriggers() throws Exception {
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
int numberOfTriggers = jobStore.getNumberOfTriggers();
assertEquals(4, numberOfTriggers);
}
@Test
public void getTriggerKeys() throws Exception {
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
Set<TriggerKey> triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupEquals("group1"));
assertThat(triggerKeys, hasSize(2));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger2", "group1"), new TriggerKey("trigger1", "group1")));
jobStore.storeTrigger(getCronTrigger("trigger4", "triggergroup1", job.getKey()), false);
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupContains("group"));
assertThat(triggerKeys, hasSize(5));
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(triggerKeys, hasSize(3));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger2", "group1"),
new TriggerKey("trigger1", "group1"), new TriggerKey("trigger4", "triggergroup1")));
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupStartsWith("trig"));
assertThat(triggerKeys, hasSize(1));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger4", "triggergroup1")));
}
@Test
public void getTriggerGroupNames() throws Exception {
List<String> triggerGroupNames = jobStore.getTriggerGroupNames();
assertThat(triggerGroupNames, not(nullValue()));
assertThat(triggerGroupNames, hasSize(0));
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
triggerGroupNames = jobStore.getTriggerGroupNames();
assertThat(triggerGroupNames, hasSize(3));
assertThat(triggerGroupNames, containsInAnyOrder("group3", "group2", "group1"));
}
@Test
public void getTriggerState() throws Exception {
SchedulerSignaler signaler = mock(SchedulerSignaler.class);
AbstractRedisStorage storageDriver = new RedisStorage(new RedisJobStoreSchema(), new ObjectMapper(), signaler, "scheduler1", 2000);
// attempt to retrieve the state of a non-existent trigger
Trigger.TriggerState state = jobStore.getTriggerState(new TriggerKey("foobar"));
assertEquals(Trigger.TriggerState.NONE, state);
// store a trigger
JobDetail job = getJobDetail();
CronTriggerImpl cronTrigger = getCronTrigger("trigger1", "group1", job.getKey());
jobStore.storeTrigger(cronTrigger, false);
// the newly-stored trigger's state should be NONE
state = jobStore.getTriggerState(cronTrigger.getKey());
assertEquals(Trigger.TriggerState.NORMAL, state);
// set the trigger's state
storageDriver.setTriggerState(RedisTriggerState.WAITING, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
// the trigger's state should now be NORMAL
state = jobStore.getTriggerState(cronTrigger.getKey());
assertEquals(Trigger.TriggerState.NORMAL, state);
}
@Test
public void pauseTrigger() throws Exception {
SchedulerSignaler signaler = mock(SchedulerSignaler.class);
AbstractRedisStorage storageDriver = new RedisStorage(new RedisJobStoreSchema(), new ObjectMapper(), signaler, "scheduler1", 2000);
// store a trigger
JobDetail job = getJobDetail();
CronTriggerImpl cronTrigger = getCronTrigger("trigger1", "group1", job.getKey());
cronTrigger.setNextFireTime(new Date(System.currentTimeMillis()));
jobStore.storeTrigger(cronTrigger, false);
// set the trigger's state to COMPLETED
storageDriver.setTriggerState(RedisTriggerState.COMPLETED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should not have changed
assertEquals(Trigger.TriggerState.COMPLETE, jobStore.getTriggerState(cronTrigger.getKey()));
// set the trigger's state to BLOCKED
storageDriver.setTriggerState(RedisTriggerState.BLOCKED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should be PAUSED
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(cronTrigger.getKey()));
// set the trigger's state to ACQUIRED
storageDriver.setTriggerState(RedisTriggerState.ACQUIRED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should be PAUSED
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(cronTrigger.getKey()));
}
@Test
public void pauseTriggersEquals() throws Exception {
// store triggers
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
}
@Test
public void pauseTriggersStartsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger1", "group2", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger1", "foogroup1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3);
Collection<String> pausedTriggerGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupStartsWith("group"));
assertThat(pausedTriggerGroups, hasSize(2));
assertThat(pausedTriggerGroups, containsInAnyOrder("group1", "group2"));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger2.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger3.getKey()));
}
@Test
public void pauseTriggersEndsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger1", "group2", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger1", "foogroup1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEndsWith("oup1"));
assertThat(pausedGroups, hasSize(2));
assertThat(pausedGroups, containsInAnyOrder("group1", "foogroup1"));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger2.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger3.getKey()));
}
@Test
public void resumeTrigger() throws Exception {
// create and store a job and trigger
JobDetail job = getJobDetail();
jobStore.storeJob(job, false);
CronTriggerImpl trigger = getCronTrigger("trigger1", "group1", job.getKey());
trigger.computeFirstFireTime(new WeeklyCalendar());
jobStore.storeTrigger(trigger, false);
// pause the trigger
jobStore.pauseTrigger(trigger.getKey());
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger.getKey()));
// resume the trigger
jobStore.resumeTrigger(trigger.getKey());
// the trigger state should now be NORMAL
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
// attempt to resume the trigger, again
jobStore.resumeTrigger(trigger.getKey());
// the trigger state should not have changed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
@Test
public void resumeTriggersEquals() throws Exception {
// store triggers and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
}
@Test
public void resumeTriggersEndsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger2.getKey()));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger2.getKey()));
}
@Test
public void resumeTriggersStartsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "mygroup1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupStartsWith("my"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("mygroup1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupStartsWith("my"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("mygroup1"));
// ensure that the triggers were actually resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger1.getKey()));
}
@Test
public void getPausedTriggerGroups() throws Exception {
// store triggers
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
pausedGroups.addAll(jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group3")));
assertThat(pausedGroups, hasSize(2));
assertThat(pausedGroups, containsInAnyOrder("group3", "group1"));
// retrieve paused trigger groups
Set<String> pausedTriggerGroups = jobStore.getPausedTriggerGroups();
assertThat(pausedTriggerGroups, hasSize(2));
assertThat(pausedTriggerGroups, containsInAnyOrder("group1", "group3"));
}
@Test
public void pauseAndResumeAll() throws Exception {
// store some jobs with triggers
Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2);
jobStore.storeJobsAndTriggers(jobsAndTriggers, false);
// ensure that all triggers are in the NORMAL state
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
}
jobStore.pauseAll();
// ensure that all triggers were paused
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger.getKey()));
}
}
// resume all triggers
jobStore.resumeAll();
// ensure that all triggers are again in the NORMAL state
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
}
}
@Test
@SuppressWarnings("unchecked")
public void triggersFired() throws Exception {
// store some jobs with triggers
Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2, "* * * * * ?");
// disallow concurrent execution for one of the jobs
Map.Entry<JobDetail, Set<? extends Trigger>> firstEntry = jobsAndTriggers.entrySet().iterator().next();
JobDetail nonConcurrentKey = firstEntry.getKey().getJobBuilder().ofType(TestJobNonConcurrent.class).build();
Set<? extends Trigger> nonConcurrentTriggers = firstEntry.getValue();
jobsAndTriggers.remove(firstEntry.getKey());
jobsAndTriggers.put(nonConcurrentKey, nonConcurrentTriggers);
jobStore.storeCalendar("testCalendar", new WeeklyCalendar(), false, true);
jobStore.storeJobsAndTriggers(jobsAndTriggers, false);
List<OperableTrigger> acquiredTriggers = jobStore.acquireNextTriggers(System.currentTimeMillis() - 1000, 500, 4000);
assertThat(acquiredTriggers, hasSize(13));
int lockedTriggers = 0;
// ensure that all triggers are in the NORMAL state and have been ACQUIRED
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
String triggerHashKey = schema.triggerHashKey(trigger.getKey());
if (jobDetailSetEntry.getKey().isConcurrentExectionDisallowed()) {
if (jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey) != null) {
assertThat("acquired trigger should be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), notNullValue());
lockedTriggers++;
} else {
assertThat("non-acquired trigger should not be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), nullValue());
}
} else {
assertThat(jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey), not(nullValue()));
}
}
}
assertThat(lockedTriggers, equalTo(1));
Set<? extends OperableTrigger> triggers = (Set<? extends OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(0).getValue();
List<TriggerFiredResult> triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
assertThat("exactly one trigger fired for job with concurrent execution disallowed", triggerFiredResults, hasSize(1));
triggers = (Set<? extends OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(1).getValue();
triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
assertThat("all triggers fired for job with concurrent execution allowed", triggerFiredResults, hasSize(4));
}
@Test
public void replaceTrigger() throws Exception {
assertFalse(jobStore.replaceTrigger(TriggerKey.triggerKey("foo", "bar"), getCronTrigger()));
// store triggers and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", job.getKey());
assertTrue(jobStore.replaceTrigger(trigger1.getKey(), newTrigger));
// ensure that the proper trigger was replaced
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
List<OperableTrigger> jobTriggers = jobStore.getTriggersForJob(job.getKey());
assertThat(jobTriggers, hasSize(2));
List<TriggerKey> jobTriggerKeys = new ArrayList<>(jobTriggers.size());
for (OperableTrigger jobTrigger : jobTriggers) {
jobTriggerKeys.add(jobTrigger.getKey());
}
assertThat(jobTriggerKeys, containsInAnyOrder(trigger2.getKey(), newTrigger.getKey()));
}
@Test
public void replaceTriggerSingleTriggerNonDurableJob() throws Exception {
// store trigger and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
storeJobAndTriggers(job, trigger1);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", job.getKey());
assertTrue(jobStore.replaceTrigger(trigger1.getKey(), newTrigger));
// ensure that the proper trigger was replaced
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
List<OperableTrigger> jobTriggers = jobStore.getTriggersForJob(job.getKey());
assertThat(jobTriggers, hasSize(1));
// ensure that the job still exists
assertThat(jobStore.retrieveJob(job.getKey()), not(nullValue()));
}
@Test(expected = JobPersistenceException.class)
public void replaceTriggerWithDifferentJob() throws Exception {
// store triggers and job
JobDetail job = getJobDetail();
jobStore.storeJob(job, false);
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
jobStore.storeTrigger(trigger1, false);
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
jobStore.storeTrigger(trigger2, false);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", JobKey.jobKey("foo", "bar"));
jobStore.replaceTrigger(trigger1.getKey(), newTrigger);
}
}
| src/test/java/net/joelinn/quartz/StoreTriggerTest.java | package net.joelinn.quartz;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.joelinn.quartz.jobstore.RedisJobStoreSchema;
import net.joelinn.quartz.jobstore.AbstractRedisStorage;
import net.joelinn.quartz.jobstore.RedisStorage;
import net.joelinn.quartz.jobstore.RedisTriggerState;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.quartz.*;
import org.quartz.impl.calendar.WeeklyCalendar;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.spi.OperableTrigger;
import org.quartz.spi.SchedulerSignaler;
import org.quartz.spi.TriggerFiredResult;
import java.util.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
/**
* Joe Linn
* 7/15/2014
*/
public class StoreTriggerTest extends BaseTest{
@Test
public void storeTrigger() throws Exception {
CronTriggerImpl trigger = getCronTrigger();
trigger.getJobDataMap().put("foo", "bar");
jobStore.storeTrigger(trigger, false);
final String triggerHashKey = schema.triggerHashKey(trigger.getKey());
Map<String, String> triggerMap = jedis.hgetAll(triggerHashKey);
assertThat(triggerMap, hasKey("description"));
assertEquals(trigger.getDescription(), triggerMap.get("description"));
assertThat(triggerMap, hasKey("trigger_class"));
assertEquals(trigger.getClass().getName(), triggerMap.get("trigger_class"));
assertTrue("The trigger hash key is not a member of the triggers set.", jedis.sismember(schema.triggersSet(), triggerHashKey));
assertTrue("The trigger group set key is not a member of the trigger group set.", jedis.sismember(schema.triggerGroupsSet(), schema.triggerGroupSetKey(trigger.getKey())));
assertTrue(jedis.sismember(schema.triggerGroupSetKey(trigger.getKey()), triggerHashKey));
assertTrue(jedis.sismember(schema.jobTriggersSetKey(trigger.getJobKey()), triggerHashKey));
String triggerDataMapHashKey = schema.triggerDataMapHashKey(trigger.getKey());
MatcherAssert.assertThat(jedis.exists(triggerDataMapHashKey), equalTo(true));
MatcherAssert.assertThat(jedis.hget(triggerDataMapHashKey, "foo"), equalTo("bar"));
}
@Test(expected = JobPersistenceException.class)
public void storeTriggerNoReplace() throws Exception {
jobStore.storeTrigger(getCronTrigger(), false);
jobStore.storeTrigger(getCronTrigger(), false);
}
@Test
public void storeTriggerWithReplace() throws Exception {
jobStore.storeTrigger(getCronTrigger(), true);
jobStore.storeTrigger(getCronTrigger(), true);
}
@Test
public void retrieveTrigger() throws Exception {
CronTriggerImpl cronTrigger = getCronTrigger();
jobStore.storeJob(getJobDetail(), false);
jobStore.storeTrigger(cronTrigger, false);
OperableTrigger operableTrigger = jobStore.retrieveTrigger(cronTrigger.getKey());
assertThat(operableTrigger, instanceOf(CronTriggerImpl.class));
CronTriggerImpl retrievedTrigger = (CronTriggerImpl) operableTrigger;
assertEquals(cronTrigger.getCronExpression(), retrievedTrigger.getCronExpression());
assertEquals(cronTrigger.getTimeZone(), retrievedTrigger.getTimeZone());
assertEquals(cronTrigger.getStartTime(), retrievedTrigger.getStartTime());
}
@Test
public void removeTrigger() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "triggerGroup", job.getKey());
trigger1.getJobDataMap().put("foo", "bar");
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "triggerGroup", job.getKey());
jobStore.storeJob(job, false);
jobStore.storeTrigger(trigger1, false);
jobStore.storeTrigger(trigger2, false);
jobStore.removeTrigger(trigger1.getKey());
// ensure that the trigger was removed, but the job was not
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
assertThat(jobStore.retrieveJob(job.getKey()), not(nullValue()));
// remove the second trigger
jobStore.removeTrigger(trigger2.getKey());
// ensure that both the trigger and job were removed
assertThat(jobStore.retrieveTrigger(trigger2.getKey()), nullValue());
assertThat(jobStore.retrieveJob(job.getKey()), nullValue());
MatcherAssert.assertThat(jedis.exists(schema.triggerDataMapHashKey(trigger1.getKey())), equalTo(false));
}
@Test
public void getTriggersForJob() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "triggerGroup", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "triggerGroup", job.getKey());
jobStore.storeJob(job, false);
jobStore.storeTrigger(trigger1, false);
jobStore.storeTrigger(trigger2, false);
List<OperableTrigger> triggers = jobStore.getTriggersForJob(job.getKey());
assertThat(triggers, hasSize(2));
}
@Test
public void getNumberOfTriggers() throws Exception {
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
int numberOfTriggers = jobStore.getNumberOfTriggers();
assertEquals(4, numberOfTriggers);
}
@Test
public void getTriggerKeys() throws Exception {
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
Set<TriggerKey> triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupEquals("group1"));
assertThat(triggerKeys, hasSize(2));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger2", "group1"), new TriggerKey("trigger1", "group1")));
jobStore.storeTrigger(getCronTrigger("trigger4", "triggergroup1", job.getKey()), false);
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupContains("group"));
assertThat(triggerKeys, hasSize(5));
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(triggerKeys, hasSize(3));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger2", "group1"),
new TriggerKey("trigger1", "group1"), new TriggerKey("trigger4", "triggergroup1")));
triggerKeys = jobStore.getTriggerKeys(GroupMatcher.triggerGroupStartsWith("trig"));
assertThat(triggerKeys, hasSize(1));
assertThat(triggerKeys, containsInAnyOrder(new TriggerKey("trigger4", "triggergroup1")));
}
@Test
public void getTriggerGroupNames() throws Exception {
List<String> triggerGroupNames = jobStore.getTriggerGroupNames();
assertThat(triggerGroupNames, not(nullValue()));
assertThat(triggerGroupNames, hasSize(0));
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
triggerGroupNames = jobStore.getTriggerGroupNames();
assertThat(triggerGroupNames, hasSize(3));
assertThat(triggerGroupNames, containsInAnyOrder("group3", "group2", "group1"));
}
@Test
public void getTriggerState() throws Exception {
SchedulerSignaler signaler = mock(SchedulerSignaler.class);
AbstractRedisStorage storageDriver = new RedisStorage(new RedisJobStoreSchema(), new ObjectMapper(), signaler, "scheduler1", 2000);
// attempt to retrieve the state of a non-existent trigger
Trigger.TriggerState state = jobStore.getTriggerState(new TriggerKey("foobar"));
assertEquals(Trigger.TriggerState.NONE, state);
// store a trigger
JobDetail job = getJobDetail();
CronTriggerImpl cronTrigger = getCronTrigger("trigger1", "group1", job.getKey());
jobStore.storeTrigger(cronTrigger, false);
// the newly-stored trigger's state should be NONE
state = jobStore.getTriggerState(cronTrigger.getKey());
assertEquals(Trigger.TriggerState.NORMAL, state);
// set the trigger's state
storageDriver.setTriggerState(RedisTriggerState.WAITING, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
// the trigger's state should now be NORMAL
state = jobStore.getTriggerState(cronTrigger.getKey());
assertEquals(Trigger.TriggerState.NORMAL, state);
}
@Test
public void pauseTrigger() throws Exception {
SchedulerSignaler signaler = mock(SchedulerSignaler.class);
AbstractRedisStorage storageDriver = new RedisStorage(new RedisJobStoreSchema(), new ObjectMapper(), signaler, "scheduler1", 2000);
// store a trigger
JobDetail job = getJobDetail();
CronTriggerImpl cronTrigger = getCronTrigger("trigger1", "group1", job.getKey());
cronTrigger.setNextFireTime(new Date(System.currentTimeMillis()));
jobStore.storeTrigger(cronTrigger, false);
// set the trigger's state to COMPLETED
storageDriver.setTriggerState(RedisTriggerState.COMPLETED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should not have changed
assertEquals(Trigger.TriggerState.COMPLETE, jobStore.getTriggerState(cronTrigger.getKey()));
// set the trigger's state to BLOCKED
storageDriver.setTriggerState(RedisTriggerState.BLOCKED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should be PAUSED
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(cronTrigger.getKey()));
// set the trigger's state to ACQUIRED
storageDriver.setTriggerState(RedisTriggerState.ACQUIRED, 500, schema.triggerHashKey(cronTrigger.getKey()), jedis);
jobStore.pauseTrigger(cronTrigger.getKey());
// trigger's state should be PAUSED
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(cronTrigger.getKey()));
}
@Test
public void pauseTriggersEquals() throws Exception {
// store triggers
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
}
@Test
public void pauseTriggersStartsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger1", "group2", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger1", "foogroup1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3);
Collection<String> pausedTriggerGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupStartsWith("group"));
assertThat(pausedTriggerGroups, hasSize(2));
assertThat(pausedTriggerGroups, containsInAnyOrder("group1", "group2"));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger2.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger3.getKey()));
}
@Test
public void pauseTriggersEndsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger1", "group2", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger1", "foogroup1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEndsWith("oup1"));
assertThat(pausedGroups, hasSize(2));
assertThat(pausedGroups, containsInAnyOrder("group1", "foogroup1"));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger2.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger3.getKey()));
}
@Test
public void resumeTrigger() throws Exception {
// create and store a job and trigger
JobDetail job = getJobDetail();
jobStore.storeJob(job, false);
CronTriggerImpl trigger = getCronTrigger("trigger1", "group1", job.getKey());
trigger.computeFirstFireTime(new WeeklyCalendar());
jobStore.storeTrigger(trigger, false);
// pause the trigger
jobStore.pauseTrigger(trigger.getKey());
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger.getKey()));
// resume the trigger
jobStore.resumeTrigger(trigger.getKey());
// the trigger state should now be NORMAL
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
// attempt to resume the trigger, again
jobStore.resumeTrigger(trigger.getKey());
// the trigger state should not have changed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
@Test
public void resumeTriggersEquals() throws Exception {
// store triggers and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupEquals("group1"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(new TriggerKey("trigger1", "group1")));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(new TriggerKey("trigger2", "group1")));
}
@Test
public void resumeTriggersEndsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger2.getKey()));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupEndsWith("1"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("group1"));
// ensure that the triggers were actually resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger1.getKey()));
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger2.getKey()));
}
@Test
public void resumeTriggersStartsWith() throws Exception {
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "mygroup1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
CronTriggerImpl trigger3 = getCronTrigger("trigger3", "group2", job.getKey());
CronTriggerImpl trigger4 = getCronTrigger("trigger4", "group3", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2, trigger3, trigger4);
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupStartsWith("my"));
assertThat(pausedGroups, hasSize(1));
assertThat(pausedGroups, containsInAnyOrder("mygroup1"));
// ensure that the triggers were actually paused
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger1.getKey()));
// resume triggers
Collection<String> resumedGroups = jobStore.resumeTriggers(GroupMatcher.triggerGroupStartsWith("my"));
assertThat(resumedGroups, hasSize(1));
assertThat(resumedGroups, containsInAnyOrder("mygroup1"));
// ensure that the triggers were actually resumed
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger1.getKey()));
}
@Test
public void getPausedTriggerGroups() throws Exception {
// store triggers
JobDetail job = getJobDetail();
jobStore.storeTrigger(getCronTrigger("trigger1", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger2", "group1", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger3", "group2", job.getKey()), false);
jobStore.storeTrigger(getCronTrigger("trigger4", "group3", job.getKey()), false);
// pause triggers
Collection<String> pausedGroups = jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group1"));
pausedGroups.addAll(jobStore.pauseTriggers(GroupMatcher.triggerGroupEquals("group3")));
assertThat(pausedGroups, hasSize(2));
assertThat(pausedGroups, containsInAnyOrder("group3", "group1"));
// retrieve paused trigger groups
Set<String> pausedTriggerGroups = jobStore.getPausedTriggerGroups();
assertThat(pausedTriggerGroups, hasSize(2));
assertThat(pausedTriggerGroups, containsInAnyOrder("group1", "group3"));
}
@Test
public void pauseAndResumeAll() throws Exception {
// store some jobs with triggers
Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2);
jobStore.storeJobsAndTriggers(jobsAndTriggers, false);
// ensure that all triggers are in the NORMAL state
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
}
jobStore.pauseAll();
// ensure that all triggers were paused
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.PAUSED, jobStore.getTriggerState(trigger.getKey()));
}
}
// resume all triggers
jobStore.resumeAll();
// ensure that all triggers are again in the NORMAL state
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
}
}
}
@Test
@SuppressWarnings("unchecked")
public void triggersFired() throws Exception {
// store some jobs with triggers
Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2, "* * * * * ?");
jobStore.storeCalendar("testCalendar", new WeeklyCalendar(), false, true);
jobStore.storeJobsAndTriggers(jobsAndTriggers, false);
List<OperableTrigger> acquiredTriggers = jobStore.acquireNextTriggers(System.currentTimeMillis() - 1000, 500, 4000);
assertThat(acquiredTriggers, hasSize(16));
// ensure that all triggers are in the NORMAL state and have been ACQUIRED
for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
for (Trigger trigger : jobDetailSetEntry.getValue()) {
assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
String triggerHashKey = schema.triggerHashKey(trigger.getKey());
assertThat(jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey), not(nullValue()));
assertThat(jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), notNullValue());
}
}
Set<? extends OperableTrigger> triggers = (Set<? extends OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(0).getValue();
List<TriggerFiredResult> triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
assertThat(triggerFiredResults, hasSize(4));
}
@Test
public void replaceTrigger() throws Exception {
assertFalse(jobStore.replaceTrigger(TriggerKey.triggerKey("foo", "bar"), getCronTrigger()));
// store triggers and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
storeJobAndTriggers(job, trigger1, trigger2);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", job.getKey());
assertTrue(jobStore.replaceTrigger(trigger1.getKey(), newTrigger));
// ensure that the proper trigger was replaced
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
List<OperableTrigger> jobTriggers = jobStore.getTriggersForJob(job.getKey());
assertThat(jobTriggers, hasSize(2));
List<TriggerKey> jobTriggerKeys = new ArrayList<>(jobTriggers.size());
for (OperableTrigger jobTrigger : jobTriggers) {
jobTriggerKeys.add(jobTrigger.getKey());
}
assertThat(jobTriggerKeys, containsInAnyOrder(trigger2.getKey(), newTrigger.getKey()));
}
@Test
public void replaceTriggerSingleTriggerNonDurableJob() throws Exception {
// store trigger and job
JobDetail job = getJobDetail();
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
storeJobAndTriggers(job, trigger1);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", job.getKey());
assertTrue(jobStore.replaceTrigger(trigger1.getKey(), newTrigger));
// ensure that the proper trigger was replaced
assertThat(jobStore.retrieveTrigger(trigger1.getKey()), nullValue());
List<OperableTrigger> jobTriggers = jobStore.getTriggersForJob(job.getKey());
assertThat(jobTriggers, hasSize(1));
// ensure that the job still exists
assertThat(jobStore.retrieveJob(job.getKey()), not(nullValue()));
}
@Test(expected = JobPersistenceException.class)
public void replaceTriggerWithDifferentJob() throws Exception {
// store triggers and job
JobDetail job = getJobDetail();
jobStore.storeJob(job, false);
CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
jobStore.storeTrigger(trigger1, false);
CronTriggerImpl trigger2 = getCronTrigger("trigger2", "group1", job.getKey());
jobStore.storeTrigger(trigger2, false);
CronTriggerImpl newTrigger = getCronTrigger("newTrigger", "group1", JobKey.jobKey("foo", "bar"));
jobStore.replaceTrigger(trigger1.getKey(), newTrigger);
}
}
| Fix StoreTriggerTest
| src/test/java/net/joelinn/quartz/StoreTriggerTest.java | Fix StoreTriggerTest | <ide><path>rc/test/java/net/joelinn/quartz/StoreTriggerTest.java
<ide> public void triggersFired() throws Exception {
<ide> // store some jobs with triggers
<ide> Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2, "* * * * * ?");
<add>
<add> // disallow concurrent execution for one of the jobs
<add> Map.Entry<JobDetail, Set<? extends Trigger>> firstEntry = jobsAndTriggers.entrySet().iterator().next();
<add> JobDetail nonConcurrentKey = firstEntry.getKey().getJobBuilder().ofType(TestJobNonConcurrent.class).build();
<add> Set<? extends Trigger> nonConcurrentTriggers = firstEntry.getValue();
<add> jobsAndTriggers.remove(firstEntry.getKey());
<add> jobsAndTriggers.put(nonConcurrentKey, nonConcurrentTriggers);
<add>
<ide> jobStore.storeCalendar("testCalendar", new WeeklyCalendar(), false, true);
<ide> jobStore.storeJobsAndTriggers(jobsAndTriggers, false);
<ide>
<ide> List<OperableTrigger> acquiredTriggers = jobStore.acquireNextTriggers(System.currentTimeMillis() - 1000, 500, 4000);
<del> assertThat(acquiredTriggers, hasSize(16));
<del>
<add> assertThat(acquiredTriggers, hasSize(13));
<add>
<add> int lockedTriggers = 0;
<ide> // ensure that all triggers are in the NORMAL state and have been ACQUIRED
<ide> for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
<ide> for (Trigger trigger : jobDetailSetEntry.getValue()) {
<ide> assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
<ide> String triggerHashKey = schema.triggerHashKey(trigger.getKey());
<del> assertThat(jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey), not(nullValue()));
<del> assertThat(jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), notNullValue());
<add> if (jobDetailSetEntry.getKey().isConcurrentExectionDisallowed()) {
<add> if (jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey) != null) {
<add> assertThat("acquired trigger should be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), notNullValue());
<add> lockedTriggers++;
<add> } else {
<add> assertThat("non-acquired trigger should not be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), nullValue());
<add> }
<add> } else {
<add> assertThat(jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey), not(nullValue()));
<add> }
<ide> }
<ide> }
<ide>
<add> assertThat(lockedTriggers, equalTo(1));
<add>
<ide> Set<? extends OperableTrigger> triggers = (Set<? extends OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(0).getValue();
<ide> List<TriggerFiredResult> triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
<del> assertThat(triggerFiredResults, hasSize(4));
<add> assertThat("exactly one trigger fired for job with concurrent execution disallowed", triggerFiredResults, hasSize(1));
<add>
<add> triggers = (Set<? extends OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(1).getValue();
<add> triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
<add> assertThat("all triggers fired for job with concurrent execution allowed", triggerFiredResults, hasSize(4));
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | e5a01cc4dee4134a0c4fe7658854ee5a87cfce23 | 0 | SAP/cloud-odata-java,SAP/cloud-odata-java | package com.sap.core.odata.ref.model;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class DataContainer {
private static final int NUMBER_OF_PHOTOS = 4;
private static final String[] arrayForImageType = { "PNG", "BMP", "JPEG", "GIF" };
private static final boolean SCRUMTEAM_TRUE = true;
private static final boolean SCRUMTEAM_FALSE = false;
private static final String IMAGE_JPEG = "image/jpeg";
private Set<Photo> photoSet;
private Set<Building> buildingSet = new HashSet<Building>();
private Set<Team> teamSet = new HashSet<Team>();
private Set<Room> roomSet = new HashSet<Room>();
private Set<Employee> employeeSet = new HashSet<Employee>();
private Set<Manager> managerSet = new HashSet<Manager>();
public void init() {
photoSet = generatePhotos();
// ------------- Buildings ---------------
Building building1 = new Building("Building 1");
Building building2 = new Building("Building 2");
Building building3 = new Building("Building 3");
buildingSet.add(building1);
buildingSet.add(building2);
buildingSet.add(building3);
// ------------- Teams ---------------
Team team1 = new Team("Team 1", SCRUMTEAM_FALSE);
Team team2 = new Team("Team 2", SCRUMTEAM_TRUE);
Team team3 = new Team("Team 3", SCRUMTEAM_FALSE);
teamSet.add(team1);
teamSet.add(team2);
teamSet.add(team3);
// ------------- Rooms ---------------
Room room1 = new Room("Room 1", 1);
Room room2 = new Room("Room 2", 5);
Room room3 = new Room("Room 3", 4);
room1.setBuilding(building1);
room2.setBuilding(building2);
room3.setBuilding(building2);
room1.setVersion(1);
room2.setVersion(2);
room3.setVersion(3);
roomSet.add(room1);
roomSet.add(room2);
roomSet.add(room3);
for (int i = 4; i <= 103; i++) {
Room roomN = new Room("Room " + i, (4 + i) / 5);
roomN.setBuilding(building3);
roomN.setVersion(1);
roomSet.add(roomN);
}
// ------------- Employees and Managers ------------
Employee emp1 = new Manager("Walter Winter", 52, room1, team1);
emp1.setEntryDate(generateDate("1999-01-01"));
emp1.setManager((Manager) emp1);
emp1.setLocation(new Location("Germany", "69124", "Heidelberg"));
emp1.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg");
emp1.setImage("/male_1_WinterW.jpg");
emp1.setImageType(IMAGE_JPEG);
employeeSet.add(emp1);
managerSet.add((Manager)emp1);
Employee emp2 = new Employee("Frederic Fall", 32, room2, team1);
emp2.setEntryDate(generateDate("2003-07-01"));
emp2.setManager((Manager) emp1);
emp2.setLocation(new Location("Germany", "69190", "Walldorf"));
emp2.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_2_FallF.jpg");
emp2.setImage("/male_2_FallF.jpg");
emp2.setImageType(IMAGE_JPEG);
employeeSet.add(emp2);
Manager emp3 = new Manager("Jonathan Smith", 56, room2, team1);
emp3.setManager((Manager) emp1);
emp3.setLocation(new Location("Germany", "69190", "Walldorf"));
emp3.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_3_SmithJo.jpg");
emp3.setImage("/male_3_SmithJo.jpg");
emp3.setImageType(IMAGE_JPEG);
employeeSet.add(emp3);
managerSet.add((Manager)emp3);
Employee emp4 = new Employee("Peter Burke", 39, room2, team2);
emp4.setManager(emp3);
emp4.setEntryDate(generateDate("2004-09-12"));
emp4.setLocation(new Location("Germany", "69190", "Walldorf"));
emp4.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_4_BurkeP.jpg");
emp4.setImage("/male_4_BurkeP.jpg");
emp4.setImageType(IMAGE_JPEG);
employeeSet.add(emp4);
Employee emp5 = new Employee("John Field", 42, room3, team2);
emp5.setManager(emp3);
emp5.setEntryDate(generateDate("2001-02-01"));
emp5.setLocation(new Location("Germany", "69190", "Walldorf"));
emp5.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_5_FieldJ.jpg");
emp5.setImage("/male_5_FieldJ.jpg");
emp5.setImageType(IMAGE_JPEG);
employeeSet.add(emp5);
Employee emp6 = new Employee("Susan Bay", 29, room2, team3);
emp6.setManager((Manager) emp1);
emp6.setEntryDate(generateDate("2010-12-01"));
emp6.setLocation(new Location("Germany", "69190", "Walldorf"));
emp6.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/female_6_BaySu.jpg");
emp6.setImage("/female_6_BaySu.jpg");
emp6.setImageType(IMAGE_JPEG);
employeeSet.add(emp6);
}
private Date generateDate(String dateString) {
Date date = new Date();
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
date = df.parse(dateString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return date;
}
private Set<Photo> generatePhotos() {
Set<Photo> photos = new HashSet<Photo>();
for (int z = 0; z < NUMBER_OF_PHOTOS; z++) {
Photo photo = new Photo("Photo " + (z + 1));
photo.setType("image/" + arrayForImageType[z % (arrayForImageType.length)].toLowerCase());
photos.add(photo);
}
return photos;
}
public Set<Photo> getPhotoSet() {
return photoSet;
}
public Set<Employee> getEmployeeSet() {
return employeeSet;
}
public Set<Building> getBuildingSet() {
return buildingSet;
}
public Set<Room> getRoomSet() {
return roomSet;
}
public Set<Team> getTeamSet() {
return teamSet;
}
public void reset() {
if(photoSet != null){
photoSet.clear();
}
if(employeeSet != null){
employeeSet.clear();
}
if(buildingSet != null){
buildingSet.clear();
}
if(roomSet != null){
roomSet.clear();
}
if(teamSet != null){
teamSet.clear();
}
if(managerSet != null){
managerSet.clear();
}
Team.reset();
Building.reset();
Employee.reset();
Room.reset();
Photo.reset();
init();
}
public Set<Manager> getManagerSet() {
return managerSet;
}
}
| odata-ref/src/main/java/com/sap/core/odata/ref/model/DataContainer.java | package com.sap.core.odata.ref.model;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class DataContainer {
private static final int NUMBER_OF_PHOTOS = 4;
private static final String[] arrayForImageType = { "PNG", "BMP", "JPEG", "GIF" };
private static final boolean SCRUMTEAM_TRUE = true;
private static final boolean SCRUMTEAM_FALSE = false;
private static final String IMAGE_JPEG = "image/jpeg";
private Set<Photo> photoSet;
private Set<Building> buildingSet = new HashSet<Building>();
private Set<Team> teamSet = new HashSet<Team>();
private Set<Room> roomSet = new HashSet<Room>();
private Set<Employee> employeeSet = new HashSet<Employee>();
private Set<Manager> managerSet = new HashSet<Manager>();
public void init() {
photoSet = generatePhotos();
// ------------- Buildings ---------------
Building building1 = new Building("Building 1");
Building building2 = new Building("Building 2");
Building building3 = new Building("Building 3");
buildingSet.add(building1);
buildingSet.add(building2);
buildingSet.add(building3);
// ------------- Teams ---------------
Team team1 = new Team("Team 1", SCRUMTEAM_FALSE);
Team team2 = new Team("Team 2", SCRUMTEAM_TRUE);
Team team3 = new Team("Team 3", SCRUMTEAM_FALSE);
teamSet.add(team1);
teamSet.add(team2);
teamSet.add(team3);
// ------------- Rooms ---------------
Room room1 = new Room("Room 1", 1);
Room room2 = new Room("Room 2", 5);
Room room3 = new Room("Room 3", 4);
room1.setBuilding(building1);
room2.setBuilding(building2);
room3.setBuilding(building2);
room1.setVersion(1);
room2.setVersion(2);
room3.setVersion(3);
roomSet.add(room1);
roomSet.add(room2);
roomSet.add(room3);
for (int i = 4; i <= 103; i++) {
Room roomN = new Room("Room " + i, (4 + i) / 5);
roomN.setBuilding(building3);
roomN.setVersion(1);
roomSet.add(roomN);
}
// ------------- Employees and Managers ------------
Employee emp1 = new Manager("Walter Winter", 52, room1, team1);
emp1.setEntryDate(generateDate("1999-01-01"));
emp1.setManager((Manager) emp1);
emp1.setLocation(new Location("Germany", "69124", "Heidelberg"));
emp1.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg");
emp1.setImage("/male_1_WinterW.jpg");
emp1.setImageType(IMAGE_JPEG);
employeeSet.add(emp1);
managerSet.add((Manager)emp1);
Employee emp2 = new Employee("Frederic Fall", 32, room2, team1);
emp2.setEntryDate(generateDate("2003-07-01"));
emp2.setManager((Manager) emp1);
emp2.setLocation(new Location("Germany", "69190", "Walldorf"));
emp2.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_2_FallF.jpg");
emp2.setImage("/male_2_FallF.jpg");
emp2.setImageType(IMAGE_JPEG);
employeeSet.add(emp2);
Manager emp3 = new Manager("Jonathan Smith", 56, room2, team1);
emp3.setManager((Manager) emp1);
emp3.setEntryDate(generateDate("2012-12-12"));
emp3.setLocation(new Location("Germany", "69190", "Walldorf"));
emp3.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_3_SmithJo.jpg");
emp3.setImage("/male_3_SmithJo.jpg");
emp3.setImageType(IMAGE_JPEG);
employeeSet.add(emp3);
managerSet.add((Manager)emp3);
Employee emp4 = new Employee("Peter Burke", 39, room2, team2);
emp4.setManager(emp3);
emp4.setEntryDate(generateDate("2004-09-12"));
emp4.setLocation(new Location("Germany", "69190", "Walldorf"));
emp4.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_4_BurkeP.jpg");
emp4.setImage("/male_4_BurkeP.jpg");
emp4.setImageType(IMAGE_JPEG);
employeeSet.add(emp4);
Employee emp5 = new Employee("John Field", 42, room3, team2);
emp5.setManager(emp3);
emp5.setEntryDate(generateDate("2001-02-01"));
emp5.setLocation(new Location("Germany", "69190", "Walldorf"));
emp5.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_5_FieldJ.jpg");
emp5.setImage("/male_5_FieldJ.jpg");
emp5.setImageType(IMAGE_JPEG);
employeeSet.add(emp5);
Employee emp6 = new Employee("Susan Bay", 29, room2, team3);
emp6.setManager((Manager) emp1);
emp6.setEntryDate(generateDate("2010-12-01"));
emp6.setLocation(new Location("Germany", "69190", "Walldorf"));
emp6.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/female_6_BaySu.jpg");
emp6.setImage("/female_6_BaySu.jpg");
emp6.setImageType(IMAGE_JPEG);
employeeSet.add(emp6);
}
private Date generateDate(String dateString) {
Date date = new Date();
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
date = df.parse(dateString);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return date;
}
private Set<Photo> generatePhotos() {
Set<Photo> photos = new HashSet<Photo>();
for (int z = 0; z < NUMBER_OF_PHOTOS; z++) {
Photo photo = new Photo("Photo " + (z + 1));
photo.setType("image/" + arrayForImageType[z % (arrayForImageType.length)].toLowerCase());
photos.add(photo);
}
return photos;
}
public Set<Photo> getPhotoSet() {
return photoSet;
}
public Set<Employee> getEmployeeSet() {
return employeeSet;
}
public Set<Building> getBuildingSet() {
return buildingSet;
}
public Set<Room> getRoomSet() {
return roomSet;
}
public Set<Team> getTeamSet() {
return teamSet;
}
public void reset() {
if(photoSet != null){
photoSet.clear();
}
if(employeeSet != null){
employeeSet.clear();
}
if(buildingSet != null){
buildingSet.clear();
}
if(roomSet != null){
roomSet.clear();
}
if(teamSet != null){
teamSet.clear();
}
if(managerSet != null){
managerSet.clear();
}
Team.reset();
Building.reset();
Employee.reset();
Room.reset();
Photo.reset();
init();
}
public Set<Manager> getManagerSet() {
return managerSet;
}
}
| revert ref. scenario data change
Change-Id: I0e0c87f3418e37c4990fbb063ef8c941f6e86f6c
| odata-ref/src/main/java/com/sap/core/odata/ref/model/DataContainer.java | revert ref. scenario data change | <ide><path>data-ref/src/main/java/com/sap/core/odata/ref/model/DataContainer.java
<ide>
<ide> Manager emp3 = new Manager("Jonathan Smith", 56, room2, team1);
<ide> emp3.setManager((Manager) emp1);
<del> emp3.setEntryDate(generateDate("2012-12-12"));
<ide> emp3.setLocation(new Location("Germany", "69190", "Walldorf"));
<ide> emp3.setImageUri("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_3_SmithJo.jpg");
<ide> emp3.setImage("/male_3_SmithJo.jpg"); |
|
Java | mit | 09a2981f379e13099296273233e9734548331654 | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* PixelCalibratorDialog.java
*
* Created on Mar 1, 2010, 10:21:50 AM
*/
package org.micromanager.pixelcalibrator;
import java.awt.Dimension;
import java.awt.Point;
import java.util.prefs.Preferences;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
/**
*
* @author arthur
*/
public class PixelCalibratorDialog extends javax.swing.JFrame {
private PixelCalibratorPlugin plugin_;
/** Creates new form PixelCalibratorDialog */
PixelCalibratorDialog(PixelCalibratorPlugin plugin) {
plugin_ = plugin;
initComponents();
GUIUtils.recallPosition(this);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
explanationLabel = new javax.swing.JLabel();
calibrationProgressBar = new javax.swing.JProgressBar();
startButton = new javax.swing.JButton();
stopButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Pixel Calibrator (BETA)");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
explanationLabel.setText("<html>This plugin automatically measures size of the default camera's pixels at the sample plane.<br><br>To calibrate:<br><ol><li>Make sure you are using a correctly calibrated motorized xy stage.</li><li>Choose a nonperiodic specimen (e.g., a cell) and adjust your illumination and focus until you obtain crisp, high-contrast images. <li>Press Start (below).</li></ol></html>");
calibrationProgressBar.setForeground(new java.awt.Color(255, 0, 51));
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
stopButton.setText("Stop");
stopButton.setEnabled(false);
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(explanationLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 363, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(70, 70, 70)
.add(stopButton))
.add(startButton))
.add(18, 18, 18)
.add(calibrationProgressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 190, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(14, 14, 14))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(explanationLabel)
.add(10, 10, 10)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(stopButton)
.add(startButton))
.add(calibrationProgressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap(17, Short.MAX_VALUE))
);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-387)/2, (screenSize.height-268)/2, 387, 268);
}// </editor-fold>//GEN-END:initComponents
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
plugin_.stopCalibration();
}//GEN-LAST:event_stopButtonActionPerformed
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
plugin_.startCalibration();
}//GEN-LAST:event_startButtonActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
GUIUtils.storePosition(this);
plugin_.dispose();
}//GEN-LAST:event_formWindowClosing
public void updateStatus(boolean running, double progress) {
if (!running) {
startButton.setEnabled(true);
stopButton.setEnabled(false);
calibrationProgressBar.setEnabled(false);
} else {
toFront();
startButton.setEnabled(false);
stopButton.setEnabled(true);
calibrationProgressBar.setEnabled(true);
}
calibrationProgressBar.setValue((int) (progress*100));
this.repaint();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JProgressBar calibrationProgressBar;
private javax.swing.JLabel explanationLabel;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
// End of variables declaration//GEN-END:variables
public void dispose() {
GUIUtils.storePosition(this);
super.dispose();
}
public void setPlugin(PixelCalibratorPlugin plugin) {
plugin_ = plugin;
}
}
| plugins/PixelCalibrator/src/org/micromanager/pixelcalibrator/PixelCalibratorDialog.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* PixelCalibratorDialog.java
*
* Created on Mar 1, 2010, 10:21:50 AM
*/
package org.micromanager.pixelcalibrator;
import java.awt.Dimension;
import java.awt.Point;
import java.util.prefs.Preferences;
import org.micromanager.utils.JavaUtils;
/**
*
* @author arthur
*/
public class PixelCalibratorDialog extends javax.swing.JFrame {
private PixelCalibratorPlugin plugin_;
private final Preferences prefs_;
private String DIALOG_POSITION = "dialogPosition";
/** Creates new form PixelCalibratorDialog */
PixelCalibratorDialog(PixelCalibratorPlugin plugin) {
plugin_ = plugin;
initComponents();
prefs_ = Preferences.userNodeForPackage(this.getClass());
Point dialogPosition = (Point) JavaUtils.getObjectFromPrefs(prefs_, DIALOG_POSITION,null);
if (dialogPosition==null) {
Dimension screenDims = JavaUtils.getScreenDimensions();
dialogPosition = new Point((screenDims.width - this.getWidth())/2, (screenDims.height - this.getHeight())/2);
}
this.setLocation(dialogPosition);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
explanationLabel = new javax.swing.JLabel();
calibrationProgressBar = new javax.swing.JProgressBar();
startButton = new javax.swing.JButton();
stopButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Pixel Calibrator (BETA)");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
explanationLabel.setText("<html>This plugin automatically measures size of the default camera's pixels at the sample plane.<br><br>To calibrate:<br><ol><li>Make sure you are using a correctly calibrated motorized xy stage.</li><li>Choose a nonperiodic specimen (e.g., a cell) and adjust your illumination and focus until you obtain crisp, high-contrast images. <li>Press Start (below).</li></ol></html>");
calibrationProgressBar.setForeground(new java.awt.Color(255, 0, 51));
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
stopButton.setText("Stop");
stopButton.setEnabled(false);
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(explanationLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 363, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(70, 70, 70)
.add(stopButton))
.add(startButton))
.add(18, 18, 18)
.add(calibrationProgressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 190, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(14, 14, 14))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(explanationLabel)
.add(10, 10, 10)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(stopButton)
.add(startButton))
.add(calibrationProgressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap(17, Short.MAX_VALUE))
);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-387)/2, (screenSize.height-268)/2, 387, 268);
}// </editor-fold>//GEN-END:initComponents
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
plugin_.stopCalibration();
}//GEN-LAST:event_stopButtonActionPerformed
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
plugin_.startCalibration();
}//GEN-LAST:event_startButtonActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
JavaUtils.putObjectInPrefs(prefs_, DIALOG_POSITION, this.getLocation());
plugin_.dispose();
}//GEN-LAST:event_formWindowClosing
public void updateStatus(boolean running, double progress) {
if (!running) {
startButton.setEnabled(true);
stopButton.setEnabled(false);
calibrationProgressBar.setEnabled(false);
} else {
toFront();
startButton.setEnabled(false);
stopButton.setEnabled(true);
calibrationProgressBar.setEnabled(true);
}
calibrationProgressBar.setValue((int) (progress*100));
this.repaint();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JProgressBar calibrationProgressBar;
private javax.swing.JLabel explanationLabel;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
// End of variables declaration//GEN-END:variables
public void dispose() {
JavaUtils.putObjectInPrefs(prefs_, DIALOG_POSITION, this.getLocation());
super.dispose();
}
public void setPlugin(PixelCalibratorPlugin plugin) {
plugin_ = plugin;
}
}
| Storing location of window size using GUIUtils calls.
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@4314 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| plugins/PixelCalibrator/src/org/micromanager/pixelcalibrator/PixelCalibratorDialog.java | Storing location of window size using GUIUtils calls. | <ide><path>lugins/PixelCalibrator/src/org/micromanager/pixelcalibrator/PixelCalibratorDialog.java
<ide> import java.awt.Dimension;
<ide> import java.awt.Point;
<ide> import java.util.prefs.Preferences;
<add>import org.micromanager.utils.GUIUtils;
<ide> import org.micromanager.utils.JavaUtils;
<ide>
<ide> /**
<ide> */
<ide> public class PixelCalibratorDialog extends javax.swing.JFrame {
<ide> private PixelCalibratorPlugin plugin_;
<del> private final Preferences prefs_;
<del> private String DIALOG_POSITION = "dialogPosition";
<add>
<ide>
<ide> /** Creates new form PixelCalibratorDialog */
<ide> PixelCalibratorDialog(PixelCalibratorPlugin plugin) {
<ide> plugin_ = plugin;
<ide> initComponents();
<del> prefs_ = Preferences.userNodeForPackage(this.getClass());
<del> Point dialogPosition = (Point) JavaUtils.getObjectFromPrefs(prefs_, DIALOG_POSITION,null);
<del> if (dialogPosition==null) {
<del> Dimension screenDims = JavaUtils.getScreenDimensions();
<del> dialogPosition = new Point((screenDims.width - this.getWidth())/2, (screenDims.height - this.getHeight())/2);
<del> }
<del> this.setLocation(dialogPosition);
<add> GUIUtils.recallPosition(this);
<add> }
<ide>
<del> }
<ide>
<ide> /** This method is called from within the constructor to
<ide> * initialize the form.
<ide> }//GEN-LAST:event_startButtonActionPerformed
<ide>
<ide> private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
<del> JavaUtils.putObjectInPrefs(prefs_, DIALOG_POSITION, this.getLocation());
<add> GUIUtils.storePosition(this);
<ide> plugin_.dispose();
<ide> }//GEN-LAST:event_formWindowClosing
<ide>
<ide> // End of variables declaration//GEN-END:variables
<ide>
<ide> public void dispose() {
<del> JavaUtils.putObjectInPrefs(prefs_, DIALOG_POSITION, this.getLocation());
<add> GUIUtils.storePosition(this);
<ide> super.dispose();
<ide> }
<ide> |
|
JavaScript | mit | 75199691adeccc7a31586182ce567981f6988bfe | 0 | fireball-packages/code-editor,fireball-packages/code-editor | /* global __dirname */
/* global Editor */
var Util = require( 'util' );
var Path = require( 'path' );
var Firedoc = require( 'firedoc' ).Firedoc;
var enginePath = Editor.url( 'app://utils/api/engine-framework' );
var editorPath = Editor.url( 'app://utils/api/editor-framework' );
var runtimePath = Editor.runtimePath;
var doc;
module.exports = {
load: function () {
doc = new Firedoc( {
cwd: enginePath,
paths: [
enginePath,
editorPath,
Editor.projectPath
],
parseOnly: true
} );
console.log(Editor.appPath);
},
unload: function () {
Editor.Panel.close('code-editor.panel');
},
'code-editor:open-by-uuid': function( uuid ) {
// if ( !win || !win.focus ) {
// win = new Editor.Window( 'code-editor', {
// 'title': 'Fireball - Code Editor',
// 'width': 960,
// 'height': 720,
// 'min-width': 300,
// 'min-height': 300,
// 'show': true,
// 'resizable': true,
// } );
// Editor.MainMenu.add( 'File/Save', {
// 'message': 'code-editor:save'
// } );
// win.nativeWin.on( 'closed', function() {
// Editor.MainMenu.remove('File/Save');
// win = null;
// } );
// win.nativeWin.webContents.on( 'did-finish-load', function() {
// doc.build( function ( err, ast, opt ) {
// win.nativeWin.webContents.send( 'code-editor:ast', ast );
// } );
// } );
// } else {
// win.focus();
// }
// win.load( 'packages://code-editor/panel/index.html', {
// url: Editor.assetdb.uuidToUrl( uuid ),
// path: Editor.assetdb.uuidToFspath( uuid ),
// } );
var editorWin = Editor.Panel.findWindow('code-editor.panel');
Editor.Panel.open('code-editor.panel', {
url: Editor.assetdb.uuidToUrl( uuid ),
path: Editor.assetdb.uuidToFspath( uuid ),
});
// first time open the code editor
if ( !editorWin ) {
editorWin = Editor.Panel.findWindow('code-editor.panel');
editorWin.nativeWin.webContents.on( 'did-finish-load', function() {
doc.build( function ( err, ast, opt ) {
editorWin.sendToPage( 'code-editor:ast', ast );
});
});
}
},
'code-editor:save': function() {
// win.nativeWin.webContents.send( 'code-editor:save-from-page' );
Editor.Panel.sendToPanel( 'code-editor.panel', 'code-editor:save-from-page' );
},
// 'code-editor:open-by-path': function( path ) {
// var win = new Editor.Window( 'code-editor', {
// 'title': 'Fireball - Canvas Studio',
// 'width': 1280,
// 'height': 720,
// 'min-width': 100,
// 'min-height': 100,
// 'show': false,
// 'resizable': true,
// } );
// win.load( 'packages://code-editor/panel/index.html', {
// path: path
// } );
// },
};
| main.js | /* global __dirname */
/* global Editor */
var Util = require( 'util' );
var Path = require( 'path' );
var Firedoc = require( 'firedoc' ).Firedoc;
var enginePath = Editor.url( 'app://utils/api/engine-framework' );
var editorPath = Editor.url( 'app://utils/api/editor-framework' );
var runtimePath = Editor.runtimePath;
var doc;
module.exports = {
load: function () {
doc = new Firedoc( {
cwd: enginePath,
paths: [
enginePath,
editorPath,
Editor.projectPath
],
parseOnly: true
} );
console.log(Editor.appPath);
},
unload: function () {
Editor.Panel.close('code-editor.panel');
},
'code-editor:open-by-uuid': function( uuid ) {
// if ( !win || !win.focus ) {
// win = new Editor.Window( 'code-editor', {
// 'title': 'Fireball - Code Editor',
// 'width': 960,
// 'height': 720,
// 'min-width': 300,
// 'min-height': 300,
// 'show': true,
// 'resizable': true,
// } );
// Editor.MainMenu.add( 'File/Save', {
// 'message': 'code-editor:save'
// } );
// win.nativeWin.on( 'closed', function() {
// Editor.MainMenu.remove('File/Save');
// win = null;
// } );
// win.nativeWin.webContents.on( 'did-finish-load', function() {
// doc.build( function ( err, ast, opt ) {
// win.nativeWin.webContents.send( 'code-editor:ast', ast );
// } );
// } );
// } else {
// win.focus();
// }
// win.load( 'packages://code-editor/panel/index.html', {
// url: Editor.assetdb.uuidToUrl( uuid ),
// path: Editor.assetdb.uuidToFspath( uuid ),
// } );
Editor.Panel.open('code-editor.panel', {
url: Editor.assetdb.uuidToUrl( uuid ),
path: Editor.assetdb.uuidToFspath( uuid ),
});
var editorWin = Editor.Panel.findWindow('code-editor.panel');
editorWin.nativeWin.webContents.on( 'did-finish-load', function() {
doc.build( function ( err, ast, opt ) {
editorWin.sendToPage( 'code-editor:ast', ast );
});
});
},
'code-editor:save': function() {
// win.nativeWin.webContents.send( 'code-editor:save-from-page' );
Editor.Panel.sendToPanel( 'code-editor.panel', 'code-editor:save-from-page' );
},
// 'code-editor:open-by-path': function( path ) {
// var win = new Editor.Window( 'code-editor', {
// 'title': 'Fireball - Canvas Studio',
// 'width': 1280,
// 'height': 720,
// 'min-width': 100,
// 'min-height': 100,
// 'show': false,
// 'resizable': true,
// } );
// win.load( 'packages://code-editor/panel/index.html', {
// path: path
// } );
// },
};
| add init code for code ast
| main.js | add init code for code ast | <ide><path>ain.js
<ide> // path: Editor.assetdb.uuidToFspath( uuid ),
<ide> // } );
<ide>
<add> var editorWin = Editor.Panel.findWindow('code-editor.panel');
<add>
<ide> Editor.Panel.open('code-editor.panel', {
<ide> url: Editor.assetdb.uuidToUrl( uuid ),
<ide> path: Editor.assetdb.uuidToFspath( uuid ),
<ide> });
<ide>
<del> var editorWin = Editor.Panel.findWindow('code-editor.panel');
<del> editorWin.nativeWin.webContents.on( 'did-finish-load', function() {
<del> doc.build( function ( err, ast, opt ) {
<del> editorWin.sendToPage( 'code-editor:ast', ast );
<add> // first time open the code editor
<add> if ( !editorWin ) {
<add> editorWin = Editor.Panel.findWindow('code-editor.panel');
<add> editorWin.nativeWin.webContents.on( 'did-finish-load', function() {
<add> doc.build( function ( err, ast, opt ) {
<add> editorWin.sendToPage( 'code-editor:ast', ast );
<add> });
<ide> });
<del> });
<add> }
<ide> },
<ide>
<ide> 'code-editor:save': function() { |
|
Java | agpl-3.0 | a8957bb3bdc875a68729b69bf23ad340b1e56ce1 | 0 | cojen/Tupl | /*
* Copyright (C) 2011-2017 Cojen.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cojen.tupl.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Random;
import org.junit.*;
import static org.junit.Assert.*;
import org.cojen.tupl.*;
import static org.cojen.tupl.core.TestUtils.*;
/**
*
*
* @author Brian S O'Neill
*/
public class CompactTest {
public static void main(String[] args) throws Exception {
org.junit.runner.JUnitCore.main(CompactTest.class.getName());
}
protected DatabaseConfig decorate(DatabaseConfig config) throws Exception {
config.directPageAccess(false);
return config;
}
protected Database newTempDb() throws Exception {
return newTempDatabase(getClass());
}
@After
public void teardown() throws Exception {
deleteTempDatabases(getClass());
mDb = null;
mIndex = null;
}
protected Database mDb;
private Index mIndex;
private Index openTestIndex() throws Exception {
// Stash in a field to prevent GC activity from closing index too soon and messing up
// the stats.
return mIndex = mDb.openIndex("test");
}
@Test
public void basic() throws Exception {
mDb = newTempDb();
final Index ix = openTestIndex();
final int seed = 98232;
final int count = 100000;
var rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
ix.store(Transaction.BOGUS, key, key);
}
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
Database.Stats stats1 = mDb.stats();
mDb.compactFile(null, 0.9);
Database.Stats stats2 = mDb.stats();
try {
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
} catch (AssertionError e) {
// Can fail if delayed by concurrent test load. Retry.
mDb.compactFile(null, 0.9);
stats2 = mDb.stats();
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
}
assertTrue(mDb.verify(null));
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(key, value);
}
}
// Compact even further.
for (int i=91; i<=99; i++) {
mDb.compactFile(null, i / 100.0);
}
Database.Stats stats3 = mDb.stats();
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
assertTrue(mDb.verify(null));
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(key, value);
}
}
}
@Test
public void largeValues1() throws Exception {
largeValues(512, 1000, 4000, 4000);
}
@Test
public void largeValues2() throws Exception {
largeValues(16384, 100, 10000, 50000);
}
@Test
public void largeValues3() throws Exception {
largeValues(65536, 100, 70000, 90000);
}
@Test
public void largeValues4() throws Exception {
largeValues(512, 100, 30000, 50000);
}
@Test
public void largeValues5() throws Exception {
// Include a large sparse value too.
largeValues(512, 100, 30000, 50000, () -> {
Index ix = openTestIndex();
ValueAccessor accessor = ix.newAccessor(null, "sparse".getBytes());
accessor.valueLength(100_000);
accessor.close();
});
}
private void largeValues(final int pageSize, final int count,
final int min, final int max)
throws Exception
{
largeValues(pageSize, count, min, max, null);
}
private void largeValues(final int pageSize, final int count,
final int min, final int max,
final Callback prepare)
throws Exception
{
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.pageSize(pageSize)
.minCacheSize(10_000_000)
.durabilityMode(DurabilityMode.NO_FLUSH)));
final Index ix = openTestIndex();
final int seed = 1234;
var rnd1 = new Random(seed);
var rnd2 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
byte[] key = ("key" + k).getBytes();
byte[] value = randomStr(rnd2, min, max);
ix.store(Transaction.BOGUS, key, value);
}
rnd1 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
if (i % 2 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
if (prepare != null) {
prepare.run();
}
Database.Stats stats1 = mDb.stats();
mDb.compactFile(null, 0.9);
Database.Stats stats2 = mDb.stats();
try {
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
} catch (AssertionError e) {
// Can fail if delayed by concurrent test load. Retry.
mDb.compactFile(null, 0.9);
stats2 = mDb.stats();
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
}
assertTrue(mDb.verify(null));
rnd1 = new Random(seed);
rnd2 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
byte[] v = randomStr(rnd2, min, max);
if (i % 2 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(v, value);
}
}
// Compact even further.
for (int i=91; i<=99; i++) {
mDb.compactFile(null, i / 100.0);
}
Database.Stats stats3 = mDb.stats();
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
assertTrue(mDb.verify(null));
rnd1 = new Random(seed);
rnd2 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
byte[] v = randomStr(rnd2, min, max);
if (i % 2 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(v, value);
}
}
}
@Test
public void manualAbort() throws Exception {
mDb = newTempDb();
final Index ix = openTestIndex();
final int seed = 98232;
final int count = 100000;
var rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
ix.store(Transaction.BOGUS, key, key);
}
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
var obs = new CompactionObserver() {
private int count;
@Override
public boolean indexNodeVisited(long id) {
return ++count < 100;
}
};
mDb.compactFile(obs, 0.5);
Database.Stats stats2 = mDb.stats();
assertEquals(stats1, stats2);
assertTrue(mDb.verify(null));
}
@Test
public void autoAbort() throws Exception {
mDb = newTempDb();
final Index ix = openTestIndex();
final int seed = 98232;
final int count = 100000;
var rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
ix.store(Transaction.BOGUS, key, key);
}
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
final var obs = new CompactionObserver() {
private int count;
private boolean resume;
@Override
public synchronized boolean indexNodeVisited(long id) {
if (++count > 100) {
try {
while (!resume) {
wait();
}
} catch (InterruptedException e) {
return false;
}
}
return true;
}
synchronized void resume() {
this.resume = true;
notify();
}
};
var comp = new Thread() {
volatile Object result;
@Override
public void run() {
try {
Database.Stats stats1 = mDb.stats();
mDb.compactFile(obs, 0.5);
Database.Stats stats2 = mDb.stats();
result = stats2.totalPages() < stats1.totalPages();
} catch (Exception e) {
result = e;
}
}
};
comp.start();
// Compaction will abort because of database growth.
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.insert(Transaction.BOGUS, key, key);
}
}
obs.resume();
comp.join();
assertEquals(Boolean.FALSE, comp.result);
assertTrue(mDb.verify(null));
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(key, value);
}
}
@Test
public void stress() throws Exception {
for (int i=3; --i>=0; ) {
AssertionError e = doStress();
if (e == null) {
break;
}
if (i == 0) {
throw e;
}
// Retry.
teardown();
}
}
/* FIXME
java.lang.IllegalArgumentException: Negative position
at java.base/sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:785)
at [email protected]/org.cojen.tupl.io.JavaFileIO.doRead(JavaFileIO.java:160)
at [email protected]/org.cojen.tupl.io.AbstractFileIO.access(AbstractFileIO.java:325)
at [email protected]/org.cojen.tupl.io.AbstractFileIO.access(AbstractFileIO.java:340)
at [email protected]/org.cojen.tupl.io.AbstractFileIO.read(AbstractFileIO.java:192)
at [email protected]/org.cojen.tupl.io.FilePageArray.readPage(FilePageArray.java:112)
at [email protected]/org.cojen.tupl.core._SnapshotPageArray.readPage(_SnapshotPageArray.java:124)
at [email protected]/org.cojen.tupl.io.PageArray.readPage(PageArray.java:119)
at [email protected]/org.cojen.tupl.core._PageQueue.readRemoveNode(_PageQueue.java:396)
at [email protected]/org.cojen.tupl.core._PageQueue.loadRemoveNode(_PageQueue.java:378)
at [email protected]/org.cojen.tupl.core._PageQueue.tryRemove(_PageQueue.java:353)
at [email protected]/org.cojen.tupl.core._PageQueue.reclaim(_PageQueue.java:267)
at [email protected]/org.cojen.tupl.core._PageManager.compactionReclaim(_PageManager.java:587)
at [email protected]/org.cojen.tupl.core._DurablePageDb.compactionReclaim(_DurablePageDb.java:595)
at [email protected]/org.cojen.tupl.core._LocalDatabase.compactFile(_LocalDatabase.java:2616)
at [email protected]/org.cojen.tupl.core.CompactTest$4.run(CompactTest.java:444)
*/
private AssertionError doStress() throws Exception {
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.pageSize(512)
.minCacheSize(10_000_000).maxCacheSize(100_000_000)
.durabilityMode(DurabilityMode.NO_FLUSH)));
var comp = new Thread() {
volatile boolean stop;
volatile int success;
volatile int abort;
volatile Exception failed;
@Override
public void run() {
try {
while (!stop) {
Database.Stats stats1 = mDb.stats();
mDb.compactFile(null, 0.5);
Database.Stats stats2 = mDb.stats();
if (stats2.totalPages() < stats1.totalPages()) {
success++;
} else {
abort++;
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
failed = e;
}
}
};
comp.start();
final Index ix = openTestIndex();
final int count = 1000;
int seed = 1234;
for (int round=0; round<1000; round++) {
int roundCount = round;
var rnd1 = new Random(seed);
var rnd2 = new Random(seed);
for (int i=0; i<roundCount; i++) {
int k = rnd1.nextInt();
byte[] key = ("key" + k).getBytes();
byte[] value = randomStr(rnd2, 1000);
ix.store(Transaction.BOGUS, key, value);
}
rnd1 = new Random(seed);
for (int i=0; i<roundCount; i++) {
int k = rnd1.nextInt();
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
seed++;
}
comp.stop = true;
comp.join();
assertNull(comp.failed);
assertTrue(comp.abort > 0);
try {
// This assertion might fail on a slower machine.
assertTrue(comp.success > 0);
return null;
} catch (AssertionError e) {
return e;
}
}
@Test
public void longTransaction() throws Exception {
// A transaction with an undo log persisted will not be discovered by the compaction
// scan. This is only a problem for long running transactions -- they need to span the
// entire duration of the compaction.
mDb = newTempDb();
mDb.suspendCheckpoints();
final Index ix = openTestIndex();
for (int i=100000; i<200000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.insert(null, key, key);
}
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
assertEquals(0, stats1.freePages());
Transaction txn = mDb.newTransaction();
for (int i=110000; i<200000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.delete(txn, key);
}
mDb.checkpoint();
Database.Stats stats2 = mDb.stats();
assertTrue(stats2.freePages() > 100);
mDb.compactFile(null, 0.9);
// Nothing happened because most pages were in the undo log and not moved.
assertEquals(stats2, mDb.stats());
txn.commit();
// Compact will work this time now that undo log is gone.
mDb.compactFile(null, 0.9);
Database.Stats stats3 = mDb.stats();
try {
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
} catch (AssertionError e) {
// Can fail if delayed by concurrent test load. Retry.
mDb.compactFile(null, 0.9);
stats3 = mDb.stats();
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
}
}
@Test
public void trashHiding() throws Exception {
// A transaction can move a large value into the fragmented trash and compaction won't
// be able to move it. This is not desirable, but at least confirm the behavior. If the
// trash could be scanned, it would also need to check if compaction is in progress
// when values move to and from the trash.
mDb = newTempDb();
final Index ix = openTestIndex();
byte[] key = "hello".getBytes();
byte[] value = randomStr(new Random(), 1000000);
ix.store(Transaction.BOGUS, key, value);
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
Transaction txn = mDb.newTransaction();
ix.delete(txn, key);
mDb.compactFile(null, 0.9);
Database.Stats stats2 = mDb.stats();
assertTrue(stats2.totalPages() - stats2.freePages() > 200);
txn.commit();
mDb.compactFile(null, 0.9);
Database.Stats stats3 = mDb.stats();
assertTrue(stats3.totalPages() - stats3.freePages() < 50);
}
@Test
public void randomInserts() throws Exception {
// Random inserts with a small cache size tends to create a lot of extra unused space
// in the file. Verify compaction can reclaim the space.
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.minCacheSize(1_000_000)
.checkpointRate(-1, null)
.durabilityMode(DurabilityMode.NO_FLUSH)));
final Index ix = openTestIndex();
final int seed = 793846;
final int count = 500000;
var rnd = new Random(seed);
var value = new byte[0];
for (int i=0; i<count; i++) {
byte[] key = randomStr(rnd, 10, 20);
ix.store(null, key, value);
if (i % 100000 == 0) {
mDb.checkpoint();
}
}
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
assertTrue(mDb.compactFile(null, 0.95));
Database.Stats stats2 = mDb.stats();
assertTrue(stats1.totalPages() > stats2.totalPages() * 2);
// Verify no data loss.
mDb.verify(null);
rnd = new Random(seed);
for (int i=0; i<count; i++) {
byte[] key = randomStr(rnd, 10, 20);
value = ix.load(null, key);
assertNotNull(value);
assertEquals(0, value.length);
}
}
@Test
public void snapshotAbort() throws Exception {
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.checkpointRate(-1, null)
.durabilityMode(DurabilityMode.NO_FLUSH)));
final Index ix = openTestIndex();
for (int i=0; i<100000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.store(null, key, key);
}
mDb.checkpoint();
for (int i=0; i<100000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.delete(null, key);
}
Snapshot snap = mDb.beginSnapshot();
for (int i=0; i<10; i++) {
assertFalse(mDb.compactFile(null, 0.9));
}
var dbFile = new File(baseFileForTempDatabase(getClass(), mDb).getPath() + ".db");
assertTrue(dbFile.length() > 1_000_000);
var bout = new ByteArrayOutputStream();
snap.writeTo(bout);
assertTrue(mDb.compactFile(null, 0.9));
assertTrue(dbFile.length() < 100_000);
deleteTempDatabase(getClass(), mDb);
var bin = new ByteArrayInputStream(bout.toByteArray());
DatabaseConfig config = decorate(new DatabaseConfig()
.baseFile(newTempBaseFile(getClass())));
mDb = Database.restoreFromSnapshot(config, bin);
assertTrue(mDb.verify(null));
mDb.close();
}
}
| src/test/java/org/cojen/tupl/core/CompactTest.java | /*
* Copyright (C) 2011-2017 Cojen.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cojen.tupl.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Random;
import org.junit.*;
import static org.junit.Assert.*;
import org.cojen.tupl.*;
import static org.cojen.tupl.core.TestUtils.*;
/**
*
*
* @author Brian S O'Neill
*/
public class CompactTest {
public static void main(String[] args) throws Exception {
org.junit.runner.JUnitCore.main(CompactTest.class.getName());
}
protected DatabaseConfig decorate(DatabaseConfig config) throws Exception {
config.directPageAccess(false);
return config;
}
protected Database newTempDb() throws Exception {
return newTempDatabase(getClass());
}
@After
public void teardown() throws Exception {
deleteTempDatabases(getClass());
mDb = null;
mIndex = null;
}
protected Database mDb;
private Index mIndex;
private Index openTestIndex() throws Exception {
// Stash in a field to prevent GC activity from closing index too soon and messing up
// the stats.
return mIndex = mDb.openIndex("test");
}
@Test
public void basic() throws Exception {
mDb = newTempDb();
final Index ix = openTestIndex();
final int seed = 98232;
final int count = 100000;
var rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
ix.store(Transaction.BOGUS, key, key);
}
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
Database.Stats stats1 = mDb.stats();
mDb.compactFile(null, 0.9);
Database.Stats stats2 = mDb.stats();
try {
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
} catch (AssertionError e) {
// Can fail if delayed by concurrent test load. Retry.
mDb.compactFile(null, 0.9);
stats2 = mDb.stats();
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
}
assertTrue(mDb.verify(null));
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(key, value);
}
}
// Compact even further.
for (int i=91; i<=99; i++) {
mDb.compactFile(null, i / 100.0);
}
Database.Stats stats3 = mDb.stats();
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
assertTrue(mDb.verify(null));
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(key, value);
}
}
}
@Test
public void largeValues1() throws Exception {
largeValues(512, 1000, 4000, 4000);
}
@Test
public void largeValues2() throws Exception {
largeValues(16384, 100, 10000, 50000);
}
@Test
public void largeValues3() throws Exception {
largeValues(65536, 100, 70000, 90000);
}
@Test
public void largeValues4() throws Exception {
largeValues(512, 100, 30000, 50000);
}
@Test
public void largeValues5() throws Exception {
// Include a large sparse value too.
largeValues(512, 100, 30000, 50000, () -> {
Index ix = openTestIndex();
ValueAccessor accessor = ix.newAccessor(null, "sparse".getBytes());
accessor.valueLength(100_000);
accessor.close();
});
}
private void largeValues(final int pageSize, final int count,
final int min, final int max)
throws Exception
{
largeValues(pageSize, count, min, max, null);
}
private void largeValues(final int pageSize, final int count,
final int min, final int max,
final Callback prepare)
throws Exception
{
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.pageSize(pageSize)
.minCacheSize(10_000_000)
.durabilityMode(DurabilityMode.NO_FLUSH)));
final Index ix = openTestIndex();
final int seed = 1234;
var rnd1 = new Random(seed);
var rnd2 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
byte[] key = ("key" + k).getBytes();
byte[] value = randomStr(rnd2, min, max);
ix.store(Transaction.BOGUS, key, value);
}
rnd1 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
if (i % 2 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
if (prepare != null) {
prepare.run();
}
Database.Stats stats1 = mDb.stats();
mDb.compactFile(null, 0.9);
Database.Stats stats2 = mDb.stats();
try {
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
} catch (AssertionError e) {
// Can fail if delayed by concurrent test load. Retry.
mDb.compactFile(null, 0.9);
stats2 = mDb.stats();
assertTrue(stats2.freePages() < stats1.freePages());
assertTrue(stats2.totalPages() < stats1.totalPages());
}
assertTrue(mDb.verify(null));
rnd1 = new Random(seed);
rnd2 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
byte[] v = randomStr(rnd2, min, max);
if (i % 2 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(v, value);
}
}
// Compact even further.
for (int i=91; i<=99; i++) {
mDb.compactFile(null, i / 100.0);
}
Database.Stats stats3 = mDb.stats();
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
assertTrue(mDb.verify(null));
rnd1 = new Random(seed);
rnd2 = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd1.nextInt();
byte[] v = randomStr(rnd2, min, max);
if (i % 2 == 0) {
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(v, value);
}
}
}
@Test
public void manualAbort() throws Exception {
mDb = newTempDb();
final Index ix = openTestIndex();
final int seed = 98232;
final int count = 100000;
var rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
ix.store(Transaction.BOGUS, key, key);
}
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
var obs = new CompactionObserver() {
private int count;
@Override
public boolean indexNodeVisited(long id) {
return ++count < 100;
}
};
mDb.compactFile(obs, 0.5);
Database.Stats stats2 = mDb.stats();
assertEquals(stats1, stats2);
assertTrue(mDb.verify(null));
}
@Test
public void autoAbort() throws Exception {
mDb = newTempDb();
final Index ix = openTestIndex();
final int seed = 98232;
final int count = 100000;
var rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
ix.store(Transaction.BOGUS, key, key);
}
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
}
final var obs = new CompactionObserver() {
private int count;
private boolean resume;
@Override
public synchronized boolean indexNodeVisited(long id) {
if (++count > 100) {
try {
while (!resume) {
wait();
}
} catch (InterruptedException e) {
return false;
}
}
return true;
}
synchronized void resume() {
this.resume = true;
notify();
}
};
var comp = new Thread() {
volatile Object result;
@Override
public void run() {
try {
Database.Stats stats1 = mDb.stats();
mDb.compactFile(obs, 0.5);
Database.Stats stats2 = mDb.stats();
result = stats2.totalPages() < stats1.totalPages();
} catch (Exception e) {
result = e;
}
}
};
comp.start();
// Compaction will abort because of database growth.
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
if (i % 4 != 0) {
byte[] key = ("key" + k).getBytes();
ix.insert(Transaction.BOGUS, key, key);
}
}
obs.resume();
comp.join();
assertEquals(Boolean.FALSE, comp.result);
assertTrue(mDb.verify(null));
rnd = new Random(seed);
for (int i=0; i<count; i++) {
int k = rnd.nextInt();
byte[] key = ("key" + k).getBytes();
byte[] value = ix.load(Transaction.BOGUS, key);
fastAssertArrayEquals(key, value);
}
}
@Test
public void stress() throws Exception {
for (int i=3; --i>=0; ) {
AssertionError e = doStress();
if (e == null) {
break;
}
if (i == 0) {
throw e;
}
// Retry.
teardown();
}
}
private AssertionError doStress() throws Exception {
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.pageSize(512)
.minCacheSize(10_000_000).maxCacheSize(100_000_000)
.durabilityMode(DurabilityMode.NO_FLUSH)));
var comp = new Thread() {
volatile boolean stop;
volatile int success;
volatile int abort;
volatile Exception failed;
@Override
public void run() {
try {
while (!stop) {
Database.Stats stats1 = mDb.stats();
mDb.compactFile(null, 0.5);
Database.Stats stats2 = mDb.stats();
if (stats2.totalPages() < stats1.totalPages()) {
success++;
} else {
abort++;
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
failed = e;
}
}
};
comp.start();
final Index ix = openTestIndex();
final int count = 1000;
int seed = 1234;
for (int round=0; round<1000; round++) {
int roundCount = round;
var rnd1 = new Random(seed);
var rnd2 = new Random(seed);
for (int i=0; i<roundCount; i++) {
int k = rnd1.nextInt();
byte[] key = ("key" + k).getBytes();
byte[] value = randomStr(rnd2, 1000);
ix.store(Transaction.BOGUS, key, value);
}
rnd1 = new Random(seed);
for (int i=0; i<roundCount; i++) {
int k = rnd1.nextInt();
byte[] key = ("key" + k).getBytes();
ix.delete(Transaction.BOGUS, key);
}
seed++;
}
comp.stop = true;
comp.join();
assertNull(comp.failed);
assertTrue(comp.abort > 0);
try {
// This assertion might fail on a slower machine.
assertTrue(comp.success > 0);
return null;
} catch (AssertionError e) {
return e;
}
}
@Test
public void longTransaction() throws Exception {
// A transaction with an undo log persisted will not be discovered by the compaction
// scan. This is only a problem for long running transactions -- they need to span the
// entire duration of the compaction.
mDb = newTempDb();
mDb.suspendCheckpoints();
final Index ix = openTestIndex();
for (int i=100000; i<200000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.insert(null, key, key);
}
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
assertEquals(0, stats1.freePages());
Transaction txn = mDb.newTransaction();
for (int i=110000; i<200000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.delete(txn, key);
}
mDb.checkpoint();
Database.Stats stats2 = mDb.stats();
assertTrue(stats2.freePages() > 100);
mDb.compactFile(null, 0.9);
// Nothing happened because most pages were in the undo log and not moved.
assertEquals(stats2, mDb.stats());
txn.commit();
// Compact will work this time now that undo log is gone.
mDb.compactFile(null, 0.9);
Database.Stats stats3 = mDb.stats();
try {
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
} catch (AssertionError e) {
// Can fail if delayed by concurrent test load. Retry.
mDb.compactFile(null, 0.9);
stats3 = mDb.stats();
assertTrue(stats3.freePages() < stats2.freePages());
assertTrue(stats3.totalPages() < stats2.totalPages());
}
}
@Test
public void trashHiding() throws Exception {
// A transaction can move a large value into the fragmented trash and compaction won't
// be able to move it. This is not desirable, but at least confirm the behavior. If the
// trash could be scanned, it would also need to check if compaction is in progress
// when values move to and from the trash.
mDb = newTempDb();
final Index ix = openTestIndex();
byte[] key = "hello".getBytes();
byte[] value = randomStr(new Random(), 1000000);
ix.store(Transaction.BOGUS, key, value);
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
Transaction txn = mDb.newTransaction();
ix.delete(txn, key);
mDb.compactFile(null, 0.9);
Database.Stats stats2 = mDb.stats();
assertTrue(stats2.totalPages() - stats2.freePages() > 200);
txn.commit();
mDb.compactFile(null, 0.9);
Database.Stats stats3 = mDb.stats();
assertTrue(stats3.totalPages() - stats3.freePages() < 50);
}
@Test
public void randomInserts() throws Exception {
// Random inserts with a small cache size tends to create a lot of extra unused space
// in the file. Verify compaction can reclaim the space.
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.minCacheSize(1_000_000)
.checkpointRate(-1, null)
.durabilityMode(DurabilityMode.NO_FLUSH)));
final Index ix = openTestIndex();
final int seed = 793846;
final int count = 500000;
var rnd = new Random(seed);
var value = new byte[0];
for (int i=0; i<count; i++) {
byte[] key = randomStr(rnd, 10, 20);
ix.store(null, key, value);
if (i % 100000 == 0) {
mDb.checkpoint();
}
}
mDb.checkpoint();
Database.Stats stats1 = mDb.stats();
assertTrue(mDb.compactFile(null, 0.95));
Database.Stats stats2 = mDb.stats();
assertTrue(stats1.totalPages() > stats2.totalPages() * 2);
// Verify no data loss.
mDb.verify(null);
rnd = new Random(seed);
for (int i=0; i<count; i++) {
byte[] key = randomStr(rnd, 10, 20);
value = ix.load(null, key);
assertNotNull(value);
assertEquals(0, value.length);
}
}
@Test
public void snapshotAbort() throws Exception {
mDb = newTempDatabase(getClass(),
decorate(new DatabaseConfig()
.checkpointRate(-1, null)
.durabilityMode(DurabilityMode.NO_FLUSH)));
final Index ix = openTestIndex();
for (int i=0; i<100000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.store(null, key, key);
}
mDb.checkpoint();
for (int i=0; i<100000; i++) {
byte[] key = ("key-" + i).getBytes();
ix.delete(null, key);
}
Snapshot snap = mDb.beginSnapshot();
for (int i=0; i<10; i++) {
assertFalse(mDb.compactFile(null, 0.9));
}
var dbFile = new File(baseFileForTempDatabase(getClass(), mDb).getPath() + ".db");
assertTrue(dbFile.length() > 1_000_000);
var bout = new ByteArrayOutputStream();
snap.writeTo(bout);
assertTrue(mDb.compactFile(null, 0.9));
assertTrue(dbFile.length() < 100_000);
deleteTempDatabase(getClass(), mDb);
var bin = new ByteArrayInputStream(bout.toByteArray());
DatabaseConfig config = decorate(new DatabaseConfig()
.baseFile(newTempBaseFile(getClass())));
mDb = Database.restoreFromSnapshot(config, bin);
assertTrue(mDb.verify(null));
mDb.close();
}
}
| Add stress test failure info.
| src/test/java/org/cojen/tupl/core/CompactTest.java | Add stress test failure info. | <ide><path>rc/test/java/org/cojen/tupl/core/CompactTest.java
<ide> }
<ide> }
<ide>
<add> /* FIXME
<add>
<add>java.lang.IllegalArgumentException: Negative position
<add> at java.base/sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:785)
<add> at [email protected]/org.cojen.tupl.io.JavaFileIO.doRead(JavaFileIO.java:160)
<add> at [email protected]/org.cojen.tupl.io.AbstractFileIO.access(AbstractFileIO.java:325)
<add> at [email protected]/org.cojen.tupl.io.AbstractFileIO.access(AbstractFileIO.java:340)
<add> at [email protected]/org.cojen.tupl.io.AbstractFileIO.read(AbstractFileIO.java:192)
<add> at [email protected]/org.cojen.tupl.io.FilePageArray.readPage(FilePageArray.java:112)
<add> at [email protected]/org.cojen.tupl.core._SnapshotPageArray.readPage(_SnapshotPageArray.java:124)
<add> at [email protected]/org.cojen.tupl.io.PageArray.readPage(PageArray.java:119)
<add> at [email protected]/org.cojen.tupl.core._PageQueue.readRemoveNode(_PageQueue.java:396)
<add> at [email protected]/org.cojen.tupl.core._PageQueue.loadRemoveNode(_PageQueue.java:378)
<add> at [email protected]/org.cojen.tupl.core._PageQueue.tryRemove(_PageQueue.java:353)
<add> at [email protected]/org.cojen.tupl.core._PageQueue.reclaim(_PageQueue.java:267)
<add> at [email protected]/org.cojen.tupl.core._PageManager.compactionReclaim(_PageManager.java:587)
<add> at [email protected]/org.cojen.tupl.core._DurablePageDb.compactionReclaim(_DurablePageDb.java:595)
<add> at [email protected]/org.cojen.tupl.core._LocalDatabase.compactFile(_LocalDatabase.java:2616)
<add> at [email protected]/org.cojen.tupl.core.CompactTest$4.run(CompactTest.java:444)
<add>
<add> */
<ide> private AssertionError doStress() throws Exception {
<ide> mDb = newTempDatabase(getClass(),
<ide> decorate(new DatabaseConfig() |
|
Java | mit | 93ee1ef14e838c8ad0cea64f325b820742d872ca | 0 | hhu-stups/bmoth | package de.bmoth.ltl;
import de.bmoth.backend.ltl.LTLTransformations;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ParserException;
import de.bmoth.parser.ast.nodes.ltl.BuechiAutomaton;
import de.bmoth.parser.ast.nodes.ltl.LTLFormula;
import de.bmoth.parser.ast.nodes.ltl.LTLNode;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LTLBuechiTest {
@Test
public void testGraphConstructionNext() throws ParserException {
String formula = "(X {0=1})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(3, buechiAutomaton.getFinalNodeSet().size());
}
@Test
public void testGraphConstructionGlobally() throws ParserException {
String formula = "G (X {0=1})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(2, buechiAutomaton.getFinalNodeSet().size());
}
@Test
@Ignore
public void testGraphConstructionGloballyFinally() throws ParserException {
String formula = "G (F (X {0=1}))";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
System.out.println(node.toString());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
System.out.println(buechiAutomaton.toString());
assertEquals(4, buechiAutomaton.getFinalNodeSet().size());
}
@Test
@Ignore
public void testGraphConstructionFinally() throws ParserException {
String formula = "F (X {0=1})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(4, buechiAutomaton.getFinalNodeSet().size());
}
@Test
public void testGraphConstructionNot() throws ParserException {
String formula = "G not (X {0=1})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(2, buechiAutomaton.getFinalNodeSet().size());
}
@Test
public void testGraphConstructionAnd() throws ParserException {
String formula = "G (X ( {0=1} & {2=3} ) )";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(2, buechiAutomaton.getFinalNodeSet().size());
}
}
| src/test/java/de/bmoth/ltl/LTLBuechiTest.java | package de.bmoth.ltl;
import de.bmoth.backend.ltl.LTLTransformations;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ParserException;
import de.bmoth.parser.ast.nodes.ltl.BuechiAutomaton;
import de.bmoth.parser.ast.nodes.ltl.LTLFormula;
import de.bmoth.parser.ast.nodes.ltl.LTLNode;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LTLBuechiTest {
@Test
public void testGraphConstructionNext() throws ParserException {
String formula = "(X {0=1})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(3, buechiAutomaton.getFinalNodeSet().size());
}
@Test
public void testGraphConstructionGlobally() throws ParserException {
String formula = "G (X {0=1})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(2, buechiAutomaton.getFinalNodeSet().size());
}
@Test
@Ignore
public void testGraphConstructionGloballyFinally() throws ParserException {
String formula = "G (F (X {0=1}))";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(4, buechiAutomaton.getFinalNodeSet().size());
}
@Test
public void testGraphConstructionNot() throws ParserException {
String formula = "G not (X {0=1})";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(2, buechiAutomaton.getFinalNodeSet().size());
}
@Test
public void testGraphConstructionAnd() throws ParserException {
String formula = "G (X ( {0=1} & {2=3} ) )";
LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
assertEquals(2, buechiAutomaton.getFinalNodeSet().size());
}
}
| Two ignored tests for finally
| src/test/java/de/bmoth/ltl/LTLBuechiTest.java | Two ignored tests for finally | <ide><path>rc/test/java/de/bmoth/ltl/LTLBuechiTest.java
<ide> String formula = "G (F (X {0=1}))";
<ide> LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
<ide> LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
<add> System.out.println(node.toString());
<add> BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
<add> System.out.println(buechiAutomaton.toString());
<add> assertEquals(4, buechiAutomaton.getFinalNodeSet().size());
<add> }
<add>
<add> @Test
<add> @Ignore
<add> public void testGraphConstructionFinally() throws ParserException {
<add> String formula = "F (X {0=1})";
<add> LTLFormula ltlFormula = Parser.getLTLFormulaAsSemanticAst(formula);
<add> LTLNode node = LTLTransformations.transformLTLNode(ltlFormula.getLTLNode());
<ide> BuechiAutomaton buechiAutomaton = new BuechiAutomaton(node);
<ide> assertEquals(4, buechiAutomaton.getFinalNodeSet().size());
<ide> } |
|
Java | apache-2.0 | 8a5a36bd1d4f4b9b66ade9ddfbdec57269bf8268 | 0 | smartcommunitylab/sco.cityreport,smartcommunitylab/sco.cityreport,smartcommunitylab/sco.cityreport | package it.smartcommunitylab.cityreport.utils;
import it.smartcommunitylab.cityreport.data.IssueRepository;
import it.smartcommunitylab.cityreport.model.Issuer;
import it.smartcommunitylab.cityreport.model.Location;
import it.smartcommunitylab.cityreport.model.ServiceIssue;
import it.smartcommunitylab.cityreport.services.IssueManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.codec.digest.DigestUtils;
import org.bson.types.ObjectId;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import eu.trentorise.smartcampus.aac.AACService;
import eu.trentorise.smartcampus.aac.model.TokenData;
import eu.trentorise.smartcampus.network.RemoteConnector;
import eu.trentorise.smartcampus.profileservice.BasicProfileService;
import eu.trentorise.smartcampus.profileservice.model.AccountProfile;
@Component
public class GericoConnector {
private static final String F_EXTERNAL_ID_NEW = "external_id_new";
private static final String F_EXTERNAL_ID = "external_id";
private static final String F_NOTE_EXTERNAL = "note_external";
private static final String F_MAC = "mac";
private static final String F_STRADA = "strada";
private static final String F_LONGITUDINE = "longitudine";
private static final String F_LATITUDINE = "latitudine";
private static final String F_STATO = "stato";
private static final String F_NOTE = "note";
private static final String F_OGGETTO = "oggetto";
private static final String F_EMAIL = "email";
private static final String F_ORIGINE_DETTAGLIO = "origine_dettaglio";
private static final String F_ORIGINE = "origine";
private static final String F_MEZZO = "mezzo";
private static final String F_PUBBLICO = "pubblico";
private static final String F_ATTIVATORE = "attivatore";
private static final Object F_ID = "id";
private static final String APP_NAME = "App segnala";
private static final String APP_ID = "app_s";
@Autowired
private IssueRepository issueRepository;
@Autowired
private IssueManager manager;
@Autowired
private Environment env;
private AACService service;
private BasicProfileService profileService;
@PostConstruct
private void init() {
service = new AACService(env.getProperty("ext.aacURL"), env.getProperty("ext.clientId"), env.getProperty("ext.clientSecret"));
profileService = new BasicProfileService(env.getProperty("ext.aacURL"));
}
private final static Logger logger = LoggerFactory.getLogger(GericoConnector.class);
@SuppressWarnings("unchecked")
@Scheduled(initialDelay=10000, fixedRate=7200000)
public void getIssues() throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
logger.debug("Scheduled Gerico");
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(new URL("https://www2.comune.rovereto.tn.it/gerico/extra/opendata_richieste/"), Map.class);
List<Map<String, Object>> data = (List<Map<String, Object>>)map.get("data");
for (Map<String, Object> entry: data) {
String attivatore = (String)entry.get(F_ATTIVATORE);
if (APP_NAME.equals(attivatore) || APP_ID.equals(attivatore)) {
processEntry(entry);
} else if ("1".equals(entry.get(F_PUBBLICO))) {
processExternalEntry(entry);
}
}
}
@SuppressWarnings("unchecked")
public void getIssues(String year, String fromMonth, String toMonth) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(new URL("https://www2.comune.rovereto.tn.it/gerico/extra/opendata_richieste/0/" + year + "/" + fromMonth + "/" + toMonth), Map.class);
List<Map<String, Object>> data = (List<Map<String, Object>>)map.get("data");
for (Map<String, Object> entry: data) {
String attivatore = (String)entry.get(F_ATTIVATORE);
if (APP_NAME.equals(attivatore) || APP_ID.equals(attivatore)) {
processEntry(entry);
} else if ("1".equals(entry.get(F_PUBBLICO))) {
processExternalEntry(entry);
}
}
}
/**
* @param entry
*/
private void processExternalEntry(Map<String, Object> entry) {
String externalId = (String)entry.get(F_EXTERNAL_ID);
if (!StringUtils.hasText(externalId)) {
externalId = (String)entry.get(F_ID);
}
ServiceIssue issue = issueRepository.findByExternalId(externalId);
String status = (String)entry.get(F_STATO);
if ("A".equals(status)) {
status = Constants.STATUS_OPEN;
} else if ("C".equals(status)) {
status = Constants.STATUS_CLOSED;
}
// System.out.println(entry);
// System.out.println("_____________________________");
if (issue != null) {
logger.info("Updating " + issue.getExternalId());
} else {
logger.info("Creating " + externalId);
issue = new ServiceIssue();
issue.setProviderId("ComuneRovereto");
issue.setServiceId("problems");
issue.setExternalId(externalId);
issue.setCreated(System.currentTimeMillis());
}
issue.setAttribute(new HashMap<String, Object>());
issue.getAttribute().put("title", entry.get(F_OGGETTO));
issue.getAttribute().put("description", entry.get(F_NOTE));
issue.getAttribute().put("activator", entry.get(F_ATTIVATORE));
issue.setLocation(new Location());
issue.getLocation().setAddress((String) entry.get(F_STRADA));
issue.setIssuer(new Issuer());
try {
issue.getLocation().setCoordinates(new double[]{
Double.parseDouble((String)entry.get(F_LATITUDINE)),
Double.parseDouble((String)entry.get(F_LONGITUDINE))
});
} catch (Exception e) {
return;
}
issue.setStatus(status);
issue.setStatusNotes((String)entry.get(F_NOTE_EXTERNAL));
issue.setNotes((String)entry.get(F_NOTE_EXTERNAL));
issueRepository.save(issue);
}
private void processEntry(Map<String, Object> entry) {
String externalId = (String)entry.get(F_EXTERNAL_ID);
ServiceIssue issue = issueRepository.findByExternalId(externalId);
// System.out.println(entry);
// System.out.println("_____________________________");
if (issue != null) {
logger.info("Updating " + issue.getExternalId());
String status = (String)entry.get(F_STATO);
if ("A".equals(status)) {
status = Constants.STATUS_OPEN;
} else if ("C".equals(status)) {
status = Constants.STATUS_CLOSED;
}
issue.setStatus(status);
issue.setStatusNotes((String)entry.get(F_NOTE_EXTERNAL));
issue.setNotes((String)entry.get(F_NOTE_EXTERNAL));
issueRepository.save(issue);
}
}
/**
*
* @param issue
* @return
*/
public boolean sendIssue(ServiceIssue issue) {
boolean ok = true;
try {
Map<String, Object> data = new HashMap<String, Object>();
// String id = "" + manager.increaseCounter();
// data.put("external_id", id);
String id = new ObjectId().toString();
data.put(F_EXTERNAL_ID_NEW, id);
data.put(F_ATTIVATORE, APP_ID);
data.put(F_MEZZO, APP_ID);
data.put(F_ORIGINE, "cit");
// data.put("operatore_inserimento", "loris");
data.put(F_ORIGINE_DETTAGLIO, issue.getIssuer().fullName());
String email = getUserEmail(issue.getIssuer().getUserId());
data.put(F_EMAIL, email);
String oggetto = "";
if (issue.getAttribute() != null && issue.getAttribute().containsKey("title")) {
oggetto = (String) issue.getAttribute().get("title");
}
data.put(F_OGGETTO, oggetto);
String note = "";
if (issue.getAttribute() != null && issue.getAttribute().containsKey("description") &&
issue.getAttribute().get("description") != null) {
note += (String) issue.getAttribute().get("description") + "\n";
}
if (issue.getMedia() != null) {
for (String media : issue.getMedia()) {
note += media + "\n";
}
}
note = URLEncoder.encode(note.trim(), "utf-8");
data.put(F_NOTE, note);
data.put(F_STATO, "A");
if (issue.getLocation() != null) {
if (issue.getLocation().getAddress() != null) {
data.put(F_STRADA, issue.getLocation().getAddress());
}
if (issue.getLocation().getCoordinates() != null) {
data.put(F_LATITUDINE, "" + issue.getLocation().getCoordinates()[0]);
data.put(F_LONGITUDINE, "" + issue.getLocation().getCoordinates()[1]);
}
//
}
data.put(F_MAC, generateMac("286b5d03a4b2fa092f091c2b982cb028090e2936", id));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false);
String body =mapper.writeValueAsString(data);
logger.info("Sending user signal: "+body);
body = URLEncoder.encode(body, "utf-8");
logger.info("Sending user signal (URL encoded): "+body);
logger.info("Using email: "+ email);
String result = RemoteConnector.getJSON("https://www2.comune.rovereto.tn.it/", "gerico/ws_crea_richiesta/" + body, null);
try {
issue.setExternalId(id);
issueRepository.save(issue);
} catch (Exception e) {
logger.error("ws_crea_richiesta returned: " + result);
e.printStackTrace();
ok = false;
}
} catch (Exception e) {
e.printStackTrace();
ok = false;
}
return ok;
}
private Object generateMac(String key, String id) throws UnsupportedEncodingException, NoSuchAlgorithmException {
return DigestUtils.shaHex((id+key).getBytes("utf8"));
}
private String getUserEmail(String userId) {
try {
TokenData token = service.generateClientToken();
List<AccountProfile> profiles = profileService.getAccountProfilesByUserId(Collections.singletonList(userId), token.getAccess_token());
if (profiles == null || profiles.size() == 0) return null;
String email = profiles.get(0).getAttribute("google", "OIDC_CLAIM_email");
return email;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| cityreport-web/src/main/java/it/smartcommunitylab/cityreport/utils/GericoConnector.java | package it.smartcommunitylab.cityreport.utils;
import it.smartcommunitylab.cityreport.data.IssueRepository;
import it.smartcommunitylab.cityreport.model.Issuer;
import it.smartcommunitylab.cityreport.model.Location;
import it.smartcommunitylab.cityreport.model.ServiceIssue;
import it.smartcommunitylab.cityreport.services.IssueManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.codec.digest.DigestUtils;
import org.bson.types.ObjectId;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import eu.trentorise.smartcampus.aac.AACService;
import eu.trentorise.smartcampus.aac.model.TokenData;
import eu.trentorise.smartcampus.network.RemoteConnector;
import eu.trentorise.smartcampus.profileservice.BasicProfileService;
import eu.trentorise.smartcampus.profileservice.model.AccountProfile;
@Component
public class GericoConnector {
private static final String F_EXTERNAL_ID_NEW = "external_id_new";
private static final String F_EXTERNAL_ID = "external_id";
private static final String F_NOTE_EXTERNAL = "note_external";
private static final String F_MAC = "mac";
private static final String F_STRADA = "strada";
private static final String F_LONGITUDINE = "longitudine";
private static final String F_LATITUDINE = "latitudine";
private static final String F_STATO = "stato";
private static final String F_NOTE = "note";
private static final String F_OGGETTO = "oggetto";
private static final String F_EMAIL = "email";
private static final String F_ORIGINE_DETTAGLIO = "origine_dettaglio";
private static final String F_ORIGINE = "origine";
private static final String F_MEZZO = "mezzo";
private static final String F_PUBBLICO = "pubblico";
private static final String F_ATTIVATORE = "attivatore";
private static final Object F_ID = "id";
private static final String APP_NAME = "App segnala";
private static final String APP_ID = "app_s";
@Autowired
private IssueRepository issueRepository;
@Autowired
private IssueManager manager;
@Autowired
private Environment env;
private AACService service;
private BasicProfileService profileService;
@PostConstruct
private void init() {
service = new AACService(env.getProperty("ext.aacURL"), env.getProperty("ext.clientId"), env.getProperty("ext.clientSecret"));
profileService = new BasicProfileService(env.getProperty("ext.aacURL"));
}
private final static Logger logger = LoggerFactory.getLogger(GericoConnector.class);
@SuppressWarnings("unchecked")
@Scheduled(initialDelay=10000, fixedRate=7200000)
public void getIssues() throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
logger.debug("Scheduled Gerico");
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(new URL("https://www2.comune.rovereto.tn.it/gerico/extra/opendata_richieste/"), Map.class);
List<Map<String, Object>> data = (List<Map<String, Object>>)map.get("data");
for (Map<String, Object> entry: data) {
String attivatore = (String)entry.get(F_ATTIVATORE);
if (APP_NAME.equals(attivatore) || APP_ID.equals(attivatore)) {
processEntry(entry);
} else if ("1".equals(entry.get(F_PUBBLICO))) {
processExternalEntry(entry);
}
}
}
@SuppressWarnings("unchecked")
public void getIssues(String year, String fromMonth, String toMonth) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(new URL("https://www2.comune.rovereto.tn.it/gerico/extra/opendata_richieste/0/" + year + "/" + fromMonth + "/" + toMonth), Map.class);
List<Map<String, Object>> data = (List<Map<String, Object>>)map.get("data");
for (Map<String, Object> entry: data) {
String attivatore = (String)entry.get(F_ATTIVATORE);
if (APP_NAME.equals(attivatore) || APP_ID.equals(attivatore)) {
processEntry(entry);
} else if ("1".equals(entry.get(F_PUBBLICO))) {
processExternalEntry(entry);
}
}
}
/**
* @param entry
*/
private void processExternalEntry(Map<String, Object> entry) {
String externalId = (String)entry.get(F_EXTERNAL_ID);
if (!StringUtils.hasText(externalId)) {
externalId = (String)entry.get(F_ID);
}
ServiceIssue issue = issueRepository.findByExternalId(externalId);
String status = (String)entry.get(F_STATO);
if ("A".equals(status)) {
status = Constants.STATUS_OPEN;
} else if ("C".equals(status)) {
status = Constants.STATUS_CLOSED;
}
// System.out.println(entry);
// System.out.println("_____________________________");
if (issue != null) {
logger.info("Updating " + issue.getExternalId());
} else {
logger.info("Creating " + externalId);
issue = new ServiceIssue();
issue.setProviderId("ComuneRovereto");
issue.setServiceId("problems");
issue.setExternalId(externalId);
issue.setCreated(System.currentTimeMillis());
}
issue.setAttribute(new HashMap<String, Object>());
issue.getAttribute().put("title", entry.get(F_OGGETTO));
issue.getAttribute().put("description", entry.get(F_NOTE));
issue.getAttribute().put("activator", entry.get(F_ATTIVATORE));
issue.setLocation(new Location());
issue.getLocation().setAddress((String) entry.get(F_STRADA));
issue.setIssuer(new Issuer());
try {
issue.getLocation().setCoordinates(new double[]{
Double.parseDouble((String)entry.get(F_LATITUDINE)),
Double.parseDouble((String)entry.get(F_LONGITUDINE))
});
} catch (Exception e) {
return;
}
issue.setStatus(status);
issue.setStatusNotes((String)entry.get(F_NOTE_EXTERNAL));
issue.setNotes((String)entry.get(F_NOTE_EXTERNAL));
issueRepository.save(issue);
}
private void processEntry(Map<String, Object> entry) {
String externalId = (String)entry.get(F_EXTERNAL_ID);
ServiceIssue issue = issueRepository.findByExternalId(externalId);
// System.out.println(entry);
// System.out.println("_____________________________");
if (issue != null) {
logger.info("Updating " + issue.getExternalId());
String status = (String)entry.get(F_STATO);
if ("A".equals(status)) {
status = Constants.STATUS_OPEN;
} else if ("C".equals(status)) {
status = Constants.STATUS_CLOSED;
}
issue.setStatus(status);
issue.setStatusNotes((String)entry.get(F_NOTE_EXTERNAL));
issue.setNotes((String)entry.get(F_NOTE_EXTERNAL));
issueRepository.save(issue);
}
}
/**
*
* @param issue
* @return
*/
public boolean sendIssue(ServiceIssue issue) {
boolean ok = true;
try {
Map<String, Object> data = new HashMap<String, Object>();
// String id = "" + manager.increaseCounter();
// data.put("external_id", id);
String id = new ObjectId().toString();
data.put(F_EXTERNAL_ID_NEW, id);
data.put(F_ATTIVATORE, APP_ID);
data.put(F_MEZZO, APP_ID);
data.put(F_ORIGINE, "cit");
// data.put("operatore_inserimento", "loris");
data.put(F_ORIGINE_DETTAGLIO, issue.getIssuer().fullName());
String email = getUserEmail(issue.getIssuer().getUserId());
data.put(F_EMAIL, email);
String oggetto = "";
if (issue.getAttribute() != null && issue.getAttribute().containsKey("title")) {
oggetto = (String) issue.getAttribute().get("title");
}
data.put(F_OGGETTO, oggetto);
String note = "";
if (issue.getAttribute() != null && issue.getAttribute().containsKey("description")) {
note += (String) issue.getAttribute().get("description") + "\n";
}
if (issue.getMedia() != null) {
for (String media : issue.getMedia()) {
note += media + "\n";
}
}
note = URLEncoder.encode(note, "utf-8");
data.put(F_NOTE, note);
data.put(F_STATO, "A");
if (issue.getLocation() != null) {
if (issue.getLocation().getAddress() != null) {
data.put(F_STRADA, issue.getLocation().getAddress());
}
if (issue.getLocation().getCoordinates() != null) {
data.put(F_LATITUDINE, "" + issue.getLocation().getCoordinates()[0]);
data.put(F_LONGITUDINE, "" + issue.getLocation().getCoordinates()[1]);
}
//
}
data.put(F_MAC, generateMac("286b5d03a4b2fa092f091c2b982cb028090e2936", id));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.WRITE_NULL_MAP_VALUES, false);
String body =mapper.writeValueAsString(data);
logger.info("Sending user signal: "+body);
body = URLEncoder.encode(body, "utf-8");
logger.info("Sending user signal (URL encoded): "+body);
logger.info("Using email: "+ email);
String result = RemoteConnector.getJSON("https://www2.comune.rovereto.tn.it/", "gerico/ws_crea_richiesta/" + body, null);
try {
issue.setExternalId(id);
issueRepository.save(issue);
} catch (Exception e) {
logger.error("ws_crea_richiesta returned: " + result);
e.printStackTrace();
ok = false;
}
} catch (Exception e) {
e.printStackTrace();
ok = false;
}
return ok;
}
private Object generateMac(String key, String id) throws UnsupportedEncodingException, NoSuchAlgorithmException {
return DigestUtils.shaHex((id+key).getBytes("utf8"));
}
private String getUserEmail(String userId) {
try {
TokenData token = service.generateClientToken();
List<AccountProfile> profiles = profileService.getAccountProfilesByUserId(Collections.singletonList(userId), token.getAccess_token());
if (profiles == null || profiles.size() == 0) return null;
String email = profiles.get(0).getAttribute("google", "OIDC_CLAIM_email");
return email;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| fix for data format | cityreport-web/src/main/java/it/smartcommunitylab/cityreport/utils/GericoConnector.java | fix for data format | <ide><path>ityreport-web/src/main/java/it/smartcommunitylab/cityreport/utils/GericoConnector.java
<ide> data.put(F_OGGETTO, oggetto);
<ide>
<ide> String note = "";
<del> if (issue.getAttribute() != null && issue.getAttribute().containsKey("description")) {
<add> if (issue.getAttribute() != null && issue.getAttribute().containsKey("description") &&
<add> issue.getAttribute().get("description") != null) {
<ide> note += (String) issue.getAttribute().get("description") + "\n";
<ide> }
<ide> if (issue.getMedia() != null) {
<ide> note += media + "\n";
<ide> }
<ide> }
<del> note = URLEncoder.encode(note, "utf-8");
<add> note = URLEncoder.encode(note.trim(), "utf-8");
<ide> data.put(F_NOTE, note);
<ide> data.put(F_STATO, "A");
<ide> |
|
Java | mit | 600917e2e79ba1b86013431f3d6055cdc3bc1745 | 0 | raviflipsyde/zab_java | package servers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.Queue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import serverHandlers.TimeClientHandler;
import util.TcpClient1;
public class NodeServer implements Runnable{
private static final Logger LOG = LogManager.getLogger(NodeServer.class);
private String bootstrapHost;
private int bootstrapPort;
private int nodePort;
private List<InetSocketAddress> memberList;
private List<TimeClient> channelList;
EventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap b;
private String myIP;
private NodeServerProperties properties;
public static ConcurrentLinkedQueue<Notification> electionQueue123 = new ConcurrentLinkedQueue<Notification>();
//private long electionRound;
public NodeServer(String bhost, int bport, int nport){
this.bootstrapHost = bhost;
this.bootstrapPort = bport;
this.nodePort = nport;
this.properties = new NodeServerProperties();
this.memberList = new CopyOnWriteArrayList<InetSocketAddress>();
final NodeServer this1 = this;
myIP = getMyIP();
if(bhost.equals("localhost"))
myIP = "localhost";
workerGroup = new NioEventLoopGroup();
b = new Bootstrap();
channelList = new ArrayList<TimeClient>();
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler(this1));
}
});
}
public String getMemberListString(){
StringBuilder strb = new StringBuilder();
for(InetSocketAddress addr: memberList){
strb.append(addr.toString()+ ", ");
}
return strb.toString();
}
public synchronized void addMemberToList(InetSocketAddress member) {
this.memberList.add(member);
}
public synchronized void removeMemberFromList(InetSocketAddress member) {
this.memberList.add(member);
}
public List<InetSocketAddress> getMemberList() {
return memberList;
}
public void setMemberList(List<InetSocketAddress> memberList) {
this.memberList = memberList;
}
public NodeServerProperties getProperties() {
return properties;
}
public void run() {
System.out.println("Start Node Server");
// send the address to bootstrap, get the member list, get the nodeID
msgBootstrap();
LOG.info("ID for this node is :"+ properties.getId());
//Start the NettyServer at the nodeport
Thread serverThread = new Thread(new NettyServer(nodePort, this));
serverThread.start();
informGroupMembers();
// writeHistory();
readHistory();
changePhase();
}
private void informGroupMembers() {
List<InetSocketAddress> unreachablelist = new ArrayList<InetSocketAddress>();
for(InetSocketAddress member: memberList){
String ret;
try {
ret = new TcpClient1(member.getHostName(), member.getPort()).sendMsg("JOIN_GROUP:"+myIP+":"+nodePort);
LOG.info("tcp client recieved "+ ret);
} catch (IOException e) {
unreachablelist.add(member);
e.printStackTrace();
}
}
for(InetSocketAddress member: unreachablelist){
this.removeMemberFromList(member);
}
}
private void changePhase() {
/*
The logic of changing phases
*/
long leaderID = properties.getId();
if( properties.getNodestate().equals(NodeServerProperties.State.ELECTION)){
LOG.info("Begin Leader Election---------");
Vote leaderVote = startLeaderElection();
LOG.info("End Leader Election---------");
LOG.info("Leader ID:"+leaderVote.getId() );
if(leaderVote.getId() == properties.getId()){
properties.setLeader(true);
properties.setNodestate(NodeServerProperties.State.LEADING);
leaderID = properties.getId();
}
else{
properties.setLeader(true);
properties.setNodestate(NodeServerProperties.State.FOLLOWING);
leaderID = leaderVote.getId();
}
}
//startRecovery();
//startBroadcast();
}
private Vote startLeaderElection() {
// TODO same thread or different thread?
memberList = this.getMemberList();
this.properties.setElectionRound(this.properties.getElectionRound()+1);
HashMap<Long, Vote> receivedVote = new HashMap<Long, Vote>();
HashMap<Long, Long> receivedVotesRound = new HashMap<Long, Long>();
HashMap<Long, Vote> OutOfElectionVotes = new HashMap<Long, Vote>();
HashMap<Long, Long> OutOfElectionVotesRound = new HashMap<Long, Long>();
long limit_timeout = 10000;
long timeout = 1000;
//Queue<Notification> currentElectionQueue = new ConcurrentLinkedQueue<Notification>();
// this.getProperties().setElectionQueue(currentElectionQueue);
ConcurrentLinkedQueue<Notification> currentElectionQueue = electionQueue123;
Vote myVote123 = new Vote(this.properties.getLastZxId(), this.properties.getCurrentEpoch(), this.properties.getId());
this.properties.setMyVote(myVote123);
Notification myNotification = new Notification(this.properties.getMyVote(), this.properties.getElectionRound(), this.properties.getId(), this.properties.getNodestate());
LOG.info("My Notification is:"+myNotification.toString());
sendNotification(memberList, myNotification, currentElectionQueue);
Notification currentN = null;
while( properties.getNodestate() == NodeServerProperties.State.ELECTION && timeout<limit_timeout ){
LOG.info("ElectionQueue:"+ this.getProperties().getElectionQueue());
System.out.println(currentElectionQueue.toString());
currentN = currentElectionQueue.poll();
if(currentN==null){
LOG.info("Queue is empty!!");
try {
synchronized (currentElectionQueue) {
currentElectionQueue.wait(timeout);
}
currentN = currentElectionQueue.poll();
if(currentN==null){
LOG.info("Queue is empty again!!");
timeout = 2*timeout;
LOG.info("increasing timeout");
sendNotification(memberList, myNotification, currentElectionQueue);
continue;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//CurrentN is not null
else if ( currentN.getSenderState() == NodeServerProperties.State.ELECTION ){
LOG.info("Received notification is in Election");
if(currentN.getSenderRound() < this.properties.getElectionRound()){
LOG.info("Disregard vote as round number is smaller than mine");
continue;
}else{
if(currentN.getSenderRound() > this.properties.getElectionRound()){
LOG.info("The round number is larger than mine");
this.properties.setElectionRound(currentN.getSenderRound());
receivedVote = new HashMap<Long, Vote>();
receivedVotesRound = new HashMap<Long, Long>();
}
if(currentN.getVote().compareTo(this.properties.getMyVote()) > 0 ){ // if the currentN is bigger thn myvote
LOG.info("His vote bigger than mine");
this.properties.setMyVote(currentN.getVote()); // update myvote
myNotification.setVote(this.properties.getMyVote()); // update notification
}
sendNotification(memberList, myNotification, currentElectionQueue);
// update the receivedVote datastructure
receivedVote.put(currentN.getSenderId(), currentN.getVote());
receivedVotesRound.put(currentN.getSenderId(), currentN.getSenderRound());
//TODO shoul i put my vote in the receivedVote
receivedVote.put(this.properties.getId(), this.properties.getMyVote());
receivedVotesRound.put(this.properties.getId(), this.properties.getElectionRound());
if(receivedVote.size() == (memberList.size()+1)){
//TODO check for quorum in the receivedvotes and then declare leader
LOG.info("received votes from all the members");
break;
}
else {
LOG.info("checking for quorum in received votes");
int myVoteCounter = 0;
for( Entry<Long, Vote> v:receivedVote.entrySet()){
Vote currVote = v.getValue();
if(currVote.equals(this.properties.getMyVote())){
myVoteCounter++;
}
}
if(myVoteCounter> (memberList.size()+1)/2 ){
LOG.info("Found quorum in received votes");
try {
// properties.getElectionQueue().wait(timeout);
Thread.sleep(timeout);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(properties.getElectionQueue().size() > 0) {
LOG.info("Still have notifications in ElectionQueue");
continue; }
else {
LOG.info("No notifications in ElectionQueue");
break;
}
}
else{
continue;
}
}
}
} //end of if election
// the received vote is either leading or following
else{
if(currentN.getSenderRound() == this.properties.getElectionRound()){
LOG.info("notification is not in election, round number are same");
receivedVote.put(currentN.getSenderId(), currentN.getVote());
receivedVotesRound.put(currentN.getSenderId(), currentN.getSenderRound());
//TODO shoul i put my vote in the receivedVote
// receivedVote.put(this.properties.getId(), myVote);
// receivedVotesRound.put(this.properties.getId(), this.electionRound);
if(currentN.getSenderState() == NodeServerProperties.State.LEADING){
LOG.info("notification is not in Leading state");
this.properties.setMyVote( currentN.getVote());
break;
}
else{
LOG.info("notification is not in Followinf state");
int myVoteCounter = 0;
for( Entry<Long, Vote> v:receivedVote.entrySet()){
Vote currVote = v.getValue();
if(currVote.equals(this.properties.getMyVote())){
myVoteCounter++;
}
}
// if the currentN's vote is to me and i achieve quorum in receivedVote then i be the leader
if(currentN.getVote().getId()==this.properties.getMyVote().getId() && myVoteCounter> (memberList.size()+1)/2 ){
this.properties.setMyVote(currentN.getVote());
break;
}
else if(myVoteCounter> (memberList.size()+1)/2 ){ //our improvement
this.properties.setMyVote(currentN.getVote());
break;
}
//wrong condition
// else if(myVoteCounter> (memberList.size()+1)/2
// && OutOfElectionVotes.containsKey(currentN.getVote().getId())){
// //TODO this is not 100% sure
// myVote = currentN.getVote();
// break;
// }
}
}
OutOfElectionVotes.put(currentN.getSenderId(), currentN.getVote());
OutOfElectionVotesRound.put(currentN.getSenderId(), currentN.getSenderRound());
int myVoteCounter = 0;
for( Entry<Long, Vote> v:OutOfElectionVotes.entrySet()){
Vote currVote = v.getValue();
if(currVote.equals(this.properties.getMyVote())){
myVoteCounter++;
}
}
if(currentN.getVote().getId()==this.properties.getMyVote().getId() && myVoteCounter> (memberList.size()+1)/2 ){
this.properties.setElectionRound(currentN.getSenderRound());
this.properties.setMyVote(currentN.getVote());
break;
}
else if(myVoteCounter> (memberList.size()+1)/2 ){ //our improvement just chekc for the quorum
this.properties.setMyVote(currentN.getVote());
break;
}
//wrong condition
// else if(myVoteCounter> (memberList.size()+1)/2 && OutOfElectionVotes.containsKey(currentN.getVote().getId())){
// this.electionRound = currentN.getSenderRound();
//
// }
} //end of else
}// end of while
// Here the leader is the one pointed by my vote
return this.properties.getMyVote();
}
private void sendNotification(List<InetSocketAddress> memberList2, Notification myNotification, ConcurrentLinkedQueue<Notification> currentElectionQueue) {
if(memberList2.isEmpty()) return;
for(InetSocketAddress member: memberList2){
SendNotificationThread nt0 = new SendNotificationThread(member, myNotification);
nt0.setElectionQueue1(currentElectionQueue);
Thread t = new Thread(nt0);
t.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Util functions
public long msgBootstrap(){
Socket socket;
long id = 0;
try {
socket = new Socket (bootstrapHost, bootstrapPort);
PrintWriter out = new PrintWriter (socket.getOutputStream(), true);
BufferedReader in = new BufferedReader (new InputStreamReader(socket.getInputStream ()));
//set self_ip:port to bootsstrap
out.println ("set "+ myIP + ":"+nodePort);
String memberList = in.readLine ();
String memberId = in.readLine();
id = Long.parseLong(memberId);
LOG.info("MemberID received:"+ id);
//process memberlist
this.properties.setId(id);
parseMemberList(memberList);
out.close ();
in.close();
socket.close ();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return id;
}
private void parseMemberList(String memberList) {
String[] list = memberList.split(",");
System.out.println("Members");
for(String s:list){
String[] address = s.split(":");
String ip = address[0];
int port = Integer.parseInt(address[1]);
if(myIP.equals(ip) && nodePort== port){}
else{
InetSocketAddress addr = new InetSocketAddress(address[0], Integer.parseInt(address[1]));
this.memberList.add(addr);
}
}
}
public String getMyIP(){
BufferedReader in = null;
String ip = " ";
try {
URL whatismyip = new URL("http://ipv4bot.whatismyipaddress.com/");
in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
ip = in.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ip;
}
private void writeHistory() {
String fileName = "CommitedHistory_"+this.nodePort+".txt";
File fout = new File(fileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for(Message m: this.properties.getMessageList()){
bw.write(m.toString());
bw.newLine();
}
bw.flush();
bw.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void readHistory() {
String fileName = "CommitedHistory_"+this.nodePort+".txt";
String line = null;
List<Message> msgList = this.properties.getMessageList();
try {
FileReader fileReader = new FileReader(fileName );
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
Message m = new Message(line);
msgList.add(m);
System.out.println(m);
}
bufferedReader.close();
fileReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Message lastMsg = msgList.get(msgList.size()-1);
this.properties.setCurrentEpoch(lastMsg.getEpoch());
this.properties.setLastZxId(lastMsg.getTxId());
}
}
| src/main/java/servers/NodeServer.java | package servers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.Queue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import serverHandlers.TimeClientHandler;
import util.TcpClient1;
public class NodeServer implements Runnable{
private static final Logger LOG = LogManager.getLogger(NodeServer.class);
private String bootstrapHost;
private int bootstrapPort;
private int nodePort;
private List<InetSocketAddress> memberList;
private List<TimeClient> channelList;
EventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap b;
private String myIP;
private NodeServerProperties properties;
public static ConcurrentLinkedQueue<Notification> electionQueue123 = new ConcurrentLinkedQueue<Notification>();
//private long electionRound;
public NodeServer(String bhost, int bport, int nport){
this.bootstrapHost = bhost;
this.bootstrapPort = bport;
this.nodePort = nport;
this.properties = new NodeServerProperties();
this.memberList = new ArrayList<InetSocketAddress>();
final NodeServer this1 = this;
myIP = getMyIP();
if(bhost.equals("localhost"))
myIP = "localhost";
workerGroup = new NioEventLoopGroup();
b = new Bootstrap();
channelList = new ArrayList<TimeClient>();
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler(this1));
}
});
}
public String getMemberListString(){
StringBuilder strb = new StringBuilder();
for(InetSocketAddress addr: memberList){
strb.append(addr.toString()+ ", ");
}
return strb.toString();
}
public synchronized void addMemberToList(InetSocketAddress member) {
this.memberList.add(member);
}
public synchronized void removeMemberFromList(InetSocketAddress member) {
this.memberList.add(member);
}
public List<InetSocketAddress> getMemberList() {
return memberList;
}
public void setMemberList(List<InetSocketAddress> memberList) {
this.memberList = memberList;
}
public NodeServerProperties getProperties() {
return properties;
}
public void run() {
System.out.println("Start Node Server");
// send the address to bootstrap, get the member list, get the nodeID
msgBootstrap();
LOG.info("ID for this node is :"+ properties.getId());
//Start the NettyServer at the nodeport
Thread serverThread = new Thread(new NettyServer(nodePort, this));
serverThread.start();
informGroupMembers();
// writeHistory();
readHistory();
changePhase();
}
private void informGroupMembers() {
List<InetSocketAddress> unreachablelist = new ArrayList<InetSocketAddress>();
for(InetSocketAddress member: memberList){
String ret;
try {
ret = new TcpClient1(member.getHostName(), member.getPort()).sendMsg("JOIN_GROUP:"+myIP+":"+nodePort);
LOG.info("tcp client recieved "+ ret);
} catch (IOException e) {
unreachablelist.add(member);
e.printStackTrace();
}
}
for(InetSocketAddress member: unreachablelist){
this.removeMemberFromList(member);
}
}
private void changePhase() {
/*
The logic of changing phases
*/
long leaderID = properties.getId();
if( properties.getNodestate().equals(NodeServerProperties.State.ELECTION)){
LOG.info("Begin Leader Election---------");
Vote leaderVote = startLeaderElection();
LOG.info("End Leader Election---------");
LOG.info("Leader ID:"+leaderVote.getId() );
if(leaderVote.getId() == properties.getId()){
properties.setLeader(true);
properties.setNodestate(NodeServerProperties.State.LEADING);
leaderID = properties.getId();
}
else{
properties.setLeader(true);
properties.setNodestate(NodeServerProperties.State.FOLLOWING);
leaderID = leaderVote.getId();
}
}
//startRecovery();
//startBroadcast();
}
private Vote startLeaderElection() {
// TODO same thread or different thread?
memberList = this.getMemberList();
this.properties.setElectionRound(this.properties.getElectionRound()+1);
HashMap<Long, Vote> receivedVote = new HashMap<Long, Vote>();
HashMap<Long, Long> receivedVotesRound = new HashMap<Long, Long>();
HashMap<Long, Vote> OutOfElectionVotes = new HashMap<Long, Vote>();
HashMap<Long, Long> OutOfElectionVotesRound = new HashMap<Long, Long>();
long limit_timeout = 10000;
long timeout = 1000;
//Queue<Notification> currentElectionQueue = new ConcurrentLinkedQueue<Notification>();
// this.getProperties().setElectionQueue(currentElectionQueue);
ConcurrentLinkedQueue<Notification> currentElectionQueue = electionQueue123;
Vote myVote123 = new Vote(this.properties.getLastZxId(), this.properties.getCurrentEpoch(), this.properties.getId());
this.properties.setMyVote(myVote123);
Notification myNotification = new Notification(this.properties.getMyVote(), this.properties.getElectionRound(), this.properties.getId(), this.properties.getNodestate());
LOG.info("My Notification is:"+myNotification.toString());
sendNotification(memberList, myNotification, currentElectionQueue);
Notification currentN = null;
while( properties.getNodestate() == NodeServerProperties.State.ELECTION && timeout<limit_timeout ){
LOG.info("ElectionQueue:"+ this.getProperties().getElectionQueue());
System.out.println(currentElectionQueue.toString());
currentN = currentElectionQueue.poll();
if(currentN==null){
LOG.info("Queue is empty!!");
try {
synchronized (currentElectionQueue) {
currentElectionQueue.wait(timeout);
}
currentN = currentElectionQueue.poll();
if(currentN==null){
LOG.info("Queue is empty again!!");
timeout = 2*timeout;
LOG.info("increasing timeout");
sendNotification(memberList, myNotification, currentElectionQueue);
continue;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//CurrentN is not null
else if ( currentN.getSenderState() == NodeServerProperties.State.ELECTION ){
LOG.info("Received notification is in Election");
if(currentN.getSenderRound() < this.properties.getElectionRound()){
LOG.info("Disregard vote as round number is smaller than mine");
continue;
}else{
if(currentN.getSenderRound() > this.properties.getElectionRound()){
LOG.info("The round number is larger than mine");
this.properties.setElectionRound(currentN.getSenderRound());
receivedVote = new HashMap<Long, Vote>();
receivedVotesRound = new HashMap<Long, Long>();
}
if(currentN.getVote().compareTo(this.properties.getMyVote()) > 0 ){ // if the currentN is bigger thn myvote
LOG.info("His vote bigger than mine");
this.properties.setMyVote(currentN.getVote()); // update myvote
myNotification.setVote(this.properties.getMyVote()); // update notification
}
sendNotification(memberList, myNotification, currentElectionQueue);
// update the receivedVote datastructure
receivedVote.put(currentN.getSenderId(), currentN.getVote());
receivedVotesRound.put(currentN.getSenderId(), currentN.getSenderRound());
//TODO shoul i put my vote in the receivedVote
receivedVote.put(this.properties.getId(), this.properties.getMyVote());
receivedVotesRound.put(this.properties.getId(), this.properties.getElectionRound());
if(receivedVote.size() == (memberList.size()+1)){
//TODO check for quorum in the receivedvotes and then declare leader
LOG.info("received votes from all the members");
break;
}
else {
LOG.info("checking for quorum in received votes");
int myVoteCounter = 0;
for( Entry<Long, Vote> v:receivedVote.entrySet()){
Vote currVote = v.getValue();
if(currVote.equals(this.properties.getMyVote())){
myVoteCounter++;
}
}
if(myVoteCounter> (memberList.size()+1)/2 ){
LOG.info("Found quorum in received votes");
try {
// properties.getElectionQueue().wait(timeout);
Thread.sleep(timeout);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(properties.getElectionQueue().size() > 0) {
LOG.info("Still have notifications in ElectionQueue");
continue; }
else {
LOG.info("No notifications in ElectionQueue");
break;
}
}
else{
continue;
}
}
}
} //end of if election
// the received vote is either leading or following
else{
if(currentN.getSenderRound() == this.properties.getElectionRound()){
LOG.info("notification is not in election, round number are same");
receivedVote.put(currentN.getSenderId(), currentN.getVote());
receivedVotesRound.put(currentN.getSenderId(), currentN.getSenderRound());
//TODO shoul i put my vote in the receivedVote
// receivedVote.put(this.properties.getId(), myVote);
// receivedVotesRound.put(this.properties.getId(), this.electionRound);
if(currentN.getSenderState() == NodeServerProperties.State.LEADING){
LOG.info("notification is not in Leading state");
this.properties.setMyVote( currentN.getVote());
break;
}
else{
LOG.info("notification is not in Followinf state");
int myVoteCounter = 0;
for( Entry<Long, Vote> v:receivedVote.entrySet()){
Vote currVote = v.getValue();
if(currVote.equals(this.properties.getMyVote())){
myVoteCounter++;
}
}
// if the currentN's vote is to me and i achieve quorum in receivedVote then i be the leader
if(currentN.getVote().getId()==this.properties.getMyVote().getId() && myVoteCounter> (memberList.size()+1)/2 ){
this.properties.setMyVote(currentN.getVote());
break;
}
else if(myVoteCounter> (memberList.size()+1)/2 ){ //our improvement
this.properties.setMyVote(currentN.getVote());
break;
}
//wrong condition
// else if(myVoteCounter> (memberList.size()+1)/2
// && OutOfElectionVotes.containsKey(currentN.getVote().getId())){
// //TODO this is not 100% sure
// myVote = currentN.getVote();
// break;
// }
}
}
OutOfElectionVotes.put(currentN.getSenderId(), currentN.getVote());
OutOfElectionVotesRound.put(currentN.getSenderId(), currentN.getSenderRound());
int myVoteCounter = 0;
for( Entry<Long, Vote> v:OutOfElectionVotes.entrySet()){
Vote currVote = v.getValue();
if(currVote.equals(this.properties.getMyVote())){
myVoteCounter++;
}
}
if(currentN.getVote().getId()==this.properties.getMyVote().getId() && myVoteCounter> (memberList.size()+1)/2 ){
this.properties.setElectionRound(currentN.getSenderRound());
this.properties.setMyVote(currentN.getVote());
break;
}
else if(myVoteCounter> (memberList.size()+1)/2 ){ //our improvement just chekc for the quorum
this.properties.setMyVote(currentN.getVote());
break;
}
//wrong condition
// else if(myVoteCounter> (memberList.size()+1)/2 && OutOfElectionVotes.containsKey(currentN.getVote().getId())){
// this.electionRound = currentN.getSenderRound();
//
// }
} //end of else
}// end of while
// Here the leader is the one pointed by my vote
return this.properties.getMyVote();
}
private void sendNotification(List<InetSocketAddress> memberList2, Notification myNotification, ConcurrentLinkedQueue<Notification> currentElectionQueue) {
if(memberList2.isEmpty()) return;
for(InetSocketAddress member: memberList2){
SendNotificationThread nt0 = new SendNotificationThread(member, myNotification);
nt0.setElectionQueue1(currentElectionQueue);
Thread t = new Thread(nt0);
t.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Util functions
public long msgBootstrap(){
Socket socket;
long id = 0;
try {
socket = new Socket (bootstrapHost, bootstrapPort);
PrintWriter out = new PrintWriter (socket.getOutputStream(), true);
BufferedReader in = new BufferedReader (new InputStreamReader(socket.getInputStream ()));
//set self_ip:port to bootsstrap
out.println ("set "+ myIP + ":"+nodePort);
String memberList = in.readLine ();
String memberId = in.readLine();
id = Long.parseLong(memberId);
LOG.info("MemberID received:"+ id);
//process memberlist
this.properties.setId(id);
parseMemberList(memberList);
out.close ();
in.close();
socket.close ();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return id;
}
private void parseMemberList(String memberList) {
String[] list = memberList.split(",");
System.out.println("Members");
for(String s:list){
String[] address = s.split(":");
String ip = address[0];
int port = Integer.parseInt(address[1]);
if(myIP.equals(ip) && nodePort== port){}
else{
InetSocketAddress addr = new InetSocketAddress(address[0], Integer.parseInt(address[1]));
this.memberList.add(addr);
}
}
}
public String getMyIP(){
BufferedReader in = null;
String ip = " ";
try {
URL whatismyip = new URL("http://ipv4bot.whatismyipaddress.com/");
in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
ip = in.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ip;
}
private void writeHistory() {
String fileName = "CommitedHistory_"+this.nodePort+".txt";
File fout = new File(fileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for(Message m: this.properties.getMessageList()){
bw.write(m.toString());
bw.newLine();
}
bw.flush();
bw.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void readHistory() {
String fileName = "CommitedHistory_"+this.nodePort+".txt";
String line = null;
List<Message> msgList = this.properties.getMessageList();
try {
FileReader fileReader = new FileReader(fileName );
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
Message m = new Message(line);
msgList.add(m);
System.out.println(m);
}
bufferedReader.close();
fileReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Message lastMsg = msgList.get(msgList.size()-1);
this.properties.setCurrentEpoch(lastMsg.getEpoch());
this.properties.setLastZxId(lastMsg.getTxId());
}
}
| FLE v0.0.5
| src/main/java/servers/NodeServer.java | FLE v0.0.5 | <ide><path>rc/main/java/servers/NodeServer.java
<ide> import java.util.List;
<ide> import java.util.Map.Entry;
<ide> import java.util.concurrent.ConcurrentLinkedQueue;
<add>import java.util.concurrent.CopyOnWriteArrayList;
<ide> import java.util.Queue;
<ide>
<ide> import org.apache.logging.log4j.LogManager;
<ide> this.bootstrapPort = bport;
<ide> this.nodePort = nport;
<ide> this.properties = new NodeServerProperties();
<del> this.memberList = new ArrayList<InetSocketAddress>();
<add> this.memberList = new CopyOnWriteArrayList<InetSocketAddress>();
<ide> final NodeServer this1 = this;
<ide> myIP = getMyIP();
<ide> if(bhost.equals("localhost")) |
|
Java | bsd-3-clause | 652ced7f8e3d415a85f94988b85ef3d795670c29 | 0 | Monsters-308/FRC2016 | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
// Max
// Matteo
package org.usfirst.frc308.FRC2016.subsystems;
import org.usfirst.frc308.FRC2016.Robot;
import org.usfirst.frc308.FRC2016.RobotConstants;
import org.usfirst.frc308.FRC2016.RobotMap;
import org.usfirst.frc308.FRC2016.commands.*;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.CANTalon.TalonControlMode;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class Shooter extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final CANTalon shootMotor1 = RobotMap.shootershootMotor1;
private final CANTalon intakeMotor = RobotMap.shooterintakeMotor;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final DigitalInput highOpticalSensor = RobotMap.highopticalsensor;
private final DigitalInput lowOpticalSensor = RobotMap.lowopticalsensor;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
setDefaultCommand(new teleopShooter());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
/**
* keeps ball between optical sensors
*/
public void adjustBall() {
// If lowOpticalSensor is false and highOpticalSensor is true
if (lowOpticalSensor.get() == false && highOpticalSensor.get() == true) {
// then run intakeMotor reverse intakeAdjustSpeed
Robot.shooter.intakeMotor.set(-RobotConstants.intakeAdjustSpeed);
} else {
if (lowOpticalSensor.get() == true && highOpticalSensor.get() == false) {
Robot.shooter.intakeMotor.set(RobotConstants.intakeAdjustSpeed);
} else {
Robot.shooter.intakeMotor.set(0);
}
}
// Else if lowOpticalSensor is true and highOpticalSensor is false
// then run intakeMotor forward intakeAdjustSpeed
//
// Else set intakeMotor to 0 (stop)
}
/**
* sets up shooter without PID
*/
public void setupShooter() {
shootMotor1.changeControlMode(TalonControlMode.PercentVbus);
intakeMotor.changeControlMode(TalonControlMode.PercentVbus);
}
/**
* runs the intake motor
*/
public void runIntakeMotor() {
// if highOpticalSensor is false
// set intakeMotor to constant intakeGrabSpeed
if (highOpticalSensor.get() == false) {
Robot.shooter.intakeMotor.set(RobotConstants.intakeGrabSpeed);
} else {
Robot.shooter.intakeMotor.set(0);
}
// else set intakeMotor to 0
}
/**
* shoots the ball
*/
public void shootBallHigh() {
/*
* if shooter not up to speed and both optical sensors are true, then
* set shootMotor to shooterSpeed
*
* else if current shooter speed is within shootingTolerance , then set
* intakeMotor to intakeShooterSpeed
*
* else set shootMotor 0
*/
if (Math.abs(RobotConstants.shooterSpeed
- Robot.shooter.shootMotor1.getEncVelocity()) > RobotConstants.shooterTolerance
&& (highOpticalSensor.get() == true && lowOpticalSensor.get() == true)) {
Robot.shooter.shootMotor1.set(RobotConstants.intakeShooterSpeed);
} else if (Math.abs(RobotConstants.shooterSpeed
- Robot.shooter.shootMotor1.getEncVelocity()) < RobotConstants.shooterTolerance) {
Robot.shooter.intakeMotor.set(RobotConstants.intakeShooterSpeed);
} else {
Robot.shooter.shootMotor1.set(0);
}
}
public void ejectBall() {
// set intakeMotor to negative intakeEjectSpeed
Robot.shooter.intakeMotor.set(-RobotConstants.intakeEjectSpeed);
}
/**
* sets the shooter power
*
* @param power
* the power to shoot, from -1.0 to 1.0
*/
public void setShootPower(double power) {
shootMotor1.set(power);
}
}
| src/org/usfirst/frc308/FRC2016/subsystems/Shooter.java | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
// Max
// Matteo
package org.usfirst.frc308.FRC2016.subsystems;
import org.usfirst.frc308.FRC2016.RobotMap;
import org.usfirst.frc308.FRC2016.commands.*;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.CANTalon.TalonControlMode;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class Shooter extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final CANTalon shootMotor1 = RobotMap.shootershootMotor1;
private final CANTalon intakeMotor = RobotMap.shooterintakeMotor;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final DigitalInput highOpticalSensor = RobotMap.highopticalsensor;
private final DigitalInput lowOpticalSensor = RobotMap.lowopticalsensor;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
setDefaultCommand(new teleopShooter());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
/**
* keeps ball between optical sensors
*/
public void adjustBall() {
/*If lowOpticalSensor is false and highOpticalSensor is true
*then run intakeMotor reverse intakeAdjustSpeed
*
*Else if lowOpticalSensor is true and highOpticalSensor is false
*then run intakeMotor forward intakeAdjustSpeed
*
*Else set intakeMotor to 0 (stop)
*/
}
/**
* sets up shooter without PID
*/
public void setupShooter() {
shootMotor1.changeControlMode(TalonControlMode.PercentVbus);
intakeMotor.changeControlMode(TalonControlMode.PercentVbus);
}
/**
* runs the intake motor
*/
public void runIntakeMotor() {
// if highOpticalSensor is false
// set intakeMotor to constant intakeGrabSpeed
// else set intakeMotor to 0
}
/**
* shoots the ball
*/
public void shootBallHigh() {
/*
* if shooter not up to speed and both optical sensors are true,
* then set shootMotor to shooterSpeed
*
* else if current shooter speed is within shootingTolerance ,
* then set intakeMotor to intakeShooterSpeed
*
* else set shootMotor 0
*/
}
public void ejectBall() {
/*
* if buttonC is pressed, set intakeMotor to negative intakeEjectSpeed
*
* else set intakeMotor 0
*/
}
/**
* sets the shooter power
*
* @param power
* the power to shoot, from -1.0 to 1.0
*/
public void setShootPower(double power) {
shootMotor1.set(power);
}
}
| Turned shooter pseudo code into true code
Bill gates first commit
| src/org/usfirst/frc308/FRC2016/subsystems/Shooter.java | Turned shooter pseudo code into true code | <ide><path>rc/org/usfirst/frc308/FRC2016/subsystems/Shooter.java
<ide> // Matteo
<ide> package org.usfirst.frc308.FRC2016.subsystems;
<ide>
<add>import org.usfirst.frc308.FRC2016.Robot;
<add>import org.usfirst.frc308.FRC2016.RobotConstants;
<ide> import org.usfirst.frc308.FRC2016.RobotMap;
<ide> import org.usfirst.frc308.FRC2016.commands.*;
<ide> import edu.wpi.first.wpilibj.CANTalon;
<ide> private final CANTalon intakeMotor = RobotMap.shooterintakeMotor;
<ide>
<ide> // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
<del>
<add>
<ide> private final DigitalInput highOpticalSensor = RobotMap.highopticalsensor;
<ide> private final DigitalInput lowOpticalSensor = RobotMap.lowopticalsensor;
<ide>
<ide> * keeps ball between optical sensors
<ide> */
<ide> public void adjustBall() {
<del> /*If lowOpticalSensor is false and highOpticalSensor is true
<del> *then run intakeMotor reverse intakeAdjustSpeed
<del> *
<del> *Else if lowOpticalSensor is true and highOpticalSensor is false
<del> *then run intakeMotor forward intakeAdjustSpeed
<del> *
<del> *Else set intakeMotor to 0 (stop)
<del> */
<add> // If lowOpticalSensor is false and highOpticalSensor is true
<add> if (lowOpticalSensor.get() == false && highOpticalSensor.get() == true) {
<add> // then run intakeMotor reverse intakeAdjustSpeed
<add> Robot.shooter.intakeMotor.set(-RobotConstants.intakeAdjustSpeed);
<add> } else {
<add> if (lowOpticalSensor.get() == true && highOpticalSensor.get() == false) {
<add> Robot.shooter.intakeMotor.set(RobotConstants.intakeAdjustSpeed);
<add> } else {
<add> Robot.shooter.intakeMotor.set(0);
<add> }
<add> }
<add> // Else if lowOpticalSensor is true and highOpticalSensor is false
<add> // then run intakeMotor forward intakeAdjustSpeed
<add> //
<add> // Else set intakeMotor to 0 (stop)
<add>
<ide> }
<ide>
<ide> /**
<ide> intakeMotor.changeControlMode(TalonControlMode.PercentVbus);
<ide> }
<ide>
<del>
<del>
<del>
<del>
<ide> /**
<ide> * runs the intake motor
<ide> */
<ide> public void runIntakeMotor() {
<ide> // if highOpticalSensor is false
<ide> // set intakeMotor to constant intakeGrabSpeed
<del>
<add> if (highOpticalSensor.get() == false) {
<add> Robot.shooter.intakeMotor.set(RobotConstants.intakeGrabSpeed);
<add> } else {
<add> Robot.shooter.intakeMotor.set(0);
<add> }
<ide> // else set intakeMotor to 0
<ide>
<ide> }
<ide> */
<ide> public void shootBallHigh() {
<ide> /*
<del> * if shooter not up to speed and both optical sensors are true,
<del> * then set shootMotor to shooterSpeed
<add> * if shooter not up to speed and both optical sensors are true, then
<add> * set shootMotor to shooterSpeed
<ide> *
<del> * else if current shooter speed is within shootingTolerance ,
<del> * then set intakeMotor to intakeShooterSpeed
<add> * else if current shooter speed is within shootingTolerance , then set
<add> * intakeMotor to intakeShooterSpeed
<ide> *
<ide> * else set shootMotor 0
<ide> */
<add> if (Math.abs(RobotConstants.shooterSpeed
<add> - Robot.shooter.shootMotor1.getEncVelocity()) > RobotConstants.shooterTolerance
<add> && (highOpticalSensor.get() == true && lowOpticalSensor.get() == true)) {
<add> Robot.shooter.shootMotor1.set(RobotConstants.intakeShooterSpeed);
<add> } else if (Math.abs(RobotConstants.shooterSpeed
<add> - Robot.shooter.shootMotor1.getEncVelocity()) < RobotConstants.shooterTolerance) {
<add> Robot.shooter.intakeMotor.set(RobotConstants.intakeShooterSpeed);
<add> } else {
<add> Robot.shooter.shootMotor1.set(0);
<add> }
<add> }
<ide>
<del> }
<ide> public void ejectBall() {
<del> /*
<del> * if buttonC is pressed, set intakeMotor to negative intakeEjectSpeed
<del> *
<del> * else set intakeMotor 0
<del> */
<del>
<add> // set intakeMotor to negative intakeEjectSpeed
<add>
<add> Robot.shooter.intakeMotor.set(-RobotConstants.intakeEjectSpeed);
<add>
<ide> }
<ide>
<ide> /** |
|
Java | mit | ba63b4c1668ea03d37ac57ad0ce68d1554d6dde8 | 0 | jenkinsci/saltstack-plugin,jenkinsci/saltstack-plugin,spacanowski/saltstack-plugin,spacanowski/saltstack-plugin | package com.waytta;
import hudson.Launcher;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.AbstractProject;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;
import net.sf.json.JSONSerializer;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
public class SaltAPIBuilder extends Builder {
private final String servername;
private final String username;
private final String userpass;
private final String authtype;
private final String target;
private final String targettype;
private final String function;
private final String arguments;
private final String kwarguments;
private final JSONObject clientInterfaces;
private final String clientInterface;
private final Boolean blockbuild;
private final Integer jobPollTime;
private final String batchSize;
private final String mods;
private final Boolean usePillar;
private final String pillarkey;
private final String pillarvalue;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public SaltAPIBuilder(String servername, String username, String userpass, String authtype, String target, String targettype, String function, String arguments, String kwarguments, JSONObject clientInterfaces, Integer jobPollTime, String mods, String pillarkey, String pillarvalue) {
this.servername = servername;
this.username = username;
this.userpass = userpass;
this.authtype = authtype;
this.target = target;
this.targettype = targettype;
this.function = function;
this.arguments = arguments;
this.kwarguments = kwarguments;
this.clientInterfaces = clientInterfaces;
if (clientInterfaces.has("clientInterface")) {
this.clientInterface = clientInterfaces.get("clientInterface").toString();
} else {
this.clientInterface = "local";
}
if (clientInterface.equals("local")) {
this.blockbuild = clientInterfaces.getBoolean("blockbuild");
this.jobPollTime = clientInterfaces.getInt("jobPollTime");
this.batchSize = "100%";
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("local_batch")) {
this.batchSize = clientInterfaces.get("batchSize").toString();
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("runner")) {
this.mods = clientInterfaces.get("mods").toString();
if (clientInterfaces.has("usePillar")) {
this.usePillar = true;
this.pillarkey = clientInterfaces.getJSONObject("usePillar").get("pillarkey").toString();
this.pillarvalue = clientInterfaces.getJSONObject("usePillar").get("pillarvalue").toString();
} else {
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
this.blockbuild = false;
this.jobPollTime = 10;
this.batchSize = "100%";
} else {
this.batchSize = "100%";
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
}
/*
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getServername() {
return servername;
}
public String getUsername() {
return username;
}
public String getUserpass() {
return userpass;
}
public String getAuthtype() {
return authtype;
}
public String getTarget() {
return target;
}
public String getTargettype() {
return this.targettype;
}
public String getFunction() {
return function;
}
public String getArguments() {
return arguments;
}
public String getKwarguments() {
return kwarguments;
}
public String getClientInterface() {
return clientInterface;
}
public Boolean getBlockbuild() {
return blockbuild;
}
public String getBatchSize() {
return batchSize;
}
public Integer getJobPollTime() {
return jobPollTime;
}
public String getMods() {
return mods;
}
public Boolean getUsePillar() {
return usePillar;
}
public String getPillarkey() {
return pillarkey;
}
public String getPillarvalue() {
return pillarvalue;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
// This is where you 'build' the project.
// If not not configured, grab the default
int myJobPollTime = 10;
if (jobPollTime == null) {
myJobPollTime = getDescriptor().getPollTime();
} else {
myJobPollTime = jobPollTime;
}
Boolean mySaltMessageDebug = getDescriptor().getSaltMessageDebug();
String myClientInterface = clientInterface;
String myservername = servername;
String mytarget = target;
String myfunction = function;
String myarguments = arguments;
String mykwarguments = kwarguments;
Boolean myBlockBuild = blockbuild;
//listener.getLogger().println("Salt Arguments before: "+myarguments);
myservername = Utils.paramorize(build, listener, servername);
mytarget = Utils.paramorize(build, listener, target);
myfunction = Utils.paramorize(build, listener, function);
myarguments = Utils.paramorize(build, listener, arguments);
mykwarguments = Utils.paramorize(build, listener, kwarguments);
//listener.getLogger().println("Salt Arguments after: "+myarguments);
//Setup connection for auth
String token = new String();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
JSONArray authArray = new JSONArray();
authArray.add(auth);
//listener.getLogger().println("Sending auth: "+authArray.toString());
JSONObject httpResponse = new JSONObject();
//Get an auth token
token = Utils.getToken(myservername, authArray);
if (token.contains("Error")) {
listener.getLogger().println(token);
return false;
}
//If we got this far, auth must have been pretty good and we've got a token
JSONArray saltArray = new JSONArray();
JSONObject saltFunc = new JSONObject();
// Hardcode clientInterface if not yet set. Once constructor runs, this will not be necessary
if (myClientInterface == null) {
myClientInterface = "local";
}
saltFunc.put("client", myClientInterface);
if (myClientInterface.equals("local_batch")) {
saltFunc.put("batch", batchSize);
listener.getLogger().println("Running in batch mode. Batch size: "+batchSize);
}
if (myClientInterface.equals("runner")) {
saltFunc.put("mods", mods);
if (usePillar) {
String myPillarkey = Utils.paramorize(build, listener, pillarkey);
String myPillarvalue = Utils.paramorize(build, listener, pillarvalue);
JSONObject jPillar = new JSONObject();
jPillar.put(JSONUtils.stripQuotes(myPillarkey), JSONUtils.stripQuotes(myPillarvalue));
saltFunc.put("pillar", jPillar);
}
}
saltFunc.put("tgt", mytarget);
saltFunc.put("expr_form", targettype);
saltFunc.put("fun", myfunction);
if (myarguments.length() > 0){
List saltArguments = new ArrayList();
//spit on comma seperated not inside of quotes
String[] argItems = myarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String arg : argItems) {
//remove spaces at begining or end
arg = arg.replaceAll("^\\s+|\\s+$", "");
arg = arg.replaceAll("\"|\\\"", "");
saltArguments.add(arg);
}
//Add any args to json message
saltFunc.element("arg", saltArguments);
}
if (mykwarguments.length() > 0){
Map kwArgs = new HashMap();
//spit on comma seperated not inside of quotes
String[] kwargItems = mykwarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String kwarg : kwargItems) {
//remove spaces at begining or end
kwarg = kwarg.replaceAll("^\\s+|\\s+$", "");
kwarg = kwarg.replaceAll("\"|\\\"", "");
if (kwarg.contains("=")) {
String[] kwString = kwarg.split("=");
if (kwString.length > 2){
//kwarg contained more than one =. Let's put the string back together
String kwFull = new String();
for (String kwItem : kwString){
//Ignore the first item as it will remain the key
if ( kwItem == kwString[0] ) continue;
//add the second item
if ( kwItem == kwString[1] ) {
kwFull += kwItem;
continue;
}
//add all other items with an = to rejoin
kwFull += "="+kwItem;
}
kwArgs.put(kwString[0], kwFull);
} else {
kwArgs.put(kwString[0], kwString[1]);
}
}
}
//Add any kwargs to json message
saltFunc.element("kwarg", kwArgs);
}
saltArray.add(saltFunc);
if (mySaltMessageDebug) {
listener.getLogger().println("Sending JSON: "+saltArray.toString());
}
if (myBlockBuild == null) {
//Set a sane default if uninitialized
myBlockBuild = false;
}
//blocking request
if (myBlockBuild) {
String jid = new String();
//Send request to /minion url. This will give back a jid which we will need to poll and lookup for completion
httpResponse = Utils.getJSON(myservername+"/minions", saltArray, token);
try {
JSONArray returnArray = httpResponse.getJSONArray("return");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
jid = line.getString("jid");
}
//Print out success
listener.getLogger().println("Running jid: " + jid);
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+myservername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Request successfully sent. Now use jid to check if job complete
int numMinions = 0;
int numMinionsDone = 0;
JSONArray returnArray = new JSONArray();
httpResponse = Utils.getJSON(myservername+"/jobs/"+jid, null, token);
try {
//info array will tell us how many minions were targeted
returnArray = httpResponse.getJSONArray("info");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
JSONArray minionsArray = line.getJSONArray("Minions");
//Check the info[Minions[]] array to see how many nodes we expect to hear back from
numMinions = minionsArray.size();
listener.getLogger().println("Waiting for " + numMinions + " minions");
}
returnArray = httpResponse.getJSONArray("return");
//Check the return[] array to see how many minions have responded
if (!returnArray.getJSONObject(0).names().isEmpty()) {
numMinionsDone = returnArray.getJSONObject(0).names().size();
} else {
numMinionsDone = 0;
}
listener.getLogger().println(numMinionsDone + " minions are done");
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+myservername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Now that we know how many minions have responded, and how many we are waiting on. Let's see more have finished
if (numMinionsDone < numMinions) {
//Don't print annying messages unless we really are waiting for more minions to return
listener.getLogger().println("Will check status every "+String.valueOf(myJobPollTime)+" seconds...");
}
while (numMinionsDone < numMinions) {
try {
Thread.sleep(myJobPollTime*1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
//Allow user to cancel job in jenkins interface
listener.getLogger().println("Cancelling job");
return false;
}
httpResponse = Utils.getJSON(myservername+"/jobs/"+jid, null, token);
try {
returnArray = httpResponse.getJSONArray("return");
numMinionsDone = returnArray.getJSONObject(0).names().size();
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
}
if (returnArray.get(0).toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error for "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
return false;
}
//If running script module check for non-zero exit codes in retcode.
returnArray = httpResponse.getJSONArray("return");
if (myfunction.equals("cmd.script")) {
for (Object o : returnArray) {
JSONObject minion = (JSONObject) o;
for (Object name : minion.names()) {
Integer retcode = minion.getJSONObject(name.toString()).getInt("retcode");
if (retcode != 0) {
listener.getLogger().println("One or more minion did not return code 0 for "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
return false;
}
}
}
}
//Loop is done. We have heard back from everybody. Good work team!
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
} else {
//Just send a salt request. Don't wait for reply
httpResponse = Utils.getJSON(myservername, saltArray, token);
try {
if (!httpResponse.getJSONArray("return").isArray()) {
//Print problem
listener.getLogger().println("Problem on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
}
} catch (Exception e) {
listener.getLogger().println("Problem with "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
//valide return
if (httpResponse.toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
} else {
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
}
}
//No fail condition reached. Must be good.
return true;
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
private int pollTime=10;
private boolean saltMessageDebug;
public DescriptorImpl() {
load();
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
try {
//Test that value entered in config is an integer
pollTime = formData.getInt("pollTime");
} catch (Exception e) {
//Fall back to default
pollTime = 10;
}
saltMessageDebug = formData.getBoolean("saltMessageDebug");
save();
return super.configure(req,formData);
}
public int getPollTime() {
return pollTime;
}
public boolean getSaltMessageDebug() {
return saltMessageDebug;
}
public FormValidation doTestConnection(@QueryParameter("servername") final String servername,
@QueryParameter("username") final String username,
@QueryParameter("userpass") final String userpass,
@QueryParameter("authtype") final String authtype)
throws IOException, ServletException {
if (!servername.matches("\\{\\{\\w+\\}\\}")) {
JSONObject httpResponse = new JSONObject();
JSONArray authArray = new JSONArray();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
authArray.add(auth);
String token = Utils.getToken(servername, authArray);
if (token.contains("Error")) {
return FormValidation.error("Client error : "+token);
} else {
return FormValidation.ok("Success");
}
} else {
return FormValidation.warning("Cannot expand parametrized server name.");
}
}
public FormValidation doCheckServername(@QueryParameter String value)
throws IOException, ServletException {
if (!value.matches("\\{\\{\\w+\\}\\}")) {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 10)
return FormValidation.warning("Isn't the name too short?");
if (!value.contains("https://") && !value.contains("http://"))
return FormValidation.warning("Missing protocol: Servername should be in the format https://host.domain:8000");
if (!value.substring(7).contains(":"))
return FormValidation.warning("Missing port: Servername should be in the format https://host.domain:8000");
return FormValidation.ok();
} else {
return FormValidation.warning("Cannot expand parametrized server name.");
}
}
public FormValidation doCheckUsername(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 3)
return FormValidation.warning("Isn't the name too short?");
return FormValidation.ok();
}
public FormValidation doCheckUserpass(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a password");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckTarget(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt target");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckFunction(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt function");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckPollTime(@QueryParameter String value)
throws IOException, ServletException {
try {
Integer.parseInt(value);
} catch(NumberFormatException e) {
return FormValidation.error("Specify a number larger than 3");
}
if (Integer.parseInt(value) < 3)
return FormValidation.warning("Specify a number larger than 3");
return FormValidation.ok();
}
public FormValidation doCheckBatchSize(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify batch size");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Send a message to Salt API";
}
}
}
| src/main/java/com/waytta/SaltAPIBuilder.java | package com.waytta;
import hudson.Launcher;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.AbstractProject;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;
import net.sf.json.JSONSerializer;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
public class SaltAPIBuilder extends Builder {
private final String servername;
private final String username;
private final String userpass;
private final String authtype;
private final String target;
private final String targettype;
private final String function;
private final String arguments;
private final String kwarguments;
private final JSONObject clientInterfaces;
private final String clientInterface;
private final Boolean blockbuild;
private final Integer jobPollTime;
private final String batchSize;
private final String mods;
private final Boolean usePillar;
private final String pillarkey;
private final String pillarvalue;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public SaltAPIBuilder(String servername, String username, String userpass, String authtype, String target, String targettype, String function, String arguments, String kwarguments, JSONObject clientInterfaces, Integer jobPollTime, String mods, String pillarkey, String pillarvalue) {
this.servername = servername;
this.username = username;
this.userpass = userpass;
this.authtype = authtype;
this.target = target;
this.targettype = targettype;
this.function = function;
this.arguments = arguments;
this.kwarguments = kwarguments;
this.clientInterfaces = clientInterfaces;
if (clientInterfaces.has("clientInterface")) {
this.clientInterface = clientInterfaces.get("clientInterface").toString();
} else {
this.clientInterface = "local";
}
if (clientInterface.equals("local")) {
this.blockbuild = clientInterfaces.getBoolean("blockbuild");
this.jobPollTime = clientInterfaces.getInt("jobPollTime");
this.batchSize = "100%";
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("local_batch")) {
this.batchSize = clientInterfaces.get("batchSize").toString();
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
} else if (clientInterface.equals("runner")) {
this.mods = clientInterfaces.get("mods").toString();
if (clientInterfaces.has("usePillar")) {
this.usePillar = true;
this.pillarkey = clientInterfaces.getJSONObject("usePillar").get("pillarkey").toString();
this.pillarvalue = clientInterfaces.getJSONObject("usePillar").get("pillarvalue").toString();
} else {
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
this.blockbuild = false;
this.jobPollTime = 10;
this.batchSize = "100%";
} else {
this.batchSize = "100%";
this.blockbuild = false;
this.jobPollTime = 10;
this.mods = "";
this.usePillar = false;
this.pillarkey = "";
this.pillarvalue = "";
}
}
/*
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getServername() {
return servername;
}
public String getUsername() {
return username;
}
public String getUserpass() {
return userpass;
}
public String getAuthtype() {
return authtype;
}
public String getTarget() {
return target;
}
public String getTargettype() {
return this.targettype;
}
public String getFunction() {
return function;
}
public String getArguments() {
return arguments;
}
public String getKwarguments() {
return kwarguments;
}
public String getClientInterface() {
return clientInterface;
}
public Boolean getBlockbuild() {
return blockbuild;
}
public String getBatchSize() {
return batchSize;
}
public Integer getJobPollTime() {
return jobPollTime;
}
public String getMods() {
return mods;
}
public Boolean getUsePillar() {
return usePillar;
}
public String getPillarkey() {
return pillarkey;
}
public String getPillarvalue() {
return pillarvalue;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
// This is where you 'build' the project.
// If not not configured, grab the default
int myJobPollTime = 10;
if (jobPollTime == null) {
myJobPollTime = getDescriptor().getPollTime();
} else {
myJobPollTime = jobPollTime;
}
Boolean mySaltMessageDebug = getDescriptor().getSaltMessageDebug();
String myClientInterface = clientInterface;
String mytarget = target;
String myfunction = function;
String myarguments = arguments;
String mykwarguments = kwarguments;
Boolean myBlockBuild = blockbuild;
//listener.getLogger().println("Salt Arguments before: "+myarguments);
mytarget = Utils.paramorize(build, listener, target);
myfunction = Utils.paramorize(build, listener, function);
myarguments = Utils.paramorize(build, listener, arguments);
mykwarguments = Utils.paramorize(build, listener, kwarguments);
//listener.getLogger().println("Salt Arguments after: "+myarguments);
//Setup connection for auth
String token = new String();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
JSONArray authArray = new JSONArray();
authArray.add(auth);
//listener.getLogger().println("Sending auth: "+authArray.toString());
JSONObject httpResponse = new JSONObject();
//Get an auth token
token = Utils.getToken(servername, authArray);
if (token.contains("Error")) {
listener.getLogger().println(token);
return false;
}
//If we got this far, auth must have been pretty good and we've got a token
JSONArray saltArray = new JSONArray();
JSONObject saltFunc = new JSONObject();
// Hardcode clientInterface if not yet set. Once constructor runs, this will not be necessary
if (myClientInterface == null) {
myClientInterface = "local";
}
saltFunc.put("client", myClientInterface);
if (myClientInterface.equals("local_batch")) {
saltFunc.put("batch", batchSize);
listener.getLogger().println("Running in batch mode. Batch size: "+batchSize);
}
if (myClientInterface.equals("runner")) {
saltFunc.put("mods", mods);
if (usePillar) {
String myPillarkey = Utils.paramorize(build, listener, pillarkey);
String myPillarvalue = Utils.paramorize(build, listener, pillarvalue);
JSONObject jPillar = new JSONObject();
jPillar.put(JSONUtils.stripQuotes(myPillarkey), JSONUtils.stripQuotes(myPillarvalue));
saltFunc.put("pillar", jPillar);
}
}
saltFunc.put("tgt", mytarget);
saltFunc.put("expr_form", targettype);
saltFunc.put("fun", myfunction);
if (myarguments.length() > 0){
List saltArguments = new ArrayList();
//spit on comma seperated not inside of quotes
String[] argItems = myarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String arg : argItems) {
//remove spaces at begining or end
arg = arg.replaceAll("^\\s+|\\s+$", "");
arg = arg.replaceAll("\"|\\\"", "");
saltArguments.add(arg);
}
//Add any args to json message
saltFunc.element("arg", saltArguments);
}
if (mykwarguments.length() > 0){
Map kwArgs = new HashMap();
//spit on comma seperated not inside of quotes
String[] kwargItems = mykwarguments.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String kwarg : kwargItems) {
//remove spaces at begining or end
kwarg = kwarg.replaceAll("^\\s+|\\s+$", "");
kwarg = kwarg.replaceAll("\"|\\\"", "");
if (kwarg.contains("=")) {
String[] kwString = kwarg.split("=");
if (kwString.length > 2){
//kwarg contained more than one =. Let's put the string back together
String kwFull = new String();
for (String kwItem : kwString){
//Ignore the first item as it will remain the key
if ( kwItem == kwString[0] ) continue;
//add the second item
if ( kwItem == kwString[1] ) {
kwFull += kwItem;
continue;
}
//add all other items with an = to rejoin
kwFull += "="+kwItem;
}
kwArgs.put(kwString[0], kwFull);
} else {
kwArgs.put(kwString[0], kwString[1]);
}
}
}
//Add any kwargs to json message
saltFunc.element("kwarg", kwArgs);
}
saltArray.add(saltFunc);
if (mySaltMessageDebug) {
listener.getLogger().println("Sending JSON: "+saltArray.toString());
}
if (myBlockBuild == null) {
//Set a sane default if uninitialized
myBlockBuild = false;
}
//blocking request
if (myBlockBuild) {
String jid = new String();
//Send request to /minion url. This will give back a jid which we will need to poll and lookup for completion
httpResponse = Utils.getJSON(servername+"/minions", saltArray, token);
try {
JSONArray returnArray = httpResponse.getJSONArray("return");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
jid = line.getString("jid");
}
//Print out success
listener.getLogger().println("Running jid: " + jid);
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Request successfully sent. Now use jid to check if job complete
int numMinions = 0;
int numMinionsDone = 0;
JSONArray returnArray = new JSONArray();
httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
try {
//info array will tell us how many minions were targeted
returnArray = httpResponse.getJSONArray("info");
for (Object o : returnArray ) {
JSONObject line = (JSONObject) o;
JSONArray minionsArray = line.getJSONArray("Minions");
//Check the info[Minions[]] array to see how many nodes we expect to hear back from
numMinions = minionsArray.size();
listener.getLogger().println("Waiting for " + numMinions + " minions");
}
returnArray = httpResponse.getJSONArray("return");
//Check the return[] array to see how many minions have responded
if (!returnArray.getJSONObject(0).names().isEmpty()) {
numMinionsDone = returnArray.getJSONObject(0).names().size();
} else {
numMinionsDone = 0;
}
listener.getLogger().println(numMinionsDone + " minions are done");
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
return false;
}
//Now that we know how many minions have responded, and how many we are waiting on. Let's see more have finished
if (numMinionsDone < numMinions) {
//Don't print annying messages unless we really are waiting for more minions to return
listener.getLogger().println("Will check status every "+String.valueOf(myJobPollTime)+" seconds...");
}
while (numMinionsDone < numMinions) {
try {
Thread.sleep(myJobPollTime*1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
//Allow user to cancel job in jenkins interface
listener.getLogger().println("Cancelling job");
return false;
}
httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
try {
returnArray = httpResponse.getJSONArray("return");
numMinionsDone = returnArray.getJSONObject(0).names().size();
} catch (Exception e) {
listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
}
if (returnArray.get(0).toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error for "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
return false;
}
//Loop is done. We have heard back from everybody. Good work team!
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
} else {
//Just send a salt request. Don't wait for reply
httpResponse = Utils.getJSON(servername, saltArray, token);
try {
if (!httpResponse.getJSONArray("return").isArray()) {
//Print problem
listener.getLogger().println("Problem on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
}
} catch (Exception e) {
listener.getLogger().println("Problem with "+myfunction+" "+myarguments+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2).split("\\\\n")[0]);
return false;
}
//valide return
if (httpResponse.toString().contains("TypeError")) {
listener.getLogger().println("Salt reported an error on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
return false;
} else {
listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+httpResponse.toString(2));
}
}
//No fail condition reached. Must be good.
return true;
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
private int pollTime=10;
private boolean saltMessageDebug;
public DescriptorImpl() {
load();
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
try {
//Test that value entered in config is an integer
pollTime = formData.getInt("pollTime");
} catch (Exception e) {
//Fall back to default
pollTime = 10;
}
saltMessageDebug = formData.getBoolean("saltMessageDebug");
save();
return super.configure(req,formData);
}
public int getPollTime() {
return pollTime;
}
public boolean getSaltMessageDebug() {
return saltMessageDebug;
}
public FormValidation doTestConnection(@QueryParameter("servername") final String servername,
@QueryParameter("username") final String username,
@QueryParameter("userpass") final String userpass,
@QueryParameter("authtype") final String authtype)
throws IOException, ServletException {
JSONObject httpResponse = new JSONObject();
JSONArray authArray = new JSONArray();
JSONObject auth = new JSONObject();
auth.put("username", username);
auth.put("password", userpass);
auth.put("eauth", authtype);
authArray.add(auth);
String token = Utils.getToken(servername, authArray);
if (token.contains("Error")) {
return FormValidation.error("Client error : "+token);
} else {
return FormValidation.ok("Success");
}
}
public FormValidation doCheckServername(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 10)
return FormValidation.warning("Isn't the name too short?");
if (!value.contains("https://") && !value.contains("http://"))
return FormValidation.warning("Missing protocol: Servername should be in the format https://host.domain:8000");
if (!value.substring(7).contains(":"))
return FormValidation.warning("Missing port: Servername should be in the format https://host.domain:8000");
return FormValidation.ok();
}
public FormValidation doCheckUsername(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a name");
if (value.length() < 3)
return FormValidation.warning("Isn't the name too short?");
return FormValidation.ok();
}
public FormValidation doCheckUserpass(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a password");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckTarget(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt target");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckFunction(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify a salt function");
if (value.length() < 3)
return FormValidation.warning("Isn't it too short?");
return FormValidation.ok();
}
public FormValidation doCheckPollTime(@QueryParameter String value)
throws IOException, ServletException {
try {
Integer.parseInt(value);
} catch(NumberFormatException e) {
return FormValidation.error("Specify a number larger than 3");
}
if (Integer.parseInt(value) < 3)
return FormValidation.warning("Specify a number larger than 3");
return FormValidation.ok();
}
public FormValidation doCheckBatchSize(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please specify batch size");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Send a message to Salt API";
}
}
}
| Allow paramoized server input and fail on non-zero retcode value when running script salt module in blocking mode.
| src/main/java/com/waytta/SaltAPIBuilder.java | Allow paramoized server input and fail on non-zero retcode value when running script salt module in blocking mode. | <ide><path>rc/main/java/com/waytta/SaltAPIBuilder.java
<ide> }
<ide> Boolean mySaltMessageDebug = getDescriptor().getSaltMessageDebug();
<ide> String myClientInterface = clientInterface;
<add> String myservername = servername;
<ide> String mytarget = target;
<ide> String myfunction = function;
<ide> String myarguments = arguments;
<ide> Boolean myBlockBuild = blockbuild;
<ide>
<ide> //listener.getLogger().println("Salt Arguments before: "+myarguments);
<add> myservername = Utils.paramorize(build, listener, servername);
<ide> mytarget = Utils.paramorize(build, listener, target);
<ide> myfunction = Utils.paramorize(build, listener, function);
<ide> myarguments = Utils.paramorize(build, listener, arguments);
<ide> JSONObject httpResponse = new JSONObject();
<ide>
<ide> //Get an auth token
<del> token = Utils.getToken(servername, authArray);
<add> token = Utils.getToken(myservername, authArray);
<ide> if (token.contains("Error")) {
<ide> listener.getLogger().println(token);
<ide> return false;
<ide> if (myBlockBuild) {
<ide> String jid = new String();
<ide> //Send request to /minion url. This will give back a jid which we will need to poll and lookup for completion
<del> httpResponse = Utils.getJSON(servername+"/minions", saltArray, token);
<add> httpResponse = Utils.getJSON(myservername+"/minions", saltArray, token);
<ide> try {
<ide> JSONArray returnArray = httpResponse.getJSONArray("return");
<ide> for (Object o : returnArray ) {
<ide> //Print out success
<ide> listener.getLogger().println("Running jid: " + jid);
<ide> } catch (Exception e) {
<del> listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
<add> listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+myservername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
<ide> return false;
<ide> }
<ide>
<ide> int numMinions = 0;
<ide> int numMinionsDone = 0;
<ide> JSONArray returnArray = new JSONArray();
<del> httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
<add> httpResponse = Utils.getJSON(myservername+"/jobs/"+jid, null, token);
<ide> try {
<ide> //info array will tell us how many minions were targeted
<ide> returnArray = httpResponse.getJSONArray("info");
<ide> }
<ide> listener.getLogger().println(numMinionsDone + " minions are done");
<ide> } catch (Exception e) {
<del> listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+servername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
<add> listener.getLogger().println("Problem: "+myfunction+" "+myarguments+" to "+myservername+" for "+mytarget+":\n"+e+"\n\n"+httpResponse.toString(2));
<ide> return false;
<ide> }
<ide>
<ide> listener.getLogger().println("Cancelling job");
<ide> return false;
<ide> }
<del> httpResponse = Utils.getJSON(servername+"/jobs/"+jid, null, token);
<add> httpResponse = Utils.getJSON(myservername+"/jobs/"+jid, null, token);
<ide> try {
<ide> returnArray = httpResponse.getJSONArray("return");
<ide> numMinionsDone = returnArray.getJSONObject(0).names().size();
<ide> listener.getLogger().println("Salt reported an error for "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
<ide> return false;
<ide> }
<add>
<add> //If running script module check for non-zero exit codes in retcode.
<add> returnArray = httpResponse.getJSONArray("return");
<add> if (myfunction.equals("cmd.script")) {
<add> for (Object o : returnArray) {
<add> JSONObject minion = (JSONObject) o;
<add> for (Object name : minion.names()) {
<add> Integer retcode = minion.getJSONObject(name.toString()).getInt("retcode");
<add> if (retcode != 0) {
<add> listener.getLogger().println("One or more minion did not return code 0 for "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
<add> return false;
<add> }
<add> }
<add> }
<add> }
<add>
<ide> //Loop is done. We have heard back from everybody. Good work team!
<ide> listener.getLogger().println("Response on "+myfunction+" "+myarguments+" for "+mytarget+":\n"+returnArray.toString(2));
<ide> } else {
<ide> //Just send a salt request. Don't wait for reply
<del> httpResponse = Utils.getJSON(servername, saltArray, token);
<add> httpResponse = Utils.getJSON(myservername, saltArray, token);
<ide> try {
<ide> if (!httpResponse.getJSONArray("return").isArray()) {
<ide> //Print problem
<ide> @QueryParameter("userpass") final String userpass,
<ide> @QueryParameter("authtype") final String authtype)
<ide> throws IOException, ServletException {
<del> JSONObject httpResponse = new JSONObject();
<del> JSONArray authArray = new JSONArray();
<del> JSONObject auth = new JSONObject();
<del> auth.put("username", username);
<del> auth.put("password", userpass);
<del> auth.put("eauth", authtype);
<del> authArray.add(auth);
<del> String token = Utils.getToken(servername, authArray);
<del> if (token.contains("Error")) {
<del> return FormValidation.error("Client error : "+token);
<del> } else {
<del> return FormValidation.ok("Success");
<del> }
<add> if (!servername.matches("\\{\\{\\w+\\}\\}")) {
<add> JSONObject httpResponse = new JSONObject();
<add> JSONArray authArray = new JSONArray();
<add> JSONObject auth = new JSONObject();
<add> auth.put("username", username);
<add> auth.put("password", userpass);
<add> auth.put("eauth", authtype);
<add> authArray.add(auth);
<add> String token = Utils.getToken(servername, authArray);
<add> if (token.contains("Error")) {
<add> return FormValidation.error("Client error : "+token);
<add> } else {
<add> return FormValidation.ok("Success");
<add> }
<add> } else {
<add> return FormValidation.warning("Cannot expand parametrized server name.");
<add> }
<ide> }
<ide>
<ide>
<ide> public FormValidation doCheckServername(@QueryParameter String value)
<ide> throws IOException, ServletException {
<del> if (value.length() == 0)
<del> return FormValidation.error("Please specify a name");
<del> if (value.length() < 10)
<del> return FormValidation.warning("Isn't the name too short?");
<del> if (!value.contains("https://") && !value.contains("http://"))
<del> return FormValidation.warning("Missing protocol: Servername should be in the format https://host.domain:8000");
<del> if (!value.substring(7).contains(":"))
<del> return FormValidation.warning("Missing port: Servername should be in the format https://host.domain:8000");
<del> return FormValidation.ok();
<add> if (!value.matches("\\{\\{\\w+\\}\\}")) {
<add> if (value.length() == 0)
<add> return FormValidation.error("Please specify a name");
<add> if (value.length() < 10)
<add> return FormValidation.warning("Isn't the name too short?");
<add> if (!value.contains("https://") && !value.contains("http://"))
<add> return FormValidation.warning("Missing protocol: Servername should be in the format https://host.domain:8000");
<add> if (!value.substring(7).contains(":"))
<add> return FormValidation.warning("Missing port: Servername should be in the format https://host.domain:8000");
<add> return FormValidation.ok();
<add> } else {
<add> return FormValidation.warning("Cannot expand parametrized server name.");
<add> }
<ide> }
<ide>
<ide> public FormValidation doCheckUsername(@QueryParameter String value) |
|
Java | unlicense | ba7913fe3d33e406c5628737da1910e1760b0472 | 0 | tsal/ElysiumFrontend,wastevens/ElysiumFrontend,wastevens/ElysiumFrontend,gnu-lorien/ElysiumFrontend,wastevens/ElysiumFrontend,tsal/ElysiumFrontend,tsal/ElysiumFrontend,gnu-lorien/ElysiumFrontend,gnu-lorien/ElysiumFrontend | package com.dstevens.event;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import org.hibernate.annotations.ForeignKey;
import com.dstevens.troupe.Venue;
import com.dstevens.user.PlayerCharacterOwnership;
@SuppressWarnings("deprecation")
@Entity
public class VenueEvent extends Event {
@Column(name="venue")
private final Venue venue;
@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name="VenueEvent_Attendance", joinColumns = @JoinColumn(name="event_id"),
inverseJoinColumns = @JoinColumn(name="playerCharacterOwnership_id"))
@ForeignKey(name="VenueEvent_PlayerCharacterOwnership_FK", inverseName="PlayerCharacterOwnership_TroupeEvent_FK")
private final Set<PlayerCharacterOwnership> attendance;
//Used only for hibernate
@SuppressWarnings("unused")
@Deprecated
private VenueEvent() {
this(null, null, null, null, null, null);
}
public VenueEvent(Integer id, String name, Date eventDate, EventStatus eventStatus, Venue venue, Set<PlayerCharacterOwnership> attendance) {
super(id, name, eventDate, eventStatus);
this.venue = venue;
this.attendance = attendance;
}
public Venue getVenue() {
return venue;
}
public Set<PlayerCharacterOwnership> getAttendance() {
return attendance;
}
}
| src/java/com/dstevens/event/VenueEvent.java | package com.dstevens.event;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import org.hibernate.annotations.ForeignKey;
import com.dstevens.troupe.Venue;
import com.dstevens.user.PlayerCharacterOwnership;
@SuppressWarnings("deprecation")
@Entity
public class VenueEvent extends Event {
@Column(name="venue")
private final Venue venue;
@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name="TroupeEvent_Attendance", joinColumns = @JoinColumn(name="event_id"),
inverseJoinColumns = @JoinColumn(name="playerCharacterOwnership_id"))
@ForeignKey(name="TroupeEvent_PlayerCharacterOwnership_FK", inverseName="PlayerCharacterOwnership_TroupeEvent_FK")
private final Set<PlayerCharacterOwnership> attendance;
//Used only for hibernate
@SuppressWarnings("unused")
@Deprecated
private VenueEvent() {
this(null, null, null, null, null, null);
}
public VenueEvent(Integer id, String name, Date eventDate, EventStatus eventStatus, Venue venue, Set<PlayerCharacterOwnership> attendance) {
super(id, name, eventDate, eventStatus);
this.venue = venue;
this.attendance = attendance;
}
public Venue getVenue() {
return venue;
}
public Set<PlayerCharacterOwnership> getAttendance() {
return attendance;
}
}
| Changed VenueEvent to carry PlayerCharacterOwnerships
for attendance. | src/java/com/dstevens/event/VenueEvent.java | Changed VenueEvent to carry PlayerCharacterOwnerships for attendance. | <ide><path>rc/java/com/dstevens/event/VenueEvent.java
<ide> private final Venue venue;
<ide>
<ide> @ManyToMany(cascade={CascadeType.ALL})
<del> @JoinTable(name="TroupeEvent_Attendance", joinColumns = @JoinColumn(name="event_id"),
<add> @JoinTable(name="VenueEvent_Attendance", joinColumns = @JoinColumn(name="event_id"),
<ide> inverseJoinColumns = @JoinColumn(name="playerCharacterOwnership_id"))
<del> @ForeignKey(name="TroupeEvent_PlayerCharacterOwnership_FK", inverseName="PlayerCharacterOwnership_TroupeEvent_FK")
<add> @ForeignKey(name="VenueEvent_PlayerCharacterOwnership_FK", inverseName="PlayerCharacterOwnership_TroupeEvent_FK")
<ide> private final Set<PlayerCharacterOwnership> attendance;
<ide>
<ide> //Used only for hibernate |
|
Java | mit | 4bc170428943a32db58b9022e7e1c41b6cc81010 | 0 | danfunk/MindTrails,danfunk/MindTrails,danfunk/MindTrails,danfunk/MindTrails | package org.mindtrails.controller;
import org.mindtrails.domain.ExportMode;
import org.mindtrails.domain.Participant;
import org.mindtrails.domain.RestExceptions.NoModelForFormException;
import org.mindtrails.domain.RestExceptions.WrongFormException;
import org.mindtrails.domain.questionnaire.HasReturnDate;
import org.mindtrails.domain.questionnaire.LinkedQuestionnaireData;
import org.mindtrails.domain.questionnaire.QuestionnaireData;
import org.mindtrails.service.ExportService;
import org.mindtrails.service.ParticipantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.mobile.device.Device;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.WebRequestDataBinder;
import org.springframework.web.context.request.WebRequest;
import javax.validation.Validator;
import java.security.Principal;
import java.util.Date;
/**
* Handles Form postings from Questionnaires. Expects the following:
* 1. An Html Form, whose form action = "questions/FormName"
* 2. An Entity class that describes how the form data should be stored.
* 3. A Repository Class that allows the entity to be saved to the database.
*
* If these things exist on the class path, then any data posted to the form
* will to saved to the database and accessible through the export routine.
* You do not need to add anything to this class for that to work.
*
* If you need custom data provided to your form, or if you need to perform
* a custom action after the form is submitted, you can add your own endpoint
* to this class. use "recordSessionProgress" method to record your data
* if you override the submission behavior.
*
* */
@Controller@RequestMapping("/questions")
public class QuestionController extends BaseController {
private static final Logger LOG = LoggerFactory.getLogger(QuestionController.class);
@Autowired
private ExportService exportService;
@Autowired
private ParticipantService participantService;
@Autowired
private Validator validator;
@RequestMapping(value = "{form}", method = RequestMethod.GET)
public String showForm(ModelMap model, Principal principal, @PathVariable("form") String formName) {
Participant participant = participantService.get(principal);
// It is possible that the Quesionnaire Data object will want to add some additional
// parameters to the web form.
try {
if(exportService.getDomainType(formName, false) == null) {
String message = "You are missing a model for storing data for the form " +
"'" + formName + "'";
LOG.error(message);
throw new RuntimeException(message);
}
QuestionnaireData data = (QuestionnaireData) exportService.getDomainType(formName, false).newInstance();
model.addAllAttributes(data.modelAttributes(participant));
model.addAttribute("model", data);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return ("questions/" + formName);
}
@ExportMode
@RequestMapping(value = "{form}", method = RequestMethod.POST)
public String handleForm(@PathVariable("form") String formName,
WebRequest request, ModelMap model, Principal principal,
Device device,
@RequestHeader(value="User-Agent", defaultValue="foo") String userAgent) throws Exception {
return saveForm(formName, request, model, principal, userAgent, device);
}
/**
* Handles a form submission in a standardized way. This is useful if
* you extend this class to handle a custom form submission.
*/
@ExportMode
public String saveForm(String formName, WebRequest request, ModelMap model, Principal principal, String userAgent,
Device device) {
JpaRepository repository = exportService.getRepositoryForName(formName, false);
if(repository == null) {
LOG.error("Received a post for form '" + formName +"' But no Repository exists with this name.");
throw new NoModelForFormException();
}
try {
Participant participant = participantService.get(principal);
Class<?> questionClass = exportService.getDomainType(formName, false);
QuestionnaireData data = (QuestionnaireData)questionClass.newInstance();
WebRequestDataBinder binder = new WebRequestDataBinder(data, exportService.getDomainType(formName, false).getName());
binder.bind(request);
data.setDate(new Date());
setReturnDate(participant, data);
if(data.validate(this.validator)) {
recordSessionProgress(formName, data, repository, device, userAgent);
return "redirect:/session/next";
} else {
model.addAttribute("error", "Please complete all required fields.");
model.addAllAttributes(data.modelAttributes(participant));
model.addAttribute("model", data);
return ("questions/" + formName);
}
} catch (ClassCastException | InstantiationException | IllegalAccessException e) {
LOG.error("Failed to save model '" + formName + "' : " + e.getMessage());
throw new NoModelForFormException(e);
}
}
/**
* If a questionniare implements the hasReturnDate, we should record this on the particpant
* model, and include an email invitation in the followup email messages.
*/
private void setReturnDate(Participant participant, QuestionnaireData data) {
if(data instanceof HasReturnDate) {
HasReturnDate inviteData = (HasReturnDate)data;
participant.setReturnDate(inviteData.getReturnDate());
participantService.save(participant);
}
}
/**
* Does some tasks common to all forms:
* - Adds the current CBMStudy.NAME to the data being recorded
* - Marks this "task" as complete, and moves the participant on to the next session
* - Connects the data to the participant who completed it.
* - Notifies the backup service that it may need to export data.
*
* @param data
*/
@ExportMode
protected void recordSessionProgress(String formName, QuestionnaireData data, JpaRepository repository, Device device, String userAgent) {
Participant participant;
participant = (Participant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(participantService.findByEmail(participant.getEmail()) != null)
participant = participantService.findByEmail(participant.getEmail()); // Refresh session object from database.
// Only treat this as progress in the session if the submitted task is
// a part of the regularly occurring questionnaires. Other questions, such
// as a "reason for ending" should not be recorded as making progress in the session.
boolean isProgress = participant.getStudy().isProgress(formName);
String currentTaskName = participant.getStudy().getCurrentSession().getCurrentTask().getName();
if(!currentTaskName.equals(formName) && isProgress && !participant.isAdmin()) {
String error = "The current task for this participant is : " + currentTaskName + " however, they submitted the form:" + formName;
LOG.info(error);
throw new WrongFormException(error);
}
// Grab the tag of the current task, and incorporate it into the data.
String tag = participant.getStudy().getCurrentSession().getCurrentTask().getTag();
data.setTag(tag);
// Save time on Task to TaskLog.
double timeOnTask = data.getTimeOnPage();
if(timeOnTask == 0d) throw new RuntimeException("Missing Time on Page, please add it.");
// Attempt to set the participant link, depending on sub-class type
if(data instanceof LinkedQuestionnaireData)
((LinkedQuestionnaireData) data).setParticipant(participant);
data.setSession(participant.getStudy().getCurrentSession().getName());
// Be sure to save the data BEFORE you mark it as complete in the task log. Otherwise
// it looks like its done in one place, but it isn't complete in the other. Why did I create
// such a stupid duplication of data? Because we have the delete the questionnaire data and
// move it elsewhere for security reasons. Don't you start in on me with "database hooks",
// NoSQL, query back, micro api crap. Who are you anyway, why are you even reading this? What
// do you want from me. It's late. I wanted to sleep. It works here. Don't move it.
repository.save(data);
// Update the participant's session status, and save back to the database.
if(isProgress) {
participant.getStudy().completeCurrentTask(timeOnTask, device, userAgent);
participantService.save(participant);
}
}
}
| core/src/main/java/org/mindtrails/controller/QuestionController.java | package org.mindtrails.controller;
import org.mindtrails.domain.ExportMode;
import org.mindtrails.domain.Participant;
import org.mindtrails.domain.RestExceptions.NoModelForFormException;
import org.mindtrails.domain.RestExceptions.WrongFormException;
import org.mindtrails.domain.questionnaire.HasReturnDate;
import org.mindtrails.domain.questionnaire.LinkedQuestionnaireData;
import org.mindtrails.domain.questionnaire.QuestionnaireData;
import org.mindtrails.service.ExportService;
import org.mindtrails.service.ParticipantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.mobile.device.Device;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.WebRequestDataBinder;
import org.springframework.web.context.request.WebRequest;
import javax.validation.Validator;
import java.security.Principal;
import java.util.Date;
/**
* Handles Form postings from Questionnaires. Expects the following:
* 1. An Html Form, whose form action = "questions/FormName"
* 2. An Entity class that describes how the form data should be stored.
* 3. A Repository Class that allows the entity to be saved to the database.
*
* If these things exist on the class path, then any data posted to the form
* will to saved to the database and accessible through the export routine.
* You do not need to add anything to this class for that to work.
*
* If you need custom data provided to your form, or if you need to perform
* a custom action after the form is submitted, you can add your own endpoint
* to this class. use "recordSessionProgress" method to record your data
* if you override the submission behavior.
*
* */
@Controller@RequestMapping("/questions")
public class QuestionController extends BaseController {
private static final Logger LOG = LoggerFactory.getLogger(QuestionController.class);
@Autowired
private ExportService exportService;
@Autowired
private ParticipantService participantService;
@Autowired
private Validator validator;
@RequestMapping(value = "{form}", method = RequestMethod.GET)
public String showForm(ModelMap model, Principal principal, @PathVariable("form") String formName) {
Participant participant = participantService.get(principal);
// It is possible that the Quesionnaire Data object will want to add some additional
// parameters to the web form.
try {
if(exportService.getDomainType(formName, false) == null) {
String message = "You are missing a model for storing data for the form " +
"'" + formName + "'";
LOG.error(message);
throw new RuntimeException(message);
}
QuestionnaireData data = (QuestionnaireData) exportService.getDomainType(formName, false).newInstance();
model.addAllAttributes(data.modelAttributes(participant));
model.addAttribute("model", data);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return ("questions/" + formName);
}
@ExportMode
@RequestMapping(value = "{form}", method = RequestMethod.POST)
public String handleForm(@PathVariable("form") String formName,
WebRequest request, ModelMap model, Principal principal,
Device device,
@RequestHeader(value="User-Agent", defaultValue="foo") String userAgent) throws Exception {
return saveForm(formName, request, model, principal, userAgent, device);
}
/**
* Handles a form submission in a standardized way. This is useful if
* you extend this class to handle a custom form submission.
*/
@ExportMode
public String saveForm(String formName, WebRequest request, ModelMap model, Principal principal, String userAgent,
Device device) {
JpaRepository repository = exportService.getRepositoryForName(formName, false);
if(repository == null) {
LOG.error("Received a post for form '" + formName +"' But no Repository exists with this name.");
throw new NoModelForFormException();
}
try {
Participant participant = participantService.get(principal);
Class<?> questionClass = exportService.getDomainType(formName, false);
QuestionnaireData data = (QuestionnaireData)questionClass.newInstance();
WebRequestDataBinder binder = new WebRequestDataBinder(data, exportService.getDomainType(formName, false).getName());
binder.bind(request);
data.setDate(new Date());
setReturnDate(participant, data);
if(data.validate(this.validator)) {
repository.save(data);
recordSessionProgress(formName, data, device, userAgent);
return "redirect:/session/next";
} else {
model.addAttribute("error", "Please complete all required fields.");
model.addAllAttributes(data.modelAttributes(participant));
model.addAttribute("model", data);
return ("questions/" + formName);
}
} catch (ClassCastException | InstantiationException | IllegalAccessException e) {
LOG.error("Failed to save model '" + formName + "' : " + e.getMessage());
throw new NoModelForFormException(e);
}
}
/**
* If a questionniare implements the hasReturnDate, we should record this on the particpant
* model, and include an email invitation in the followup email messages.
*/
private void setReturnDate(Participant participant, QuestionnaireData data) {
if(data instanceof HasReturnDate) {
HasReturnDate inviteData = (HasReturnDate)data;
participant.setReturnDate(inviteData.getReturnDate());
participantService.save(participant);
}
}
/**
* Does some tasks common to all forms:
* - Adds the current CBMStudy.NAME to the data being recorded
* - Marks this "task" as complete, and moves the participant on to the next session
* - Connects the data to the participant who completed it.
* - Notifies the backup service that it may need to export data.
*
* @param data
*/
@ExportMode
protected void recordSessionProgress(String formName, QuestionnaireData data, Device device, String userAgent) {
Participant participant;
participant = (Participant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(participantService.findByEmail(participant.getEmail()) != null)
participant = participantService.findByEmail(participant.getEmail()); // Refresh session object from database.
// Only treat this as progress in the session if the submitted task is
// a part of the regularly occurring questionnaires. Other questions, such
// as a "reason for ending" should not be recorded as making progress in the session.
boolean isProgress = participant.getStudy().isProgress(formName);
String currentTaskName = participant.getStudy().getCurrentSession().getCurrentTask().getName();
if(!currentTaskName.equals(formName) && isProgress && !participant.isAdmin()) {
String error = "The current task for this participant is : " + currentTaskName + " however, they submitted the form:" + formName;
LOG.info(error);
throw new WrongFormException(error);
}
// Grab the tag of the current task, and incorporate it into the data.
String tag = participant.getStudy().getCurrentSession().getCurrentTask().getTag();
data.setTag(tag);
// Save time on Task to TaskLog.
double timeOnTask = data.getTimeOnPage();
if(timeOnTask == 0d) throw new RuntimeException("Missing Time on Page, please add it.");
// Attempt to set the participant link, depending on sub-class type
if(data instanceof LinkedQuestionnaireData)
((LinkedQuestionnaireData) data).setParticipant(participant);
data.setSession(participant.getStudy().getCurrentSession().getName());
// Update the participant's session status, and save back to the database.
if(isProgress) {
participant.getStudy().completeCurrentTask(timeOnTask, device, userAgent);
participantService.save(participant);
}
}
}
| This is a slighty scary change. We would log that a questionnaire was complete before saving it. If it caused a database error, we would have the log of progress, but not the actual questionnaire record. This subtle change is risky, but important, to prevent missing data.
| core/src/main/java/org/mindtrails/controller/QuestionController.java | This is a slighty scary change. We would log that a questionnaire was complete before saving it. If it caused a database error, we would have the log of progress, but not the actual questionnaire record. This subtle change is risky, but important, to prevent missing data. | <ide><path>ore/src/main/java/org/mindtrails/controller/QuestionController.java
<ide> import org.springframework.mobile.device.Device;
<ide> import org.springframework.security.core.context.SecurityContextHolder;
<ide> import org.springframework.stereotype.Controller;
<add>import org.springframework.stereotype.Repository;
<ide> import org.springframework.ui.ModelMap;
<ide> import org.springframework.web.bind.annotation.PathVariable;
<ide> import org.springframework.web.bind.annotation.RequestHeader;
<ide> data.setDate(new Date());
<ide> setReturnDate(participant, data);
<ide> if(data.validate(this.validator)) {
<del> repository.save(data);
<del> recordSessionProgress(formName, data, device, userAgent);
<add> recordSessionProgress(formName, data, repository, device, userAgent);
<ide> return "redirect:/session/next";
<ide> } else {
<ide> model.addAttribute("error", "Please complete all required fields.");
<ide> * @param data
<ide> */
<ide> @ExportMode
<del> protected void recordSessionProgress(String formName, QuestionnaireData data, Device device, String userAgent) {
<add> protected void recordSessionProgress(String formName, QuestionnaireData data, JpaRepository repository, Device device, String userAgent) {
<ide>
<ide> Participant participant;
<ide>
<ide> if(data instanceof LinkedQuestionnaireData)
<ide> ((LinkedQuestionnaireData) data).setParticipant(participant);
<ide>
<del>
<ide> data.setSession(participant.getStudy().getCurrentSession().getName());
<add>
<add> // Be sure to save the data BEFORE you mark it as complete in the task log. Otherwise
<add> // it looks like its done in one place, but it isn't complete in the other. Why did I create
<add> // such a stupid duplication of data? Because we have the delete the questionnaire data and
<add> // move it elsewhere for security reasons. Don't you start in on me with "database hooks",
<add> // NoSQL, query back, micro api crap. Who are you anyway, why are you even reading this? What
<add> // do you want from me. It's late. I wanted to sleep. It works here. Don't move it.
<add> repository.save(data);
<ide>
<ide> // Update the participant's session status, and save back to the database.
<ide> if(isProgress) { |
|
JavaScript | apache-2.0 | 8cd635dc6d5f951ee2ee28d0eace138606ee6df0 | 0 | puppeteer/puppeteer,puppeteer/puppeteer,puppeteer/puppeteer,puppeteer/puppeteer | /**
* Copyright 2020 Google 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.
*/
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'body-max-line-length': [0, 'always', 100],
'footer-max-line-length': [0, 'always', 100],
'subject-case': [0, 'never'],
},
};
| commitlint.config.js | /**
* Copyright 2020 Google 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.
*/
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'body-max-line-length': [0, 'always', 100],
'footer-max-line-length': [0, 'always', 100],
},
};
| chore: remove subject-case rule from commitlint (#8091)
| commitlint.config.js | chore: remove subject-case rule from commitlint (#8091) | <ide><path>ommitlint.config.js
<ide> rules: {
<ide> 'body-max-line-length': [0, 'always', 100],
<ide> 'footer-max-line-length': [0, 'always', 100],
<add> 'subject-case': [0, 'never'],
<ide> },
<ide> }; |
|
Java | lgpl-2.1 | 21e2b3ec7fc3efa2730a3a8e1537320b8b731124 | 0 | fquinner/OpenMAMA,fquinner/OpenMAMA,fquinner/OpenMAMA,fquinner/OpenMAMA,fquinner/OpenMAMA,fquinner/OpenMAMA,fquinner/OpenMAMA | /* $Id$
*
* OpenMAMA: The open middleware agnostic messaging API
* Copyright (C) 2011 NYSE Technologies, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
package com.wombat.mama.junittests;
import junit.framework.*;
import com.wombat.mama.*;
/**
*
* This class will test setting a timezone on MamaDateTime and the setLogCallback function.
*/
public class MamaDateTimeSetTimeZone extends TestCase
{
/* ****************************************************** */
/* Protected Member Variables. */
/* ****************************************************** */
// The date time under test
protected MamaDateTime mDateTime;
// A time zone
protected MamaTimeZone mTimeZone;
/* ****************************************************** */
/* Protected Functions. */
/* ****************************************************** */
@Override
protected void setUp()
{
// Create the date time
mDateTime = new MamaDateTime();
// Create a new mama time zone
mTimeZone = null; // set to UTC for these tests
}
@Override
protected void tearDown()
{
// Reset member variables
mDateTime = null;
mTimeZone = null;
}
/* ****************************************************** */
/* Test Functions. */
/* ****************************************************** */
public void testSetToMidnightToday()
{
// Call the function
mDateTime.setToMidnightToday(mTimeZone);
// If we get here then the test has passed
// Check that the time is midnight
String time = mDateTime.getTimeAsString();
assertEquals(time, "00:00:00");
}
public void testSetTime()
{
// Set the time
mDateTime.setTime(3, 16, 42, 99, MamaDateTimePrecision.PREC_MICROSECONDS, mTimeZone);
// Get the time as a string
String time = mDateTime.getTimeAsString();
assertEquals(time, "03:16:42.000099");
}
public void testSetFromString()
{
// Recreate the date time using a string
mDateTime = new MamaDateTime("03:16:42.000099", mTimeZone);
// Get the time as a string
String time = mDateTime.getTimeAsString();
assertEquals(time, "03:16:42.000099");
}
public void testSetEpochTimeLargePositive()
{
mDateTime.setEpochTime (4211753600L, 0, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (4211753600.0, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (4211753600000000L, timeus);
long timems = mDateTime.getEpochTimeMilliseconds();
assertEquals (4211753600000L, timems);
}
public void testSetEpochTimeLargePositiveWithMSec()
{
mDateTime.setEpochTime (4211753600L, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (4211753600.999999, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (4211753600999999L, timeus);
long timems = mDateTime.getEpochTimeMilliseconds();
assertEquals (4211753600999L, timems);
}
public void testSetEpochTimeLargeNegative()
{
mDateTime.setEpochTime (-4211753600L, 0, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (-4211753600.0, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (-4211753600000000L, timeus);
long timems = mDateTime.getEpochTimeMilliseconds();
assertEquals (-4211753600000L, timems);
}
public void testSetEpochTimeLargeNegativeWithMSec()
{
mDateTime.setEpochTime (-4211753600L, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (-4211753599.000001, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (-4211753599000001L, timeus);
}
public void testSetEpochTimeNegativeExtreme()
{
// This test will use the largest number that can be represented as microseconds
mDateTime.setEpochTime (-9223372036854L, 0, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (-9223372036854.0, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (-9223372036854000000L, timeus);
long timems = mDateTime.getEpochTimeMilliseconds();
assertEquals (-9223372036854000L, timems);
}
public void testSetEpochTimeNegativeExtremeWithMSec()
{
// This test will use the largest number that can be represented as microseconds
mDateTime.setEpochTime (-9223372036854L, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (-9223372036853.000001, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (-9223372036853000001L, timeus);
long timems = mDateTime.getEpochTimeMilliseconds();
assertEquals (-9223372036853001L, timems);
}
public void testSetEpochTime()
{
mDateTime.setEpochTime (123456, 12, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (123456.000012, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (123456000012L, timeus);
}
public void testSetEpochTimeBigMicroSecond()
{
mDateTime.setEpochTime (123456, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (123456.999999, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (123456999999L, timeus);
}
public void testSetEpochTimeNegativeMicroSecond()
{
mDateTime.setEpochTime (123456, -123456, MamaDateTimePrecision.PREC_UNKNOWN);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (123455.876544, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (123455876544L, timeus);
}
public void testSetWithHints()
{
// The hints are never used.
mDateTime.setWithHints (123456, 12, MamaDateTimePrecision.PREC_UNKNOWN, null);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (123456.000012, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (123456000012L, timeus);
}
public void testSetWithHintsWithMSec()
{
// The hints are never used.
mDateTime.setWithHints (123456, 999999, MamaDateTimePrecision.PREC_UNKNOWN, null);
double timeDouble = mDateTime.getEpochTimeSeconds();
assertEquals (123456.999999, timeDouble);
long timeus = mDateTime.getEpochTimeMicroseconds();
assertEquals (123456999999L, timeus);
}
}
| mama/jni/src/junittests/MamaDateTimeSetTimeZone.java | /* $Id$
*
* OpenMAMA: The open middleware agnostic messaging API
* Copyright (C) 2011 NYSE Technologies, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
package com.wombat.mama.junittests;
import junit.framework.*;
import com.wombat.mama.*;
/**
*
* This class will test setting a timezone on MamaDateTime and the setLogCallback function.
*/
public class MamaDateTimeSetTimeZone extends TestCase
{
/* ****************************************************** */
/* Protected Member Variables. */
/* ****************************************************** */
// The date time under test
protected MamaDateTime mDateTime;
// A time zone
protected MamaTimeZone mTimeZone;
/* ****************************************************** */
/* Protected Functions. */
/* ****************************************************** */
@Override
protected void setUp()
{
// Create the date time
mDateTime = new MamaDateTime();
// Create a new mama time zone
mTimeZone = null; // set to UTC for these tests
}
@Override
protected void tearDown()
{
// Reset member variables
mDateTime = null;
mTimeZone = null;
}
/* ****************************************************** */
/* Test Functions. */
/* ****************************************************** */
public void testSetToMidnightToday()
{
// Call the function
mDateTime.setToMidnightToday(mTimeZone);
// If we get here then the test has passed
// Check that the time is midnight
String time = mDateTime.getTimeAsString();
assertEquals(time, "00:00:00");
}
public void testSetTime()
{
// Set the time
mDateTime.setTime(3, 16, 42, 99, MamaDateTimePrecision.PREC_MICROSECONDS, mTimeZone);
// Get the time as a string
String time = mDateTime.getTimeAsString();
assertEquals(time, "03:16:42.000099");
}
public void testSetFromString()
{
// Recreate the date time using a string
mDateTime = new MamaDateTime("03:16:42.000099", mTimeZone);
// Get the time as a string
String time = mDateTime.getTimeAsString();
assertEquals(time, "03:16:42.000099");
}
}
| PLAT-971: Junittests for PLAT-773
Some new Junittests for extended datetimes
Signed-off-by: Gary Molloy <[email protected]>
| mama/jni/src/junittests/MamaDateTimeSetTimeZone.java | PLAT-971: Junittests for PLAT-773 | <ide><path>ama/jni/src/junittests/MamaDateTimeSetTimeZone.java
<ide> String time = mDateTime.getTimeAsString();
<ide> assertEquals(time, "03:16:42.000099");
<ide> }
<add>
<add> public void testSetEpochTimeLargePositive()
<add> {
<add> mDateTime.setEpochTime (4211753600L, 0, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (4211753600.0, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (4211753600000000L, timeus);
<add> long timems = mDateTime.getEpochTimeMilliseconds();
<add> assertEquals (4211753600000L, timems);
<add> }
<add>
<add>
<add> public void testSetEpochTimeLargePositiveWithMSec()
<add> {
<add> mDateTime.setEpochTime (4211753600L, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (4211753600.999999, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (4211753600999999L, timeus);
<add> long timems = mDateTime.getEpochTimeMilliseconds();
<add> assertEquals (4211753600999L, timems);
<add> }
<add>
<add> public void testSetEpochTimeLargeNegative()
<add> {
<add> mDateTime.setEpochTime (-4211753600L, 0, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (-4211753600.0, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (-4211753600000000L, timeus);
<add> long timems = mDateTime.getEpochTimeMilliseconds();
<add> assertEquals (-4211753600000L, timems);
<add> }
<add>
<add>
<add> public void testSetEpochTimeLargeNegativeWithMSec()
<add> {
<add> mDateTime.setEpochTime (-4211753600L, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (-4211753599.000001, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (-4211753599000001L, timeus);
<add> }
<add>
<add> public void testSetEpochTimeNegativeExtreme()
<add> {
<add> // This test will use the largest number that can be represented as microseconds
<add> mDateTime.setEpochTime (-9223372036854L, 0, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (-9223372036854.0, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (-9223372036854000000L, timeus);
<add> long timems = mDateTime.getEpochTimeMilliseconds();
<add> assertEquals (-9223372036854000L, timems);
<add> }
<add>
<add>
<add> public void testSetEpochTimeNegativeExtremeWithMSec()
<add> {
<add> // This test will use the largest number that can be represented as microseconds
<add> mDateTime.setEpochTime (-9223372036854L, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (-9223372036853.000001, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (-9223372036853000001L, timeus);
<add> long timems = mDateTime.getEpochTimeMilliseconds();
<add> assertEquals (-9223372036853001L, timems);
<add> }
<add>
<add> public void testSetEpochTime()
<add> {
<add> mDateTime.setEpochTime (123456, 12, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (123456.000012, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (123456000012L, timeus);
<add> }
<add>
<add>
<add> public void testSetEpochTimeBigMicroSecond()
<add> {
<add> mDateTime.setEpochTime (123456, 999999, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (123456.999999, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (123456999999L, timeus);
<add> }
<add>
<add> public void testSetEpochTimeNegativeMicroSecond()
<add> {
<add> mDateTime.setEpochTime (123456, -123456, MamaDateTimePrecision.PREC_UNKNOWN);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (123455.876544, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (123455876544L, timeus);
<add> }
<add>
<add> public void testSetWithHints()
<add> {
<add> // The hints are never used.
<add> mDateTime.setWithHints (123456, 12, MamaDateTimePrecision.PREC_UNKNOWN, null);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (123456.000012, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (123456000012L, timeus);
<add> }
<add>
<add> public void testSetWithHintsWithMSec()
<add> {
<add> // The hints are never used.
<add> mDateTime.setWithHints (123456, 999999, MamaDateTimePrecision.PREC_UNKNOWN, null);
<add>
<add> double timeDouble = mDateTime.getEpochTimeSeconds();
<add> assertEquals (123456.999999, timeDouble);
<add>
<add> long timeus = mDateTime.getEpochTimeMicroseconds();
<add> assertEquals (123456999999L, timeus);
<add> }
<ide> } |
|
Java | apache-2.0 | 07391aac445a1e4e61bb96edad55c67dde4fa542 | 0 | ricomaster9000/sageOneApiLibrary-SA,ricomaster9000/sageOneApiLibrary-GLOBAL | /**
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 SageOneIntegration.SageOneApiEntities;
import java.sql.Date;
/**
* Created by ricardo on 2017/05/30.
*/
public final class SageOneCompany {
private Integer ID;
private String Name;
private String CurrencySymbol;
private Integer CurrencyDecimalDigits;
private Integer NumberDecimalDigits;
private String DecimalSeparator;
private Integer HoursDecimalDigits;
private Integer ItemCostPriceDecimalDigits;
private Integer ItemSellingPriceDecimalDigits;
private String PostalAddress1 = "";
private String PostalAddress2 = "";
private String PostalAddress3 = "";
private String PostalAddress4 = "";
private String PostalAddress5 = "";
private String GroupSeparator = "";
private Integer RoundingValue;
private SageOneTaxSystemClass TaxSystem;
private SageOneRoundingTypeClass RoundingType;
private boolean AgeMonthly;
private boolean DisplayInactiveItems;
private boolean WarnWhenItemCostIsZero;
private boolean DoNotAllowProcessingIntoNegativeQuantities;
private boolean WarnWhenItemQuantityIsZero;
private boolean WarnWhenItemSellingBelowCost;
private Integer CountryId;
private Integer CompanyEntityTypeId;
private Date TakeOnBalanceDate;
private boolean EnableCustomerZone;
private boolean EnableAutomaticBankFeedRefresh;
private String ContactName;
private String Telephone;
private String Fax;
private String Mobile;
private String Email;
private boolean IsPrimarySendingEmail;
private String PostalAddress01 = "";
private String PostalAddress02 = "";
private String PostalAddress03 = "";
private String PostalAddress04 = "";
private String PostalAddress05 = "";
private String CompanyInfo01;
private String CompanyInfo02;
private String CompanyInfo03;
private String CompanyInfo04;
private String CompanyInfo05;
private boolean IsOwner;
private boolean UseCCEmail;
private String CCEmail;
private Integer DateFormatId;
private boolean CheckForDuplicateCustomerReferences;
private boolean CheckForDuplicateSupplierReferences;
private String DisplayName;
private boolean DisplayInactiveCustomers;
private boolean DisplayInactiveSuppliers;
private boolean DisplayInactiveTimeProjects;
private boolean UseInclusiveProcessingByDefault;
private boolean LockProcessing;
private Date LockProcessingDate;
private boolean LockTimesheetProcessing;
private Date LockTimesheetProcessingDate;
private Integer TaxPeriodFrequency;
private Date PreviousTaxPeriodEndDate;
private Date PreviousTaxReturnDate;
private boolean UseNoreplyEmail;
private boolean AgeingBasedOnDueDate;
private boolean UseLogoOnEmails;
private boolean UseLogoOnCustomerZone;
private String City;
private String State;
private String Country;
private Integer HomeCurrencyId;
private Integer CurrencyId;
private Date Created;
private Date Modified;
private boolean Active;
private String TaxNumber;
private String RegisteredName;
private String RegistrationNumber;
private boolean IsPracticeAccount;
private Integer LogoPositionID;
private SageOneCompanyLogoClass Attachment;
private String CompanyTaxNumber;
private String TaxOffice;
private String CustomerZoneGuid;
private Integer ClientTypeId;
private Integer DisplayTotalTypeId;
private boolean DisplayInCompanyConsole;
private Date LastLoginDate;
private SageOneCompanyStatus Status;
public Integer getId() {
return ID;
}
public final String getName() {
return this.Name;
}
public final void setName(final String Name) {
this.Name = Name;
}
public final String getCurrencySymbol() {
return this.CurrencySymbol;
}
public final void setCurrencySymbol(final String CurrencySymbol) {
this.CurrencySymbol = CurrencySymbol;
}
public final Integer getCurrencyDecimalDigits() {
return this.CurrencyDecimalDigits;
}
public final void setCurrencyDecimalDigits(final Integer CurrencyDecimalDigits) {
this.CurrencyDecimalDigits = CurrencyDecimalDigits;
}
public final Integer getNumberDecimalDigits() {
return this.NumberDecimalDigits;
}
public final void setNumberDecimalDigits(final Integer NumberDecimalDigits) {
this.NumberDecimalDigits = NumberDecimalDigits;
}
public final String getDecimalSeparator() {
return this.DecimalSeparator;
}
public final void setDecimalSeparator(final String DecimalSeparator) {
this.DecimalSeparator = DecimalSeparator;
}
public final Integer getHoursDecimalDigits() {
return this.HoursDecimalDigits;
}
public final void setHoursDecimalDigits(final Integer HoursDecimalDigits) {
this.HoursDecimalDigits = HoursDecimalDigits;
}
public final Integer getItemCostPriceDecimalDigits() {
return this.ItemCostPriceDecimalDigits;
}
public final void setItemCostPriceDecimalDigits(final Integer ItemCostPriceDecimalDigits) {
this.ItemCostPriceDecimalDigits = ItemCostPriceDecimalDigits;
}
public final Integer getItemSellingPriceDecimalDigits() {
return this.ItemSellingPriceDecimalDigits;
}
public final void setItemSellingPriceDecimalDigits(final Integer ItemSellingPriceDecimalDigits) {
this.ItemSellingPriceDecimalDigits = ItemSellingPriceDecimalDigits;
}
public final String getPostalAddress1() {
return this.PostalAddress1;
}
public final void setPostalAddress1(final String PostalAddress1) {
this.PostalAddress1 = PostalAddress1;
}
public final String getPostalAddress2() {
return this.PostalAddress2;
}
public final void setPostalAddress2(final String PostalAddress2) {
this.PostalAddress2 = PostalAddress2;
}
public final String getPostalAddress3() {
return this.PostalAddress3;
}
public final void setPostalAddress3(final String PostalAddress3) {
this.PostalAddress3 = PostalAddress3;
}
public final String getPostalAddress4() {
return this.PostalAddress4;
}
public final void setPostalAddress4(final String PostalAddress4) {
this.PostalAddress2 = PostalAddress2;
}
public final String getPostalAddress5() {
return this.PostalAddress5;
}
public final void setPostalAddress5(final String PostalAddress5) {
this.PostalAddress5 = PostalAddress5;
}
public final String getGroupSeparator() {
return this.GroupSeparator;
}
public final void setGroupSeparator(final String GroupSeparator) {
this.GroupSeparator = GroupSeparator;
}
public final Integer getRoundingValue() {
return this.RoundingValue;
}
public final void setRoundingValue(final int RoundingValue) {
this.RoundingValue = RoundingValue;
}
public final SageOneTaxSystemClass getTaxSystem() {
return this.TaxSystem;
}
public final void setTaxSystem(final SageOneTaxSystemClass TaxSystem) {
this.TaxSystem = TaxSystem;
}
public final SageOneRoundingTypeClass getRoundingType() {
return this.RoundingType;
}
public final void setRoundingType(final SageOneRoundingTypeClass RoundingType) {
this.RoundingType = RoundingType;
}
public final boolean getAgeMonthly() {
return this.AgeMonthly;
}
public final void setAgeMonthly(final boolean AgeMonthly) {
this.AgeMonthly = AgeMonthly;
}
public final boolean getDisplayInactiveItems() {
return this.DisplayInactiveItems;
}
public final void setDisplayInactiveItems(final boolean DisplayInactiveItems) {
this.DisplayInactiveItems = DisplayInactiveItems;
}
public final boolean getWarnWhenItemCostIsZero() {
return this.WarnWhenItemCostIsZero;
}
public final void setWarnWhenItemCostIsZero(final boolean WarnWhenItemCostIsZero) {
this.WarnWhenItemCostIsZero = WarnWhenItemCostIsZero;
}
public final boolean getDoNotAllowProcessingIntoNegativeQuantities() {
return this.DoNotAllowProcessingIntoNegativeQuantities;
}
public final void setDoNotAllowProcessingIntoNegativeQuantities(final boolean DoNotAllowProcessingIntoNegativeQuantities) {
this.DoNotAllowProcessingIntoNegativeQuantities = DoNotAllowProcessingIntoNegativeQuantities;
}
public final boolean getWarnWhenItemQuantityIsZero() {
return this.WarnWhenItemQuantityIsZero;
}
public final void setWarnWhenItemQuantityIsZero(final boolean WarnWhenItemQuantityIsZero) {
this.WarnWhenItemQuantityIsZero = WarnWhenItemQuantityIsZero;
}
public final boolean getWarnWhenItemSellingBelowCost() {
return this.WarnWhenItemSellingBelowCost;
}
public final void setWarnWhenItemSellingBelowCost(final boolean WarnWhenItemSellingBelowCost) {
this.WarnWhenItemSellingBelowCost = WarnWhenItemSellingBelowCost;
}
public final Integer getCountryId() {
return this.CountryId;
}
public final void setCountryId(final Integer CountryId) {
this.CountryId = CountryId;
}
public final Integer getCompanyEntityTypeId() {
return this.CompanyEntityTypeId;
}
public final void setCompanyEntityTypeId(final Integer CompanyEntityTypeId) {
this.CompanyEntityTypeId = CompanyEntityTypeId;
}
public final Date getTakeOnBalanceDate() {
return this.TakeOnBalanceDate;
}
public final void TakeOnBalanceDate(final Date TakeOnBalanceDate) {
this.TakeOnBalanceDate = TakeOnBalanceDate;
}
public final boolean getEnableCustomerZone() {
return this.EnableCustomerZone;
}
public final void setEnableCustomerZone(final boolean EnableCustomerZone) {
this.EnableCustomerZone = EnableCustomerZone;
}
public final boolean getEnableAutomaticBankFeedRefresh() {
return this.EnableAutomaticBankFeedRefresh;
}
public final void setEnableAutomaticBankFeedRefresh(final boolean EnableAutomaticBankFeedRefresh) {
this.EnableAutomaticBankFeedRefresh = EnableAutomaticBankFeedRefresh;
}
public final String getContactName() {
return this.ContactName;
}
public final void setContactName(final String ContactName) {
this.ContactName = ContactName;
}
public final String getTelephone() {
return this.Telephone;
}
public final void setTelephone(final String Telephone) {
this.Telephone = Telephone;
}
public final String getFax() {
return this.Fax;
}
public final void setFax(final String Fax) {
this.Fax = Fax;
}
public final String getMobile() {
return this.Mobile;
}
public final void setMobile(final String Mobile) {
this.Mobile = Mobile;
}
public final String getEmail() {
return this.Email;
}
public final void setEmail(final String Email) {
this.Email = Email;
}
public final boolean getIsPrimarySendingEmail() {
return this.IsPrimarySendingEmail;
}
public final void setIsPrimarySendingEmail(final boolean IsPrimarySendingEmail) {
this.IsPrimarySendingEmail = IsPrimarySendingEmail;
}
public final String getPostalAddress01() {
return this.PostalAddress01;
}
public final void setPostalAddress01(final String PostalAddress01) {
this.PostalAddress01 = PostalAddress01;
}
public final String getPostalAddress02() {
return this.PostalAddress02;
}
public final void setPostalAddress02(final String PostalAddress02) {
this.PostalAddress02 = PostalAddress02;
}
public final String getPostalAddress03() {
return this.PostalAddress03;
}
public final void setPostalAddress03(final String PostalAddress03) {
this.PostalAddress03 = PostalAddress03;
}
public final String getPostalAddress04() {
return this.PostalAddress04;
}
public final void setPostalAddress04(final String PostalAddress04) {
this.PostalAddress04 = PostalAddress04;
}
public final String getPostalAddress05() {
return this.PostalAddress05;
}
public final void setPostalAddress05(final String PostalAddress05) {
this.PostalAddress05 = PostalAddress05;
}
public final String getCompanyInfo01() {
return this.CompanyInfo01;
}
public final void setCompanyInfo01(final String CompanyInfo01) {
this.CompanyInfo01 = CompanyInfo01;
}
public final String getCompanyInfo02() {
return this.CompanyInfo02;
}
public final void setCompanyInfo02(final String CompanyInfo02) {
this.CompanyInfo02 = CompanyInfo02;
}
public final String getCompanyInfo03() {
return this.CompanyInfo03;
}
public final void setCompanyInfo03(final String CompanyInfo03) {
this.CompanyInfo03 = CompanyInfo03;
}
public final String getCompanyInfo04() {
return this.CompanyInfo04;
}
public final void setCompanyInfo04(final String CompanyInfo04) {
this.CompanyInfo04 = CompanyInfo04;
}
public final String getCompanyInfo05() {
return this.CompanyInfo05;
}
public final void setCompanyInfo05(final String CompanyInfo05) {
this.CompanyInfo05 = CompanyInfo05;
}
public final boolean getIsOwner() {
return this.IsOwner;
}
public final void setIsOwner(final boolean IsOwner) {
this.IsOwner = IsOwner;
}
public final boolean getUseCCEmail() {
return this.UseCCEmail;
}
public final void setUseCCEmail(final boolean UseCCEmail) {
this.UseCCEmail = UseCCEmail;
}
public final String getCCEmail() {
return this.CCEmail;
}
public final void setCCEmail(final String CCEmail) {
this.CCEmail = CCEmail;
}
public final Integer getDateFormatId() {
return this.DateFormatId;
}
public final void setDateFormatId(final Integer DateFormatId) {
this.DateFormatId = DateFormatId;
}
public final boolean getCheckForDuplicateCustomerReferences() {
return this.CheckForDuplicateCustomerReferences;
}
public final void setCheckForDuplicateCustomerReferences(final boolean CheckForDuplicateCustomerReferences) {
this.CheckForDuplicateCustomerReferences = CheckForDuplicateCustomerReferences;
}
public final boolean getCheckForDuplicateSupplierReferences() {
return this.CheckForDuplicateSupplierReferences;
}
public final void setCheckForDuplicateSupplierReferences(final boolean CheckForDuplicateSupplierReferences) {
this.CheckForDuplicateSupplierReferences = CheckForDuplicateSupplierReferences;
}
public final String getDisplayName() {
return this.DisplayName;
}
public final void setDisplayName(final String DisplayName) {
this.DisplayName = DisplayName;
}
public final boolean getDisplayInactiveCustomers() {
return this.DisplayInactiveCustomers;
}
public final void setDisplayInactiveCustomers(final boolean DisplayInactiveCustomers) {
this.DisplayInactiveCustomers = DisplayInactiveCustomers;
}
public final boolean getDisplayInactiveSuppliers() {
return this.DisplayInactiveSuppliers;
}
public final void setDisplayInactiveSuppliers(final boolean DisplayInactiveSuppliers) {
this.DisplayInactiveSuppliers = DisplayInactiveSuppliers;
}
public final boolean getDisplayInactiveTimeProjects() {
return this.DisplayInactiveTimeProjects;
}
public final void setDisplayInactiveTimeProjects(final boolean DisplayInactiveTimeProjects) {
this.DisplayInactiveTimeProjects = DisplayInactiveTimeProjects;
}
public final boolean getUseInclusiveProcessingByDefault() {
return this.UseInclusiveProcessingByDefault;
}
public final void setUseInclusiveProcessingByDefault(final boolean UseInclusiveProcessingByDefault) {
this.UseInclusiveProcessingByDefault = UseInclusiveProcessingByDefault;
}
public final boolean getLockProcessing() {
return this.LockProcessing;
}
public final void setLockProcessing(final boolean LockProcessing) {
this.LockProcessing = LockProcessing;
}
public final Date getLockProcessingDate() {
return this.LockProcessingDate;
}
public final void setLockProcessingDate(final Date LockProcessingDate) {
this.LockProcessingDate = LockProcessingDate;
}
public final boolean getLockTimesheetProcessing() {
return this.LockTimesheetProcessing;
}
public final void setLockTimesheetProcessing(final boolean LockTimesheetProcessing) {
this.LockTimesheetProcessing = LockTimesheetProcessing;
}
public final Date getLockTimesheetProcessingDate() {
return this.LockTimesheetProcessingDate;
}
public final void setLockTimesheetProcessingDate(final Date LockTimesheetProcessingDate) {
this.LockTimesheetProcessingDate = LockTimesheetProcessingDate;
}
public final int getTaxPeriodFrequency() {
return this.TaxPeriodFrequency;
}
public final void setTaxPeriodFrequency(final int TaxPeriodFrequency) {
this.TaxPeriodFrequency = TaxPeriodFrequency;
}
public final Date getPreviousTaxPeriodEndDate() {
return this.PreviousTaxPeriodEndDate;
}
public final void setPreviousTaxPeriodEndDate(final Date PreviousTaxPeriodEndDate) {
this.PreviousTaxPeriodEndDate = PreviousTaxPeriodEndDate;
}
public final Date getPreviousTaxReturnDate() {
return this.PreviousTaxReturnDate;
}
public final void setPreviousTaxReturnDate(final Date PreviousTaxReturnDate) {
this.PreviousTaxReturnDate = PreviousTaxReturnDate;
}
public final boolean getUseNoreplyEmail() {
return this.UseNoreplyEmail;
}
public final void setUseNoreplyEmail(final boolean UseNoreplyEmail) {
this.UseNoreplyEmail = UseNoreplyEmail;
}
public final boolean getAgeingBasedOnDueDate() {
return this.AgeingBasedOnDueDate;
}
public final void setAgeingBasedOnDueDate(final boolean AgeingBasedOnDueDate) {
this.AgeingBasedOnDueDate = AgeingBasedOnDueDate;
}
public final boolean getUseLogoOnEmails() {
return this.UseLogoOnEmails;
}
public final void setUseLogoOnEmails(final boolean UseLogoOnEmails) {
this.UseLogoOnEmails = UseLogoOnEmails;
}
public final boolean getUseLogoOnCustomerZone() {
return this.UseLogoOnCustomerZone;
}
public final void setUseLogoOnCustomerZone(final boolean UseLogoOnCustomerZone) {
this.UseLogoOnCustomerZone = UseLogoOnCustomerZone;
}
public final String getCity() {
return this.City;
}
public final void setCity(final String City) {
this.City = City;
}
public final String getState() {
return this.State;
}
public final void setState(final String State) {
this.State = State;
}
public final String getCountry() {
return this.Country;
}
public final void setCountry(final String Country) {
this.Country = Country;
}
public final Integer getHomeCurrencyId() {
return this.HomeCurrencyId;
}
public final void setHomeCurrencyId(final Integer HomeCurrencyId) {
this.HomeCurrencyId = HomeCurrencyId;
}
public final Integer getCurrencyId() {
return this.CurrencyId;
}
public final void setCurrencyId(final Integer CurrencyId) {
this.CurrencyId = CurrencyId;
}
public final Date getCreated() {
return this.Created;
}
public final void setCreated(final Date Created) {
this.Created = Created;
}
public final Date getModified() {
return this.Modified;
}
public final void setModified(final Date Modified) {
this.Modified = Modified;
}
public final boolean getActive() {
return this.Active;
}
public final void setActive(final boolean Active) {
this.Active = Active;
}
public final String getTaxNumber() {
return this.TaxNumber;
}
public final void setTaxNumber(final String TaxNumber) {
this.TaxNumber = TaxNumber;
}
public final String getRegisteredName() {
return this.RegisteredName;
}
public final void setRegisteredName(final String RegisteredName) {
this.RegisteredName = RegisteredName;
}
public final String getRegistrationNumber() {
return this.RegistrationNumber;
}
public final void setRegistrationNumber(final String RegistrationNumber) {
this.RegistrationNumber = RegistrationNumber;
}
public final boolean getIsPracticeAccount() {
return this.IsPracticeAccount;
}
public final void setIsPracticeAccount(final boolean IsPracticeAccount) {
this.IsPracticeAccount = IsPracticeAccount;
}
public final Integer getLogoPositionID() {
return this.LogoPositionID;
}
public final void setLogoPositionID(final Integer LogoPositionID) {
this.LogoPositionID = LogoPositionID;
}
public final SageOneCompanyLogoClass getAttachment() {
return this.Attachment;
}
public final void setAttachment(final SageOneCompanyLogoClass Attachment) {
this.Attachment = Attachment;
}
public final String getCompanyTaxNumber() {
return this.CompanyTaxNumber;
}
public final void setCompanyTaxNumber(final String CompanyTaxNumber) {
this.CompanyTaxNumber = CompanyTaxNumber;
}
public final String getTaxOffice() {
return this.TaxOffice;
}
public final void setTaxOffice(final String TaxOffice) {
this.TaxOffice = TaxOffice;
}
public final String getCustomerZoneGuid() {
return this.CustomerZoneGuid;
}
public final void setCustomerZoneGuid(final String CustomerZoneGuid) {
this.CustomerZoneGuid = CustomerZoneGuid;
}
public final Integer getClientTypeId() {
return this.ClientTypeId;
}
public final void setClientTypeId(final Integer ClientTypeId) {
this.ClientTypeId = ClientTypeId;
}
public final Integer getDisplayTotalTypeId() {
return this.DisplayTotalTypeId;
}
public final void setDisplayTotalTypeId(final Integer DisplayTotalTypeId) {
this.DisplayTotalTypeId = DisplayTotalTypeId;
}
public final boolean getDisplayInCompanyConsole() {
return this.DisplayInCompanyConsole;
}
public final void setDisplayInCompanyConsole(final boolean DisplayInCompanyConsole) {
this.DisplayInCompanyConsole = DisplayInCompanyConsole;
}
public final Date getLastLoginDate() {
return this.LastLoginDate;
}
public final void setLastLoginDate(final Date LastLoginDate) {
this.LastLoginDate = LastLoginDate;
}
public final SageOneCompanyStatus getStatus() {
return this.Status;
}
public final void setStatus(final SageOneCompanyStatus Status) {
this.Status = Status;
}
}
| src/main/java/SageOneIntegration/SageOneApiEntities/SageOneCompany.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 SageOneIntegration.SageOneApiEntities;
import java.sql.Date;
/**
* Created by ricardo on 2017/05/30.
*/
public final class SageOneCompany {
private Integer ID;
private String Name;
private String CurrencySymbol;
private Integer CurrencyDecimalDigits;
private Integer NumberDecimalDigits;
private String DecimalSeparator;
private Integer HoursDecimalDigits;
private Integer ItemCostPriceDecimalDigits;
private Integer ItemSellingPriceDecimalDigits;
private String PostalAddress1 = "";
private String PostalAddress2 = "";
private String PostalAddress3 = "";
private String PostalAddress4 = "";
private String PostalAddress5 = "";
private String GroupSeparator = "";
private Integer RoundingValue;
private SageOneTaxSystemClass TaxSystem;
private SageOneRoundingTypeClass RoundingType;
private boolean AgeMonthly;
private boolean DisplayInactiveItems;
private boolean WarnWhenItemCostIsZero;
private boolean DoNotAllowProcessingIntoNegativeQuantities;
private boolean WarnWhenItemQuantityIsZero;
private boolean WarnWhenItemSellingBelowCost;
private Integer CountryId;
private Integer CompanyEntityTypeId;
private Date TakeOnBalanceDate;
private boolean EnableCustomerZone;
private boolean EnableAutomaticBankFeedRefresh;
private String ContactName;
private String Telephone;
private String Fax;
private String Mobile;
private String Email;
private boolean IsPrimarySendingEmail;
private String PostalAddress01 = "";
private String PostalAddress02 = "";
private String PostalAddress03 = "";
private String PostalAddress04 = "";
private String PostalAddress05 = "";
private String CompanyInfo01;
private String CompanyInfo02;
private String CompanyInfo03;
private String CompanyInfo04;
private String CompanyInfo05;
private boolean IsOwner;
private boolean UseCCEmail;
private String CCEmail;
private Integer DateFormatId;
private boolean CheckForDuplicateCustomerReferences;
private boolean CheckForDuplicateSupplierReferences;
private String DisplayName;
private boolean DisplayInactiveCustomers;
private boolean DisplayInactiveSuppliers;
private boolean DisplayInactiveTimeProjects;
private boolean UseInclusiveProcessingByDefault;
private boolean LockProcessing;
private Date LockProcessingDate;
private boolean LockTimesheetProcessing;
private Date LockTimesheetProcessingDate;
private Integer TaxPeriodFrequency;
private Date PreviousTaxPeriodEndDate;
private Date PreviousTaxReturnDate;
private boolean UseNoreplyEmail;
private boolean AgeingBasedOnDueDate;
private boolean UseLogoOnEmails;
private boolean UseLogoOnCustomerZone;
private String City;
private String State;
private String Country;
private Integer HomeCurrencyId;
private Integer CurrencyId;
private Date Created;
private Date Modified;
private boolean Active;
private String TaxNumber;
private String RegisteredName;
private String RegistrationNumber;
private boolean IsPracticeAccount;
private Integer LogoPositionID;
private SageOneCompanyLogoClass Attachment;
private String CompanyTaxNumber;
private String TaxOffice;
private String CustomerZoneGuid;
private Integer ClientTypeId;
private Integer DisplayTotalTypeId;
private boolean DisplayInCompanyConsole;
private Date LastLoginDate;
private SageOneCompanyStatus Status;
public final String getName() {
return this.Name;
}
public final void setName(final String Name) {
this.Name = Name;
}
public final String getCurrencySymbol() {
return this.CurrencySymbol;
}
public final void setCurrencySymbol(final String CurrencySymbol) {
this.CurrencySymbol = CurrencySymbol;
}
public final Integer getCurrencyDecimalDigits() {
return this.CurrencyDecimalDigits;
}
public final void setCurrencyDecimalDigits(final Integer CurrencyDecimalDigits) {
this.CurrencyDecimalDigits = CurrencyDecimalDigits;
}
public final Integer getNumberDecimalDigits() {
return this.NumberDecimalDigits;
}
public final void setNumberDecimalDigits(final Integer NumberDecimalDigits) {
this.NumberDecimalDigits = NumberDecimalDigits;
}
public final String getDecimalSeparator() {
return this.DecimalSeparator;
}
public final void setDecimalSeparator(final String DecimalSeparator) {
this.DecimalSeparator = DecimalSeparator;
}
public final Integer getHoursDecimalDigits() {
return this.HoursDecimalDigits;
}
public final void setHoursDecimalDigits(final Integer HoursDecimalDigits) {
this.HoursDecimalDigits = HoursDecimalDigits;
}
public final Integer getItemCostPriceDecimalDigits() {
return this.ItemCostPriceDecimalDigits;
}
public final void setItemCostPriceDecimalDigits(final Integer ItemCostPriceDecimalDigits) {
this.ItemCostPriceDecimalDigits = ItemCostPriceDecimalDigits;
}
public final Integer getItemSellingPriceDecimalDigits() {
return this.ItemSellingPriceDecimalDigits;
}
public final void setItemSellingPriceDecimalDigits(final Integer ItemSellingPriceDecimalDigits) {
this.ItemSellingPriceDecimalDigits = ItemSellingPriceDecimalDigits;
}
public final String getPostalAddress1() {
return this.PostalAddress1;
}
public final void setPostalAddress1(final String PostalAddress1) {
this.PostalAddress1 = PostalAddress1;
}
public final String getPostalAddress2() {
return this.PostalAddress2;
}
public final void setPostalAddress2(final String PostalAddress2) {
this.PostalAddress2 = PostalAddress2;
}
public final String getPostalAddress3() {
return this.PostalAddress3;
}
public final void setPostalAddress3(final String PostalAddress3) {
this.PostalAddress3 = PostalAddress3;
}
public final String getPostalAddress4() {
return this.PostalAddress4;
}
public final void setPostalAddress4(final String PostalAddress4) {
this.PostalAddress2 = PostalAddress2;
}
public final String getPostalAddress5() {
return this.PostalAddress5;
}
public final void setPostalAddress5(final String PostalAddress5) {
this.PostalAddress5 = PostalAddress5;
}
public final String getGroupSeparator() {
return this.GroupSeparator;
}
public final void setGroupSeparator(final String GroupSeparator) {
this.GroupSeparator = GroupSeparator;
}
public final Integer getRoundingValue() {
return this.RoundingValue;
}
public final void setRoundingValue(final int RoundingValue) {
this.RoundingValue = RoundingValue;
}
public final SageOneTaxSystemClass getTaxSystem() {
return this.TaxSystem;
}
public final void setTaxSystem(final SageOneTaxSystemClass TaxSystem) {
this.TaxSystem = TaxSystem;
}
public final SageOneRoundingTypeClass getRoundingType() {
return this.RoundingType;
}
public final void setRoundingType(final SageOneRoundingTypeClass RoundingType) {
this.RoundingType = RoundingType;
}
public final boolean getAgeMonthly() {
return this.AgeMonthly;
}
public final void setAgeMonthly(final boolean AgeMonthly) {
this.AgeMonthly = AgeMonthly;
}
public final boolean getDisplayInactiveItems() {
return this.DisplayInactiveItems;
}
public final void setDisplayInactiveItems(final boolean DisplayInactiveItems) {
this.DisplayInactiveItems = DisplayInactiveItems;
}
public final boolean getWarnWhenItemCostIsZero() {
return this.WarnWhenItemCostIsZero;
}
public final void setWarnWhenItemCostIsZero(final boolean WarnWhenItemCostIsZero) {
this.WarnWhenItemCostIsZero = WarnWhenItemCostIsZero;
}
public final boolean getDoNotAllowProcessingIntoNegativeQuantities() {
return this.DoNotAllowProcessingIntoNegativeQuantities;
}
public final void setDoNotAllowProcessingIntoNegativeQuantities(final boolean DoNotAllowProcessingIntoNegativeQuantities) {
this.DoNotAllowProcessingIntoNegativeQuantities = DoNotAllowProcessingIntoNegativeQuantities;
}
public final boolean getWarnWhenItemQuantityIsZero() {
return this.WarnWhenItemQuantityIsZero;
}
public final void setWarnWhenItemQuantityIsZero(final boolean WarnWhenItemQuantityIsZero) {
this.WarnWhenItemQuantityIsZero = WarnWhenItemQuantityIsZero;
}
public final boolean getWarnWhenItemSellingBelowCost() {
return this.WarnWhenItemSellingBelowCost;
}
public final void setWarnWhenItemSellingBelowCost(final boolean WarnWhenItemSellingBelowCost) {
this.WarnWhenItemSellingBelowCost = WarnWhenItemSellingBelowCost;
}
public final Integer getCountryId() {
return this.CountryId;
}
public final void setCountryId(final Integer CountryId) {
this.CountryId = CountryId;
}
public final Integer getCompanyEntityTypeId() {
return this.CompanyEntityTypeId;
}
public final void setCompanyEntityTypeId(final Integer CompanyEntityTypeId) {
this.CompanyEntityTypeId = CompanyEntityTypeId;
}
public final Date getTakeOnBalanceDate() {
return this.TakeOnBalanceDate;
}
public final void TakeOnBalanceDate(final Date TakeOnBalanceDate) {
this.TakeOnBalanceDate = TakeOnBalanceDate;
}
public final boolean getEnableCustomerZone() {
return this.EnableCustomerZone;
}
public final void setEnableCustomerZone(final boolean EnableCustomerZone) {
this.EnableCustomerZone = EnableCustomerZone;
}
public final boolean getEnableAutomaticBankFeedRefresh() {
return this.EnableAutomaticBankFeedRefresh;
}
public final void setEnableAutomaticBankFeedRefresh(final boolean EnableAutomaticBankFeedRefresh) {
this.EnableAutomaticBankFeedRefresh = EnableAutomaticBankFeedRefresh;
}
public final String getContactName() {
return this.ContactName;
}
public final void setContactName(final String ContactName) {
this.ContactName = ContactName;
}
public final String getTelephone() {
return this.Telephone;
}
public final void setTelephone(final String Telephone) {
this.Telephone = Telephone;
}
public final String getFax() {
return this.Fax;
}
public final void setFax(final String Fax) {
this.Fax = Fax;
}
public final String getMobile() {
return this.Mobile;
}
public final void setMobile(final String Mobile) {
this.Mobile = Mobile;
}
public final String getEmail() {
return this.Email;
}
public final void setEmail(final String Email) {
this.Email = Email;
}
public final boolean getIsPrimarySendingEmail() {
return this.IsPrimarySendingEmail;
}
public final void setIsPrimarySendingEmail(final boolean IsPrimarySendingEmail) {
this.IsPrimarySendingEmail = IsPrimarySendingEmail;
}
public final String getPostalAddress01() {
return this.PostalAddress01;
}
public final void setPostalAddress01(final String PostalAddress01) {
this.PostalAddress01 = PostalAddress01;
}
public final String getPostalAddress02() {
return this.PostalAddress02;
}
public final void setPostalAddress02(final String PostalAddress02) {
this.PostalAddress02 = PostalAddress02;
}
public final String getPostalAddress03() {
return this.PostalAddress03;
}
public final void setPostalAddress03(final String PostalAddress03) {
this.PostalAddress03 = PostalAddress03;
}
public final String getPostalAddress04() {
return this.PostalAddress04;
}
public final void setPostalAddress04(final String PostalAddress04) {
this.PostalAddress04 = PostalAddress04;
}
public final String getPostalAddress05() {
return this.PostalAddress05;
}
public final void setPostalAddress05(final String PostalAddress05) {
this.PostalAddress05 = PostalAddress05;
}
public final String getCompanyInfo01() {
return this.CompanyInfo01;
}
public final void setCompanyInfo01(final String CompanyInfo01) {
this.CompanyInfo01 = CompanyInfo01;
}
public final String getCompanyInfo02() {
return this.CompanyInfo02;
}
public final void setCompanyInfo02(final String CompanyInfo02) {
this.CompanyInfo02 = CompanyInfo02;
}
public final String getCompanyInfo03() {
return this.CompanyInfo03;
}
public final void setCompanyInfo03(final String CompanyInfo03) {
this.CompanyInfo03 = CompanyInfo03;
}
public final String getCompanyInfo04() {
return this.CompanyInfo04;
}
public final void setCompanyInfo04(final String CompanyInfo04) {
this.CompanyInfo04 = CompanyInfo04;
}
public final String getCompanyInfo05() {
return this.CompanyInfo05;
}
public final void setCompanyInfo05(final String CompanyInfo05) {
this.CompanyInfo05 = CompanyInfo05;
}
public final boolean getIsOwner() {
return this.IsOwner;
}
public final void setIsOwner(final boolean IsOwner) {
this.IsOwner = IsOwner;
}
public final boolean getUseCCEmail() {
return this.UseCCEmail;
}
public final void setUseCCEmail(final boolean UseCCEmail) {
this.UseCCEmail = UseCCEmail;
}
public final String getCCEmail() {
return this.CCEmail;
}
public final void setCCEmail(final String CCEmail) {
this.CCEmail = CCEmail;
}
public final Integer getDateFormatId() {
return this.DateFormatId;
}
public final void setDateFormatId(final Integer DateFormatId) {
this.DateFormatId = DateFormatId;
}
public final boolean getCheckForDuplicateCustomerReferences() {
return this.CheckForDuplicateCustomerReferences;
}
public final void setCheckForDuplicateCustomerReferences(final boolean CheckForDuplicateCustomerReferences) {
this.CheckForDuplicateCustomerReferences = CheckForDuplicateCustomerReferences;
}
public final boolean getCheckForDuplicateSupplierReferences() {
return this.CheckForDuplicateSupplierReferences;
}
public final void setCheckForDuplicateSupplierReferences(final boolean CheckForDuplicateSupplierReferences) {
this.CheckForDuplicateSupplierReferences = CheckForDuplicateSupplierReferences;
}
public final String getDisplayName() {
return this.DisplayName;
}
public final void setDisplayName(final String DisplayName) {
this.DisplayName = DisplayName;
}
public final boolean getDisplayInactiveCustomers() {
return this.DisplayInactiveCustomers;
}
public final void setDisplayInactiveCustomers(final boolean DisplayInactiveCustomers) {
this.DisplayInactiveCustomers = DisplayInactiveCustomers;
}
public final boolean getDisplayInactiveSuppliers() {
return this.DisplayInactiveSuppliers;
}
public final void setDisplayInactiveSuppliers(final boolean DisplayInactiveSuppliers) {
this.DisplayInactiveSuppliers = DisplayInactiveSuppliers;
}
public final boolean getDisplayInactiveTimeProjects() {
return this.DisplayInactiveTimeProjects;
}
public final void setDisplayInactiveTimeProjects(final boolean DisplayInactiveTimeProjects) {
this.DisplayInactiveTimeProjects = DisplayInactiveTimeProjects;
}
public final boolean getUseInclusiveProcessingByDefault() {
return this.UseInclusiveProcessingByDefault;
}
public final void setUseInclusiveProcessingByDefault(final boolean UseInclusiveProcessingByDefault) {
this.UseInclusiveProcessingByDefault = UseInclusiveProcessingByDefault;
}
public final boolean getLockProcessing() {
return this.LockProcessing;
}
public final void setLockProcessing(final boolean LockProcessing) {
this.LockProcessing = LockProcessing;
}
public final Date getLockProcessingDate() {
return this.LockProcessingDate;
}
public final void setLockProcessingDate(final Date LockProcessingDate) {
this.LockProcessingDate = LockProcessingDate;
}
public final boolean getLockTimesheetProcessing() {
return this.LockTimesheetProcessing;
}
public final void setLockTimesheetProcessing(final boolean LockTimesheetProcessing) {
this.LockTimesheetProcessing = LockTimesheetProcessing;
}
public final Date getLockTimesheetProcessingDate() {
return this.LockTimesheetProcessingDate;
}
public final void setLockTimesheetProcessingDate(final Date LockTimesheetProcessingDate) {
this.LockTimesheetProcessingDate = LockTimesheetProcessingDate;
}
public final int getTaxPeriodFrequency() {
return this.TaxPeriodFrequency;
}
public final void setTaxPeriodFrequency(final int TaxPeriodFrequency) {
this.TaxPeriodFrequency = TaxPeriodFrequency;
}
public final Date getPreviousTaxPeriodEndDate() {
return this.PreviousTaxPeriodEndDate;
}
public final void setPreviousTaxPeriodEndDate(final Date PreviousTaxPeriodEndDate) {
this.PreviousTaxPeriodEndDate = PreviousTaxPeriodEndDate;
}
public final Date getPreviousTaxReturnDate() {
return this.PreviousTaxReturnDate;
}
public final void setPreviousTaxReturnDate(final Date PreviousTaxReturnDate) {
this.PreviousTaxReturnDate = PreviousTaxReturnDate;
}
public final boolean getUseNoreplyEmail() {
return this.UseNoreplyEmail;
}
public final void setUseNoreplyEmail(final boolean UseNoreplyEmail) {
this.UseNoreplyEmail = UseNoreplyEmail;
}
public final boolean getAgeingBasedOnDueDate() {
return this.AgeingBasedOnDueDate;
}
public final void setAgeingBasedOnDueDate(final boolean AgeingBasedOnDueDate) {
this.AgeingBasedOnDueDate = AgeingBasedOnDueDate;
}
public final boolean getUseLogoOnEmails() {
return this.UseLogoOnEmails;
}
public final void setUseLogoOnEmails(final boolean UseLogoOnEmails) {
this.UseLogoOnEmails = UseLogoOnEmails;
}
public final boolean getUseLogoOnCustomerZone() {
return this.UseLogoOnCustomerZone;
}
public final void setUseLogoOnCustomerZone(final boolean UseLogoOnCustomerZone) {
this.UseLogoOnCustomerZone = UseLogoOnCustomerZone;
}
public final String getCity() {
return this.City;
}
public final void setCity(final String City) {
this.City = City;
}
public final String getState() {
return this.State;
}
public final void setState(final String State) {
this.State = State;
}
public final String getCountry() {
return this.Country;
}
public final void setCountry(final String Country) {
this.Country = Country;
}
public final Integer getHomeCurrencyId() {
return this.HomeCurrencyId;
}
public final void setHomeCurrencyId(final Integer HomeCurrencyId) {
this.HomeCurrencyId = HomeCurrencyId;
}
public final Integer getCurrencyId() {
return this.CurrencyId;
}
public final void setCurrencyId(final Integer CurrencyId) {
this.CurrencyId = CurrencyId;
}
public final Date getCreated() {
return this.Created;
}
public final void setCreated(final Date Created) {
this.Created = Created;
}
public final Date getModified() {
return this.Modified;
}
public final void setModified(final Date Modified) {
this.Modified = Modified;
}
public final boolean getActive() {
return this.Active;
}
public final void setActive(final boolean Active) {
this.Active = Active;
}
public final String getTaxNumber() {
return this.TaxNumber;
}
public final void setTaxNumber(final String TaxNumber) {
this.TaxNumber = TaxNumber;
}
public final String getRegisteredName() {
return this.RegisteredName;
}
public final void setRegisteredName(final String RegisteredName) {
this.RegisteredName = RegisteredName;
}
public final String getRegistrationNumber() {
return this.RegistrationNumber;
}
public final void setRegistrationNumber(final String RegistrationNumber) {
this.RegistrationNumber = RegistrationNumber;
}
public final boolean getIsPracticeAccount() {
return this.IsPracticeAccount;
}
public final void setIsPracticeAccount(final boolean IsPracticeAccount) {
this.IsPracticeAccount = IsPracticeAccount;
}
public final Integer getLogoPositionID() {
return this.LogoPositionID;
}
public final void setLogoPositionID(final Integer LogoPositionID) {
this.LogoPositionID = LogoPositionID;
}
public final SageOneCompanyLogoClass getAttachment() {
return this.Attachment;
}
public final void setAttachment(final SageOneCompanyLogoClass Attachment) {
this.Attachment = Attachment;
}
public final String getCompanyTaxNumber() {
return this.CompanyTaxNumber;
}
public final void setCompanyTaxNumber(final String CompanyTaxNumber) {
this.CompanyTaxNumber = CompanyTaxNumber;
}
public final String getTaxOffice() {
return this.TaxOffice;
}
public final void setTaxOffice(final String TaxOffice) {
this.TaxOffice = TaxOffice;
}
public final String getCustomerZoneGuid() {
return this.CustomerZoneGuid;
}
public final void setCustomerZoneGuid(final String CustomerZoneGuid) {
this.CustomerZoneGuid = CustomerZoneGuid;
}
public final Integer getClientTypeId() {
return this.ClientTypeId;
}
public final void setClientTypeId(final Integer ClientTypeId) {
this.ClientTypeId = ClientTypeId;
}
public final Integer getDisplayTotalTypeId() {
return this.DisplayTotalTypeId;
}
public final void setDisplayTotalTypeId(final Integer DisplayTotalTypeId) {
this.DisplayTotalTypeId = DisplayTotalTypeId;
}
public final boolean getDisplayInCompanyConsole() {
return this.DisplayInCompanyConsole;
}
public final void setDisplayInCompanyConsole(final boolean DisplayInCompanyConsole) {
this.DisplayInCompanyConsole = DisplayInCompanyConsole;
}
public final Date getLastLoginDate() {
return this.LastLoginDate;
}
public final void setLastLoginDate(final Date LastLoginDate) {
this.LastLoginDate = LastLoginDate;
}
public final SageOneCompanyStatus getStatus() {
return this.Status;
}
public final void setStatus(final SageOneCompanyStatus Status) {
this.Status = Status;
}
}
| for previous commit
| src/main/java/SageOneIntegration/SageOneApiEntities/SageOneCompany.java | for previous commit | <ide><path>rc/main/java/SageOneIntegration/SageOneApiEntities/SageOneCompany.java
<ide> private Date LastLoginDate;
<ide> private SageOneCompanyStatus Status;
<ide>
<add> public Integer getId() {
<add> return ID;
<add> }
<add>
<ide> public final String getName() {
<ide> return this.Name;
<ide> } |
|
Java | mit | 4aea90eb39daff9858db2228778be66f63481ed6 | 0 | UCSB-CS56-Projects/cs56-games-poker | package edu.ucsb.cs56.projects.games.poker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
* The Poker Game Main Page (Start-Up) screen
*/
public class PokerMain {
/**
* Frame holding buttons representing initial options
*/
JFrame playButtonFrame;
/**
* Button to start a single player game
*/
JButton singlePlayerButton;
JButton multiPlayerButton;
/**
* Currently unused
*/
JButton serverButton, clientButton;
/**
* Button to open a chat client
*/
JButton clientChatButton;
/**
* Button to start chat server
*/
JButton serverChatButton;
/**
* Panel to hold buttons representing initial options
*/
JPanel panel;
/**
* Chat server address
*/
String address;
/**
* Runs the application
*/
public static void main(String[] args) {
PokerMain start = new PokerMain();
start.go();
}
/**
* Brings up option window to start game.
*/
public void go() {
playButtonFrame = new JFrame();
playButtonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PlayButtonHandler listener = new PlayButtonHandler();
panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
singlePlayerButton = new JButton("Play Single Player");
singlePlayerButton.addActionListener(listener);
panel.add(singlePlayerButton);
multiPlayerButton = new JButton("Play MultiPlayer");
multiPlayerButton.addActionListener(listener);
panel.add(multiPlayerButton);
/*
serverButton = new JButton("Create Poker Server");
serverButton.addActionListener(listener);
panel.add(serverButton);
clientButton = new JButton("Connect to Poker Server");
clientButton.addActionListener(listener);
panel.add(clientButton);
*/
serverChatButton = new JButton("Create Poker Chat Server");
serverChatButton.addActionListener(listener);
panel.add(serverChatButton);
clientChatButton = new JButton("Connect to Poker Chat Server");
clientChatButton.addActionListener(listener);
panel.add(clientChatButton);
playButtonFrame.add(BorderLayout.CENTER, panel);
playButtonFrame.setSize(300, 200);
playButtonFrame.setResizable(false);
playButtonFrame.setLocation(250, 250);
playButtonFrame.setVisible(true);
}
/**
* Handles the buttons in the option window.
*/
private class PlayButtonHandler implements ActionListener {
/**
* listener for play, serverChat, and clientChat buttons
* @param e action event
*/
public void actionPerformed(ActionEvent event) {
Object src = event.getSource();
if (src == singlePlayerButton) {
PokerSinglePlayer singlePlayer = new PokerSinglePlayer(500, 500);
singlePlayer.go();
}
/*
else if (src == serverButton) {
PokerServer server = new PokerServer();
server.go();
}
else if (src == clientButton) {
PokerClient client = new PokerClient();
address = JOptionPane.showInputDialog(playButtonFrame, "What IP Address are you connecting to?");
if(address != null){
client.setAddress(address);
try{
client.go();
} catch (IOException ex){ex.printStackTrace();
}
}
}*/
else if(src == serverChatButton){
PokerChatServer server2 = new PokerChatServer();
server2.go();
}
else if(src == clientChatButton){
address = JOptionPane.showInputDialog(playButtonFrame, "What IP Address are you connecting to?");
PokerChatClient client2 = new PokerChatClient();
if(address != null){
client2.setAddress(address);
client2.go();
}
}
playButtonFrame.setVisible(false);
}
}
}
| src/edu/ucsb/cs56/projects/games/poker/PokerMain.java | package edu.ucsb.cs56.projects.games.poker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
* The Poker Game Main Page (Start-Up) screen
*/
public class PokerMain {
/**
* Frame holding buttons representing initial options
*/
JFrame playButtonFrame;
/**
* Button to start a single player game
*/
JButton singlePlayerButton;
JButton multiPlayerButton;
/**
* Currently unused
*/
JButton serverButton, clientButton;
/**
* Button to open a chat client
*/
JButton clientChatButton;
/**
* Button to start chat server
*/
JButton serverChatButton;
/**
* Panel to hold buttons representing initial options
*/
JPanel panel;
/**
* Chat server address
*/
String address;
/**
* Runs the application
*/
public static void main(String[] args) {
PokerMain start = new PokerMain();
start.go();
}
/**
* Brings up option window to start game.
*/
public void go() {
playButtonFrame = new JFrame();
playButtonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PlayButtonHandler listener = new PlayButtonHandler();
panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
singlePlayerButton = new JButton("Play Single Player");
singlePlayerButton.addActionListener(listener);
panel.add(singlePlayerButton);
multiPlayerButton = new JButton("Play MultiPlayer");
multiPlayerButton.addActionListener(listener);
panel.add(multiPlayerButton);
/*
serverButton = new JButton("Create Poker Server");
serverButton.addActionListener(listener);
panel.add(serverButton);
clientButton = new JButton("Connect to Poker Server");
clientButton.addActionListener(listener);
panel.add(clientButton);
*/
serverChatButton = new JButton("Create Poker Chat Server");
serverChatButton.addActionListener(listener);
panel.add(serverChatButton);
clientChatButton = new JButton("Connect to Poker Chat Server");
clientChatButton.addActionListener(listener);
panel.add(clientChatButton);
playButtonFrame.add(BorderLayout.CENTER, panel);
playButtonFrame.setSize(300, 200);
playButtonFrame.setResizable(false);
playButtonFrame.setLocation(250, 250);
playButtonFrame.setVisible(true);
}
/**
* Handles the buttons in the option window.
*/
private class PlayButtonHandler implements ActionListener {
/**
* listener for play, serverChat, and clientChat buttons
* @param e action event
*/
public void actionPerformed(ActionEvent event) {
Object src = event.getSource();
if (src == singlePlayerButton) {
PokerSinglePlayer singlePlayer = new PokerSinglePlayer(500, 500);
singlePlayer.go();
}
/*
else if (src == serverButton) {
PokerServer server = new PokerServer();
server.go();
}
else if (src == clientButton) {
PokerClient client = new PokerClient();
address = JOptionPane.showInputDialog(playButtonFrame, "What IP Address are you connecting to?");
if(address != null){
client.setAddress(address);
try{
client.go();
} catch (IOException ex){ex.printStackTrace();
}
}
}*/
else if(src == serverChatButton){
PokerChatServer server2 = new PokerChatServer();
server2.go();
}
else if(src == clientChatButton){
address = JOptionPane.showInputDialog(playButtonFrame, "What IP Address are you connecting to?");
PokerChatClient client2 = new PokerChatClient();
if(address != null){
client2.setAddress(address);
client2.go();
}
}
playButtonFrame.setVisible(false);
}
}
}
| AB/HS Added multiplayer option to GUI, not yet implemented
| src/edu/ucsb/cs56/projects/games/poker/PokerMain.java | AB/HS Added multiplayer option to GUI, not yet implemented | <ide><path>rc/edu/ucsb/cs56/projects/games/poker/PokerMain.java
<ide> multiPlayerButton.addActionListener(listener);
<ide> panel.add(multiPlayerButton);
<ide>
<del>
<ide> /*
<ide> serverButton = new JButton("Create Poker Server");
<ide> serverButton.addActionListener(listener); |
|
JavaScript | agpl-3.0 | 4b21e3f125f8cb5bd24de7649a74850af6641829 | 0 | sirDonovan/Pokemon-Showdown-Client,Zarel/Pokemon-Showdown-Client,panpawn/Gold-Client,sirDonovan/Pokemon-Showdown-Client,panpawn/Gold-Client,asgdf/Pokemon-Showdown-Client,asgdf/Pokemon-Showdown-Client,QuiteQuiet/Pokemon-Showdown-Client,sirDonovan/Pokemon-Showdown-Client,asgdf/Pokemon-Showdown-Client,QuiteQuiet/Pokemon-Showdown-Client,Zarel/Pokemon-Showdown-Client,submindraikou/Pokemon-Showdown-Client,sirDonovan/Pokemon-Showdown-Client,Zarel/Pokemon-Showdown-Client,QuiteQuiet/Pokemon-Showdown-Client,asgdf/Pokemon-Showdown-Client,panpawn/Gold-Client,Zarel/Pokemon-Showdown-Client,submindraikou/Pokemon-Showdown-Client,QuiteQuiet/Pokemon-Showdown-Client,submindraikou/Pokemon-Showdown-Client | (function (exports, $) {
// this is a useful global
var teams;
var TeambuilderRoom = exports.TeambuilderRoom = exports.Room.extend({
type: 'teambuilder',
title: 'Teambuilder',
initialize: function () {
teams = Storage.teams;
// left menu
this.$el.addClass('ps-room-light').addClass('scrollable');
if (!Storage.whenTeamsLoaded.isLoaded) {
Storage.whenTeamsLoaded(this.update, this);
}
this.update();
},
focus: function () {
this.buildMovelists();
if (this.curTeam) {
this.curTeam.iconCache = '!';
this.curTeam.gen = this.getGen(this.curTeam.format);
Storage.activeSetList = this.curSetList;
}
},
blur: function () {
if (this.saveFlag) {
this.saveFlag = false;
app.user.trigger('saveteams');
}
},
events: {
// team changes
'change input.teamnameedit': 'teamNameChange',
'click button.formatselect': 'selectFormat',
'change input[name=nickname]': 'nicknameChange',
// details
'change .detailsform input': 'detailsChange',
// stats
'keyup .statform input.numform': 'statChange',
'input .statform input[type=number].numform': 'statChange',
'change select[name=nature]': 'natureChange',
// teambuilder events
'click .utilichart a': 'chartClick',
'keydown .chartinput': 'chartKeydown',
'keyup .chartinput': 'chartKeyup',
'focus .chartinput': 'chartFocus',
'change .chartinput': 'chartChange',
// drag/drop
'click .team': 'edit',
'click .selectFolder': 'selectFolder',
'mouseover .team': 'mouseOverTeam',
'mouseout .team': 'mouseOutTeam',
'dragstart .team': 'dragStartTeam',
'dragend .team': 'dragEndTeam',
'dragenter .team': 'dragEnterTeam',
'dragenter .folder .selectFolder': 'dragEnterFolder',
'dragleave .folder .selectFolder': 'dragLeaveFolder',
'dragexit .folder .selectFolder': 'dragExitFolder',
// clipboard
'click .teambuilder-clipboard-data .result': 'clipboardResultSelect',
'click .teambuilder-clipboard-data': 'clipboardExpand',
'blur .teambuilder-clipboard-data': 'clipboardShrink'
},
dispatchClick: function (e) {
e.preventDefault();
e.stopPropagation();
if (this[e.currentTarget.value]) this[e.currentTarget.value](e);
},
saveTeams: function () {
// save and return
Storage.saveTeams();
app.user.trigger('saveteams');
this.update();
},
back: function () {
if (this.exportMode) {
if (this.curTeam) this.curTeam.team = Storage.packTeam(this.curSetList);
this.exportMode = false;
Storage.saveTeams();
} else if (this.curSet) {
app.clearGlobalListeners();
this.curSet = null;
Storage.saveTeams();
} else if (this.curTeam) {
this.curTeam.team = Storage.packTeam(this.curSetList);
this.curTeam.iconCache = '';
var team = this.curTeam;
this.curTeam = null;
Storage.activeSetList = this.curSetList = null;
Storage.saveTeam(team);
} else {
return;
}
app.user.trigger('saveteams');
this.update();
},
// the teambuilder has three views:
// - team list (curTeam falsy)
// - team view (curTeam exists, curSet falsy)
// - set view (curTeam exists, curSet exists)
curTeam: null,
curTeamLoc: 0,
curSet: null,
curSetLoc: 0,
// curFolder will have '/' at the end if it's a folder, but
// it will be alphanumeric (so guaranteed no '/') if it's a
// format
// Special values:
// '' - show all
// 'gen6' - show teams with no format
// '/' - show teams with no folder
curFolder: '',
curFolderKeep: '',
exportMode: false,
update: function () {
teams = Storage.teams;
if (this.curTeam) {
this.ignoreEVLimits = (this.curTeam.gen < 3);
if (this.curSet) {
return this.updateSetView();
}
return this.updateTeamView();
}
return this.updateTeamInterface();
},
/*********************************************************
* Team list view
*********************************************************/
deletedTeam: null,
deletedTeamLoc: -1,
updateTeamInterface: function () {
this.deletedSet = null;
this.deletedSetLoc = -1;
var buf = '';
if (this.exportMode) {
buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <button name="saveBackup" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>';
buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportAllTeams()) + '</textarea></div>';
this.$el.html(buf);
this.$('.teamedit textarea').focus().select();
return;
}
if (!Storage.whenTeamsLoaded.isLoaded) {
buf = '<div class="pad"><p>lol zarel this is a horrible teambuilder</p>';
buf += '<p>that\'s because we\'re not done loading it...</p></div>';
this.$el.html(buf);
return;
}
// folderpane
buf = '<div class="folderpane">';
buf += '</div>';
// teampane
buf += '<div class="teampane">';
buf += '</div>';
this.$el.html(buf);
this.updateFolderList();
this.updateTeamList();
},
updateFolderList: function () {
var buf = '<div class="folderlist"><div class="folderlistbefore"></div>';
buf += '<div class="folder' + (!this.curFolder ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="all"><em>(all)</em></div></div>' + (!this.curFolder ? '</div>' : '');
var folderTable = {};
var folders = [];
if (Storage.teams) for (var i = -2; i < Storage.teams.length; i++) {
if (i >= 0) {
var folder = Storage.teams[i].folder;
if (folder && !((folder + '/') in folderTable)) {
folders.push('Z' + folder);
folderTable[folder + '/'] = 1;
if (!('/' in folderTable)) {
folders.push('Z~');
folderTable['/'] = 1;
}
}
}
var format;
if (i === -2) {
format = this.curFolderKeep;
} else if (i === -1) {
format = this.curFolder;
} else {
format = Storage.teams[i].format;
if (!format) format = 'gen6';
}
if (!format) continue;
if (format in folderTable) continue;
folderTable[format] = 1;
if (format.slice(-1) === '/') {
folders.push('Z' + (format.slice(0, -1) || '~'));
if (!('/' in folderTable)) {
folders.push('Z~');
folderTable['/'] = 1;
}
continue;
}
if (format === 'gen6') {
folders.push('A~');
continue;
}
switch (format.slice(0, 4)) {
case 'gen1': format = 'F' + format.slice(4); break;
case 'gen2': format = 'E' + format.slice(4); break;
case 'gen3': format = 'D' + format.slice(4); break;
case 'gen4': format = 'C' + format.slice(4); break;
case 'gen5': format = 'B' + format.slice(4); break;
default: format = 'A' + format; break;
}
folders.push(format);
}
folders.sort();
var gen = '';
var formatFolderBuf = '<div class="foldersep"></div>';
formatFolderBuf += '<div class="folder"><div class="selectFolder" data-value="+"><i class="fa fa-plus"></i><em>(add format folder)</em></div></div>';
for (var i = 0; i < folders.length; i++) {
var format = folders[i];
var newGen;
switch (format.charAt(0)) {
case 'F': newGen = '1'; break;
case 'E': newGen = '2'; break;
case 'D': newGen = '3'; break;
case 'C': newGen = '4'; break;
case 'B': newGen = '5'; break;
case 'A': newGen = '6'; break;
case 'Z': newGen = '/'; break;
}
if (gen !== newGen) {
gen = newGen;
if (gen === '/') {
buf += formatFolderBuf;
formatFolderBuf = '';
buf += '<div class="foldersep"></div>';
buf += '<div class="folder"><h3>Folders</h3></div>';
} else {
buf += '<div class="folder"><h3>Gen ' + gen + '</h3></div>';
}
}
if (gen === '/') {
formatName = format.slice(1);
format = formatName + '/';
if (formatName === '~') {
formatName = '(uncategorized)';
format = '/';
} else {
formatName = Tools.escapeHTML(formatName);
}
buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open' : 'fa-folder') + (format === '/' ? '-o' : '') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : '');
continue;
}
var formatName = format.slice(1);
if (formatName === '~') formatName = '';
if (newGen === '6' && formatName) {
format = formatName;
} else {
format = 'gen' + newGen + formatName;
}
if (format === 'gen6') formatName = '(uncategorized)';
// folders are <div>s rather than <button>s because in theory it has
// less weird interactions with HTML5 drag-and-drop
buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open-o' : 'fa-folder-o') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : '');
}
buf += formatFolderBuf;
buf += '<div class="foldersep"></div>';
buf += '<div class="folder"><div class="selectFolder" data-value="++"><i class="fa fa-plus"></i><em>(add folder)</em></div></div>';
buf += '<div class="folderlistafter"></div></div>';
this.$('.folderpane').html(buf);
},
updateTeamList: function (resetScroll) {
var teams = Storage.teams;
var buf = '';
// teampane
buf += this.clipboardHTML();
var filterFormat = '';
var filterFolder = undefined;
if (!this.curFolder) {
buf += '<h2>Hi</h2>';
buf += '<p>Did you have a good day?</p>';
buf += '<p><button class="button" name="greeting" value="Y"><i class="fa fa-smile-o"></i> Yes, my day was pretty good</button> <button class="button" name="greeting" value="N"><i class="fa fa-frown-o"></i> No, it wasn\'t great</button></p>';
buf += '<h2>All teams</h2>';
} else {
if (this.curFolder.slice(-1) === '/') {
filterFolder = this.curFolder.slice(0, -1);
if (filterFolder) {
buf += '<h2><i class="fa fa-folder-open"></i> ' + filterFolder + ' <button class="button small" style="margin-left:5px" name="renameFolder"><i class="fa fa-pencil"></i> Rename</button></h2>';
} else {
buf += '<h2><i class="fa fa-folder-open-o"></i> Teams not in any folders</h2>';
}
} else {
filterFormat = this.curFolder;
buf += '<h2><i class="fa fa-folder-open-o"></i> ' + filterFormat + '</h2>';
}
}
var newButtonText = "New Team";
if (filterFolder) newButtonText = "New Team in folder";
if (filterFormat && filterFormat !== 'gen6') {
newButtonText = "New " + Tools.escapeFormat(filterFormat) + " Team";
}
buf += '<p><button name="newTop" class="button big"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>';
buf += '<ul class="teamlist">';
var atLeastOne = false;
if (!window.localStorage && !window.nodewebkit) buf += '<li>== CAN\'T SAVE ==<br /><small>Your browser doesn\'t support <code>localStorage</code> and can\'t save teams! Update to a newer browser.</small></li>';
if (Storage.cantSave) buf += '<li>== CAN\'T SAVE ==<br /><small>You hit your browser\'s limit for team storage! Please backup them and delete some of them. Your teams won\'t be saved until you\'re under the limit again.</small></li>';
if (!teams.length) {
if (this.deletedTeamLoc >= 0) {
buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
buf += '<li><p><em>you don\'t have any teams lol</em></p></li>';
} else {
for (var i = 0; i < teams.length + 1; i++) {
if (i === this.deletedTeamLoc) {
if (!atLeastOne) atLeastOne = true;
buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
if (i >= teams.length) break;
var team = teams[i];
if (team && !team.team && team.team !== '') {
team = null;
}
if (!team) {
buf += '<li>Error: A corrupted team was dropped</li>';
teams.splice(i, 1);
i--;
if (this.deletedTeamLoc && this.deletedTeamLoc > i) this.deletedTeamLoc--;
continue;
}
if (filterFormat && filterFormat !== (team.format || 'gen6')) continue;
if (filterFolder !== undefined && filterFolder !== team.folder) continue;
if (!atLeastOne) atLeastOne = true;
var formatText = '';
if (team.format) {
formatText = '[' + team.format + '] ';
}
if (team.folder) formatText += team.folder + '/';
// teams are <div>s rather than <button>s because Firefox doesn't
// support dragging and dropping buttons.
buf += '<li><div name="edit" data-value="' + i + '" class="team" draggable="true">' + formatText + '<strong>' + Tools.escapeHTML(team.name) + '</strong><br /><small>';
buf += Storage.getTeamIcons(team);
buf += '</small></div><button name="edit" value="' + i + '"><i class="fa fa-pencil"></i>Edit</button><button name="delete" value="' + i + '"><i class="fa fa-trash"></i>Delete</button></li>';
}
if (!atLeastOne) {
if (filterFolder) {
buf += '<li><p><em>you don\'t have any teams in this folder lol</em></p></li>';
} else {
buf += '<li><p><em>you don\'t have any ' + this.curFolder + ' teams lol</em></p></li>';
}
}
}
buf += '</ul>';
if (atLeastOne) {
buf += '<p><button name="new" class="button"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>';
}
if (window.nodewebkit) {
buf += '<button name="revealFolder" class="button"><i class="fa fa-folder-open"></i> Reveal teams folder</button> <button name="reloadTeamsFolder" class="button"><i class="fa fa-refresh"></i> Reload teams files</button> <button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>';
} else if (atLeastOne) {
buf += '<p><strong>Clearing your cookies (specifically, <code>localStorage</code>) will delete your teams.</strong></p>';
buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>';
buf += '<p>If you want to clear your cookies or <code>localStorage</code>, you can use the Backup/Restore feature to save your teams as text first.</p>';
} else {
buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Restore teams from backup</button>';
}
var $pane = this.$('.teampane');
$pane.html(buf);
if (resetScroll) $pane.scrollTop(0);
},
greeting: function (answer, button) {
var buf = '<p><strong>' + $(button).html() + '</p></strong>';
if (answer === 'N') {
buf += '<p>Aww, that\'s too bad. :( I hope playing on Pokémon Showdown today can help cheer you up!</p>';
} else if (answer === 'Y') {
buf += '<p>Cool! I just added some pretty cool teambuilder features, so I\'m pretty happy, too. Did you know you can drag and drop teams to different format-folders? You can also drag and drop them to and from your computer (works best in Chrome).</p>';
buf += '<p><button class="button" name="greeting" value="W"><i class="fa fa-question-circle"></i> Wait, who are you? Talking to a teambuilder is weird.</button></p>';
} else if (answer === 'W') {
buf += '<p>Oh, I\'m Zarel! I made a Credits button for this...</p>';
buf += '<div class="menugroup"><p><button class="button mainmenu4" name="credits"><i class="fa fa-info-circle"></i> Credits</button></p></div>';
buf += '<p>Isn\'t it pretty? Matches your background and everything. It used to be in the Main Menu but we had to get rid of it to save space.</p>';
buf += '<p>Speaking of, you should try <button class="button" name="background"><i class="fa fa-picture-o"></i> changing your background</button>.';
buf += '<p><button class="button" name="greeting" value="B"><i class="fa fa-hand-pointer-o"></i> You might be having too much fun with these buttons and icons</button></p>';
} else if (answer === 'B') {
buf += '<p>I paid good money for those icons! I need to get my money\'s worth!</p>';
buf += '<p><button class="button" name="greeting" value="WR"><i class="fa fa-exclamation-triangle"></i> Wait, really?</button></p>';
} else if (answer === 'WR') {
buf += '<p>No, they were free. That just makes it easier to get my money\'s worth. Let\'s play rock paper scissors!</p>';
buf += '<p><button class="button" name="greeting" value="RR"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="RS"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="RL"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="RK"><i class="fa fa-hand-spock-o"></i> Spock</button></p>';
} else if (answer[0] === 'R') {
buf += '<p>I play laser, I win. <i class="fa fa-hand-o-left"></i></p>';
buf += '<p><button class="button" name="greeting" value="YC"><i class="fa fa-thumbs-o-down"></i> You can\'t do that!</button></p>';
} else if (answer === 'SP') {
buf += '<p>Okay, sure. I warn you, I\'m using the same RNG that makes Stone Edge miss for you.</p>';
buf += '<p><button class="button" name="greeting" value="SP3"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors</button> <button class="button" name="greeting" value="SP5"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors Lizard Spock</button></p>';
} else if (answer === 'SP3') {
buf += '<p><button class="button" name="greeting" value="PR3"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP3"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS3"><i class="fa fa-hand-scissors-o"></i> Scissors</button></p>';
} else if (answer === 'SP5') {
buf += '<p><button class="button" name="greeting" value="PR5"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP5"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS5"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="PL5"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="PK5"><i class="fa fa-hand-spock-o"></i> Spock</button></p>';
} else if (answer[0] === 'P') {
var rpsChart = {
R: 'rock',
P: 'paper',
S: 'scissors',
L: 'lizard',
K: 'spock'
};
var rpsWinChart = {
SP: 'cuts',
SL: 'decapitates',
PR: 'covers',
PK: 'disproves',
RL: 'crushes',
RS: 'crushes',
LK: 'poisons',
LP: 'eats',
KS: 'smashes',
KR: 'vaporizes'
};
var my = ['R', 'P', 'S', 'L', 'K'][Math.floor(Math.random() * Number(answer[2]))];
var your = answer[1];
buf += '<p>I play <i class="fa fa-hand-' + rpsChart[my] + '-o"></i> ' + rpsChart[my] + '!</p>';
if ((my + your) in rpsWinChart) {
buf += '<p>And ' + rpsChart[my] + ' ' + rpsWinChart[my + your] + ' ' + rpsChart[your] + ', so I win!</p>';
} else if ((your + my) in rpsWinChart) {
buf += '<p>But ' + rpsChart[your] + ' ' + rpsWinChart[your + my] + ' ' + rpsChart[my] + ', so you win...</p>';
} else {
buf += '<p>We played the same thing, so it\'s a tie.</p>';
}
buf += '<p>Score: ' + ['pi', '$3.50', '9.80665 m/s<sup>2</sup>', '28°C', '百万点', '<i class="fa fa-bitcoin"></i>0.0000174', '<s>priceless</s> <i class="fa fa-cc-mastercard"></i> MasterCard', '127.0.0.1', 'C−, see me after class'][Math.floor(Math.random() * 9)];
buf += '<p><button class="button" name="greeting" value="SP' + answer[2] + '"><i class="fa fa-caret-square-o-right"></i> I demand a rematch!</button></p>';
} else if (answer === 'YC') {
buf += '<p>Okay, then I play peace sign <i class="fa fa-hand-peace-o"></i>, everyone signs a peace treaty, ending the war and ushering in a new era of prosperity.</p>';
buf += '<p><button class="button" name="greeting" value="SP"><i class="fa fa-caret-square-o-right"></i> I wanted to play for real...</button></p>';
}
$(button).parent().replaceWith(buf);
},
credits: function () {
app.addPopup(CreditsPopup);
},
background: function () {
app.addPopup(CustomBackgroundPopup);
},
selectFolder: function (format) {
if (format && format.currentTarget) {
var e = format;
format = $(e.currentTarget).data('value');
e.preventDefault();
if (format === '+') {
e.stopImmediatePropagation();
var self = this;
app.addPopup(FormatPopup, {format: '', sourceEl: e.currentTarget, selectType: 'teambuilder', onselect: function (newFormat) {
self.selectFolder(newFormat);
}});
return;
}
if (format === '++') {
e.stopImmediatePropagation();
var self = this;
// app.addPopupPrompt("Folder name:", "Create folder", function (newFormat) {
// self.selectFolder(newFormat + '/');
// });
app.addPopup(PromptPopup, {message: "Folder name:", button: "Create folder", sourceEl: e.currentTarget, callback: function (name) {
name = $.trim(name);
if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator.");
name = name.replace(/[\\\/]/g, '');
}
if (!name) return;
self.selectFolder(name + '/');
}});
return;
}
} else {
this.curFolderKeep = format;
}
this.curFolder = (format === 'all' ? '' : format);
this.updateFolderList();
this.updateTeamList(true);
},
renameFolder: function () {
if (!this.curFolder) return;
if (this.curFolder.slice(-1) !== '/') return;
var oldFolder = this.curFolder.slice(0, -1);
var self = this;
app.addPopup(PromptPopup, {message: "Folder name:", button: "Rename folder", value: oldFolder, callback: function (name) {
name = $.trim(name);
if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator.");
name = name.replace(/[\\\/]/g, '');
}
if (!name) return;
if (name === oldFolder) return;
for (var i = 0; i < Storage.teams.length; i++) {
var team = Storage.teams[i];
if (team.folder !== oldFolder) continue;
team.folder = name;
if (window.nodewebkit) Storage.saveTeam(team);
}
if (!window.nodewebkit) Storage.saveTeam(team);
self.selectFolder(name + '/');
}});
},
show: function () {
Room.prototype.show.apply(this, arguments);
var $teamwrapper = this.$('.teamwrapper');
var width = $(window).width();
if (!$teamwrapper.length) return;
if (width < 640) {
var scale = (width / 640);
$teamwrapper.css('transform', 'scale(' + scale + ')');
$teamwrapper.addClass('scaled');
} else {
$teamwrapper.css('transform', 'none');
$teamwrapper.removeClass('scaled');
}
},
// button actions
revealFolder: function () {
Storage.revealFolder();
},
reloadTeamsFolder: function () {
Storage.nwLoadTeams();
},
edit: function (i) {
if (i && i.currentTarget) {
i = $(i.currentTarget).data('value');
}
i = +i;
this.curTeam = teams[i];
this.curTeam.iconCache = '!';
this.curTeam.gen = this.getGen(this.curTeam.format);
Storage.activeSetList = this.curSetList = Storage.unpackTeam(this.curTeam.team);
this.curTeamIndex = i;
this.update();
},
"delete": function (i) {
i = +i;
this.deletedTeamLoc = i;
this.deletedTeam = teams.splice(i, 1)[0];
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
if (i < obj.curTeamIndex) {
obj.curTeamIndex--;
} else if (i === obj.curTeamIndex) {
obj.curTeamIndex = -1;
}
}
Storage.deleteTeam(this.deletedTeam);
app.user.trigger('saveteams');
this.updateTeamList();
},
undoDelete: function () {
if (this.deletedTeamLoc >= 0) {
teams.splice(this.deletedTeamLoc, 0, this.deletedTeam);
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
if (this.deletedTeamLoc < obj.curTeamIndex + 1) {
obj.curTeamIndex++;
} else if (obj.curTeamIndex === -1) {
obj.curTeamIndex = this.deletedTeamLoc;
}
}
var undeletedTeam = this.deletedTeam;
this.deletedTeam = null;
this.deletedTeamLoc = -1;
Storage.saveTeam(undeletedTeam);
app.user.trigger('saveteams');
this.update();
}
},
saveBackup: function () {
Storage.deleteAllTeams();
Storage.importTeam(this.$('.teamedit textarea').val(), true);
teams = Storage.teams;
Storage.saveAllTeams();
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
obj.curTeamIndex = 0;
}
this.back();
},
"new": function () {
var format = this.curFolder;
var folder = '';
if (format && format.charAt(format.length - 1) === '/') {
folder = format.slice(0, -1);
format = '';
}
var newTeam = {
name: 'Untitled ' + (teams.length + 1),
format: format,
team: '',
folder: folder,
iconCache: ''
};
teams.push(newTeam);
this.edit(teams.length - 1);
},
newTop: function () {
var format = this.curFolder;
var folder = '';
if (format && format.charAt(format.length - 1) === '/') {
folder = format.slice(0, -1);
format = '';
}
var newTeam = {
name: 'Untitled ' + (teams.length + 1),
format: format,
team: '',
folder: folder,
iconCache: ''
};
teams.unshift(newTeam);
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
obj.curTeamIndex++;
}
this.edit(0);
},
"import": function () {
if (this.exportMode) return this.back();
this.exportMode = true;
if (!this.curTeam) {
this['new']();
} else {
this.update();
}
},
backup: function () {
this.curTeam = null;
this.curSetList = null;
this.exportMode = true;
this.update();
},
// drag and drop
// because of a bug in Chrome and Webkit:
// https://code.google.com/p/chromium/issues/detail?id=410328
// we can't use CSS :hover
mouseOverTeam: function (e) {
e.currentTarget.className = 'team team-hover';
},
mouseOutTeam: function (e) {
e.currentTarget.className = 'team';
},
dragStartTeam: function (e) {
var target = e.currentTarget;
var dataTransfer = e.originalEvent.dataTransfer;
dataTransfer.effectAllowed = 'copyMove';
dataTransfer.setData("text/plain", "Team " + e.currentTarget.dataset.value);
var team = Storage.teams[e.currentTarget.dataset.value];
var filename = team.name;
if (team.format) filename = '[' + team.format + '] ' + filename;
filename = $.trim(filename).replace(/[\\\/]+/g, '') + '.txt';
var urlprefix = "data:text/plain;base64,";
if (document.location.protocol === 'https:') {
// Chrome is dumb and doesn't support data URLs in HTTPS
urlprefix = "https://play.pokemonshowdown.com/action.php?act=dlteam&team=";
}
var contents = Storage.exportTeam(team.team).replace(/\n/g, '\r\n');
var downloadurl = "text/plain:" + filename + ":" + urlprefix + encodeURIComponent(window.btoa(unescape(encodeURIComponent(contents))));
console.log(downloadurl);
dataTransfer.setData("DownloadURL", downloadurl);
app.dragging = e.currentTarget;
app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10);
var elOffset = $(e.currentTarget).offset();
app.draggingOffsetX = e.originalEvent.pageX - elOffset.left;
app.draggingOffsetY = e.originalEvent.pageY - elOffset.top;
app.draggingRoom = this.id;
this.finalOffset = null;
setTimeout(function () {
$(e.currentTarget).parent().addClass('dragging');
}, 0);
},
dragEndTeam: function (e) {
this.finishDrop();
},
finishDrop: function () {
var teamEl = app.dragging;
app.dragging = null;
var originalLoc = parseInt(teamEl.dataset.value, 10);
if (isNaN(originalLoc)) {
throw new Error("drag failed");
}
var newLoc = Math.floor(app.draggingLoc);
if (app.draggingLoc < originalLoc) newLoc += 1;
var team = Storage.teams[originalLoc];
var edited = false;
if (newLoc !== originalLoc) {
Storage.teams.splice(originalLoc, 1);
Storage.teams.splice(newLoc, 0, team);
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
if (originalLoc === obj.curTeamIndex) {
obj.curTeamIndex = newLoc;
} else if (originalLoc > obj.curTeamIndex && newLoc <= obj.curTeamIndex) {
obj.curTeamIndex++;
} else if (originalLoc < obj.curTeamIndex && newLoc >= obj.curTeamIndex) {
obj.curTeamIndex--;
}
}
edited = true;
}
// possibly half-works-around a hover issue in
this.$('.teamlist').css('pointer-events', 'none');
$(teamEl).parent().removeClass('dragging');
var format = this.curFolder;
if (app.draggingFolder) {
format = app.draggingFolder.dataset.value;
app.draggingFolder = null;
if (format.slice(-1) === '/') {
team.folder = format.slice(0, -1);
} else {
team.format = format;
}
this.selectFolder(format);
edited = true;
} else {
if (format.slice(-1) === '/') {
team.folder = format.slice(0, -1);
edited = true;
}
this.updateTeamList();
}
if (edited) {
Storage.saveTeam(team);
app.user.trigger('saveteams');
}
// We're going to try to animate the team settling into its new position
if (this.finalOffset) {
// event.pageY and event.pageX are buggy on literally every browser:
// in Chrome:
// event.pageX|pageY is the position of the bottom left corner of the draggable, instead
// of the mouse position
// in Safari:
// window.innerHeight * 2 - window.outerHeight - event.pageY is the mouse position
// No, I don't understand what's going on, either, but unsurprisingly this fails utterly
// if the page is zoomed.
// in Firefox:
// event.pageX|pageY are straight-up unsupported
// if you don't believe me, uncomment and see for yourself:
// console.log('x,y = ' + [e.originalEvent.x, e.originalEvent.y]);
// console.log('screenX,screenY = ' + [e.originalEvent.screenX, e.originalEvent.screenY]);
// console.log('clientX,clientY = ' + [e.originalEvent.clientX, e.originalEvent.clientY]);
// console.log('pageX,pageY = ' + [e.originalEvent.pageX, e.originalEvent.pageY]);
// Because of this, we're just going to steal the values from the drop event, where
// everything is sane.
var $newTeamEl = this.$('.team[data-value=' + newLoc + ']');
var finalPos = $newTeamEl.offset();
$newTeamEl.css('transform', 'translate(' + (this.finalOffset[0] - finalPos.left) + 'px, ' + (this.finalOffset[1] - finalPos.top) + 'px)');
setTimeout(function () {
$newTeamEl.css('transition', 'transform 0.15s');
// it's 2015 and Safari doesn't support unprefixed transition!!!
$newTeamEl.css('-webkit-transition', '-webkit-transform 0.15s');
$newTeamEl.css('transform', 'translate(0px, 0px)');
});
}
},
dragEnterTeam: function (e) {
if (!app.dragging) return;
var $draggingLi = $(app.dragging).parent();
this.dragLeaveFolder();
if (e.currentTarget === app.dragging) {
e.preventDefault();
return;
}
var hoverLoc = parseInt(e.currentTarget.dataset.value, 10);
if (app.draggingLoc > hoverLoc) {
// dragging up
$(e.currentTarget).parent().before($draggingLi);
app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) - 0.5;
} else {
// dragging down
$(e.currentTarget).parent().after($draggingLi);
app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) + 0.5;
}
},
dragEnterFolder: function (e) {
if (!app.dragging) return;
this.dragLeaveFolder();
if (e.currentTarget === app.draggingFolder) {
return;
}
var format = e.currentTarget.dataset.value;
if (format === '+' || format === '++' || format === 'all' || format === this.curFolder) {
return;
}
if (parseInt(app.dragging.dataset.value, 10) >= Storage.teams.length && format.slice(-1) !== '/') {
// dragging a team file, already has a known format
return;
}
app.draggingFolder = e.currentTarget;
$(app.draggingFolder).addClass('active');
// amusing note: using .detach() instead of .hide() will make `dragend` not fire
$(app.dragging).parent().hide();
},
dragLeaveFolder: function (e) {
// sometimes there's a race condition and dragEnter happens before dragLeave
if (e && e.currentTarget !== app.draggingFolder) return;
if (!app.dragging || !app.draggingFolder) return;
$(app.draggingFolder).removeClass('active');
app.draggingFolder = null;
$(app.dragging).parent().show();
},
defaultDragEnterTeam: function (e) {
var dataTransfer = e.originalEvent.dataTransfer;
if (!dataTransfer) return;
if (dataTransfer.types.indexOf && dataTransfer.types.indexOf('Files') === -1) return;
if (dataTransfer.types.contains && !dataTransfer.types.contains('Files')) return;
if (dataTransfer.files[0] && dataTransfer.files[0].name.slice(-4) !== '.txt') return;
// We're dragging a file! It might be a team!
if (app.curFolder && app.curFolder.slice(-1) !== '/') {
this.selectFolder('all');
}
this.$('.teamlist').append('<li class="dragging"><div class="team" data-value="' + Storage.teams.length + '"></div></li>');
app.dragging = this.$('.dragging .team')[0];
app.draggingLoc = Storage.teams.length;
app.draggingOffsetX = 180;
app.draggingOffsetY = 25;
app.draggingRoom = this.id;
},
defaultDropTeam: function (e) {
if (e.originalEvent.dataTransfer.files && e.originalEvent.dataTransfer.files[0]) {
var file = e.originalEvent.dataTransfer.files[0];
var name = file.name;
if (name.slice(-4) !== '.txt') {
app.dragging = null;
this.updateTeamList();
app.addPopupMessage("Your file is not a valid team. Team files are .txt files.");
return;
}
var reader = new FileReader();
var self = this;
reader.onload = function (e) {
var team;
try {
team = Storage.packTeam(Storage.importTeam(e.target.result));
} catch (err) {
app.addPopupMessage("Your file is not a valid team.");
self.updateTeamList();
return;
}
var name = file.name;
if (name.slice(name.length - 4).toLowerCase() === '.txt') {
name = name.substr(0, name.length - 4);
}
var format = '';
var bracketIndex = name.indexOf(']');
if (bracketIndex >= 0) {
format = name.substr(1, bracketIndex - 1);
name = $.trim(name.substr(bracketIndex + 1));
}
Storage.teams.push({
name: name,
format: format,
team: team,
folder: '',
iconCache: ''
});
self.finishDrop();
};
reader.readAsText(file);
}
this.finalOffset = [e.originalEvent.pageX - app.draggingOffsetX, e.originalEvent.pageY - app.draggingOffsetY];
},
/*********************************************************
* Team view
*********************************************************/
updateTeamView: function () {
this.curChartName = '';
this.curChartType = '';
var buf = '';
if (this.exportMode) {
buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="saveImport"><i class="fa fa-upload"></i> Import/Export</button> <button name="saveImport" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>';
buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportTeam(this.curSetList)) + '</textarea></div>';
} else {
buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="import"><i class="fa fa-upload"></i> Import/Export</button></div>';
buf += '<div class="teamchartbox">';
buf += '<ol class="teamchart">';
buf += '<li>' + this.clipboardHTML() + '</li>';
var i = 0;
if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].species) {
this.curSetList.splice(this.curSetList.length - 1, 1);
}
if (exports.BattleFormats) {
buf += '<li class="format-select">';
buf += '<label class="label">Format:</label><button class="select formatselect teambuilderformatselect" name="format" value="' + this.curTeam.format + '">' + (Tools.escapeFormat(this.curTeam.format) || '<em>Select a format</em>') + '</button>';
buf += ' <button name="validate" class="button"><i class="fa fa-check"></i> Validate</button></li>';
}
if (!this.curSetList.length) {
buf += '<li><em>you have no pokemon lol</em></li>';
}
for (i = 0; i < this.curSetList.length; i++) {
if (this.curSetList.length < 6 && this.deletedSet && i === this.deletedSetLoc) {
buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
buf += this.renderSet(this.curSetList[i], i);
}
if (this.deletedSet && i === this.deletedSetLoc) {
buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
if (i === 0) {
buf += '<li><button name="import" class="button big"><i class="fa fa-upload"></i> Import from text</button></li>';
}
if (i < 6) {
buf += '<li><button name="addPokemon" class="button big"><i class="fa fa-plus"></i> Add Pokémon</button></li>';
}
buf += '</ol>';
buf += '</div>';
}
this.$el.html('<div class="teamwrapper">' + buf + '</div>');
this.$(".teamedit textarea").focus().select();
if ($(window).width() < 640) this.show();
},
renderSet: function (set, i) {
var template = Tools.getTemplate(set.species);
var buf = '<li value="' + i + '">';
if (!set.species) {
if (this.deletedSet) {
buf += '<div class="setmenu setmenu-left"><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></div>';
}
buf += '<div class="setmenu"><button name="importSet"><i class="fa fa-upload"></i>Import</button></div>';
buf += '<div class="setchart"><div class="setcol setcol-icon" style="background-image:url(' + Tools.resourcePrefix + 'sprites/bw/0.png);"><span class="itemicon"></span><div class="setcell setcell-pokemon"><label>Pokemon</label><input type="text" name="pokemon" class="chartinput" value="" /></div></div></div>';
buf += '</li>';
return buf;
}
buf += '<div class="setmenu"><button name="copySet"><i class="fa fa-files-o"></i>Copy</button> <button name="importSet"><i class="fa fa-upload"></i>Import/Export</button> <button name="moveSet"><i class="fa fa-arrows"></i>Move</button> <button name="deleteSet"><i class="fa fa-trash"></i>Delete</button></div>';
buf += '<div class="setchart-nickname">';
buf += '<label>Nickname</label><input type="text" value="' + Tools.escapeHTML(set.name || set.species) + '" name="nickname" />';
buf += '</div>';
buf += '<div class="setchart">';
// icon
var itemicon = '<span class="itemicon"></span>';
if (set.item) {
var item = Tools.getItem(set.item);
itemicon = '<span class="itemicon" style="' + Tools.getItemIcon(item) + '"></span>';
}
buf += '<div class="setcol setcol-icon" style="' + Tools.getTeambuilderSprite(set) + ';">' + itemicon + '<div class="setcell setcell-pokemon"><label>Pokemon</label><input type="text" name="pokemon" class="chartinput" value="' + Tools.escapeHTML(set.species) + '" /></div></div>';
// details
buf += '<div class="setcol setcol-details"><div class="setrow">';
buf += '<div class="setcell setcell-details"><label>Details</label><button class="setdetails" tabindex="-1" name="details">';
var GenderChart = {
'M': 'Male',
'F': 'Female',
'N': '—'
};
buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>';
if (this.curTeam.gen > 1) {
buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[template.gender || set.gender || 'N'] + '</span>';
buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>';
buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>';
}
buf += '</button></div>';
buf += '</div><div class="setrow">';
if (this.curTeam.gen > 1) buf += '<div class="setcell setcell-item"><label>Item</label><input type="text" name="item" class="chartinput" value="' + Tools.escapeHTML(set.item) + '" /></div>';
if (this.curTeam.gen > 2) buf += '<div class="setcell setcell-ability"><label>Ability</label><input type="text" name="ability" class="chartinput" value="' + Tools.escapeHTML(set.ability) + '" /></div>';
buf += '</div></div>';
// moves
if (!set.moves) set.moves = [];
buf += '<div class="setcol setcol-moves"><div class="setcell"><label>Moves</label>';
buf += '<input type="text" name="move1" class="chartinput" value="' + Tools.escapeHTML(set.moves[0]) + '" /></div>';
buf += '<div class="setcell"><input type="text" name="move2" class="chartinput" value="' + Tools.escapeHTML(set.moves[1]) + '" /></div>';
buf += '<div class="setcell"><input type="text" name="move3" class="chartinput" value="' + Tools.escapeHTML(set.moves[2]) + '" /></div>';
buf += '<div class="setcell"><input type="text" name="move4" class="chartinput" value="' + Tools.escapeHTML(set.moves[3]) + '" /></div>';
buf += '</div>';
// stats
buf += '<div class="setcol setcol-stats"><div class="setrow"><label>Stats</label><button class="setstats" name="stats" class="chartinput">';
buf += '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>';
var stats = {};
for (var j in BattleStatNames) {
if (j === 'spd' && this.curTeam.gen === 1) continue;
stats[j] = this.getStat(j, set);
var ev = '<em>' + (set.evs[j] || '') + '</em>';
if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === j) {
ev += '<small>+</small>';
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === j) {
ev += '<small>−</small>';
}
var width = stats[j] * 75 / 504;
if (j == 'hp') width = stats[j] * 75 / 704;
if (width > 75) width = 75;
var color = Math.floor(stats[j] * 180 / 714);
if (color > 360) color = 360;
var statName = this.curTeam.gen === 1 && j === 'spa' ? 'Spc' : BattleStatNames[j];
buf += '<span class="statrow"><label>' + statName + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + ev + '</span>';
}
buf += '</button></div></div>';
buf += '</div></li>';
return buf;
},
saveImport: function () {
Storage.activeSetList = this.curSetList = Storage.importTeam(this.$('.teamedit textarea').val());
this.back();
},
addPokemon: function () {
if (!this.curTeam) return;
var team = this.curSetList;
if (!team.length || team[team.length - 1].species) {
var newPokemon = {
name: '',
species: '',
item: '',
nature: '',
evs: {},
ivs: {},
moves: []
};
team.push(newPokemon);
}
this.curSet = team[team.length - 1];
this.curSetLoc = team.length - 1;
this.curChartName = '';
this.update();
this.$('input[name=pokemon]').select();
},
pastePokemon: function (i, btn) {
if (!this.curTeam) return;
var team = this.curSetList;
if (team.length >= 6) return;
if (!this.clipboardCount()) return;
if (team.push($.extend(true, {}, this.clipboard[0])) >= 6) {
$(btn).css('display', 'none');
}
this.update();
this.save();
},
saveFlag: false,
save: function () {
this.saveFlag = true;
Storage.saveTeams();
},
validate: function () {
var format = this.curTeam.format;
if (!format) {
app.addPopupMessage('You need to pick a format to validate your team.');
return;
}
if (window.BattleFormats && BattleFormats[this.curTeam.format] && BattleFormats[this.curTeam.format].hasBattleFormat) {
format = BattleFormats[this.curTeam.format].battleFormat;
}
app.sendTeam(this.curTeam);
app.send('/vtm ' + format);
},
teamNameChange: function (e) {
var name = ($.trim(e.currentTarget.value) || 'Untitled ' + (this.curTeamLoc + 1));
if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator.");
name = name.replace(/[\\\/]/g, '');
}
this.curTeam.name = name;
e.currentTarget.value = name;
this.save();
},
format: function (format, button) {
if (!window.BattleFormats) {
return;
}
var self = this;
app.addPopup(FormatPopup, {format: format, sourceEl: button, selectType: 'teambuilder', onselect: function (newFormat) {
self.changeFormat(newFormat);
}});
},
changeFormat: function (format) {
this.curTeam.format = format;
this.curTeam.gen = this.getGen(this.curTeam.format);
this.save();
if (this.curTeam.gen === 5 && !Tools.loadedSpriteData['bw']) Tools.loadSpriteData('bw');
this.update();
},
nicknameChange: function (e) {
var i = +$(e.currentTarget).closest('li').attr('value');
var set = this.curSetList[i];
var name = $.trim(e.currentTarget.value) || set.species;
e.currentTarget.value = set.name = name;
this.save();
},
// clipboard
clipboard: [],
clipboardCount: function () {
return this.clipboard.length;
},
clipboardVisible: function () {
return !!this.clipboardCount();
},
clipboardHTML: function () {
var buf = '';
buf += '<div class="teambuilder-clipboard-container" style="display: ' + (this.clipboardVisible() ? 'block' : 'none') + ';">';
buf += '<div class="teambuilder-clipboard-title">Clipboard:</div>';
buf += '<div class="teambuilder-clipboard-data" tabindex="-1">' + this.clipboardInnerHTML() + '</div>';
buf += '<div class="teambuilder-clipboard-buttons">';
if (this.curTeam && this.curSetList.length < 6) {
buf += '<button name="pastePokemon" class="teambuilder-clipboard-button-left"><i class="fa fa-clipboard"></i> Paste!</button>';
}
buf += '<button name="clipboardRemoveAll" class="teambuilder-clipboard-button-right"><i class="fa fa-trash"></i> Clear clipboard</button>';
buf += '</div>';
buf += '</div>';
return buf;
},
clipboardInnerHTMLCache: '',
clipboardInnerHTML: function () {
if (this.clipboardInnerHTMLCache) {
return this.clipboardInnerHTMLCache;
}
var buf = '';
for (var i = 0; i < this.clipboardCount(); i++) {
var res = this.clipboard[i];
var pokemon = Tools.getTemplate(res.species);
buf += '<div class="result" data-id="' + i + '">';
buf += '<div class="section"><span class="icon" style="' + Tools.getIcon(res.species) + '"></span>';
buf += '<span class="species">' + (pokemon.species === pokemon.baseSpecies ? pokemon.species : (pokemon.baseSpecies + '-<small>' + pokemon.species.substr(pokemon.baseSpecies.length + 1) + '</small>')) + '</span></div>';
buf += '<div class="section"><span class="ability-item">' + (res.ability || '<i>No ability</i>') + '<br />' + (res.item || '<i>No item</i>') + '</span></div>';
buf += '<div class="section no-border">';
for (var j = 0; j < 4; j++) {
if (!(j & 1)) {
buf += '<span class="moves">';
}
buf += (res.moves[j] || '<i>No move</i>') + (!(j & 1) ? '<br />' : '');
if (j & 1) {
buf += '</span>';
}
}
buf += '</div>';
buf += '</div>';
}
this.clipboardInnerHTMLCache = buf;
return buf;
},
clipboardUpdate: function () {
this.clipboardInnerHTMLCache = '';
$('.teambuilder-clipboard-data').html(this.clipboardInnerHTML());
},
clipboardExpanded: false,
clipboardExpand: function () {
var $clipboard = $('.teambuilder-clipboard-data');
$clipboard.animate({height: this.clipboardCount() * 28}, 500, function () {
setTimeout(function () { $clipboard.focus(); }, 100);
});
setTimeout(function () {
this.clipboardExpanded = true;
}.bind(this), 10);
},
clipboardShrink: function () {
var $clipboard = $('.teambuilder-clipboard-data');
$clipboard.animate({height: 26}, 500);
setTimeout(function () {
this.clipboardExpanded = false;
}.bind(this), 10);
},
clipboardResultSelect: function (e) {
if (!this.clipboardExpanded) return;
e.preventDefault();
e.stopPropagation();
var target = +($(e.target).closest('.result').data('id'));
if (target === -1) {
this.clipboardShrink();
this.clipboardRemoveAll();
return;
}
this.clipboard.unshift(this.clipboard.splice(target, 1)[0]);
this.clipboardUpdate();
this.clipboardShrink();
},
clipboardAdd: function (set) {
if (this.clipboard.unshift(set) > 6) {
// we don't want the clipboard so big that it lags the teambuilder
this.clipboard.pop();
}
this.clipboardUpdate();
if (this.clipboardCount() === 1) {
var $clipboard = $('.teambuilder-clipboard-container').css('opacity', 0);
$clipboard.slideDown(250, function () {
$clipboard.animate({opacity: 1}, 250);
});
}
},
clipboardRemoveAll: function () {
this.clipboard = [];
var self = this;
var $clipboard = $('.teambuilder-clipboard-container');
$clipboard.animate({opacity: 0}, 250, function () {
$clipboard.slideUp(250, function () {
self.clipboardUpdate();
});
});
},
// copy/import/export/move/delete
copySet: function (i, button) {
i = +($(button).closest('li').attr('value'));
this.clipboardAdd($.extend(true, {}, this.curSetList[i]));
button.blur();
},
wasViewingPokemon: false,
importSet: function (i, button) {
i = +($(button).closest('li').attr('value'));
this.wasViewingPokemon = true;
if (!this.curSet) {
this.wasViewingPokemon = false;
this.selectPokemon(i);
}
this.$('li').find('input, button').prop('disabled', true);
this.$chart.hide();
this.$('.teambuilder-pokemon-import')
.show()
.find('textarea')
.val(Storage.exportTeam([this.curSet]).trim())
.focus()
.select();
},
closePokemonImport: function (force) {
if (!this.wasViewingPokemon) return this.back();
var $li = this.$('li');
var i = +($li.attr('value'));
this.$('.teambuilder-pokemon-import').hide();
this.$chart.show();
if (force === true) return this.selectPokemon(i);
$li.find('input, button').prop('disabled', false);
},
savePokemonImport: function (i) {
i = +(this.$('li').attr('value'));
var curSet = Storage.importTeam(this.$('.pokemonedit').val())[0];
if (curSet) {
this.curSet = curSet;
this.curSetList[i] = curSet;
}
this.closePokemonImport(true);
},
moveSet: function (i, button) {
i = +($(button).closest('li').attr('value'));
app.addPopup(MovePopup, {
i: i,
team: this.curSetList
});
},
deleteSet: function (i, button) {
i = +($(button).closest('li').attr('value'));
this.deletedSetLoc = i;
this.deletedSet = this.curSetList.splice(i, 1)[0];
if (this.curSet) {
this.addPokemon();
} else {
this.update();
}
this.save();
},
undeleteSet: function () {
if (this.deletedSet) {
var loc = this.deletedSetLoc;
this.curSetList.splice(loc, 0, this.deletedSet);
this.deletedSet = null;
this.deletedSetLoc = -1;
this.save();
if (this.curSet) {
this.curSetLoc = loc;
this.curSet = this.curSetList[loc];
this.curChartName = '';
this.update();
this.updateChart();
} else {
this.update();
}
}
},
/*********************************************************
* Set view
*********************************************************/
updateSetView: function () {
// pokemon
var buf = '<div class="pad">';
buf += '<button name="back"><i class="fa fa-chevron-left"></i> Team</button></div>';
buf += '<div class="teambar">';
buf += this.renderTeambar();
buf += '</div>';
// pokemon
buf += '<div class="teamchartbox individual">';
buf += '<ol class="teamchart">';
buf += this.renderSet(this.curSet, this.curSetLoc);
buf += '</ol>';
buf += '</div>';
// results
this.chartPrevSearch = '[init]';
buf += '<div class="teambuilder-results"></div>';
// import/export
buf += '<div class="teambuilder-pokemon-import">';
buf += '<div class="pokemonedit-buttons"><button name="closePokemonImport"><i class="fa fa-chevron-left"></i> Back</button> <button name="savePokemonImport"><i class="fa fa-floppy-o"></i> Save</button></div>';
buf += '<textarea class="pokemonedit textbox" rows="14"></textarea>';
buf += '</div>';
this.$el.html('<div class="teamwrapper">' + buf + '</div>');
if ($(window).width() < 640) this.show();
this.$chart = this.$('.teambuilder-results');
},
updateSetTop: function () {
this.$('.teambar').html(this.renderTeambar());
this.$('.teamchart').first().html(this.renderSet(this.curSet, this.curSetLoc));
},
renderTeambar: function () {
var buf = '';
var isAdd = false;
if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].name && this.curSetLoc !== this.curSetList.length - 1) {
this.curSetList.splice(this.curSetList.length - 1, 1);
}
for (var i = 0; i < this.curSetList.length; i++) {
var set = this.curSetList[i];
var pokemonicon = '<span class="pokemonicon pokemonicon-' + i + '" style="' + Tools.getIcon(set) + '"></span>';
if (!set.name) {
buf += '<button disabled="disabled" class="addpokemon"><i class="fa fa-plus"></i></button> ';
isAdd = true;
} else if (i == this.curSetLoc) {
buf += '<button disabled="disabled" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name || '<i class="fa fa-plus"></i>') + '</button> ';
} else {
buf += '<button name="selectPokemon" value="' + i + '" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name) + '</button> ';
}
}
if (this.curSetList.length < 6 && !isAdd) {
buf += '<button name="addPokemon"><i class="fa fa-plus"></i></button> ';
}
return buf;
},
updatePokemonSprite: function () {
var set = this.curSet;
if (!set) return;
var shiny = (set.shiny ? '-shiny' : '');
var sprite = Tools.getTemplate(set.species).spriteid;
if (BattlePokemonSprites && BattlePokemonSprites[sprite] && BattlePokemonSprites[sprite].front && BattlePokemonSprites[sprite].front.anif && set.gender === 'F') {
sprite += '-f';
}
this.$('.setcol-icon').css('background-image', Tools.getTeambuilderSprite(set).substr(17));
this.$('.pokemonicon-' + this.curSetLoc).css('background', Tools.getIcon(set).substr(11));
var item = Tools.getItem(set.item);
if (item.id) {
this.$('.setcol-icon .itemicon').css('background', Tools.getItemIcon(item).substr(11));
} else {
this.$('.setcol-icon .itemicon').css('background', 'none');
}
this.updateStatGraph();
},
updateStatGraph: function () {
var set = this.curSet;
if (!set) return;
var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''};
// stat cell
var buf = '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>';
for (var stat in stats) {
if (stat === 'spd' && this.curTeam.gen === 1) continue;
stats[stat] = this.getStat(stat, set);
var ev = '<em>' + (set.evs[stat] || '') + '</em>';
if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) {
ev += '<small>+</small>';
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) {
ev += '<small>−</small>';
}
var width = stats[stat] * 75 / 504;
if (stat == 'hp') width = stats[stat] * 75 / 704;
if (width > 75) width = 75;
var color = Math.floor(stats[stat] * 180 / 714);
if (color > 360) color = 360;
buf += '<span class="statrow"><label>' + BattleStatNames[stat] + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + ev + '</span>';
}
this.$('button[name=stats]').html(buf);
if (this.curChartType !== 'stats') return;
buf = '<div></div>';
for (var stat in stats) {
buf += '<div><b>' + stats[stat] + '</b></div>';
}
this.$chart.find('.statscol').html(buf);
buf = '<div></div>';
var totalev = 0;
for (var stat in stats) {
if (stat === 'spd' && this.curTeam.gen === 1) continue;
var width = stats[stat] * 180 / 504;
if (stat == 'hp') width = stats[stat] * 180 / 704;
if (width > 179) width = 179;
var color = Math.floor(stats[stat] * 180 / 714);
if (color > 360) color = 360;
buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>';
totalev += (set.evs[stat] || 0);
}
buf += '<div><em>Remaining:</em></div>';
this.$chart.find('.graphcol').html(buf);
var maxEv = this.curTeam.gen > 2 ? 510 : this.curTeam.gen === 1 ? 1275 : 1530;
if (totalev <= maxEv) {
this.$chart.find('.totalev').html('<em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em>');
} else {
this.$chart.find('.totalev').html('<b>' + (maxEv - totalev) + '</b>');
}
this.$chart.find('select[name=nature]').val(set.nature || 'Serious');
},
curChartType: '',
curChartName: '',
updateChart: function () {
var type = this.curChartType;
app.clearGlobalListeners();
if (type === 'stats') {
this.updateStatForm();
return;
}
if (type === 'details') {
this.updateDetailsForm();
return;
}
// cache movelist ref
var speciesid = toId(this.curSet.species);
var g6 = (this.curTeam.format && this.curTeam.format === 'vgc2016');
this.applyMovelist(g6, speciesid);
this.$chart.html('<em>Loading ' + this.curChartType + '...</em>');
var self = this;
if (this.updateChartTimeout) clearTimeout(this.updateChartTimeout);
this.updateChartTimeout = setTimeout(function () {
self.updateChartTimeout = null;
if (self.curChartType === 'stats' || self.curChartType === 'details' || !self.curChartName) return;
self.$chart.html(Chart.chart(self.$('input[name=' + self.curChartName + ']').val(), self.curChartType, true, _.bind(self.arrangeCallback[self.curChartType], self), null, self.curTeam.gen));
}, 10);
},
updateChartTimeout: null,
updateChartDelayed: function () {
// cache movelist ref
var speciesid = toId(this.curSet.species);
var g6 = (this.curTeam.format && this.curTeam.format === 'vgc2016');
this.applyMovelist(g6, speciesid);
var self = this;
if (this.updateChartTimeout) clearTimeout(this.updateChartTimeout);
this.updateChartTimeout = setTimeout(function () {
self.updateChartTimeout = null;
if (self.curChartType === 'stats' || self.curChartType === 'details') return;
self.$chart.html(Chart.chart(self.$('input[name=' + self.curChartName + ']').val(), self.curChartType, false, _.bind(self.arrangeCallback[self.curChartType], self), null, self.curTeam.gen));
}, 200);
},
selectPokemon: function (i) {
i = +i;
var set = this.curSetList[i];
if (set) {
this.curSet = set;
this.curSetLoc = i;
var name = this.curChartName || 'details';
if (name === 'details' || name === 'stats') {
this.update();
this.updateChart();
} else {
this.curChartName = '';
this.update();
this.$('input[name=' + name + ']').select();
}
}
},
stats: function (i, button) {
if (!this.curSet) this.selectPokemon($(button).closest('li').val());
this.curChartName = 'stats';
this.curChartType = 'stats';
this.updateStatForm();
},
details: function (i, button) {
if (!this.curSet) this.selectPokemon($(button).closest('li').val());
this.curChartName = 'details';
this.curChartType = 'details';
this.updateDetailsForm();
},
/*********************************************************
* Set stat form
*********************************************************/
plus: '',
minus: '',
smogdexLink: function (template) {
var template = Tools.getTemplate(template);
var format = this.curTeam && this.curTeam.format;
var smogdexid = toId(template.baseSpecies);
if (template.isNonstandard) {
return 'http://www.smogon.com/cap/pokemon/strategies/' + smogdexid;
}
if (template.speciesid === 'meowstic') {
smogdexid = 'meowstic-m';
} else if (template.speciesid === 'hoopaunbound') {
smogdexid = 'hoopa-alt';
} else if (smogdexid === 'rotom' || smogdexid === 'deoxys' || smogdexid === 'kyurem' || smogdexid === 'giratina' || smogdexid === 'shaymin' || smogdexid === 'tornadus' || smogdexid === 'thundurus' || smogdexid === 'landorus' || smogdexid === 'pumpkaboo' || smogdexid === 'gourgeist' || smogdexid === 'arceus' || smogdexid === 'meowstic') {
if (template.forme) smogdexid += '-' + toId(template.forme);
}
var generationNumber = 6;
if (format.substr(0, 3) === 'gen') {
var number = format.charAt(3);
if ('1' <= number && number <= '5') {
generationNumber = +number;
format = format.substr(4);
}
}
var generation = ['rb', 'gs', 'rs', 'dp', 'bw', 'xy'][generationNumber - 1];
if (format === 'battlespotdoubles') {
smogdexid += '/vgc15';
} else if (format === 'doublesou' || format === 'doublesuu') {
smogdexid += '/doubles';
} else if (format === 'ou' || format === 'uu' || format === 'ru' || format === 'nu' || format === 'pu' || format === 'lc') {
smogdexid += '/' + format;
}
return 'http://smogon.com/dex/' + generation + '/pokemon/' + smogdexid + '/';
},
updateStatForm: function (setGuessed) {
var buf = '';
var set = this.curSet;
var template = Tools.getTemplate(this.curSet.species);
var baseStats = template.baseStats;
buf += '<h3>EVs</h3>';
buf += '<div class="statform">';
var role = this.guessRole();
var guessedEVs = {};
var guessedPlus = '';
var guessedMinus = '';
buf += '<p class="suggested"><small>Suggested spread:';
if (role === '?') {
buf += ' (Please choose 4 moves to get a suggested spread) (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon analysis</a>)</small></p>';
} else {
guessedEVs = this.guessEVs(role);
guessedPlus = guessedEVs.plusStat;
delete guessedEVs.plusStat;
guessedMinus = guessedEVs.minusStat;
delete guessedEVs.minusStat;
buf += ' </small><button name="setStatFormGuesses">' + role + ': ';
for (var i in guessedEVs) {
if (guessedEVs[i]) {
var statName = this.curTeam.gen === 1 && i === 'spa' ? 'Spc' : BattleStatNames[i];
buf += '' + guessedEVs[i] + ' ' + statName + ' / ';
}
}
if (guessedPlus && guessedMinus) buf += ' (+' + BattleStatNames[guessedPlus] + ', -' + BattleStatNames[guessedMinus] + ')';
else buf = buf.slice(0, -3);
buf += '</button><small> (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon analysis</a>)</small></p>';
//buf += ' <small>(' + role + ' | bulk: phys ' + Math.round(this.moveCount.physicalBulk/1000) + ' + spec ' + Math.round(this.moveCount.specialBulk/1000) + ' = ' + Math.round(this.moveCount.bulk/1000) + ')</small>';
}
if (setGuessed) {
set.evs = guessedEVs;
this.plus = guessedPlus;
this.minus = guessedMinus;
this.updateNature();
this.save();
this.updateStatGraph();
this.natureChange();
return;
}
var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''};
if (this.curTeam.gen === 1) delete stats.spd;
if (!set) return;
var nature = BattleNatures[set.nature || 'Serious'];
if (!nature) nature = {};
// label column
buf += '<div class="col labelcol"><div></div>';
buf += '<div><label>HP</label></div><div><label>Attack</label></div><div><label>Defense</label></div><div>';
if (this.curTeam.gen === 1) {
buf += '<label>Special</label></div>';
} else {
buf += '<label>Sp. Atk.</label></div><div><label>Sp. Def.</label></div>';
}
buf += '<div><label>Speed</label></div></div>';
buf += '<div class="col basestatscol"><div><em>Base</em></div>';
for (var i in stats) {
buf += '<div><b>' + baseStats[i] + '</b></div>';
}
buf += '</div>';
buf += '<div class="col graphcol"><div></div>';
for (var i in stats) {
stats[i] = this.getStat(i);
var width = stats[i] * 180 / 504;
if (i == 'hp') width = Math.floor(stats[i] * 180 / 704);
if (width > 179) width = 179;
var color = Math.floor(stats[i] * 180 / 714);
if (color > 360) color = 360;
buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>';
}
buf += '<div><em>Remaining:</em></div>';
buf += '</div>';
buf += '<div class="col evcol"><div><strong>EVs</strong></div>';
var totalev = 0;
this.plus = '';
this.minus = '';
for (var i in stats) {
var width = stats[i] * 200 / 504;
if (i == 'hp') width = stats[i] * 200 / 704;
if (width > 200) width = 200;
var val = '' + (set.evs[i] || '');
if (nature.plus === i) {
val += '+';
this.plus = i;
}
if (nature.minus === i) {
val += '-';
this.minus = i;
}
buf += '<div><input type="text" name="stat-' + i + '" value="' + val + '" class="inputform numform" /></div>';
totalev += (set.evs[i] || 0);
}
var maxEv = this.curTeam.gen > 2 ? 510 : this.curTeam.gen === 1 ? 1275 : 1530;
if (totalev <= maxEv) {
buf += '<div class="totalev"><em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em></div>';
} else {
buf += '<div class="totalev"><b>' + (maxEv - totalev) + '</b></div>';
}
buf += '</div>';
buf += '<div class="col evslidercol"><div></div>';
for (var i in stats) {
if (i === 'spd' && this.curTeam.gen === 1) continue;
buf += '<div><input type="slider" name="evslider-' + i + '" value="' + Tools.escapeHTML(set.evs[i] || '0') + '" min="0" max="252" step="4" class="evslider" /></div>';
}
buf += '</div>';
buf += '<div class="col ivcol"><div><strong>IVs</strong></div>';
var totalev = 0;
if (!set.ivs) set.ivs = {};
for (var i in stats) {
if (typeof set.ivs[i] === 'undefined' || isNaN(set.ivs[i])) set.ivs[i] = 31;
var val = '' + (set.ivs[i]);
buf += '<div><input type="number" name="iv-' + i + '" value="' + Tools.escapeHTML(val) + '" class="inputform numform" min="0" max="31" step="1" /></div>';
}
buf += '</div>';
buf += '<div class="col statscol"><div></div>';
for (var i in stats) {
buf += '<div><b>' + stats[i] + '</b></div>';
}
buf += '</div>';
if (this.curTeam.gen > 2) {
buf += '<p style="clear:both">Nature: <select name="nature">';
for (var i in BattleNatures) {
var curNature = BattleNatures[i];
buf += '<option value="' + i + '"' + (curNature === nature ? 'selected="selected"' : '') + '>' + i;
if (curNature.plus) {
buf += ' (+' + BattleStatNames[curNature.plus] + ', -' + BattleStatNames[curNature.minus] + ')';
}
buf += '</option>';
}
buf += '</select></p>';
buf += '<p><em>Protip:</em> You can also set natures by typing "+" and "-" next to a stat.</p>';
}
buf += '</div>';
this.$chart.html(buf);
var self = this;
this.suppressSliderCallback = true;
app.clearGlobalListeners();
this.$chart.find('.evslider').slider({
from: 0,
to: 252,
step: 4,
skin: 'round_plastic',
onstatechange: function (val) {
if (!self.suppressSliderCallback) self.statSlide(val, this);
},
callback: function () {
self.save();
}
});
this.suppressSliderCallback = false;
},
setStatFormGuesses: function () {
this.updateStatForm(true);
},
setSlider: function (stat, val) {
this.suppressSliderCallback = true;
this.$chart.find('input[name=evslider-' + stat + ']').slider('value', val || 0);
this.suppressSliderCallback = false;
},
updateNature: function () {
var set = this.curSet;
if (!set) return;
if (this.plus === '' || this.minus === '') {
set.nature = 'Serious';
} else {
for (var i in BattleNatures) {
if (BattleNatures[i].plus === this.plus && BattleNatures[i].minus === this.minus) {
set.nature = i;
break;
}
}
}
},
statChange: function (e) {
var inputName = '';
inputName = e.currentTarget.name;
var val = Math.abs(parseInt(e.currentTarget.value, 10));
var set = this.curSet;
if (!set) return;
if (inputName.substr(0, 5) === 'stat-') {
// EV
// Handle + and -
var stat = inputName.substr(5);
if (!set.evs) set.evs = {};
var lastchar = e.currentTarget.value.charAt(e.target.value.length - 1);
var firstchar = e.currentTarget.value.charAt(0);
var natureChange = true;
if ((lastchar === '+' || firstchar === '+') && stat !== 'hp') {
if (this.plus && this.plus !== stat) this.$chart.find('input[name=stat-' + this.plus + ']').val(set.evs[this.plus] || '');
this.plus = stat;
} else if ((lastchar === '-' || lastchar === "\u2212" || firstchar === '-' || firstchar === "\u2212") && stat !== 'hp') {
if (this.minus && this.minus !== stat) this.$chart.find('input[name=stat-' + this.minus + ']').val(set.evs[this.minus] || '');
this.minus = stat;
} else if (this.plus === stat) {
this.plus = '';
} else if (this.minus === stat) {
this.minus = '';
} else {
natureChange = false;
}
if (natureChange) {
this.updateNature();
}
// cap
if (val > 252) val = 252;
if (val < 0 || isNaN(val)) val = 0;
if (set.evs[stat] !== val || natureChange) {
set.evs[stat] = val;
this.setSlider(stat, val);
this.updateStatGraph();
}
} else {
// IV
var stat = inputName.substr(3);
if (val > 31 || isNaN(val)) val = 31;
if (val < 0) val = 0;
if (!set.ivs) set.ivs = {};
if (set.ivs[stat] !== val) {
set.ivs[stat] = val;
this.updateStatGraph();
}
}
this.save();
},
statSlide: function (val, slider) {
var stat = slider.inputNode[0].name.substr(9);
var set = this.curSet;
if (!set) return;
val = +val;
var originalVal = val;
var result = this.getStat(stat, set, val);
while (val && this.getStat(stat, set, val - 4) == result) val -= 4;
if (!this.ignoreEVLimits && set.evs) {
var total = 0;
for (var i in set.evs) {
total += (i === stat ? val : set.evs[i]);
}
if (total > 508 && val - total + 508 >= 0) {
// don't allow dragging beyond 508 EVs
val = val - total + 508;
// make sure val is a legal value
val = +val;
if (!val || val <= 0) val = 0;
if (val > 252) val = 252;
}
}
// Don't try this at home.
// I am a trained professional.
if (val !== originalVal) slider.o.pointers[0].set(val);
if (!set.evs) set.evs = {};
set.evs[stat] = val;
val = '' + (val || '') + (this.plus === stat ? '+' : '') + (this.minus === stat ? '-' : '');
this.$('input[name=stat-' + stat + ']').val(val);
this.updateStatGraph();
},
natureChange: function (e) {
var set = this.curSet;
if (!set) return;
if (e) {
set.nature = e.currentTarget.value;
}
this.plus = '';
this.minus = '';
var nature = BattleNatures[set.nature || 'Serious'];
for (var i in BattleStatNames) {
var val = '' + (set.evs[i] || '');
if (nature.plus === i) {
this.plus = i;
val += '+';
}
if (nature.minus === i) {
this.minus = i;
val += '-';
}
this.$chart.find('input[name=stat-' + i + ']').val(val);
if (!e) this.setSlider(i, set.evs[i]);
}
this.save();
this.updateStatGraph();
},
/*********************************************************
* Set details form
*********************************************************/
updateDetailsForm: function () {
var buf = '';
var set = this.curSet;
var template = Tools.getTemplate(set.species);
if (!set) return;
buf += '<h3>Details</h3>';
buf += '<form class="detailsform">';
buf += '<div class="formrow"><label class="formlabel">Level:</label><div><input type="number" min="1" max="100" step="1" name="level" value="' + Tools.escapeHTML(set.level || 100) + '" class="textbox inputform numform" /></div></div>';
if (this.curTeam.gen > 1) {
buf += '<div class="formrow"><label class="formlabel">Gender:</label><div>';
if (template.gender) {
var genderTable = {'M': "Male", 'F': "Female", 'N': "Genderless"};
buf += genderTable[template.gender];
} else {
buf += '<label><input type="radio" name="gender" value="M"' + (set.gender === 'M' ? ' checked' : '') + ' /> Male</label> ';
buf += '<label><input type="radio" name="gender" value="F"' + (set.gender === 'F' ? ' checked' : '') + ' /> Female</label> ';
buf += '<label><input type="radio" name="gender" value="N"' + (!set.gender ? ' checked' : '') + ' /> Random</label>';
}
buf += '</div></div>';
buf += '<div class="formrow"><label class="formlabel">Happiness:</label><div><input type="number" min="0" max="255" step="1" name="happiness" value="' + (typeof set.happiness === 'number' ? set.happiness : 255) + '" class="textbox inputform numform" /></div></div>';
buf += '<div class="formrow"><label class="formlabel">Shiny:</label><div>';
buf += '<label><input type="radio" name="shiny" value="yes"' + (set.shiny ? ' checked' : '') + ' /> Yes</label> ';
buf += '<label><input type="radio" name="shiny" value="no"' + (!set.shiny ? ' checked' : '') + ' /> No</label>';
buf += '</div></div>';
}
buf += '</form>';
this.$chart.html(buf);
},
detailsChange: function () {
var set = this.curSet;
if (!set) return;
// level
var level = parseInt(this.$chart.find('input[name=level]').val(), 10);
if (!level || level > 100 || level < 1) level = 100;
if (level !== 100 || set.level) set.level = level;
// happiness
var happiness = parseInt(this.$chart.find('input[name=happiness]').val(), 10);
if (happiness > 255) happiness = 255;
if (happiness < 0) happiness = 255;
set.happiness = happiness;
if (set.happiness === 255) delete set.happiness;
// shiny
var shiny = (this.$chart.find('input[name=shiny]:checked').val() === 'yes');
if (shiny) {
set.shiny = true;
} else {
delete set.shiny;
}
var gender = this.$chart.find('input[name=gender]:checked').val();
if (gender === 'M' || gender === 'F') {
set.gender = gender;
} else {
delete set.gender;
}
// update details cell
var buf = '';
var GenderChart = {
'M': 'Male',
'F': 'Female',
'N': '—'
};
buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>';
if (this.curTeam.gen > 1) {
buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[set.gender || 'N'] + '</span>';
buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>';
buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>';
}
this.$('button[name=details]').html(buf);
this.save();
this.updatePokemonSprite();
},
/*********************************************************
* Set charts
*********************************************************/
arrangeCallback: {
pokemon: function (pokemon) {
if (!pokemon) {
if (this.curTeam) {
if (this.curTeam.format === 'ubers' || this.curTeam.format === 'anythinggoes') return ['Uber', 'OU', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'ou') return ['OU', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'cap') return ['CAP', 'OU', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'uu') return ['UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'ru') return ['RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'nu') return ['NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'pu') return ['PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'lc') return ['LC'];
}
return ['OU', 'Uber', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC', 'Unreleased', 'CAP'];
}
var speciesid = toId(pokemon.species);
var tierData = exports.BattleFormatsData[speciesid];
if (!tierData) return 'Illegal';
var displayTier = {"(OU)": "OU only when combining mega and non-mega usage", "(UU)": "UU only when combining mega and non-mega usage", "(RU)": "RU only when combining mega and non-mega usage", "(NU)": "NU only when combining mega and non-mega usage"};
if (tierData.tier in displayTier) {
return displayTier[tierData.tier];
}
return tierData.tier;
},
item: function (item) {
if (!item) return ['Items'];
return 'Items';
},
ability: function (ability) {
if (!this.curSet) return;
var template = Tools.getTemplate(this.curSet.species);
var isMega = false;
if (template.forme.substr(0, 4) === 'Mega' && this.curTeam.format !== 'balancedhackmons') {
if (!ability) return ['Pre-Mega Abilities', 'Pre-Mega Hidden Ability'];
isMega = true;
template = Tools.getTemplate(template.baseSpecies);
}
if (!ability) return ['Abilities', 'Hidden Ability'];
if (!template.abilities) return 'Abilities';
if (ability.name === template.abilities['0']) return isMega ? 'Pre-Mega Abilities' : 'Abilities';
if (ability.name === template.abilities['1']) return isMega ? 'Pre-Mega Abilities' : 'Abilities';
if (ability.name === template.abilities['H']) return isMega ? 'Pre-Mega Hidden Ability' : 'Hidden Ability';
if (!this.curTeam || this.curTeam.format !== 'balancedhackmons') return 'Illegal';
},
move: function (move) {
if (!this.curSet) return;
if (!move) return ['Usable Moves', 'Moves', 'Usable Sketch Moves', 'Sketch Moves'];
var movelist = this.movelist;
if (!movelist) return 'Illegal';
if (!movelist[move.id]) {
if (movelist['sketch'] && move.id !== 'chatter' && move.id !== 'struggle') {
if (move.isViable) return 'Usable Sketch Moves';
return 'Sketch Moves';
}
if (!this.curTeam || this.curTeam.format !== 'balancedhackmons') return 'Illegal';
}
var speciesid = toId(this.curSet.species);
if (move.isViable) return 'Usable Moves';
return 'Moves';
}
},
chartTypes: {
pokemon: 'pokemon',
item: 'item',
ability: 'ability',
move1: 'move',
move2: 'move',
move3: 'move',
move4: 'move',
stats: 'stats',
details: 'details'
},
chartClick: function (e) {
this.chartSet($(e.currentTarget).data('name'), true);
},
chartKeydown: function (e) {
var modifier = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || e.cmdKey);
if (e.keyCode === 13 || (e.keyCode === 9 && !modifier)) {
if (!this.arrangeCallback[this.curChartType]) return;
e.stopPropagation();
e.preventDefault();
var name = e.currentTarget.name;
this.$chart.html(Chart.chart(e.currentTarget.value, this.curChartType, false, _.bind(this.arrangeCallback[this.curChartType], this), null, this.curTeam.gen));
var val = Chart.firstResult;
this.chartSet(val, true);
return;
}
},
chartKeyup: function () {
this.updateChartDelayed();
},
chartFocus: function (e) {
var $target = $(e.currentTarget);
var name = e.currentTarget.name;
var type = this.chartTypes[name];
$target.removeClass('incomplete');
if (this.curChartName === name) return;
if (!this.curSet) {
var i = +$target.closest('li').prop('value');
this.curSet = this.curSetList[i];
this.curSetLoc = i;
this.update();
if (type === 'stats' || type === 'details') {
this.$('button[name=' + name + ']').click();
} else {
this.$('input[name=' + name + ']').select();
}
return;
}
this.curChartName = name;
this.curChartType = type;
this.updateChart();
},
chartChange: function (e) {
var name = e.currentTarget.name;
var type = this.chartTypes[name];
var arrange = null;
if (this.arrangeCallback[this.curChartType]) {
arrange = _.bind(this.arrangeCallback[this.curChartType], this);
}
this.$chart.html(Chart.chart(e.currentTarget.value, type, false, arrange, null, this.curTeam.gen));
var val = Chart.firstResult;
var id = toId(e.currentTarget.value);
if (toId(val) !== id) {
$(e.currentTarget).addClass('incomplete');
return;
}
this.chartSet(val);
},
chartSet: function (val, selectNext) {
var inputName = this.curChartName;
var id = toId(val);
this.$('input[name=' + inputName + ']').val(val).removeClass('incomplete');
switch (inputName) {
case 'pokemon':
this.setPokemon(val, selectNext);
break;
case 'item':
this.curSet.item = val;
this.updatePokemonSprite();
if (selectNext) this.$(this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]').select();
break;
case 'ability':
this.curSet.ability = val;
if (selectNext) this.$('input[name=move1]').select();
break;
case 'move1':
this.curSet.moves[0] = val;
this.chooseMove(val);
if (selectNext) this.$('input[name=move2]').select();
break;
case 'move2':
if (!this.curSet.moves[0]) this.curSet.moves[0] = '';
this.curSet.moves[1] = val;
this.chooseMove(val);
this.$('input[name=move3]').select();
break;
case 'move3':
if (!this.curSet.moves[0]) this.curSet.moves[0] = '';
if (!this.curSet.moves[1]) this.curSet.moves[1] = '';
this.curSet.moves[2] = val;
this.chooseMove(val);
if (selectNext) this.$('input[name=move4]').select();
break;
case 'move4':
if (!this.curSet.moves[0]) this.curSet.moves[0] = '';
if (!this.curSet.moves[1]) this.curSet.moves[1] = '';
if (!this.curSet.moves[2]) this.curSet.moves[2] = '';
this.curSet.moves[3] = val;
this.chooseMove(val);
if (selectNext) this.stats();
break;
}
this.save();
},
chooseMove: function (move) {
var set = this.curSet;
if (!set) return;
if (move.substr(0, 13) === 'Hidden Power ') {
set.ivs = {};
for (var i in exports.BattleTypeChart[move.substr(13)].HPivs) {
set.ivs[i] = exports.BattleTypeChart[move.substr(13)].HPivs[i];
}
var moves = this.curSet.moves;
for (var i = 0; i < moves.length; ++i) {
if (moves[i] === 'Gyro Ball' || moves[i] === 'Trick Room') set.ivs['spe'] = set.ivs['spe'] % 4;
}
} else if (move === 'Gyro Ball' || move === 'Trick Room') {
var hasHiddenPower = false;
var moves = this.curSet.moves;
for (var i = 0; i < moves.length; ++i) {
if (moves[i].substr(0, 13) === 'Hidden Power ') hasHiddenPower = true;
}
set.ivs['spe'] = hasHiddenPower ? set.ivs['spe'] % 4 : 0;
} else if (move === 'Return') {
this.curSet.happiness = 255;
} else if (move === 'Frustration') {
this.curSet.happiness = 0;
}
},
setPokemon: function (val, selectNext) {
var set = this.curSet;
var template = Tools.getTemplate(val);
var newPokemon = !set.species;
if (!template.exists || set.species === template.species) return;
set.name = template.species;
set.species = val;
if (set.level) delete set.level;
if (this.curTeam && this.curTeam.format) {
if (this.curTeam.format.substr(0, 10) === 'battlespot' || this.curTeam.format.substr(0, 3) === 'vgc') set.level = 50;
if (this.curTeam.format.substr(0, 2) === 'lc' || this.curTeam.format === 'gen5lc' || this.curTeam.format === 'gen4lc') set.level = 5;
}
if (set.gender) delete set.gender;
if (template.gender && template.gender !== 'N') set.gender = template.gender;
if (set.happiness) delete set.happiness;
if (set.shiny) delete set.shiny;
if (this.curTeam.format !== 'balancedhackmons') {
var formatsData = window.BattleFormatsData && BattleFormatsData[template.speciesid];
set.item = (formatsData.requiredItem || '');
} else {
set.item = '';
}
set.ability = template.abilities['0'];
set.moves = [];
set.evs = {};
set.ivs = {};
set.nature = '';
this.updateSetTop();
if (selectNext) this.$(set.item || !this.$('input[name=item]').length ? (this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]') : 'input[name=item]').select();
},
/*********************************************************
* Utility functions
*********************************************************/
// EV guesser
guessRole: function () {
var set = this.curSet;
if (!set) return '?';
if (!set.moves) return '?';
var moveCount = {
'Physical': 0,
'Special': 0,
'PhysicalOffense': 0,
'SpecialOffense': 0,
'PhysicalSetup': 0,
'SpecialSetup': 0,
'Support': 0,
'Setup': 0,
'Restoration': 0,
'Offense': 0,
'Stall': 0,
'SpecialStall': 0,
'PhysicalStall': 0,
'Ultrafast': 0
};
var hasMove = {};
var template = Tools.getTemplate(set.species || set.name);
var stats = template.baseStats;
var itemid = toId(set.item);
var abilityid = toId(set.ability);
if (set.moves.length < 4 && template.id !== 'unown' && template.id !== 'ditto' && this.curTeam.gen > 2) return '?';
for (var i = 0, len = set.moves.length; i < len; i++) {
var move = Tools.getMove(set.moves[i]);
hasMove[move.id] = 1;
if (move.category === 'Status') {
if (move.id === 'batonpass' || move.id === 'healingwish' || move.id === 'lunardance') {
moveCount['Support']++;
} else if (move.id === 'naturepower') {
moveCount['Special']++;
} else if (move.id === 'protect' || move.id === 'detect' || move.id === 'spikyshield' || move.id === 'kingsshield') {
moveCount['Stall']++;
} else if (move.id === 'wish') {
moveCount['Restoration']++;
moveCount['Stall']++;
moveCount['Support']++;
} else if (move.heal) {
moveCount['Restoration']++;
moveCount['Stall']++;
} else if (move.target === 'self') {
if (move.id === 'agility' || move.id === 'rockpolish' || move.id === 'shellsmash' || move.id === 'growth' || move.id === 'workup') {
moveCount['PhysicalSetup']++;
moveCount['SpecialSetup']++;
} else if (move.id === 'dragondance' || move.id === 'swordsdance' || move.id === 'coil' || move.id === 'bulkup' || move.id === 'curse' || move.id === 'bellydrum') {
moveCount['PhysicalSetup']++;
} else if (move.id === 'nastyplot' || move.id === 'tailglow' || move.id === 'quiverdance' || move.id === 'calmmind' || move.id === 'geomancy') {
moveCount['SpecialSetup']++;
}
if (move.id === 'substitute') moveCount['Stall']++;
moveCount['Setup']++;
} else {
if (move.id === 'toxic' || move.id === 'leechseed' || move.id === 'willowisp') moveCount['Stall']++;
moveCount['Support']++;
}
} else if (move.id === 'counter' || move.id === 'endeavor' || move.id === 'metalburst' || move.id === 'mirrorcoat' || move.id === 'rapidspin') {
moveCount['Support']++;
} else if (move.id === 'nightshade' || move.id === 'seismictoss' || move.id === 'superfang' || move.id === 'foulplay' || move.id === 'finalgambit') {
moveCount['Offense']++;
} else if (move.id === 'fellstinger') {
moveCount['PhysicalSetup']++;
moveCount['Setup']++;
} else {
moveCount[move.category]++;
moveCount['Offense']++;
if (move.id === 'knockoff') moveCount['Support']++;
if (move.id === 'scald' || move.id === 'voltswitch' || move.id === 'uturn') moveCount[move.category] -= 0.2;
}
}
if (hasMove['batonpass']) moveCount['Support'] += moveCount['Setup'];
moveCount['PhysicalAttack'] = moveCount['Physical'];
moveCount['Physical'] += moveCount['PhysicalSetup'];
moveCount['SpecialAttack'] = moveCount['Special'];
moveCount['Special'] += moveCount['SpecialSetup'];
if (hasMove['dragondance'] || hasMove['quiverdance']) moveCount['Ultrafast'] = 1;
var isFast = (stats.spe > 95);
var physicalBulk = (stats.hp + 75) * (stats.def + 87);
var specialBulk = (stats.hp + 75) * (stats.spd + 87);
if (hasMove['willowisp'] || hasMove['acidarmor'] || hasMove['irondefense'] || hasMove['cottonguard']) {
physicalBulk *= 1.6;
moveCount['PhysicalStall']++;
} else if (hasMove['scald'] || hasMove['bulkup'] || hasMove['coil'] || hasMove['cosmicpower']) {
physicalBulk *= 1.3;
if (hasMove['scald']) { // partial stall goes in reverse
moveCount['SpecialStall']++;
} else {
moveCount['PhysicalStall']++;
}
}
if (abilityid === 'flamebody') physicalBulk *= 1.1;
if (hasMove['calmmind'] || hasMove['quiverdance'] || hasMove['geomancy']) {
specialBulk *= 1.3;
moveCount['SpecialStall']++;
}
if (template.id === 'tyranitar') specialBulk *= 1.5;
if (hasMove['bellydrum']) {
physicalBulk *= 0.6;
specialBulk *= 0.6;
}
if (moveCount['Restoration']) {
physicalBulk *= 1.5;
specialBulk *= 1.5;
} else if (hasMove['painsplit'] && hasMove['substitute']) {
// SubSplit isn't generally a stall set
moveCount['Stall']--;
} else if (hasMove['painsplit'] || hasMove['rest']) {
physicalBulk *= 1.4;
specialBulk *= 1.4;
}
if ((hasMove['bodyslam'] || hasMove['thunder']) && abilityid === 'serenegrace' || hasMove['thunderwave']) {
physicalBulk *= 1.1;
specialBulk *= 1.1;
}
if ((hasMove['ironhead'] || hasMove['airslash']) && abilityid === 'serenegrace') {
physicalBulk *= 1.1;
specialBulk *= 1.1;
}
if (hasMove['gigadrain'] || hasMove['drainpunch'] || hasMove['hornleech']) {
physicalBulk *= 1.15;
specialBulk *= 1.15;
}
if (itemid === 'leftovers' || itemid === 'blacksludge') {
physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
}
if (hasMove['leechseed']) {
physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
}
if ((itemid === 'flameorb' || itemid === 'toxicorb') && abilityid !== 'magicguard') {
if (itemid === 'toxicorb' && abilityid === 'poisonheal') {
physicalBulk *= 1 + 0.1 * (2 + moveCount['Stall']);
specialBulk *= 1 + 0.1 * (2 + moveCount['Stall']);
} else {
physicalBulk *= 0.8;
specialBulk *= 0.8;
}
}
if (itemid === 'lifeorb') {
physicalBulk *= 0.7;
specialBulk *= 0.7;
}
if (abilityid === 'multiscale' || abilityid === 'magicguard' || abilityid === 'regenerator') {
physicalBulk *= 1.4;
specialBulk *= 1.4;
}
if (itemid === 'eviolite') {
physicalBulk *= 1.5;
specialBulk *= 1.5;
}
if (itemid === 'assaultvest') specialBulk *= 1.5;
var bulk = physicalBulk + specialBulk;
if (bulk < 46000 && stats.spe >= 70) isFast = true;
moveCount['bulk'] = bulk;
moveCount['physicalBulk'] = physicalBulk;
moveCount['specialBulk'] = specialBulk;
if (hasMove['agility'] || hasMove['dragondance'] || hasMove['quiverdance'] || hasMove['rockpolish'] || hasMove['shellsmash'] || hasMove['flamecharge']) {
isFast = true;
} else if (abilityid === 'unburden' || abilityid === 'speedboost' || abilityid === 'motordrive') {
isFast = true;
moveCount['Ultrafast'] = 1;
} else if (abilityid === 'chlorophyll' || abilityid === 'swiftswim' || abilityid === 'sandrush') {
isFast = true;
moveCount['Ultrafast'] = 2;
}
if (hasMove['agility'] || hasMove['shellsmash'] || hasMove['autotomize'] || hasMove['shiftgear'] || hasMove['rockpolish']) moveCount['Ultrafast'] = 2;
moveCount['Fast'] = isFast ? 1 : 0;
this.moveCount = moveCount;
this.hasMove = hasMove;
if (template.id === 'ditto') return abilityid === 'imposter' ? 'Physically Defensive' : 'Fast Bulky Support';
if (template.id === 'shedinja') return 'Fast Physical Sweeper';
if (itemid === 'choiceband' && moveCount['PhysicalAttack'] >= 2) {
if (!isFast) return 'Bulky Band';
return 'Fast Band';
} else if (itemid === 'choicespecs' && moveCount['SpecialAttack'] >= 2) {
if (!isFast) return 'Bulky Specs';
return 'Fast Specs';
} else if (itemid === 'choicescarf') {
if (moveCount['PhysicalAttack'] === 0) return 'Special Scarf';
if (moveCount['SpecialAttack'] === 0) return 'Physical Scarf';
if (moveCount['PhysicalAttack'] > moveCount['SpecialAttack']) return 'Physical Biased Mixed Scarf';
if (moveCount['PhysicalAttack'] < moveCount['SpecialAttack']) return 'Special Biased Mixed Scarf';
if (stats.atk < stats.spa) return 'Special Biased Mixed Scarf';
return 'Physical Biased Mixed Scarf';
}
if (template.id === 'unown') return 'Fast Special Sweeper';
if (moveCount['PhysicalStall'] && moveCount['Restoration']) {
return 'Specially Defensive';
}
if (moveCount['SpecialStall'] && moveCount['Restoration'] && itemid !== 'lifeorb') {
return 'Physically Defensive';
}
var offenseBias = '';
if (stats.spa > stats.atk && moveCount['Special'] > 1) offenseBias = 'Special';
else if (stats.spa > stats.atk && moveCount['Special'] > 1) offenseBias = 'Special';
else if (moveCount['Special'] > moveCount['Physical']) offenseBias = 'Special';
else offenseBias = 'Physical';
var offenseStat = stats[offenseBias === 'Special' ? 'spa' : 'atk'];
if (moveCount['Stall'] + moveCount['Support'] / 2 <= 2 && bulk < 135000 && moveCount[offenseBias] >= 1.5) {
if (isFast) {
if (bulk > 80000 && !moveCount['Ultrafast']) return 'Bulky ' + offenseBias + ' Sweeper';
return 'Fast ' + offenseBias + ' Sweeper';
} else {
if (moveCount[offenseBias] >= 3 || moveCount['Stall'] <= 0) {
return 'Bulky ' + offenseBias + ' Sweeper';
}
}
}
if (isFast && abilityid !== 'prankster') {
if (stats.spe > 100 || bulk < 55000 || moveCount['Ultrafast']) {
return 'Fast Bulky Support';
}
}
if (moveCount['SpecialStall']) return 'Physically Defensive';
if (moveCount['PhysicalStall']) return 'Specially Defensive';
if (template.id === 'blissey' || template.id === 'chansey') return 'Physically Defensive';
if (specialBulk >= physicalBulk) return 'Specially Defensive';
return 'Physically Defensive';
},
ensureMinEVs: function (evs, stat, min, evTotal) {
if (!evs[stat]) evs[stat] = 0;
var diff = min - evs[stat];
if (diff <= 0) return evTotal;
if (evTotal <= 504) {
var change = Math.min(508 - evTotal, diff);
evTotal += change;
evs[stat] += change;
diff -= change;
}
if (diff <= 0) return evTotal;
var evPriority = {def: 1, spd: 1, hp: 1, atk: 1, spa: 1, spe: 1};
for (var i in evPriority) {
if (i === stat) continue;
if (evs[i] && evs[i] > 128) {
evs[i] -= diff;
evs[stat] += diff;
return evTotal;
}
}
return evTotal; // can't do it :(
},
ensureMaxEVs: function (evs, stat, min, evTotal) {
if (!evs[stat]) evs[stat] = 0;
var diff = evs[stat] - min;
if (diff <= 0) return evTotal;
evs[stat] -= diff;
evTotal -= diff;
return evTotal; // can't do it :(
},
guessEVs: function (role) {
var set = this.curSet;
if (!set) return {};
var template = Tools.getTemplate(set.species || set.name);
var stats = template.baseStats;
var hasMove = this.hasMove;
var moveCount = this.moveCount;
var evs = {};
var plusStat = '';
var minusStat = '';
var statChart = {
'Bulky Band': ['atk', 'hp'],
'Fast Band': ['spe', 'atk'],
'Bulky Specs': ['spa', 'hp'],
'Fast Specs': ['spe', 'spa'],
'Physical Scarf': ['spe', 'atk'],
'Special Scarf': ['spe', 'spa'],
'Physical Biased Mixed Scarf': ['spe', 'atk'],
'Special Biased Mixed Scarf': ['spe', 'spa'],
'Fast Physical Sweeper': ['spe', 'atk'],
'Fast Special Sweeper': ['spe', 'spa'],
'Bulky Physical Sweeper': ['atk', 'hp'],
'Bulky Special Sweeper': ['spa', 'hp'],
'Fast Bulky Support': ['spe', 'hp'],
'Physically Defensive': ['def', 'hp'],
'Specially Defensive': ['spd', 'hp']
};
plusStat = statChart[role][0];
if (role === 'Fast Bulky Support') moveCount['Ultrafast'] = 0;
if (plusStat === 'spe' && (moveCount['Ultrafast'] || evs['spe'] < 252)) {
if (statChart[role][1] === 'atk' || statChart[role][1] == 'spa') {
plusStat = statChart[role][1];
} else if (moveCount['Physical'] >= 3) {
plusStat = 'atk';
} else if (stats.spd > stats.def) {
plusStat = 'spd';
} else {
plusStat = 'def';
}
}
if (this.curTeam && this.ignoreEVLimits) {
evs = {hp:252, atk:252, def:252, spa:252, spd:252, spe:252};
if (hasMove['gyroball'] || hasMove['trickroom']) delete evs.spe;
if (this.curTeam.gen === 1) delete evs.spd;
if (this.curTeam.gen < 3) return evs;
} else {
if (!statChart[role]) return {};
var evTotal = 0;
var i = statChart[role][0];
var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0);
var ev = 252;
while (stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4;
evs[i] = ev;
evTotal += ev;
var i = statChart[role][1];
if (i === 'hp' && set.level && set.level < 20) i = 'spd';
var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0);
var ev = 252;
if (i === 'hp' && (hasMove['substitute'] || hasMove['transform']) && stat == Math.floor(stat / 4) * 4) stat -= 1;
while (stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4;
if (ev < 0) ev = 0;
evs[i] = ev;
evTotal += ev;
if (set.item !== 'Leftovers' && set.item !== 'Black Sludge') {
var hpParity = 1; // 1 = should be odd, 0 = should be even
if ((hasMove['substitute'] || hasMove['bellydrum']) && (set.item || '').slice(-5) === 'Berry') {
hpParity = 0;
}
var hp = evs['hp'] || 0;
while (hp < 252 && evTotal < 508 && this.getStat('hp', null, hp, 1) % 2 !== hpParity) {
hp += 4;
evTotal += 4;
}
while (hp && this.getStat('hp', null, hp, 1) % 2 !== hpParity) {
hp -= 4;
evTotal -= 4;
}
while (hp && this.getStat('hp', null, hp - 4, 1) % 2 === hpParity) {
hp -= 4;
evTotal -= 4;
}
if (hp || evs['hp']) evs['hp'] = hp;
}
if (template.id === 'tentacruel') evTotal = this.ensureMinEVs(evs, 'spe', 16, evTotal);
if (template.id === 'skarmory') evTotal = this.ensureMinEVs(evs, 'spe', 24, evTotal);
if (template.id === 'jirachi') evTotal = this.ensureMinEVs(evs, 'spe', 32, evTotal);
if (template.id === 'celebi') evTotal = this.ensureMinEVs(evs, 'spe', 36, evTotal);
if (template.id === 'volcarona') evTotal = this.ensureMinEVs(evs, 'spe', 52, evTotal);
if (template.id === 'gliscor') evTotal = this.ensureMinEVs(evs, 'spe', 72, evTotal);
if (stats.spe == 97) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal);
if (template.id === 'dragonite' && evs['hp']) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal);
if (evTotal < 508) {
var remaining = 508 - evTotal;
if (remaining > 252) remaining = 252;
i = null;
if (!evs['atk'] && moveCount['PhysicalAttack'] >= 1) {
i = 'atk';
} else if (!evs['spa'] && moveCount['SpecialAttack'] >= 1) {
i = 'spa';
} else if (stats.hp == 1 && !evs['def']) {
i = 'def';
} else if (stats.def === stats.spd && !evs['spd']) {
i = 'spd';
} else if (!evs['spd']) {
i = 'spd';
} else if (!evs['def']) {
i = 'def';
}
if (i) {
ev = remaining;
stat = this.getStat(i, null, ev);
while (ev > 0 && stat === this.getStat(i, null, ev - 4)) ev -= 4;
if (ev) evs[i] = ev;
remaining -= ev;
}
if (remaining && !evs['spe']) {
ev = remaining;
stat = this.getStat('spe', null, ev);
while (ev > 0 && stat === this.getStat('spe', null, ev - 4)) ev -= 4;
if (ev) evs['spe'] = ev;
}
}
}
if (hasMove['gyroball'] || hasMove['trickroom']) {
minusStat = 'spe';
} else if (!moveCount['PhysicalAttack']) {
minusStat = 'atk';
} else if (moveCount['SpecialAttack'] < 1) {
minusStat = 'spa';
} else if (moveCount['PhysicalAttack'] < 1) {
minusStat = 'atk';
} else if (stats.def > stats.spd) {
minusStat = 'spd';
} else {
minusStat = 'def';
}
if (plusStat === minusStat) {
minusStat = (plusStat === 'spe' ? 'spd' : 'spe');
}
evs.plusStat = plusStat;
evs.minusStat = minusStat;
return evs;
},
// Stat calculator
getStat: function (stat, set, evOverride, natureOverride) {
if (!set) set = this.curSet;
if (!set) return 0;
if (!set.ivs) set.ivs = {
hp: 31,
atk: 31,
def: 31,
spa: 31,
spd: 31,
spe: 31
};
if (!set.evs) set.evs = {
hp: 0,
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0
};
// do this after setting set.evs because it's assumed to exist
// after getStat is run
var template = Tools.getTemplate(set.species);
if (!template.exists) return 0;
if (!set.level) set.level = 100;
if (typeof set.ivs[stat] === 'undefined') set.ivs[stat] = 31;
if (evOverride === 0) evOverride = 1;
if (stat === 'hp') {
if (template.baseStats['hp'] === 1) return 1;
return Math.floor(Math.floor(2 * template.baseStats['hp'] + (set.ivs['hp'] || 0) + Math.floor((evOverride || set.evs['hp'] || 0) / 4) + 100) * set.level / 100 + 10);
}
var val = Math.floor(Math.floor(2 * template.baseStats[stat] + (set.ivs[stat] || 0) + Math.floor((evOverride || set.evs[stat] || 0) / 4)) * set.level / 100 + 5);
if (natureOverride) {
val *= natureOverride;
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) {
val *= 1.1;
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) {
val *= 0.9;
}
return Math.floor(val);
},
// initialization
buildMovelists: function () {
if (Tools.movelists) return;
if (!window.BattlePokedex) return;
Tools.movelists = {};
Tools.g6movelists = {};
for (var pokemon in window.BattlePokedex) {
var template = Tools.getTemplate(pokemon);
var moves = {};
var g6moves = {};
var alreadyChecked = {};
do {
alreadyChecked[template.speciesid] = true;
if (template.learnset) {
for (var l in template.learnset) {
moves[l] = true;
if (template.learnset[l].length) g6moves[l] = true;
}
}
if (template.speciesid === 'shaymin') {
template = Tools.getTemplate('shayminsky');
} else if (toId(template.baseSpecies) !== toId(template.species) && toId(template.baseSpecies) !== 'pikachu' && toId(template.baseSpecies) !== 'wormadam' && toId(template.baseSpecies) !== 'kyurem') {
template = Tools.getTemplate(template.baseSpecies);
} else {
template = Tools.getTemplate(template.prevo);
}
} while (template && template.species && !alreadyChecked[template.speciesid]);
Tools.movelists[pokemon] = moves;
Tools.g6movelists[pokemon] = g6moves;
}
},
applyMovelist: function (g6only, speciesid) {
this.buildMovelists();
if (!Tools.movelists) {
this.movelist = false;
} else if (g6only) {
this.movelist = Tools.g6movelists[speciesid];
} else {
this.movelist = Tools.movelists[speciesid];
}
},
getGen: function (format) {
format = '' + format;
if (format.substr(0, 3) !== 'gen') return 6;
return parseInt(format.substr(3, 1), 10) || 6;
},
destroy: function () {
app.clearGlobalListeners();
Room.prototype.destroy.call(this);
}
});
var MovePopup = exports.MovePopup = Popup.extend({
initialize: function (data) {
var buf = '<ul class="popupmenu">';
this.i = data.i;
this.team = data.team;
for (var i = 0; i < data.team.length; i++) {
var set = data.team[i];
if (i !== data.i && i !== data.i + 1) {
buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>';
}
buf += '<li' + (i === data.i ? ' style="opacity:.3"' : ' style="opacity:.6"') + '><span class="pokemonicon" style="display:inline-block;vertical-align:middle;' + Tools.getIcon(set) + '"></span> ' + Tools.escapeHTML(set.name) + '</li>';
}
if (i !== data.i && i !== data.i + 1) {
buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>';
}
buf += '</ul>';
this.$el.html(buf);
},
moveHere: function (i) {
this.close();
i = +i;
var movedSet = this.team.splice(this.i, 1)[0];
if (i > this.i) i--;
this.team.splice(i, 0, movedSet);
app.rooms['teambuilder'].save();
if (app.rooms['teambuilder'].curSet) {
app.rooms['teambuilder'].curSetLoc = i;
app.rooms['teambuilder'].update();
app.rooms['teambuilder'].updateChart();
} else {
app.rooms['teambuilder'].update();
}
}
});
})(window, jQuery);
| js/client-teambuilder.js | (function (exports, $) {
// this is a useful global
var teams;
var TeambuilderRoom = exports.TeambuilderRoom = exports.Room.extend({
type: 'teambuilder',
title: 'Teambuilder',
initialize: function () {
teams = Storage.teams;
// left menu
this.$el.addClass('ps-room-light').addClass('scrollable');
if (!Storage.whenTeamsLoaded.isLoaded) {
Storage.whenTeamsLoaded(this.update, this);
}
this.update();
},
focus: function () {
this.buildMovelists();
if (this.curTeam) {
this.curTeam.iconCache = '!';
this.curTeam.gen = this.getGen(this.curTeam.format);
Storage.activeSetList = this.curSetList;
}
},
blur: function () {
if (this.saveFlag) {
this.saveFlag = false;
app.user.trigger('saveteams');
}
},
events: {
// team changes
'change input.teamnameedit': 'teamNameChange',
'click button.formatselect': 'selectFormat',
'change input[name=nickname]': 'nicknameChange',
// details
'change .detailsform input': 'detailsChange',
// stats
'keyup .statform input.numform': 'statChange',
'input .statform input[type=number].numform': 'statChange',
'change select[name=nature]': 'natureChange',
// teambuilder events
'click .utilichart a': 'chartClick',
'keydown .chartinput': 'chartKeydown',
'keyup .chartinput': 'chartKeyup',
'focus .chartinput': 'chartFocus',
'change .chartinput': 'chartChange',
// drag/drop
'click .team': 'edit',
'click .selectFolder': 'selectFolder',
'mouseover .team': 'mouseOverTeam',
'mouseout .team': 'mouseOutTeam',
'dragstart .team': 'dragStartTeam',
'dragend .team': 'dragEndTeam',
'dragenter .team': 'dragEnterTeam',
'dragenter .folder .selectFolder': 'dragEnterFolder',
'dragleave .folder .selectFolder': 'dragLeaveFolder',
'dragexit .folder .selectFolder': 'dragExitFolder',
// clipboard
'click .teambuilder-clipboard-data .result': 'clipboardResultSelect',
'click .teambuilder-clipboard-data': 'clipboardExpand',
'blur .teambuilder-clipboard-data': 'clipboardShrink'
},
dispatchClick: function (e) {
e.preventDefault();
e.stopPropagation();
if (this[e.currentTarget.value]) this[e.currentTarget.value](e);
},
saveTeams: function () {
// save and return
Storage.saveTeams();
app.user.trigger('saveteams');
this.update();
},
back: function () {
if (this.exportMode) {
if (this.curTeam) this.curTeam.team = Storage.packTeam(this.curSetList);
this.exportMode = false;
Storage.saveTeams();
} else if (this.curSet) {
app.clearGlobalListeners();
this.curSet = null;
Storage.saveTeams();
} else if (this.curTeam) {
this.curTeam.team = Storage.packTeam(this.curSetList);
this.curTeam.iconCache = '';
var team = this.curTeam;
this.curTeam = null;
Storage.activeSetList = this.curSetList = null;
Storage.saveTeam(team);
} else {
return;
}
app.user.trigger('saveteams');
this.update();
},
// the teambuilder has three views:
// - team list (curTeam falsy)
// - team view (curTeam exists, curSet falsy)
// - set view (curTeam exists, curSet exists)
curTeam: null,
curTeamLoc: 0,
curSet: null,
curSetLoc: 0,
// curFolder will have '/' at the end if it's a folder, but
// it will be alphanumeric (so guaranteed no '/') if it's a
// format
// Special values:
// '' - show all
// 'gen6' - show teams with no format
// '/' - show teams with no folder
curFolder: '',
curFolderKeep: '',
exportMode: false,
update: function () {
teams = Storage.teams;
if (this.curTeam) {
this.ignoreEVLimits = (this.curTeam.gen < 3);
if (this.curSet) {
return this.updateSetView();
}
return this.updateTeamView();
}
return this.updateTeamInterface();
},
/*********************************************************
* Team list view
*********************************************************/
deletedTeam: null,
deletedTeamLoc: -1,
updateTeamInterface: function () {
this.deletedSet = null;
this.deletedSetLoc = -1;
var buf = '';
if (this.exportMode) {
buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <button name="saveBackup" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>';
buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportAllTeams()) + '</textarea></div>';
this.$el.html(buf);
this.$('.teamedit textarea').focus().select();
return;
}
if (!Storage.whenTeamsLoaded.isLoaded) {
buf = '<div class="pad"><p>lol zarel this is a horrible teambuilder</p>';
buf += '<p>that\'s because we\'re not done loading it...</p></div>';
this.$el.html(buf);
return;
}
// folderpane
buf = '<div class="folderpane">';
buf += '</div>';
// teampane
buf += '<div class="teampane">';
buf += '</div>';
this.$el.html(buf);
this.updateFolderList();
this.updateTeamList();
},
updateFolderList: function () {
var buf = '<div class="folderlist"><div class="folderlistbefore"></div>';
buf += '<div class="folder' + (!this.curFolder ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="all"><em>(all)</em></div></div>' + (!this.curFolder ? '</div>' : '');
var folderTable = {};
var folders = [];
if (Storage.teams) for (var i = -2; i < Storage.teams.length; i++) {
if (i >= 0) {
var folder = Storage.teams[i].folder;
if (folder && !((folder + '/') in folderTable)) {
folders.push('Z' + folder);
folderTable[folder + '/'] = 1;
if (!('/' in folderTable)) {
folders.push('Z~');
folderTable['/'] = 1;
}
}
}
var format;
if (i === -2) {
format = this.curFolderKeep;
} else if (i === -1) {
format = this.curFolder;
} else {
format = Storage.teams[i].format;
if (!format) format = 'gen6';
}
if (!format) continue;
if (format in folderTable) continue;
folderTable[format] = 1;
if (format.slice(-1) === '/') {
folders.push('Z' + (format.slice(0, -1) || '~'));
if (!('/' in folderTable)) {
folders.push('Z~');
folderTable['/'] = 1;
}
continue;
}
if (format === 'gen6') {
folders.push('A~');
continue;
}
switch (format.slice(0, 4)) {
case 'gen1': format = 'F' + format.slice(4); break;
case 'gen2': format = 'E' + format.slice(4); break;
case 'gen3': format = 'D' + format.slice(4); break;
case 'gen4': format = 'C' + format.slice(4); break;
case 'gen5': format = 'B' + format.slice(4); break;
default: format = 'A' + format; break;
}
folders.push(format);
}
folders.sort();
var gen = '';
var formatFolderBuf = '<div class="foldersep"></div>';
formatFolderBuf += '<div class="folder"><div class="selectFolder" data-value="+"><i class="fa fa-plus"></i><em>(add format folder)</em></div></div>';
for (var i = 0; i < folders.length; i++) {
var format = folders[i];
var newGen;
switch (format.charAt(0)) {
case 'F': newGen = '1'; break;
case 'E': newGen = '2'; break;
case 'D': newGen = '3'; break;
case 'C': newGen = '4'; break;
case 'B': newGen = '5'; break;
case 'A': newGen = '6'; break;
case 'Z': newGen = '/'; break;
}
if (gen !== newGen) {
gen = newGen;
if (gen === '/') {
buf += formatFolderBuf;
formatFolderBuf = '';
buf += '<div class="foldersep"></div>';
buf += '<div class="folder"><h3>Folders</h3></div>';
} else {
buf += '<div class="folder"><h3>Gen ' + gen + '</h3></div>';
}
}
if (gen === '/') {
formatName = format.slice(1);
format = formatName + '/';
if (formatName === '~') {
formatName = '(uncategorized)';
format = '/';
} else {
formatName = Tools.escapeHTML(formatName);
}
buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open' : 'fa-folder') + (format === '/' ? '-o' : '') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : '');
continue;
}
var formatName = format.slice(1);
if (formatName === '~') formatName = '';
if (newGen === '6' && formatName) {
format = formatName;
} else {
format = 'gen' + newGen + formatName;
}
if (format === 'gen6') formatName = '(uncategorized)';
// folders are <div>s rather than <button>s because in theory it has
// less weird interactions with HTML5 drag-and-drop
buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open-o' : 'fa-folder-o') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : '');
}
buf += formatFolderBuf;
buf += '<div class="foldersep"></div>';
buf += '<div class="folder"><div class="selectFolder" data-value="++"><i class="fa fa-plus"></i><em>(add folder)</em></div></div>';
buf += '<div class="folderlistafter"></div></div>';
this.$('.folderpane').html(buf);
},
updateTeamList: function (resetScroll) {
var teams = Storage.teams;
var buf = '';
// teampane
buf += this.clipboardHTML();
var filterFormat = '';
var filterFolder = undefined;
if (!this.curFolder) {
buf += '<h2>Hi</h2>';
buf += '<p>Did you have a good day?</p>';
buf += '<p><button class="button" name="greeting" value="Y"><i class="fa fa-smile-o"></i> Yes, my day was pretty good</button> <button class="button" name="greeting" value="N"><i class="fa fa-frown-o"></i> No, it wasn\'t great</button></p>';
buf += '<h2>All teams</h2>';
} else {
if (this.curFolder.slice(-1) === '/') {
filterFolder = this.curFolder.slice(0, -1);
if (filterFolder) {
buf += '<h2><i class="fa fa-folder-open"></i> ' + filterFolder + ' <button class="button small" style="margin-left:5px" name="renameFolder"><i class="fa fa-pencil"></i> Rename</button></h2>';
} else {
buf += '<h2><i class="fa fa-folder-open-o"></i> Teams not in any folders</h2>';
}
} else {
filterFormat = this.curFolder;
buf += '<h2><i class="fa fa-folder-open-o"></i> ' + filterFormat + '</h2>';
}
}
var newButtonText = "New Team";
if (filterFolder) newButtonText = "New Team in folder";
if (filterFormat && filterFormat !== 'gen6') {
newButtonText = "New " + Tools.escapeFormat(filterFormat) + " Team";
}
buf += '<p><button name="newTop" class="button big"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>';
buf += '<ul class="teamlist">';
var atLeastOne = false;
if (!window.localStorage && !window.nodewebkit) buf += '<li>== CAN\'T SAVE ==<br /><small>Your browser doesn\'t support <code>localStorage</code> and can\'t save teams! Update to a newer browser.</small></li>';
if (Storage.cantSave) buf += '<li>== CAN\'T SAVE ==<br /><small>You hit your browser\'s limit for team storage! Please backup them and delete some of them. Your teams won\'t be saved until you\'re under the limit again.</small></li>';
if (!teams.length) {
if (this.deletedTeamLoc >= 0) {
buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
buf += '<li><p><em>you don\'t have any teams lol</em></p></li>';
} else {
for (var i = 0; i < teams.length + 1; i++) {
if (i === this.deletedTeamLoc) {
if (!atLeastOne) atLeastOne = true;
buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
if (i >= teams.length) break;
var team = teams[i];
if (team && !team.team && team.team !== '') {
team = null;
}
if (!team) {
buf += '<li>Error: A corrupted team was dropped</li>';
teams.splice(i, 1);
i--;
if (this.deletedTeamLoc && this.deletedTeamLoc > i) this.deletedTeamLoc--;
continue;
}
if (filterFormat && filterFormat !== (team.format || 'gen6')) continue;
if (filterFolder !== undefined && filterFolder !== team.folder) continue;
if (!atLeastOne) atLeastOne = true;
var formatText = '';
if (team.format) {
formatText = '[' + team.format + '] ';
}
if (team.folder) formatText += team.folder + '/';
// teams are <div>s rather than <button>s because Firefox doesn't
// support dragging and dropping buttons.
buf += '<li><div name="edit" data-value="' + i + '" class="team" draggable="true">' + formatText + '<strong>' + Tools.escapeHTML(team.name) + '</strong><br /><small>';
buf += Storage.getTeamIcons(team);
buf += '</small></div><button name="edit" value="' + i + '"><i class="fa fa-pencil"></i>Edit</button><button name="delete" value="' + i + '"><i class="fa fa-trash"></i>Delete</button></li>';
}
if (!atLeastOne) {
if (filterFolder) {
buf += '<li><p><em>you don\'t have any teams in this folder lol</em></p></li>';
} else {
buf += '<li><p><em>you don\'t have any ' + this.curFolder + ' teams lol</em></p></li>';
}
}
}
buf += '</ul>';
if (atLeastOne) {
buf += '<p><button name="new" class="button"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>';
}
if (window.nodewebkit) {
buf += '<button name="revealFolder" class="button"><i class="fa fa-folder-open"></i> Reveal teams folder</button> <button name="reloadTeamsFolder" class="button"><i class="fa fa-refresh"></i> Reload teams files</button> <button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>';
} else if (atLeastOne) {
buf += '<p><strong>Clearing your cookies (specifically, <code>localStorage</code>) will delete your teams.</strong></p>';
buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>';
buf += '<p>If you want to clear your cookies or <code>localStorage</code>, you can use the Backup/Restore feature to save your teams as text first.</p>';
} else {
buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Restore teams from backup</button>';
}
var $pane = this.$('.teampane');
$pane.html(buf);
if (resetScroll) $pane.scrollTop(0);
},
greeting: function (answer, button) {
var buf = '<p><strong>' + $(button).html() + '</p></strong>';
if (answer === 'N') {
buf += '<p>Aww, that\'s too bad. :( I hope playing on Pokémon Showdown today can help cheer you up!</p>';
} else if (answer === 'Y') {
buf += '<p>Cool! I just added some pretty cool teambuilder features, so I\'m pretty happy, too. Did you know you can drag and drop teams to different format-folders? You can also drag and drop them to and from your computer (works best in Chrome).</p>';
buf += '<p><button class="button" name="greeting" value="W"><i class="fa fa-question-circle"></i> Wait, who are you? Talking to a teambuilder is weird.</button></p>';
} else if (answer === 'W') {
buf += '<p>Oh, I\'m Zarel! I made a Credits button for this...</p>';
buf += '<div class="menugroup"><p><button class="button mainmenu4" name="credits"><i class="fa fa-info-circle"></i> Credits</button></p></div>';
buf += '<p>Isn\'t it pretty? Matches your background and everything. It used to be in the Main Menu but we had to get rid of it to save space.</p>';
buf += '<p>Speaking of, you should try <button class="button" name="background"><i class="fa fa-picture-o"></i> changing your background</button>.';
buf += '<p><button class="button" name="greeting" value="B"><i class="fa fa-hand-pointer-o"></i> You might be having too much fun with these buttons and icons</button></p>';
} else if (answer === 'B') {
buf += '<p>I paid good money for those icons! I need to get my money\'s worth!</p>';
buf += '<p><button class="button" name="greeting" value="WR"><i class="fa fa-exclamation-triangle"></i> Wait, really?</button></p>';
} else if (answer === 'WR') {
buf += '<p>No, they were free. That just makes it easier to get my money\'s worth. Let\'s play rock paper scissors!</p>';
buf += '<p><button class="button" name="greeting" value="RR"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-rock-o"></i> Paper</button> <button class="button" name="greeting" value="RS"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="RL"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-spock-o"></i> Spock</button></p>';
} else if (answer[0] === 'R') {
buf += '<p>I play laser, I win. <i class="fa fa-hand-o-left"></i></p>';
buf += '<p><button class="button" name="greeting" value="YC"><i class="fa fa-thumbs-o-down"></i> You can\'t do that!</button></p>';
} else if (answer === 'YC') {
buf += '<p>Okay, then I play peace sign <i class="fa fa-hand-peace-o"></i>, everyone signs a peace treaty, ending the war and ushering in a new era of prosperity.</p>';
}
$(button).parent().replaceWith(buf);
},
credits: function () {
app.addPopup(CreditsPopup);
},
background: function () {
app.addPopup(CustomBackgroundPopup);
},
selectFolder: function (format) {
if (format && format.currentTarget) {
var e = format;
format = $(e.currentTarget).data('value');
e.preventDefault();
if (format === '+') {
e.stopImmediatePropagation();
var self = this;
app.addPopup(FormatPopup, {format: '', sourceEl: e.currentTarget, selectType: 'teambuilder', onselect: function (newFormat) {
self.selectFolder(newFormat);
}});
return;
}
if (format === '++') {
e.stopImmediatePropagation();
var self = this;
// app.addPopupPrompt("Folder name:", "Create folder", function (newFormat) {
// self.selectFolder(newFormat + '/');
// });
app.addPopup(PromptPopup, {message: "Folder name:", button: "Create folder", sourceEl: e.currentTarget, callback: function (name) {
name = $.trim(name);
if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator.");
name = name.replace(/[\\\/]/g, '');
}
if (!name) return;
self.selectFolder(name + '/');
}});
return;
}
} else {
this.curFolderKeep = format;
}
this.curFolder = (format === 'all' ? '' : format);
this.updateFolderList();
this.updateTeamList(true);
},
renameFolder: function () {
if (!this.curFolder) return;
if (this.curFolder.slice(-1) !== '/') return;
var oldFolder = this.curFolder.slice(0, -1);
var self = this;
app.addPopup(PromptPopup, {message: "Folder name:", button: "Rename folder", value: oldFolder, callback: function (name) {
name = $.trim(name);
if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator.");
name = name.replace(/[\\\/]/g, '');
}
if (!name) return;
if (name === oldFolder) return;
for (var i = 0; i < Storage.teams.length; i++) {
var team = Storage.teams[i];
if (team.folder !== oldFolder) continue;
team.folder = name;
if (window.nodewebkit) Storage.saveTeam(team);
}
if (!window.nodewebkit) Storage.saveTeam(team);
self.selectFolder(name + '/');
}});
},
show: function () {
Room.prototype.show.apply(this, arguments);
var $teamwrapper = this.$('.teamwrapper');
var width = $(window).width();
if (!$teamwrapper.length) return;
if (width < 640) {
var scale = (width / 640);
$teamwrapper.css('transform', 'scale(' + scale + ')');
$teamwrapper.addClass('scaled');
} else {
$teamwrapper.css('transform', 'none');
$teamwrapper.removeClass('scaled');
}
},
// button actions
revealFolder: function () {
Storage.revealFolder();
},
reloadTeamsFolder: function () {
Storage.nwLoadTeams();
},
edit: function (i) {
if (i && i.currentTarget) {
i = $(i.currentTarget).data('value');
}
i = +i;
this.curTeam = teams[i];
this.curTeam.iconCache = '!';
this.curTeam.gen = this.getGen(this.curTeam.format);
Storage.activeSetList = this.curSetList = Storage.unpackTeam(this.curTeam.team);
this.curTeamIndex = i;
this.update();
},
"delete": function (i) {
i = +i;
this.deletedTeamLoc = i;
this.deletedTeam = teams.splice(i, 1)[0];
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
if (i < obj.curTeamIndex) {
obj.curTeamIndex--;
} else if (i === obj.curTeamIndex) {
obj.curTeamIndex = -1;
}
}
Storage.deleteTeam(this.deletedTeam);
app.user.trigger('saveteams');
this.updateTeamList();
},
undoDelete: function () {
if (this.deletedTeamLoc >= 0) {
teams.splice(this.deletedTeamLoc, 0, this.deletedTeam);
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
if (this.deletedTeamLoc < obj.curTeamIndex + 1) {
obj.curTeamIndex++;
} else if (obj.curTeamIndex === -1) {
obj.curTeamIndex = this.deletedTeamLoc;
}
}
var undeletedTeam = this.deletedTeam;
this.deletedTeam = null;
this.deletedTeamLoc = -1;
Storage.saveTeam(undeletedTeam);
app.user.trigger('saveteams');
this.update();
}
},
saveBackup: function () {
Storage.deleteAllTeams();
Storage.importTeam(this.$('.teamedit textarea').val(), true);
teams = Storage.teams;
Storage.saveAllTeams();
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
obj.curTeamIndex = 0;
}
this.back();
},
"new": function () {
var format = this.curFolder;
var folder = '';
if (format && format.charAt(format.length - 1) === '/') {
folder = format.slice(0, -1);
format = '';
}
var newTeam = {
name: 'Untitled ' + (teams.length + 1),
format: format,
team: '',
folder: folder,
iconCache: ''
};
teams.push(newTeam);
this.edit(teams.length - 1);
},
newTop: function () {
var format = this.curFolder;
var folder = '';
if (format && format.charAt(format.length - 1) === '/') {
folder = format.slice(0, -1);
format = '';
}
var newTeam = {
name: 'Untitled ' + (teams.length + 1),
format: format,
team: '',
folder: folder,
iconCache: ''
};
teams.unshift(newTeam);
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
obj.curTeamIndex++;
}
this.edit(0);
},
"import": function () {
if (this.exportMode) return this.back();
this.exportMode = true;
if (!this.curTeam) {
this['new']();
} else {
this.update();
}
},
backup: function () {
this.curTeam = null;
this.curSetList = null;
this.exportMode = true;
this.update();
},
// drag and drop
// because of a bug in Chrome and Webkit:
// https://code.google.com/p/chromium/issues/detail?id=410328
// we can't use CSS :hover
mouseOverTeam: function (e) {
e.currentTarget.className = 'team team-hover';
},
mouseOutTeam: function (e) {
e.currentTarget.className = 'team';
},
dragStartTeam: function (e) {
var target = e.currentTarget;
var dataTransfer = e.originalEvent.dataTransfer;
dataTransfer.effectAllowed = 'copyMove';
dataTransfer.setData("text/plain", "Team " + e.currentTarget.dataset.value);
var team = Storage.teams[e.currentTarget.dataset.value];
var filename = team.name;
if (team.format) filename = '[' + team.format + '] ' + filename;
filename = $.trim(filename).replace(/[\\\/]+/g, '') + '.txt';
var urlprefix = "data:text/plain;base64,";
if (document.location.protocol === 'https:') {
// Chrome is dumb and doesn't support data URLs in HTTPS
urlprefix = "https://play.pokemonshowdown.com/action.php?act=dlteam&team=";
}
var contents = Storage.exportTeam(team.team).replace(/\n/g, '\r\n');
var downloadurl = "text/plain:" + filename + ":" + urlprefix + encodeURIComponent(window.btoa(unescape(encodeURIComponent(contents))));
console.log(downloadurl);
dataTransfer.setData("DownloadURL", downloadurl);
app.dragging = e.currentTarget;
app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10);
var elOffset = $(e.currentTarget).offset();
app.draggingOffsetX = e.originalEvent.pageX - elOffset.left;
app.draggingOffsetY = e.originalEvent.pageY - elOffset.top;
app.draggingRoom = this.id;
this.finalOffset = null;
setTimeout(function () {
$(e.currentTarget).parent().addClass('dragging');
}, 0);
},
dragEndTeam: function (e) {
this.finishDrop();
},
finishDrop: function () {
var teamEl = app.dragging;
app.dragging = null;
var originalLoc = parseInt(teamEl.dataset.value, 10);
if (isNaN(originalLoc)) {
throw new Error("drag failed");
}
var newLoc = Math.floor(app.draggingLoc);
if (app.draggingLoc < originalLoc) newLoc += 1;
var team = Storage.teams[originalLoc];
var edited = false;
if (newLoc !== originalLoc) {
Storage.teams.splice(originalLoc, 1);
Storage.teams.splice(newLoc, 0, team);
for (var room in app.rooms) {
var selection = app.rooms[room].$('button.teamselect').val();
if (!selection || selection === 'random') continue;
var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox;
if (originalLoc === obj.curTeamIndex) {
obj.curTeamIndex = newLoc;
} else if (originalLoc > obj.curTeamIndex && newLoc <= obj.curTeamIndex) {
obj.curTeamIndex++;
} else if (originalLoc < obj.curTeamIndex && newLoc >= obj.curTeamIndex) {
obj.curTeamIndex--;
}
}
edited = true;
}
// possibly half-works-around a hover issue in
this.$('.teamlist').css('pointer-events', 'none');
$(teamEl).parent().removeClass('dragging');
var format = this.curFolder;
if (app.draggingFolder) {
format = app.draggingFolder.dataset.value;
app.draggingFolder = null;
if (format.slice(-1) === '/') {
team.folder = format.slice(0, -1);
} else {
team.format = format;
}
this.selectFolder(format);
edited = true;
} else {
if (format.slice(-1) === '/') {
team.folder = format.slice(0, -1);
edited = true;
}
this.updateTeamList();
}
if (edited) {
Storage.saveTeam(team);
app.user.trigger('saveteams');
}
// We're going to try to animate the team settling into its new position
if (this.finalOffset) {
// event.pageY and event.pageX are buggy on literally every browser:
// in Chrome:
// event.pageX|pageY is the position of the bottom left corner of the draggable, instead
// of the mouse position
// in Safari:
// window.innerHeight * 2 - window.outerHeight - event.pageY is the mouse position
// No, I don't understand what's going on, either, but unsurprisingly this fails utterly
// if the page is zoomed.
// in Firefox:
// event.pageX|pageY are straight-up unsupported
// if you don't believe me, uncomment and see for yourself:
// console.log('x,y = ' + [e.originalEvent.x, e.originalEvent.y]);
// console.log('screenX,screenY = ' + [e.originalEvent.screenX, e.originalEvent.screenY]);
// console.log('clientX,clientY = ' + [e.originalEvent.clientX, e.originalEvent.clientY]);
// console.log('pageX,pageY = ' + [e.originalEvent.pageX, e.originalEvent.pageY]);
// Because of this, we're just going to steal the values from the drop event, where
// everything is sane.
var $newTeamEl = this.$('.team[data-value=' + newLoc + ']');
var finalPos = $newTeamEl.offset();
$newTeamEl.css('transform', 'translate(' + (this.finalOffset[0] - finalPos.left) + 'px, ' + (this.finalOffset[1] - finalPos.top) + 'px)');
setTimeout(function () {
$newTeamEl.css('transition', 'transform 0.15s');
// it's 2015 and Safari doesn't support unprefixed transition!!!
$newTeamEl.css('-webkit-transition', '-webkit-transform 0.15s');
$newTeamEl.css('transform', 'translate(0px, 0px)');
});
}
},
dragEnterTeam: function (e) {
if (!app.dragging) return;
var $draggingLi = $(app.dragging).parent();
this.dragLeaveFolder();
if (e.currentTarget === app.dragging) {
e.preventDefault();
return;
}
var hoverLoc = parseInt(e.currentTarget.dataset.value, 10);
if (app.draggingLoc > hoverLoc) {
// dragging up
$(e.currentTarget).parent().before($draggingLi);
app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) - 0.5;
} else {
// dragging down
$(e.currentTarget).parent().after($draggingLi);
app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) + 0.5;
}
},
dragEnterFolder: function (e) {
if (!app.dragging) return;
this.dragLeaveFolder();
if (e.currentTarget === app.draggingFolder) {
return;
}
var format = e.currentTarget.dataset.value;
if (format === '+' || format === '++' || format === 'all' || format === this.curFolder) {
return;
}
if (parseInt(app.dragging.dataset.value, 10) >= Storage.teams.length && format.slice(-1) !== '/') {
// dragging a team file, already has a known format
return;
}
app.draggingFolder = e.currentTarget;
$(app.draggingFolder).addClass('active');
// amusing note: using .detach() instead of .hide() will make `dragend` not fire
$(app.dragging).parent().hide();
},
dragLeaveFolder: function (e) {
// sometimes there's a race condition and dragEnter happens before dragLeave
if (e && e.currentTarget !== app.draggingFolder) return;
if (!app.dragging || !app.draggingFolder) return;
$(app.draggingFolder).removeClass('active');
app.draggingFolder = null;
$(app.dragging).parent().show();
},
defaultDragEnterTeam: function (e) {
var dataTransfer = e.originalEvent.dataTransfer;
if (!dataTransfer) return;
if (dataTransfer.types.indexOf && dataTransfer.types.indexOf('Files') === -1) return;
if (dataTransfer.types.contains && !dataTransfer.types.contains('Files')) return;
if (dataTransfer.files[0] && dataTransfer.files[0].name.slice(-4) !== '.txt') return;
// We're dragging a file! It might be a team!
if (app.curFolder && app.curFolder.slice(-1) !== '/') {
this.selectFolder('all');
}
this.$('.teamlist').append('<li class="dragging"><div class="team" data-value="' + Storage.teams.length + '"></div></li>');
app.dragging = this.$('.dragging .team')[0];
app.draggingLoc = Storage.teams.length;
app.draggingOffsetX = 180;
app.draggingOffsetY = 25;
app.draggingRoom = this.id;
},
defaultDropTeam: function (e) {
if (e.originalEvent.dataTransfer.files && e.originalEvent.dataTransfer.files[0]) {
var file = e.originalEvent.dataTransfer.files[0];
var name = file.name;
if (name.slice(-4) !== '.txt') {
app.dragging = null;
this.updateTeamList();
app.addPopupMessage("Your file is not a valid team. Team files are .txt files.");
return;
}
var reader = new FileReader();
var self = this;
reader.onload = function (e) {
var team;
try {
team = Storage.packTeam(Storage.importTeam(e.target.result));
} catch (err) {
app.addPopupMessage("Your file is not a valid team.");
self.updateTeamList();
return;
}
var name = file.name;
if (name.slice(name.length - 4).toLowerCase() === '.txt') {
name = name.substr(0, name.length - 4);
}
var format = '';
var bracketIndex = name.indexOf(']');
if (bracketIndex >= 0) {
format = name.substr(1, bracketIndex - 1);
name = $.trim(name.substr(bracketIndex + 1));
}
Storage.teams.push({
name: name,
format: format,
team: team,
folder: '',
iconCache: ''
});
self.finishDrop();
};
reader.readAsText(file);
}
this.finalOffset = [e.originalEvent.pageX - app.draggingOffsetX, e.originalEvent.pageY - app.draggingOffsetY];
},
/*********************************************************
* Team view
*********************************************************/
updateTeamView: function () {
this.curChartName = '';
this.curChartType = '';
var buf = '';
if (this.exportMode) {
buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="saveImport"><i class="fa fa-upload"></i> Import/Export</button> <button name="saveImport" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>';
buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportTeam(this.curSetList)) + '</textarea></div>';
} else {
buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="import"><i class="fa fa-upload"></i> Import/Export</button></div>';
buf += '<div class="teamchartbox">';
buf += '<ol class="teamchart">';
buf += '<li>' + this.clipboardHTML() + '</li>';
var i = 0;
if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].species) {
this.curSetList.splice(this.curSetList.length - 1, 1);
}
if (exports.BattleFormats) {
buf += '<li class="format-select">';
buf += '<label class="label">Format:</label><button class="select formatselect teambuilderformatselect" name="format" value="' + this.curTeam.format + '">' + (Tools.escapeFormat(this.curTeam.format) || '<em>Select a format</em>') + '</button>';
buf += ' <button name="validate" class="button"><i class="fa fa-check"></i> Validate</button></li>';
}
if (!this.curSetList.length) {
buf += '<li><em>you have no pokemon lol</em></li>';
}
for (i = 0; i < this.curSetList.length; i++) {
if (this.curSetList.length < 6 && this.deletedSet && i === this.deletedSetLoc) {
buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
buf += this.renderSet(this.curSetList[i], i);
}
if (this.deletedSet && i === this.deletedSetLoc) {
buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>';
}
if (i === 0) {
buf += '<li><button name="import" class="button big"><i class="fa fa-upload"></i> Import from text</button></li>';
}
if (i < 6) {
buf += '<li><button name="addPokemon" class="button big"><i class="fa fa-plus"></i> Add Pokémon</button></li>';
}
buf += '</ol>';
buf += '</div>';
}
this.$el.html('<div class="teamwrapper">' + buf + '</div>');
this.$(".teamedit textarea").focus().select();
if ($(window).width() < 640) this.show();
},
renderSet: function (set, i) {
var template = Tools.getTemplate(set.species);
var buf = '<li value="' + i + '">';
if (!set.species) {
if (this.deletedSet) {
buf += '<div class="setmenu setmenu-left"><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></div>';
}
buf += '<div class="setmenu"><button name="importSet"><i class="fa fa-upload"></i>Import</button></div>';
buf += '<div class="setchart"><div class="setcol setcol-icon" style="background-image:url(' + Tools.resourcePrefix + 'sprites/bw/0.png);"><span class="itemicon"></span><div class="setcell setcell-pokemon"><label>Pokemon</label><input type="text" name="pokemon" class="chartinput" value="" /></div></div></div>';
buf += '</li>';
return buf;
}
buf += '<div class="setmenu"><button name="copySet"><i class="fa fa-files-o"></i>Copy</button> <button name="importSet"><i class="fa fa-upload"></i>Import/Export</button> <button name="moveSet"><i class="fa fa-arrows"></i>Move</button> <button name="deleteSet"><i class="fa fa-trash"></i>Delete</button></div>';
buf += '<div class="setchart-nickname">';
buf += '<label>Nickname</label><input type="text" value="' + Tools.escapeHTML(set.name || set.species) + '" name="nickname" />';
buf += '</div>';
buf += '<div class="setchart">';
// icon
var itemicon = '<span class="itemicon"></span>';
if (set.item) {
var item = Tools.getItem(set.item);
itemicon = '<span class="itemicon" style="' + Tools.getItemIcon(item) + '"></span>';
}
buf += '<div class="setcol setcol-icon" style="' + Tools.getTeambuilderSprite(set) + ';">' + itemicon + '<div class="setcell setcell-pokemon"><label>Pokemon</label><input type="text" name="pokemon" class="chartinput" value="' + Tools.escapeHTML(set.species) + '" /></div></div>';
// details
buf += '<div class="setcol setcol-details"><div class="setrow">';
buf += '<div class="setcell setcell-details"><label>Details</label><button class="setdetails" tabindex="-1" name="details">';
var GenderChart = {
'M': 'Male',
'F': 'Female',
'N': '—'
};
buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>';
if (this.curTeam.gen > 1) {
buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[template.gender || set.gender || 'N'] + '</span>';
buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>';
buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>';
}
buf += '</button></div>';
buf += '</div><div class="setrow">';
if (this.curTeam.gen > 1) buf += '<div class="setcell setcell-item"><label>Item</label><input type="text" name="item" class="chartinput" value="' + Tools.escapeHTML(set.item) + '" /></div>';
if (this.curTeam.gen > 2) buf += '<div class="setcell setcell-ability"><label>Ability</label><input type="text" name="ability" class="chartinput" value="' + Tools.escapeHTML(set.ability) + '" /></div>';
buf += '</div></div>';
// moves
if (!set.moves) set.moves = [];
buf += '<div class="setcol setcol-moves"><div class="setcell"><label>Moves</label>';
buf += '<input type="text" name="move1" class="chartinput" value="' + Tools.escapeHTML(set.moves[0]) + '" /></div>';
buf += '<div class="setcell"><input type="text" name="move2" class="chartinput" value="' + Tools.escapeHTML(set.moves[1]) + '" /></div>';
buf += '<div class="setcell"><input type="text" name="move3" class="chartinput" value="' + Tools.escapeHTML(set.moves[2]) + '" /></div>';
buf += '<div class="setcell"><input type="text" name="move4" class="chartinput" value="' + Tools.escapeHTML(set.moves[3]) + '" /></div>';
buf += '</div>';
// stats
buf += '<div class="setcol setcol-stats"><div class="setrow"><label>Stats</label><button class="setstats" name="stats" class="chartinput">';
buf += '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>';
var stats = {};
for (var j in BattleStatNames) {
if (j === 'spd' && this.curTeam.gen === 1) continue;
stats[j] = this.getStat(j, set);
var ev = '<em>' + (set.evs[j] || '') + '</em>';
if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === j) {
ev += '<small>+</small>';
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === j) {
ev += '<small>−</small>';
}
var width = stats[j] * 75 / 504;
if (j == 'hp') width = stats[j] * 75 / 704;
if (width > 75) width = 75;
var color = Math.floor(stats[j] * 180 / 714);
if (color > 360) color = 360;
var statName = this.curTeam.gen === 1 && j === 'spa' ? 'Spc' : BattleStatNames[j];
buf += '<span class="statrow"><label>' + statName + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + ev + '</span>';
}
buf += '</button></div></div>';
buf += '</div></li>';
return buf;
},
saveImport: function () {
Storage.activeSetList = this.curSetList = Storage.importTeam(this.$('.teamedit textarea').val());
this.back();
},
addPokemon: function () {
if (!this.curTeam) return;
var team = this.curSetList;
if (!team.length || team[team.length - 1].species) {
var newPokemon = {
name: '',
species: '',
item: '',
nature: '',
evs: {},
ivs: {},
moves: []
};
team.push(newPokemon);
}
this.curSet = team[team.length - 1];
this.curSetLoc = team.length - 1;
this.curChartName = '';
this.update();
this.$('input[name=pokemon]').select();
},
pastePokemon: function (i, btn) {
if (!this.curTeam) return;
var team = this.curSetList;
if (team.length >= 6) return;
if (!this.clipboardCount()) return;
if (team.push($.extend(true, {}, this.clipboard[0])) >= 6) {
$(btn).css('display', 'none');
}
this.update();
this.save();
},
saveFlag: false,
save: function () {
this.saveFlag = true;
Storage.saveTeams();
},
validate: function () {
var format = this.curTeam.format;
if (!format) {
app.addPopupMessage('You need to pick a format to validate your team.');
return;
}
if (window.BattleFormats && BattleFormats[this.curTeam.format] && BattleFormats[this.curTeam.format].hasBattleFormat) {
format = BattleFormats[this.curTeam.format].battleFormat;
}
app.sendTeam(this.curTeam);
app.send('/vtm ' + format);
},
teamNameChange: function (e) {
var name = ($.trim(e.currentTarget.value) || 'Untitled ' + (this.curTeamLoc + 1));
if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator.");
name = name.replace(/[\\\/]/g, '');
}
this.curTeam.name = name;
e.currentTarget.value = name;
this.save();
},
format: function (format, button) {
if (!window.BattleFormats) {
return;
}
var self = this;
app.addPopup(FormatPopup, {format: format, sourceEl: button, selectType: 'teambuilder', onselect: function (newFormat) {
self.changeFormat(newFormat);
}});
},
changeFormat: function (format) {
this.curTeam.format = format;
this.curTeam.gen = this.getGen(this.curTeam.format);
this.save();
if (this.curTeam.gen === 5 && !Tools.loadedSpriteData['bw']) Tools.loadSpriteData('bw');
this.update();
},
nicknameChange: function (e) {
var i = +$(e.currentTarget).closest('li').attr('value');
var set = this.curSetList[i];
var name = $.trim(e.currentTarget.value) || set.species;
e.currentTarget.value = set.name = name;
this.save();
},
// clipboard
clipboard: [],
clipboardCount: function () {
return this.clipboard.length;
},
clipboardVisible: function () {
return !!this.clipboardCount();
},
clipboardHTML: function () {
var buf = '';
buf += '<div class="teambuilder-clipboard-container" style="display: ' + (this.clipboardVisible() ? 'block' : 'none') + ';">';
buf += '<div class="teambuilder-clipboard-title">Clipboard:</div>';
buf += '<div class="teambuilder-clipboard-data" tabindex="-1">' + this.clipboardInnerHTML() + '</div>';
buf += '<div class="teambuilder-clipboard-buttons">';
if (this.curTeam && this.curSetList.length < 6) {
buf += '<button name="pastePokemon" class="teambuilder-clipboard-button-left"><i class="fa fa-clipboard"></i> Paste!</button>';
}
buf += '<button name="clipboardRemoveAll" class="teambuilder-clipboard-button-right"><i class="fa fa-trash"></i> Clear clipboard</button>';
buf += '</div>';
buf += '</div>';
return buf;
},
clipboardInnerHTMLCache: '',
clipboardInnerHTML: function () {
if (this.clipboardInnerHTMLCache) {
return this.clipboardInnerHTMLCache;
}
var buf = '';
for (var i = 0; i < this.clipboardCount(); i++) {
var res = this.clipboard[i];
var pokemon = Tools.getTemplate(res.species);
buf += '<div class="result" data-id="' + i + '">';
buf += '<div class="section"><span class="icon" style="' + Tools.getIcon(res.species) + '"></span>';
buf += '<span class="species">' + (pokemon.species === pokemon.baseSpecies ? pokemon.species : (pokemon.baseSpecies + '-<small>' + pokemon.species.substr(pokemon.baseSpecies.length + 1) + '</small>')) + '</span></div>';
buf += '<div class="section"><span class="ability-item">' + (res.ability || '<i>No ability</i>') + '<br />' + (res.item || '<i>No item</i>') + '</span></div>';
buf += '<div class="section no-border">';
for (var j = 0; j < 4; j++) {
if (!(j & 1)) {
buf += '<span class="moves">';
}
buf += (res.moves[j] || '<i>No move</i>') + (!(j & 1) ? '<br />' : '');
if (j & 1) {
buf += '</span>';
}
}
buf += '</div>';
buf += '</div>';
}
this.clipboardInnerHTMLCache = buf;
return buf;
},
clipboardUpdate: function () {
this.clipboardInnerHTMLCache = '';
$('.teambuilder-clipboard-data').html(this.clipboardInnerHTML());
},
clipboardExpanded: false,
clipboardExpand: function () {
var $clipboard = $('.teambuilder-clipboard-data');
$clipboard.animate({height: this.clipboardCount() * 28}, 500, function () {
setTimeout(function () { $clipboard.focus(); }, 100);
});
setTimeout(function () {
this.clipboardExpanded = true;
}.bind(this), 10);
},
clipboardShrink: function () {
var $clipboard = $('.teambuilder-clipboard-data');
$clipboard.animate({height: 26}, 500);
setTimeout(function () {
this.clipboardExpanded = false;
}.bind(this), 10);
},
clipboardResultSelect: function (e) {
if (!this.clipboardExpanded) return;
e.preventDefault();
e.stopPropagation();
var target = +($(e.target).closest('.result').data('id'));
if (target === -1) {
this.clipboardShrink();
this.clipboardRemoveAll();
return;
}
this.clipboard.unshift(this.clipboard.splice(target, 1)[0]);
this.clipboardUpdate();
this.clipboardShrink();
},
clipboardAdd: function (set) {
if (this.clipboard.unshift(set) > 6) {
// we don't want the clipboard so big that it lags the teambuilder
this.clipboard.pop();
}
this.clipboardUpdate();
if (this.clipboardCount() === 1) {
var $clipboard = $('.teambuilder-clipboard-container').css('opacity', 0);
$clipboard.slideDown(250, function () {
$clipboard.animate({opacity: 1}, 250);
});
}
},
clipboardRemoveAll: function () {
this.clipboard = [];
var self = this;
var $clipboard = $('.teambuilder-clipboard-container');
$clipboard.animate({opacity: 0}, 250, function () {
$clipboard.slideUp(250, function () {
self.clipboardUpdate();
});
});
},
// copy/import/export/move/delete
copySet: function (i, button) {
i = +($(button).closest('li').attr('value'));
this.clipboardAdd($.extend(true, {}, this.curSetList[i]));
button.blur();
},
wasViewingPokemon: false,
importSet: function (i, button) {
i = +($(button).closest('li').attr('value'));
this.wasViewingPokemon = true;
if (!this.curSet) {
this.wasViewingPokemon = false;
this.selectPokemon(i);
}
this.$('li').find('input, button').prop('disabled', true);
this.$chart.hide();
this.$('.teambuilder-pokemon-import')
.show()
.find('textarea')
.val(Storage.exportTeam([this.curSet]).trim())
.focus()
.select();
},
closePokemonImport: function (force) {
if (!this.wasViewingPokemon) return this.back();
var $li = this.$('li');
var i = +($li.attr('value'));
this.$('.teambuilder-pokemon-import').hide();
this.$chart.show();
if (force === true) return this.selectPokemon(i);
$li.find('input, button').prop('disabled', false);
},
savePokemonImport: function (i) {
i = +(this.$('li').attr('value'));
var curSet = Storage.importTeam(this.$('.pokemonedit').val())[0];
if (curSet) {
this.curSet = curSet;
this.curSetList[i] = curSet;
}
this.closePokemonImport(true);
},
moveSet: function (i, button) {
i = +($(button).closest('li').attr('value'));
app.addPopup(MovePopup, {
i: i,
team: this.curSetList
});
},
deleteSet: function (i, button) {
i = +($(button).closest('li').attr('value'));
this.deletedSetLoc = i;
this.deletedSet = this.curSetList.splice(i, 1)[0];
if (this.curSet) {
this.addPokemon();
} else {
this.update();
}
this.save();
},
undeleteSet: function () {
if (this.deletedSet) {
var loc = this.deletedSetLoc;
this.curSetList.splice(loc, 0, this.deletedSet);
this.deletedSet = null;
this.deletedSetLoc = -1;
this.save();
if (this.curSet) {
this.curSetLoc = loc;
this.curSet = this.curSetList[loc];
this.curChartName = '';
this.update();
this.updateChart();
} else {
this.update();
}
}
},
/*********************************************************
* Set view
*********************************************************/
updateSetView: function () {
// pokemon
var buf = '<div class="pad">';
buf += '<button name="back"><i class="fa fa-chevron-left"></i> Team</button></div>';
buf += '<div class="teambar">';
buf += this.renderTeambar();
buf += '</div>';
// pokemon
buf += '<div class="teamchartbox individual">';
buf += '<ol class="teamchart">';
buf += this.renderSet(this.curSet, this.curSetLoc);
buf += '</ol>';
buf += '</div>';
// results
this.chartPrevSearch = '[init]';
buf += '<div class="teambuilder-results"></div>';
// import/export
buf += '<div class="teambuilder-pokemon-import">';
buf += '<div class="pokemonedit-buttons"><button name="closePokemonImport"><i class="fa fa-chevron-left"></i> Back</button> <button name="savePokemonImport"><i class="fa fa-floppy-o"></i> Save</button></div>';
buf += '<textarea class="pokemonedit textbox" rows="14"></textarea>';
buf += '</div>';
this.$el.html('<div class="teamwrapper">' + buf + '</div>');
if ($(window).width() < 640) this.show();
this.$chart = this.$('.teambuilder-results');
},
updateSetTop: function () {
this.$('.teambar').html(this.renderTeambar());
this.$('.teamchart').first().html(this.renderSet(this.curSet, this.curSetLoc));
},
renderTeambar: function () {
var buf = '';
var isAdd = false;
if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].name && this.curSetLoc !== this.curSetList.length - 1) {
this.curSetList.splice(this.curSetList.length - 1, 1);
}
for (var i = 0; i < this.curSetList.length; i++) {
var set = this.curSetList[i];
var pokemonicon = '<span class="pokemonicon pokemonicon-' + i + '" style="' + Tools.getIcon(set) + '"></span>';
if (!set.name) {
buf += '<button disabled="disabled" class="addpokemon"><i class="fa fa-plus"></i></button> ';
isAdd = true;
} else if (i == this.curSetLoc) {
buf += '<button disabled="disabled" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name || '<i class="fa fa-plus"></i>') + '</button> ';
} else {
buf += '<button name="selectPokemon" value="' + i + '" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name) + '</button> ';
}
}
if (this.curSetList.length < 6 && !isAdd) {
buf += '<button name="addPokemon"><i class="fa fa-plus"></i></button> ';
}
return buf;
},
updatePokemonSprite: function () {
var set = this.curSet;
if (!set) return;
var shiny = (set.shiny ? '-shiny' : '');
var sprite = Tools.getTemplate(set.species).spriteid;
if (BattlePokemonSprites && BattlePokemonSprites[sprite] && BattlePokemonSprites[sprite].front && BattlePokemonSprites[sprite].front.anif && set.gender === 'F') {
sprite += '-f';
}
this.$('.setcol-icon').css('background-image', Tools.getTeambuilderSprite(set).substr(17));
this.$('.pokemonicon-' + this.curSetLoc).css('background', Tools.getIcon(set).substr(11));
var item = Tools.getItem(set.item);
if (item.id) {
this.$('.setcol-icon .itemicon').css('background', Tools.getItemIcon(item).substr(11));
} else {
this.$('.setcol-icon .itemicon').css('background', 'none');
}
this.updateStatGraph();
},
updateStatGraph: function () {
var set = this.curSet;
if (!set) return;
var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''};
// stat cell
var buf = '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>';
for (var stat in stats) {
if (stat === 'spd' && this.curTeam.gen === 1) continue;
stats[stat] = this.getStat(stat, set);
var ev = '<em>' + (set.evs[stat] || '') + '</em>';
if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) {
ev += '<small>+</small>';
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) {
ev += '<small>−</small>';
}
var width = stats[stat] * 75 / 504;
if (stat == 'hp') width = stats[stat] * 75 / 704;
if (width > 75) width = 75;
var color = Math.floor(stats[stat] * 180 / 714);
if (color > 360) color = 360;
buf += '<span class="statrow"><label>' + BattleStatNames[stat] + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + ev + '</span>';
}
this.$('button[name=stats]').html(buf);
if (this.curChartType !== 'stats') return;
buf = '<div></div>';
for (var stat in stats) {
buf += '<div><b>' + stats[stat] + '</b></div>';
}
this.$chart.find('.statscol').html(buf);
buf = '<div></div>';
var totalev = 0;
for (var stat in stats) {
if (stat === 'spd' && this.curTeam.gen === 1) continue;
var width = stats[stat] * 180 / 504;
if (stat == 'hp') width = stats[stat] * 180 / 704;
if (width > 179) width = 179;
var color = Math.floor(stats[stat] * 180 / 714);
if (color > 360) color = 360;
buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>';
totalev += (set.evs[stat] || 0);
}
buf += '<div><em>Remaining:</em></div>';
this.$chart.find('.graphcol').html(buf);
var maxEv = this.curTeam.gen > 2 ? 510 : this.curTeam.gen === 1 ? 1275 : 1530;
if (totalev <= maxEv) {
this.$chart.find('.totalev').html('<em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em>');
} else {
this.$chart.find('.totalev').html('<b>' + (maxEv - totalev) + '</b>');
}
this.$chart.find('select[name=nature]').val(set.nature || 'Serious');
},
curChartType: '',
curChartName: '',
updateChart: function () {
var type = this.curChartType;
app.clearGlobalListeners();
if (type === 'stats') {
this.updateStatForm();
return;
}
if (type === 'details') {
this.updateDetailsForm();
return;
}
// cache movelist ref
var speciesid = toId(this.curSet.species);
var g6 = (this.curTeam.format && this.curTeam.format === 'vgc2016');
this.applyMovelist(g6, speciesid);
this.$chart.html('<em>Loading ' + this.curChartType + '...</em>');
var self = this;
if (this.updateChartTimeout) clearTimeout(this.updateChartTimeout);
this.updateChartTimeout = setTimeout(function () {
self.updateChartTimeout = null;
if (self.curChartType === 'stats' || self.curChartType === 'details' || !self.curChartName) return;
self.$chart.html(Chart.chart(self.$('input[name=' + self.curChartName + ']').val(), self.curChartType, true, _.bind(self.arrangeCallback[self.curChartType], self), null, self.curTeam.gen));
}, 10);
},
updateChartTimeout: null,
updateChartDelayed: function () {
// cache movelist ref
var speciesid = toId(this.curSet.species);
var g6 = (this.curTeam.format && this.curTeam.format === 'vgc2016');
this.applyMovelist(g6, speciesid);
var self = this;
if (this.updateChartTimeout) clearTimeout(this.updateChartTimeout);
this.updateChartTimeout = setTimeout(function () {
self.updateChartTimeout = null;
if (self.curChartType === 'stats' || self.curChartType === 'details') return;
self.$chart.html(Chart.chart(self.$('input[name=' + self.curChartName + ']').val(), self.curChartType, false, _.bind(self.arrangeCallback[self.curChartType], self), null, self.curTeam.gen));
}, 200);
},
selectPokemon: function (i) {
i = +i;
var set = this.curSetList[i];
if (set) {
this.curSet = set;
this.curSetLoc = i;
var name = this.curChartName || 'details';
if (name === 'details' || name === 'stats') {
this.update();
this.updateChart();
} else {
this.curChartName = '';
this.update();
this.$('input[name=' + name + ']').select();
}
}
},
stats: function (i, button) {
if (!this.curSet) this.selectPokemon($(button).closest('li').val());
this.curChartName = 'stats';
this.curChartType = 'stats';
this.updateStatForm();
},
details: function (i, button) {
if (!this.curSet) this.selectPokemon($(button).closest('li').val());
this.curChartName = 'details';
this.curChartType = 'details';
this.updateDetailsForm();
},
/*********************************************************
* Set stat form
*********************************************************/
plus: '',
minus: '',
smogdexLink: function (template) {
var template = Tools.getTemplate(template);
var format = this.curTeam && this.curTeam.format;
var smogdexid = toId(template.baseSpecies);
if (template.isNonstandard) {
return 'http://www.smogon.com/cap/pokemon/strategies/' + smogdexid;
}
if (template.speciesid === 'meowstic') {
smogdexid = 'meowstic-m';
} else if (template.speciesid === 'hoopaunbound') {
smogdexid = 'hoopa-alt';
} else if (smogdexid === 'rotom' || smogdexid === 'deoxys' || smogdexid === 'kyurem' || smogdexid === 'giratina' || smogdexid === 'shaymin' || smogdexid === 'tornadus' || smogdexid === 'thundurus' || smogdexid === 'landorus' || smogdexid === 'pumpkaboo' || smogdexid === 'gourgeist' || smogdexid === 'arceus' || smogdexid === 'meowstic') {
if (template.forme) smogdexid += '-' + toId(template.forme);
}
var generationNumber = 6;
if (format.substr(0, 3) === 'gen') {
var number = format.charAt(3);
if ('1' <= number && number <= '5') {
generationNumber = +number;
format = format.substr(4);
}
}
var generation = ['rb', 'gs', 'rs', 'dp', 'bw', 'xy'][generationNumber - 1];
if (format === 'battlespotdoubles') {
smogdexid += '/vgc15';
} else if (format === 'doublesou' || format === 'doublesuu') {
smogdexid += '/doubles';
} else if (format === 'ou' || format === 'uu' || format === 'ru' || format === 'nu' || format === 'pu' || format === 'lc') {
smogdexid += '/' + format;
}
return 'http://smogon.com/dex/' + generation + '/pokemon/' + smogdexid + '/';
},
updateStatForm: function (setGuessed) {
var buf = '';
var set = this.curSet;
var template = Tools.getTemplate(this.curSet.species);
var baseStats = template.baseStats;
buf += '<h3>EVs</h3>';
buf += '<div class="statform">';
var role = this.guessRole();
var guessedEVs = {};
var guessedPlus = '';
var guessedMinus = '';
buf += '<p class="suggested"><small>Suggested spread:';
if (role === '?') {
buf += ' (Please choose 4 moves to get a suggested spread) (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon analysis</a>)</small></p>';
} else {
guessedEVs = this.guessEVs(role);
guessedPlus = guessedEVs.plusStat;
delete guessedEVs.plusStat;
guessedMinus = guessedEVs.minusStat;
delete guessedEVs.minusStat;
buf += ' </small><button name="setStatFormGuesses">' + role + ': ';
for (var i in guessedEVs) {
if (guessedEVs[i]) {
var statName = this.curTeam.gen === 1 && i === 'spa' ? 'Spc' : BattleStatNames[i];
buf += '' + guessedEVs[i] + ' ' + statName + ' / ';
}
}
if (guessedPlus && guessedMinus) buf += ' (+' + BattleStatNames[guessedPlus] + ', -' + BattleStatNames[guessedMinus] + ')';
else buf = buf.slice(0, -3);
buf += '</button><small> (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon analysis</a>)</small></p>';
//buf += ' <small>(' + role + ' | bulk: phys ' + Math.round(this.moveCount.physicalBulk/1000) + ' + spec ' + Math.round(this.moveCount.specialBulk/1000) + ' = ' + Math.round(this.moveCount.bulk/1000) + ')</small>';
}
if (setGuessed) {
set.evs = guessedEVs;
this.plus = guessedPlus;
this.minus = guessedMinus;
this.updateNature();
this.save();
this.updateStatGraph();
this.natureChange();
return;
}
var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''};
if (this.curTeam.gen === 1) delete stats.spd;
if (!set) return;
var nature = BattleNatures[set.nature || 'Serious'];
if (!nature) nature = {};
// label column
buf += '<div class="col labelcol"><div></div>';
buf += '<div><label>HP</label></div><div><label>Attack</label></div><div><label>Defense</label></div><div>';
if (this.curTeam.gen === 1) {
buf += '<label>Special</label></div>';
} else {
buf += '<label>Sp. Atk.</label></div><div><label>Sp. Def.</label></div>';
}
buf += '<div><label>Speed</label></div></div>';
buf += '<div class="col basestatscol"><div><em>Base</em></div>';
for (var i in stats) {
buf += '<div><b>' + baseStats[i] + '</b></div>';
}
buf += '</div>';
buf += '<div class="col graphcol"><div></div>';
for (var i in stats) {
stats[i] = this.getStat(i);
var width = stats[i] * 180 / 504;
if (i == 'hp') width = Math.floor(stats[i] * 180 / 704);
if (width > 179) width = 179;
var color = Math.floor(stats[i] * 180 / 714);
if (color > 360) color = 360;
buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>';
}
buf += '<div><em>Remaining:</em></div>';
buf += '</div>';
buf += '<div class="col evcol"><div><strong>EVs</strong></div>';
var totalev = 0;
this.plus = '';
this.minus = '';
for (var i in stats) {
var width = stats[i] * 200 / 504;
if (i == 'hp') width = stats[i] * 200 / 704;
if (width > 200) width = 200;
var val = '' + (set.evs[i] || '');
if (nature.plus === i) {
val += '+';
this.plus = i;
}
if (nature.minus === i) {
val += '-';
this.minus = i;
}
buf += '<div><input type="text" name="stat-' + i + '" value="' + val + '" class="inputform numform" /></div>';
totalev += (set.evs[i] || 0);
}
var maxEv = this.curTeam.gen > 2 ? 510 : this.curTeam.gen === 1 ? 1275 : 1530;
if (totalev <= maxEv) {
buf += '<div class="totalev"><em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em></div>';
} else {
buf += '<div class="totalev"><b>' + (maxEv - totalev) + '</b></div>';
}
buf += '</div>';
buf += '<div class="col evslidercol"><div></div>';
for (var i in stats) {
if (i === 'spd' && this.curTeam.gen === 1) continue;
buf += '<div><input type="slider" name="evslider-' + i + '" value="' + Tools.escapeHTML(set.evs[i] || '0') + '" min="0" max="252" step="4" class="evslider" /></div>';
}
buf += '</div>';
buf += '<div class="col ivcol"><div><strong>IVs</strong></div>';
var totalev = 0;
if (!set.ivs) set.ivs = {};
for (var i in stats) {
if (typeof set.ivs[i] === 'undefined' || isNaN(set.ivs[i])) set.ivs[i] = 31;
var val = '' + (set.ivs[i]);
buf += '<div><input type="number" name="iv-' + i + '" value="' + Tools.escapeHTML(val) + '" class="inputform numform" min="0" max="31" step="1" /></div>';
}
buf += '</div>';
buf += '<div class="col statscol"><div></div>';
for (var i in stats) {
buf += '<div><b>' + stats[i] + '</b></div>';
}
buf += '</div>';
if (this.curTeam.gen > 2) {
buf += '<p style="clear:both">Nature: <select name="nature">';
for (var i in BattleNatures) {
var curNature = BattleNatures[i];
buf += '<option value="' + i + '"' + (curNature === nature ? 'selected="selected"' : '') + '>' + i;
if (curNature.plus) {
buf += ' (+' + BattleStatNames[curNature.plus] + ', -' + BattleStatNames[curNature.minus] + ')';
}
buf += '</option>';
}
buf += '</select></p>';
buf += '<p><em>Protip:</em> You can also set natures by typing "+" and "-" next to a stat.</p>';
}
buf += '</div>';
this.$chart.html(buf);
var self = this;
this.suppressSliderCallback = true;
app.clearGlobalListeners();
this.$chart.find('.evslider').slider({
from: 0,
to: 252,
step: 4,
skin: 'round_plastic',
onstatechange: function (val) {
if (!self.suppressSliderCallback) self.statSlide(val, this);
},
callback: function () {
self.save();
}
});
this.suppressSliderCallback = false;
},
setStatFormGuesses: function () {
this.updateStatForm(true);
},
setSlider: function (stat, val) {
this.suppressSliderCallback = true;
this.$chart.find('input[name=evslider-' + stat + ']').slider('value', val || 0);
this.suppressSliderCallback = false;
},
updateNature: function () {
var set = this.curSet;
if (!set) return;
if (this.plus === '' || this.minus === '') {
set.nature = 'Serious';
} else {
for (var i in BattleNatures) {
if (BattleNatures[i].plus === this.plus && BattleNatures[i].minus === this.minus) {
set.nature = i;
break;
}
}
}
},
statChange: function (e) {
var inputName = '';
inputName = e.currentTarget.name;
var val = Math.abs(parseInt(e.currentTarget.value, 10));
var set = this.curSet;
if (!set) return;
if (inputName.substr(0, 5) === 'stat-') {
// EV
// Handle + and -
var stat = inputName.substr(5);
if (!set.evs) set.evs = {};
var lastchar = e.currentTarget.value.charAt(e.target.value.length - 1);
var firstchar = e.currentTarget.value.charAt(0);
var natureChange = true;
if ((lastchar === '+' || firstchar === '+') && stat !== 'hp') {
if (this.plus && this.plus !== stat) this.$chart.find('input[name=stat-' + this.plus + ']').val(set.evs[this.plus] || '');
this.plus = stat;
} else if ((lastchar === '-' || lastchar === "\u2212" || firstchar === '-' || firstchar === "\u2212") && stat !== 'hp') {
if (this.minus && this.minus !== stat) this.$chart.find('input[name=stat-' + this.minus + ']').val(set.evs[this.minus] || '');
this.minus = stat;
} else if (this.plus === stat) {
this.plus = '';
} else if (this.minus === stat) {
this.minus = '';
} else {
natureChange = false;
}
if (natureChange) {
this.updateNature();
}
// cap
if (val > 252) val = 252;
if (val < 0 || isNaN(val)) val = 0;
if (set.evs[stat] !== val || natureChange) {
set.evs[stat] = val;
this.setSlider(stat, val);
this.updateStatGraph();
}
} else {
// IV
var stat = inputName.substr(3);
if (val > 31 || isNaN(val)) val = 31;
if (val < 0) val = 0;
if (!set.ivs) set.ivs = {};
if (set.ivs[stat] !== val) {
set.ivs[stat] = val;
this.updateStatGraph();
}
}
this.save();
},
statSlide: function (val, slider) {
var stat = slider.inputNode[0].name.substr(9);
var set = this.curSet;
if (!set) return;
val = +val;
var originalVal = val;
var result = this.getStat(stat, set, val);
while (val && this.getStat(stat, set, val - 4) == result) val -= 4;
if (!this.ignoreEVLimits && set.evs) {
var total = 0;
for (var i in set.evs) {
total += (i === stat ? val : set.evs[i]);
}
if (total > 508 && val - total + 508 >= 0) {
// don't allow dragging beyond 508 EVs
val = val - total + 508;
// make sure val is a legal value
val = +val;
if (!val || val <= 0) val = 0;
if (val > 252) val = 252;
}
}
// Don't try this at home.
// I am a trained professional.
if (val !== originalVal) slider.o.pointers[0].set(val);
if (!set.evs) set.evs = {};
set.evs[stat] = val;
val = '' + (val || '') + (this.plus === stat ? '+' : '') + (this.minus === stat ? '-' : '');
this.$('input[name=stat-' + stat + ']').val(val);
this.updateStatGraph();
},
natureChange: function (e) {
var set = this.curSet;
if (!set) return;
if (e) {
set.nature = e.currentTarget.value;
}
this.plus = '';
this.minus = '';
var nature = BattleNatures[set.nature || 'Serious'];
for (var i in BattleStatNames) {
var val = '' + (set.evs[i] || '');
if (nature.plus === i) {
this.plus = i;
val += '+';
}
if (nature.minus === i) {
this.minus = i;
val += '-';
}
this.$chart.find('input[name=stat-' + i + ']').val(val);
if (!e) this.setSlider(i, set.evs[i]);
}
this.save();
this.updateStatGraph();
},
/*********************************************************
* Set details form
*********************************************************/
updateDetailsForm: function () {
var buf = '';
var set = this.curSet;
var template = Tools.getTemplate(set.species);
if (!set) return;
buf += '<h3>Details</h3>';
buf += '<form class="detailsform">';
buf += '<div class="formrow"><label class="formlabel">Level:</label><div><input type="number" min="1" max="100" step="1" name="level" value="' + Tools.escapeHTML(set.level || 100) + '" class="textbox inputform numform" /></div></div>';
if (this.curTeam.gen > 1) {
buf += '<div class="formrow"><label class="formlabel">Gender:</label><div>';
if (template.gender) {
var genderTable = {'M': "Male", 'F': "Female", 'N': "Genderless"};
buf += genderTable[template.gender];
} else {
buf += '<label><input type="radio" name="gender" value="M"' + (set.gender === 'M' ? ' checked' : '') + ' /> Male</label> ';
buf += '<label><input type="radio" name="gender" value="F"' + (set.gender === 'F' ? ' checked' : '') + ' /> Female</label> ';
buf += '<label><input type="radio" name="gender" value="N"' + (!set.gender ? ' checked' : '') + ' /> Random</label>';
}
buf += '</div></div>';
buf += '<div class="formrow"><label class="formlabel">Happiness:</label><div><input type="number" min="0" max="255" step="1" name="happiness" value="' + (typeof set.happiness === 'number' ? set.happiness : 255) + '" class="textbox inputform numform" /></div></div>';
buf += '<div class="formrow"><label class="formlabel">Shiny:</label><div>';
buf += '<label><input type="radio" name="shiny" value="yes"' + (set.shiny ? ' checked' : '') + ' /> Yes</label> ';
buf += '<label><input type="radio" name="shiny" value="no"' + (!set.shiny ? ' checked' : '') + ' /> No</label>';
buf += '</div></div>';
}
buf += '</form>';
this.$chart.html(buf);
},
detailsChange: function () {
var set = this.curSet;
if (!set) return;
// level
var level = parseInt(this.$chart.find('input[name=level]').val(), 10);
if (!level || level > 100 || level < 1) level = 100;
if (level !== 100 || set.level) set.level = level;
// happiness
var happiness = parseInt(this.$chart.find('input[name=happiness]').val(), 10);
if (happiness > 255) happiness = 255;
if (happiness < 0) happiness = 255;
set.happiness = happiness;
if (set.happiness === 255) delete set.happiness;
// shiny
var shiny = (this.$chart.find('input[name=shiny]:checked').val() === 'yes');
if (shiny) {
set.shiny = true;
} else {
delete set.shiny;
}
var gender = this.$chart.find('input[name=gender]:checked').val();
if (gender === 'M' || gender === 'F') {
set.gender = gender;
} else {
delete set.gender;
}
// update details cell
var buf = '';
var GenderChart = {
'M': 'Male',
'F': 'Female',
'N': '—'
};
buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>';
if (this.curTeam.gen > 1) {
buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[set.gender || 'N'] + '</span>';
buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>';
buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>';
}
this.$('button[name=details]').html(buf);
this.save();
this.updatePokemonSprite();
},
/*********************************************************
* Set charts
*********************************************************/
arrangeCallback: {
pokemon: function (pokemon) {
if (!pokemon) {
if (this.curTeam) {
if (this.curTeam.format === 'ubers' || this.curTeam.format === 'anythinggoes') return ['Uber', 'OU', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'ou') return ['OU', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'cap') return ['CAP', 'OU', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'uu') return ['UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'ru') return ['RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'nu') return ['NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'pu') return ['PU', 'NFE', 'LC Uber', 'LC'];
if (this.curTeam.format === 'lc') return ['LC'];
}
return ['OU', 'Uber', 'BL', 'OU only when combining mega and non-mega usage', 'UU', 'BL2', 'UU only when combining mega and non-mega usage', 'RU', 'BL3', 'RU only when combining mega and non-mega usage', 'NU', 'BL4', 'NU only when combining mega and non-mega usage', 'PU', 'NFE', 'LC Uber', 'LC', 'Unreleased', 'CAP'];
}
var speciesid = toId(pokemon.species);
var tierData = exports.BattleFormatsData[speciesid];
if (!tierData) return 'Illegal';
var displayTier = {"(OU)": "OU only when combining mega and non-mega usage", "(UU)": "UU only when combining mega and non-mega usage", "(RU)": "RU only when combining mega and non-mega usage", "(NU)": "NU only when combining mega and non-mega usage"};
if (tierData.tier in displayTier) {
return displayTier[tierData.tier];
}
return tierData.tier;
},
item: function (item) {
if (!item) return ['Items'];
return 'Items';
},
ability: function (ability) {
if (!this.curSet) return;
var template = Tools.getTemplate(this.curSet.species);
var isMega = false;
if (template.forme.substr(0, 4) === 'Mega' && this.curTeam.format !== 'balancedhackmons') {
if (!ability) return ['Pre-Mega Abilities', 'Pre-Mega Hidden Ability'];
isMega = true;
template = Tools.getTemplate(template.baseSpecies);
}
if (!ability) return ['Abilities', 'Hidden Ability'];
if (!template.abilities) return 'Abilities';
if (ability.name === template.abilities['0']) return isMega ? 'Pre-Mega Abilities' : 'Abilities';
if (ability.name === template.abilities['1']) return isMega ? 'Pre-Mega Abilities' : 'Abilities';
if (ability.name === template.abilities['H']) return isMega ? 'Pre-Mega Hidden Ability' : 'Hidden Ability';
if (!this.curTeam || this.curTeam.format !== 'balancedhackmons') return 'Illegal';
},
move: function (move) {
if (!this.curSet) return;
if (!move) return ['Usable Moves', 'Moves', 'Usable Sketch Moves', 'Sketch Moves'];
var movelist = this.movelist;
if (!movelist) return 'Illegal';
if (!movelist[move.id]) {
if (movelist['sketch'] && move.id !== 'chatter' && move.id !== 'struggle') {
if (move.isViable) return 'Usable Sketch Moves';
return 'Sketch Moves';
}
if (!this.curTeam || this.curTeam.format !== 'balancedhackmons') return 'Illegal';
}
var speciesid = toId(this.curSet.species);
if (move.isViable) return 'Usable Moves';
return 'Moves';
}
},
chartTypes: {
pokemon: 'pokemon',
item: 'item',
ability: 'ability',
move1: 'move',
move2: 'move',
move3: 'move',
move4: 'move',
stats: 'stats',
details: 'details'
},
chartClick: function (e) {
this.chartSet($(e.currentTarget).data('name'), true);
},
chartKeydown: function (e) {
var modifier = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || e.cmdKey);
if (e.keyCode === 13 || (e.keyCode === 9 && !modifier)) {
if (!this.arrangeCallback[this.curChartType]) return;
e.stopPropagation();
e.preventDefault();
var name = e.currentTarget.name;
this.$chart.html(Chart.chart(e.currentTarget.value, this.curChartType, false, _.bind(this.arrangeCallback[this.curChartType], this), null, this.curTeam.gen));
var val = Chart.firstResult;
this.chartSet(val, true);
return;
}
},
chartKeyup: function () {
this.updateChartDelayed();
},
chartFocus: function (e) {
var $target = $(e.currentTarget);
var name = e.currentTarget.name;
var type = this.chartTypes[name];
$target.removeClass('incomplete');
if (this.curChartName === name) return;
if (!this.curSet) {
var i = +$target.closest('li').prop('value');
this.curSet = this.curSetList[i];
this.curSetLoc = i;
this.update();
if (type === 'stats' || type === 'details') {
this.$('button[name=' + name + ']').click();
} else {
this.$('input[name=' + name + ']').select();
}
return;
}
this.curChartName = name;
this.curChartType = type;
this.updateChart();
},
chartChange: function (e) {
var name = e.currentTarget.name;
var type = this.chartTypes[name];
var arrange = null;
if (this.arrangeCallback[this.curChartType]) {
arrange = _.bind(this.arrangeCallback[this.curChartType], this);
}
this.$chart.html(Chart.chart(e.currentTarget.value, type, false, arrange, null, this.curTeam.gen));
var val = Chart.firstResult;
var id = toId(e.currentTarget.value);
if (toId(val) !== id) {
$(e.currentTarget).addClass('incomplete');
return;
}
this.chartSet(val);
},
chartSet: function (val, selectNext) {
var inputName = this.curChartName;
var id = toId(val);
this.$('input[name=' + inputName + ']').val(val).removeClass('incomplete');
switch (inputName) {
case 'pokemon':
this.setPokemon(val, selectNext);
break;
case 'item':
this.curSet.item = val;
this.updatePokemonSprite();
if (selectNext) this.$(this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]').select();
break;
case 'ability':
this.curSet.ability = val;
if (selectNext) this.$('input[name=move1]').select();
break;
case 'move1':
this.curSet.moves[0] = val;
this.chooseMove(val);
if (selectNext) this.$('input[name=move2]').select();
break;
case 'move2':
if (!this.curSet.moves[0]) this.curSet.moves[0] = '';
this.curSet.moves[1] = val;
this.chooseMove(val);
this.$('input[name=move3]').select();
break;
case 'move3':
if (!this.curSet.moves[0]) this.curSet.moves[0] = '';
if (!this.curSet.moves[1]) this.curSet.moves[1] = '';
this.curSet.moves[2] = val;
this.chooseMove(val);
if (selectNext) this.$('input[name=move4]').select();
break;
case 'move4':
if (!this.curSet.moves[0]) this.curSet.moves[0] = '';
if (!this.curSet.moves[1]) this.curSet.moves[1] = '';
if (!this.curSet.moves[2]) this.curSet.moves[2] = '';
this.curSet.moves[3] = val;
this.chooseMove(val);
if (selectNext) this.stats();
break;
}
this.save();
},
chooseMove: function (move) {
var set = this.curSet;
if (!set) return;
if (move.substr(0, 13) === 'Hidden Power ') {
set.ivs = {};
for (var i in exports.BattleTypeChart[move.substr(13)].HPivs) {
set.ivs[i] = exports.BattleTypeChart[move.substr(13)].HPivs[i];
}
var moves = this.curSet.moves;
for (var i = 0; i < moves.length; ++i) {
if (moves[i] === 'Gyro Ball' || moves[i] === 'Trick Room') set.ivs['spe'] = set.ivs['spe'] % 4;
}
} else if (move === 'Gyro Ball' || move === 'Trick Room') {
var hasHiddenPower = false;
var moves = this.curSet.moves;
for (var i = 0; i < moves.length; ++i) {
if (moves[i].substr(0, 13) === 'Hidden Power ') hasHiddenPower = true;
}
set.ivs['spe'] = hasHiddenPower ? set.ivs['spe'] % 4 : 0;
} else if (move === 'Return') {
this.curSet.happiness = 255;
} else if (move === 'Frustration') {
this.curSet.happiness = 0;
}
},
setPokemon: function (val, selectNext) {
var set = this.curSet;
var template = Tools.getTemplate(val);
var newPokemon = !set.species;
if (!template.exists || set.species === template.species) return;
set.name = template.species;
set.species = val;
if (set.level) delete set.level;
if (this.curTeam && this.curTeam.format) {
if (this.curTeam.format.substr(0, 10) === 'battlespot' || this.curTeam.format.substr(0, 3) === 'vgc') set.level = 50;
if (this.curTeam.format.substr(0, 2) === 'lc' || this.curTeam.format === 'gen5lc' || this.curTeam.format === 'gen4lc') set.level = 5;
}
if (set.gender) delete set.gender;
if (template.gender && template.gender !== 'N') set.gender = template.gender;
if (set.happiness) delete set.happiness;
if (set.shiny) delete set.shiny;
if (this.curTeam.format !== 'balancedhackmons') {
var formatsData = window.BattleFormatsData && BattleFormatsData[template.speciesid];
set.item = (formatsData.requiredItem || '');
} else {
set.item = '';
}
set.ability = template.abilities['0'];
set.moves = [];
set.evs = {};
set.ivs = {};
set.nature = '';
this.updateSetTop();
if (selectNext) this.$(set.item || !this.$('input[name=item]').length ? (this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]') : 'input[name=item]').select();
},
/*********************************************************
* Utility functions
*********************************************************/
// EV guesser
guessRole: function () {
var set = this.curSet;
if (!set) return '?';
if (!set.moves) return '?';
var moveCount = {
'Physical': 0,
'Special': 0,
'PhysicalOffense': 0,
'SpecialOffense': 0,
'PhysicalSetup': 0,
'SpecialSetup': 0,
'Support': 0,
'Setup': 0,
'Restoration': 0,
'Offense': 0,
'Stall': 0,
'SpecialStall': 0,
'PhysicalStall': 0,
'Ultrafast': 0
};
var hasMove = {};
var template = Tools.getTemplate(set.species || set.name);
var stats = template.baseStats;
var itemid = toId(set.item);
var abilityid = toId(set.ability);
if (set.moves.length < 4 && template.id !== 'unown' && template.id !== 'ditto' && this.curTeam.gen > 2) return '?';
for (var i = 0, len = set.moves.length; i < len; i++) {
var move = Tools.getMove(set.moves[i]);
hasMove[move.id] = 1;
if (move.category === 'Status') {
if (move.id === 'batonpass' || move.id === 'healingwish' || move.id === 'lunardance') {
moveCount['Support']++;
} else if (move.id === 'naturepower') {
moveCount['Special']++;
} else if (move.id === 'protect' || move.id === 'detect' || move.id === 'spikyshield' || move.id === 'kingsshield') {
moveCount['Stall']++;
} else if (move.id === 'wish') {
moveCount['Restoration']++;
moveCount['Stall']++;
moveCount['Support']++;
} else if (move.heal) {
moveCount['Restoration']++;
moveCount['Stall']++;
} else if (move.target === 'self') {
if (move.id === 'agility' || move.id === 'rockpolish' || move.id === 'shellsmash' || move.id === 'growth' || move.id === 'workup') {
moveCount['PhysicalSetup']++;
moveCount['SpecialSetup']++;
} else if (move.id === 'dragondance' || move.id === 'swordsdance' || move.id === 'coil' || move.id === 'bulkup' || move.id === 'curse' || move.id === 'bellydrum') {
moveCount['PhysicalSetup']++;
} else if (move.id === 'nastyplot' || move.id === 'tailglow' || move.id === 'quiverdance' || move.id === 'calmmind' || move.id === 'geomancy') {
moveCount['SpecialSetup']++;
}
if (move.id === 'substitute') moveCount['Stall']++;
moveCount['Setup']++;
} else {
if (move.id === 'toxic' || move.id === 'leechseed' || move.id === 'willowisp') moveCount['Stall']++;
moveCount['Support']++;
}
} else if (move.id === 'counter' || move.id === 'endeavor' || move.id === 'metalburst' || move.id === 'mirrorcoat' || move.id === 'rapidspin') {
moveCount['Support']++;
} else if (move.id === 'nightshade' || move.id === 'seismictoss' || move.id === 'superfang' || move.id === 'foulplay' || move.id === 'finalgambit') {
moveCount['Offense']++;
} else if (move.id === 'fellstinger') {
moveCount['PhysicalSetup']++;
moveCount['Setup']++;
} else {
moveCount[move.category]++;
moveCount['Offense']++;
if (move.id === 'knockoff') moveCount['Support']++;
if (move.id === 'scald' || move.id === 'voltswitch' || move.id === 'uturn') moveCount[move.category] -= 0.2;
}
}
if (hasMove['batonpass']) moveCount['Support'] += moveCount['Setup'];
moveCount['PhysicalAttack'] = moveCount['Physical'];
moveCount['Physical'] += moveCount['PhysicalSetup'];
moveCount['SpecialAttack'] = moveCount['Special'];
moveCount['Special'] += moveCount['SpecialSetup'];
if (hasMove['dragondance'] || hasMove['quiverdance']) moveCount['Ultrafast'] = 1;
var isFast = (stats.spe > 95);
var physicalBulk = (stats.hp + 75) * (stats.def + 87);
var specialBulk = (stats.hp + 75) * (stats.spd + 87);
if (hasMove['willowisp'] || hasMove['acidarmor'] || hasMove['irondefense'] || hasMove['cottonguard']) {
physicalBulk *= 1.6;
moveCount['PhysicalStall']++;
} else if (hasMove['scald'] || hasMove['bulkup'] || hasMove['coil'] || hasMove['cosmicpower']) {
physicalBulk *= 1.3;
if (hasMove['scald']) { // partial stall goes in reverse
moveCount['SpecialStall']++;
} else {
moveCount['PhysicalStall']++;
}
}
if (abilityid === 'flamebody') physicalBulk *= 1.1;
if (hasMove['calmmind'] || hasMove['quiverdance'] || hasMove['geomancy']) {
specialBulk *= 1.3;
moveCount['SpecialStall']++;
}
if (template.id === 'tyranitar') specialBulk *= 1.5;
if (hasMove['bellydrum']) {
physicalBulk *= 0.6;
specialBulk *= 0.6;
}
if (moveCount['Restoration']) {
physicalBulk *= 1.5;
specialBulk *= 1.5;
} else if (hasMove['painsplit'] && hasMove['substitute']) {
// SubSplit isn't generally a stall set
moveCount['Stall']--;
} else if (hasMove['painsplit'] || hasMove['rest']) {
physicalBulk *= 1.4;
specialBulk *= 1.4;
}
if ((hasMove['bodyslam'] || hasMove['thunder']) && abilityid === 'serenegrace' || hasMove['thunderwave']) {
physicalBulk *= 1.1;
specialBulk *= 1.1;
}
if ((hasMove['ironhead'] || hasMove['airslash']) && abilityid === 'serenegrace') {
physicalBulk *= 1.1;
specialBulk *= 1.1;
}
if (hasMove['gigadrain'] || hasMove['drainpunch'] || hasMove['hornleech']) {
physicalBulk *= 1.15;
specialBulk *= 1.15;
}
if (itemid === 'leftovers' || itemid === 'blacksludge') {
physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
}
if (hasMove['leechseed']) {
physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5);
}
if ((itemid === 'flameorb' || itemid === 'toxicorb') && abilityid !== 'magicguard') {
if (itemid === 'toxicorb' && abilityid === 'poisonheal') {
physicalBulk *= 1 + 0.1 * (2 + moveCount['Stall']);
specialBulk *= 1 + 0.1 * (2 + moveCount['Stall']);
} else {
physicalBulk *= 0.8;
specialBulk *= 0.8;
}
}
if (itemid === 'lifeorb') {
physicalBulk *= 0.7;
specialBulk *= 0.7;
}
if (abilityid === 'multiscale' || abilityid === 'magicguard' || abilityid === 'regenerator') {
physicalBulk *= 1.4;
specialBulk *= 1.4;
}
if (itemid === 'eviolite') {
physicalBulk *= 1.5;
specialBulk *= 1.5;
}
if (itemid === 'assaultvest') specialBulk *= 1.5;
var bulk = physicalBulk + specialBulk;
if (bulk < 46000 && stats.spe >= 70) isFast = true;
moveCount['bulk'] = bulk;
moveCount['physicalBulk'] = physicalBulk;
moveCount['specialBulk'] = specialBulk;
if (hasMove['agility'] || hasMove['dragondance'] || hasMove['quiverdance'] || hasMove['rockpolish'] || hasMove['shellsmash'] || hasMove['flamecharge']) {
isFast = true;
} else if (abilityid === 'unburden' || abilityid === 'speedboost' || abilityid === 'motordrive') {
isFast = true;
moveCount['Ultrafast'] = 1;
} else if (abilityid === 'chlorophyll' || abilityid === 'swiftswim' || abilityid === 'sandrush') {
isFast = true;
moveCount['Ultrafast'] = 2;
}
if (hasMove['agility'] || hasMove['shellsmash'] || hasMove['autotomize'] || hasMove['shiftgear'] || hasMove['rockpolish']) moveCount['Ultrafast'] = 2;
moveCount['Fast'] = isFast ? 1 : 0;
this.moveCount = moveCount;
this.hasMove = hasMove;
if (template.id === 'ditto') return abilityid === 'imposter' ? 'Physically Defensive' : 'Fast Bulky Support';
if (template.id === 'shedinja') return 'Fast Physical Sweeper';
if (itemid === 'choiceband' && moveCount['PhysicalAttack'] >= 2) {
if (!isFast) return 'Bulky Band';
return 'Fast Band';
} else if (itemid === 'choicespecs' && moveCount['SpecialAttack'] >= 2) {
if (!isFast) return 'Bulky Specs';
return 'Fast Specs';
} else if (itemid === 'choicescarf') {
if (moveCount['PhysicalAttack'] === 0) return 'Special Scarf';
if (moveCount['SpecialAttack'] === 0) return 'Physical Scarf';
if (moveCount['PhysicalAttack'] > moveCount['SpecialAttack']) return 'Physical Biased Mixed Scarf';
if (moveCount['PhysicalAttack'] < moveCount['SpecialAttack']) return 'Special Biased Mixed Scarf';
if (stats.atk < stats.spa) return 'Special Biased Mixed Scarf';
return 'Physical Biased Mixed Scarf';
}
if (template.id === 'unown') return 'Fast Special Sweeper';
if (moveCount['PhysicalStall'] && moveCount['Restoration']) {
return 'Specially Defensive';
}
if (moveCount['SpecialStall'] && moveCount['Restoration'] && itemid !== 'lifeorb') {
return 'Physically Defensive';
}
var offenseBias = '';
if (stats.spa > stats.atk && moveCount['Special'] > 1) offenseBias = 'Special';
else if (stats.spa > stats.atk && moveCount['Special'] > 1) offenseBias = 'Special';
else if (moveCount['Special'] > moveCount['Physical']) offenseBias = 'Special';
else offenseBias = 'Physical';
var offenseStat = stats[offenseBias === 'Special' ? 'spa' : 'atk'];
if (moveCount['Stall'] + moveCount['Support'] / 2 <= 2 && bulk < 135000 && moveCount[offenseBias] >= 1.5) {
if (isFast) {
if (bulk > 80000 && !moveCount['Ultrafast']) return 'Bulky ' + offenseBias + ' Sweeper';
return 'Fast ' + offenseBias + ' Sweeper';
} else {
if (moveCount[offenseBias] >= 3 || moveCount['Stall'] <= 0) {
return 'Bulky ' + offenseBias + ' Sweeper';
}
}
}
if (isFast && abilityid !== 'prankster') {
if (stats.spe > 100 || bulk < 55000 || moveCount['Ultrafast']) {
return 'Fast Bulky Support';
}
}
if (moveCount['SpecialStall']) return 'Physically Defensive';
if (moveCount['PhysicalStall']) return 'Specially Defensive';
if (template.id === 'blissey' || template.id === 'chansey') return 'Physically Defensive';
if (specialBulk >= physicalBulk) return 'Specially Defensive';
return 'Physically Defensive';
},
ensureMinEVs: function (evs, stat, min, evTotal) {
if (!evs[stat]) evs[stat] = 0;
var diff = min - evs[stat];
if (diff <= 0) return evTotal;
if (evTotal <= 504) {
var change = Math.min(508 - evTotal, diff);
evTotal += change;
evs[stat] += change;
diff -= change;
}
if (diff <= 0) return evTotal;
var evPriority = {def: 1, spd: 1, hp: 1, atk: 1, spa: 1, spe: 1};
for (var i in evPriority) {
if (i === stat) continue;
if (evs[i] && evs[i] > 128) {
evs[i] -= diff;
evs[stat] += diff;
return evTotal;
}
}
return evTotal; // can't do it :(
},
ensureMaxEVs: function (evs, stat, min, evTotal) {
if (!evs[stat]) evs[stat] = 0;
var diff = evs[stat] - min;
if (diff <= 0) return evTotal;
evs[stat] -= diff;
evTotal -= diff;
return evTotal; // can't do it :(
},
guessEVs: function (role) {
var set = this.curSet;
if (!set) return {};
var template = Tools.getTemplate(set.species || set.name);
var stats = template.baseStats;
var hasMove = this.hasMove;
var moveCount = this.moveCount;
var evs = {};
var plusStat = '';
var minusStat = '';
var statChart = {
'Bulky Band': ['atk', 'hp'],
'Fast Band': ['spe', 'atk'],
'Bulky Specs': ['spa', 'hp'],
'Fast Specs': ['spe', 'spa'],
'Physical Scarf': ['spe', 'atk'],
'Special Scarf': ['spe', 'spa'],
'Physical Biased Mixed Scarf': ['spe', 'atk'],
'Special Biased Mixed Scarf': ['spe', 'spa'],
'Fast Physical Sweeper': ['spe', 'atk'],
'Fast Special Sweeper': ['spe', 'spa'],
'Bulky Physical Sweeper': ['atk', 'hp'],
'Bulky Special Sweeper': ['spa', 'hp'],
'Fast Bulky Support': ['spe', 'hp'],
'Physically Defensive': ['def', 'hp'],
'Specially Defensive': ['spd', 'hp']
};
plusStat = statChart[role][0];
if (role === 'Fast Bulky Support') moveCount['Ultrafast'] = 0;
if (plusStat === 'spe' && (moveCount['Ultrafast'] || evs['spe'] < 252)) {
if (statChart[role][1] === 'atk' || statChart[role][1] == 'spa') {
plusStat = statChart[role][1];
} else if (moveCount['Physical'] >= 3) {
plusStat = 'atk';
} else if (stats.spd > stats.def) {
plusStat = 'spd';
} else {
plusStat = 'def';
}
}
if (this.curTeam && this.ignoreEVLimits) {
evs = {hp:252, atk:252, def:252, spa:252, spd:252, spe:252};
if (hasMove['gyroball'] || hasMove['trickroom']) delete evs.spe;
if (this.curTeam.gen === 1) delete evs.spd;
if (this.curTeam.gen < 3) return evs;
} else {
if (!statChart[role]) return {};
var evTotal = 0;
var i = statChart[role][0];
var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0);
var ev = 252;
while (stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4;
evs[i] = ev;
evTotal += ev;
var i = statChart[role][1];
if (i === 'hp' && set.level && set.level < 20) i = 'spd';
var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0);
var ev = 252;
if (i === 'hp' && (hasMove['substitute'] || hasMove['transform']) && stat == Math.floor(stat / 4) * 4) stat -= 1;
while (stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4;
if (ev < 0) ev = 0;
evs[i] = ev;
evTotal += ev;
if (set.item !== 'Leftovers' && set.item !== 'Black Sludge') {
var hpParity = 1; // 1 = should be odd, 0 = should be even
if ((hasMove['substitute'] || hasMove['bellydrum']) && (set.item || '').slice(-5) === 'Berry') {
hpParity = 0;
}
var hp = evs['hp'] || 0;
while (hp < 252 && evTotal < 508 && this.getStat('hp', null, hp, 1) % 2 !== hpParity) {
hp += 4;
evTotal += 4;
}
while (hp && this.getStat('hp', null, hp, 1) % 2 !== hpParity) {
hp -= 4;
evTotal -= 4;
}
while (hp && this.getStat('hp', null, hp - 4, 1) % 2 === hpParity) {
hp -= 4;
evTotal -= 4;
}
if (hp || evs['hp']) evs['hp'] = hp;
}
if (template.id === 'tentacruel') evTotal = this.ensureMinEVs(evs, 'spe', 16, evTotal);
if (template.id === 'skarmory') evTotal = this.ensureMinEVs(evs, 'spe', 24, evTotal);
if (template.id === 'jirachi') evTotal = this.ensureMinEVs(evs, 'spe', 32, evTotal);
if (template.id === 'celebi') evTotal = this.ensureMinEVs(evs, 'spe', 36, evTotal);
if (template.id === 'volcarona') evTotal = this.ensureMinEVs(evs, 'spe', 52, evTotal);
if (template.id === 'gliscor') evTotal = this.ensureMinEVs(evs, 'spe', 72, evTotal);
if (stats.spe == 97) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal);
if (template.id === 'dragonite' && evs['hp']) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal);
if (evTotal < 508) {
var remaining = 508 - evTotal;
if (remaining > 252) remaining = 252;
i = null;
if (!evs['atk'] && moveCount['PhysicalAttack'] >= 1) {
i = 'atk';
} else if (!evs['spa'] && moveCount['SpecialAttack'] >= 1) {
i = 'spa';
} else if (stats.hp == 1 && !evs['def']) {
i = 'def';
} else if (stats.def === stats.spd && !evs['spd']) {
i = 'spd';
} else if (!evs['spd']) {
i = 'spd';
} else if (!evs['def']) {
i = 'def';
}
if (i) {
ev = remaining;
stat = this.getStat(i, null, ev);
while (ev > 0 && stat === this.getStat(i, null, ev - 4)) ev -= 4;
if (ev) evs[i] = ev;
remaining -= ev;
}
if (remaining && !evs['spe']) {
ev = remaining;
stat = this.getStat('spe', null, ev);
while (ev > 0 && stat === this.getStat('spe', null, ev - 4)) ev -= 4;
if (ev) evs['spe'] = ev;
}
}
}
if (hasMove['gyroball'] || hasMove['trickroom']) {
minusStat = 'spe';
} else if (!moveCount['PhysicalAttack']) {
minusStat = 'atk';
} else if (moveCount['SpecialAttack'] < 1) {
minusStat = 'spa';
} else if (moveCount['PhysicalAttack'] < 1) {
minusStat = 'atk';
} else if (stats.def > stats.spd) {
minusStat = 'spd';
} else {
minusStat = 'def';
}
if (plusStat === minusStat) {
minusStat = (plusStat === 'spe' ? 'spd' : 'spe');
}
evs.plusStat = plusStat;
evs.minusStat = minusStat;
return evs;
},
// Stat calculator
getStat: function (stat, set, evOverride, natureOverride) {
if (!set) set = this.curSet;
if (!set) return 0;
if (!set.ivs) set.ivs = {
hp: 31,
atk: 31,
def: 31,
spa: 31,
spd: 31,
spe: 31
};
if (!set.evs) set.evs = {
hp: 0,
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0
};
// do this after setting set.evs because it's assumed to exist
// after getStat is run
var template = Tools.getTemplate(set.species);
if (!template.exists) return 0;
if (!set.level) set.level = 100;
if (typeof set.ivs[stat] === 'undefined') set.ivs[stat] = 31;
if (evOverride === 0) evOverride = 1;
if (stat === 'hp') {
if (template.baseStats['hp'] === 1) return 1;
return Math.floor(Math.floor(2 * template.baseStats['hp'] + (set.ivs['hp'] || 0) + Math.floor((evOverride || set.evs['hp'] || 0) / 4) + 100) * set.level / 100 + 10);
}
var val = Math.floor(Math.floor(2 * template.baseStats[stat] + (set.ivs[stat] || 0) + Math.floor((evOverride || set.evs[stat] || 0) / 4)) * set.level / 100 + 5);
if (natureOverride) {
val *= natureOverride;
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) {
val *= 1.1;
} else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) {
val *= 0.9;
}
return Math.floor(val);
},
// initialization
buildMovelists: function () {
if (Tools.movelists) return;
if (!window.BattlePokedex) return;
Tools.movelists = {};
Tools.g6movelists = {};
for (var pokemon in window.BattlePokedex) {
var template = Tools.getTemplate(pokemon);
var moves = {};
var g6moves = {};
var alreadyChecked = {};
do {
alreadyChecked[template.speciesid] = true;
if (template.learnset) {
for (var l in template.learnset) {
moves[l] = true;
if (template.learnset[l].length) g6moves[l] = true;
}
}
if (template.speciesid === 'shaymin') {
template = Tools.getTemplate('shayminsky');
} else if (toId(template.baseSpecies) !== toId(template.species) && toId(template.baseSpecies) !== 'pikachu' && toId(template.baseSpecies) !== 'wormadam' && toId(template.baseSpecies) !== 'kyurem') {
template = Tools.getTemplate(template.baseSpecies);
} else {
template = Tools.getTemplate(template.prevo);
}
} while (template && template.species && !alreadyChecked[template.speciesid]);
Tools.movelists[pokemon] = moves;
Tools.g6movelists[pokemon] = g6moves;
}
},
applyMovelist: function (g6only, speciesid) {
this.buildMovelists();
if (!Tools.movelists) {
this.movelist = false;
} else if (g6only) {
this.movelist = Tools.g6movelists[speciesid];
} else {
this.movelist = Tools.movelists[speciesid];
}
},
getGen: function (format) {
format = '' + format;
if (format.substr(0, 3) !== 'gen') return 6;
return parseInt(format.substr(3, 1), 10) || 6;
},
destroy: function () {
app.clearGlobalListeners();
Room.prototype.destroy.call(this);
}
});
var MovePopup = exports.MovePopup = Popup.extend({
initialize: function (data) {
var buf = '<ul class="popupmenu">';
this.i = data.i;
this.team = data.team;
for (var i = 0; i < data.team.length; i++) {
var set = data.team[i];
if (i !== data.i && i !== data.i + 1) {
buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>';
}
buf += '<li' + (i === data.i ? ' style="opacity:.3"' : ' style="opacity:.6"') + '><span class="pokemonicon" style="display:inline-block;vertical-align:middle;' + Tools.getIcon(set) + '"></span> ' + Tools.escapeHTML(set.name) + '</li>';
}
if (i !== data.i && i !== data.i + 1) {
buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>';
}
buf += '</ul>';
this.$el.html(buf);
},
moveHere: function (i) {
this.close();
i = +i;
var movedSet = this.team.splice(this.i, 1)[0];
if (i > this.i) i--;
this.team.splice(i, 0, movedSet);
app.rooms['teambuilder'].save();
if (app.rooms['teambuilder'].curSet) {
app.rooms['teambuilder'].curSetLoc = i;
app.rooms['teambuilder'].update();
app.rooms['teambuilder'].updateChart();
} else {
app.rooms['teambuilder'].update();
}
}
});
})(window, jQuery);
| Add a playable R-P-S game to Teambuilder greeting
| js/client-teambuilder.js | Add a playable R-P-S game to Teambuilder greeting | <ide><path>s/client-teambuilder.js
<ide> buf += '<p><button class="button" name="greeting" value="WR"><i class="fa fa-exclamation-triangle"></i> Wait, really?</button></p>';
<ide> } else if (answer === 'WR') {
<ide> buf += '<p>No, they were free. That just makes it easier to get my money\'s worth. Let\'s play rock paper scissors!</p>';
<del> buf += '<p><button class="button" name="greeting" value="RR"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-rock-o"></i> Paper</button> <button class="button" name="greeting" value="RS"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="RL"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-spock-o"></i> Spock</button></p>';
<add> buf += '<p><button class="button" name="greeting" value="RR"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="RS"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="RL"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="RK"><i class="fa fa-hand-spock-o"></i> Spock</button></p>';
<ide> } else if (answer[0] === 'R') {
<ide> buf += '<p>I play laser, I win. <i class="fa fa-hand-o-left"></i></p>';
<ide> buf += '<p><button class="button" name="greeting" value="YC"><i class="fa fa-thumbs-o-down"></i> You can\'t do that!</button></p>';
<add> } else if (answer === 'SP') {
<add> buf += '<p>Okay, sure. I warn you, I\'m using the same RNG that makes Stone Edge miss for you.</p>';
<add> buf += '<p><button class="button" name="greeting" value="SP3"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors</button> <button class="button" name="greeting" value="SP5"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors Lizard Spock</button></p>';
<add> } else if (answer === 'SP3') {
<add> buf += '<p><button class="button" name="greeting" value="PR3"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP3"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS3"><i class="fa fa-hand-scissors-o"></i> Scissors</button></p>';
<add> } else if (answer === 'SP5') {
<add> buf += '<p><button class="button" name="greeting" value="PR5"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP5"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS5"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="PL5"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="PK5"><i class="fa fa-hand-spock-o"></i> Spock</button></p>';
<add> } else if (answer[0] === 'P') {
<add> var rpsChart = {
<add> R: 'rock',
<add> P: 'paper',
<add> S: 'scissors',
<add> L: 'lizard',
<add> K: 'spock'
<add> };
<add> var rpsWinChart = {
<add> SP: 'cuts',
<add> SL: 'decapitates',
<add> PR: 'covers',
<add> PK: 'disproves',
<add> RL: 'crushes',
<add> RS: 'crushes',
<add> LK: 'poisons',
<add> LP: 'eats',
<add> KS: 'smashes',
<add> KR: 'vaporizes'
<add> };
<add> var my = ['R', 'P', 'S', 'L', 'K'][Math.floor(Math.random() * Number(answer[2]))];
<add> var your = answer[1];
<add> buf += '<p>I play <i class="fa fa-hand-' + rpsChart[my] + '-o"></i> ' + rpsChart[my] + '!</p>';
<add> if ((my + your) in rpsWinChart) {
<add> buf += '<p>And ' + rpsChart[my] + ' ' + rpsWinChart[my + your] + ' ' + rpsChart[your] + ', so I win!</p>';
<add> } else if ((your + my) in rpsWinChart) {
<add> buf += '<p>But ' + rpsChart[your] + ' ' + rpsWinChart[your + my] + ' ' + rpsChart[my] + ', so you win...</p>';
<add> } else {
<add> buf += '<p>We played the same thing, so it\'s a tie.</p>';
<add> }
<add> buf += '<p>Score: ' + ['pi', '$3.50', '9.80665 m/s<sup>2</sup>', '28°C', '百万点', '<i class="fa fa-bitcoin"></i>0.0000174', '<s>priceless</s> <i class="fa fa-cc-mastercard"></i> MasterCard', '127.0.0.1', 'C−, see me after class'][Math.floor(Math.random() * 9)];
<add> buf += '<p><button class="button" name="greeting" value="SP' + answer[2] + '"><i class="fa fa-caret-square-o-right"></i> I demand a rematch!</button></p>';
<ide> } else if (answer === 'YC') {
<ide> buf += '<p>Okay, then I play peace sign <i class="fa fa-hand-peace-o"></i>, everyone signs a peace treaty, ending the war and ushering in a new era of prosperity.</p>';
<add> buf += '<p><button class="button" name="greeting" value="SP"><i class="fa fa-caret-square-o-right"></i> I wanted to play for real...</button></p>';
<ide> }
<ide> $(button).parent().replaceWith(buf);
<ide> }, |
|
Java | apache-2.0 | 2429ace84a6da8137122e7c323f4c5c8112d4d78 | 0 | apache/xml-graphics-commons,apache/xml-graphics-commons,apache/xml-graphics-commons | /*
* 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.
*/
/* $Id$ */
package org.apache.xmlgraphics.util.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URL;
import org.junit.Test;
import static org.junit.Assert.fail;
import org.apache.commons.io.IOUtils;
/**
* This test validates that the Base64 encoder/decoders work properly.
*
* @version $Id$
*/
public class Base64TestCase {
private void innerBase64Test(String action, URL in, URL ref) throws Exception {
InputStream inIS = dos2Unix(in);
if (action.equals("ROUND")) {
ref = in;
} else if (!action.equals("ENCODE") && !action.equals("DECODE")) {
fail("Bad action string");
}
InputStream refIS = dos2Unix(ref);
if (action.equals("ENCODE") || action.equals("ROUND")) {
// We need to encode the incomming data
PipedOutputStream pos = new PipedOutputStream();
OutputStream os = new Base64EncodeStream(pos);
// Copy the input to the Base64 Encoder (in a seperate thread).
Thread t = new StreamCopier(inIS, os);
// Read that from the piped output stream.
inIS = new PipedInputStream(pos);
t.start();
}
if (action.equals("DECODE") || action.equals("ROUND")) {
inIS = new Base64DecodeStream(inIS);
}
int mismatch = compareStreams(inIS, refIS, action.equals("ENCODE"));
if (mismatch != -1) {
fail("Wrong result");
}
}
private InputStream dos2Unix(URL url) throws IOException {
InputStream is = url.openStream();
byte[] data = IOUtils.toByteArray(is);
if (data.length > 1 && data[data.length - 1] == '\n') {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (byte b : data) {
if (b != '\r') {
bos.write(b);
}
}
return new ByteArrayInputStream(bos.toByteArray());
}
return new ByteArrayInputStream(data);
}
private void innerBase64Test(String action, String in, String ref) throws Exception {
final String baseURL = "file:src/test/resources/org/apache/xmlgraphics/util/io/";
innerBase64Test(action, new URL(baseURL + in), new URL(baseURL + ref));
}
private void innerBase64Test(String in) throws Exception {
innerBase64Test("ROUND", in, in);
}
private void testBase64Group(String name) throws Exception {
innerBase64Test("ENCODE", name, name + ".64");
innerBase64Test("DECODE", name + ".64", name);
innerBase64Test(name);
}
/**
* This method will only throw exceptions if some aspect
* of the test's internal operation fails.
*/
@Test
public void testBase64() throws Exception {
System.out.println(new File(".").getCanonicalPath());
testBase64Group("zeroByte");
testBase64Group("oneByte");
testBase64Group("twoByte");
testBase64Group("threeByte");
testBase64Group("fourByte");
testBase64Group("tenByte");
testBase64Group("small");
testBase64Group("medium");
innerBase64Test("DECODE", "medium.pc.64", "medium");
innerBase64Test("large");
}
/**
* Returns true if the contents of <tt>is1</tt> match the
* contents of <tt>is2</tt>
*/
public static int compareStreams(InputStream is1, InputStream is2,
boolean skipws) {
byte[] data1 = new byte[100];
byte[] data2 = new byte[100];
int off1 = 0;
int off2 = 0;
int idx = 0;
try {
while (true) {
int len1 = is1.read(data1, off1, data1.length - off1);
int len2 = is2.read(data2, off2, data2.length - off2);
if (off1 != 0) {
if (len1 == -1) {
len1 = off1;
} else {
len1 += off1;
}
}
if (off2 != 0) {
if (len2 == -1) {
len2 = off2;
} else {
len2 += off2;
}
}
if (len1 == -1) {
if (len2 == -1) {
break; // Both done...
}
// Only is1 is done...
if (!skipws) {
return idx;
}
// check if the rest of is2 is whitespace...
for (int i2 = 0; i2 < len2; i2++) {
if ((data2[i2] != '\n') && (data2[i2] != '\r') && (data2[i2] != ' ')) {
return idx + i2;
}
}
off1 = off2 = 0;
continue;
}
if (len2 == -1) {
// Only is2 is done...
if (!skipws) {
return idx;
}
// Check if rest of is1 is whitespace...
for (int i1 = 0; i1 < len1; i1++) {
if ((data1[i1] != '\n') && (data1[i1] != '\r') && (data1[i1] != ' ')) {
return idx + i1;
}
}
off1 = off2 = 0;
continue;
}
int i1 = 0;
int i2 = 0;
while ((i1 < len1) && (i2 < len2)) {
if (skipws) {
if ((data1[i1] == '\n') || (data1[i1] == '\r') || (data1[i1] == ' ')) {
i1++;
continue;
}
if ((data2[i2] == '\n') || (data2[i2] == '\r') || (data2[i2] == ' ')) {
i2++;
continue;
}
}
if (data1[i1] != data2[i2]) {
return idx + i2;
}
i1++;
i2++;
}
if (i1 != len1) {
System.arraycopy(data1, i1, data1, 0, len1 - i1);
}
if (i2 != len2) {
System.arraycopy(data2, i2, data2, 0, len2 - i2);
}
off1 = len1 - i1;
off2 = len2 - i2;
idx += i2;
}
} catch (IOException ioe) {
ioe.printStackTrace();
return idx;
}
return -1;
}
static class StreamCopier extends Thread {
InputStream src;
OutputStream dst;
public StreamCopier(InputStream src,
OutputStream dst) {
this.src = src;
this.dst = dst;
}
public void run() {
try {
byte[] data = new byte[1000];
while (true) {
int len = src.read(data, 0, data.length);
if (len == -1) {
break;
}
dst.write(data, 0, len);
}
} catch (IOException ioe) {
// Nothing
}
try {
dst.close();
} catch (IOException ioe) {
// Nothing
}
}
}
}
| src/test/java/org/apache/xmlgraphics/util/io/Base64TestCase.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.
*/
/* $Id$ */
package org.apache.xmlgraphics.util.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URL;
import org.junit.Test;
import static org.junit.Assert.fail;
/**
* This test validates that the Base64 encoder/decoders work properly.
*
* @version $Id$
*/
public class Base64TestCase {
private void innerBase64Test(String action, URL in, URL ref) throws Exception {
InputStream inIS = in.openStream();
if (action.equals("ROUND")) {
ref = in;
} else if (!action.equals("ENCODE") && !action.equals("DECODE")) {
fail("Bad action string");
}
InputStream refIS = ref.openStream();
if (action.equals("ENCODE") || action.equals("ROUND")) {
// We need to encode the incomming data
PipedOutputStream pos = new PipedOutputStream();
OutputStream os = new Base64EncodeStream(pos);
// Copy the input to the Base64 Encoder (in a seperate thread).
Thread t = new StreamCopier(inIS, os);
// Read that from the piped output stream.
inIS = new PipedInputStream(pos);
t.start();
}
if (action.equals("DECODE") || action.equals("ROUND")) {
inIS = new Base64DecodeStream(inIS);
}
int mismatch = compareStreams(inIS, refIS, action.equals("ENCODE"));
if (mismatch != -1) {
fail("Wrong result");
}
}
private void innerBase64Test(String action, String in, String ref) throws Exception {
final String baseURL = "file:src/test/resources/org/apache/xmlgraphics/util/io/";
innerBase64Test(action, new URL(baseURL + in), new URL(baseURL + ref));
}
private void innerBase64Test(String in) throws Exception {
innerBase64Test("ROUND", in, in);
}
private void testBase64Group(String name) throws Exception {
innerBase64Test("ENCODE", name, name + ".64");
innerBase64Test("DECODE", name + ".64", name);
innerBase64Test(name);
}
/**
* This method will only throw exceptions if some aspect
* of the test's internal operation fails.
*/
@Test
public void testBase64() throws Exception {
System.out.println(new File(".").getCanonicalPath());
testBase64Group("zeroByte");
testBase64Group("oneByte");
testBase64Group("twoByte");
testBase64Group("threeByte");
testBase64Group("fourByte");
testBase64Group("tenByte");
testBase64Group("small");
testBase64Group("medium");
innerBase64Test("DECODE", "medium.pc.64", "medium");
innerBase64Test("large");
}
/**
* Returns true if the contents of <tt>is1</tt> match the
* contents of <tt>is2</tt>
*/
public static int compareStreams(InputStream is1, InputStream is2,
boolean skipws) {
byte[] data1 = new byte[100];
byte[] data2 = new byte[100];
int off1 = 0;
int off2 = 0;
int idx = 0;
try {
while (true) {
int len1 = is1.read(data1, off1, data1.length - off1);
int len2 = is2.read(data2, off2, data2.length - off2);
if (off1 != 0) {
if (len1 == -1) {
len1 = off1;
} else {
len1 += off1;
}
}
if (off2 != 0) {
if (len2 == -1) {
len2 = off2;
} else {
len2 += off2;
}
}
if (len1 == -1) {
if (len2 == -1) {
break; // Both done...
}
// Only is1 is done...
if (!skipws) {
return idx;
}
// check if the rest of is2 is whitespace...
for (int i2 = 0; i2 < len2; i2++) {
if ((data2[i2] != '\n') && (data2[i2] != '\r') && (data2[i2] != ' ')) {
return idx + i2;
}
}
off1 = off2 = 0;
continue;
}
if (len2 == -1) {
// Only is2 is done...
if (!skipws) {
return idx;
}
// Check if rest of is1 is whitespace...
for (int i1 = 0; i1 < len1; i1++) {
if ((data1[i1] != '\n') && (data1[i1] != '\r') && (data1[i1] != ' ')) {
return idx + i1;
}
}
off1 = off2 = 0;
continue;
}
int i1 = 0;
int i2 = 0;
while ((i1 < len1) && (i2 < len2)) {
if (skipws) {
if ((data1[i1] == '\n') || (data1[i1] == '\r') || (data1[i1] == ' ')) {
i1++;
continue;
}
if ((data2[i2] == '\n') || (data2[i2] == '\r') || (data2[i2] == ' ')) {
i2++;
continue;
}
}
if (data1[i1] != data2[i2]) {
return idx + i2;
}
i1++;
i2++;
}
if (i1 != len1) {
System.arraycopy(data1, i1, data1, 0, len1 - i1);
}
if (i2 != len2) {
System.arraycopy(data2, i2, data2, 0, len2 - i2);
}
off1 = len1 - i1;
off2 = len2 - i2;
idx += i2;
}
} catch (IOException ioe) {
ioe.printStackTrace();
return idx;
}
return -1;
}
static class StreamCopier extends Thread {
InputStream src;
OutputStream dst;
public StreamCopier(InputStream src,
OutputStream dst) {
this.src = src;
this.dst = dst;
}
public void run() {
try {
byte[] data = new byte[1000];
while (true) {
int len = src.read(data, 0, data.length);
if (len == -1) {
break;
}
dst.write(data, 0, len);
}
} catch (IOException ioe) {
// Nothing
}
try {
dst.close();
} catch (IOException ioe) {
// Nothing
}
}
}
}
| Fix test on Windows
git-svn-id: c1447309447e562cc43d70ade9fe6c70ff9b4cec@1876186 13f79535-47bb-0310-9956-ffa450edef68
| src/test/java/org/apache/xmlgraphics/util/io/Base64TestCase.java | Fix test on Windows | <ide><path>rc/test/java/org/apache/xmlgraphics/util/io/Base64TestCase.java
<ide>
<ide> package org.apache.xmlgraphics.util.io;
<ide>
<add>import java.io.ByteArrayInputStream;
<add>import java.io.ByteArrayOutputStream;
<ide> import java.io.File;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide>
<ide> import static org.junit.Assert.fail;
<ide>
<add>import org.apache.commons.io.IOUtils;
<add>
<ide> /**
<ide> * This test validates that the Base64 encoder/decoders work properly.
<ide> *
<ide> public class Base64TestCase {
<ide>
<ide> private void innerBase64Test(String action, URL in, URL ref) throws Exception {
<del> InputStream inIS = in.openStream();
<add> InputStream inIS = dos2Unix(in);
<ide>
<ide> if (action.equals("ROUND")) {
<ide> ref = in;
<ide> fail("Bad action string");
<ide> }
<ide>
<del> InputStream refIS = ref.openStream();
<add> InputStream refIS = dos2Unix(ref);
<ide>
<ide> if (action.equals("ENCODE") || action.equals("ROUND")) {
<ide> // We need to encode the incomming data
<ide> if (mismatch != -1) {
<ide> fail("Wrong result");
<ide> }
<add> }
<add>
<add> private InputStream dos2Unix(URL url) throws IOException {
<add> InputStream is = url.openStream();
<add> byte[] data = IOUtils.toByteArray(is);
<add> if (data.length > 1 && data[data.length - 1] == '\n') {
<add> ByteArrayOutputStream bos = new ByteArrayOutputStream();
<add> for (byte b : data) {
<add> if (b != '\r') {
<add> bos.write(b);
<add> }
<add> }
<add> return new ByteArrayInputStream(bos.toByteArray());
<add> }
<add> return new ByteArrayInputStream(data);
<ide> }
<ide>
<ide> private void innerBase64Test(String action, String in, String ref) throws Exception { |
|
Java | apache-2.0 | 436037cc6a731d5ff9b524c2ea61eaddd50fb7c5 | 0 | jruesga/cm-cloud-generator,jruesga/cm-cloud-generator | import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import wordcloud.CollisionMode;
import wordcloud.WordCloud;
import wordcloud.WordFrequency;
import wordcloud.bg.PixelBoundryBackground;
import wordcloud.font.CloudFont;
import wordcloud.font.scale.FontScalar;
import wordcloud.font.scale.SqrtFontScalar;
import wordcloud.palette.ColorPalette;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CloudGenerator {
private static final Logger LOGGER = Logger.getLogger(CloudGenerator.class);
private static final String ROOT_DIR = "./";
private static final String DB_NAME = ROOT_DIR + "db/cloud.db";
private static final String ACCOUNTS_DIR = ROOT_DIR + "db/accounts";
private static final String CHANGES_DIR = ROOT_DIR + "db/changes";
private static final String STATS_DIR = ROOT_DIR + "db/stats/";
private static final String WELL_KNOWN_ACCOUNTS = ROOT_DIR + "resources/well-known-accounts.txt";
private static final String ALL_STATS_FILENAME = "all_stats.dat";
private static final String TRANSLATIONS_STATS_FILENAME = "translations_stats.dat";
private static final String CLOUD_DATA = ROOT_DIR + "db/cloud.data";
private static final String CLOUD_IMAGE = ROOT_DIR + "out/cloud.png";
private static final String CLOUD_SVG = ROOT_DIR + "out/cloud.svg";
private static final String CLOUD_DB_FILE = ROOT_DIR + "out/cloud.db";
private static final String CLOUD_DATA_OUTPUT = ROOT_DIR + "out/cloud.data";
private static final String CLOUD_DIST_FILE = ROOT_DIR + "out/cloud.zip";
private static final String CLOUD_BG_SVG = ROOT_DIR + "resources/cid_head.svg";
private static final String CLOUD_BG_PNG = ROOT_DIR + "resources/cid_head.png";
private static final String CLOUD_FONT = ROOT_DIR + "resources/Roboto-Bold.ttf";
private static final String LAST_CLOUD_SIZE = ROOT_DIR + "db/last_cloud_size.txt";
private static final int DEFAULT_CLOUD_SIZE = 1920;
private static final int DEFAULT_CLOUD_INCREMENT = 4;
private static int wellKnownAccounts;
private static class Account {
public int id;
public int accountId = -1;
public List<String> usernames = new ArrayList<>();
public List<String> names = new ArrayList<>();
public List<String> emails = new ArrayList<>();
}
public static void main(String[] args) throws Exception {
boolean FROM_GERRIT = true;
boolean closed = false;
new File(DB_NAME).delete();
new File(CLOUD_DB_FILE).delete();
Connection conn = createDb();
Connection connMetadata = createMetadataDb();
conn.setAutoCommit(false);
connMetadata.setAutoCommit(false);
try {
LOGGER.info("Collecting data");
processAccounts(conn);
processStats(conn); // Still use the github data to map emails
if (FROM_GERRIT) {
fetchAllGerritCommits();
processAllGerritCommits(conn);
}
create_indexes(conn);
extractEmailsFromCommitNames(conn);
if (FROM_GERRIT) {
generateCloudDataFromGerrit(conn);
writeGerritCloudData(conn);
} else {
computeCommitsPerProject(conn);
generateCloudDataFromGithub(conn);
filterDataByUserWithCommits(conn);
}
LOGGER.info("Generating cloud");
generateCloud(connMetadata);
generateMetadata(conn, connMetadata);
// Close the database prior to compress it
connMetadata.commit();
connMetadata.close();
generateCloudZip();
} finally {
conn.commit();
conn.close();
if (!connMetadata.isClosed()) {
connMetadata.commit();
connMetadata.close();
}
}
}
private static Connection createDb() throws Exception {
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + DB_NAME);
Statement st = conn.createStatement();
st.execute("PRAGMA synchronous = OFF;");
st.execute("PRAGMA journal_mode = MEMORY;");
st.execute("drop table if exists accounts;");
st.execute("drop table if exists gerrit_accounts;");
st.execute("drop table if exists usernames;");
st.execute("drop table if exists names;");
st.execute("drop table if exists emails;");
st.execute("drop table if exists all_commits;");
st.execute("drop table if exists translations_commits;");
st.execute("drop table if exists stats;");
st.execute("drop table if exists raw_cloud_data;");
st.execute("drop table if exists all_accounts_with_commits;");
st.execute("drop table if exists cloud_data;");
st.execute("drop table if exists gerrit_commits;");
st.execute("create table accounts (id NUMBER, accountId NUMBER, username TEXT, name TEXT, email TEXT);");
st.execute("create table gerrit_accounts (accountId NUMBER, username TEXT, name TEXT, email TEXT);");
st.execute("create table usernames (id NUMBER, username TEXT);");
st.execute("create table names (id NUMBER, name TEXT);");
st.execute("create table emails (id NUMBER, email TEXT);");
st.execute("create table all_commits (project TEXT, commits NUMBER, name TEXT, email TEXT);");
st.execute("create table translations_commits (project TEXT, commits NUMBER, name TEXT, email TEXT);");
st.execute("create table stats (project TEXT, id NUMBER, commits NUMBER);");
st.execute("create table raw_cloud_data (commits NUMBER, id NUMBER, name TEXT, username TEXT, filter TEXT);");
st.execute("create table all_accounts_with_commits (accountId NUMBER);");
st.execute("create table cloud_data (commits NUMBER, id NUMBER, name TEXT, username TEXT, filter TEXT);");
st.execute("create table gerrit_commits (id NUMBER, changeId TEXT, project TEXT, branch TEXT, subject TEXT, author_name TEXT, author_email TEXT, owner_name, owner_email);");
st.close();
return conn;
}
private static Connection createMetadataDb() throws Exception {
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + CLOUD_DB_FILE);
Statement st = conn.createStatement();
st.execute("PRAGMA synchronous = OFF;");
st.execute("PRAGMA journal_mode = MEMORY;");
st.execute("drop table if exists android_metadata;");
st.execute("drop table if exists metadata;");
st.execute("drop table if exists info;");
st.execute("create table android_metadata (locale TEXT);");
st.execute("insert into android_metadata (locale) values ('us_US')");
st.execute("create table metadata (id NUMBER, name TEXT, username TEXT, filter TEXT, commits NUMBER, x NUMBER, y NUMBER, w NUMBER, h NUMBER, r NUMBER, fs REAL);");
st.execute("create index metadata_idx_1 on metadata (name);");
st.execute("create index metadata_idx_2 on metadata (filter);");
st.execute("create index metadata_idx_3 on metadata (x, y, w, h);");
st.execute("create index metadata_idx_4 on metadata (commits);");
st.execute("create table info (key TEXT, value TEXT);");
st.close();
return conn;
}
private static void create_indexes(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("create index accounts_idx_1 on accounts (id);");
st.execute("create index usernames_idx_1 on usernames (username);");
st.execute("create index names_idx_1 on names (name);");
st.execute("create index emails_idx_1 on emails (email);");
st.execute("create index all_commits_idx_1 on all_commits (name);");
st.execute("create index all_commits_idx_2 on all_commits (email);");
st.execute("create index translations_commits_idx_1 on translations_commits (name);");
st.execute("create index translations_commits_idx_2 on translations_commits (email);");
st.execute("create index gerrit_commits_idx_1 on gerrit_commits (author_email);");
st.execute("create index gerrit_commits_idx_2 on gerrit_commits (owner_email);");
st.execute("create index gerrit_commits_idx_3 on gerrit_commits (changeId);");
st.close();
}
private static void extractEmailsFromCommitNames(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("drop table if exists temp_emails;");
st.execute("create table temp_emails (id NUMBER, email TEXT);");
st.execute("insert into temp_emails (id, email) select id, email from emails");
st.execute("insert into temp_emails (id, email) select distinct b.id, a.email from names b, " +
"all_commits a where a.name = b.name and a.name is not null and a.email is " +
"not null and instr(a.name ,'?') = 0 and length(a.name) > 9 " +
"and (select count(*) from names z where z.name = a.name) = 1;");
st.execute("insert into temp_emails (id, email) select distinct b.id, a.email from names b, " +
"translations_commits a where a.name = b.name and a.name is not null and a.email is " +
"not null and instr(a.name ,'?') = 0 and length(a.name) > 9 " +
"and (select count(*) from names z where z.name = a.name) = 1;");
st.execute("delete from emails");
st.execute("insert into emails (id, email) select distinct id, email from temp_emails");
st.execute("drop table if exists temp_emails;");
st.close();
}
private static void computeCommitsPerProject(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("insert into stats (project, id, commits) " +
"select z.project, acc.id, z.commits " +
"from " +
"( " +
"select project, id, sum(commits) commits " +
"from " +
"( " +
"select a.project, b.id, a.commits from all_commits a, emails b " +
"where a.email = b.email " +
"union " +
"select a.project, b.id, a.commits * -1 from translations_commits a, emails b " +
"where a.email = b.email " +
") " +
"group by project, id " +
") z, accounts acc " +
"where z.id = acc.id " +
"and z.commits > 0;");
st.close();
}
private static void generateCloudDataFromGithub(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("insert into raw_cloud_data (commits, id, name, username, filter) " +
"select sum(stats.commits) commits, accounts.id, accounts.name, accounts.username, a.filter " +
"from stats, accounts, " +
"( " +
"select id, group_concat(filter,'|') filter from " +
"( " +
"select id, group_concat(username,'|') filter from usernames " +
"group by id " +
"union " +
"select id, group_concat(name,'|') filter from names " +
"group by id " +
") " +
"group by id " +
") a " +
"where stats.id = accounts.id " +
"and accounts.id = a.id " +
"group by accounts.id, accounts.name, accounts.username, a.filter " +
"order by 1 desc;");
st.close();
}
private static void generateCloudDataFromGerrit(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("insert into cloud_data (commits, id, name, username, filter) " +
"select count(*) commits, a.id, a.name, a.username, f.filter from ( " +
"select (select e.id from emails e where e.email = c.author_email) id, changeId from gerrit_commits c " +
"where c.subject <> 'Automatic translation import' " +
") c, accounts a, " +
"( " +
"select id, group_concat(filter,'|') filter from " +
"( " +
"select id, group_concat(username,'|') filter from usernames " +
"group by id " +
"union " +
"select id, group_concat(name,'|') filter from names " +
"group by id " +
") " +
"group by id " +
") f " +
"where c.id = a.id " +
"and a.id = f.id " +
"group by a.id " +
"order by commits desc");
st.close();
}
@SuppressWarnings("unchecked")
private static void filterDataByUserWithCommits(Connection conn) throws Exception {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select accounts.id, accounts.accountId, accounts.name, group_concat(emails.email,'|') emails " +
"from raw_cloud_data, accounts, emails " +
"where raw_cloud_data.id = accounts.id and accounts.id = emails.id " +
"group by accounts.id, accounts.name " +
"order by raw_cloud_data.commits desc;");
while(rs.next()) {
int id = rs.getInt(1);
int accountId = rs.getInt(2);
String name = rs.getString(3);
String[] emails = rs.getString(4).split("\\|");
boolean hasCommits = false;
for (String email : emails) {
if (userHasCommits(id, accountId, name, email)) {
new File(ACCOUNTS_DIR, accountId + ".hasCommits").createNewFile();
if (new File(ACCOUNTS_DIR, accountId + ".noHasCommits").exists()) {
new File(ACCOUNTS_DIR, accountId + ".noHasCommits").delete();
}
hasCommits = true;
break;
}
}
File noHasCommits = new File(ACCOUNTS_DIR, accountId + ".noHasCommits");
if (!hasCommits && (!noHasCommits.exists() || (System.currentTimeMillis() - noHasCommits.lastModified()) > 2592000000L)) { // 30 days
noHasCommits.createNewFile();
}
}
rs.close();
File accounts = new File(ACCOUNTS_DIR);
Collection<File> allAccountsWithCommits = FileUtils.listFiles(accounts, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".hasCommits");
}
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".hasCommits");
}
}, TrueFileFilter.INSTANCE);
PreparedStatement ps1 = conn.prepareStatement("insert into all_accounts_with_commits (accountId) values (?);");
for (File acc : allAccountsWithCommits) {
int accountId = Integer.parseInt(acc.getName().substring(0, acc.getName().lastIndexOf(".")));
ps1.setInt(1, accountId);
ps1.execute();
}
ps1.close();
st.execute("insert into cloud_data (commits, id, name, username, filter) " +
"select sum(r.commits), r.id, r.name, r.username, r.filter from raw_cloud_data r, accounts a "+
"where r.id = a.id and a.accountId in (select accountId from all_accounts_with_commits) " +
"group by r.name");
FileWriter fw = new FileWriter(CLOUD_DATA);
rs = st.executeQuery("select id, commits, name, filter from cloud_data order by 1;");
while (rs.next()) {
String id = rs.getString(1);
String commits = rs.getString(2);
String name = cleanup(rs.getString(3));
String filter = cleanup(rs.getString(4));
fw.write(String.format("%s,%s,%s|%s", id, commits, name, filter) + "\r\n");
}
fw.close();
rs.close();
st.close();
}
private static void fetchAllGerritCommits() throws Exception {
final StringBuffer start = new StringBuffer("2010-10-28");
File statsDir = new File(CHANGES_DIR);
statsDir.mkdirs();
FileUtils.listFiles(statsDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.compareTo(start.toString()) > 0) {
start.setLength(0);
start.append(name);
}
return true;
}
@Override
public boolean accept(File file) {
String name = file.getName();
if (name.compareTo(start.toString()) > 0) {
start.setLength(0);
start.append(name);
}
return true;
}
}, TrueFileFilter.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(start.toString()));
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DAY_OF_YEAR, -30);
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
while (c.compareTo(now) <= 0) {
fetchGerritCommits(c.getTime());
c.add(Calendar.DAY_OF_YEAR, 1);
}
}
private static void fetchGerritCommits(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
String end = sdf.format(c.getTime());
c.add(Calendar.DAY_OF_YEAR, 1);
String start = sdf.format(c.getTime());
LOGGER.info("Fetching gerrit changes: " + end);
File dir = new File(CHANGES_DIR, end);
dir.mkdirs();
int i = 1;
int s = 0;
final int count = 250;
while (true) {
try {
String url = "http://review.cyanogenmod.org/changes/?q=status:merged+before:\"" + start + "\"+after:\"" + end + "\"&n=" + count + "&O=a&o=DETAILED_ACCOUNTS";
if (s > 0) {
url += "&S="+s;
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new URL(url).openStream(), "UTF-8"));
FileWriter fw = new FileWriter(new File(dir, String.valueOf(i)));
reader.readLine();
int read = -1;
char[] data = new char[10240];
StringBuffer sb = new StringBuffer();
while ((read = reader.read(data, 0, 10240)) != -1) {
sb.append(data, 0, read);
fw.write(data, 0, read);
}
reader.close();
fw.close();
if (sb.indexOf("\"_more_changes\": true") == -1) {
break;
}
i++;
s+=count;
} catch (Exception ex) {
LOGGER.error("Error downloading gerrit changes " + end + "-" + start, ex);
break;
}
}
}
@SuppressWarnings("unchecked")
private static void processAllGerritCommits(Connection conn) throws Exception {
File changesDir = new File(CHANGES_DIR);
Collection<File> changes = FileUtils.listFiles(changesDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return true;
}
@Override
public boolean accept(File file) {
return true;
}
}, TrueFileFilter.INSTANCE);
PreparedStatement ps1 = conn.prepareStatement("insert into gerrit_commits (id, changeId, project, branch, subject, author_name, author_email, owner_name, owner_email) values (?,?,?,?,?,?,?,?,?);");
for (File change : changes) {
if (!change.isFile()) continue;
String json = readJson(change, false);
if (json.trim().length() == 0) continue;
try {
JSONArray a = new JSONArray(json);
int count = a.length();
for (int i = 0; i < count; i++) {
JSONObject o = a.getJSONObject(i);
int id = o.optInt("_number", i);
String changeId = o.optString("change_id");
String project = o.optString("project");
String branch = o.optString("branch");
String subject = o.optString("subject");
String curRev = o.optString("current_revision");
String author_name = null;
String author_email = null;
try {
JSONObject author = o.optJSONObject("revisions").getJSONObject(curRev).getJSONObject("commit").getJSONObject("author");
author_name = cleanup(author.optString("name"));
author_email = cleanup(author.optString("email"));
} catch (Exception ex) {
try {
JSONObject owner = o.optJSONObject("owner");
author_name = cleanup(owner.optString("name"));
author_email = cleanup(owner.optString("email"));
} catch (Exception ex2) {
System.out.println("Fail to read current revision data. change: " + change + "; changeId: " + changeId);
}
}
JSONObject owner = o.optJSONObject("owner");
String owner_name = cleanup(owner.optString("name"));
String owner_email = cleanup(owner.optString("email"));
ps1.setInt(1, id);
if (!isEmpty(changeId)) {
ps1.setString(2, changeId);
} else {
ps1.setNull(2, Types.VARCHAR);
}
if (!isEmpty(project)) {
ps1.setString(3, project);
} else {
ps1.setNull(3, Types.VARCHAR);
}
if (!isEmpty(branch)) {
ps1.setString(4, branch);
} else {
ps1.setNull(4, Types.VARCHAR);
}
if (!isEmpty(subject)) {
ps1.setString(5, subject);
} else {
ps1.setNull(5, Types.VARCHAR);
}
if (!isEmpty(author_name)) {
ps1.setString(6, author_name);
} else {
ps1.setNull(6, Types.VARCHAR);
}
if (!isEmpty(author_email)) {
ps1.setString(7, author_email);
} else {
ps1.setNull(7, Types.VARCHAR);
}
if (!isEmpty(owner_name)) {
ps1.setString(8, owner_name);
} else {
ps1.setNull(8, Types.VARCHAR);
}
if (!isEmpty(owner_email)) {
ps1.setString(9, owner_email);
} else {
ps1.setNull(9, Types.VARCHAR);
}
ps1.execute();
}
} catch (Exception ex) {
System.out.println("Unable to parse changes in " + change);
System.out.println(json);
throw ex;
}
}
ps1.close();
}
private static void writeGerritCloudData(Connection conn) throws Exception {
FileWriter fw = new FileWriter(CLOUD_DATA);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select id, commits, name, filter from cloud_data order by 1;");
while (rs.next()) {
String id = rs.getString(1);
String commits = rs.getString(2);
String name = cleanup(rs.getString(3));
String filter = cleanup(rs.getString(4));
fw.write(String.format("%s,%s,%s|%s", id, commits, name, filter) + "\r\n");
}
fw.close();
rs.close();
st.close();
}
private static void generateMetadata(Connection conn, Connection connMetadata) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(new File(CLOUD_DATA_OUTPUT)));
PreparedStatement ps1 = conn.prepareStatement("select name, username, filter, commits from cloud_data where id = ?;");
PreparedStatement ps2 = connMetadata.prepareStatement("insert into metadata (id, name, username, filter, commits, x, y, w, h, r, fs) values (?,?,?,?,?,?,?,?,?,?,?);");
String line = br.readLine();
int fillId = -1000;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
int x = Integer.parseInt(data[1]);
int y = Integer.parseInt(data[2]);
int w = Integer.parseInt(data[3]);
int h = Integer.parseInt(data[4]);
int r = Integer.parseInt(data[5]);
float fs = Float.parseFloat(data[6]);
if (id != -1) {
ps1.setInt(1, id);
ResultSet rs = ps1.executeQuery();
if (rs.next()) {
String name = rs.getString(1);
String username = rs.getString(2);
String filter = rs.getString(3);
int commits = rs.getInt(4);
ps2.setInt(1, id);
if (!isEmpty(name)) {
ps2.setString(2, name);
} else {
ps2.setNull(2, Types.VARCHAR);
}
if (!isEmpty(username)) {
ps2.setString(3, username);
} else {
ps2.setNull(3, Types.VARCHAR);
}
if (!isEmpty(filter)) {
ps2.setString(4, filter);
} else {
ps2.setNull(4, Types.VARCHAR);
}
ps2.setInt(5, commits);
ps2.setInt(6, x);
ps2.setInt(7, y);
ps2.setInt(8, w);
ps2.setInt(9, h);
ps2.setInt(10, r);
ps2.setFloat(11, fs);
ps2.execute();
}
rs.close();
} else {
String[] aux = data[7].split("\\|");
ps2.setInt(1, fillId);
ps2.setString(2, aux[0]);
ps2.setString(3, aux[1]);
ps2.setNull(4, Types.VARCHAR);
ps2.setInt(5, 0);
ps2.setInt(6, x);
ps2.setInt(7, y);
ps2.setInt(8, w);
ps2.setInt(9, h);
ps2.setInt(10, r);
ps2.setFloat(11, fs);
ps2.execute();
fillId--;
}
}
ps1.close();
ps2.close();
br.close();
}
private static void writeMetadataInfo(Connection conn, int originalSize) throws Exception {
PreparedStatement ps1 = conn.prepareStatement("insert into info (key, value) values (?,?);");
//--- Date
ps1.setString(1, "date");
ps1.setString(2, String.valueOf(System.currentTimeMillis()));
ps1.execute();
//--- Original Image Size (the one in which is based the metadata)
ps1.setString(1, "orig_size");
ps1.setString(2, String.valueOf(originalSize));
ps1.execute();
ps1.close();
}
private static void generateCloudZip() throws Exception {
final int BUFFER = 10240;
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(CLOUD_DIST_FILE);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
String[] files = {CLOUD_IMAGE, CLOUD_SVG, CLOUD_DATA_OUTPUT, CLOUD_DB_FILE};
for (int i=0; i < files.length; i++) {
File cloudImage = new File(files[i]);
FileInputStream fi = new FileInputStream(cloudImage);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(cloudImage.getName());
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
}
private static List<Account> processAccounts(Connection conn) throws Exception {
List<Account> accts = new ArrayList<>();
accts.addAll(readWellKnownAccounts());
wellKnownAccounts = accts.size();
int id = wellKnownAccounts + 1;
PreparedStatement ps1 = conn.prepareStatement("insert into accounts (id, accountId, username, name, email) values (?,?,?,?,?);");
PreparedStatement ps5 = conn.prepareStatement("insert into gerrit_accounts (accountId, username, name, email) values (?,?,?,?);");
PreparedStatement ps2 = conn.prepareStatement("insert into usernames (id, username) values (?,?);");
PreparedStatement ps3 = conn.prepareStatement("insert into names (id, name) values (?,?);");
PreparedStatement ps4 = conn.prepareStatement("insert into emails (id, email) values (?,?);");
File accountsDir = new File(ACCOUNTS_DIR);
File[] accounts = accountsDir.listFiles();
for (File account : accounts) {
if (account.getName().equals("last.txt") || account.getName().endsWith(".hasCommits")
|| account.getName().endsWith(".noHasCommits")) continue;
String json = readJson(account, true);
if (json.trim().length() == 0) continue;
try {
JSONObject o = new JSONObject(json);
int accId = Integer.parseInt(account.getName());
String username = o.optString("username");
if (username != null) username = cleanup(username);
String name = o.optString("name");
if (name != null) name = cleanup(name);
if (!isLegalName(name)) {
name = null;
}
String email = o.optString("email");
if (email != null) email = cleanup(email);
ps5.setInt(1, accId);
if (isEmpty(username)) {
ps5.setNull(2, Types.VARCHAR);
} else {
ps5.setString(2, username);
}
if (isEmpty(name)) {
ps5.setNull(3, Types.VARCHAR);
} else {
ps5.setString(3, name);
}
if (isEmpty(email)) {
ps5.setNull(4, Types.VARCHAR);
} else {
ps5.setString(4, email);
}
ps5.execute();
boolean found = false;
for (Account acc : accts) {
if (!isEmpty(email) && acc.emails.contains(email)) {
if (!isEmpty(username) && !acc.usernames.contains(username)) {
acc.usernames.add(username);
}
if (!isEmpty(name) && !acc.names.contains(name)) {
acc.names.add(name);
}
if (acc.accountId == -1) acc.accountId = accId;
found = true;
break;
}
if (!isEmpty(name) && acc.names.contains(name) && isValidNameForSearch(name)) {
if (!isEmpty(username) && !acc.usernames.contains(username)) {
acc.usernames.add(username);
}
if (!isEmpty(email) && !acc.emails.contains(email)) {
acc.emails.add(email);
}
if (acc.accountId == -1) acc.accountId = accId;
found = true;
break;
}
if (!isEmpty(username) && acc.usernames.contains(username)) {
if (!isEmpty(name) && !acc.names.contains(name)) {
acc.names.add(name);
}
if (!isEmpty(email) && !acc.emails.contains(email)) {
acc.emails.add(email);
}
if (acc.accountId == -1) acc.accountId = accId;
found = true;
break;
}
}
if (found) {
continue;
}
id++;
Account acc = new Account();
acc.id = id;
acc.accountId = accId;
boolean hasData = false;
if (!isEmpty(email)) {
acc.emails.add(email);
hasData = true;
}
if (!isEmpty(name)) {
acc.names.add(name);
hasData = true;
}
if (!isEmpty(username)) {
acc.usernames.add(username);
hasData = true;
}
if (hasData) {
accts.add(acc);
}
} catch (Exception ex) {
System.out.println("Unable to parse account " + account.getName());
System.out.println(json);
throw ex;
}
}
for (Account acc : accts) {
for (String username : acc.usernames) {
ps2.setInt(1, acc.id);
ps2.setString(2, username);
ps2.execute();
}
for (String name : acc.names) {
ps3.setInt(1, acc.id);
ps3.setString(2, name);
ps3.execute();
}
for (String email : acc.emails) {
ps4.setInt(1, acc.id);
ps4.setString(2, email);
ps4.execute();
}
String username = null;
String name = null;
String email = null;
if (acc.usernames.size() > 0) {
username = acc.usernames.get(0);
}
if (acc.names.size() > 0) {
name = acc.names.get(0);
}
if (acc.emails.size() > 0) {
email = acc.emails.get(0);
}
ps1.setInt(1, acc.id);
ps1.setInt(2, acc.accountId);
if (isEmpty(username)) {
ps1.setNull(3, Types.VARCHAR);
} else {
ps1.setString(3, username);
}
if (isEmpty(name)) {
ps1.setNull(4, Types.VARCHAR);
} else {
ps1.setString(4, name);
}
if (isEmpty(email)) {
ps1.setNull(5, Types.VARCHAR);
} else {
ps1.setString(5, email);
}
ps1.execute();
}
ps1.close();
ps2.close();
ps3.close();
ps4.close();
ps5.close();
return accts;
}
@SuppressWarnings("unchecked")
private static void processStats(Connection conn) throws Exception {
PreparedStatement ps1 = conn.prepareStatement("insert into all_commits (project, commits, name, email) values (?,?,?,?);");
PreparedStatement ps2 = conn.prepareStatement("insert into translations_commits (project, commits, name, email) values (?,?,?,?);");
File statsDir = new File(STATS_DIR);
Collection<File> allStats = FileUtils.listFiles(statsDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(ALL_STATS_FILENAME);
}
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().equals(ALL_STATS_FILENAME);
}
}, TrueFileFilter.INSTANCE);
for (File stats : allStats) {
String project = stats.getPath().replaceAll("\\\\", "/").replaceFirst(STATS_DIR, "");
project = project.substring(0, project.lastIndexOf("/"));
BufferedReader br = new BufferedReader(new FileReader(stats));
String line = null;
while ((line = br.readLine()) != null) {
int commits = Integer.parseInt(line.substring(0, line.indexOf("\t")).trim());
String name = cleanup(line.substring(line.indexOf("\t")+1,line.lastIndexOf("<")).trim());
String email = cleanup(line.substring(line.lastIndexOf("<")+1, line.length()-1).trim());
ps1.setString(1, project);
ps1.setInt(2, commits);
if (isEmpty(name)) {
ps1.setNull(3, Types.VARCHAR);
} else {
ps1.setString(3, name);
}
if (isEmpty(email)) {
ps1.setNull(4, Types.VARCHAR);
} else {
ps1.setString(4, email);
}
ps1.execute();
}
br.close();
}
Collection<File> translationStats = FileUtils.listFiles(statsDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(TRANSLATIONS_STATS_FILENAME);
}
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().equals(TRANSLATIONS_STATS_FILENAME);
}
}, TrueFileFilter.INSTANCE);
for (File stats : translationStats) {
String project = stats.getPath().replaceAll("\\\\", "/").replaceFirst(STATS_DIR, "");
project = project.substring(0, project.lastIndexOf("/"));
BufferedReader br = new BufferedReader(new FileReader(stats));
String line = null;
while ((line = br.readLine()) != null) {
int commits = Integer.parseInt(line.substring(0, line.indexOf("\t")).trim());
String name = cleanup(line.substring(line.indexOf("\t")+1,line.lastIndexOf("<")).trim());
String email = cleanup(line.substring(line.lastIndexOf("<")+1, line.length()-1).trim());
ps2.setString(1, project);
ps2.setInt(2, commits);
if (isEmpty(name)) {
ps2.setNull(3, Types.VARCHAR);
} else {
ps2.setString(3, name);
}
if (isEmpty(email)) {
ps2.setNull(4, Types.VARCHAR);
} else {
ps2.setString(4, email);
}
ps2.execute();
}
br.close();
}
ps1.close();
ps2.close();
}
private static boolean isEmpty(String src) {
return src == null || src.trim().length() == 0;
}
private static List<Account> readWellKnownAccounts() throws Exception {
BufferedReader br = new BufferedReader(new FileReader(WELL_KNOWN_ACCOUNTS));
String line = null;
List<Account> accounts = new ArrayList<>();
int i = 1;
while ((line = br.readLine()) != null) {
if (line.length() == 0) continue;
String[] fields = line.split("\\|");
Account acc = new Account();
acc.id = i;
acc.names.add(fields[0].trim());
String[] usernames = fields[1].trim().split("/");
for (String username : usernames) {
acc.usernames.add(username.trim());
}
for (int j = 2; j < fields.length; j++) {
acc.emails.add(fields[j].trim());
}
accounts.add(acc);
i++;
}
br.close();
return accounts;
}
private static String readJson(File json, boolean hasheader) throws Exception {
FileReader fr = new FileReader(json);
if (hasheader) {
fr.read(new char[5]);
}
StringBuffer sb = new StringBuffer();
char[] data = new char[10240];
int read = -1;
while ((read = fr.read(data, 0, 10240)) != -1) {
sb.append(data, 0, read);
}
fr.close();
return sb.toString();
}
private static String cleanup(String src) {
String dst = src;
int s = src.indexOf("(");
int e = src.indexOf(")");
if (s != -1 && s < e) {
dst = dst.substring(0, s) + dst.substring(e + 1);
}
s = dst.indexOf("[");
e = dst.indexOf("]");
if (s != -1 && s < e) {
dst = dst.substring(0, s) + dst.substring(e + 1);
}
s = dst.indexOf("~");
if (s != -1) {
dst = dst.substring(0, s);
}
dst = dst.replaceAll("\\|", "");
dst = dst.replaceAll("\u200e", "");
dst = dst.replaceAll("\u200f", "");
return dst.replaceAll(" ", " ").trim();
}
private static boolean isLegalName(String name) {
return name == null || !(name.contains("?") || name.equals("DO NOT USE"));
}
private static boolean isValidNameForSearch(String name) {
return name.indexOf(" ") != -1 && name.length() >= 5 && !name.equals("John Smith") && !name.equals("John Doe");
}
private static boolean userHasCommits(int id, int accountId, String name, String email) {
InputStream is = null;
String url = null;
try {
if (id <= wellKnownAccounts) {
return true;
}
if (new File(ACCOUNTS_DIR, accountId + ".hasCommits").exists()) {
return true;
}
File noHasCommits = new File(ACCOUNTS_DIR, accountId + ".noHasCommits");
if (noHasCommits.exists() && (System.currentTimeMillis() - noHasCommits.lastModified()) < 2592000000L) { // 30 days
return false;
}
String owner = name + " <" + email + ">";
if (isEmpty(name)) {
owner = name + " <" + email + ">";
}
url = "http://review.cyanogenmod.org/changes/?q=status:merged+owner:\"" + owner+ "\"&limit=1";
owner = URLEncoder.encode(owner, "UTF-8");
is = new URL("http://review.cyanogenmod.org/changes/?q=status:merged+owner:\"" + owner+ "\"&limit=1").openStream();
byte[] data = new byte[11];
int read = is.read(data);
LOGGER.info ("Fetched " + url + ": " + (read > 8));
return read > 8;
} catch (Exception e) {
LOGGER.info ("Fetched " + url + ": error");
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) { }
}
}
return false;
}
public static void generateCloud(Connection conn) throws Exception {
final List<WordFrequency> wordFrequencies = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(CLOUD_DATA));
String line = null;
while ((line = reader.readLine()) != null) {
String record = line.trim();
if (record.length() > 0) {
int pos = record.indexOf(",");
int pos2 = record.indexOf(",", pos+1);
int pos3 = record.indexOf("|");
int id = Integer.parseInt(record.substring(0, pos));
int freq = Integer.parseInt(record.substring(pos+1, pos2));
String word = record.substring(pos2+1, pos3);
String filter = record.substring(pos3+1);
if (word.length() <= 0) {
continue;
}
wordFrequencies.add(new WordFrequency(id, word, filter, freq));
}
}
reader.close();
int size = readLastCloudSize();
int increment = DEFAULT_CLOUD_INCREMENT;
while (true) {
convertSvgToPng(CLOUD_BG_SVG, CLOUD_BG_PNG, 1024, size, null);
final WordCloud wordCloud = new WordCloud(size, size, CollisionMode.RECTANGLE, true);
final String[] EXTRA_WORDS = {"cid", "cyanogenmod", "android", "aosp",
"nexus", "bacon", "adb", "apk", "dalvik", "droid", "logcat", "fastboot"};
Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(CLOUD_FONT));
wordCloud.setCloudFont(new CloudFont(font));
wordCloud.setPadding(1);
wordCloud.setBackground(new PixelBoundryBackground(new FileInputStream(CLOUD_BG_PNG)));
wordCloud.setBackgroundColor(new Color(0x474647));
wordCloud.setColorPalette(new ColorPalette(new Color(0x6199b9)));
FontScalar scalar = new SqrtFontScalar(12, 24);
wordCloud.setFontScalar(scalar);
wordCloud.build(wordFrequencies);
boolean done = false;
int i;
for (i = 0; i <=4; i++) {
scalar.reduceBy(1);
if (wordCloud.fill(wordFrequencies, i+1)) {
done = true;
break;
}
}
if (!done) {
int newsize = size + DEFAULT_CLOUD_INCREMENT;
LOGGER.info("Word cloud doesn't fit in " + size + "x" + size +
". Retrying at " + newsize + "x" + newsize +" ...");
wordCloud.writeToImage(CLOUD_IMAGE + "." + size + "x" + size + ".png");
size += increment;
continue;
}
scalar.reduceBy(4-i);
wordCloud.printSkippedWords();
wordCloud.fillWithOtherWords(wordFrequencies, EXTRA_WORDS);
LOGGER.info("Saving wordcloud. Image size " + size + "x" + size);
wordCloud.drawForgroundToBackground();
wordCloud.writeToImage(CLOUD_IMAGE);
wordCloud.writeWordsToFile(CLOUD_DATA_OUTPUT, size);
break;
}
// Write metadainfo and save last size
writeLastCloudSize(size);
writeMetadataInfo(conn, size);
// Write the cloud to an SVG
writeToSvg(CLOUD_SVG, size, new Color(0x6199b9), new Color(0x474647));
}
private static void writeToSvg(String svg, int size, Color color, Color bgcolor) throws Exception {
String c = String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
String bg = String.format("#%02x%02x%02x", bgcolor.getRed(), bgcolor.getGreen(), bgcolor.getBlue());
FileWriter fw = new FileWriter(svg);
fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
fw.write("<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\r\n");
fw.write("viewBox=\"0 0 " + size + " " + size + "\"\r\n");
fw.write("version=\"1.1\"\r\n");
fw.write("width=\"" + size + "\"\r\n");
fw.write("height=\"" + size + "\"\r\n");
fw.write("text-rendering=\"geometricPrecision\">\r\n");
fw.write("<defs >\r\n");
fw.write("<font-face font-family=\"Roboto\">\r\n");
fw.write("<font-face-src>\r\n");
fw.write("<font-face-uri xlink:href=\"../Roboto-Bold.svg#Roboto-Bold\">\r\n");
fw.write("<font-face-format string=\"svg\"/>\r\n");
fw.write("</font-face-uri>\r\n");
fw.write("</font-face-src>\r\n");
fw.write("</font-face>\r\n");
fw.write("</defs>\r\n");
fw.write("<g>\r\n");
fw.write("<rect width=\"" + size + "\" height=\"" + size + "\" style=\"fill: " + bg + ";\"/>\r\n");
BufferedReader br = new BufferedReader(new FileReader(CLOUD_DATA_OUTPUT));
String line=null;
br.readLine();
while ((line = br.readLine()) != null) {
int lastIndex = 0;
int index = line.indexOf(',', lastIndex);
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float x = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float y = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float w = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float h = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
int r = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float fs = Float.parseFloat(line.substring(lastIndex, index));
lastIndex = index+1;
String xx = line.substring(lastIndex);
String n = xx.substring(0, xx.indexOf("|"));
if (r == 0) {
fw.write("<text x=\"" + x + "\" y=\"" + y + "\" font-family=\"'Roboto'\" font-size=\"" + fs + "\" style=\"fill: " + c + "\">" + n + "</text>\r\n");
} else {
if (r == -1) {
fw.write("<text x=\"" + x + "\" y=\"" + y + "\" transform=\"translate(" + (w / 2) + "," + (h - (w / 2)) + ")rotate(-90 " + x + "," + y + ")\" font-family=\"'Roboto'\" font-size=\"" + fs + "\" style=\"fill: " + c + "\">" + n + "</text>\r\n");
} else {
fw.write("<text x=\"" + x + "\" y=\"" + y + "\" transform=\"translate(0,-" + (w / 2) + ")rotate(90 " + x + "," + y + ")\" font-family=\"'Roboto'\" font-size=\"" + fs + "\" style=\"fill: " + c + "\">" + n + "</text>\r\n");
}
}
}
br.close();
fw.write("</g>\r\n");
fw.write("</svg>\r\n");
fw.close();
}
private static void convertSvgToPng(String svg, String png, int origSize, int dstSize, Color bg) throws Exception {
String svg_URI_input = Paths.get(svg).toUri().toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
OutputStream png_ostream = new FileOutputStream(png);
TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);
PNGTranscoder my_converter = new PNGTranscoder();
my_converter.addTranscodingHint( PNGTranscoder.KEY_WIDTH, new Float( dstSize ) );
my_converter.addTranscodingHint( PNGTranscoder.KEY_HEIGHT, new Float( dstSize ) );
my_converter.addTranscodingHint( PNGTranscoder.KEY_AOI, new Rectangle( 0, 0, origSize, origSize) );
if (bg != null) {
my_converter.addTranscodingHint( PNGTranscoder.KEY_BACKGROUND_COLOR, bg);
}
my_converter.transcode(input_svg_image, output_png_image);
png_ostream.flush();
png_ostream.close();
}
private static int readLastCloudSize() throws Exception {
File file = new File(LAST_CLOUD_SIZE);
if (!file.exists()) {
return DEFAULT_CLOUD_SIZE;
}
BufferedReader br = new BufferedReader(new FileReader(file));
try {
return Integer.parseInt(br.readLine());
} catch (Exception ex) {
} finally {
br.close();
}
return DEFAULT_CLOUD_SIZE;
}
private static void writeLastCloudSize(int size) throws Exception {
File file = new File(LAST_CLOUD_SIZE);
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(size));
bw.close();
}
}
| source/src/main/java/CloudGenerator.java | import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import wordcloud.CollisionMode;
import wordcloud.WordCloud;
import wordcloud.WordFrequency;
import wordcloud.bg.PixelBoundryBackground;
import wordcloud.font.CloudFont;
import wordcloud.font.scale.FontScalar;
import wordcloud.font.scale.SqrtFontScalar;
import wordcloud.palette.ColorPalette;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CloudGenerator {
private static final Logger LOGGER = Logger.getLogger(CloudGenerator.class);
private static final String ROOT_DIR = "./";
private static final String DB_NAME = ROOT_DIR + "db/cloud.db";
private static final String ACCOUNTS_DIR = ROOT_DIR + "db/accounts";
private static final String CHANGES_DIR = ROOT_DIR + "db/changes";
private static final String STATS_DIR = ROOT_DIR + "db/stats/";
private static final String WELL_KNOWN_ACCOUNTS = ROOT_DIR + "resources/well-known-accounts.txt";
private static final String ALL_STATS_FILENAME = "all_stats.dat";
private static final String TRANSLATIONS_STATS_FILENAME = "translations_stats.dat";
private static final String CLOUD_DATA = ROOT_DIR + "db/cloud.data";
private static final String CLOUD_IMAGE = ROOT_DIR + "out/cloud.png";
private static final String CLOUD_SVG = ROOT_DIR + "out/cloud.svg";
private static final String CLOUD_DB_FILE = ROOT_DIR + "out/cloud.db";
private static final String CLOUD_DATA_OUTPUT = ROOT_DIR + "out/cloud.data";
private static final String CLOUD_DIST_FILE = ROOT_DIR + "out/cloud.zip";
private static final String CLOUD_BG_SVG = ROOT_DIR + "resources/cid_head.svg";
private static final String CLOUD_BG_PNG = ROOT_DIR + "resources/cid_head.png";
private static final String CLOUD_FONT = ROOT_DIR + "resources/Roboto-Bold.ttf";
private static final String LAST_CLOUD_SIZE = ROOT_DIR + "db/last_cloud_size.txt";
private static final int DEFAULT_CLOUD_SIZE = 1920;
private static final int DEFAULT_CLOUD_INCREMENT = 4;
private static int wellKnownAccounts;
private static class Account {
public int id;
public int accountId = -1;
public List<String> usernames = new ArrayList<>();
public List<String> names = new ArrayList<>();
public List<String> emails = new ArrayList<>();
}
public static void main(String[] args) throws Exception {
boolean FROM_GERRIT = true;
new File(DB_NAME).delete();
new File(CLOUD_DB_FILE).delete();
Connection conn = createDb();
Connection connMetadata = createMetadataDb();
conn.setAutoCommit(false);
connMetadata.setAutoCommit(false);
try {
LOGGER.info("Collecting data");
processAccounts(conn);
processStats(conn); // Still use the github data to map emails
if (FROM_GERRIT) {
fetchAllGerritCommits();
processAllGerritCommits(conn);
}
create_indexes(conn);
extractEmailsFromCommitNames(conn);
if (FROM_GERRIT) {
generateCloudDataFromGerrit(conn);
writeGerritCloudData(conn);
} else {
computeCommitsPerProject(conn);
generateCloudDataFromGithub(conn);
filterDataByUserWithCommits(conn);
}
LOGGER.info("Generating cloud");
generateCloud(connMetadata);
generateMetadata(conn, connMetadata);
generateCloudZip();
} finally {
conn.commit();
conn.close();
connMetadata.commit();
connMetadata.close();
}
}
private static Connection createDb() throws Exception {
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + DB_NAME);
Statement st = conn.createStatement();
st.execute("PRAGMA synchronous = OFF;");
st.execute("PRAGMA journal_mode = MEMORY;");
st.execute("drop table if exists accounts;");
st.execute("drop table if exists gerrit_accounts;");
st.execute("drop table if exists usernames;");
st.execute("drop table if exists names;");
st.execute("drop table if exists emails;");
st.execute("drop table if exists all_commits;");
st.execute("drop table if exists translations_commits;");
st.execute("drop table if exists stats;");
st.execute("drop table if exists raw_cloud_data;");
st.execute("drop table if exists all_accounts_with_commits;");
st.execute("drop table if exists cloud_data;");
st.execute("drop table if exists gerrit_commits;");
st.execute("create table accounts (id NUMBER, accountId NUMBER, username TEXT, name TEXT, email TEXT);");
st.execute("create table gerrit_accounts (accountId NUMBER, username TEXT, name TEXT, email TEXT);");
st.execute("create table usernames (id NUMBER, username TEXT);");
st.execute("create table names (id NUMBER, name TEXT);");
st.execute("create table emails (id NUMBER, email TEXT);");
st.execute("create table all_commits (project TEXT, commits NUMBER, name TEXT, email TEXT);");
st.execute("create table translations_commits (project TEXT, commits NUMBER, name TEXT, email TEXT);");
st.execute("create table stats (project TEXT, id NUMBER, commits NUMBER);");
st.execute("create table raw_cloud_data (commits NUMBER, id NUMBER, name TEXT, username TEXT, filter TEXT);");
st.execute("create table all_accounts_with_commits (accountId NUMBER);");
st.execute("create table cloud_data (commits NUMBER, id NUMBER, name TEXT, username TEXT, filter TEXT);");
st.execute("create table gerrit_commits (id NUMBER, changeId TEXT, project TEXT, branch TEXT, subject TEXT, author_name TEXT, author_email TEXT, owner_name, owner_email);");
st.close();
return conn;
}
private static Connection createMetadataDb() throws Exception {
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + CLOUD_DB_FILE);
Statement st = conn.createStatement();
st.execute("PRAGMA synchronous = OFF;");
st.execute("PRAGMA journal_mode = MEMORY;");
st.execute("drop table if exists android_metadata;");
st.execute("drop table if exists metadata;");
st.execute("drop table if exists info;");
st.execute("create table android_metadata (locale TEXT);");
st.execute("insert into android_metadata (locale) values ('us_US')");
st.execute("create table metadata (id NUMBER, name TEXT, username TEXT, filter TEXT, commits NUMBER, x NUMBER, y NUMBER, w NUMBER, h NUMBER, r NUMBER, fs REAL);");
st.execute("create index metadata_idx_1 on metadata (name);");
st.execute("create index metadata_idx_2 on metadata (filter);");
st.execute("create index metadata_idx_3 on metadata (x, y, w, h);");
st.execute("create index metadata_idx_4 on metadata (commits);");
st.execute("create table info (key TEXT, value TEXT);");
st.close();
return conn;
}
private static void create_indexes(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("create index accounts_idx_1 on accounts (id);");
st.execute("create index usernames_idx_1 on usernames (username);");
st.execute("create index names_idx_1 on names (name);");
st.execute("create index emails_idx_1 on emails (email);");
st.execute("create index all_commits_idx_1 on all_commits (name);");
st.execute("create index all_commits_idx_2 on all_commits (email);");
st.execute("create index translations_commits_idx_1 on translations_commits (name);");
st.execute("create index translations_commits_idx_2 on translations_commits (email);");
st.execute("create index gerrit_commits_idx_1 on gerrit_commits (author_email);");
st.execute("create index gerrit_commits_idx_2 on gerrit_commits (owner_email);");
st.execute("create index gerrit_commits_idx_3 on gerrit_commits (changeId);");
st.close();
}
private static void extractEmailsFromCommitNames(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("drop table if exists temp_emails;");
st.execute("create table temp_emails (id NUMBER, email TEXT);");
st.execute("insert into temp_emails (id, email) select id, email from emails");
st.execute("insert into temp_emails (id, email) select distinct b.id, a.email from names b, " +
"all_commits a where a.name = b.name and a.name is not null and a.email is " +
"not null and instr(a.name ,'?') = 0 and length(a.name) > 9 " +
"and (select count(*) from names z where z.name = a.name) = 1;");
st.execute("insert into temp_emails (id, email) select distinct b.id, a.email from names b, " +
"translations_commits a where a.name = b.name and a.name is not null and a.email is " +
"not null and instr(a.name ,'?') = 0 and length(a.name) > 9 " +
"and (select count(*) from names z where z.name = a.name) = 1;");
st.execute("delete from emails");
st.execute("insert into emails (id, email) select distinct id, email from temp_emails");
st.execute("drop table if exists temp_emails;");
st.close();
}
private static void computeCommitsPerProject(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("insert into stats (project, id, commits) " +
"select z.project, acc.id, z.commits " +
"from " +
"( " +
"select project, id, sum(commits) commits " +
"from " +
"( " +
"select a.project, b.id, a.commits from all_commits a, emails b " +
"where a.email = b.email " +
"union " +
"select a.project, b.id, a.commits * -1 from translations_commits a, emails b " +
"where a.email = b.email " +
") " +
"group by project, id " +
") z, accounts acc " +
"where z.id = acc.id " +
"and z.commits > 0;");
st.close();
}
private static void generateCloudDataFromGithub(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("insert into raw_cloud_data (commits, id, name, username, filter) " +
"select sum(stats.commits) commits, accounts.id, accounts.name, accounts.username, a.filter " +
"from stats, accounts, " +
"( " +
"select id, group_concat(filter,'|') filter from " +
"( " +
"select id, group_concat(username,'|') filter from usernames " +
"group by id " +
"union " +
"select id, group_concat(name,'|') filter from names " +
"group by id " +
") " +
"group by id " +
") a " +
"where stats.id = accounts.id " +
"and accounts.id = a.id " +
"group by accounts.id, accounts.name, accounts.username, a.filter " +
"order by 1 desc;");
st.close();
}
private static void generateCloudDataFromGerrit(Connection conn) throws Exception {
Statement st = conn.createStatement();
st.execute("insert into cloud_data (commits, id, name, username, filter) " +
"select count(*) commits, a.id, a.name, a.username, f.filter from ( " +
"select (select e.id from emails e where e.email = c.author_email) id, changeId from gerrit_commits c " +
"where c.subject <> 'Automatic translation import' " +
") c, accounts a, " +
"( " +
"select id, group_concat(filter,'|') filter from " +
"( " +
"select id, group_concat(username,'|') filter from usernames " +
"group by id " +
"union " +
"select id, group_concat(name,'|') filter from names " +
"group by id " +
") " +
"group by id " +
") f " +
"where c.id = a.id " +
"and a.id = f.id " +
"group by a.id " +
"order by commits desc");
st.close();
}
@SuppressWarnings("unchecked")
private static void filterDataByUserWithCommits(Connection conn) throws Exception {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select accounts.id, accounts.accountId, accounts.name, group_concat(emails.email,'|') emails " +
"from raw_cloud_data, accounts, emails " +
"where raw_cloud_data.id = accounts.id and accounts.id = emails.id " +
"group by accounts.id, accounts.name " +
"order by raw_cloud_data.commits desc;");
while(rs.next()) {
int id = rs.getInt(1);
int accountId = rs.getInt(2);
String name = rs.getString(3);
String[] emails = rs.getString(4).split("\\|");
boolean hasCommits = false;
for (String email : emails) {
if (userHasCommits(id, accountId, name, email)) {
new File(ACCOUNTS_DIR, accountId + ".hasCommits").createNewFile();
if (new File(ACCOUNTS_DIR, accountId + ".noHasCommits").exists()) {
new File(ACCOUNTS_DIR, accountId + ".noHasCommits").delete();
}
hasCommits = true;
break;
}
}
File noHasCommits = new File(ACCOUNTS_DIR, accountId + ".noHasCommits");
if (!hasCommits && (!noHasCommits.exists() || (System.currentTimeMillis() - noHasCommits.lastModified()) > 2592000000L)) { // 30 days
noHasCommits.createNewFile();
}
}
rs.close();
File accounts = new File(ACCOUNTS_DIR);
Collection<File> allAccountsWithCommits = FileUtils.listFiles(accounts, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".hasCommits");
}
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".hasCommits");
}
}, TrueFileFilter.INSTANCE);
PreparedStatement ps1 = conn.prepareStatement("insert into all_accounts_with_commits (accountId) values (?);");
for (File acc : allAccountsWithCommits) {
int accountId = Integer.parseInt(acc.getName().substring(0, acc.getName().lastIndexOf(".")));
ps1.setInt(1, accountId);
ps1.execute();
}
ps1.close();
st.execute("insert into cloud_data (commits, id, name, username, filter) " +
"select sum(r.commits), r.id, r.name, r.username, r.filter from raw_cloud_data r, accounts a "+
"where r.id = a.id and a.accountId in (select accountId from all_accounts_with_commits) " +
"group by r.name");
FileWriter fw = new FileWriter(CLOUD_DATA);
rs = st.executeQuery("select id, commits, name, filter from cloud_data order by 1;");
while (rs.next()) {
String id = rs.getString(1);
String commits = rs.getString(2);
String name = cleanup(rs.getString(3));
String filter = cleanup(rs.getString(4));
fw.write(String.format("%s,%s,%s|%s", id, commits, name, filter) + "\r\n");
}
fw.close();
rs.close();
st.close();
}
private static void fetchAllGerritCommits() throws Exception {
final StringBuffer start = new StringBuffer("2010-10-28");
File statsDir = new File(CHANGES_DIR);
statsDir.mkdirs();
FileUtils.listFiles(statsDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.compareTo(start.toString()) > 0) {
start.setLength(0);
start.append(name);
}
return true;
}
@Override
public boolean accept(File file) {
String name = file.getName();
if (name.compareTo(start.toString()) > 0) {
start.setLength(0);
start.append(name);
}
return true;
}
}, TrueFileFilter.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(start.toString()));
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DAY_OF_YEAR, -30);
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
while (c.compareTo(now) <= 0) {
fetchGerritCommits(c.getTime());
c.add(Calendar.DAY_OF_YEAR, 1);
}
}
private static void fetchGerritCommits(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
String end = sdf.format(c.getTime());
c.add(Calendar.DAY_OF_YEAR, 1);
String start = sdf.format(c.getTime());
LOGGER.info("Fetching gerrit changes: " + end);
File dir = new File(CHANGES_DIR, end);
dir.mkdirs();
int i = 1;
int s = 0;
final int count = 250;
while (true) {
try {
String url = "http://review.cyanogenmod.org/changes/?q=status:merged+before:\"" + start + "\"+after:\"" + end + "\"&n=" + count + "&O=a&o=DETAILED_ACCOUNTS";
if (s > 0) {
url += "&S="+s;
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new URL(url).openStream(), "UTF-8"));
FileWriter fw = new FileWriter(new File(dir, String.valueOf(i)));
reader.readLine();
int read = -1;
char[] data = new char[10240];
StringBuffer sb = new StringBuffer();
while ((read = reader.read(data, 0, 10240)) != -1) {
sb.append(data, 0, read);
fw.write(data, 0, read);
}
reader.close();
fw.close();
if (sb.indexOf("\"_more_changes\": true") == -1) {
break;
}
i++;
s+=count;
} catch (Exception ex) {
LOGGER.error("Error downloading gerrit changes " + end + "-" + start, ex);
break;
}
}
}
@SuppressWarnings("unchecked")
private static void processAllGerritCommits(Connection conn) throws Exception {
File changesDir = new File(CHANGES_DIR);
Collection<File> changes = FileUtils.listFiles(changesDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return true;
}
@Override
public boolean accept(File file) {
return true;
}
}, TrueFileFilter.INSTANCE);
PreparedStatement ps1 = conn.prepareStatement("insert into gerrit_commits (id, changeId, project, branch, subject, author_name, author_email, owner_name, owner_email) values (?,?,?,?,?,?,?,?,?);");
for (File change : changes) {
if (!change.isFile()) continue;
String json = readJson(change, false);
if (json.trim().length() == 0) continue;
try {
JSONArray a = new JSONArray(json);
int count = a.length();
for (int i = 0; i < count; i++) {
JSONObject o = a.getJSONObject(i);
int id = o.optInt("_number", i);
String changeId = o.optString("change_id");
String project = o.optString("project");
String branch = o.optString("branch");
String subject = o.optString("subject");
String curRev = o.optString("current_revision");
String author_name = null;
String author_email = null;
try {
JSONObject author = o.optJSONObject("revisions").getJSONObject(curRev).getJSONObject("commit").getJSONObject("author");
author_name = cleanup(author.optString("name"));
author_email = cleanup(author.optString("email"));
} catch (Exception ex) {
try {
JSONObject owner = o.optJSONObject("owner");
author_name = cleanup(owner.optString("name"));
author_email = cleanup(owner.optString("email"));
} catch (Exception ex2) {
System.out.println("Fail to read current revision data. change: " + change + "; changeId: " + changeId);
}
}
JSONObject owner = o.optJSONObject("owner");
String owner_name = cleanup(owner.optString("name"));
String owner_email = cleanup(owner.optString("email"));
ps1.setInt(1, id);
if (!isEmpty(changeId)) {
ps1.setString(2, changeId);
} else {
ps1.setNull(2, Types.VARCHAR);
}
if (!isEmpty(project)) {
ps1.setString(3, project);
} else {
ps1.setNull(3, Types.VARCHAR);
}
if (!isEmpty(branch)) {
ps1.setString(4, branch);
} else {
ps1.setNull(4, Types.VARCHAR);
}
if (!isEmpty(subject)) {
ps1.setString(5, subject);
} else {
ps1.setNull(5, Types.VARCHAR);
}
if (!isEmpty(author_name)) {
ps1.setString(6, author_name);
} else {
ps1.setNull(6, Types.VARCHAR);
}
if (!isEmpty(author_email)) {
ps1.setString(7, author_email);
} else {
ps1.setNull(7, Types.VARCHAR);
}
if (!isEmpty(owner_name)) {
ps1.setString(8, owner_name);
} else {
ps1.setNull(8, Types.VARCHAR);
}
if (!isEmpty(owner_email)) {
ps1.setString(9, owner_email);
} else {
ps1.setNull(9, Types.VARCHAR);
}
ps1.execute();
}
} catch (Exception ex) {
System.out.println("Unable to parse changes in " + change);
System.out.println(json);
throw ex;
}
}
ps1.close();
}
private static void writeGerritCloudData(Connection conn) throws Exception {
FileWriter fw = new FileWriter(CLOUD_DATA);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select id, commits, name, filter from cloud_data order by 1;");
while (rs.next()) {
String id = rs.getString(1);
String commits = rs.getString(2);
String name = cleanup(rs.getString(3));
String filter = cleanup(rs.getString(4));
fw.write(String.format("%s,%s,%s|%s", id, commits, name, filter) + "\r\n");
}
fw.close();
rs.close();
st.close();
}
private static void generateMetadata(Connection conn, Connection connMetadata) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(new File(CLOUD_DATA_OUTPUT)));
PreparedStatement ps1 = conn.prepareStatement("select name, username, filter, commits from cloud_data where id = ?;");
PreparedStatement ps2 = connMetadata.prepareStatement("insert into metadata (id, name, username, filter, commits, x, y, w, h, r, fs) values (?,?,?,?,?,?,?,?,?,?,?);");
String line = br.readLine();
int fillId = -1000;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
int x = Integer.parseInt(data[1]);
int y = Integer.parseInt(data[2]);
int w = Integer.parseInt(data[3]);
int h = Integer.parseInt(data[4]);
int r = Integer.parseInt(data[5]);
float fs = Float.parseFloat(data[6]);
if (id != -1) {
ps1.setInt(1, id);
ResultSet rs = ps1.executeQuery();
if (rs.next()) {
String name = rs.getString(1);
String username = rs.getString(2);
String filter = rs.getString(3);
int commits = rs.getInt(4);
ps2.setInt(1, id);
if (!isEmpty(name)) {
ps2.setString(2, name);
} else {
ps2.setNull(2, Types.VARCHAR);
}
if (!isEmpty(username)) {
ps2.setString(3, username);
} else {
ps2.setNull(3, Types.VARCHAR);
}
if (!isEmpty(filter)) {
ps2.setString(4, filter);
} else {
ps2.setNull(4, Types.VARCHAR);
}
ps2.setInt(5, commits);
ps2.setInt(6, x);
ps2.setInt(7, y);
ps2.setInt(8, w);
ps2.setInt(9, h);
ps2.setInt(10, r);
ps2.setFloat(11, fs);
ps2.execute();
}
rs.close();
} else {
String[] aux = data[7].split("\\|");
ps2.setInt(1, fillId);
ps2.setString(2, aux[0]);
ps2.setString(3, aux[1]);
ps2.setNull(4, Types.VARCHAR);
ps2.setInt(5, 0);
ps2.setInt(6, x);
ps2.setInt(7, y);
ps2.setInt(8, w);
ps2.setInt(9, h);
ps2.setInt(10, r);
ps2.setFloat(11, fs);
ps2.execute();
fillId--;
}
}
ps1.close();
ps2.close();
br.close();
}
private static void writeMetadataInfo(Connection conn, int originalSize) throws Exception {
PreparedStatement ps1 = conn.prepareStatement("insert into info (key, value) values (?,?);");
//--- Date
ps1.setString(1, "date");
ps1.setString(2, String.valueOf(System.currentTimeMillis()));
ps1.execute();
//--- Original Image Size (the one in which is based the metadata)
ps1.setString(1, "orig_size");
ps1.setString(2, String.valueOf(originalSize));
ps1.execute();
ps1.close();
}
private static void generateCloudZip() throws Exception {
final int BUFFER = 10240;
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(CLOUD_DIST_FILE);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
String[] files = {CLOUD_IMAGE, CLOUD_SVG, CLOUD_DATA_OUTPUT, CLOUD_DB_FILE};
for (int i=0; i < files.length; i++) {
File cloudImage = new File(files[i]);
FileInputStream fi = new FileInputStream(cloudImage);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(cloudImage.getName());
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
}
private static List<Account> processAccounts(Connection conn) throws Exception {
List<Account> accts = new ArrayList<>();
accts.addAll(readWellKnownAccounts());
wellKnownAccounts = accts.size();
int id = wellKnownAccounts + 1;
PreparedStatement ps1 = conn.prepareStatement("insert into accounts (id, accountId, username, name, email) values (?,?,?,?,?);");
PreparedStatement ps5 = conn.prepareStatement("insert into gerrit_accounts (accountId, username, name, email) values (?,?,?,?);");
PreparedStatement ps2 = conn.prepareStatement("insert into usernames (id, username) values (?,?);");
PreparedStatement ps3 = conn.prepareStatement("insert into names (id, name) values (?,?);");
PreparedStatement ps4 = conn.prepareStatement("insert into emails (id, email) values (?,?);");
File accountsDir = new File(ACCOUNTS_DIR);
File[] accounts = accountsDir.listFiles();
for (File account : accounts) {
if (account.getName().equals("last.txt") || account.getName().endsWith(".hasCommits")
|| account.getName().endsWith(".noHasCommits")) continue;
String json = readJson(account, true);
if (json.trim().length() == 0) continue;
try {
JSONObject o = new JSONObject(json);
int accId = Integer.parseInt(account.getName());
String username = o.optString("username");
if (username != null) username = cleanup(username);
String name = o.optString("name");
if (name != null) name = cleanup(name);
if (!isLegalName(name)) {
name = null;
}
String email = o.optString("email");
if (email != null) email = cleanup(email);
ps5.setInt(1, accId);
if (isEmpty(username)) {
ps5.setNull(2, Types.VARCHAR);
} else {
ps5.setString(2, username);
}
if (isEmpty(name)) {
ps5.setNull(3, Types.VARCHAR);
} else {
ps5.setString(3, name);
}
if (isEmpty(email)) {
ps5.setNull(4, Types.VARCHAR);
} else {
ps5.setString(4, email);
}
ps5.execute();
boolean found = false;
for (Account acc : accts) {
if (!isEmpty(email) && acc.emails.contains(email)) {
if (!isEmpty(username) && !acc.usernames.contains(username)) {
acc.usernames.add(username);
}
if (!isEmpty(name) && !acc.names.contains(name)) {
acc.names.add(name);
}
if (acc.accountId == -1) acc.accountId = accId;
found = true;
break;
}
if (!isEmpty(name) && acc.names.contains(name) && isValidNameForSearch(name)) {
if (!isEmpty(username) && !acc.usernames.contains(username)) {
acc.usernames.add(username);
}
if (!isEmpty(email) && !acc.emails.contains(email)) {
acc.emails.add(email);
}
if (acc.accountId == -1) acc.accountId = accId;
found = true;
break;
}
if (!isEmpty(username) && acc.usernames.contains(username)) {
if (!isEmpty(name) && !acc.names.contains(name)) {
acc.names.add(name);
}
if (!isEmpty(email) && !acc.emails.contains(email)) {
acc.emails.add(email);
}
if (acc.accountId == -1) acc.accountId = accId;
found = true;
break;
}
}
if (found) {
continue;
}
id++;
Account acc = new Account();
acc.id = id;
acc.accountId = accId;
boolean hasData = false;
if (!isEmpty(email)) {
acc.emails.add(email);
hasData = true;
}
if (!isEmpty(name)) {
acc.names.add(name);
hasData = true;
}
if (!isEmpty(username)) {
acc.usernames.add(username);
hasData = true;
}
if (hasData) {
accts.add(acc);
}
} catch (Exception ex) {
System.out.println("Unable to parse account " + account.getName());
System.out.println(json);
throw ex;
}
}
for (Account acc : accts) {
for (String username : acc.usernames) {
ps2.setInt(1, acc.id);
ps2.setString(2, username);
ps2.execute();
}
for (String name : acc.names) {
ps3.setInt(1, acc.id);
ps3.setString(2, name);
ps3.execute();
}
for (String email : acc.emails) {
ps4.setInt(1, acc.id);
ps4.setString(2, email);
ps4.execute();
}
String username = null;
String name = null;
String email = null;
if (acc.usernames.size() > 0) {
username = acc.usernames.get(0);
}
if (acc.names.size() > 0) {
name = acc.names.get(0);
}
if (acc.emails.size() > 0) {
email = acc.emails.get(0);
}
ps1.setInt(1, acc.id);
ps1.setInt(2, acc.accountId);
if (isEmpty(username)) {
ps1.setNull(3, Types.VARCHAR);
} else {
ps1.setString(3, username);
}
if (isEmpty(name)) {
ps1.setNull(4, Types.VARCHAR);
} else {
ps1.setString(4, name);
}
if (isEmpty(email)) {
ps1.setNull(5, Types.VARCHAR);
} else {
ps1.setString(5, email);
}
ps1.execute();
}
ps1.close();
ps2.close();
ps3.close();
ps4.close();
ps5.close();
return accts;
}
@SuppressWarnings("unchecked")
private static void processStats(Connection conn) throws Exception {
PreparedStatement ps1 = conn.prepareStatement("insert into all_commits (project, commits, name, email) values (?,?,?,?);");
PreparedStatement ps2 = conn.prepareStatement("insert into translations_commits (project, commits, name, email) values (?,?,?,?);");
File statsDir = new File(STATS_DIR);
Collection<File> allStats = FileUtils.listFiles(statsDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(ALL_STATS_FILENAME);
}
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().equals(ALL_STATS_FILENAME);
}
}, TrueFileFilter.INSTANCE);
for (File stats : allStats) {
String project = stats.getPath().replaceAll("\\\\", "/").replaceFirst(STATS_DIR, "");
project = project.substring(0, project.lastIndexOf("/"));
BufferedReader br = new BufferedReader(new FileReader(stats));
String line = null;
while ((line = br.readLine()) != null) {
int commits = Integer.parseInt(line.substring(0, line.indexOf("\t")).trim());
String name = cleanup(line.substring(line.indexOf("\t")+1,line.lastIndexOf("<")).trim());
String email = cleanup(line.substring(line.lastIndexOf("<")+1, line.length()-1).trim());
ps1.setString(1, project);
ps1.setInt(2, commits);
if (isEmpty(name)) {
ps1.setNull(3, Types.VARCHAR);
} else {
ps1.setString(3, name);
}
if (isEmpty(email)) {
ps1.setNull(4, Types.VARCHAR);
} else {
ps1.setString(4, email);
}
ps1.execute();
}
br.close();
}
Collection<File> translationStats = FileUtils.listFiles(statsDir, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(TRANSLATIONS_STATS_FILENAME);
}
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().equals(TRANSLATIONS_STATS_FILENAME);
}
}, TrueFileFilter.INSTANCE);
for (File stats : translationStats) {
String project = stats.getPath().replaceAll("\\\\", "/").replaceFirst(STATS_DIR, "");
project = project.substring(0, project.lastIndexOf("/"));
BufferedReader br = new BufferedReader(new FileReader(stats));
String line = null;
while ((line = br.readLine()) != null) {
int commits = Integer.parseInt(line.substring(0, line.indexOf("\t")).trim());
String name = cleanup(line.substring(line.indexOf("\t")+1,line.lastIndexOf("<")).trim());
String email = cleanup(line.substring(line.lastIndexOf("<")+1, line.length()-1).trim());
ps2.setString(1, project);
ps2.setInt(2, commits);
if (isEmpty(name)) {
ps2.setNull(3, Types.VARCHAR);
} else {
ps2.setString(3, name);
}
if (isEmpty(email)) {
ps2.setNull(4, Types.VARCHAR);
} else {
ps2.setString(4, email);
}
ps2.execute();
}
br.close();
}
ps1.close();
ps2.close();
}
private static boolean isEmpty(String src) {
return src == null || src.trim().length() == 0;
}
private static List<Account> readWellKnownAccounts() throws Exception {
BufferedReader br = new BufferedReader(new FileReader(WELL_KNOWN_ACCOUNTS));
String line = null;
List<Account> accounts = new ArrayList<>();
int i = 1;
while ((line = br.readLine()) != null) {
if (line.length() == 0) continue;
String[] fields = line.split("\\|");
Account acc = new Account();
acc.id = i;
acc.names.add(fields[0].trim());
String[] usernames = fields[1].trim().split("/");
for (String username : usernames) {
acc.usernames.add(username.trim());
}
for (int j = 2; j < fields.length; j++) {
acc.emails.add(fields[j].trim());
}
accounts.add(acc);
i++;
}
br.close();
return accounts;
}
private static String readJson(File json, boolean hasheader) throws Exception {
FileReader fr = new FileReader(json);
if (hasheader) {
fr.read(new char[5]);
}
StringBuffer sb = new StringBuffer();
char[] data = new char[10240];
int read = -1;
while ((read = fr.read(data, 0, 10240)) != -1) {
sb.append(data, 0, read);
}
fr.close();
return sb.toString();
}
private static String cleanup(String src) {
String dst = src;
int s = src.indexOf("(");
int e = src.indexOf(")");
if (s != -1 && s < e) {
dst = dst.substring(0, s) + dst.substring(e + 1);
}
s = dst.indexOf("[");
e = dst.indexOf("]");
if (s != -1 && s < e) {
dst = dst.substring(0, s) + dst.substring(e + 1);
}
s = dst.indexOf("~");
if (s != -1) {
dst = dst.substring(0, s);
}
dst = dst.replaceAll("\\|", "");
dst = dst.replaceAll("\u200e", "");
dst = dst.replaceAll("\u200f", "");
return dst.replaceAll(" ", " ").trim();
}
private static boolean isLegalName(String name) {
return name == null || !(name.contains("?") || name.equals("DO NOT USE"));
}
private static boolean isValidNameForSearch(String name) {
return name.indexOf(" ") != -1 && name.length() >= 5 && !name.equals("John Smith") && !name.equals("John Doe");
}
private static boolean userHasCommits(int id, int accountId, String name, String email) {
InputStream is = null;
String url = null;
try {
if (id <= wellKnownAccounts) {
return true;
}
if (new File(ACCOUNTS_DIR, accountId + ".hasCommits").exists()) {
return true;
}
File noHasCommits = new File(ACCOUNTS_DIR, accountId + ".noHasCommits");
if (noHasCommits.exists() && (System.currentTimeMillis() - noHasCommits.lastModified()) < 2592000000L) { // 30 days
return false;
}
String owner = name + " <" + email + ">";
if (isEmpty(name)) {
owner = name + " <" + email + ">";
}
url = "http://review.cyanogenmod.org/changes/?q=status:merged+owner:\"" + owner+ "\"&limit=1";
owner = URLEncoder.encode(owner, "UTF-8");
is = new URL("http://review.cyanogenmod.org/changes/?q=status:merged+owner:\"" + owner+ "\"&limit=1").openStream();
byte[] data = new byte[11];
int read = is.read(data);
LOGGER.info ("Fetched " + url + ": " + (read > 8));
return read > 8;
} catch (Exception e) {
LOGGER.info ("Fetched " + url + ": error");
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) { }
}
}
return false;
}
public static void generateCloud(Connection conn) throws Exception {
final List<WordFrequency> wordFrequencies = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(CLOUD_DATA));
String line = null;
while ((line = reader.readLine()) != null) {
String record = line.trim();
if (record.length() > 0) {
int pos = record.indexOf(",");
int pos2 = record.indexOf(",", pos+1);
int pos3 = record.indexOf("|");
int id = Integer.parseInt(record.substring(0, pos));
int freq = Integer.parseInt(record.substring(pos+1, pos2));
String word = record.substring(pos2+1, pos3);
String filter = record.substring(pos3+1);
if (word.length() <= 0) {
continue;
}
wordFrequencies.add(new WordFrequency(id, word, filter, freq));
}
}
reader.close();
int size = readLastCloudSize();
int increment = DEFAULT_CLOUD_INCREMENT;
while (true) {
convertSvgToPng(CLOUD_BG_SVG, CLOUD_BG_PNG, 1024, size, null);
final WordCloud wordCloud = new WordCloud(size, size, CollisionMode.RECTANGLE, true);
final String[] EXTRA_WORDS = {"cid", "cyanogenmod", "android", "aosp",
"nexus", "bacon", "adb", "apk", "dalvik", "droid", "logcat", "fastboot"};
Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(CLOUD_FONT));
wordCloud.setCloudFont(new CloudFont(font));
wordCloud.setPadding(1);
wordCloud.setBackground(new PixelBoundryBackground(new FileInputStream(CLOUD_BG_PNG)));
wordCloud.setBackgroundColor(new Color(0x474647));
wordCloud.setColorPalette(new ColorPalette(new Color(0x6199b9)));
FontScalar scalar = new SqrtFontScalar(12, 24);
wordCloud.setFontScalar(scalar);
wordCloud.build(wordFrequencies);
boolean done = false;
int i;
for (i = 0; i <=4; i++) {
scalar.reduceBy(1);
if (wordCloud.fill(wordFrequencies, i+1)) {
done = true;
break;
}
}
if (!done) {
int newsize = size + DEFAULT_CLOUD_INCREMENT;
LOGGER.info("Word cloud doesn't fit in " + size + "x" + size +
". Retrying at " + newsize + "x" + newsize +" ...");
wordCloud.writeToImage(CLOUD_IMAGE + "." + size + "x" + size + ".png");
size += increment;
continue;
}
scalar.reduceBy(4-i);
wordCloud.printSkippedWords();
wordCloud.fillWithOtherWords(wordFrequencies, EXTRA_WORDS);
LOGGER.info("Saving wordcloud. Image size " + size + "x" + size);
wordCloud.drawForgroundToBackground();
wordCloud.writeToImage(CLOUD_IMAGE);
wordCloud.writeWordsToFile(CLOUD_DATA_OUTPUT, size);
break;
}
// Write metadainfo and save last size
writeLastCloudSize(size);
writeMetadataInfo(conn, size);
// Write the cloud to an SVG
writeToSvg(CLOUD_SVG, size, new Color(0x6199b9), new Color(0x474647));
}
private static void writeToSvg(String svg, int size, Color color, Color bgcolor) throws Exception {
String c = String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
String bg = String.format("#%02x%02x%02x", bgcolor.getRed(), bgcolor.getGreen(), bgcolor.getBlue());
FileWriter fw = new FileWriter(svg);
fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
fw.write("<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\r\n");
fw.write("viewBox=\"0 0 " + size + " " + size + "\"\r\n");
fw.write("version=\"1.1\"\r\n");
fw.write("width=\"" + size + "\"\r\n");
fw.write("height=\"" + size + "\"\r\n");
fw.write("text-rendering=\"geometricPrecision\">\r\n");
fw.write("<defs >\r\n");
fw.write("<font-face font-family=\"Roboto\">\r\n");
fw.write("<font-face-src>\r\n");
fw.write("<font-face-uri xlink:href=\"../Roboto-Bold.svg#Roboto-Bold\">\r\n");
fw.write("<font-face-format string=\"svg\"/>\r\n");
fw.write("</font-face-uri>\r\n");
fw.write("</font-face-src>\r\n");
fw.write("</font-face>\r\n");
fw.write("</defs>\r\n");
fw.write("<g>\r\n");
fw.write("<rect width=\"" + size + "\" height=\"" + size + "\" style=\"fill: " + bg + ";\"/>\r\n");
BufferedReader br = new BufferedReader(new FileReader(CLOUD_DATA_OUTPUT));
String line=null;
br.readLine();
while ((line = br.readLine()) != null) {
int lastIndex = 0;
int index = line.indexOf(',', lastIndex);
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float x = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float y = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float w = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float h = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
int r = Integer.parseInt(line.substring(lastIndex, index));
lastIndex = index+1;
index = line.indexOf(',', lastIndex);
float fs = Float.parseFloat(line.substring(lastIndex, index));
lastIndex = index+1;
String xx = line.substring(lastIndex);
String n = xx.substring(0, xx.indexOf("|"));
if (r == 0) {
fw.write("<text x=\"" + x + "\" y=\"" + y + "\" font-family=\"'Roboto'\" font-size=\"" + fs + "\" style=\"fill: " + c + "\">" + n + "</text>\r\n");
} else {
if (r == -1) {
fw.write("<text x=\"" + x + "\" y=\"" + y + "\" transform=\"translate(" + (w / 2) + "," + (h - (w / 2)) + ")rotate(-90 " + x + "," + y + ")\" font-family=\"'Roboto'\" font-size=\"" + fs + "\" style=\"fill: " + c + "\">" + n + "</text>\r\n");
} else {
fw.write("<text x=\"" + x + "\" y=\"" + y + "\" transform=\"translate(0,-" + (w / 2) + ")rotate(90 " + x + "," + y + ")\" font-family=\"'Roboto'\" font-size=\"" + fs + "\" style=\"fill: " + c + "\">" + n + "</text>\r\n");
}
}
}
br.close();
fw.write("</g>\r\n");
fw.write("</svg>\r\n");
fw.close();
}
private static void convertSvgToPng(String svg, String png, int origSize, int dstSize, Color bg) throws Exception {
String svg_URI_input = Paths.get(svg).toUri().toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
OutputStream png_ostream = new FileOutputStream(png);
TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);
PNGTranscoder my_converter = new PNGTranscoder();
my_converter.addTranscodingHint( PNGTranscoder.KEY_WIDTH, new Float( dstSize ) );
my_converter.addTranscodingHint( PNGTranscoder.KEY_HEIGHT, new Float( dstSize ) );
my_converter.addTranscodingHint( PNGTranscoder.KEY_AOI, new Rectangle( 0, 0, origSize, origSize) );
if (bg != null) {
my_converter.addTranscodingHint( PNGTranscoder.KEY_BACKGROUND_COLOR, bg);
}
my_converter.transcode(input_svg_image, output_png_image);
png_ostream.flush();
png_ostream.close();
}
private static int readLastCloudSize() throws Exception {
File file = new File(LAST_CLOUD_SIZE);
if (!file.exists()) {
return DEFAULT_CLOUD_SIZE;
}
BufferedReader br = new BufferedReader(new FileReader(file));
try {
return Integer.parseInt(br.readLine());
} catch (Exception ex) {
} finally {
br.close();
}
return DEFAULT_CLOUD_SIZE;
}
private static void writeLastCloudSize(int size) throws Exception {
File file = new File(LAST_CLOUD_SIZE);
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(size));
bw.close();
}
}
| close metadata db prior to compress it
Signed-off-by: Jorge Ruesga <[email protected]>
| source/src/main/java/CloudGenerator.java | close metadata db prior to compress it | <ide><path>ource/src/main/java/CloudGenerator.java
<ide>
<ide> public static void main(String[] args) throws Exception {
<ide> boolean FROM_GERRIT = true;
<add> boolean closed = false;
<ide>
<ide> new File(DB_NAME).delete();
<ide> new File(CLOUD_DB_FILE).delete();
<ide> LOGGER.info("Generating cloud");
<ide> generateCloud(connMetadata);
<ide> generateMetadata(conn, connMetadata);
<add>
<add> // Close the database prior to compress it
<add> connMetadata.commit();
<add> connMetadata.close();
<ide> generateCloudZip();
<ide>
<ide> } finally {
<ide> conn.commit();
<ide> conn.close();
<del> connMetadata.commit();
<del> connMetadata.close();
<add> if (!connMetadata.isClosed()) {
<add> connMetadata.commit();
<add> connMetadata.close();
<add> }
<ide> }
<ide> }
<ide> |
|
Java | mit | 600ae3b0af461f953f4d88a0060d9b61aa02e70e | 0 | icode/ameba,icode/ameba,wangscript/ameba,xiangyong/ameba | package ameba.db.ebean.internal;
import ameba.db.ebean.EbeanUtils;
import ameba.db.model.Model;
import ameba.lib.LoggerOwner;
import com.avaje.ebean.*;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.api.ScopeTrans;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.internal.util.collection.Ref;
import org.glassfish.jersey.internal.util.collection.Refs;
import javax.annotation.Nullable;
import javax.persistence.OptimisticLockException;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.*;
import java.net.URI;
import java.util.List;
import java.util.Set;
/**
* <p>Abstract ModelResourceStructure class.</p>
*
* @author icode
* @since 0.1.6e
*/
public abstract class ModelResourceStructure<ID, M extends Model> extends LoggerOwner {
protected final SpiEbeanServer server;
protected Class<M> modelType;
protected String defaultFindOrderBy;
@Context
protected UriInfo uriInfo;
private BeanDescriptor descriptor;
/**
* <p>Constructor for ModelResourceStructure.</p>
*
* @param modelType a {@link java.lang.Class} object.
*/
public ModelResourceStructure(Class<M> modelType) {
this(modelType, (SpiEbeanServer) Ebean.getServer(null));
}
/**
* <p>Constructor for ModelResourceStructure.</p>
*
* @param modelType a {@link java.lang.Class} object.
* @param server a {@link com.avaje.ebeaninternal.api.SpiEbeanServer} object.
*/
public ModelResourceStructure(Class<M> modelType, SpiEbeanServer server) {
this.modelType = modelType;
this.server = server;
}
/**
* <p>getModelBeanDescriptor.</p>
*
* @return a {@link com.avaje.ebeaninternal.server.deploy.BeanDescriptor} object.
*/
protected BeanDescriptor getModelBeanDescriptor() {
if (descriptor == null) {
descriptor = server.getBeanDescriptor(modelType);
}
return descriptor;
}
/**
* convert string to id
*
* @param id id string
* @return ID object
* @see ModelResourceStructure#deleteMultiple(Object, PathSegment)
*/
@SuppressWarnings("unchecked")
protected ID stringToId(String id) {
return (ID) getModelBeanDescriptor().convertId(id);
}
/**
* convert string to id
*
* @param id string id
* @return ID
* @throws BadRequestException response status 400
*/
protected final ID tryConvertId(Object id) {
try {
return stringToId(id.toString());
} catch (Exception e) {
throw new BadRequestException("Id syntax error", e);
}
}
/**
* convert id to string for insert
*
* @param id id object
* @return id string
* @see ModelResourceStructure#insert(Model)
* @see ModelResourceStructure#patch(Object, Model)
*/
protected String idToString(@NotNull ID id) {
return id.toString();
}
/**
* <p>setForInsertId.</p>
*
* @param model a M object.
*/
protected void setForInsertId(final M model) {
BeanDescriptor descriptor = getModelBeanDescriptor();
EntityBeanIntercept intercept = ((EntityBean) model)._ebean_getIntercept();
BeanProperty idProp = descriptor.getIdProperty();
if (idProp != null) {
idProp.setValue((EntityBean) model, null);
intercept.setPropertyUnloaded(idProp.getPropertyIndex());
}
}
protected void flushBatch() {
Transaction t = server.currentTransaction();
if (t != null)
t.flushBatch();
}
/**
* Insert a model.
* <p/>
* success status 201
*
* @param model the model to insert
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.POST
* @see ameba.db.ebean.internal.AbstractModelResource#insert(Model)
*/
@SuppressWarnings("unchecked")
public Response insert(@NotNull @Valid final M model) throws Exception {
setForInsertId(model);
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preInsertModel(model);
insertModel(model);
postInsertModel(model);
}
});
ID id = (ID) server.getBeanId(model);
return Response.created(buildLocationUri(id)).build();
}
/**
* <p>preInsertModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void preInsertModel(final M model) throws Exception {
}
/**
* <p>insertModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void insertModel(final M model) throws Exception {
server.insert(model);
flushBatch();
}
/**
* <p>postInsertModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void postInsertModel(final M model) throws Exception {
}
/**
* replace or insert a model.
* <p/>
* success replace status 204
* <br/>
* fail replace but inserted status 201
*
* @param id the unique id of the model
* @param model the model to update
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.PUT
* @see ameba.db.ebean.internal.AbstractModelResource#replace(Object, Model)
*/
public Response replace(@PathParam("id") final ID id, @NotNull @Valid final M model) throws Exception {
BeanDescriptor descriptor = getModelBeanDescriptor();
final ID mId = tryConvertId(id);
descriptor.convertSetId(mId, (EntityBean) model);
EbeanUtils.forceUpdateAllProperties(server, model);
final Response.ResponseBuilder builder = Response.noContent();
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preReplaceModel(model);
replaceModel(model);
postReplaceModel(model);
}
}, new TxRunnable() {
@Override
public void run() throws Exception {
logger().debug("not found model record, insert a model record.");
preInsertModel(model);
insertModel(model);
postInsertModel(model);
builder.status(Response.Status.CREATED).location(buildLocationUri(mId, true));
}
});
return builder.build();
}
/**
* <p>preReplaceModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void preReplaceModel(final M model) throws Exception {
}
/**
* <p>replaceModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void replaceModel(final M model) throws Exception {
server.update(model, null, true);
}
/**
* <p>postReplaceModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void postReplaceModel(final M model) throws Exception {
}
/**
* Update a model items.
* <p/>
* success status 204
* <br/>
* fail status 422
*
* @param id the unique id of the model
* @param model the model to update
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see ameba.core.ws.rs.PATCH
* @see ameba.db.ebean.internal.AbstractModelResource#patch(Object, Model)
*/
public Response patch(@PathParam("id") final ID id, @NotNull final M model) throws Exception {
BeanDescriptor descriptor = getModelBeanDescriptor();
descriptor.convertSetId(tryConvertId(id), (EntityBean) model);
final Response.ResponseBuilder builder = Response.noContent()
.contentLocation(uriInfo.getAbsolutePath());
return executeTx(new TxCallable<Response>() {
@Override
public Response call() throws Exception {
prePatchModel(model);
patchModel(model);
postPatchModel(model);
return builder.build();
}
}, new TxCallable<Response>() {
@Override
public Response call() {
// id 无法对应数据。实体对象和补丁都正确,但无法处理请求,所以返回422
return builder.status(422).build();
}
});
}
/**
* <p>prePatchModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void prePatchModel(final M model) throws Exception {
}
/**
* <p>patchModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void patchModel(final M model) throws Exception {
server.update(model, null, false);
}
/**
* <p>postPatchModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void postPatchModel(final M model) throws Exception {
}
/**
* Delete multiple model using Id's from the Matrix.
* <p/>
* success status 200
* <br/>
* fail status 404
* <br/>
* logical delete status 202
*
* @param id The id use for path matching type
* @param ids The ids in the form "/resource/id1" or "/resource/id1;id2;id3"
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.DELETE
* @see ameba.db.ebean.internal.AbstractModelResource#deleteMultiple(Object, PathSegment)
*/
public Response deleteMultiple(@NotNull @PathParam("ids") ID id,
@NotNull @PathParam("ids") final PathSegment ids) throws Exception {
final ID firstId = tryConvertId(ids.getPath());
Set<String> idSet = ids.getMatrixParameters().keySet();
final Response.ResponseBuilder builder = Response.noContent();
final TxRunnable failProcess = new TxRunnable() {
@Override
public void run() {
builder.status(Response.Status.NOT_FOUND);
}
};
if (!idSet.isEmpty()) {
final Set<ID> idCollection = Sets.newLinkedHashSet();
idCollection.add(firstId);
idCollection.addAll(Collections2.transform(idSet, new Function<String, ID>() {
@Nullable
@Override
public ID apply(String input) {
return tryConvertId(input);
}
}));
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preDeleteMultipleModel(idCollection);
if (!deleteMultipleModel(idCollection)) {
builder.status(Response.Status.ACCEPTED);
}
postDeleteMultipleModel(idCollection);
}
}, failProcess);
} else {
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preDeleteModel(firstId);
if (!deleteModel(firstId)) {
builder.status(Response.Status.ACCEPTED);
}
postDeleteModel(firstId);
}
}, failProcess);
}
return builder.build();
}
/**
* <p>preDeleteMultipleModel.</p>
*
* @param idCollection a {@link java.util.Set} object.
* @throws java.lang.Exception if any.
*/
protected void preDeleteMultipleModel(Set<ID> idCollection) throws Exception {
}
/**
* delete multiple Model
*
* @param idCollection model id collection
* @return delete from physical device, if logical delete return false, response status 202
* @throws java.lang.Exception if any.
*/
protected boolean deleteMultipleModel(Set<ID> idCollection) throws Exception {
server.delete(modelType, idCollection);
return true;
}
/**
* <p>postDeleteMultipleModel.</p>
*
* @param idCollection a {@link java.util.Set} object.
* @throws java.lang.Exception if any.
*/
protected void postDeleteMultipleModel(Set<ID> idCollection) throws Exception {
}
/**
* <p>preDeleteModel.</p>
*
* @param id a ID object.
* @throws java.lang.Exception if any.
*/
protected void preDeleteModel(ID id) throws Exception {
}
/**
* delete a model
*
* @param id model id
* @return delete from physical device, if logical delete return false, response status 202
* @throws java.lang.Exception if any.
*/
protected boolean deleteModel(ID id) throws Exception {
server.delete(modelType, id);
return true;
}
/**
* <p>postDeleteModel.</p>
*
* @param id a ID object.
* @throws java.lang.Exception if any.
*/
protected void postDeleteModel(ID id) throws Exception {
}
/**
* Find a model or model list given its Ids.
*
* @param id The id use for path matching type
* @param ids the id of the model.
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.GET
* @see ameba.db.ebean.internal.AbstractModelResource#findByIds
*/
public Response findByIds(@NotNull @PathParam("ids") ID id,
@NotNull @PathParam("ids") final PathSegment ids) throws Exception {
final Query<M> query = server.find(modelType);
final ID firstId = tryConvertId(ids.getPath());
Set<String> idSet = ids.getMatrixParameters().keySet();
Object model;
final TxRunnable configureQuery = new TxRunnable() {
@Override
public void run() throws Exception {
configDefaultQuery(query);
configFindByIdsQuery(query);
applyUriQuery(query, false);
}
};
if (!idSet.isEmpty()) {
final List<ID> idCollection = Lists.newArrayList();
idCollection.add(firstId);
idCollection.addAll(Collections2.transform(idSet, new Function<String, ID>() {
@Nullable
@Override
public ID apply(String input) {
return tryConvertId(input);
}
}));
model = executeTx(new TxCallable() {
@Override
public Object call() throws Exception {
configureQuery.run();
List<M> m = query.where().idIn(idCollection).findList();
return processFoundByIdsModelList(m);
}
});
} else {
model = executeTx(new TxCallable<Object>() {
@Override
public Object call() throws Exception {
configureQuery.run();
M m = query.setId(firstId).findUnique();
return processFoundByIdModel(m);
}
});
}
if (model != null)
return Response.ok(model).build();
else
throw new NotFoundException();
}
/**
* Configure the "Find By Ids" query.
* <p>
* This is only used when no PathProperties where set via UriOptions.
* </p>
* <p>
* This effectively controls the "default" query used to render this model.
* </p>
*
* @param query a {@link com.avaje.ebean.Query} object.
* @throws java.lang.Exception if any.
*/
protected void configFindByIdsQuery(final Query<M> query) throws Exception {
}
/**
* <p>processFoundModel.</p>
*
* @param model a M object.
* @return a {@link java.lang.Object} object.
* @throws java.lang.Exception if any.
*/
protected Object processFoundByIdModel(final M model) throws Exception {
return model;
}
protected Object processFoundByIdsModelList(final List<M> models) throws Exception {
return models;
}
/**
* Find the beans for this beanType.
* <p>
* This can use URL query parameters such as order and maxrows to configure
* the query.
* </p>
*
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.GET
* @see ameba.db.ebean.internal.AbstractModelResource#find()
*/
public Response find() throws Exception {
final Query<M> query = server.find(modelType);
if (StringUtils.isNotBlank(defaultFindOrderBy)) {
// see if we should use the default orderBy clause
OrderBy<M> orderBy = query.orderBy();
if (orderBy.isEmpty()) {
query.orderBy(defaultFindOrderBy);
}
}
final Ref<FutureRowCount> rowCount = Refs.emptyRef();
Response.ResponseBuilder builder = Response.ok();
Response response = builder.entity(executeTx(new TxCallable<Object>() {
@Override
public Object call() throws Exception {
configDefaultQuery(query);
configFindQuery(query);
rowCount.set(applyUriQuery(query));
List<M> list = query.findList();
return processFoundModelList(list);
}
})
).build();
applyRowCountHeader(response.getHeaders(), query, rowCount.get());
return response;
}
/**
* Configure the "Find" query.
* <p>
* This is only used when no PathProperties where set via UriOptions.
* </p>
* <p>
* This effectively controls the "default" query used with the find all
* query.
* </p>
*
* @param query a {@link com.avaje.ebean.Query} object.
* @throws java.lang.Exception if any.
*/
protected void configFindQuery(final Query<M> query) throws Exception {
}
/**
* <p>processFoundModelList.</p>
*
* @param list a {@link java.util.List} object.
* @return a {@link java.lang.Object} object.
* @throws java.lang.Exception if any.
*/
protected Object processFoundModelList(final List<M> list) throws Exception {
return list;
}
/**
* all query config default query
*
* @param query query
* @throws java.lang.Exception if any.
*/
protected void configDefaultQuery(final Query<M> query) throws Exception {
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// ///////////////////////////////////
/////////////////////////////////// useful method block ///////////////////////////////////
/////////////////////////////////// ///////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* apply uri query parameter on query
*
* @param query Query
* @param needPageList need page list
* @return page list count or null
* @see EbeanModelInterceptor#applyUriQuery(MultivaluedMap, Query, boolean)
*/
protected FutureRowCount applyUriQuery(final Query<M> query, boolean needPageList) {
return EbeanModelInterceptor.applyUriQuery(uriInfo.getQueryParameters(), query, needPageList);
}
/**
* <p>applyUriQuery.</p>
*
* @param query a {@link com.avaje.ebean.Query} object.
* @return a {@link com.avaje.ebean.FutureRowCount} object.
*/
protected FutureRowCount applyUriQuery(final Query<M> query) {
return applyUriQuery(query, true);
}
/**
* <p>applyRowCountHeader.</p>
*
* @param headerParams a {@link javax.ws.rs.core.MultivaluedMap} object.
* @param query a {@link com.avaje.ebean.Query} object.
* @param rowCount a {@link com.avaje.ebean.FutureRowCount} object.
*/
protected void applyRowCountHeader(MultivaluedMap<String, Object> headerParams, Query query, FutureRowCount rowCount) {
EbeanModelInterceptor.applyRowCountHeader(headerParams, query, rowCount);
}
/**
* <p>processTransactionError.</p>
*
* @param callable a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @param process a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @throws java.lang.Exception if any.
*/
protected <T> T processTransactionError(TxCallable<T> callable, TxCallable<T> process) throws Exception {
try {
return callable.call();
} catch (Exception e) {
return processCheckRowCountError(e, e, process);
}
}
protected <T> T processCheckRowCountError(Exception root, Throwable e, TxCallable<T> process) throws Exception {
if (e == null) {
throw root;
}
if (e instanceof OptimisticLockException) {
if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) {
if (process != null)
return process.call();
}
}
return processCheckRowCountError(root, e.getCause(), process);
}
/**
* <p>executeTx.</p>
*
* @param scope a {@link com.avaje.ebean.TxScope} object.
* @param r a {@link ameba.db.ebean.internal.ModelResourceStructure.TxRunnable} object.
* @throws java.lang.Exception if any.
*/
protected void executeTx(TxScope scope, final TxRunnable r, final TxRunnable errorHandler) throws Exception {
final ScopeTrans scopeTrans = server.createScopeTrans(scope);
configureTransDefault();
processTransactionError(new TxCallable() {
@Override
public Object call() throws Exception {
try {
r.run();
} catch (Error e) {
throw scopeTrans.caughtError(e);
} catch (Exception e) {
throw scopeTrans.caughtThrowable(e);
} finally {
scopeTrans.onFinally();
}
return null;
}
}, errorHandler != null ? new TxCallable() {
@Override
public Object call() throws Exception {
errorHandler.run();
return null;
}
} : null);
}
/**
* <p>executeTx.</p>
*
* @param r a {@link ameba.db.ebean.internal.ModelResourceStructure.TxRunnable} object.
* @throws java.lang.Exception if any.
*/
protected void executeTx(TxRunnable r) throws Exception {
executeTx(null, r, null);
}
protected void executeTx(TxRunnable r, TxRunnable errorHandler) throws Exception {
executeTx(null, r, errorHandler);
}
/**
* <p>executeTx.</p>
*
* @param c a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @param <O> a O object.
* @return a O object.
* @throws java.lang.Exception if any.
*/
protected <O> O executeTx(TxCallable<O> c) throws Exception {
return executeTx(null, c, null);
}
protected <O> O executeTx(TxCallable<O> c, final TxCallable<O> errorHandler) throws Exception {
return executeTx(null, c, errorHandler);
}
/**
* <p>executeTx.</p>
*
* @param scope a {@link com.avaje.ebean.TxScope} object.
* @param c a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @param <O> a O object.
* @return a O object.
* @throws java.lang.Exception if any.
*/
protected <O> O executeTx(TxScope scope, final TxCallable<O> c, final TxCallable<O> errorHandler) throws Exception {
final ScopeTrans scopeTrans = server.createScopeTrans(scope);
configureTransDefault();
return processTransactionError(new TxCallable<O>() {
@Override
public O call() throws Exception {
try {
return c.call();
} catch (Error e) {
throw scopeTrans.caughtError(e);
} catch (Exception e) {
throw scopeTrans.caughtThrowable(e);
} finally {
scopeTrans.onFinally();
}
}
}, errorHandler);
}
protected void configureTransDefault() {
}
/**
* <p>processTransactionError.</p>
*
* @param callable a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @throws java.lang.Exception if any.
*/
protected <T> T processTransactionError(TxCallable<T> callable) throws Exception {
return processTransactionError(callable, null);
}
/**
* <p>buildLocationUri.</p>
*
* @param id a ID object.
* @param useTemplate use current template
* @return a {@link java.net.URI} object.
*/
protected URI buildLocationUri(ID id, boolean useTemplate) {
if (id == null) {
throw new NotFoundException();
}
UriBuilder ub = uriInfo.getAbsolutePathBuilder();
if (useTemplate) {
return ub.build(id);
} else {
return ub.path(idToString(id)).build();
}
}
protected URI buildLocationUri(ID id) {
return buildLocationUri(id, false);
}
protected interface TxRunnable {
void run() throws Exception;
}
protected interface TxCallable<O> {
O call() throws Exception;
}
}
| src/main/java/ameba/db/ebean/internal/ModelResourceStructure.java | package ameba.db.ebean.internal;
import ameba.db.ebean.EbeanUtils;
import ameba.db.model.Model;
import ameba.lib.LoggerOwner;
import com.avaje.ebean.*;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.api.ScopeTrans;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.internal.util.collection.Ref;
import org.glassfish.jersey.internal.util.collection.Refs;
import javax.annotation.Nullable;
import javax.persistence.OptimisticLockException;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.*;
import java.net.URI;
import java.util.List;
import java.util.Set;
/**
* <p>Abstract ModelResourceStructure class.</p>
*
* @author icode
* @since 0.1.6e
*/
public abstract class ModelResourceStructure<ID, M extends Model> extends LoggerOwner {
protected final SpiEbeanServer server;
protected Class<M> modelType;
protected String defaultFindOrderBy;
@Context
protected UriInfo uriInfo;
private BeanDescriptor descriptor;
/**
* <p>Constructor for ModelResourceStructure.</p>
*
* @param modelType a {@link java.lang.Class} object.
*/
public ModelResourceStructure(Class<M> modelType) {
this(modelType, (SpiEbeanServer) Ebean.getServer(null));
}
/**
* <p>Constructor for ModelResourceStructure.</p>
*
* @param modelType a {@link java.lang.Class} object.
* @param server a {@link com.avaje.ebeaninternal.api.SpiEbeanServer} object.
*/
public ModelResourceStructure(Class<M> modelType, SpiEbeanServer server) {
this.modelType = modelType;
this.server = server;
}
/**
* <p>getModelBeanDescriptor.</p>
*
* @return a {@link com.avaje.ebeaninternal.server.deploy.BeanDescriptor} object.
*/
protected BeanDescriptor getModelBeanDescriptor() {
if (descriptor == null) {
descriptor = server.getBeanDescriptor(modelType);
}
return descriptor;
}
/**
* convert string to id
*
* @param id id string
* @return ID object
* @see ModelResourceStructure#deleteMultiple(Object, PathSegment)
*/
@SuppressWarnings("unchecked")
protected ID stringToId(String id) {
return (ID) getModelBeanDescriptor().convertId(id);
}
/**
* convert string to id
*
* @param id string id
* @return ID
* @throws BadRequestException response status 400
*/
protected final ID tryConvertId(Object id) {
try {
return stringToId(id.toString());
} catch (Exception e) {
throw new BadRequestException("Id syntax error", e);
}
}
/**
* convert id to string for insert
*
* @param id id object
* @return id string
* @see ModelResourceStructure#insert(Model)
* @see ModelResourceStructure#patch(Object, Model)
*/
protected String idToString(@NotNull ID id) {
return id.toString();
}
/**
* <p>setForInsertId.</p>
*
* @param model a M object.
*/
protected void setForInsertId(final M model) {
BeanDescriptor descriptor = getModelBeanDescriptor();
EntityBeanIntercept intercept = ((EntityBean) model)._ebean_getIntercept();
if (descriptor.hasIdProperty(intercept)) {
BeanProperty idProp = descriptor.getIdProperty();
idProp.setValue((EntityBean) model, null);
intercept.setPropertyUnloaded(idProp.getPropertyIndex());
}
}
protected void flushBatch() {
Transaction t = server.currentTransaction();
if (t != null)
t.flushBatch();
}
/**
* Insert a model.
* <p/>
* success status 201
*
* @param model the model to insert
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.POST
* @see ameba.db.ebean.internal.AbstractModelResource#insert(Model)
*/
@SuppressWarnings("unchecked")
public Response insert(@NotNull @Valid final M model) throws Exception {
setForInsertId(model);
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preInsertModel(model);
insertModel(model);
postInsertModel(model);
}
});
ID id = (ID) server.getBeanId(model);
return Response.created(buildLocationUri(id)).build();
}
/**
* <p>preInsertModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void preInsertModel(final M model) throws Exception {
}
/**
* <p>insertModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void insertModel(final M model) throws Exception {
server.insert(model);
flushBatch();
}
/**
* <p>postInsertModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void postInsertModel(final M model) throws Exception {
}
/**
* replace or insert a model.
* <p/>
* success replace status 204
* <br/>
* fail replace but inserted status 201
*
* @param id the unique id of the model
* @param model the model to update
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.PUT
* @see ameba.db.ebean.internal.AbstractModelResource#replace(Object, Model)
*/
public Response replace(@PathParam("id") final ID id, @NotNull @Valid final M model) throws Exception {
BeanDescriptor descriptor = getModelBeanDescriptor();
final ID mId = tryConvertId(id);
descriptor.convertSetId(mId, (EntityBean) model);
EbeanUtils.forceUpdateAllProperties(server, model);
final Response.ResponseBuilder builder = Response.noContent();
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preReplaceModel(model);
replaceModel(model);
postReplaceModel(model);
}
}, new TxRunnable() {
@Override
public void run() throws Exception {
logger().debug("not found model record, insert a model record.");
preInsertModel(model);
insertModel(model);
postInsertModel(model);
builder.status(Response.Status.CREATED).location(buildLocationUri(mId, true));
}
});
return builder.build();
}
/**
* <p>preReplaceModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void preReplaceModel(final M model) throws Exception {
}
/**
* <p>replaceModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void replaceModel(final M model) throws Exception {
server.update(model, null, true);
}
/**
* <p>postReplaceModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void postReplaceModel(final M model) throws Exception {
}
/**
* Update a model items.
* <p/>
* success status 204
* <br/>
* fail status 422
*
* @param id the unique id of the model
* @param model the model to update
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see ameba.core.ws.rs.PATCH
* @see ameba.db.ebean.internal.AbstractModelResource#patch(Object, Model)
*/
public Response patch(@PathParam("id") final ID id, @NotNull final M model) throws Exception {
BeanDescriptor descriptor = getModelBeanDescriptor();
descriptor.convertSetId(tryConvertId(id), (EntityBean) model);
final Response.ResponseBuilder builder = Response.noContent()
.contentLocation(uriInfo.getAbsolutePath());
return executeTx(new TxCallable<Response>() {
@Override
public Response call() throws Exception {
prePatchModel(model);
patchModel(model);
postPatchModel(model);
return builder.build();
}
}, new TxCallable<Response>() {
@Override
public Response call() {
// id 无法对应数据。实体对象和补丁都正确,但无法处理请求,所以返回422
return builder.status(422).build();
}
});
}
/**
* <p>prePatchModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void prePatchModel(final M model) throws Exception {
}
/**
* <p>patchModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void patchModel(final M model) throws Exception {
server.update(model, null, false);
}
/**
* <p>postPatchModel.</p>
*
* @param model a M object.
* @throws java.lang.Exception if any.
*/
protected void postPatchModel(final M model) throws Exception {
}
/**
* Delete multiple model using Id's from the Matrix.
* <p/>
* success status 200
* <br/>
* fail status 404
* <br/>
* logical delete status 202
*
* @param id The id use for path matching type
* @param ids The ids in the form "/resource/id1" or "/resource/id1;id2;id3"
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.DELETE
* @see ameba.db.ebean.internal.AbstractModelResource#deleteMultiple(Object, PathSegment)
*/
public Response deleteMultiple(@NotNull @PathParam("ids") ID id,
@NotNull @PathParam("ids") final PathSegment ids) throws Exception {
final ID firstId = tryConvertId(ids.getPath());
Set<String> idSet = ids.getMatrixParameters().keySet();
final Response.ResponseBuilder builder = Response.noContent();
final TxRunnable failProcess = new TxRunnable() {
@Override
public void run() {
builder.status(Response.Status.NOT_FOUND);
}
};
if (!idSet.isEmpty()) {
final Set<ID> idCollection = Sets.newLinkedHashSet();
idCollection.add(firstId);
idCollection.addAll(Collections2.transform(idSet, new Function<String, ID>() {
@Nullable
@Override
public ID apply(String input) {
return tryConvertId(input);
}
}));
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preDeleteMultipleModel(idCollection);
if (!deleteMultipleModel(idCollection)) {
builder.status(Response.Status.ACCEPTED);
}
postDeleteMultipleModel(idCollection);
}
}, failProcess);
} else {
executeTx(new TxRunnable() {
@Override
public void run() throws Exception {
preDeleteModel(firstId);
if (!deleteModel(firstId)) {
builder.status(Response.Status.ACCEPTED);
}
postDeleteModel(firstId);
}
}, failProcess);
}
return builder.build();
}
/**
* <p>preDeleteMultipleModel.</p>
*
* @param idCollection a {@link java.util.Set} object.
* @throws java.lang.Exception if any.
*/
protected void preDeleteMultipleModel(Set<ID> idCollection) throws Exception {
}
/**
* delete multiple Model
*
* @param idCollection model id collection
* @return delete from physical device, if logical delete return false, response status 202
* @throws java.lang.Exception if any.
*/
protected boolean deleteMultipleModel(Set<ID> idCollection) throws Exception {
server.delete(modelType, idCollection);
return true;
}
/**
* <p>postDeleteMultipleModel.</p>
*
* @param idCollection a {@link java.util.Set} object.
* @throws java.lang.Exception if any.
*/
protected void postDeleteMultipleModel(Set<ID> idCollection) throws Exception {
}
/**
* <p>preDeleteModel.</p>
*
* @param id a ID object.
* @throws java.lang.Exception if any.
*/
protected void preDeleteModel(ID id) throws Exception {
}
/**
* delete a model
*
* @param id model id
* @return delete from physical device, if logical delete return false, response status 202
* @throws java.lang.Exception if any.
*/
protected boolean deleteModel(ID id) throws Exception {
server.delete(modelType, id);
return true;
}
/**
* <p>postDeleteModel.</p>
*
* @param id a ID object.
* @throws java.lang.Exception if any.
*/
protected void postDeleteModel(ID id) throws Exception {
}
/**
* Find a model or model list given its Ids.
*
* @param id The id use for path matching type
* @param ids the id of the model.
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.GET
* @see ameba.db.ebean.internal.AbstractModelResource#findByIds
*/
public Response findByIds(@NotNull @PathParam("ids") ID id,
@NotNull @PathParam("ids") final PathSegment ids) throws Exception {
final Query<M> query = server.find(modelType);
final ID firstId = tryConvertId(ids.getPath());
Set<String> idSet = ids.getMatrixParameters().keySet();
Object model;
final TxRunnable configureQuery = new TxRunnable() {
@Override
public void run() throws Exception {
configDefaultQuery(query);
configFindByIdsQuery(query);
applyUriQuery(query, false);
}
};
if (!idSet.isEmpty()) {
final List<ID> idCollection = Lists.newArrayList();
idCollection.add(firstId);
idCollection.addAll(Collections2.transform(idSet, new Function<String, ID>() {
@Nullable
@Override
public ID apply(String input) {
return tryConvertId(input);
}
}));
model = executeTx(new TxCallable() {
@Override
public Object call() throws Exception {
configureQuery.run();
List<M> m = query.where().idIn(idCollection).findList();
return processFoundByIdsModelList(m);
}
});
} else {
model = executeTx(new TxCallable<Object>() {
@Override
public Object call() throws Exception {
configureQuery.run();
M m = query.setId(firstId).findUnique();
return processFoundByIdModel(m);
}
});
}
if (model != null)
return Response.ok(model).build();
else
throw new NotFoundException();
}
/**
* Configure the "Find By Ids" query.
* <p>
* This is only used when no PathProperties where set via UriOptions.
* </p>
* <p>
* This effectively controls the "default" query used to render this model.
* </p>
*
* @param query a {@link com.avaje.ebean.Query} object.
* @throws java.lang.Exception if any.
*/
protected void configFindByIdsQuery(final Query<M> query) throws Exception {
}
/**
* <p>processFoundModel.</p>
*
* @param model a M object.
* @return a {@link java.lang.Object} object.
* @throws java.lang.Exception if any.
*/
protected Object processFoundByIdModel(final M model) throws Exception {
return model;
}
protected Object processFoundByIdsModelList(final List<M> models) throws Exception {
return models;
}
/**
* Find the beans for this beanType.
* <p>
* This can use URL query parameters such as order and maxrows to configure
* the query.
* </p>
*
* @return a {@link javax.ws.rs.core.Response} object.
* @throws java.lang.Exception if any.
* @see javax.ws.rs.GET
* @see ameba.db.ebean.internal.AbstractModelResource#find()
*/
public Response find() throws Exception {
final Query<M> query = server.find(modelType);
if (StringUtils.isNotBlank(defaultFindOrderBy)) {
// see if we should use the default orderBy clause
OrderBy<M> orderBy = query.orderBy();
if (orderBy.isEmpty()) {
query.orderBy(defaultFindOrderBy);
}
}
final Ref<FutureRowCount> rowCount = Refs.emptyRef();
Response.ResponseBuilder builder = Response.ok();
Response response = builder.entity(executeTx(new TxCallable<Object>() {
@Override
public Object call() throws Exception {
configDefaultQuery(query);
configFindQuery(query);
rowCount.set(applyUriQuery(query));
List<M> list = query.findList();
return processFoundModelList(list);
}
})
).build();
applyRowCountHeader(response.getHeaders(), query, rowCount.get());
return response;
}
/**
* Configure the "Find" query.
* <p>
* This is only used when no PathProperties where set via UriOptions.
* </p>
* <p>
* This effectively controls the "default" query used with the find all
* query.
* </p>
*
* @param query a {@link com.avaje.ebean.Query} object.
* @throws java.lang.Exception if any.
*/
protected void configFindQuery(final Query<M> query) throws Exception {
}
/**
* <p>processFoundModelList.</p>
*
* @param list a {@link java.util.List} object.
* @return a {@link java.lang.Object} object.
* @throws java.lang.Exception if any.
*/
protected Object processFoundModelList(final List<M> list) throws Exception {
return list;
}
/**
* all query config default query
*
* @param query query
* @throws java.lang.Exception if any.
*/
protected void configDefaultQuery(final Query<M> query) throws Exception {
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// ///////////////////////////////////
/////////////////////////////////// useful method block ///////////////////////////////////
/////////////////////////////////// ///////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* apply uri query parameter on query
*
* @param query Query
* @param needPageList need page list
* @return page list count or null
* @see EbeanModelInterceptor#applyUriQuery(MultivaluedMap, Query, boolean)
*/
protected FutureRowCount applyUriQuery(final Query<M> query, boolean needPageList) {
return EbeanModelInterceptor.applyUriQuery(uriInfo.getQueryParameters(), query, needPageList);
}
/**
* <p>applyUriQuery.</p>
*
* @param query a {@link com.avaje.ebean.Query} object.
* @return a {@link com.avaje.ebean.FutureRowCount} object.
*/
protected FutureRowCount applyUriQuery(final Query<M> query) {
return applyUriQuery(query, true);
}
/**
* <p>applyRowCountHeader.</p>
*
* @param headerParams a {@link javax.ws.rs.core.MultivaluedMap} object.
* @param query a {@link com.avaje.ebean.Query} object.
* @param rowCount a {@link com.avaje.ebean.FutureRowCount} object.
*/
protected void applyRowCountHeader(MultivaluedMap<String, Object> headerParams, Query query, FutureRowCount rowCount) {
EbeanModelInterceptor.applyRowCountHeader(headerParams, query, rowCount);
}
/**
* <p>processTransactionError.</p>
*
* @param callable a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @param process a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @throws java.lang.Exception if any.
*/
protected <T> T processTransactionError(TxCallable<T> callable, TxCallable<T> process) throws Exception {
try {
return callable.call();
} catch (Exception e) {
return processCheckRowCountError(e, e, process);
}
}
protected <T> T processCheckRowCountError(Exception root, Throwable e, TxCallable<T> process) throws Exception {
if (e == null) {
throw root;
}
if (e instanceof OptimisticLockException) {
if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) {
if (process != null)
return process.call();
}
}
return processCheckRowCountError(root, e.getCause(), process);
}
/**
* <p>executeTx.</p>
*
* @param scope a {@link com.avaje.ebean.TxScope} object.
* @param r a {@link ameba.db.ebean.internal.ModelResourceStructure.TxRunnable} object.
* @throws java.lang.Exception if any.
*/
protected void executeTx(TxScope scope, final TxRunnable r, final TxRunnable errorHandler) throws Exception {
final ScopeTrans scopeTrans = server.createScopeTrans(scope);
configureTransDefault();
processTransactionError(new TxCallable() {
@Override
public Object call() throws Exception {
try {
r.run();
} catch (Error e) {
throw scopeTrans.caughtError(e);
} catch (Exception e) {
throw scopeTrans.caughtThrowable(e);
} finally {
scopeTrans.onFinally();
}
return null;
}
}, errorHandler != null ? new TxCallable() {
@Override
public Object call() throws Exception {
errorHandler.run();
return null;
}
} : null);
}
/**
* <p>executeTx.</p>
*
* @param r a {@link ameba.db.ebean.internal.ModelResourceStructure.TxRunnable} object.
* @throws java.lang.Exception if any.
*/
protected void executeTx(TxRunnable r) throws Exception {
executeTx(null, r, null);
}
protected void executeTx(TxRunnable r, TxRunnable errorHandler) throws Exception {
executeTx(null, r, errorHandler);
}
/**
* <p>executeTx.</p>
*
* @param c a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @param <O> a O object.
* @return a O object.
* @throws java.lang.Exception if any.
*/
protected <O> O executeTx(TxCallable<O> c) throws Exception {
return executeTx(null, c, null);
}
protected <O> O executeTx(TxCallable<O> c, final TxCallable<O> errorHandler) throws Exception {
return executeTx(null, c, errorHandler);
}
/**
* <p>executeTx.</p>
*
* @param scope a {@link com.avaje.ebean.TxScope} object.
* @param c a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @param <O> a O object.
* @return a O object.
* @throws java.lang.Exception if any.
*/
protected <O> O executeTx(TxScope scope, final TxCallable<O> c, final TxCallable<O> errorHandler) throws Exception {
final ScopeTrans scopeTrans = server.createScopeTrans(scope);
configureTransDefault();
return processTransactionError(new TxCallable<O>() {
@Override
public O call() throws Exception {
try {
return c.call();
} catch (Error e) {
throw scopeTrans.caughtError(e);
} catch (Exception e) {
throw scopeTrans.caughtThrowable(e);
} finally {
scopeTrans.onFinally();
}
}
}, errorHandler);
}
protected void configureTransDefault() {
}
/**
* <p>processTransactionError.</p>
*
* @param callable a {@link ameba.db.ebean.internal.ModelResourceStructure.TxCallable} object.
* @throws java.lang.Exception if any.
*/
protected <T> T processTransactionError(TxCallable<T> callable) throws Exception {
return processTransactionError(callable, null);
}
/**
* <p>buildLocationUri.</p>
*
* @param id a ID object.
* @param useTemplate use current template
* @return a {@link java.net.URI} object.
*/
protected URI buildLocationUri(ID id, boolean useTemplate) {
if (id == null) {
throw new NotFoundException();
}
UriBuilder ub = uriInfo.getAbsolutePathBuilder();
if (useTemplate) {
return ub.build(id);
} else {
return ub.path(idToString(id)).build();
}
}
protected URI buildLocationUri(ID id) {
return buildLocationUri(id, false);
}
protected interface TxRunnable {
void run() throws Exception;
}
protected interface TxCallable<O> {
O call() throws Exception;
}
}
| 更改ebean判断id存在
| src/main/java/ameba/db/ebean/internal/ModelResourceStructure.java | 更改ebean判断id存在 | <ide><path>rc/main/java/ameba/db/ebean/internal/ModelResourceStructure.java
<ide> protected void setForInsertId(final M model) {
<ide> BeanDescriptor descriptor = getModelBeanDescriptor();
<ide> EntityBeanIntercept intercept = ((EntityBean) model)._ebean_getIntercept();
<del> if (descriptor.hasIdProperty(intercept)) {
<del> BeanProperty idProp = descriptor.getIdProperty();
<add> BeanProperty idProp = descriptor.getIdProperty();
<add> if (idProp != null) {
<ide> idProp.setValue((EntityBean) model, null);
<ide> intercept.setPropertyUnloaded(idProp.getPropertyIndex());
<ide> } |
|
Java | bsd-3-clause | 73643925937666c1bd99da018afb848922ad54e7 | 0 | bdezonia/zorbage,bdezonia/zorbage | /*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the 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 <COPYRIGHT HOLDER> 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 nom.bdezonia.zorbage.type.real.float128;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import org.junit.Test;
import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
import nom.bdezonia.zorbage.storage.Storage;
/**
*
* @author Barry DeZonia
*
*/
public class TestFloat128Member {
// This site is invaluable for making these tests;
// http://weitz.de/ieee/
@Test
public void test() {
byte[] arr = new byte[16];
Float128Member val = G.QUAD.construct();
val.setNan();
val.encode(arr, 0); // 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
assertEquals(0x7f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(1, arr[13]);
assertEquals(1, arr[12]);
assertEquals(1, arr[11]);
assertEquals(1, arr[10]);
assertEquals(1, arr[9]);
assertEquals(1, arr[8]);
assertEquals(1, arr[7]);
assertEquals(1, arr[6]);
assertEquals(1, arr[5]);
assertEquals(1, arr[4]);
assertEquals(1, arr[3]);
assertEquals(1, arr[2]);
assertEquals(1, arr[1]);
assertEquals(1, arr[0]);
val.setNegInf();
val.encode(arr, 0); // 0xFFFF0000000000000000000000000000
assertEquals(0xff, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setPosInf();
val.encode(arr, 0); // 0x7FFF0000000000000000000000000000
assertEquals(0x7f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setNegZero();
val.encode(arr, 0); // 0x80000000000000000000000000000000
assertEquals(0x80, arr[15] & 0xff);
assertEquals(0, arr[14]);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setPosZero();
val.encode(arr, 0); // 0x00000000000000000000000000000000
assertEquals(0, arr[15]);
assertEquals(0, arr[14]);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.ONE);
val.encode(arr, 0); // 0x3FFF0000000000000000000000000000
assertEquals(0x3f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.ONE.negate());
val.encode(arr, 0);
assertEquals(0xbf, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(1.5));
val.encode(arr, 0); // 0x3FFF8000000000000000000000000000
assertEquals(0x3f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0x80, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(-1.5));
val.encode(arr, 0); // 0xBFFF8000000000000000000000000000
assertEquals(0xbf, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0x80, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(1.75));
val.encode(arr, 0); // 0x3FFFC000000000000000000000000000
assertEquals(0x3f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0xc0, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(-1.75));
val.encode(arr, 0); // 0xBFFFC000000000000000000000000000
assertEquals(0xbf, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0xc0, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(28.6333302));
val.encode(arr, 0); // 0x4003CA221ED9091B31B4ADF21632716C
assertEquals(0x40, arr[15] & 0xff);
assertEquals(0x03, arr[14] & 0xff);
assertEquals(0xca, arr[13] & 0xff);
assertEquals(0x22, arr[12] & 0xff);
assertEquals(0x1e, arr[11] & 0xff);
assertEquals(0xd9, arr[10] & 0xff);
assertEquals(0x09, arr[9] & 0xff);
assertEquals(0x1b, arr[8] & 0xff);
assertEquals(0x31, arr[7] & 0xff);
assertEquals(0xb4, arr[6] & 0xff);
assertEquals(0xad, arr[5] & 0xff);
assertEquals(0xf2, arr[4] & 0xff);
assertEquals(0x16, arr[3] & 0xff);
assertEquals(0x32, arr[2] & 0xff);
assertEquals(0x71, arr[1] & 0xff);
assertEquals(0x6c, arr[0] & 0xff);
val.setV(BigDecimal.valueOf(-28.6333302));
val.encode(arr, 0); // 0xC003CA221ED9091B31B4ADF21632716C
assertEquals(0xc0, arr[15] & 0xff);
assertEquals(0x03, arr[14] & 0xff);
assertEquals(0xca, arr[13] & 0xff);
assertEquals(0x22, arr[12] & 0xff);
assertEquals(0x1e, arr[11] & 0xff);
assertEquals(0xd9, arr[10] & 0xff);
assertEquals(0x09, arr[9] & 0xff);
assertEquals(0x1b, arr[8] & 0xff);
assertEquals(0x31, arr[7] & 0xff);
assertEquals(0xb4, arr[6] & 0xff);
assertEquals(0xad, arr[5] & 0xff);
assertEquals(0xf2, arr[4] & 0xff);
assertEquals(0x16, arr[3] & 0xff);
assertEquals(0x32, arr[2] & 0xff);
assertEquals(0x71, arr[1] & 0xff);
assertEquals(0x6c, arr[0] & 0xff);
IndexedDataSource<Float128Member> storage = Storage.allocate(val, 1);
double crazyConstant = 4213.19308583;
val.setV(BigDecimal.valueOf(crazyConstant));
val.encode(arr, 0); // 0x400B075316E12AD2BC7AF00B404FFC42
assertEquals(0x40, arr[15] & 0xff);
assertEquals(0x0b, arr[14] & 0xff);
assertEquals(0x07, arr[13] & 0xff);
assertEquals(0x53, arr[12] & 0xff);
assertEquals(0x16, arr[11] & 0xff);
assertEquals(0xe1, arr[10] & 0xff);
assertEquals(0x2a, arr[9] & 0xff);
assertEquals(0xd2, arr[8] & 0xff);
assertEquals(0xbc, arr[7] & 0xff);
assertEquals(0x7a, arr[6] & 0xff);
assertEquals(0xf0, arr[5] & 0xff);
assertEquals(0x0b, arr[4] & 0xff);
assertEquals(0x40, arr[3] & 0xff);
assertEquals(0x4f, arr[2] & 0xff);
assertEquals(0xfc, arr[1] & 0xff);
assertEquals(0x42, arr[0] & 0xff);
for (long i = 0; i < storage.size(); i++) {
storage.set(i, val);
}
for (long i = 0; i < storage.size(); i++) {
val.setPosZero();
storage.get(i, val);
assertEquals(crazyConstant, val.v().doubleValue(), 0.000000001);
}
}
@Test
public void testEncodeInts() {
Float128Member tol = new Float128Member(new BigDecimal("0.00000000000000000000000000000000000001"));
Float128Member num = new Float128Member();
byte[] arr = new byte[16];
for (int i = -2000; i <= 2000; i++) {
BigDecimal input = BigDecimal.valueOf(i);
num.setV(input);
num.encode(arr, 0);
num.decode(arr, 0);
// System.out.println(input + " " + num);
assertTrue(num.v().subtract(input).abs().compareTo(tol.v()) <= 0);
}
}
@Test
public void testEncodeFractions() {
Float128Member tol = new Float128Member(new BigDecimal("0.00000000000000000000000000000000000001"));
Float128Member num = new Float128Member();
byte[] arr = new byte[16];
for (int i = 0; i < 1000; i++) {
G.QUAD.random().call(num);
// test half the numbers as negative
if ((i & 1) == 1)
G.QUAD.negate().call(num, num);
BigDecimal before = num.v();
num.encode(arr, 0);
num.decode(arr, 0);
// System.out.println(before + " " + num);
assertTrue(num.v().subtract(before).abs().compareTo(tol.v()) <= 0);
}
}
@Test
public void testEncodeSubnormal() {
// TODO : write example code around this number
//BigDecimal tol = new BigDecimal("0.00000000000000000000000000000000000001");
BigDecimal v = new BigDecimal("2.3476754706213756379937664069229480929E-4933");
assertTrue(v.compareTo(Float128Member.MIN_SUBNORMAL) >= 0);
assertTrue(v.compareTo(Float128Member.MAX_SUBNORMAL) <= 0);
}
@Test
public void testPowersOf2() {
Float128Member num = new Float128Member();
BigDecimal start;
int count = 55; // NOTE 56 or higher fails in the divide case. Due to 40 digit roundoff?
byte[] arr1 = new byte[16];
byte[] arr2 = new byte[16];
// positive num > 1
start = BigDecimal.ONE;
for (int i = 0; i < count; i++) {
start = start.multiply(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
// positive 0 < num <= 1
start = BigDecimal.ONE;
for (int i = 0; i < count; i++) {
start = start.divide(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
// negative num < -1
start = BigDecimal.ONE.negate();
for (int i = 0; i < count; i++) {
start = start.multiply(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
// negative 0 < num <= 1
start = BigDecimal.ONE.negate();
for (int i = 0; i < count; i++) {
start = start.divide(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
}
@Test
public void testOneCase() {
Float128Member num = new Float128Member();
BigDecimal start = new BigDecimal("-0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999983189484284439532468686610913391236987");
byte[] arr1 = new byte[16];
byte[] arr2 = new byte[16];
num.setV(start);
//System.out.println(num);
num.encode(arr1, 0);
num.decode(arr1, 0);
//System.out.println(num);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
}
| src/test/java/nom/bdezonia/zorbage/type/real/float128/TestFloat128Member.java | /*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the 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 <COPYRIGHT HOLDER> 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 nom.bdezonia.zorbage.type.real.float128;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import org.junit.Test;
import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
import nom.bdezonia.zorbage.storage.Storage;
/**
*
* @author Barry DeZonia
*
*/
public class TestFloat128Member {
// This site is invaluable for making these tests;
// http://weitz.de/ieee/
@Test
public void test() {
byte[] arr = new byte[16];
Float128Member val = G.QUAD.construct();
val.setNan();
val.encode(arr, 0); // 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
assertEquals(0x7f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(1, arr[13]);
assertEquals(1, arr[12]);
assertEquals(1, arr[11]);
assertEquals(1, arr[10]);
assertEquals(1, arr[9]);
assertEquals(1, arr[8]);
assertEquals(1, arr[7]);
assertEquals(1, arr[6]);
assertEquals(1, arr[5]);
assertEquals(1, arr[4]);
assertEquals(1, arr[3]);
assertEquals(1, arr[2]);
assertEquals(1, arr[1]);
assertEquals(1, arr[0]);
val.setNegInf();
val.encode(arr, 0); // 0xFFFF0000000000000000000000000000
assertEquals(0xff, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setPosInf();
val.encode(arr, 0); // 0x7FFF0000000000000000000000000000
assertEquals(0x7f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setNegZero();
val.encode(arr, 0); // 0x80000000000000000000000000000000
assertEquals(0x80, arr[15] & 0xff);
assertEquals(0, arr[14]);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setPosZero();
val.encode(arr, 0); // 0x00000000000000000000000000000000
assertEquals(0, arr[15]);
assertEquals(0, arr[14]);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.ONE);
val.encode(arr, 0); // 0x3FFF0000000000000000000000000000
assertEquals(0x3f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.ONE.negate());
val.encode(arr, 0);
assertEquals(0xbf, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0, arr[13]);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(1.5));
val.encode(arr, 0); // 0x3FFF8000000000000000000000000000
assertEquals(0x3f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0x80, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(-1.5));
val.encode(arr, 0); // 0xBFFF8000000000000000000000000000
assertEquals(0xbf, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0x80, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(1.75));
val.encode(arr, 0); // 0x3FFFC000000000000000000000000000
assertEquals(0x3f, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0xc0, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(-1.75));
val.encode(arr, 0); // 0xBFFFC000000000000000000000000000
assertEquals(0xbf, arr[15] & 0xff);
assertEquals(0xff, arr[14] & 0xff);
assertEquals(0xc0, arr[13] & 0xff);
assertEquals(0, arr[12]);
assertEquals(0, arr[11]);
assertEquals(0, arr[10]);
assertEquals(0, arr[9]);
assertEquals(0, arr[8]);
assertEquals(0, arr[7]);
assertEquals(0, arr[6]);
assertEquals(0, arr[5]);
assertEquals(0, arr[4]);
assertEquals(0, arr[3]);
assertEquals(0, arr[2]);
assertEquals(0, arr[1]);
assertEquals(0, arr[0]);
val.setV(BigDecimal.valueOf(28.6333302));
val.encode(arr, 0); // 0x4003CA221ED9091B31B4ADF21632716C
assertEquals(0x40, arr[15] & 0xff);
assertEquals(0x03, arr[14] & 0xff);
assertEquals(0xca, arr[13] & 0xff);
assertEquals(0x22, arr[12] & 0xff);
assertEquals(0x1e, arr[11] & 0xff);
assertEquals(0xd9, arr[10] & 0xff);
assertEquals(0x09, arr[9] & 0xff);
assertEquals(0x1b, arr[8] & 0xff);
assertEquals(0x31, arr[7] & 0xff);
assertEquals(0xb4, arr[6] & 0xff);
assertEquals(0xad, arr[5] & 0xff);
assertEquals(0xf2, arr[4] & 0xff);
assertEquals(0x16, arr[3] & 0xff);
assertEquals(0x32, arr[2] & 0xff);
assertEquals(0x71, arr[1] & 0xff);
assertEquals(0x6c, arr[0] & 0xff);
val.setV(BigDecimal.valueOf(-28.6333302));
val.encode(arr, 0); // 0xC003CA221ED9091B31B4ADF21632716C
assertEquals(0xc0, arr[15] & 0xff);
assertEquals(0x03, arr[14] & 0xff);
assertEquals(0xca, arr[13] & 0xff);
assertEquals(0x22, arr[12] & 0xff);
assertEquals(0x1e, arr[11] & 0xff);
assertEquals(0xd9, arr[10] & 0xff);
assertEquals(0x09, arr[9] & 0xff);
assertEquals(0x1b, arr[8] & 0xff);
assertEquals(0x31, arr[7] & 0xff);
assertEquals(0xb4, arr[6] & 0xff);
assertEquals(0xad, arr[5] & 0xff);
assertEquals(0xf2, arr[4] & 0xff);
assertEquals(0x16, arr[3] & 0xff);
assertEquals(0x32, arr[2] & 0xff);
assertEquals(0x71, arr[1] & 0xff);
assertEquals(0x6c, arr[0] & 0xff);
IndexedDataSource<Float128Member> storage = Storage.allocate(val, 1);
double crazyConstant = 4213.19308583;
val.setV(BigDecimal.valueOf(crazyConstant));
val.encode(arr, 0); // 0x400B075316E12AD2BC7AF00B404FFC42
assertEquals(0x40, arr[15] & 0xff);
assertEquals(0x0b, arr[14] & 0xff);
assertEquals(0x07, arr[13] & 0xff);
assertEquals(0x53, arr[12] & 0xff);
assertEquals(0x16, arr[11] & 0xff);
assertEquals(0xe1, arr[10] & 0xff);
assertEquals(0x2a, arr[9] & 0xff);
assertEquals(0xd2, arr[8] & 0xff);
assertEquals(0xbc, arr[7] & 0xff);
assertEquals(0x7a, arr[6] & 0xff);
assertEquals(0xf0, arr[5] & 0xff);
assertEquals(0x0b, arr[4] & 0xff);
assertEquals(0x40, arr[3] & 0xff);
assertEquals(0x4f, arr[2] & 0xff);
assertEquals(0xfc, arr[1] & 0xff);
assertEquals(0x42, arr[0] & 0xff);
for (long i = 0; i < storage.size(); i++) {
storage.set(i, val);
}
for (long i = 0; i < storage.size(); i++) {
val.setPosZero();
storage.get(i, val);
assertEquals(crazyConstant, val.v().doubleValue(), 0.000000001);
}
}
@Test
public void testEncodeInts() {
Float128Member tol = new Float128Member(new BigDecimal("0.00000000000000000000000000000000000001"));
Float128Member num = new Float128Member();
int[] ints = new int[]{1,7,4,1,2,4,8,3,3};
byte[] arr = new byte[16];
for (int i = 0; i < ints.length; i++) {
BigDecimal input = BigDecimal.valueOf(ints[i]);
num.setV(input);
num.encode(arr, 0);
num.decode(arr, 0);
// System.out.println(input + " " + num);
assertTrue(num.v().subtract(input).abs().compareTo(tol.v()) <= 0);
}
}
@Test
public void testEncodeFractions() {
Float128Member tol = new Float128Member(new BigDecimal("0.00000000000000000000000000000000000001"));
Float128Member num = new Float128Member();
byte[] arr = new byte[16];
for (int i = 0; i < 100; i++) {
G.QUAD.random().call(num);
BigDecimal before = num.v();
num.encode(arr, 0);
num.decode(arr, 0);
// System.out.println(before + " " + num);
assertTrue(num.v().subtract(before).abs().compareTo(tol.v()) <= 0);
}
}
@Test
public void testEncodeSubnormal() {
// TODO : write example code around this number
//BigDecimal tol = new BigDecimal("0.00000000000000000000000000000000000001");
BigDecimal v = new BigDecimal("2.3476754706213756379937664069229480929E-4933");
assertTrue(v.compareTo(Float128Member.MIN_SUBNORMAL) >= 0);
assertTrue(v.compareTo(Float128Member.MAX_SUBNORMAL) <= 0);
}
@Test
public void testPowersOf2() {
Float128Member num = new Float128Member();
BigDecimal start;
int count = 55; // NOTE 56 or higher fails in the divide case. Due to 40 digit roundoff?
byte[] arr1 = new byte[16];
byte[] arr2 = new byte[16];
// positive num > 1
start = BigDecimal.ONE;
for (int i = 0; i < count; i++) {
start = start.multiply(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
// positive 0 < num <= 1
start = BigDecimal.ONE;
for (int i = 0; i < count; i++) {
start = start.divide(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
// negative num < -1
start = BigDecimal.ONE.negate();
for (int i = 0; i < count; i++) {
start = start.multiply(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
// negative 0 < num <= 1
start = BigDecimal.ONE.negate();
for (int i = 0; i < count; i++) {
start = start.divide(BigDecimal.valueOf(2));
num.setV(start);
num.encode(arr1, 0);
num.decode(arr1, 0);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
}
@Test
public void testOneCase() {
Float128Member num = new Float128Member();
BigDecimal start = new BigDecimal("-0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999983189484284439532468686610913391236987");
byte[] arr1 = new byte[16];
byte[] arr2 = new byte[16];
num.setV(start);
//System.out.println(num);
num.encode(arr1, 0);
num.decode(arr1, 0);
//System.out.println(num);
num.encode(arr2, 0);
for (int k = 0; k < 16; k++) {
assertEquals(arr1[k], arr2[k]);
}
}
}
| Improve testing coverage fpr flt128s
| src/test/java/nom/bdezonia/zorbage/type/real/float128/TestFloat128Member.java | Improve testing coverage fpr flt128s | <ide><path>rc/test/java/nom/bdezonia/zorbage/type/real/float128/TestFloat128Member.java
<ide>
<ide> Float128Member num = new Float128Member();
<ide>
<del> int[] ints = new int[]{1,7,4,1,2,4,8,3,3};
<del>
<ide> byte[] arr = new byte[16];
<del> for (int i = 0; i < ints.length; i++) {
<del>
<del> BigDecimal input = BigDecimal.valueOf(ints[i]);
<add> for (int i = -2000; i <= 2000; i++) {
<add>
<add> BigDecimal input = BigDecimal.valueOf(i);
<ide>
<ide> num.setV(input);
<ide>
<ide> Float128Member num = new Float128Member();
<ide>
<ide> byte[] arr = new byte[16];
<del> for (int i = 0; i < 100; i++) {
<add> for (int i = 0; i < 1000; i++) {
<ide>
<ide> G.QUAD.random().call(num);
<add>
<add> // test half the numbers as negative
<add>
<add> if ((i & 1) == 1)
<add> G.QUAD.negate().call(num, num);
<ide>
<ide> BigDecimal before = num.v();
<ide> |
|
Java | mit | af1ad7a63f8708e944715368ef1655dea243afbe | 0 | jpinho/soaba,jpinho/soaba,jpinho/soaba,jpinho/soaba | package soaba.core.config;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soaba.core.api.IDatapoint;
import soaba.core.api.IDatapoint.ACCESSTYPE;
import soaba.core.api.IDatapoint.DATATYPE;
import soaba.core.api.IGatewayDriver;
import soaba.core.gateways.drivers.KNXGatewayDriver;
import soaba.core.models.Datapoint;
import flexjson.JSON;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
public class AppConfig {
private static final String GATEWAY_NUCLEUS_14 = "172.20.70.241";
private static final String GATEWAY_LAB_158 = "172.20.70.209";
private static final String APP_CONFIG_FILE = "resources/soaba.config";
private static AppConfig instance;
private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
@JSON(include = true)
private List<IGatewayDriver> gateways = new ArrayList<IGatewayDriver>();
@JSON(include = true)
private List<IDatapoint> datapoints = new ArrayList<IDatapoint>();
private AppConfig() {
/* singleton class */
}
public static AppConfig getInstance() {
if (instance != null)
return instance;
return instance = new AppConfig().init();
}
public AppConfig init() {
logger.info("calling AppConfig#init()");
// loads the config from disk if it exists
File f = new File(APP_CONFIG_FILE);
if (f.exists()){
logger.info("AppConfig#init() :: configuration found on disk, loading from file.");
AppConfig config = AppConfig.load();
logger.info(
String.format("%nAppConfig#init() :: configuration summary%n - datapoints count: %d%n - gateways count: %d%n%n",
config.datapoints != null ? config.datapoints.size() : 0,
config.gateways != null ? config.gateways.size() : 0));
return config;
}
logger.info("AppConfig#init() :: configuration not found, generating new file to disk.");
String gwNucleus14 = null;
String gwLab158 = null;
/**
* Gateways Registration
*/
gateways.add(new KNXGatewayDriver("KNX Gateway Lab 1.58", gwLab158 = GATEWAY_LAB_158));
gateways.add(new KNXGatewayDriver("KNX Gateway Nucleus 14", gwNucleus14 = GATEWAY_NUCLEUS_14));
/**
* Datapoints Registration
*/
String prefix = null;
/** MIT - LAB 1.58 **/
if (gwLab158 != null) {
// lights
prefix = "EnergyLab ";
datapoints.add(new Datapoint(gwLab158, prefix + "All Lights", ACCESSTYPE.WRITE_ONLY, DATATYPE.PERCENTAGE, null, "0/1/8"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light Blackboard", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/1", "0/1/0"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light Middle1", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/21", "0/1/2"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light Middle2", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/41", "0/1/4"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light TV", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/61", "0/1/6"));
// blinds
datapoints.add(new Datapoint(gwLab158, prefix + "All Blinds", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/2/12"));
datapoints.add(new Datapoint(gwLab158, prefix + "Blind1", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/2/0", "0/2/3"));
datapoints.add(new Datapoint(gwLab158, prefix + "Blind2", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/2/13", "0/2/6"));
datapoints.add(new Datapoint(gwLab158, prefix + "Blind3", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/2/14", "0/2/9"));
// door
datapoints.add(new Datapoint(gwLab158, prefix + "Door", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/3/0"));
// meteo station sensors
datapoints.add(new Datapoint(gwLab158, prefix + "CO2", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/0", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Humidity", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/1", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Temperature", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/3", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Temperature Door", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/5", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Lux", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/4", null));
// hvac
datapoints.add(new Datapoint(gwLab158, prefix + "HVAC ONOFF", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "1/0/8", "1/0/0"));
datapoints.add(new Datapoint(gwLab158, prefix + "HVAC Mode", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "1/0/9", "1/0/1"));
// meteo station (bus Q.E. floor 1)
prefix = "Meteo Station BUS[Q.E] Floor1 - ";
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - East Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/5", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - South Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/6", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - West Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/7", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - Crepuscular Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/8", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Wind Speed Warn Interval", ACCESSTYPE.READ_WRITE, DATATYPE.TINY_NUMBER, "0/6/9", "0/6/9"));
datapoints.add(new Datapoint(gwLab158, prefix + "Wind Speed Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/10", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Outside Temp. Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/11", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Rain Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/6/13", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Outside Temp. Sensor Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/16", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Max. Temp Reached Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/19", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Min. Temp Reached Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/20", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Relative Hum. Sensor Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/22", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Drew Point", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/25", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Absolute Humidity", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/27", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Exterior Entalpia", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/28", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Global Solar Radiation Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/29", null));
}
/** MIT - NUCLEUS 14 **/
if (gwNucleus14 != null) {
// lights
datapoints.add(new Datapoint(gwNucleus14, "2-N14 - All Lights", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/0/1"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.02 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/2", "0/0/2"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.04 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/3", "0/0/3"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.06 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/4", "0/0/4"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.08 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/5", "0/0/5"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.10 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/6", "0/0/6"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.12 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/7", "0/0/7"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.14 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/8", "0/0/8"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.16 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/9", "0/0/9"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.18 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/10", "0/0/10"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.20 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/11", "0/0/11"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.22 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/12", "0/0/12"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.24 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/13", "0/0/13"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.26 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/14", "0/0/14"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.28 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/15", "0/0/15"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.1.1E/2E - Lights Circuit", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/0/16"));
// energy and general purpose sensors
prefix = "2-N14 - ";
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. A - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/0", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. B - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/1", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. C - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/2", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. D - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/3", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. A - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/4", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. B - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/5", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. C - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/6", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. D - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/7", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. A - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/2/12", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. B - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/2/13", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. C - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/2/14", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. D - HVAC Supply", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/2/15", "0/2/15"));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Luminosity - Hall - North Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/16", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Luminosity - Hall - Middle Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/17", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Luminosity - Hall - South Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/18", null));
// hvac hot H2O valves
datapoints.add(new Datapoint(gwNucleus14, "2-N14.02 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/14", "0/1/14"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.04 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/15", "0/1/15"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.06 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/16", "0/1/16"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.08 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/17", "0/1/17"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.10 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/18", "0/1/18"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.12 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/19", "0/1/19"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.14 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/20", "0/1/20"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.16 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/21", "0/1/21"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.18 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/22", "0/1/22"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.20 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/23", "0/1/23"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.24 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/24", "0/1/24"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.26 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/25", "0/1/25"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.28 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/26", "0/1/26"));
// hvac cold H2O valves
datapoints.add(new Datapoint(gwNucleus14, "2-N14.02 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/27", "0/1/27"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.04 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/28", "0/1/28"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.06 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/29", "0/1/29"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.08 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/30", "0/1/30"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.10 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/31", "0/1/31"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.12 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/32", "0/1/32"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.14 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/33", "0/1/33"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.16 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/34", "0/1/34"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.18 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/35", "0/1/35"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.20 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/36", "0/1/36"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.24 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/37", "0/1/37"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.26 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/38", "0/1/38"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.28 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/39", "0/1/39"));
//TODO: add more datapoints of N14
}
// persists the config file to disk
AppConfig.save(this);
return this;
}
public List<IGatewayDriver> getGateways() {
return gateways;
}
public List<IDatapoint> getDatapoints() {
return datapoints;
}
/**
* Stores the AppConfig to disk persistence.
*
* @param theConfig the configuration file to persist in disk
*/
private static void save(AppConfig theConfig) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
try {
FileWriter writer = new FileWriter(APP_CONFIG_FILE);
serializer.deepSerialize(theConfig, writer);
writer.close();
} catch (IOException e) {
System.err.println(e.getMessage());
logger.error("AppConfig#save(theConfig)", e);
}
}
/**
* Loads AppConfig from disk persistence.
*/
private static AppConfig load() {
JSONDeserializer<AppConfig> serializer = new JSONDeserializer<AppConfig>();
AppConfig result = null;
try {
result = serializer
.use("datapoints", ArrayList.class)
.use("datapoints.values", Datapoint.class)
.use("gateways", ArrayList.class)
.use("gateways.values", KNXGatewayDriver.class)
.deserialize(new String(Files.readAllBytes(java.nio.file.Paths.get(APP_CONFIG_FILE))));
} catch (IOException e) {
System.err.println(e.getMessage());
logger.error("AppConfig#load()", e);
}
return result;
}
/**
* Searchs for a datapoint by their id, read address or write address, the first to match
* returns the underlyining datapoint.
*
* @param dpointIdOrAddress, the id, read address or write address of the datapoint to be found
* @return the datapoint found or null if none matches the query
*/
public IDatapoint findDatapoint(String dpointIdOrAddress) {
for (IDatapoint dp : datapoints)
if (dp.getId().equals(dpointIdOrAddress) ||
(dp.getReadAddress() != null && dp.getReadAddress().equals(dpointIdOrAddress)) ||
(dp.getWriteAddress() != null && dp.getWriteAddress().equals(dpointIdOrAddress)))
return dp;
return null;
}
public IGatewayDriver findGateway(String gatewayAddress) {
for (IGatewayDriver gateway : gateways)
if (gateway.getAddress().equalsIgnoreCase(gatewayAddress))
return gateway;
return null;
}
public void setGateways(List<IGatewayDriver> gateways) {
this.gateways = gateways;
}
public void setDatapoints(List<IDatapoint> datapoints) {
this.datapoints = datapoints;
}
}
| src/main/java/soaba/core/config/AppConfig.java | package soaba.core.config;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soaba.core.api.IDatapoint;
import soaba.core.api.IDatapoint.ACCESSTYPE;
import soaba.core.api.IDatapoint.DATATYPE;
import soaba.core.api.IGatewayDriver;
import soaba.core.gateways.drivers.KNXGatewayDriver;
import soaba.core.models.Datapoint;
import flexjson.JSON;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
public class AppConfig {
private static final String GATEWAY_NUCLEUS_14 = "172.20.70.241";
private static final String GATEWAY_LAB_158 = "172.20.70.209";
private static final String APP_CONFIG_FILE = "resources/soaba.config";
private static AppConfig instance;
private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
@JSON(include = true)
private List<IGatewayDriver> gateways = new ArrayList<IGatewayDriver>();
@JSON(include = true)
private List<IDatapoint> datapoints = new ArrayList<IDatapoint>();
private AppConfig() {
/* singleton class */
}
public static AppConfig getInstance() {
if (instance != null)
return instance;
return instance = new AppConfig().init();
}
public AppConfig init() {
logger.info("calling AppConfig#init()");
// loads the config from disk if it exists
File f = new File(APP_CONFIG_FILE);
if (f.exists()){
logger.info("AppConfig#init() :: configuration found on disk, loading from file.");
AppConfig config = AppConfig.load();
logger.info(
String.format("%nAppConfig#init() :: configuration summary%n - datapoints count: %d%n - gateways count: %d%n%n",
config.datapoints != null ? config.datapoints.size() : 0,
config.gateways != null ? config.gateways.size() : 0));
return config;
}
logger.info("AppConfig#init() :: configuration not found, generating new file to disk.");
String gwNucleus14 = null;
String gwLab158 = null;
/**
* Gateways Registration
*/
gateways.add(new KNXGatewayDriver("KNX Gateway Lab 1.58", gwLab158 = GATEWAY_LAB_158));
gateways.add(new KNXGatewayDriver("KNX Gateway Nucleus 14", gwNucleus14 = GATEWAY_NUCLEUS_14));
/**
* Datapoints Registration
*/
String prefix = null;
/** MIT - LAB 1.58 **/
if (gwLab158 != null) {
// lights
prefix = "EnergyLab ";
datapoints.add(new Datapoint(gwLab158, prefix + "All Lights", ACCESSTYPE.WRITE_ONLY, DATATYPE.PERCENTAGE, null, "0/1/8"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light Blackboard", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/1", "0/1/0"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light Middle1", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/21", "0/1/2"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light Middle2", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/41", "0/1/4"));
datapoints.add(new Datapoint(gwLab158, prefix + "Light TV", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/7/61", "0/1/6"));
// blinds
datapoints.add(new Datapoint(gwLab158, prefix + "All Blinds", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/2/12"));
datapoints.add(new Datapoint(gwLab158, prefix + "Blind1", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/2/0", "0/2/3"));
datapoints.add(new Datapoint(gwLab158, prefix + "Blind2", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/2/13", "0/2/6"));
datapoints.add(new Datapoint(gwLab158, prefix + "Blind3", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/2/14", "0/2/9"));
// door
datapoints.add(new Datapoint(gwLab158, prefix + "Door", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/3/0"));
// meteo station sensors
datapoints.add(new Datapoint(gwLab158, prefix + "CO2", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/0", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Humidity", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/1", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Temperature", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/3", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Temperature Door", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/5", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Lux", ACCESSTYPE.READ_ONLY, DATATYPE.NUMBER, "0/4/4", null));
// hvac
datapoints.add(new Datapoint(gwLab158, prefix + "HVAC ONOFF", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "1/0/8", "1/0/0"));
datapoints.add(new Datapoint(gwLab158, prefix + "HVAC Mode", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "1/0/9", "1/0/1"));
// meteo station (bus Q.E. floor 1)
prefix = "Meteo Station BUS[Q.E] Floor1 - ";
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - East Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/5", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - South Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/6", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - West Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/7", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Luminosity - Crepuscular Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/8", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Wind Speed Warn Interval", ACCESSTYPE.READ_WRITE, DATATYPE.TINY_NUMBER, "0/6/9", "0/6/9"));
datapoints.add(new Datapoint(gwLab158, prefix + "Wind Speed Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/10", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Outside Temp. Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/11", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Rain Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/6/13", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Outside Temp. Sensor Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/16", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Max. Temp Reached Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/19", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Min. Temp Reached Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/20", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Relative Hum. Sensor Precision", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/22", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Drew Point", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/25", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Absolute Humidity", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/27", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Exterior Entalpia", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/28", null));
datapoints.add(new Datapoint(gwLab158, prefix + "Global Solar Radiation Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/6/29", null));
}
/** MIT - NUCLEUS 14 **/
if (gwNucleus14 != null) {
// lights
datapoints.add(new Datapoint(gwNucleus14, "2-N14 - All Lights", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/0/1"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.02 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/2", "0/0/2"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.04 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/3", "0/0/3"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.06 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/4", "0/0/4"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.08 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/5", "0/0/5"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.10 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/6", "0/0/6"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.12 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/7", "0/0/7"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.14 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/8", "0/0/8"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.16 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/9", "0/0/9"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.18 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/10", "0/0/10"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.20 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/11", "0/0/11"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.22 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/12", "0/0/12"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.24 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/13", "0/0/13"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.26 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/14", "0/0/14"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.28 - Lights", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/0/15", "0/0/15"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.1.1E/2E - Lights Circuit", ACCESSTYPE.WRITE_ONLY, DATATYPE.BIT, null, "0/0/16"));
// energy and general purpose sensors
prefix = "2-N14 - ";
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. A - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/0", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. B - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/1", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. C - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/2", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Meter - Circ. D - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/3", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. A - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/4", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. B - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/5", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. C - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/6", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Energy Time Counter - Circ. D - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/7", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. A - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/2/12", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. B - Hall Lights", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/2/13", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. C - HVAC Supply", ACCESSTYPE.READ_ONLY, DATATYPE.BIT, "0/2/14", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Status - Circ. D - HVAC Supply", ACCESSTYPE.READ_WRITE, DATATYPE.BIT, "0/2/15", "0/2/15"));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Luminosity - Hall - North Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/16", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Luminosity - Hall - Middle Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/17", null));
datapoints.add(new Datapoint(gwNucleus14, prefix + "Luminosity - Hall - South Sensor", ACCESSTYPE.READ_ONLY, DATATYPE.TINY_NUMBER, "0/2/18", null));
// hvac hot H2O valves
datapoints.add(new Datapoint(gwNucleus14, "2-N14.02 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/14", "0/1/14"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.04 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/15", "0/1/15"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.06 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/16", "0/1/16"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.08 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/17", "0/1/17"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.10 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/18", "0/1/18"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.12 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/19", "0/1/19"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.14 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/20", "0/1/20"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.16 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/21", "0/1/21"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.18 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/22", "0/1/22"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.20 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/23", "0/1/23"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.24 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/24", "0/1/24"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.26 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/25", "0/1/25"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.28 - HVAC - Hot H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/26", "0/1/26"));
// hvac cold H2O valves
datapoints.add(new Datapoint(gwNucleus14, "2-N14.02 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/27", "0/1/27"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.04 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/28", "0/1/28"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.06 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/29", "0/1/29"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.08 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/30", "0/1/30"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.10 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/31", "0/1/31"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.12 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/32", "0/1/32"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.14 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/33", "0/1/33"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.16 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/34", "0/1/34"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.18 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/35", "0/1/35"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.20 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/36", "0/1/36"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.24 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/37", "0/1/37"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.26 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/38", "0/1/38"));
datapoints.add(new Datapoint(gwNucleus14, "2-N14.28 - HVAC - Cold H2O Valve", ACCESSTYPE.READ_WRITE, DATATYPE.PERCENTAGE, "0/1/39", "0/1/39"));
//TODO: add more datapoints of N14
}
// persists the config file to disk
AppConfig.save(this);
return this;
}
public List<IGatewayDriver> getGateways() {
return gateways;
}
public List<IDatapoint> getDatapoints() {
return datapoints;
}
/**
* Stores the AppConfig to disk persistence.
*
* @param theConfig the configuration file to persist in disk
*/
private static void save(AppConfig theConfig) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
try {
FileWriter writer = new FileWriter(APP_CONFIG_FILE);
serializer.deepSerialize(theConfig, writer);
writer.close();
} catch (IOException e) {
System.err.println(e.getMessage());
logger.error("AppConfig#save(theConfig)", e);
}
}
/**
* Loads AppConfig from disk persistence.
*/
private static AppConfig load() {
JSONDeserializer<AppConfig> serializer = new JSONDeserializer<AppConfig>();
AppConfig result = null;
try {
result = serializer
.use("datapoints", ArrayList.class)
.use("datapoints.values", Datapoint.class)
.use("gateways", ArrayList.class)
.use("gateways.values", KNXGatewayDriver.class)
.deserialize(new String(Files.readAllBytes(java.nio.file.Paths.get(APP_CONFIG_FILE))));
} catch (IOException e) {
System.err.println(e.getMessage());
logger.error("AppConfig#load()", e);
}
return result;
}
public IDatapoint findDatapoint(String dpointIdOrAddress) {
for (IDatapoint dp : datapoints)
if (dp.getId().equals(dpointIdOrAddress) || dp.getReadAddress().equals(dpointIdOrAddress) || dp.getWriteAddress().equals(dpointIdOrAddress))
return dp;
return null;
}
public IGatewayDriver findGateway(String gatewayAddress) {
for (IGatewayDriver gateway : gateways)
if (gateway.getAddress().equalsIgnoreCase(gatewayAddress))
return gateway;
return null;
}
public void setGateways(List<IGatewayDriver> gateways) {
this.gateways = gateways;
}
public void setDatapoints(List<IDatapoint> datapoints) {
this.datapoints = datapoints;
}
}
| [FIX] NullRef in AppConfig.findDatapoint
| src/main/java/soaba/core/config/AppConfig.java | [FIX] NullRef in AppConfig.findDatapoint | <ide><path>rc/main/java/soaba/core/config/AppConfig.java
<ide> return result;
<ide> }
<ide>
<add> /**
<add> * Searchs for a datapoint by their id, read address or write address, the first to match
<add> * returns the underlyining datapoint.
<add> *
<add> * @param dpointIdOrAddress, the id, read address or write address of the datapoint to be found
<add> * @return the datapoint found or null if none matches the query
<add> */
<ide> public IDatapoint findDatapoint(String dpointIdOrAddress) {
<ide> for (IDatapoint dp : datapoints)
<del> if (dp.getId().equals(dpointIdOrAddress) || dp.getReadAddress().equals(dpointIdOrAddress) || dp.getWriteAddress().equals(dpointIdOrAddress))
<del> return dp;
<add> if (dp.getId().equals(dpointIdOrAddress) ||
<add> (dp.getReadAddress() != null && dp.getReadAddress().equals(dpointIdOrAddress)) ||
<add> (dp.getWriteAddress() != null && dp.getWriteAddress().equals(dpointIdOrAddress)))
<add> return dp;
<ide> return null;
<ide> }
<ide> |
|
Java | apache-2.0 | bad3ead31e8a214278b60627f2f60769e491dbd1 | 0 | lovemomia/mapi,lovemomia/mapi | package cn.momia.mapi.api.v1.im;
import cn.momia.api.course.CourseServiceApi;
import cn.momia.api.course.dto.CourseSku;
import cn.momia.api.im.ImServiceApi;
import cn.momia.api.im.dto.Group;
import cn.momia.api.im.dto.GroupMember;
import cn.momia.api.im.dto.UserGroup;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.mapi.api.AbstractApi;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping("/v1/im")
public class ImV1Api extends AbstractApi {
@Autowired private CourseServiceApi courseServiceApi;
@Autowired private ImServiceApi imServiceApi;
@Autowired private UserServiceApi userServiceApi;
@RequestMapping(value = "/token", method = RequestMethod.POST)
public MomiaHttpResponse generateImToken(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
User user = userServiceApi.get(utoken);
return MomiaHttpResponse.SUCCESS(doGenerateImToken(user));
}
private String doGenerateImToken(User user) {
String imToken = imServiceApi.generateImToken(user.getId(), user.getNickName(), completeSmallImg(user.getAvatar()));
if (!StringUtils.isBlank(imToken)) userServiceApi.updateImToken(user.getToken(), imToken);
return imToken;
}
@RequestMapping(value = "/token", method = RequestMethod.GET)
public MomiaHttpResponse getImToken(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
User user = userServiceApi.get(utoken);
String imToken = user.getImToken();
if (StringUtils.isBlank(imToken)) imToken = doGenerateImToken(user);
return MomiaHttpResponse.SUCCESS(imToken);
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
public MomiaHttpResponse getImUserInfo(@RequestParam(value = "uid") long userId) {
if (userId <= 0) return MomiaHttpResponse.BAD_REQUEST;
User user = userServiceApi.get(userId);
JSONObject imUserInfoJson = createImUserInfo(user);
List<String> latestImgs = courseServiceApi.getLatestImgs(userId);
if (!latestImgs.isEmpty()) {
imUserInfoJson.put("imgs", completeMiddleImgs(latestImgs));
}
return MomiaHttpResponse.SUCCESS(imUserInfoJson);
}
private JSONObject createImUserInfo(User user) {
JSONObject imUserInfoJson = new JSONObject();
imUserInfoJson.put("id", user.getId());
imUserInfoJson.put("nickName", user.getNickName());
imUserInfoJson.put("avatar", completeSmallImg(user.getAvatar()));
imUserInfoJson.put("role", user.getRole());
return imUserInfoJson;
}
@RequestMapping(value = "/group", method = RequestMethod.GET)
public MomiaHttpResponse getGroupInfo(@RequestParam(value = "id") long groupId) {
if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST;
Group group = imServiceApi.getGroup(groupId);
CourseSku sku = courseServiceApi.getSku(group.getCourseId(), group.getCourseSkuId());
JSONObject groupInfo = new JSONObject();
groupInfo.put("groupId", group.getGroupId());
groupInfo.put("groupName", group.getGroupName());
groupInfo.put("tips", courseServiceApi.queryTips(Sets.newHashSet(group.getCourseId())).get(String.valueOf(group.getCourseId())));
groupInfo.put("time", sku.getTime());
groupInfo.put("route", sku.getRoute());
groupInfo.put("address", sku.getPlace().getAddress());
return MomiaHttpResponse.SUCCESS(groupInfo);
}
@RequestMapping(value = "/group/member", method = RequestMethod.GET)
public MomiaHttpResponse listGroupMembers(@RequestParam String utoken, @RequestParam(value = "id") long groupId) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST;
User user = userServiceApi.get(utoken);
List<GroupMember> groupMembers = imServiceApi.listGroupMembers(user.getId(), groupId);
Set<Long> userIds = new HashSet<Long>();
for (GroupMember groupMember : groupMembers) {
userIds.add(groupMember.getUserId());
}
List<User> users = userServiceApi.list(userIds, User.Type.BASE);
Map<Long, User> usersMap = new HashMap<Long, User>();
for (User memberUser : users) {
usersMap.put(memberUser.getId(), memberUser);
}
List<JSONObject> teachers = new ArrayList<JSONObject>();
List<JSONObject> customers = new ArrayList<JSONObject>();
for (GroupMember groupMember : groupMembers) {
User memberUser = usersMap.get(groupMember.getUserId());
if (memberUser == null) continue;
JSONObject imUserJson = createImUserInfo(user);
if (groupMember.isTeacher()) teachers.add(imUserJson);
else customers.add(imUserJson);
}
JSONObject responseJson = new JSONObject();
responseJson.put("teachers", teachers);
responseJson.put("customers", customers);
return MomiaHttpResponse.SUCCESS(responseJson);
}
@RequestMapping(value = "/user/group", method = RequestMethod.GET)
public MomiaHttpResponse listUserGroups(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
User user = userServiceApi.get(utoken);
List<UserGroup> userGroups = imServiceApi.listUserGroups(user.getId());
Set<Long> courseIds = new HashSet<Long>();
for (UserGroup userGroup : userGroups) {
courseIds.add(userGroup.getCourseId());
}
Map<Long, String> tipsOfCourses = courseServiceApi.queryTips(courseIds);
for (UserGroup userGroup : userGroups) {
userGroup.setTips(tipsOfCourses.get(String.valueOf(userGroup.getCourseId())));
}
return MomiaHttpResponse.SUCCESS(userGroups);
}
}
| src/main/java/cn/momia/mapi/api/v1/im/ImV1Api.java | package cn.momia.mapi.api.v1.im;
import cn.momia.api.course.CourseServiceApi;
import cn.momia.api.course.dto.CourseSku;
import cn.momia.api.im.ImServiceApi;
import cn.momia.api.im.dto.Group;
import cn.momia.api.im.dto.Member;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.common.core.util.TimeUtil;
import cn.momia.mapi.api.AbstractApi;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping("/v1/im")
public class ImV1Api extends AbstractApi {
@Autowired private CourseServiceApi courseServiceApi;
@Autowired private ImServiceApi imServiceApi;
@Autowired private UserServiceApi userServiceApi;
@RequestMapping(value = "/token", method = RequestMethod.POST)
public MomiaHttpResponse generateImToken(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
User user = userServiceApi.get(utoken);
return MomiaHttpResponse.SUCCESS(doGenerateImToken(user));
}
private String doGenerateImToken(User user) {
String imToken = imServiceApi.generateImToken(user.getId(), user.getNickName(), completeSmallImg(user.getAvatar()));
if (!StringUtils.isBlank(imToken)) userServiceApi.updateImToken(user.getToken(), imToken);
return imToken;
}
@RequestMapping(value = "/token", method = RequestMethod.GET)
public MomiaHttpResponse getImToken(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
User user = userServiceApi.get(utoken);
String imToken = user.getImToken();
if (StringUtils.isBlank(imToken)) imToken = doGenerateImToken(user);
return MomiaHttpResponse.SUCCESS(imToken);
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
public MomiaHttpResponse getImUser(@RequestParam(value = "uid") long userId) {
if (userId <= 0) return MomiaHttpResponse.BAD_REQUEST;
User user = userServiceApi.get(userId);
JSONObject imUserJson = createImUser(user);
List<String> latestImgs = courseServiceApi.getLatestImgs(userId);
if (!latestImgs.isEmpty()) {
imUserJson.put("imgs", completeMiddleImgs(latestImgs));
}
return MomiaHttpResponse.SUCCESS(imUserJson);
}
private JSONObject createImUser(User user) {
JSONObject imUserJson = new JSONObject();
imUserJson.put("id", user.getId());
imUserJson.put("nickName", user.getNickName());
imUserJson.put("avatar", completeSmallImg(user.getAvatar()));
imUserJson.put("role", user.getRole());
return imUserJson;
}
@RequestMapping(value = "/group", method = RequestMethod.GET)
public MomiaHttpResponse getGroupInfo(@RequestParam(value = "id") long groupId) {
if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST;
Group group = imServiceApi.getGroup(groupId);
CourseSku sku = courseServiceApi.getSku(group.getCourseId(), group.getCourseSkuId());
JSONObject groupInfo = new JSONObject();
groupInfo.put("groupId", group.getGroupId());
groupInfo.put("groupName", group.getGroupName());
groupInfo.put("tips", courseServiceApi.queryTips(Sets.newHashSet(group.getCourseId())).get(String.valueOf(group.getCourseId())));
groupInfo.put("time", sku.getTime());
groupInfo.put("route", sku.getRoute());
groupInfo.put("address", sku.getPlace().getAddress());
return MomiaHttpResponse.SUCCESS(groupInfo);
}
@RequestMapping(value = "/group/member", method = RequestMethod.GET)
public MomiaHttpResponse listGroupMembers(@RequestParam String utoken, @RequestParam(value = "id") long groupId) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST;
User user = userServiceApi.get(utoken);
List<Member> members = imServiceApi.listGroupMembers(user.getId(), groupId);
Set<Long> userIds = new HashSet<Long>();
for (Member member : members) {
userIds.add(member.getUserId());
}
List<User> users = userServiceApi.list(userIds, User.Type.BASE);
Map<Long, User> usersMap = new HashMap<Long, User>();
for (User memberUser : users) {
usersMap.put(memberUser.getId(), memberUser);
}
List<JSONObject> teachers = new ArrayList<JSONObject>();
List<JSONObject> customers = new ArrayList<JSONObject>();
for (Member member : members) {
User memberUser = usersMap.get(member.getUserId());
if (memberUser == null) continue;
JSONObject imUserJson = createImUser(user);
if (member.isTeacher()) teachers.add(imUserJson);
else customers.add(imUserJson);
}
JSONObject responseJson = new JSONObject();
responseJson.put("teachers", teachers);
responseJson.put("customers", customers);
return MomiaHttpResponse.SUCCESS(responseJson);
}
@RequestMapping(value = "/user/group", method = RequestMethod.GET)
public MomiaHttpResponse listUserGroups(@RequestParam String utoken) {
if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
User user = userServiceApi.get(utoken);
List<Member> members = imServiceApi.queryMembersByUser(user.getId());
Set<Long> groupIds = new HashSet<Long>();
for (Member member : members) {
groupIds.add(member.getGroupId());
}
List<Group> groups = imServiceApi.listGroups(groupIds);
Map<Long, Group> groupsMap = new HashMap<Long, Group>();
Set<Long> courseIds = new HashSet<Long>();
for (Group group : groups) {
groupsMap.put(group.getGroupId(), group);
courseIds.add(group.getCourseId());
}
Map<Long, String> tipsOfCourses = courseServiceApi.queryTips(courseIds);
List<JSONObject> userGroups = new ArrayList<JSONObject>();
for (Member member : members) {
Group group = groupsMap.get(member.getGroupId());
if (group == null) continue;
JSONObject userGroup = new JSONObject();
userGroup.put("groupId", member.getGroupId());
userGroup.put("groupName", group.getGroupName());
userGroup.put("addTime", TimeUtil.STANDARD_DATE_FORMAT.format(member.getAddTime()));
userGroup.put("tips", tipsOfCourses.get(String.valueOf(group.getCourseId()))); // FIXME
userGroups.add(userGroup);
}
Collections.sort(userGroups, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject o1, JSONObject o2) {
return o1.getString("groupName").compareTo(o2.getString("groupName"));
}
});
return MomiaHttpResponse.SUCCESS(userGroups);
}
}
| refactor im
| src/main/java/cn/momia/mapi/api/v1/im/ImV1Api.java | refactor im | <ide><path>rc/main/java/cn/momia/mapi/api/v1/im/ImV1Api.java
<ide> import cn.momia.api.course.dto.CourseSku;
<ide> import cn.momia.api.im.ImServiceApi;
<ide> import cn.momia.api.im.dto.Group;
<del>import cn.momia.api.im.dto.Member;
<add>import cn.momia.api.im.dto.GroupMember;
<add>import cn.momia.api.im.dto.UserGroup;
<ide> import cn.momia.api.user.UserServiceApi;
<ide> import cn.momia.api.user.dto.User;
<ide> import cn.momia.common.core.http.MomiaHttpResponse;
<del>import cn.momia.common.core.util.TimeUtil;
<ide> import cn.momia.mapi.api.AbstractApi;
<ide> import com.alibaba.fastjson.JSONObject;
<ide> import com.google.common.collect.Sets;
<ide> import org.springframework.web.bind.annotation.RestController;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.Collections;
<del>import java.util.Comparator;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> }
<ide>
<ide> @RequestMapping(value = "/user", method = RequestMethod.GET)
<del> public MomiaHttpResponse getImUser(@RequestParam(value = "uid") long userId) {
<add> public MomiaHttpResponse getImUserInfo(@RequestParam(value = "uid") long userId) {
<ide> if (userId <= 0) return MomiaHttpResponse.BAD_REQUEST;
<ide>
<ide> User user = userServiceApi.get(userId);
<del> JSONObject imUserJson = createImUser(user);
<add> JSONObject imUserInfoJson = createImUserInfo(user);
<ide>
<ide> List<String> latestImgs = courseServiceApi.getLatestImgs(userId);
<ide> if (!latestImgs.isEmpty()) {
<del> imUserJson.put("imgs", completeMiddleImgs(latestImgs));
<add> imUserInfoJson.put("imgs", completeMiddleImgs(latestImgs));
<ide> }
<ide>
<del> return MomiaHttpResponse.SUCCESS(imUserJson);
<add> return MomiaHttpResponse.SUCCESS(imUserInfoJson);
<ide> }
<ide>
<del> private JSONObject createImUser(User user) {
<del> JSONObject imUserJson = new JSONObject();
<del> imUserJson.put("id", user.getId());
<del> imUserJson.put("nickName", user.getNickName());
<del> imUserJson.put("avatar", completeSmallImg(user.getAvatar()));
<del> imUserJson.put("role", user.getRole());
<add> private JSONObject createImUserInfo(User user) {
<add> JSONObject imUserInfoJson = new JSONObject();
<add> imUserInfoJson.put("id", user.getId());
<add> imUserInfoJson.put("nickName", user.getNickName());
<add> imUserInfoJson.put("avatar", completeSmallImg(user.getAvatar()));
<add> imUserInfoJson.put("role", user.getRole());
<ide>
<del> return imUserJson;
<add> return imUserInfoJson;
<ide> }
<ide>
<ide> @RequestMapping(value = "/group", method = RequestMethod.GET)
<ide> if (groupId <= 0) return MomiaHttpResponse.BAD_REQUEST;
<ide>
<ide> User user = userServiceApi.get(utoken);
<del> List<Member> members = imServiceApi.listGroupMembers(user.getId(), groupId);
<add> List<GroupMember> groupMembers = imServiceApi.listGroupMembers(user.getId(), groupId);
<ide>
<ide> Set<Long> userIds = new HashSet<Long>();
<del> for (Member member : members) {
<del> userIds.add(member.getUserId());
<add> for (GroupMember groupMember : groupMembers) {
<add> userIds.add(groupMember.getUserId());
<ide> }
<ide>
<ide> List<User> users = userServiceApi.list(userIds, User.Type.BASE);
<ide>
<ide> List<JSONObject> teachers = new ArrayList<JSONObject>();
<ide> List<JSONObject> customers = new ArrayList<JSONObject>();
<del> for (Member member : members) {
<del> User memberUser = usersMap.get(member.getUserId());
<add> for (GroupMember groupMember : groupMembers) {
<add> User memberUser = usersMap.get(groupMember.getUserId());
<ide> if (memberUser == null) continue;
<ide>
<del> JSONObject imUserJson = createImUser(user);
<del> if (member.isTeacher()) teachers.add(imUserJson);
<add> JSONObject imUserJson = createImUserInfo(user);
<add> if (groupMember.isTeacher()) teachers.add(imUserJson);
<ide> else customers.add(imUserJson);
<ide> }
<ide>
<ide> if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
<ide>
<ide> User user = userServiceApi.get(utoken);
<add> List<UserGroup> userGroups = imServiceApi.listUserGroups(user.getId());
<ide>
<del> List<Member> members = imServiceApi.queryMembersByUser(user.getId());
<del> Set<Long> groupIds = new HashSet<Long>();
<del> for (Member member : members) {
<del> groupIds.add(member.getGroupId());
<del> }
<del> List<Group> groups = imServiceApi.listGroups(groupIds);
<del> Map<Long, Group> groupsMap = new HashMap<Long, Group>();
<ide> Set<Long> courseIds = new HashSet<Long>();
<del> for (Group group : groups) {
<del> groupsMap.put(group.getGroupId(), group);
<del> courseIds.add(group.getCourseId());
<add> for (UserGroup userGroup : userGroups) {
<add> courseIds.add(userGroup.getCourseId());
<ide> }
<ide> Map<Long, String> tipsOfCourses = courseServiceApi.queryTips(courseIds);
<ide>
<del> List<JSONObject> userGroups = new ArrayList<JSONObject>();
<del> for (Member member : members) {
<del> Group group = groupsMap.get(member.getGroupId());
<del> if (group == null) continue;
<del>
<del> JSONObject userGroup = new JSONObject();
<del> userGroup.put("groupId", member.getGroupId());
<del> userGroup.put("groupName", group.getGroupName());
<del> userGroup.put("addTime", TimeUtil.STANDARD_DATE_FORMAT.format(member.getAddTime()));
<del> userGroup.put("tips", tipsOfCourses.get(String.valueOf(group.getCourseId()))); // FIXME
<del>
<del> userGroups.add(userGroup);
<add> for (UserGroup userGroup : userGroups) {
<add> userGroup.setTips(tipsOfCourses.get(String.valueOf(userGroup.getCourseId())));
<ide> }
<del>
<del> Collections.sort(userGroups, new Comparator<JSONObject>() {
<del> @Override
<del> public int compare(JSONObject o1, JSONObject o2) {
<del> return o1.getString("groupName").compareTo(o2.getString("groupName"));
<del> }
<del> });
<ide>
<ide> return MomiaHttpResponse.SUCCESS(userGroups);
<ide> } |
|
Java | epl-1.0 | ee8ce9737cefb8ffe3a4a2715558942869d60672 | 0 | golo-lang/golo-lang,golo-lang/golo-lang,golo-lang/golo-lang | /*
* Copyright (c) 2012-2020 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package gololang;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.eclipse.golo.runtime.InvalidDestructuringException;
import org.eclipse.golo.runtime.ArrayHelper;
/**
* Represents an tuple object.
* <p>
* A tuple essentially behaves like an immutable array. In Golo, tuples can be created as follows:
* <pre class="listing"><code class="lang-golo" data-lang="golo">
* # Short syntax
* let t1 = [1, 2, 3]
*
* # Complete collection literal syntax
* let t2 = tuple[1, 2, 3]
* </code></pre>
*/
public final class Tuple implements HeadTail<Object>, Comparable<Tuple> {
private static final Tuple EMPTY = new Tuple();
private final Object[] data;
/**
* Creates a new tuple from values.
*
* @param values the tuple values.
*/
public Tuple(Object... values) {
data = Arrays.copyOf(values, values.length);
}
/**
* Helper factory method.
*
* @param values the values as an array.
* @return a tuple from the array values.
*/
public static Tuple fromArray(Object[] values) {
if (values.length == 0) { return EMPTY; }
return new Tuple(values);
}
/**
* Gives the number of elements in this tuple.
*
* @return the tuple size.
*/
public int size() {
return data.length;
}
/**
* Checks whether the tuple is empty or not.
*
* @return {@code true} if the tuple has no element, {@code false} otherwise.
*/
@Override
public boolean isEmpty() {
return data.length == 0;
}
/**
* Gets the element at a specified index.
*
* @param index the element index.
* @return the element at index {@code index}.
* @throws IndexOutOfBoundsException if the specified {@code index} is not valid (negative value or above the size).
*/
public Object get(int index) {
if (index < 0 || index >= data.length) {
throw new IndexOutOfBoundsException(index + " is outside the bounds of a " + data.length + "-tuple");
}
return data[index];
}
/**
* Creates an iterator over the tuple.
* <p>The iterator does not support removal.
*
* @return an iterator.
*/
@Override
public Iterator<Object> iterator() {
return new Iterator<Object>() {
private int i = 0;
@Override
public boolean hasNext() {
return i < data.length;
}
@Override
public Object next() {
if (i >= data.length) {
throw new NoSuchElementException();
}
Object result = data[i];
i++;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Tuples are immutable");
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
Tuple tuple = (Tuple) o;
return Arrays.equals(data, tuple.data);
}
/**
* Compares this tuple with the specified tuple for order.
* <p>Returns a negative integer, zero, or a positive integer as this tuple is less than, equal to, or greater than the specified tuple.
* <p>Two tuples are compared using the lexicographical (dictionary) order, that is:
* {@code [1, 2] < [1, 3]} and {@code [2, 5] < [3, 1]}.
* <p> Two tuples are comparable if they have the same size and their elements are pairwise comparable.
*
* @param other the tuple to be compared.
* @return a negative integer, zero, or a positive integer as this tuple is less than, equal to, or greater than the specified tuple.
* @throws NullPointerException if the specified tuple is null.
* @throws ClassCastException if the type of the elements in the specified tuple prevent them from being compared to this tuple elements.
* @throws IllegalArgumentException if the specified tuple has a different size than this tuple.
*/
@Override
public int compareTo(Tuple other) {
if (this.equals(other)) {
return 0;
}
if (this.size() != other.size()) {
throw new IllegalArgumentException(String.format(
"%s and %s can't be compared since of different size", this, other));
}
for (int i = 0; i < size(); i++) {
if (!this.get(i).equals(other.get(i))) {
@SuppressWarnings("unchecked")
Comparable<Object> current = (Comparable<Object>) this.get(i);
return current.compareTo(other.get(i));
}
}
return 0;
}
@Override
public int hashCode() {
return Arrays.hashCode(data);
}
@Override
public String toString() {
return "tuple" + Arrays.toString(data);
}
/**
* Returns the first element of the tuple.
*
* @return the first element.
*/
@Override
public Object head() {
if (this.isEmpty()) {
return null;
}
return this.get(0);
}
/**
* Returns a new tuple containing the remaining elements.
*
* @return a tuple.
*/
@Override
public Tuple tail() {
return this.subTuple(1);
}
/**
* Helper for destructuring.
*
* @return the tuple itself
* @deprecated This method should not be called directly and is no more used by new style destructuring.
*/
public Tuple destruct() { return this; }
/**
* New style destructuring helper.
*
* New style destructuring must be exact. The number of variables to be affected is thus checked against the number of
* members of the structure.
*
* @param number number of variable that will be affected.
* @param substruct whether the destructuring is complete or should contains a sub structure.
* @return a tuple containing the values to assign.
*/
public Object[] __$$_destruct(int number, boolean substruct) {
Object[] destruct = ArrayHelper.newStyleDestruct(this.data, number, substruct);
if (number <= this.data.length + 1 && substruct) {
destruct[number - 1] = fromArray((Object[]) destruct[number - 1]);
}
return destruct;
}
/**
* Extract a sub-tuple.
*
* @param start the index of the first element.
* @return a new tuple containing the elements from {@code start} to the end.
*/
public Tuple subTuple(int start) {
return this.subTuple(start, data.length);
}
/**
* Extract a sub-tuple.
*
* @param start the index of the first element (inclusive).
* @param end the index of the last element (exclusive).
* @return a new tuple containing the elements between indices {@code start} inclusive and {@code end}
* exclusive.
*/
public Tuple subTuple(int start, int end) {
if (this.isEmpty()) {
return this;
}
return fromArray(Arrays.copyOfRange(data, start, end));
}
/**
* Returns an array containing all of the elements in this tuple.
*
* @return an array of values
*/
public Object[] toArray() {
return Arrays.copyOf(data, data.length);
}
/**
* Returns a new Tuple extended with the given values.
*
* @return an extended {@link Tuple}, or this one if no values are given.
*/
public Tuple extend(Object... values) {
if (values.length == 0) {
return this;
}
Object[] newdata = Arrays.copyOf(data, data.length + values.length);
for (int i = 0; i < values.length; i++) {
newdata[data.length + i] = values[i];
}
return new Tuple(newdata);
}
/**
* Returns a new Tuple extended with the given Tuple.
*
* @return an extended Tuple, or this one if the given tuple is empty.
*/
public Tuple extend(Tuple tuple) {
return this.extend(tuple.data);
}
}
| src/main/java/gololang/Tuple.java | /*
* Copyright (c) 2012-2020 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package gololang;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.eclipse.golo.runtime.InvalidDestructuringException;
/**
* Represents an tuple object.
* <p>
* A tuple essentially behaves like an immutable array. In Golo, tuples can be created as follows:
* <pre class="listing"><code class="lang-golo" data-lang="golo">
* # Short syntax
* let t1 = [1, 2, 3]
*
* # Complete collection literal syntax
* let t2 = tuple[1, 2, 3]
* </code></pre>
*/
public final class Tuple implements HeadTail<Object>, Comparable<Tuple> {
private static final Tuple EMPTY = new Tuple();
private final Object[] data;
/**
* Creates a new tuple from values.
*
* @param values the tuple values.
*/
public Tuple(Object... values) {
data = Arrays.copyOf(values, values.length);
}
/**
* Helper factory method.
*
* @param values the values as an array.
* @return a tuple from the array values.
*/
public static Tuple fromArray(Object[] values) {
return new Tuple(values);
}
/**
* Gives the number of elements in this tuple.
*
* @return the tuple size.
*/
public int size() {
return data.length;
}
/**
* Checks whether the tuple is empty or not.
*
* @return {@code true} if the tuple has no element, {@code false} otherwise.
*/
@Override
public boolean isEmpty() {
return data.length == 0;
}
/**
* Gets the element at a specified index.
*
* @param index the element index.
* @return the element at index {@code index}.
* @throws IndexOutOfBoundsException if the specified {@code index} is not valid (negative value or above the size).
*/
public Object get(int index) {
if (index < 0 || index >= data.length) {
throw new IndexOutOfBoundsException(index + " is outside the bounds of a " + data.length + "-tuple");
}
return data[index];
}
/**
* Creates an iterator over the tuple.
* <p>The iterator does not support removal.
*
* @return an iterator.
*/
@Override
public Iterator<Object> iterator() {
return new Iterator<Object>() {
private int i = 0;
@Override
public boolean hasNext() {
return i < data.length;
}
@Override
public Object next() {
if (i >= data.length) {
throw new NoSuchElementException();
}
Object result = data[i];
i++;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Tuples are immutable");
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
Tuple tuple = (Tuple) o;
return Arrays.equals(data, tuple.data);
}
/**
* Compares this tuple with the specified tuple for order.
* <p>Returns a negative integer, zero, or a positive integer as this tuple is less than, equal to, or greater than the specified tuple.
* <p>Two tuples are compared using the lexicographical (dictionary) order, that is:
* {@code [1, 2] < [1, 3]} and {@code [2, 5] < [3, 1]}.
* <p> Two tuples are comparable if they have the same size and their elements are pairwise comparable.
*
* @param other the tuple to be compared.
* @return a negative integer, zero, or a positive integer as this tuple is less than, equal to, or greater than the specified tuple.
* @throws NullPointerException if the specified tuple is null.
* @throws ClassCastException if the type of the elements in the specified tuple prevent them from being compared to this tuple elements.
* @throws IllegalArgumentException if the specified tuple has a different size than this tuple.
*/
@Override
public int compareTo(Tuple other) {
if (this.equals(other)) {
return 0;
}
if (this.size() != other.size()) {
throw new IllegalArgumentException(String.format(
"%s and %s can't be compared since of different size", this, other));
}
for (int i = 0; i < size(); i++) {
if (!this.get(i).equals(other.get(i))) {
@SuppressWarnings("unchecked")
Comparable<Object> current = (Comparable<Object>) this.get(i);
return current.compareTo(other.get(i));
}
}
return 0;
}
@Override
public int hashCode() {
return Arrays.hashCode(data);
}
@Override
public String toString() {
return "tuple" + Arrays.toString(data);
}
/**
* Returns the first element of the tuple.
*
* @return the first element.
*/
@Override
public Object head() {
if (this.isEmpty()) {
return null;
}
return this.get(0);
}
/**
* Returns a new tuple containing the remaining elements.
*
* @return a tuple.
*/
@Override
public Tuple tail() {
return this.subTuple(1);
}
/**
* Helper for destructuring.
*
* @return the tuple itself
* @deprecated This method should not be called directly and is no more used by new style destructuring.
*/
public Tuple destruct() { return this; }
/**
* New style destructuring helper.
*
* New style destructuring must be exact. The number of variables to be affected is thus checked against the number of
* members of the structure.
*
* @param number number of variable that will be affected.
* @param substruct whether the destructuring is complete or should contains a sub structure.
* @return a tuple containing the values to assign.
*/
public Object[] __$$_destruct(int number, boolean substruct) {
if (number < this.data.length && !substruct) {
throw InvalidDestructuringException.notEnoughValues(number, this.data.length, substruct);
}
if (number == this.data.length && !substruct) {
return Arrays.copyOf(this.data, number);
}
if (number <= this.data.length && substruct) {
Object[] destruct = new Object[number];
System.arraycopy(this.data, 0, destruct, 0, number - 1);
destruct[number - 1] = this.subTuple(number - 1);
return destruct;
}
if (number == this.data.length + 1 && substruct) {
Object[] destruct = Arrays.copyOf(this.data, number);
destruct[number - 1] = EMPTY;
return destruct;
}
throw InvalidDestructuringException.tooManyValues(number);
}
/**
* Extract a sub-tuple.
*
* @param start the index of the first element.
* @return a new tuple containing the elements from {@code start} to the end.
*/
public Tuple subTuple(int start) {
return this.subTuple(start, data.length);
}
/**
* Extract a sub-tuple.
*
* @param start the index of the first element (inclusive).
* @param end the index of the last element (exclusive).
* @return a new tuple containing the elements between indices {@code start} inclusive and {@code end}
* exclusive.
*/
public Tuple subTuple(int start, int end) {
if (this.isEmpty()) {
return this;
}
return fromArray(Arrays.copyOfRange(data, start, end));
}
/**
* Returns an array containing all of the elements in this tuple.
*
* @return an array of values
*/
public Object[] toArray() {
return Arrays.copyOf(data, data.length);
}
/**
* Returns a new Tuple extended with the given values.
*
* @return an extended {@link Tuple}, or this one if no values are given.
*/
public Tuple extend(Object... values) {
if (values.length == 0) {
return this;
}
Object[] newdata = Arrays.copyOf(data, data.length + values.length);
for (int i = 0; i < values.length; i++) {
newdata[data.length + i] = values[i];
}
return new Tuple(newdata);
}
/**
* Returns a new Tuple extended with the given Tuple.
*
* @return an extended Tuple, or this one if the given tuple is empty.
*/
public Tuple extend(Tuple tuple) {
return this.extend(tuple.data);
}
}
| Refactor tuple to use array implementation
| src/main/java/gololang/Tuple.java | Refactor tuple to use array implementation | <ide><path>rc/main/java/gololang/Tuple.java
<ide> import java.util.Iterator;
<ide> import java.util.NoSuchElementException;
<ide> import org.eclipse.golo.runtime.InvalidDestructuringException;
<add>import org.eclipse.golo.runtime.ArrayHelper;
<ide>
<ide> /**
<ide> * Represents an tuple object.
<ide> * @return a tuple from the array values.
<ide> */
<ide> public static Tuple fromArray(Object[] values) {
<add> if (values.length == 0) { return EMPTY; }
<ide> return new Tuple(values);
<ide> }
<ide>
<ide> * @return a tuple containing the values to assign.
<ide> */
<ide> public Object[] __$$_destruct(int number, boolean substruct) {
<del> if (number < this.data.length && !substruct) {
<del> throw InvalidDestructuringException.notEnoughValues(number, this.data.length, substruct);
<del> }
<del> if (number == this.data.length && !substruct) {
<del> return Arrays.copyOf(this.data, number);
<del> }
<del> if (number <= this.data.length && substruct) {
<del> Object[] destruct = new Object[number];
<del> System.arraycopy(this.data, 0, destruct, 0, number - 1);
<del> destruct[number - 1] = this.subTuple(number - 1);
<del> return destruct;
<del> }
<del> if (number == this.data.length + 1 && substruct) {
<del> Object[] destruct = Arrays.copyOf(this.data, number);
<del> destruct[number - 1] = EMPTY;
<del> return destruct;
<del> }
<del> throw InvalidDestructuringException.tooManyValues(number);
<add> Object[] destruct = ArrayHelper.newStyleDestruct(this.data, number, substruct);
<add> if (number <= this.data.length + 1 && substruct) {
<add> destruct[number - 1] = fromArray((Object[]) destruct[number - 1]);
<add> }
<add> return destruct;
<ide> }
<ide>
<ide> /** |
|
JavaScript | apache-2.0 | a7bb36a95010ab590c48925e68a3d7cac6c33679 | 0 | NextCenturyCorporation/digapp-ht,NextCenturyCorporation/digapp-ht,NextCenturyCorporation/digapp-ht,NextCenturyCorporation/digapp-ht | /*
* Copyright 2017 Next Century Corporation
*
* 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.
*/
/* exported searchTransform */
/* jshint camelcase:false */
var searchTransform = (function(_, commonTransforms) {
function getAggregationDataFromResponse(response, config) {
if(config && config.networkExpansionQuery) {
if(response && response.length && response[0].result && response[0].result.length > 1 && response[0].result[1].aggregations && response[0].result[1].aggregations['?' + config.name]) {
return response[0].result[1].aggregations['?' + config.name].buckets || [];
}
} else {
if(response && response.length && response[0].result && response[0].result.aggregations && response[0].result.aggregations['?' + config.name]) {
return response[0].result.aggregations['?' + config.name].buckets || [];
}
}
return [];
}
function getTemplateFromSearchParameters(searchParameters, networkExpansionParameters) {
var predicates = {};
var template = {
clauses: !networkExpansionParameters ? [] : [{
clauses: [],
type: 'Ad',
variable: '?ad1'
}],
filters: []
};
var andFilter = {
clauses: [],
operator: 'and'
};
var notFilter = {
clauses: [],
operator: 'not exists'
};
if(!_.isEmpty(searchParameters)) {
_.keys(searchParameters).forEach(function(type) {
var predicate = commonTransforms.getDatabaseTypeFromUiType(type);
var unionClause = {
clauses: [],
operator: 'union'
};
_.keys(searchParameters[type]).forEach(function(term) {
if(searchParameters[type][term].enabled) {
if(type === 'postingDate') {
// Use only a single date variable ('date1').
predicates.date = [{
optional: false
}];
andFilter.clauses.push({
constraint: searchParameters[type][term].date,
operator: term === 'dateStart' ? '>' : '<',
variable: '?date1'
});
} else if(predicate && searchParameters[type][term].search === 'excluded') {
notFilter.clauses.push({
constraint: searchParameters[type][term].key,
predicate: predicate
});
} else if(predicate && searchParameters[type][term].search === 'union') {
unionClause.clauses.push({
constraint: searchParameters[type][term].key,
isOptional: false,
predicate: predicate
});
} else if(predicate) {
var optional = (searchParameters[type][term].search !== 'required');
if(!networkExpansionParameters) {
predicates[predicate] = predicates[predicate] || [];
predicates[predicate].push({
optional: optional
});
template.clauses.push({
constraint: searchParameters[type][term].key,
isOptional: optional,
predicate: predicate
});
} else {
// we only want to add exact search terms entered in by the user to the initial query, not the expanded query
template.clauses[0].clauses.push({
constraint: searchParameters[type][term].key,
isOptional: optional,
predicate: predicate
});
if(!networkExpansionParameters[type]) {
template.clauses.push({
constraint: searchParameters[type][term].key,
isOptional: optional,
predicate: predicate
});
}
}
}
}
});
if(unionClause.clauses.length) {
template.clauses.push(unionClause);
}
if(networkExpansionParameters && networkExpansionParameters[type] && !predicates[predicate]) {
// TODO Should predicate variables for network expansion queries always be required?
predicates[predicate] = [{
optional: false
}];
}
});
_.keys(predicates).forEach(function(predicate) {
for(var i = 1; i <= predicates[predicate].length; ++i) {
if(!networkExpansionParameters) {
template.clauses.push({
isOptional: predicates[predicate][i - 1].optional,
predicate: predicate === 'date' ? 'posting_date' : predicate,
variable: '?' + predicate + i
});
} else {
template.clauses.push({
isOptional: predicates[predicate][i - 1].optional,
predicate: predicate === 'date' ? 'posting_date' : predicate,
variable: (predicate === 'date' ? ('?' + predicate + i) : ('?' + predicate))
});
template.clauses[0].clauses.push({
isOptional: predicates[predicate][i - 1].optional,
predicate: predicate === 'date' ? 'posting_date' : predicate,
variable: (predicate === 'date' ? ('?' + predicate + i) : ('?' + predicate))
});
}
}
});
}
if(andFilter.clauses.length) {
template.filters.push(andFilter);
}
if(notFilter.clauses.length) {
template.filters.push(notFilter);
}
return template;
}
return {
adQuery: function(searchParameters, config) {
var networkExpansionParameters = config ? config.custom : {};
var networkExpansionQuery = _.findKey(networkExpansionParameters, function(param) { return param === true; }) ? true : false;
var template = getTemplateFromSearchParameters(searchParameters, networkExpansionQuery ? networkExpansionParameters : undefined);
var groupBy = (!config || !config.page || !config.pageSize) ? undefined : {
limit: config.pageSize,
offset: (config.page - 1) * config.pageSize
};
return {
SPARQL: {
'group-by': groupBy,
select: {
variables: [{
type: 'simple',
variable: !networkExpansionQuery ? '?ad' : '?ad2'
}]
},
where: {
clauses: template.clauses,
filters: template.filters,
type: 'Ad',
variable: !networkExpansionQuery ? '?ad' : '?ad2'
}
},
type: 'Point Fact'
};
},
adResults: function(response, config) {
var fields = {};
// network expansion queries return an array of two result records instead of a single result
if(config && config.networkExpansionQuery) {
if(response && response.length && response[0].result && response[0].result.length > 1) {
if(response[0].query && response[0].query.SPARQL && response[0].query.SPARQL.where && response[0].query.SPARQL.where.clauses && response[0].query.SPARQL.where.clauses.length && response[0].query.SPARQL.where.clauses[0].clauses && response[0].query.SPARQL.where.clauses[0].clauses.length) {
response[0].query.SPARQL.where.clauses[0].clauses.forEach(function(clause) {
if(clause.predicate && clause.constraint && clause._id) {
var type = commonTransforms.getUiTypeFromDatabaseType(clause.predicate);
fields[type] = fields[type] || {};
fields[type][clause.constraint.toLowerCase()] = clause._id;
}
});
}
return {
fields: fields,
hits: response[0].result[1].hits || []
};
}
} else {
if(response && response.length && response[0].result) {
if(response[0].query && response[0].query.SPARQL && response[0].query.SPARQL.where && response[0].query.SPARQL.where.clauses && response[0].query.SPARQL.where.clauses.length) {
response[0].query.SPARQL.where.clauses.forEach(function(clause) {
if(clause.predicate && clause.constraint && clause._id) {
var type = commonTransforms.getUiTypeFromDatabaseType(clause.predicate);
fields[type] = fields[type] || {};
fields[type][clause.constraint] = clause._id;
}
});
}
return {
fields: fields,
hits: response[0].result.hits || []
};
}
}
return {
fields: {},
hits: {}
};
},
facetsQuery: function(searchParameters, config) {
var networkExpansionParameters = config ? config.custom : {};
var networkExpansionQuery = _.findKey(networkExpansionParameters, function(param) { return param === true; }) ? true : false;
var predicate = (config && config.aggregationType ? commonTransforms.getDatabaseTypeFromUiType(config.aggregationType) : undefined);
var template = getTemplateFromSearchParameters(searchParameters, networkExpansionQuery ? networkExpansionParameters : undefined);
var groupBy = {
limit: (config && config.pageSize ? config.pageSize : 0),
offset: 0
};
var orderBy;
var selects;
if(predicate) {
selects = [{
'function': 'count',
type: 'function',
variable: '?' + predicate
}];
// TODO What does this if statement mean?
if(!networkExpansionQuery || (_.findIndex(template.clauses, function(clause) {
return clause.predicate === predicate && clause.variable === '?' + predicate;
}) === -1)) {
template.clauses.push({
isOptional: false,
predicate: predicate,
variable: '?' + predicate
});
if(networkExpansionQuery && template.clauses.length && template.clauses[0].clauses) {
template.clauses[0].clauses.push({
isOptional: false,
predicate: predicate,
variable: '?' + predicate
});
}
}
groupBy.variables = [{
variable: '?' + predicate
}];
orderBy = {
values: [{
'function': (config && config.sortOrder === '_term' ? undefined : 'count'),
order: (config && config.sortOrder === '_term' ? 'asc' : 'desc'),
variable: '?' + predicate
}]
};
}
return {
SPARQL: {
'group-by': groupBy,
'order-by': orderBy,
select: {
variables: selects || []
},
where: {
clauses: template.clauses,
filters: template.filters,
type: 'Ad',
variable: '?ad'
}
},
type: 'Aggregation'
};
},
cityAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var city = commonTransforms.getLocationDataFromId(bucket.key).city;
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: city,
link: commonTransforms.getLink(bucket.key, 'location'),
text: city
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}).filter(function(city) {
return city.text;
});
},
emailAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var id = ('' + bucket.key).toLowerCase();
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: id,
link: commonTransforms.getLink(bucket.key, 'email')
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
filterAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var id = ('' + bucket.key).toLowerCase();
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: id
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
phoneAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: bucket.key,
link: commonTransforms.getLink(bucket.key, 'phone'),
text: commonTransforms.getFormattedPhone(bucket.key)
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
socialMediaAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var id = ('' + bucket.key).toLowerCase();
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: id.substring(id.indexOf(' ') + 1, id.length),
link: commonTransforms.getLink(bucket.key, 'social'),
text: id
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
reviewAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var extractionData = commonTransforms.getExtractionDataFromCompoundId(bucket.key);
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: extractionData.id,
link: commonTransforms.getLink(bucket.key, 'review'),
text: extractionData.text
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
// Heights, prices, weights, etc.
compoundExtractionAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var extractionData = commonTransforms.getExtractionDataFromCompoundId(bucket.key);
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: extractionData.id,
text: extractionData.text
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}).filter(function(extraction) {
return extraction.text;
});
}
};
});
| app/scripts/search-transform.js | /*
* Copyright 2017 Next Century Corporation
*
* 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.
*/
/* exported searchTransform */
/* jshint camelcase:false */
var searchTransform = (function(_, commonTransforms) {
function getAggregationDataFromResponse(response, config) {
if(config && config.networkExpansionQuery) {
if(response && response.length && response[0].result && response[0].result.length > 1 && response[0].result[1].aggregations && response[0].result[1].aggregations['?' + config.name]) {
return response[0].result[1].aggregations['?' + config.name].buckets || [];
}
} else {
if(response && response.length && response[0].result && response[0].result.aggregations && response[0].result.aggregations['?' + config.name]) {
return response[0].result.aggregations['?' + config.name].buckets || [];
}
}
return [];
}
function getTemplateFromSearchParameters(searchParameters, networkExpansionParameters) {
var predicates = {};
var template = {
clauses: !networkExpansionParameters ? [] : [{
clauses: [],
type: 'Ad',
variable: '?ad1'
}],
filters: []
};
var andFilter = {
clauses: [],
operator: 'and'
};
var notFilter = {
clauses: [],
operator: 'not exists'
};
if(!_.isEmpty(searchParameters)) {
_.keys(searchParameters).forEach(function(type) {
var predicate = commonTransforms.getDatabaseTypeFromUiType(type);
var unionClause = {
clauses: [],
operator: 'union'
};
_.keys(searchParameters[type]).forEach(function(term) {
if(searchParameters[type][term].enabled) {
if(type === 'postingDate') {
// Use only a single date variable ('date1').
predicates.date = [{
optional: false
}];
andFilter.clauses.push({
constraint: searchParameters[type][term].date,
operator: term === 'dateStart' ? '>' : '<',
variable: '?date1'
});
} else if(predicate && searchParameters[type][term].search === 'excluded') {
notFilter.clauses.push({
constraint: searchParameters[type][term].key,
predicate: predicate
});
} else if(predicate && searchParameters[type][term].search === 'union') {
unionClause.clauses.push({
constraint: searchParameters[type][term].key,
isOptional: false,
predicate: predicate
});
} else if(predicate) {
var optional = (searchParameters[type][term].search !== 'required');
if(!networkExpansionParameters) {
predicates[predicate] = predicates[predicate] || [];
predicates[predicate].push({
optional: optional
});
template.clauses.push({
constraint: searchParameters[type][term].key,
isOptional: optional,
predicate: predicate
});
} else {
// we only want to add exact search terms entered in by the user to the initial query, not the expanded query
template.clauses[0].clauses.push({
constraint: searchParameters[type][term].key,
isOptional: optional,
predicate: predicate
});
if(!networkExpansionParameters[type]) {
template.clauses.push({
constraint: searchParameters[type][term].key,
isOptional: optional,
predicate: predicate
});
}
}
}
}
});
if(unionClause.clauses.length) {
template.clauses.push(unionClause);
}
if(networkExpansionParameters && networkExpansionParameters[type] && !predicates[predicate]) {
// TODO Should predicate variables for network expansion queries always be required?
predicates[predicate] = [{
optional: false
}];
}
});
_.keys(predicates).forEach(function(predicate) {
for(var i = 1; i <= predicates[predicate].length; ++i) {
if(!networkExpansionParameters) {
template.clauses.push({
isOptional: predicates[predicate][i - 1].optional,
predicate: predicate === 'date' ? 'posting_date' : predicate,
variable: '?' + predicate + i
});
} else {
template.clauses.push({
isOptional: predicates[predicate][i - 1].optional,
predicate: predicate === 'date' ? 'posting_date' : predicate,
variable: (predicate === 'date' ? ('?' + predicate + i) : ('?' + predicate))
});
template.clauses[0].clauses.push({
isOptional: predicates[predicate][i - 1].optional,
predicate: predicate === 'date' ? 'posting_date' : predicate,
variable: (predicate === 'date' ? ('?' + predicate + i) : ('?' + predicate))
});
}
}
});
}
if(andFilter.clauses.length) {
template.filters.push(andFilter);
}
if(notFilter.clauses.length) {
template.filters.push(notFilter);
}
return template;
}
return {
adQuery: function(searchParameters, config) {
var networkExpansionParameters = config ? config.custom : {};
var networkExpansionQuery = _.findKey(networkExpansionParameters, function(param) { return param === true; }) ? true : false;
var template = getTemplateFromSearchParameters(searchParameters, networkExpansionQuery ? networkExpansionParameters : undefined);
var groupBy = (!config || !config.page || !config.pageSize) ? undefined : {
limit: config.pageSize,
offset: (config.page - 1) * config.pageSize
};
return {
SPARQL: {
'group-by': groupBy,
select: {
variables: [{
type: 'simple',
variable: !networkExpansionQuery ? '?ad' : '?ad2'
}]
},
where: {
clauses: template.clauses,
filters: template.filters,
type: 'Ad',
variable: !networkExpansionQuery ? '?ad' : '?ad2'
}
},
type: 'Point Fact'
};
},
adResults: function(response, config) {
var fields = {};
// network expansion queries return an array of two result records instead of a single result
if(config && config.networkExpansionQuery) {
if(response && response.length && response[0].result && response[0].result.length > 1) {
if(response[0].query && response[0].query.SPARQL && response[0].query.SPARQL.where && response[0].query.SPARQL.where.clauses && response[0].query.SPARQL.where.clauses.length && response[0].query.SPARQL.where.clauses[0].clauses && response[0].query.SPARQL.where.clauses[0].clauses.length) {
response[0].query.SPARQL.where.clauses[0].clauses.forEach(function(clause) {
if(clause.predicate && clause.constraint && clause._id) {
var type = commonTransforms.getUiTypeFromDatabaseType(clause.predicate);
fields[type] = fields[type] || {};
fields[type][clause.constraint.toLowerCase()] = clause._id;
}
});
}
return {
fields: fields,
hits: response[0].result[1].hits || []
};
}
} else {
if(response && response.length && response[0].result) {
if(response[0].query && response[0].query.SPARQL && response[0].query.SPARQL.where && response[0].query.SPARQL.where.clauses && response[0].query.SPARQL.where.clauses.length) {
response[0].query.SPARQL.where.clauses.forEach(function(clause) {
if(clause.predicate && clause.constraint && clause._id) {
var type = commonTransforms.getUiTypeFromDatabaseType(clause.predicate);
fields[type] = fields[type] || {};
fields[type][clause.constraint] = clause._id;
}
});
}
return {
fields: fields,
hits: response[0].result.hits || []
};
}
}
return {
fields: {},
hits: {}
};
},
facetsQuery: function(searchParameters, config) {
var networkExpansionParameters = config ? config.custom : {};
var networkExpansionQuery = _.findKey(networkExpansionParameters, function(param) { return param === true; }) ? true : false;
var predicate = (config && config.aggregationType ? commonTransforms.getDatabaseTypeFromUiType(config.aggregationType) : undefined);
var template = getTemplateFromSearchParameters(searchParameters, networkExpansionQuery ? networkExpansionParameters : undefined);
var groupBy = {
limit: (config && config.pageSize ? config.pageSize : 0),
offset: 0
};
var orderBy;
var selects;
if(predicate) {
var selects = [{
'function': 'count',
type: 'function',
variable: '?' + predicate
}];
// TODO What does this if statement mean?
if(!networkExpansionQuery || (_.findIndex(template.clauses, function(clause) {
return clause.predicate === predicate && clause.variable === '?' + predicate;
}) === -1)) {
template.clauses.push({
isOptional: false,
predicate: predicate,
variable: '?' + predicate
});
if(networkExpansionQuery && template.clauses.length && template.clauses[0].clauses) {
template.clauses[0].clauses.push({
isOptional: false,
predicate: predicate,
variable: '?' + predicate
});
}
}
groupBy.variables = [{
variable: '?' + predicate
}];
orderBy = {
values: [{
'function': (config && config.sortOrder === '_term' ? undefined : 'count'),
order: (config && config.sortOrder === '_term' ? 'asc' : 'desc'),
variable: '?' + predicate
}]
};
}
return {
SPARQL: {
'group-by': groupBy,
'order-by': orderBy,
select: {
variables: selects || []
},
where: {
clauses: template.clauses,
filters: template.filters,
type: 'Ad',
variable: '?ad'
}
},
type: 'Aggregation'
};
},
cityAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var city = commonTransforms.getLocationDataFromId(bucket.key).city;
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: city,
link: commonTransforms.getLink(bucket.key, 'location'),
text: city
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}).filter(function(city) {
return city.text;
});
},
emailAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var id = ('' + bucket.key).toLowerCase();
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: id,
link: commonTransforms.getLink(bucket.key, 'email')
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
filterAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var id = ('' + bucket.key).toLowerCase();
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: id
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
phoneAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: bucket.key,
link: commonTransforms.getLink(bucket.key, 'phone'),
text: commonTransforms.getFormattedPhone(bucket.key)
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
socialMediaAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var id = ('' + bucket.key).toLowerCase();
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: id.substring(id.indexOf(' ') + 1, id.length),
link: commonTransforms.getLink(bucket.key, 'social'),
text: id
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
reviewAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var extractionData = commonTransforms.getExtractionDataFromCompoundId(bucket.key);
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: extractionData.id,
link: commonTransforms.getLink(bucket.key, 'review'),
text: extractionData.text
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
});
},
// Heights, prices, weights, etc.
compoundExtractionAggregations: function(response, config) {
if(!config || !config.name) {
return [];
}
var newConfig = {
name: commonTransforms.getDatabaseTypeFromUiType(config.name),
networkExpansionQuery: config.networkExpansionQuery
};
var data = getAggregationDataFromResponse(response, newConfig);
return data.map(function(bucket) {
var extractionData = commonTransforms.getExtractionDataFromCompoundId(bucket.key);
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
return {
count: bucket.doc_count,
id: extractionData.id,
text: extractionData.text
};
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}).filter(function(extraction) {
return extraction.text;
});
}
};
});
| Fixed lint error.
| app/scripts/search-transform.js | Fixed lint error. | <ide><path>pp/scripts/search-transform.js
<ide> var selects;
<ide>
<ide> if(predicate) {
<del> var selects = [{
<add> selects = [{
<ide> 'function': 'count',
<ide> type: 'function',
<ide> variable: '?' + predicate |
|
Java | lgpl-2.1 | 1c97ec7092ff410ef8d3a1f78d0b449193899e14 | 0 | cwarden/kettle,juanmjacobs/kettle,cwarden/kettle,juanmjacobs/kettle,cwarden/kettle,juanmjacobs/kettle | package org.pentaho.di.core.database.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.pentaho.di.core.database.Messages;
public class DatabaseUtil
{
private static Map<String,DataSource> FoundDS = Collections.synchronizedMap(new HashMap<String,DataSource>());
/**
* Since JNDI is supported different ways in different app servers, it's
* nearly impossible to have a ubiquitous way to look up a datasource. This
* method is intended to hide all the lookups that may be required to find a
* jndi name.
*
* @param dsName
* The Datasource name
* @return DataSource if there is one bound in JNDI
* @throws NamingException
*/
public static DataSource getDataSourceFromJndi(String dsName) throws NamingException
{
Object foundDs = FoundDS.get(dsName);
if (foundDs != null)
{
return (DataSource) foundDs;
}
InitialContext ctx = new InitialContext();
Object lkup = null;
DataSource rtn = null;
NamingException firstNe = null;
// First, try what they ask for...
try
{
lkup = ctx.lookup(dsName);
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
firstNe = ignored;
}
try
{
// Needed this for Jboss
lkup = ctx.lookup("java:" + dsName); //$NON-NLS-1$
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
}
try
{
// Tomcat
lkup = ctx.lookup("java:comp/env/jdbc/" + dsName); //$NON-NLS-1$
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
}
try
{
// Others?
lkup = ctx.lookup("jdbc/" + dsName); //$NON-NLS-1$
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
}
if (firstNe != null)
{
throw firstNe;
}
throw new NamingException(Messages.getString("DatabaseUtil.DSNotFound", dsName)); //$NON-NLS-1$
}
}
| src/org/pentaho/di/core/database/util/DatabaseUtil.java | package org.pentaho.di.core.database.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.pentaho.di.core.database.Messages;
public class DatabaseUtil
{
private static Map<String,DataSource> FoundDS = Collections.synchronizedMap(new HashMap<String,DataSource>());
/**
* Since JNDI is supported different ways in different app servers, it's
* nearly impossible to have a ubiquitous way to look up a datasource. This
* method is intended to hide all the lookups that may be required to find a
* jndi name.
*
* @param dsName
* The Datasource name
* @return DataSource if there is one bound in JNDI
* @throws NamingException
*/
public static DataSource getDataSourceFromJndi(String dsName) throws NamingException
{
Object foundDs = FoundDS.get(dsName);
if (foundDs != null)
{
return (DataSource) foundDs;
}
InitialContext ctx = new InitialContext();
Object lkup = null;
DataSource rtn = null;
NamingException firstNe = null;
// First, try what they ask for...
try
{
lkup = ctx.lookup(dsName);
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
firstNe = ignored;
}
try
{
// Needed this for Jboss
lkup = ctx.lookup("java:" + dsName); //$NON-NLS-1$
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
}
try
{
// Tomcat
lkup = ctx.lookup("java:comp/env/jdbc/" + dsName); //$NON-NLS-1$
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
}
try
{
// Others?
lkup = ctx.lookup("jdbc/" + dsName); //$NON-NLS-1$
if (lkup != null)
{
rtn = (DataSource) lkup;
FoundDS.put(dsName, rtn);
return rtn;
}
} catch (NamingException ignored)
{
}
if (firstNe != null)
{
throw firstNe;
}
throw new NamingException(Messages.getString(
"DatabaseUtil.DSNotFound", dsName)); //$NON-NLS-1$
}
}
| Fix formatting throwing Pentaho Translator off guard.
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@5566 5fb7f6ec-07c1-534a-b4ca-9155e429e800
| src/org/pentaho/di/core/database/util/DatabaseUtil.java | Fix formatting throwing Pentaho Translator off guard. | <ide><path>rc/org/pentaho/di/core/database/util/DatabaseUtil.java
<ide> {
<ide> throw firstNe;
<ide> }
<del> throw new NamingException(Messages.getString(
<del> "DatabaseUtil.DSNotFound", dsName)); //$NON-NLS-1$
<add> throw new NamingException(Messages.getString("DatabaseUtil.DSNotFound", dsName)); //$NON-NLS-1$
<ide> }
<ide> } |
|
Java | apache-2.0 | 09faa72296a4a20bf554da729dccd5bd31a5e347 | 0 | tbrooks8/netty,fenik17/netty,artgon/netty,Squarespace/netty,andsel/netty,mikkokar/netty,bryce-anderson/netty,tbrooks8/netty,NiteshKant/netty,NiteshKant/netty,doom369/netty,mikkokar/netty,netty/netty,netty/netty,Spikhalskiy/netty,bryce-anderson/netty,johnou/netty,doom369/netty,NiteshKant/netty,fengjiachun/netty,doom369/netty,zer0se7en/netty,fengjiachun/netty,doom369/netty,jchambers/netty,NiteshKant/netty,mikkokar/netty,fengjiachun/netty,johnou/netty,Squarespace/netty,ejona86/netty,Squarespace/netty,Squarespace/netty,ejona86/netty,Spikhalskiy/netty,Spikhalskiy/netty,zer0se7en/netty,artgon/netty,artgon/netty,andsel/netty,fenik17/netty,andsel/netty,artgon/netty,zer0se7en/netty,mikkokar/netty,johnou/netty,netty/netty,zer0se7en/netty,andsel/netty,jchambers/netty,mikkokar/netty,bryce-anderson/netty,ejona86/netty,NiteshKant/netty,zer0se7en/netty,fengjiachun/netty,doom369/netty,fenik17/netty,ejona86/netty,tbrooks8/netty,tbrooks8/netty,Spikhalskiy/netty,artgon/netty,netty/netty,Squarespace/netty,fenik17/netty,jchambers/netty,johnou/netty,andsel/netty,netty/netty,ejona86/netty,jchambers/netty,bryce-anderson/netty,fenik17/netty,jchambers/netty,fengjiachun/netty,Spikhalskiy/netty,bryce-anderson/netty,johnou/netty,tbrooks8/netty | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.spdy;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.spdy.SpdyHttpHeaders.Names;
import io.netty.util.ReferenceCountUtil;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
/**
* {@link MessageToMessageCodec} that takes care of adding the right {@link SpdyHttpHeaders.Names#STREAM_ID} to the
* {@link HttpMessage} if one is not present. This makes it possible to just re-use plan handlers current used
* for HTTP.
*/
public class SpdyHttpResponseStreamIdHandler extends
MessageToMessageCodec<Object, HttpMessage> {
private static final Integer NO_ID = -1;
private final Queue<Integer> ids = new ArrayDeque<Integer>();
@Override
public boolean acceptInboundMessage(Object msg) throws Exception {
return msg instanceof HttpMessage || msg instanceof SpdyRstStreamFrame;
}
@Override
protected void encode(ChannelHandlerContext ctx, HttpMessage msg, List<Object> out) throws Exception {
Integer id = ids.poll();
if (id != null && id.intValue() != NO_ID && !msg.headers().contains(SpdyHttpHeaders.Names.STREAM_ID)) {
msg.headers().setInt(Names.STREAM_ID, id);
}
out.add(ReferenceCountUtil.retain(msg));
}
@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
if (msg instanceof HttpMessage) {
boolean contains = ((HttpMessage) msg).headers().contains(SpdyHttpHeaders.Names.STREAM_ID);
if (!contains) {
ids.add(NO_ID);
} else {
ids.add(((HttpMessage) msg).headers().getInt(Names.STREAM_ID));
}
} else if (msg instanceof SpdyRstStreamFrame) {
ids.remove(((SpdyRstStreamFrame) msg).streamId());
}
out.add(ReferenceCountUtil.retain(msg));
}
}
| codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpResponseStreamIdHandler.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.spdy;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.spdy.SpdyHttpHeaders.Names;
import io.netty.util.ReferenceCountUtil;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* {@link MessageToMessageCodec} that takes care of adding the right {@link SpdyHttpHeaders.Names#STREAM_ID} to the
* {@link HttpMessage} if one is not present. This makes it possible to just re-use plan handlers current used
* for HTTP.
*/
public class SpdyHttpResponseStreamIdHandler extends
MessageToMessageCodec<Object, HttpMessage> {
private static final Integer NO_ID = -1;
private final Queue<Integer> ids = new LinkedList<Integer>();
@Override
public boolean acceptInboundMessage(Object msg) throws Exception {
return msg instanceof HttpMessage || msg instanceof SpdyRstStreamFrame;
}
@Override
protected void encode(ChannelHandlerContext ctx, HttpMessage msg, List<Object> out) throws Exception {
Integer id = ids.poll();
if (id != null && id.intValue() != NO_ID && !msg.headers().contains(SpdyHttpHeaders.Names.STREAM_ID)) {
msg.headers().setInt(Names.STREAM_ID, id);
}
out.add(ReferenceCountUtil.retain(msg));
}
@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
if (msg instanceof HttpMessage) {
boolean contains = ((HttpMessage) msg).headers().contains(SpdyHttpHeaders.Names.STREAM_ID);
if (!contains) {
ids.add(NO_ID);
} else {
ids.add(((HttpMessage) msg).headers().getInt(Names.STREAM_ID));
}
} else if (msg instanceof SpdyRstStreamFrame) {
ids.remove(((SpdyRstStreamFrame) msg).streamId());
}
out.add(ReferenceCountUtil.retain(msg));
}
}
| Use ArrayDeque instead of LinkedList (#9046)
Motivation:
Prefer ArrayDeque to LinkedList because latter will produce more GC.
Modification:
- Replace LinkedList with ArrayDeque
Result:
Less GC
| codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpResponseStreamIdHandler.java | Use ArrayDeque instead of LinkedList (#9046) | <ide><path>odec-http/src/main/java/io/netty/handler/codec/spdy/SpdyHttpResponseStreamIdHandler.java
<ide> import io.netty.handler.codec.spdy.SpdyHttpHeaders.Names;
<ide> import io.netty.util.ReferenceCountUtil;
<ide>
<del>import java.util.LinkedList;
<add>import java.util.ArrayDeque;
<ide> import java.util.List;
<ide> import java.util.Queue;
<ide>
<ide> public class SpdyHttpResponseStreamIdHandler extends
<ide> MessageToMessageCodec<Object, HttpMessage> {
<ide> private static final Integer NO_ID = -1;
<del> private final Queue<Integer> ids = new LinkedList<Integer>();
<add> private final Queue<Integer> ids = new ArrayDeque<Integer>();
<ide>
<ide> @Override
<ide> public boolean acceptInboundMessage(Object msg) throws Exception { |
|
Java | agpl-3.0 | 154034b058bdf396353a2f3f1a44df733c2918c5 | 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 | c6affb0e-2e60-11e5-9284-b827eb9e62be | hello.java | c6aa6b6c-2e60-11e5-9284-b827eb9e62be | c6affb0e-2e60-11e5-9284-b827eb9e62be | hello.java | c6affb0e-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>c6aa6b6c-2e60-11e5-9284-b827eb9e62be
<add>c6affb0e-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 173df167b1eca61d2b5266c1d1e4d22012486ff9 | 0 | cherryhill/collectionspace-application | package org.collectionspace.chain.storage;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.collectionspace.chain.controller.ChainServlet;
import org.collectionspace.chain.util.json.JSONUtils;
import org.collectionspace.bconfigutils.bootstrap.BootstrapConfigController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestServiceThroughWebapp {
private String cookie;
private static final Logger log=LoggerFactory.getLogger(TestServiceThroughWebapp.class);
// XXX refactor
private InputStream getResource(String name) {
String path=getClass().getPackage().getName().replaceAll("\\.","/")+"/"+name;
return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
}
// XXX refactor
private String getResourceString(String name) throws IOException {
InputStream in=getResource(name);
return IOUtils.toString(in,"UTF-8");
}
// XXX refactor
private UTF8SafeHttpTester jettyDo(ServletTester tester,String method,String path,String data_str) throws IOException, Exception {
UTF8SafeHttpTester out=new UTF8SafeHttpTester();
out.request(tester,method,path,data_str,cookie);
return out;
}
private void login(ServletTester tester) throws IOException, Exception {
UTF8SafeHttpTester out=jettyDo(tester,"GET","/chain/[email protected]&password=testtest",null);
assertEquals(303,out.getStatus());
cookie=out.getHeader("Set-Cookie");
log.info("Got cookie "+cookie);
}
// XXX refactor into other copy of this method
private ServletTester setupJetty() throws Exception {
BootstrapConfigController config_controller=new BootstrapConfigController(null);
config_controller.addSearchSuffix("test-config-loader2.xml");
config_controller.go();
String base=config_controller.getOption("services-url");
ServletTester tester=new ServletTester();
tester.setContextPath("/chain");
tester.addServlet(ChainServlet.class, "/*");
tester.addServlet("org.mortbay.jetty.servlet.DefaultServlet", "/");
tester.setAttribute("storage","service");
tester.setAttribute("store-url",base+"/cspace-services/");
tester.setAttribute("config-filename","default.xml");
tester.start();
// Login
login(tester);
return tester;
}
private JSONObject getFields(JSONObject in) throws JSONException {
in=in.getJSONObject("fields");
in.remove("csid");
return in;
}
private JSONObject makeRequest(JSONObject fields) throws JSONException {
JSONObject out=new JSONObject();
out.put("fields",fields);
return out;
}
private String makeSimpleRequest(String in) throws JSONException {
return makeRequest(new JSONObject(in)).toString();
}
@Test public void testCollectionObjectBasic() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id=out.getHeader("Location");
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
JSONObject content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject one = new JSONObject(getResourceString("obj3.json"));
log.info(one.toString());
log.info(content.toString());
assertEquals(one.get("titleLanguage"),content.get("titleLanguage"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("obj3.json")),content));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(getResourceString("obj4.json")));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject oneb = new JSONObject(getResourceString("obj4.json"));
assertEquals(oneb.get("titleLanguage"),content.get("titleLanguage"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("obj4.json")),content));
out=jettyDo(jetty,"DELETE","/chain"+id,null);
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(out.getStatus()!=200); // XXX should be 404
}
@Test public void testIntake() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/intake/",makeSimpleRequest(getResourceString("int3.json")));
assertEquals(201,out.getStatus());
String path=out.getHeader("Location");
out=jettyDo(jetty,"GET","/chain"+path,null);
log.info(out.getContent());
JSONObject content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject one = new JSONObject(getResourceString("int3.json"));
assertEquals(one.get("packingNote"),content.get("packingNote"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int3.json")),content));
out=jettyDo(jetty,"PUT","/chain"+path,makeSimpleRequest(getResourceString("int4.json")));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+path,null);
content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject oneb = new JSONObject(getResourceString("int4.json"));
assertEquals(oneb.get("packingNote"),content.get("packingNote"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int4.json")),content));
out=jettyDo(jetty,"DELETE","/chain"+path,null);
out=jettyDo(jetty,"GET","/chain"+path,null);
assertTrue(out.getStatus()!=200); // XXX should be 404
}
@Test public void testAcquisition() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/acquisition/",makeSimpleRequest(getResourceString("create_acquistion.json")));
assertEquals(201,out.getStatus());
String path=out.getHeader("Location");
out=jettyDo(jetty,"GET","/chain"+path,null);
JSONObject content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject one = new JSONObject(getResourceString("create_acquistion.json"));
assertEquals(one.get("acquisitionFundingCurrency"),content.get("acquisitionFundingCurrency"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int5.json")),content));
out=jettyDo(jetty,"PUT","/chain"+path,makeSimpleRequest(getResourceString("update_acquistion.json")));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+path,null);
content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject oneb = new JSONObject(getResourceString("update_acquistion.json"));
assertEquals(oneb.get("acquisitionFundingCurrency"),content.get("acquisitionFundingCurrency"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int6.json")),content));
out=jettyDo(jetty,"DELETE","/chain"+path,null);
out=jettyDo(jetty,"GET","/chain"+path,null);
assertTrue(out.getStatus()!=200); // XXX should be 404
}
@Test public void testIDGenerate() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"GET","/chain/id/intake",null);
JSONObject jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("IN2010."));
//test the accessions generated id
out=jettyDo(jetty,"GET","/chain/id/objects",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("2010.1."));
//test the loans-in generated id
out=jettyDo(jetty,"GET","/chain/id/loanin",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("LI2010."));
//test the loans-out generated id
out=jettyDo(jetty,"GET","/chain/id/loanout",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("LO2010."));
//test the study generated id
out=jettyDo(jetty,"GET","/chain/id/study",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("ST2010."));
//test the evaluation generated id
out=jettyDo(jetty,"GET","/chain/id/evaluation",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("EV2010."));
//test the library generated id
out=jettyDo(jetty,"GET","/chain/id/library",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("LIB2010."));
//test the archives generated id
out=jettyDo(jetty,"GET","/chain/id/archives",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("AR2010."));
}
@Test public void testTermsUsed() throws Exception {
ServletTester jetty=setupJetty();
JSONObject data=new JSONObject("{'fields':{'displayName':'David Bowie'}}");
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/vocabularies/person",data.toString());
assertEquals(201,out.getStatus());
JSONObject jo=new JSONObject(out.getContent());
String p_csid=jo.getString("csid");
out=jettyDo(jetty,"GET","/chain/vocabularies/person/"+p_csid,data.toString());
String p_refid=new JSONObject(out.getContent()).getJSONObject("fields").getString("refid");
data=new JSONObject(getResourceString("int4.json"));
data.remove("valuer");
data.put("valuer",p_refid);
out=jettyDo(jetty,"POST","/chain/intake/",makeSimpleRequest(data.toString()));
assertEquals(201,out.getStatus());
jo=new JSONObject(out.getContent());
//log.info(jo.toString());
JSONArray terms_used=jo.getJSONArray("termsUsed");
assertEquals(1,terms_used.length());
JSONObject term_used=terms_used.getJSONObject(0);
//assertEquals("valuer",term_used.getString("sourceFieldName"));
assertEquals("person",term_used.getString("recordtype"));
assertEquals("David Bowie",term_used.getString("number"));
}
@Test public void testAutoGet() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"GET","/chain/objects/__auto",null);
assertEquals(200,out.getStatus());
// XXX this is correct currently, whilst __auto is stubbed.
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(),new JSONObject(out.getContent())));
}
@Test public void testList() throws Exception {
ServletTester jetty=setupJetty();
// delete all
UTF8SafeHttpTester out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
JSONObject in=new JSONObject(out.getContent());
JSONArray items=in.getJSONArray("items");
for(int i=0;i<items.length();i++) {
JSONObject data=items.getJSONObject(i);
out=jettyDo(jetty,"DELETE","/chain/objects/"+data.getString("csid"),null);
assertEquals(200,out.getStatus());
}
// empty
out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
in=new JSONObject(out.getContent());
items=in.getJSONArray("items");
assertEquals(0,items.length());
// put a couple in
out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id1=out.getHeader("Location");
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id2=out.getHeader("Location");
assertEquals(201,out.getStatus());
// size 2, right ones, put them in the right place
out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
in=new JSONObject(out.getContent());
items=in.getJSONArray("items");
assertEquals(2,items.length());
JSONObject obj1=items.getJSONObject(0);
JSONObject obj2=items.getJSONObject(1);
if(id2.split("/")[2].equals(obj1.getString("csid"))) {
JSONObject t=obj1;
obj1=obj2;
obj2=t;
}
/* clean up */
out=jettyDo(jetty,"DELETE","/chain"+id1,null);
out=jettyDo(jetty,"DELETE","/chain"+id2,null);
// check
assertEquals(id1.split("/")[2],obj1.getString("csid"));
assertEquals(id2.split("/")[2],obj2.getString("csid"));
assertEquals("objects",obj1.getString("recordtype"));
assertEquals("objects",obj2.getString("recordtype"));
assertEquals("title",obj1.getString("summary"));
assertEquals("title",obj2.getString("summary"));
assertEquals("objectNumber",obj1.getString("number"));
assertEquals("objectNumber",obj2.getString("number"));
}
@Test public void testSearch() throws Exception {
ServletTester jetty=setupJetty();
// one aardvark, one non-aardvark
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3-search.json")));
assertEquals(201,out.getStatus());
String id1=out.getHeader("Location");
String good=id1.split("/")[2];
out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id2=out.getHeader("Location");
String bad=id2.split("/")[2];
assertEquals(201,out.getStatus());
// search
out=jettyDo(jetty,"GET","/chain/objects/search?query=aardvark",null);
assertEquals(200,out.getStatus());
//log.info(out.getContent());
// check
JSONArray results=new JSONObject(out.getContent()).getJSONArray("results");
boolean found=false;
for(int i=0;i<results.length();i++) {
String csid=results.getJSONObject(i).getString("csid");
if(good.equals(csid))
found=true;
if(bad.equals(csid))
assertTrue(false);
}
assertTrue(found);
/* clean up */
out=jettyDo(jetty,"DELETE","/chain"+id1,null);
out=jettyDo(jetty,"DELETE","/chain"+id2,null);
}
@Test public void testLogin() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/login","[email protected]&password=testtest");
assertEquals(303,out.getStatus());
assertEquals("/cspace-ui/html/createnew.html",out.getHeader("Location"));
out=jettyDo(jetty,"POST","/chain/[email protected]&password=testtest",null);
assertEquals(303,out.getStatus());
assertFalse(out.getHeader("Location").endsWith("?result=fail"));
out=jettyDo(jetty,"POST","/chain/login?userid=guest&password=toast",null);
assertEquals(303,out.getStatus());
assertTrue(out.getHeader("Location").endsWith("?result=fail"));
out=jettyDo(jetty,"POST","/chain/login?userid=bob&password=bob",null);
assertEquals(303,out.getStatus());
assertTrue(out.getHeader("Location").endsWith("?result=fail"));
}
}
| tomcat-main/src/test/java/org/collectionspace/chain/storage/TestServiceThroughWebapp.java | package org.collectionspace.chain.storage;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.collectionspace.chain.controller.ChainServlet;
import org.collectionspace.chain.util.json.JSONUtils;
import org.collectionspace.bconfigutils.bootstrap.BootstrapConfigController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestServiceThroughWebapp {
private String cookie;
private static final Logger log=LoggerFactory.getLogger(TestServiceThroughWebapp.class);
// XXX refactor
private InputStream getResource(String name) {
String path=getClass().getPackage().getName().replaceAll("\\.","/")+"/"+name;
return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
}
// XXX refactor
private String getResourceString(String name) throws IOException {
InputStream in=getResource(name);
return IOUtils.toString(in,"UTF-8");
}
// XXX refactor
private UTF8SafeHttpTester jettyDo(ServletTester tester,String method,String path,String data_str) throws IOException, Exception {
UTF8SafeHttpTester out=new UTF8SafeHttpTester();
out.request(tester,method,path,data_str,cookie);
return out;
}
private void login(ServletTester tester) throws IOException, Exception {
UTF8SafeHttpTester out=jettyDo(tester,"GET","/chain/[email protected]&password=testtest",null);
assertEquals(303,out.getStatus());
cookie=out.getHeader("Set-Cookie");
log.info("Got cookie "+cookie);
}
// XXX refactor into other copy of this method
private ServletTester setupJetty() throws Exception {
BootstrapConfigController config_controller=new BootstrapConfigController(null);
config_controller.addSearchSuffix("test-config-loader2.xml");
config_controller.go();
String base=config_controller.getOption("services-url");
ServletTester tester=new ServletTester();
tester.setContextPath("/chain");
tester.addServlet(ChainServlet.class, "/*");
tester.addServlet("org.mortbay.jetty.servlet.DefaultServlet", "/");
tester.setAttribute("storage","service");
tester.setAttribute("store-url",base+"/cspace-services/");
tester.setAttribute("config-filename","default.xml");
tester.start();
// Login
login(tester);
return tester;
}
private JSONObject getFields(JSONObject in) throws JSONException {
in=in.getJSONObject("fields");
in.remove("csid");
return in;
}
private JSONObject makeRequest(JSONObject fields) throws JSONException {
JSONObject out=new JSONObject();
out.put("fields",fields);
return out;
}
private String makeSimpleRequest(String in) throws JSONException {
return makeRequest(new JSONObject(in)).toString();
}
@Test public void testCollectionObjectBasic() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id=out.getHeader("Location");
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
JSONObject content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject one = new JSONObject(getResourceString("obj3.json"));
log.info(one.toString());
log.info(content.toString());
assertEquals(one.get("titleLanguage"),content.get("titleLanguage"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("obj3.json")),content));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(getResourceString("obj4.json")));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject oneb = new JSONObject(getResourceString("obj4.json"));
assertEquals(oneb.get("titleLanguage"),content.get("titleLanguage"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("obj4.json")),content));
out=jettyDo(jetty,"DELETE","/chain"+id,null);
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(out.getStatus()!=200); // XXX should be 404
}
@Test public void testIntake() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/intake/",makeSimpleRequest(getResourceString("int3.json")));
assertEquals(201,out.getStatus());
String path=out.getHeader("Location");
out=jettyDo(jetty,"GET","/chain"+path,null);
log.info(out.getContent());
JSONObject content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject one = new JSONObject(getResourceString("int3.json"));
assertEquals(one.get("packingNote"),content.get("packingNote"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int3.json")),content));
out=jettyDo(jetty,"PUT","/chain"+path,makeSimpleRequest(getResourceString("int4.json")));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+path,null);
content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject oneb = new JSONObject(getResourceString("int4.json"));
assertEquals(oneb.get("packingNote"),content.get("packingNote"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int4.json")),content));
out=jettyDo(jetty,"DELETE","/chain"+path,null);
out=jettyDo(jetty,"GET","/chain"+path,null);
assertTrue(out.getStatus()!=200); // XXX should be 404
}
@Test public void testAcquisition() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/acquisition/",makeSimpleRequest(getResourceString("create_acquistion.json")));
assertEquals(201,out.getStatus());
String path=out.getHeader("Location");
out=jettyDo(jetty,"GET","/chain"+path,null);
JSONObject content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject one = new JSONObject(getResourceString("create_acquistion.json"));
assertEquals(one.get("acquisitionFundingCurrency"),content.get("acquisitionFundingCurrency"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int5.json")),content));
out=jettyDo(jetty,"PUT","/chain"+path,makeSimpleRequest(getResourceString("update_acquistion.json")));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+path,null);
content=new JSONObject(out.getContent());
content=getFields(content);
JSONObject oneb = new JSONObject(getResourceString("update_acquistion.json"));
assertEquals(oneb.get("acquisitionFundingCurrency"),content.get("acquisitionFundingCurrency"));
//assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getResourceString("int6.json")),content));
out=jettyDo(jetty,"DELETE","/chain"+path,null);
out=jettyDo(jetty,"GET","/chain"+path,null);
assertTrue(out.getStatus()!=200); // XXX should be 404
}
@Test public void testIDGenerate() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"GET","/chain/id/intake",null);
JSONObject jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("IN2010."));
//test the accessions generated id
out=jettyDo(jetty,"GET","/chain/id/objects",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("2010.1."));
//test the loans-in generated id
out=jettyDo(jetty,"GET","/chain/id/loanin",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("LI2010."));
//test the loans-out generated id
out=jettyDo(jetty,"GET","/chain/id/loanout",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("LO2010."));
//test the study generated id
out=jettyDo(jetty,"GET","/chain/id/study",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("ST2010."));
//test the evaluation generated id
out=jettyDo(jetty,"GET","/chain/id/evaluation",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("EV2010."));
//test the library generated id
out=jettyDo(jetty,"GET","/chain/id/library",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("LIB2010."));
//test the archives generated id
out=jettyDo(jetty,"GET","/chain/id/archives",null);
jo=new JSONObject(out.getContent());
assertTrue(jo.getString("next").startsWith("AR2010."));
}
@Test public void testTermsUsed() throws Exception {
ServletTester jetty=setupJetty();
JSONObject data=new JSONObject("{'fields':{'displayName':'David Bowie'}}");
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/vocabularies/person",data.toString());
assertEquals(201,out.getStatus());
JSONObject jo=new JSONObject(out.getContent());
String p_csid=jo.getString("csid");
out=jettyDo(jetty,"GET","/chain/vocabularies/person/"+p_csid,data.toString());
String p_refid=new JSONObject(out.getContent()).getJSONObject("fields").getString("refid");
data=new JSONObject(getResourceString("int4.json"));
data.remove("valuer");
data.put("valuer",p_refid);
out=jettyDo(jetty,"POST","/chain/intake/",makeSimpleRequest(data.toString()));
assertEquals(201,out.getStatus());
jo=new JSONObject(out.getContent());
//log.info(jo.toString());
JSONArray terms_used=jo.getJSONArray("termsUsed");
assertEquals(1,terms_used.length());
JSONObject term_used=terms_used.getJSONObject(0);
//assertEquals("valuer",term_used.getString("sourceFieldName"));
assertEquals("person",term_used.getString("recordtype"));
assertEquals("David Bowie",term_used.getString("number"));
}
@Test public void testAutoGet() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"GET","/chain/objects/__auto",null);
assertEquals(200,out.getStatus());
// XXX this is correct currently, whilst __auto is stubbed.
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(),new JSONObject(out.getContent())));
}
@Test public void testList() throws Exception {
ServletTester jetty=setupJetty();
// delete all
UTF8SafeHttpTester out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
JSONObject in=new JSONObject(out.getContent());
JSONArray items=in.getJSONArray("items");
for(int i=0;i<items.length();i++) {
JSONObject data=items.getJSONObject(i);
out=jettyDo(jetty,"DELETE","/chain/objects/"+data.getString("csid"),null);
assertEquals(200,out.getStatus());
}
// empty
out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
in=new JSONObject(out.getContent());
items=in.getJSONArray("items");
assertEquals(0,items.length());
// put a couple in
out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id1=out.getHeader("Location");
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id2=out.getHeader("Location");
assertEquals(201,out.getStatus());
// size 2, right ones, put them in the right place
out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
in=new JSONObject(out.getContent());
items=in.getJSONArray("items");
assertEquals(2,items.length());
JSONObject obj1=items.getJSONObject(0);
JSONObject obj2=items.getJSONObject(1);
if(id2.split("/")[2].equals(obj1.getString("csid"))) {
JSONObject t=obj1;
obj1=obj2;
obj2=t;
}
/* clean up */
out=jettyDo(jetty,"DELETE","/chain"+id1,null);
out=jettyDo(jetty,"DELETE","/chain"+id2,null);
// check
assertEquals(id1.split("/")[2],obj1.getString("csid"));
assertEquals(id2.split("/")[2],obj2.getString("csid"));
assertEquals("objects",obj1.getString("recordtype"));
assertEquals("objects",obj2.getString("recordtype"));
assertEquals("title",obj1.getString("summary"));
assertEquals("title",obj2.getString("summary"));
assertEquals("objectNumber",obj1.getString("number"));
assertEquals("objectNumber",obj2.getString("number"));
}
@Test public void testSearch() throws Exception {
ServletTester jetty=setupJetty();
// one aardvark, one non-aardvark
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3-search.json")));
assertEquals(201,out.getStatus());
String id1=out.getHeader("Location");
String good=id1.split("/")[2];
out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(getResourceString("obj3.json")));
String id2=out.getHeader("Location");
String bad=id2.split("/")[2];
assertEquals(201,out.getStatus());
// search
out=jettyDo(jetty,"GET","/chain/objects/search?query=aardvark",null);
assertEquals(200,out.getStatus());
//log.info(out.getContent());
// check
JSONArray results=new JSONObject(out.getContent()).getJSONArray("results");
boolean found=false;
for(int i=0;i<results.length();i++) {
String csid=results.getJSONObject(i).getString("csid");
if(good.equals(csid))
found=true;
if(bad.equals(csid))
assertTrue(false);
}
assertTrue(found);
/* clean up */
out=jettyDo(jetty,"DELETE","/chain"+id1,null);
out=jettyDo(jetty,"DELETE","/chain"+id2,null);
}
@Test public void testLogin() throws Exception {
ServletTester jetty=setupJetty();
UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/login","[email protected]&password=testtest");
assertEquals(303,out.getStatus());
assertEquals("/cspace-ui/html/createnew.html",out.getHeader("Location"));
out=jettyDo(jetty,"GET","/chain/[email protected]&password=testtest",null);
assertEquals(303,out.getStatus());
assertFalse(out.getHeader("Location").endsWith("?result=fail"));
out=jettyDo(jetty,"GET","/chain/login?userid=guest&password=toast",null);
assertEquals(303,out.getStatus());
assertTrue(out.getHeader("Location").endsWith("?result=fail"));
out=jettyDo(jetty,"GET","/chain/login?userid=bob&password=bob",null);
assertEquals(303,out.getStatus());
assertTrue(out.getHeader("Location").endsWith("?result=fail"));
}
}
| nojira - improve test for login
| tomcat-main/src/test/java/org/collectionspace/chain/storage/TestServiceThroughWebapp.java | nojira - improve test for login | <ide><path>omcat-main/src/test/java/org/collectionspace/chain/storage/TestServiceThroughWebapp.java
<ide> UTF8SafeHttpTester out=jettyDo(jetty,"POST","/chain/login","[email protected]&password=testtest");
<ide> assertEquals(303,out.getStatus());
<ide> assertEquals("/cspace-ui/html/createnew.html",out.getHeader("Location"));
<del> out=jettyDo(jetty,"GET","/chain/[email protected]&password=testtest",null);
<add> out=jettyDo(jetty,"POST","/chain/[email protected]&password=testtest",null);
<ide> assertEquals(303,out.getStatus());
<ide> assertFalse(out.getHeader("Location").endsWith("?result=fail"));
<del> out=jettyDo(jetty,"GET","/chain/login?userid=guest&password=toast",null);
<add> out=jettyDo(jetty,"POST","/chain/login?userid=guest&password=toast",null);
<ide> assertEquals(303,out.getStatus());
<ide> assertTrue(out.getHeader("Location").endsWith("?result=fail"));
<del> out=jettyDo(jetty,"GET","/chain/login?userid=bob&password=bob",null);
<add> out=jettyDo(jetty,"POST","/chain/login?userid=bob&password=bob",null);
<ide> assertEquals(303,out.getStatus());
<ide> assertTrue(out.getHeader("Location").endsWith("?result=fail"));
<ide> |
|
Java | apache-2.0 | f0683ed0032ef0dc250d708614cccd4d6fa696ab | 0 | gkatsikas/onos,gkatsikas/onos,gkatsikas/onos,gkatsikas/onos,gkatsikas/onos,opennetworkinglab/onos,opennetworkinglab/onos,opennetworkinglab/onos,opennetworkinglab/onos,opennetworkinglab/onos,opennetworkinglab/onos,gkatsikas/onos | /*
* Copyright 2019-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.k8snetworking.impl;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServicePort;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IPv4;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.TpPort;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cfg.ConfigProperty;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.k8snetworking.api.K8sFlowRuleService;
import org.onosproject.k8snetworking.api.K8sNetworkService;
import org.onosproject.k8snetworking.api.K8sServiceEvent;
import org.onosproject.k8snetworking.api.K8sServiceListener;
import org.onosproject.k8snetworking.api.K8sServiceService;
import org.onosproject.k8snode.api.K8sNode;
import org.onosproject.k8snode.api.K8sNodeEvent;
import org.onosproject.k8snode.api.K8sNodeListener;
import org.onosproject.k8snode.api.K8sNodeService;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.DriverService;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.instructions.ExtensionTreatment;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import static java.lang.Thread.sleep;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.k8snetworking.api.Constants.B_CLASS;
import static org.onosproject.k8snetworking.api.Constants.DST;
import static org.onosproject.k8snetworking.api.Constants.EXT_ENTRY_TABLE;
import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
import static org.onosproject.k8snetworking.api.Constants.NODE_IP_PREFIX;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_CIDR_RULE;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_INTER_ROUTING_RULE;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_NODE_PORT_RULE;
import static org.onosproject.k8snetworking.api.Constants.ROUTING_TABLE;
import static org.onosproject.k8snetworking.api.Constants.SRC;
import static org.onosproject.k8snetworking.api.Constants.TUN_ENTRY_TABLE;
import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.getBclassIpPrefixFromCidr;
import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.getPropertyValue;
import static org.onosproject.k8snetworking.util.RulePopulatorUtil.buildLoadExtension;
import static org.onosproject.k8snode.api.K8sApiConfig.Mode.PASSTHROUGH;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provides service port exposure using node port.
*/
@Component(immediate = true)
public class K8sNodePortHandler {
private final Logger log = getLogger(getClass());
private static final String NODE_PORT_TYPE = "NodePort";
private static final String LOAD_BALANCER_TYPE = "LoadBalancer";
private static final String TCP = "TCP";
private static final String UDP = "UDP";
private static final int HOST_CIDR = 32;
private static final String SERVICE_CIDR = "serviceCidr";
private static final String B_CLASS_SUFFIX = "0.0/16";
private static final long SLEEP_MS = 3000;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ComponentConfigService configService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected DeviceService deviceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected DriverService driverService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected LeadershipService leadershipService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected MastershipService mastershipService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sNodeService k8sNodeService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sNetworkService k8sNetworkService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sServiceService k8sServiceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sFlowRuleService k8sFlowRuleService;
private final InternalK8sServiceListener k8sServiceListener =
new InternalK8sServiceListener();
private final InternalK8sNodeListener k8sNodeListener =
new InternalK8sNodeListener();
private final ExecutorService eventExecutor = newSingleThreadExecutor(
groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
private ApplicationId appId;
private NodeId localNodeId;
@Activate
protected void activate() {
appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
localNodeId = clusterService.getLocalNode().id();
leadershipService.runForLeadership(appId.name());
k8sNodeService.addListener(k8sNodeListener);
k8sServiceService.addListener(k8sServiceListener);
log.info("Started");
}
@Deactivate
protected void deactivate() {
k8sNodeService.removeListener(k8sNodeListener);
k8sServiceService.removeListener(k8sServiceListener);
leadershipService.withdraw(appId.name());
eventExecutor.shutdown();
log.info("Stopped");
}
private void processNodePortEvent(K8sNode k8sNode, Service service, boolean install) {
String clusterIp = service.getSpec().getClusterIP();
for (ServicePort servicePort : service.getSpec().getPorts()) {
setNodeToServiceRules(k8sNode, clusterIp, servicePort, install);
setServiceToNodeRules(k8sNode, clusterIp, servicePort, install);
}
}
private void setIntgToExtRules(K8sNode k8sNode, String serviceCidr,
boolean install) {
// for local traffic, we add default flow rules for steering traffic from
// integration bridge to external bridge through patch port
// for remote traffic, we add default flow rules for steering traffic from
// integration bridge to tun bridge through patch port
k8sNodeService.completeNodes().forEach(n -> {
String podCidr = k8sNetworkService.network(n.hostname()).cidr();
String fullCidr = NODE_IP_PREFIX + "." +
podCidr.split("\\.")[2] + "." + B_CLASS_SUFFIX;
TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchIPSrc(IpPrefix.valueOf(serviceCidr))
.matchIPDst(IpPrefix.valueOf(fullCidr));
PortNumber output;
if (n.hostname().equals(k8sNode.hostname())) {
output = k8sNode.intgToExtPatchPortNum();
} else {
output = k8sNode.intgToTunPortNum();
}
TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
.setOutput(output);
k8sFlowRuleService.setRule(
appId,
k8sNode.intgBridge(),
sBuilder.build(),
tBuilder.build(),
PRIORITY_CIDR_RULE,
ROUTING_TABLE,
install);
});
}
private void setTunToIntgRules(K8sNode k8sNode, boolean install) {
String podCidr = k8sNetworkService.network(k8sNode.hostname()).cidr();
String fullCidr = NODE_IP_PREFIX + "." +
podCidr.split("\\.")[2] + "." + B_CLASS_SUFFIX;
TrafficSelector selector = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchIPDst(IpPrefix.valueOf(fullCidr))
.build();
TrafficTreatment treatment = DefaultTrafficTreatment.builder()
.setOutput(k8sNode.tunToIntgPortNum())
.build();
k8sFlowRuleService.setRule(
appId,
k8sNode.tunBridge(),
selector,
treatment,
PRIORITY_INTER_ROUTING_RULE,
TUN_ENTRY_TABLE,
install);
}
private void setNodeToServiceRules(K8sNode k8sNode,
String clusterIp,
ServicePort servicePort,
boolean install) {
String protocol = servicePort.getProtocol();
int nodePort = servicePort.getNodePort();
int svcPort = servicePort.getPort();
DeviceId deviceId = k8sNode.extBridge();
TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchIPDst(IpPrefix.valueOf(k8sNode.nodeIp(), HOST_CIDR));
TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
.setIpDst(IpAddress.valueOf(clusterIp));
if (TCP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP)
.matchTcpDst(TpPort.tpPort(nodePort));
tBuilder.setTcpDst(TpPort.tpPort(svcPort));
} else if (UDP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP)
.matchUdpDst(TpPort.tpPort(nodePort));
tBuilder.setUdpDst(TpPort.tpPort(svcPort));
}
String podCidr = k8sNetworkService.network(k8sNode.hostname()).cidr();
String prefix = NODE_IP_PREFIX + "." + podCidr.split("\\.")[2];
ExtensionTreatment loadTreatment = buildLoadExtension(
deviceService.getDevice(deviceId), B_CLASS, SRC, prefix);
tBuilder.extension(loadTreatment, deviceId)
.setOutput(k8sNode.extToIntgPatchPortNum());
k8sFlowRuleService.setRule(
appId,
k8sNode.extBridge(),
sBuilder.build(),
tBuilder.build(),
PRIORITY_NODE_PORT_RULE,
EXT_ENTRY_TABLE,
install);
}
private void setServiceToNodeRules(K8sNode k8sNode,
String clusterIp,
ServicePort servicePort,
boolean install) {
String protocol = servicePort.getProtocol();
int nodePort = servicePort.getNodePort();
int svcPort = servicePort.getPort();
DeviceId deviceId = k8sNode.extBridge();
String nodeIp = k8sNode.nodeIp().toString();
String nodeIpPrefix = getBclassIpPrefixFromCidr(nodeIp);
if (nodeIpPrefix == null) {
return;
}
TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchInPort(k8sNode.extToIntgPatchPortNum())
.matchIPSrc(IpPrefix.valueOf(IpAddress.valueOf(clusterIp), HOST_CIDR));
TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
.setIpSrc(k8sNode.nodeIp())
.setEthSrc(k8sNode.nodeMac());
if (TCP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP)
.matchTcpSrc(TpPort.tpPort(svcPort));
tBuilder.setTcpSrc(TpPort.tpPort(nodePort));
} else if (UDP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP)
.matchUdpSrc(TpPort.tpPort(svcPort));
tBuilder.setUdpSrc(TpPort.tpPort(nodePort));
}
ExtensionTreatment loadTreatment = buildLoadExtension(
deviceService.getDevice(deviceId), B_CLASS, DST, nodeIpPrefix);
tBuilder.extension(loadTreatment, deviceId);
// in passthrough mode, we steer the traffic to the openstack intg bridge
// in normal mode, we steer the traffic to the local port
if (k8sNode.mode() == PASSTHROUGH) {
PortNumber output = k8sNode.portNumByName(k8sNode.extBridge(),
k8sNode.k8sExtToOsPatchPortName());
if (output == null) {
log.warn("Kubernetes external to OpenStack patch port is null");
return;
}
tBuilder.setOutput(output);
} else {
tBuilder.setOutput(PortNumber.LOCAL);
}
k8sFlowRuleService.setRule(
appId,
deviceId,
sBuilder.build(),
tBuilder.build(),
PRIORITY_NODE_PORT_RULE,
EXT_ENTRY_TABLE,
install);
}
private String getServiceCidr() {
Set<ConfigProperty> properties =
configService.getProperties(K8sServiceHandler.class.getName());
return getPropertyValue(properties, SERVICE_CIDR);
}
private class InternalK8sServiceListener implements K8sServiceListener {
private boolean isRelevantHelper() {
return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
}
@Override
public void event(K8sServiceEvent event) {
switch (event.type()) {
case K8S_SERVICE_CREATED:
case K8S_SERVICE_UPDATED:
eventExecutor.execute(() -> processServiceCreation(event.subject()));
break;
default:
break;
}
}
private void processServiceCreation(Service service) {
if (!isRelevantHelper()) {
return;
}
if (NODE_PORT_TYPE.equals(service.getSpec().getType()) ||
LOAD_BALANCER_TYPE.equals(service.getSpec().getType())) {
k8sNodeService.completeNodes().forEach(n -> {
// we need to wait, until we resolve the valid MAC address of the node
while (k8sNodeService.node(n.hostname()).nodeMac() == null) {
log.warn("Node {} MAC address is not resolved, " +
"wait until resolving it", n.hostname());
try {
sleep(SLEEP_MS);
} catch (InterruptedException e) {
log.error("Exception caused by", e);
}
}
K8sNode updatedNode = k8sNodeService.node(n.hostname());
processNodePortEvent(updatedNode, service, true);
});
}
}
}
private class InternalK8sNodeListener implements K8sNodeListener {
private boolean isRelevantHelper() {
return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
}
@Override
public void event(K8sNodeEvent event) {
switch (event.type()) {
case K8S_NODE_COMPLETE:
eventExecutor.execute(() -> processNodeCompletion(event.subject()));
break;
case K8S_NODE_INCOMPLETE:
default:
break;
}
}
private void processNodeCompletion(K8sNode k8sNode) {
if (!isRelevantHelper()) {
return;
}
// we need to wait, until we resolve the valid MAC address of the node
while (k8sNodeService.node(k8sNode.hostname()).nodeMac() == null) {
log.warn("Node {} MAC address is not resolved, " +
"wait until resolving it", k8sNode.hostname());
try {
sleep(SLEEP_MS);
} catch (InterruptedException e) {
log.error("Exception caused by", e);
}
}
K8sNode updatedNode = k8sNodeService.node(k8sNode.hostname());
k8sServiceService.services().stream()
.filter(s -> NODE_PORT_TYPE.equals(s.getSpec().getType()) ||
LOAD_BALANCER_TYPE.equals(s.getSpec().getType()))
.forEach(s -> processNodePortEvent(updatedNode, s, true));
setIntgToExtRules(updatedNode, getServiceCidr(), true);
setTunToIntgRules(updatedNode, true);
}
}
}
| apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNodePortHandler.java | /*
* Copyright 2019-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.k8snetworking.impl;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServicePort;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IPv4;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.TpPort;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cfg.ConfigProperty;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.k8snetworking.api.K8sFlowRuleService;
import org.onosproject.k8snetworking.api.K8sNetworkService;
import org.onosproject.k8snetworking.api.K8sServiceEvent;
import org.onosproject.k8snetworking.api.K8sServiceListener;
import org.onosproject.k8snetworking.api.K8sServiceService;
import org.onosproject.k8snode.api.K8sNode;
import org.onosproject.k8snode.api.K8sNodeEvent;
import org.onosproject.k8snode.api.K8sNodeListener;
import org.onosproject.k8snode.api.K8sNodeService;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.DriverService;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.instructions.ExtensionTreatment;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.k8snetworking.api.Constants.B_CLASS;
import static org.onosproject.k8snetworking.api.Constants.DST;
import static org.onosproject.k8snetworking.api.Constants.EXT_ENTRY_TABLE;
import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
import static org.onosproject.k8snetworking.api.Constants.NODE_IP_PREFIX;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_CIDR_RULE;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_INTER_ROUTING_RULE;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_NODE_PORT_RULE;
import static org.onosproject.k8snetworking.api.Constants.ROUTING_TABLE;
import static org.onosproject.k8snetworking.api.Constants.SRC;
import static org.onosproject.k8snetworking.api.Constants.TUN_ENTRY_TABLE;
import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.getBclassIpPrefixFromCidr;
import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.getPropertyValue;
import static org.onosproject.k8snetworking.util.RulePopulatorUtil.buildLoadExtension;
import static org.onosproject.k8snode.api.K8sApiConfig.Mode.PASSTHROUGH;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provides service port exposure using node port.
*/
@Component(immediate = true)
public class K8sNodePortHandler {
private final Logger log = getLogger(getClass());
private static final String NODE_PORT_TYPE = "NodePort";
private static final String TCP = "TCP";
private static final String UDP = "UDP";
private static final int HOST_CIDR = 32;
private static final String SERVICE_CIDR = "serviceCidr";
private static final String B_CLASS_SUFFIX = "0.0/16";
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ComponentConfigService configService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected DeviceService deviceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected DriverService driverService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected LeadershipService leadershipService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected MastershipService mastershipService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sNodeService k8sNodeService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sNetworkService k8sNetworkService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sServiceService k8sServiceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected K8sFlowRuleService k8sFlowRuleService;
private final InternalK8sServiceListener k8sServiceListener =
new InternalK8sServiceListener();
private final InternalK8sNodeListener k8sNodeListener =
new InternalK8sNodeListener();
private final ExecutorService eventExecutor = newSingleThreadExecutor(
groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
private ApplicationId appId;
private NodeId localNodeId;
@Activate
protected void activate() {
appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
localNodeId = clusterService.getLocalNode().id();
leadershipService.runForLeadership(appId.name());
k8sNodeService.addListener(k8sNodeListener);
k8sServiceService.addListener(k8sServiceListener);
log.info("Started");
}
@Deactivate
protected void deactivate() {
k8sNodeService.removeListener(k8sNodeListener);
k8sServiceService.removeListener(k8sServiceListener);
leadershipService.withdraw(appId.name());
eventExecutor.shutdown();
log.info("Stopped");
}
private void processNodePortEvent(K8sNode k8sNode, Service service, boolean install) {
String clusterIp = service.getSpec().getClusterIP();
for (ServicePort servicePort : service.getSpec().getPorts()) {
setNodeToServiceRules(k8sNode, clusterIp, servicePort, install);
setServiceToNodeRules(k8sNode, clusterIp, servicePort, install);
}
}
private void setIntgToExtRules(K8sNode k8sNode, String serviceCidr,
boolean install) {
// for local traffic, we add default flow rules for steering traffic from
// integration bridge to external bridge through patch port
// for remote traffic, we add default flow rules for steering traffic from
// integration bridge to tun bridge through patch port
k8sNodeService.completeNodes().forEach(n -> {
String podCidr = k8sNetworkService.network(n.hostname()).cidr();
String fullCidr = NODE_IP_PREFIX + "." +
podCidr.split("\\.")[2] + "." + B_CLASS_SUFFIX;
TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchIPSrc(IpPrefix.valueOf(serviceCidr))
.matchIPDst(IpPrefix.valueOf(fullCidr));
PortNumber output;
if (n.hostname().equals(k8sNode.hostname())) {
output = k8sNode.intgToExtPatchPortNum();
} else {
output = k8sNode.intgToTunPortNum();
}
TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
.setOutput(output);
k8sFlowRuleService.setRule(
appId,
k8sNode.intgBridge(),
sBuilder.build(),
tBuilder.build(),
PRIORITY_CIDR_RULE,
ROUTING_TABLE,
install);
});
}
private void setTunToIntgRules(K8sNode k8sNode, boolean install) {
String podCidr = k8sNetworkService.network(k8sNode.hostname()).cidr();
String fullCidr = NODE_IP_PREFIX + "." +
podCidr.split("\\.")[2] + "." + B_CLASS_SUFFIX;
TrafficSelector selector = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchIPDst(IpPrefix.valueOf(fullCidr))
.build();
TrafficTreatment treatment = DefaultTrafficTreatment.builder()
.setOutput(k8sNode.tunToIntgPortNum())
.build();
k8sFlowRuleService.setRule(
appId,
k8sNode.tunBridge(),
selector,
treatment,
PRIORITY_INTER_ROUTING_RULE,
TUN_ENTRY_TABLE,
install);
}
private void setNodeToServiceRules(K8sNode k8sNode,
String clusterIp,
ServicePort servicePort,
boolean install) {
String protocol = servicePort.getProtocol();
int nodePort = servicePort.getNodePort();
int svcPort = servicePort.getPort();
DeviceId deviceId = k8sNode.extBridge();
TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchIPDst(IpPrefix.valueOf(k8sNode.nodeIp(), HOST_CIDR));
TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
.setIpDst(IpAddress.valueOf(clusterIp));
if (TCP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP)
.matchTcpDst(TpPort.tpPort(nodePort));
tBuilder.setTcpDst(TpPort.tpPort(svcPort));
} else if (UDP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP)
.matchUdpDst(TpPort.tpPort(nodePort));
tBuilder.setUdpDst(TpPort.tpPort(svcPort));
}
String podCidr = k8sNetworkService.network(k8sNode.hostname()).cidr();
String prefix = NODE_IP_PREFIX + "." + podCidr.split("\\.")[2];
ExtensionTreatment loadTreatment = buildLoadExtension(
deviceService.getDevice(deviceId), B_CLASS, SRC, prefix);
tBuilder.extension(loadTreatment, deviceId)
.setOutput(k8sNode.extToIntgPatchPortNum());
k8sFlowRuleService.setRule(
appId,
k8sNode.extBridge(),
sBuilder.build(),
tBuilder.build(),
PRIORITY_NODE_PORT_RULE,
EXT_ENTRY_TABLE,
install);
}
private void setServiceToNodeRules(K8sNode k8sNode,
String clusterIp,
ServicePort servicePort,
boolean install) {
String protocol = servicePort.getProtocol();
int nodePort = servicePort.getNodePort();
int svcPort = servicePort.getPort();
DeviceId deviceId = k8sNode.extBridge();
String nodeIp = k8sNode.nodeIp().toString();
String nodeIpPrefix = getBclassIpPrefixFromCidr(nodeIp);
if (nodeIpPrefix == null) {
return;
}
TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
.matchEthType(Ethernet.TYPE_IPV4)
.matchInPort(k8sNode.extToIntgPatchPortNum())
.matchIPSrc(IpPrefix.valueOf(IpAddress.valueOf(clusterIp), HOST_CIDR));
TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
.setIpSrc(k8sNode.nodeIp())
.setEthSrc(k8sNode.nodeMac());
if (TCP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_TCP)
.matchTcpSrc(TpPort.tpPort(svcPort));
tBuilder.setTcpSrc(TpPort.tpPort(nodePort));
} else if (UDP.equals(protocol)) {
sBuilder.matchIPProtocol(IPv4.PROTOCOL_UDP)
.matchUdpSrc(TpPort.tpPort(svcPort));
tBuilder.setUdpSrc(TpPort.tpPort(nodePort));
}
ExtensionTreatment loadTreatment = buildLoadExtension(
deviceService.getDevice(deviceId), B_CLASS, DST, nodeIpPrefix);
tBuilder.extension(loadTreatment, deviceId);
// in passthrough mode, we steer the traffic to the openstack intg bridge
// in normal mode, we steer the traffic to the local port
if (k8sNode.mode() == PASSTHROUGH) {
PortNumber output = k8sNode.portNumByName(k8sNode.extBridge(),
k8sNode.k8sExtToOsPatchPortName());
if (output == null) {
log.warn("Kubernetes external to OpenStack patch port is null");
return;
}
tBuilder.setOutput(output);
} else {
tBuilder.setOutput(PortNumber.LOCAL);
}
k8sFlowRuleService.setRule(
appId,
deviceId,
sBuilder.build(),
tBuilder.build(),
PRIORITY_NODE_PORT_RULE,
EXT_ENTRY_TABLE,
install);
}
private String getServiceCidr() {
Set<ConfigProperty> properties =
configService.getProperties(K8sServiceHandler.class.getName());
return getPropertyValue(properties, SERVICE_CIDR);
}
private class InternalK8sServiceListener implements K8sServiceListener {
private boolean isRelevantHelper() {
return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
}
@Override
public void event(K8sServiceEvent event) {
switch (event.type()) {
case K8S_SERVICE_CREATED:
case K8S_SERVICE_UPDATED:
eventExecutor.execute(() -> processServiceCreation(event.subject()));
break;
default:
break;
}
}
private void processServiceCreation(Service service) {
if (!isRelevantHelper()) {
return;
}
if (NODE_PORT_TYPE.equals(service.getSpec().getType())) {
k8sNodeService.completeNodes().forEach(n ->
processNodePortEvent(n, service, true)
);
}
}
}
private class InternalK8sNodeListener implements K8sNodeListener {
private boolean isRelevantHelper() {
return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
}
@Override
public void event(K8sNodeEvent event) {
switch (event.type()) {
case K8S_NODE_COMPLETE:
eventExecutor.execute(() -> processNodeCompletion(event.subject()));
break;
case K8S_NODE_INCOMPLETE:
default:
break;
}
}
private void processNodeCompletion(K8sNode k8sNode) {
if (!isRelevantHelper()) {
return;
}
k8sServiceService.services().stream()
.filter(s -> NODE_PORT_TYPE.equals(s.getSpec().getType()))
.forEach(s -> processNodePortEvent(k8sNode, s, true));
setIntgToExtRules(k8sNode, getServiceCidr(), true);
setTunToIntgRules(k8sNode, true);
}
}
}
| Support Kubernetes LoadBalancer service type
Change-Id: Ife5a75a68a5b83dbf51787e686412b9318c27aa0
(cherry picked from commit 897d92d094473847a1a843b72a2b9946ad902a6e)
| apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNodePortHandler.java | Support Kubernetes LoadBalancer service type | <ide><path>pps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sNodePortHandler.java
<ide> import java.util.Set;
<ide> import java.util.concurrent.ExecutorService;
<ide>
<add>import static java.lang.Thread.sleep;
<ide> import static java.util.concurrent.Executors.newSingleThreadExecutor;
<ide> import static org.onlab.util.Tools.groupedThreads;
<ide> import static org.onosproject.k8snetworking.api.Constants.B_CLASS;
<ide> private final Logger log = getLogger(getClass());
<ide>
<ide> private static final String NODE_PORT_TYPE = "NodePort";
<add> private static final String LOAD_BALANCER_TYPE = "LoadBalancer";
<ide> private static final String TCP = "TCP";
<ide> private static final String UDP = "UDP";
<ide> private static final int HOST_CIDR = 32;
<ide> private static final String SERVICE_CIDR = "serviceCidr";
<ide> private static final String B_CLASS_SUFFIX = "0.0/16";
<add>
<add> private static final long SLEEP_MS = 3000;
<ide>
<ide> @Reference(cardinality = ReferenceCardinality.MANDATORY)
<ide> protected CoreService coreService;
<ide> return;
<ide> }
<ide>
<del> if (NODE_PORT_TYPE.equals(service.getSpec().getType())) {
<del> k8sNodeService.completeNodes().forEach(n ->
<del> processNodePortEvent(n, service, true)
<del> );
<add> if (NODE_PORT_TYPE.equals(service.getSpec().getType()) ||
<add> LOAD_BALANCER_TYPE.equals(service.getSpec().getType())) {
<add> k8sNodeService.completeNodes().forEach(n -> {
<add> // we need to wait, until we resolve the valid MAC address of the node
<add> while (k8sNodeService.node(n.hostname()).nodeMac() == null) {
<add> log.warn("Node {} MAC address is not resolved, " +
<add> "wait until resolving it", n.hostname());
<add> try {
<add> sleep(SLEEP_MS);
<add> } catch (InterruptedException e) {
<add> log.error("Exception caused by", e);
<add> }
<add> }
<add> K8sNode updatedNode = k8sNodeService.node(n.hostname());
<add> processNodePortEvent(updatedNode, service, true);
<add> });
<ide> }
<ide> }
<ide> }
<ide> return;
<ide> }
<ide>
<add> // we need to wait, until we resolve the valid MAC address of the node
<add> while (k8sNodeService.node(k8sNode.hostname()).nodeMac() == null) {
<add> log.warn("Node {} MAC address is not resolved, " +
<add> "wait until resolving it", k8sNode.hostname());
<add> try {
<add> sleep(SLEEP_MS);
<add> } catch (InterruptedException e) {
<add> log.error("Exception caused by", e);
<add> }
<add> }
<add>
<add> K8sNode updatedNode = k8sNodeService.node(k8sNode.hostname());
<add>
<ide> k8sServiceService.services().stream()
<del> .filter(s -> NODE_PORT_TYPE.equals(s.getSpec().getType()))
<del> .forEach(s -> processNodePortEvent(k8sNode, s, true));
<del>
<del> setIntgToExtRules(k8sNode, getServiceCidr(), true);
<del> setTunToIntgRules(k8sNode, true);
<add> .filter(s -> NODE_PORT_TYPE.equals(s.getSpec().getType()) ||
<add> LOAD_BALANCER_TYPE.equals(s.getSpec().getType()))
<add> .forEach(s -> processNodePortEvent(updatedNode, s, true));
<add>
<add> setIntgToExtRules(updatedNode, getServiceCidr(), true);
<add> setTunToIntgRules(updatedNode, true);
<ide> }
<ide> }
<ide> } |
|
JavaScript | agpl-3.0 | 1d40145d525a1cc23dff419d0afdf96b21ba19ff | 0 | fyruna/WoWAnalyzer,fyruna/WoWAnalyzer,Juko8/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,yajinni/WoWAnalyzer,FaideWW/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,ronaldpereira/WoWAnalyzer,FaideWW/WoWAnalyzer,ronaldpereira/WoWAnalyzer,Juko8/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,yajinni/WoWAnalyzer,anom0ly/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,ronaldpereira/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer,sMteX/WoWAnalyzer,FaideWW/WoWAnalyzer,fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import { calculateSecondaryStatDefault} from 'common/stats';
import { formatPercentage, formatNumber } from 'common/format';
import Analyzer from 'Parser/Core/Analyzer';
/**
* Construct Overcharger -
* Equip: Your attacks have a chance to increase your Haste by 21 for 10 sec, stacking up to 8 times.
*/
class ConstructOvercharger extends Analyzer{
statBuff = 0;
constructor(...args){
super(...args);
this.active = this.selectedCombatant.hasTrinket(ITEMS.CONSTRUCT_OVERCHARGER.id);
if(this.active){
this.statBuff = calculateSecondaryStatDefault(355, 33, this.selectedCombatant.getItem(ITEMS.CONSTRUCT_OVERCHARGER.id).itemLevel);
}
}
averageStatGain(){
const averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.TITANIC_OVERCHARGE.id) / this.owner.fightDuration;
return averageStacks * this.statBuff;
}
totalBuffUptime(){
return this.selectedCombatant.getBuffUptime(SPELLS.TITANIC_OVERCHARGE.id)/this.owner.fightDuration;
}
buffTriggerCount(){
return this.selectedCombatant.getBuffTriggerCount(SPELLS.TITANIC_OVERCHARGE.id);
}
item(){
return {
item: ITEMS.CONSTRUCT_OVERCHARGER,
result: (
<dfn data-tip={`Procced ${this.buffTriggerCount()} times.`}>
{formatPercentage(this.totalBuffUptime())}% uptime.<br />
{formatNumber(this.averageStatGain())} average Haste.
</dfn>
),
};
}
}
export default ConstructOvercharger;
| src/Parser/Core/Modules/Items/BFA/Raids/Uldir/ConstructOvercharger.js | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import { calculateSecondaryStatDefault} from 'common/stats';
import { formatPercentage, formatNumber } from 'common/format';
import Analyzer from 'Parser/Core/Analyzer';
/**
* Construct Overcharger -
* Equipe: Your attacks have a chance to increase your Haste by 6 for 10 sec, stacking up to 8 times.
*/
class ConstructOvercharger extends Analyzer{
statBuff = 0;
constructor(...args){
super(...args);
this.active = this.selectedCombatant.hasTrinket(ITEMS.CONSTRUCT_OVERCHARGER.id);
if(this.active){
this.statBuff = calculateSecondaryStatDefault(355, 33, this.selectedCombatant.getItem(ITEMS.CONSTRUCT_OVERCHARGER.id).itemLevel);
}
}
averageStatGain(){
const averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.TITANIC_OVERCHARGE.id) / this.owner.fightDuration;
return averageStacks * this.statBuff;
}
totalBuffUptime(){
return this.selectedCombatant.getBuffUptime(SPELLS.TITANIC_OVERCHARGE.id)/this.owner.fightDuration;
}
buffTriggerCount(){
return this.selectedCombatant.getBuffTriggerCount(SPELLS.TITANIC_OVERCHARGE.id);
}
item(){
return {
item: ITEMS.CONSTRUCT_OVERCHARGER,
result: (
<dfn data-tip={`Procced ${this.buffTriggerCount()} times.`}>
{formatPercentage(this.totalBuffUptime())}% uptime.<br />
{formatNumber(this.averageStatGain())} average Haste.
</dfn>
),
};
}
}
export default ConstructOvercharger;
| Fix comment typos.
| src/Parser/Core/Modules/Items/BFA/Raids/Uldir/ConstructOvercharger.js | Fix comment typos. | <ide><path>rc/Parser/Core/Modules/Items/BFA/Raids/Uldir/ConstructOvercharger.js
<ide>
<ide> /**
<ide> * Construct Overcharger -
<del> * Equipe: Your attacks have a chance to increase your Haste by 6 for 10 sec, stacking up to 8 times.
<add> * Equip: Your attacks have a chance to increase your Haste by 21 for 10 sec, stacking up to 8 times.
<ide> */
<ide>
<ide> class ConstructOvercharger extends Analyzer{ |
|
Java | mit | error: pathspec 'java/Point.java' did not match any file(s) known to git
| cb6124b60c37d680864dc6b817809beb1b0e6c01 | 1 | consttgit/crosssection,consttgit/crosssection | public class Point {
public double x;
public double y;
private static int num = 0;
public Point(double x, double y) {
this.x = x;
this.y = y;
++num;
}
public Point() {
this(0.0, 0.0);
}
public double distance(Point other) {
return Math.sqrt(
Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2)
);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof Point)) return false;
Point point = (Point)obj;
return ((this.x == point.x) && (this.y == point.y));
}
public String toString() {
return String.format("(%.2f, %.2f)", this.x, this.y);
}
public static int getNum() {
return num;
}
}
| java/Point.java | add a point class
| java/Point.java | add a point class | <ide><path>ava/Point.java
<add>public class Point {
<add> public double x;
<add> public double y;
<add> private static int num = 0;
<add>
<add> public Point(double x, double y) {
<add> this.x = x;
<add> this.y = y;
<add> ++num;
<add> }
<add>
<add> public Point() {
<add> this(0.0, 0.0);
<add> }
<add>
<add> public double distance(Point other) {
<add> return Math.sqrt(
<add> Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2)
<add> );
<add> }
<add>
<add> @Override
<add> public boolean equals(Object obj) {
<add> if (this == obj) return true;
<add> if (obj == null) return false;
<add> if (!(obj instanceof Point)) return false;
<add> Point point = (Point)obj;
<add> return ((this.x == point.x) && (this.y == point.y));
<add> }
<add>
<add> public String toString() {
<add> return String.format("(%.2f, %.2f)", this.x, this.y);
<add> }
<add>
<add> public static int getNum() {
<add> return num;
<add> }
<add>} |
|
Java | mit | error: pathspec 'BOJ/17181/Main.java' did not match any file(s) known to git
| 23b2b2baa93af4a74ddd5a412c395ce85176be92 | 1 | ISKU/Algorithm | /*
* Author: Minho Kim (ISKU)
* Date: May 4, 2019
* E-mail: [email protected]
*
* https://github.com/ISKU/Algorithm
* https://www.acmicpc.net/problem/17181
*/
import java.io.*;
import java.util.*;
public class Main {
public static final int[] dy = new int[] { -1, 1, 0, 0 };
public static final int[] dx = new int[] { 0, 0, -1, 1 };
private static int[][] map;
private static int[][][] dp;
private static int Y, X;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Y = Integer.parseInt(st.nextToken());
X = Integer.parseInt(st.nextToken());
map = new int[Y][X];
dp = new int[Y][X][3];
for (int y = 0; y < Y; y++) {
st = new StringTokenizer(br.readLine());
for (int x = 0; x < X; x++) {
map[y][x] = Integer.parseInt(st.nextToken());
Arrays.fill(dp[y][x], Integer.MAX_VALUE);
}
}
if (map[0][0] <= 13)
dfs(0, 0, 0, 0);
int answer = Math.min(dp[Y - 1][X - 1][1], dp[Y - 1][X - 1][2]);
System.out.print((answer == Integer.MAX_VALUE) ? "BAD" : answer);
}
private static void dfs(int y, int x, int status, int count) {
if (dp[y][x][status] <= count)
return;
dp[y][x][status] = count;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || ny >= Y || nx < 0 || nx >= X)
continue;
if (status == 0 && map[ny][nx] >= 14)
dfs(ny, nx, 1, count + 1);
if (status == 1 && map[ny][nx] <= 13) {
dfs(ny, nx, 2, count);
dfs(ny, nx, 0, count);
}
if (status == 2 && map[ny][nx] <= 13)
dfs(ny, nx, 0, count);
}
}
} | BOJ/17181/Main.java | BOJ #17181: 나랏말싸미 America와 different~
| BOJ/17181/Main.java | BOJ #17181: 나랏말싸미 America와 different~ | <ide><path>OJ/17181/Main.java
<add>/*
<add> * Author: Minho Kim (ISKU)
<add> * Date: May 4, 2019
<add> * E-mail: [email protected]
<add> *
<add> * https://github.com/ISKU/Algorithm
<add> * https://www.acmicpc.net/problem/17181
<add> */
<add>
<add>import java.io.*;
<add>import java.util.*;
<add>
<add>public class Main {
<add>
<add> public static final int[] dy = new int[] { -1, 1, 0, 0 };
<add> public static final int[] dx = new int[] { 0, 0, -1, 1 };
<add> private static int[][] map;
<add> private static int[][][] dp;
<add> private static int Y, X;
<add>
<add> public static void main(String[] args) throws Exception {
<add> BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
<add> StringTokenizer st = new StringTokenizer(br.readLine());
<add> Y = Integer.parseInt(st.nextToken());
<add> X = Integer.parseInt(st.nextToken());
<add>
<add> map = new int[Y][X];
<add> dp = new int[Y][X][3];
<add> for (int y = 0; y < Y; y++) {
<add> st = new StringTokenizer(br.readLine());
<add> for (int x = 0; x < X; x++) {
<add> map[y][x] = Integer.parseInt(st.nextToken());
<add> Arrays.fill(dp[y][x], Integer.MAX_VALUE);
<add> }
<add> }
<add>
<add> if (map[0][0] <= 13)
<add> dfs(0, 0, 0, 0);
<add> int answer = Math.min(dp[Y - 1][X - 1][1], dp[Y - 1][X - 1][2]);
<add> System.out.print((answer == Integer.MAX_VALUE) ? "BAD" : answer);
<add> }
<add>
<add> private static void dfs(int y, int x, int status, int count) {
<add> if (dp[y][x][status] <= count)
<add> return;
<add> dp[y][x][status] = count;
<add>
<add> for (int i = 0; i < 4; i++) {
<add> int ny = y + dy[i];
<add> int nx = x + dx[i];
<add> if (ny < 0 || ny >= Y || nx < 0 || nx >= X)
<add> continue;
<add>
<add> if (status == 0 && map[ny][nx] >= 14)
<add> dfs(ny, nx, 1, count + 1);
<add> if (status == 1 && map[ny][nx] <= 13) {
<add> dfs(ny, nx, 2, count);
<add> dfs(ny, nx, 0, count);
<add> }
<add> if (status == 2 && map[ny][nx] <= 13)
<add> dfs(ny, nx, 0, count);
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | b0595873432ccfb298d780da92151bc9dd2f6840 | 0 | apache/incubator-asterixdb,heriram/incubator-asterixdb,ty1er/incubator-asterixdb,heriram/incubator-asterixdb,ty1er/incubator-asterixdb,heriram/incubator-asterixdb,ecarm002/incubator-asterixdb,heriram/incubator-asterixdb,apache/incubator-asterixdb,apache/incubator-asterixdb,ecarm002/incubator-asterixdb,apache/incubator-asterixdb,heriram/incubator-asterixdb,ty1er/incubator-asterixdb,heriram/incubator-asterixdb,ecarm002/incubator-asterixdb,apache/incubator-asterixdb,ecarm002/incubator-asterixdb,ecarm002/incubator-asterixdb,heriram/incubator-asterixdb,apache/incubator-asterixdb,ecarm002/incubator-asterixdb,apache/incubator-asterixdb,ecarm002/incubator-asterixdb,ty1er/incubator-asterixdb,ty1er/incubator-asterixdb,ty1er/incubator-asterixdb | /*
* 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.hyracks.api.config;
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.logging.Level;
/**
* Accessor for the data contained in the global application configuration file.
*/
public interface IApplicationConfig {
String getString(String section, String key);
int getInt(String section, String key);
long getLong(String section, String key);
Set<String> getSectionNames();
Set<String> getKeys(String section);
Object getStatic(IOption option);
List<String> getNCNames();
IOption lookupOption(String sectionName, String propertyName);
Set<IOption> getOptions();
Set<IOption> getOptions(Section section);
IApplicationConfig getNCEffectiveConfig(String nodeId);
Set<Section> getSections();
Set<Section> getSections(Predicate<Section> predicate);
default Object get(IOption option) {
return option.get(this);
}
default long getLong(IOption option) {
return (long)get(option);
}
default int getInt(IOption option) {
return (int)get(option);
}
default String getString(IOption option) {
return (String)get(option);
}
default boolean getBoolean(IOption option) {
return (boolean)get(option);
}
default Level getLoggingLevel(IOption option) {
return (Level)get(option);
}
default double getDouble(IOption option) {
return (double)get(option);
}
default String [] getStringArray(IOption option) {
return (String [])get(option);
}
default URL getURL(IOption option) {
return (URL)get(option);
}
}
| hyracks-fullstack/hyracks/hyracks-api/src/main/java/org/apache/hyracks/api/config/IApplicationConfig.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.hyracks.api.config;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.logging.Level;
/**
* Accessor for the data contained in the global application configuration file.
*/
public interface IApplicationConfig {
String getString(String section, String key);
int getInt(String section, String key);
long getLong(String section, String key);
Set<String> getSectionNames();
Set<String> getKeys(String section);
Object getStatic(IOption option);
List<String> getNCNames();
IOption lookupOption(String sectionName, String propertyName);
Set<IOption> getOptions();
Set<IOption> getOptions(Section section);
IApplicationConfig getNCEffectiveConfig(String nodeId);
Set<Section> getSections();
Set<Section> getSections(Predicate<Section> predicate);
default Object get(IOption option) {
return option.get(this);
}
default long getLong(IOption option) {
return (long)get(option);
}
default int getInt(IOption option) {
return (int)get(option);
}
default String getString(IOption option) {
return (String)get(option);
}
default boolean getBoolean(IOption option) {
return (boolean)get(option);
}
default Level getLoggingLevel(IOption option) {
return (Level)get(option);
}
default double getDouble(IOption option) {
return (double)get(option);
}
default String [] getStringArray(IOption option) {
return (String [])get(option);
}
}
| Add getURL Accessor To IApplicationConfig
Change-Id: I7823ebe31d787399523386f0439128150c58ab39
Reviewed-on: https://asterix-gerrit.ics.uci.edu/1731
Sonar-Qube: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
Tested-by: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
BAD: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
Integration-Tests: Jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@fulliautomatix.ics.uci.edu>
Reviewed-by: Till Westmann <[email protected]>
| hyracks-fullstack/hyracks/hyracks-api/src/main/java/org/apache/hyracks/api/config/IApplicationConfig.java | Add getURL Accessor To IApplicationConfig | <ide><path>yracks-fullstack/hyracks/hyracks-api/src/main/java/org/apache/hyracks/api/config/IApplicationConfig.java
<ide> */
<ide> package org.apache.hyracks.api.config;
<ide>
<add>import java.net.URL;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide> import java.util.function.Predicate;
<ide> default String [] getStringArray(IOption option) {
<ide> return (String [])get(option);
<ide> }
<add>
<add> default URL getURL(IOption option) {
<add> return (URL)get(option);
<add> }
<ide> } |
|
Java | mit | fe260a7c0f4cf08027d6ad5743943abce1ff098d | 0 | olavloite/spanner-jdbc | package nl.topicus.jdbc.test.integration;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.Instance;
import com.google.cloud.spanner.InstanceAdminClient;
import com.google.cloud.spanner.InstanceConfig;
import com.google.cloud.spanner.InstanceConfigId;
import com.google.cloud.spanner.InstanceId;
import com.google.cloud.spanner.Operation;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.SpannerOptions.Builder;
import com.google.spanner.admin.database.v1.CreateDatabaseMetadata;
import com.google.spanner.admin.instance.v1.CreateInstanceMetadata;
import nl.topicus.jdbc.CloudSpannerConnection;
import nl.topicus.jdbc.CloudSpannerDriver;
import nl.topicus.jdbc.test.integration.category.IntegrationTest;
import nl.topicus.jdbc.test.integration.ddl.MetaDataTester;
import nl.topicus.jdbc.test.integration.ddl.TableDDLTester;
import nl.topicus.jdbc.test.integration.dml.DMLTester;
@Category(IntegrationTest.class)
public class JdbcIntegrationTest
{
private static final Logger log = Logger.getLogger(JdbcIntegrationTest.class.getName());
private static final boolean CREATE_INSTANCE = true;
private static final boolean CREATE_DATABASE = true;
private final String instanceId;
private static final String DATABASE_ID = "test-database";
private Spanner spanner;
private final String projectId;
private final String credentialsPath;
public JdbcIntegrationTest()
{
// generate a unique instance id for this test run
Random rnd = new Random();
this.instanceId = "test-instance-" + rnd.nextInt(1000000);
this.credentialsPath = "cloudspanner-key.json";
this.projectId = CloudSpannerConnection.getServiceAccountProjectId(credentialsPath);
GoogleCredentials credentials = null;
try
{
credentials = CloudSpannerConnection.getCredentialsFromFile(credentialsPath);
}
catch (IOException e)
{
throw new RuntimeException("Could not read key file " + credentialsPath, e);
}
Builder builder = SpannerOptions.newBuilder();
builder.setProjectId(projectId);
builder.setCredentials(credentials);
SpannerOptions options = builder.build();
spanner = options.getService();
}
/**
* Run the different tests on the configured database.
*/
@Test
public void performDatabaseTests()
{
try
{
log.info("Starting tests, about to create database");
if (CREATE_INSTANCE)
createInstance();
if (CREATE_DATABASE)
createDatabase();
log.info("Database created");
// Do the testing
log.info("Starting JDBC tests");
performJdbcTests();
log.info("JDBC tests completed");
}
catch (Exception e)
{
throw new RuntimeException("Tests failed", e);
}
finally
{
// Clean up test instance and test database.
log.info("Cleaning up database");
if (CREATE_INSTANCE)
cleanUpInstance();
if (CREATE_DATABASE)
cleanUpDatabase();
spanner.close();
log.info("Clean up completed");
}
}
private void performJdbcTests() throws SQLException, IOException, URISyntaxException
{
// Get a JDBC connection
try (Connection connection = createConnection())
{
connection.setAutoCommit(false);
// Test Table DDL statements
TableDDLTester tableDDLTester = new TableDDLTester(connection);
tableDDLTester.runCreateTests();
// Test DML statements
DMLTester dmlTester = new DMLTester(connection);
dmlTester.runDMLTests();
// Test meta data functions
MetaDataTester metaDataTester = new MetaDataTester(connection);
metaDataTester.runMetaDataTests();
// Test drop statements
tableDDLTester.runDropTests();
}
catch (SQLException e)
{
log.log(Level.WARNING, "Error during JDBC tests", e);
throw e;
}
}
private Connection createConnection() throws SQLException
{
try
{
Class.forName(CloudSpannerDriver.class.getName());
}
catch (ClassNotFoundException e)
{
throw new SQLException("Could not load JDBC driver", e);
}
StringBuilder url = new StringBuilder("jdbc:cloudspanner://localhost");
url.append(";Project=").append(projectId);
url.append(";Instance=").append(instanceId);
url.append(";Database=").append(DATABASE_ID);
url.append(";PvtKeyPath=").append(credentialsPath);
return DriverManager.getConnection(url.toString());
}
private void createInstance()
{
InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();
Iterator<InstanceConfig> configs = instanceAdminClient.listInstanceConfigs().iterateAll().iterator();
InstanceConfigId configId = null;
while (configs.hasNext())
{
InstanceConfig cfg = configs.next();
if (cfg.getDisplayName().toLowerCase().contains("europe"))
{
configId = cfg.getId();
break;
}
}
Instance instance = instanceAdminClient.newInstanceBuilder(InstanceId.of(projectId, instanceId))
.setDisplayName("Test Instance").setInstanceConfigId(configId).setNodeCount(1).build();
Operation<Instance, CreateInstanceMetadata> createInstance = instanceAdminClient.createInstance(instance);
createInstance = createInstance.waitFor();
}
private void createDatabase()
{
Operation<Database, CreateDatabaseMetadata> createDatabase = spanner.getDatabaseAdminClient()
.createDatabase(instanceId, DATABASE_ID, Arrays.asList());
createDatabase = createDatabase.waitFor();
}
private void cleanUpInstance()
{
spanner.getInstanceAdminClient().deleteInstance(instanceId);
}
private void cleanUpDatabase()
{
spanner.getDatabaseAdminClient().dropDatabase(instanceId, DATABASE_ID);
}
}
| src/test/java/nl/topicus/jdbc/test/integration/JdbcIntegrationTest.java | package nl.topicus.jdbc.test.integration;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.Instance;
import com.google.cloud.spanner.InstanceAdminClient;
import com.google.cloud.spanner.InstanceConfig;
import com.google.cloud.spanner.InstanceConfigId;
import com.google.cloud.spanner.InstanceId;
import com.google.cloud.spanner.Operation;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.SpannerOptions.Builder;
import com.google.spanner.admin.database.v1.CreateDatabaseMetadata;
import com.google.spanner.admin.instance.v1.CreateInstanceMetadata;
import nl.topicus.jdbc.CloudSpannerConnection;
import nl.topicus.jdbc.CloudSpannerDriver;
import nl.topicus.jdbc.test.integration.category.IntegrationTest;
import nl.topicus.jdbc.test.integration.ddl.MetaDataTester;
import nl.topicus.jdbc.test.integration.ddl.TableDDLTester;
import nl.topicus.jdbc.test.integration.dml.DMLTester;
@Category(IntegrationTest.class)
public class JdbcIntegrationTest
{
private static final Logger log = Logger.getLogger(JdbcIntegrationTest.class.getName());
private static final boolean CREATE_INSTANCE = true;
private static final boolean CREATE_DATABASE = true;
private static final String INSTANCE_ID = "test-instance";
private static final String DATABASE_ID = "test-database";
private Spanner spanner;
private final String projectId;
private final String credentialsPath;
public JdbcIntegrationTest()
{
this.credentialsPath = "cloudspanner-key.json";
this.projectId = CloudSpannerConnection.getServiceAccountProjectId(credentialsPath);
GoogleCredentials credentials = null;
try
{
credentials = CloudSpannerConnection.getCredentialsFromFile(credentialsPath);
}
catch (IOException e)
{
throw new RuntimeException("Could not read key file " + credentialsPath, e);
}
Builder builder = SpannerOptions.newBuilder();
builder.setProjectId(projectId);
builder.setCredentials(credentials);
SpannerOptions options = builder.build();
spanner = options.getService();
}
/**
* Run the different tests on the configured database.
*/
@Test
public void performDatabaseTests()
{
try
{
log.info("Starting tests, about to create database");
if (CREATE_INSTANCE)
createInstance();
if (CREATE_DATABASE)
createDatabase();
log.info("Database created");
// Do the testing
log.info("Starting JDBC tests");
performJdbcTests();
log.info("JDBC tests completed");
}
catch (Exception e)
{
throw new RuntimeException("Tests failed", e);
}
finally
{
// Clean up test instance and test database.
log.info("Cleaning up database");
if (CREATE_INSTANCE)
cleanUpInstance();
if (CREATE_DATABASE)
cleanUpDatabase();
spanner.close();
log.info("Clean up completed");
}
}
private void performJdbcTests() throws SQLException, IOException, URISyntaxException
{
// Get a JDBC connection
try (Connection connection = createConnection())
{
connection.setAutoCommit(false);
// Test Table DDL statements
TableDDLTester tableDDLTester = new TableDDLTester(connection);
tableDDLTester.runCreateTests();
// Test DML statements
DMLTester dmlTester = new DMLTester(connection);
dmlTester.runDMLTests();
// Test meta data functions
MetaDataTester metaDataTester = new MetaDataTester(connection);
metaDataTester.runMetaDataTests();
// Test drop statements
tableDDLTester.runDropTests();
}
catch (SQLException e)
{
log.log(Level.WARNING, "Error during JDBC tests", e);
throw e;
}
}
private Connection createConnection() throws SQLException
{
try
{
Class.forName(CloudSpannerDriver.class.getName());
}
catch (ClassNotFoundException e)
{
throw new SQLException("Could not load JDBC driver", e);
}
StringBuilder url = new StringBuilder("jdbc:cloudspanner://localhost");
url.append(";Project=").append(projectId);
url.append(";Instance=").append(INSTANCE_ID);
url.append(";Database=").append(DATABASE_ID);
url.append(";PvtKeyPath=").append(credentialsPath);
return DriverManager.getConnection(url.toString());
}
private void createInstance()
{
InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();
Iterator<InstanceConfig> configs = instanceAdminClient.listInstanceConfigs().iterateAll().iterator();
InstanceConfigId configId = null;
while (configs.hasNext())
{
InstanceConfig cfg = configs.next();
if (cfg.getDisplayName().toLowerCase().contains("europe"))
{
configId = cfg.getId();
break;
}
}
Instance instance = instanceAdminClient.newInstanceBuilder(InstanceId.of(projectId, INSTANCE_ID))
.setDisplayName("Test Instance").setInstanceConfigId(configId).setNodeCount(1).build();
Operation<Instance, CreateInstanceMetadata> createInstance = instanceAdminClient.createInstance(instance);
createInstance = createInstance.waitFor();
}
private void createDatabase()
{
Operation<Database, CreateDatabaseMetadata> createDatabase = spanner.getDatabaseAdminClient()
.createDatabase(INSTANCE_ID, DATABASE_ID, Arrays.asList());
createDatabase = createDatabase.waitFor();
}
private void cleanUpInstance()
{
spanner.getInstanceAdminClient().deleteInstance(INSTANCE_ID);
}
private void cleanUpDatabase()
{
spanner.getDatabaseAdminClient().dropDatabase(INSTANCE_ID, DATABASE_ID);
}
}
| generate unique id for test instance to allow multiple integration tests
to run in parallel | src/test/java/nl/topicus/jdbc/test/integration/JdbcIntegrationTest.java | generate unique id for test instance to allow multiple integration tests to run in parallel | <ide><path>rc/test/java/nl/topicus/jdbc/test/integration/JdbcIntegrationTest.java
<ide> import java.sql.SQLException;
<ide> import java.util.Arrays;
<ide> import java.util.Iterator;
<add>import java.util.Random;
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide>
<ide>
<ide> private static final boolean CREATE_DATABASE = true;
<ide>
<del> private static final String INSTANCE_ID = "test-instance";
<add> private final String instanceId;
<ide>
<ide> private static final String DATABASE_ID = "test-database";
<ide>
<ide>
<ide> public JdbcIntegrationTest()
<ide> {
<add> // generate a unique instance id for this test run
<add> Random rnd = new Random();
<add> this.instanceId = "test-instance-" + rnd.nextInt(1000000);
<ide> this.credentialsPath = "cloudspanner-key.json";
<ide> this.projectId = CloudSpannerConnection.getServiceAccountProjectId(credentialsPath);
<ide> GoogleCredentials credentials = null;
<ide> }
<ide> StringBuilder url = new StringBuilder("jdbc:cloudspanner://localhost");
<ide> url.append(";Project=").append(projectId);
<del> url.append(";Instance=").append(INSTANCE_ID);
<add> url.append(";Instance=").append(instanceId);
<ide> url.append(";Database=").append(DATABASE_ID);
<ide> url.append(";PvtKeyPath=").append(credentialsPath);
<ide> return DriverManager.getConnection(url.toString());
<ide> break;
<ide> }
<ide> }
<del> Instance instance = instanceAdminClient.newInstanceBuilder(InstanceId.of(projectId, INSTANCE_ID))
<add> Instance instance = instanceAdminClient.newInstanceBuilder(InstanceId.of(projectId, instanceId))
<ide> .setDisplayName("Test Instance").setInstanceConfigId(configId).setNodeCount(1).build();
<ide> Operation<Instance, CreateInstanceMetadata> createInstance = instanceAdminClient.createInstance(instance);
<ide> createInstance = createInstance.waitFor();
<ide> private void createDatabase()
<ide> {
<ide> Operation<Database, CreateDatabaseMetadata> createDatabase = spanner.getDatabaseAdminClient()
<del> .createDatabase(INSTANCE_ID, DATABASE_ID, Arrays.asList());
<add> .createDatabase(instanceId, DATABASE_ID, Arrays.asList());
<ide> createDatabase = createDatabase.waitFor();
<ide> }
<ide>
<ide> private void cleanUpInstance()
<ide> {
<del> spanner.getInstanceAdminClient().deleteInstance(INSTANCE_ID);
<add> spanner.getInstanceAdminClient().deleteInstance(instanceId);
<ide> }
<ide>
<ide> private void cleanUpDatabase()
<ide> {
<del> spanner.getDatabaseAdminClient().dropDatabase(INSTANCE_ID, DATABASE_ID);
<add> spanner.getDatabaseAdminClient().dropDatabase(instanceId, DATABASE_ID);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | b98453b778fbbe4aa9fb9b0af569c5c6f591c62e | 0 | apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc | /*
* 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.core.execute.sql.execute.result;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.execute.sql.execute.row.QueryRow;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Distinct query result.
*
* @author panjuan
* @author yangyi
* @author sunbufu
*/
@RequiredArgsConstructor
@Getter(AccessLevel.PROTECTED)
public class DistinctQueryResult implements QueryResult {
@Getter
private final QueryResultMetaData queryResultMetaData;
private final List<Boolean> columnCaseSensitive;
private final Iterator<QueryRow> resultData;
private QueryRow currentRow;
@SneakyThrows
public DistinctQueryResult(final Collection<QueryResult> queryResults, final List<String> distinctColumnLabels) {
QueryResult firstQueryResult = queryResults.iterator().next();
this.queryResultMetaData = firstQueryResult.getQueryResultMetaData();
this.columnCaseSensitive = getColumnCaseSensitive(firstQueryResult);
resultData = getResultData(queryResults, distinctColumnLabels);
}
@SneakyThrows
private List<Boolean> getColumnCaseSensitive(final QueryResult queryResult) {
List<Boolean> result = Lists.newArrayList(false);
for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) {
result.add(queryResult.isCaseSensitive(columnIndex));
}
return result;
}
@SneakyThrows
private Iterator<QueryRow> getResultData(final Collection<QueryResult> queryResults, final List<String> distinctColumnLabels) {
Set<QueryRow> result = new LinkedHashSet<>();
List<Integer> distinctColumnIndexes = Lists.transform(distinctColumnLabels, new Function<String, Integer>() {
@Override
public Integer apply(final String input) {
return getColumnIndex(input);
}
});
for (QueryResult each : queryResults) {
fill(result, each, distinctColumnIndexes);
}
return result.iterator();
}
@SneakyThrows
private void fill(final Set<QueryRow> resultData, final QueryResult queryResult, final List<Integer> distinctColumnIndexes) {
while (queryResult.next()) {
List<Object> rowData = new ArrayList<>(queryResult.getColumnCount());
for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) {
rowData.add(queryResult.getValue(columnIndex, Object.class));
}
resultData.add(new QueryRow(rowData, distinctColumnIndexes));
}
}
/**
* Divide one distinct query result to multiple child ones.
*
* @return multiple child distinct query results
*/
public List<DistinctQueryResult> divide() {
return Lists.newArrayList(Iterators.transform(resultData, new Function<QueryRow, DistinctQueryResult>() {
@Override
public DistinctQueryResult apply(final QueryRow row) {
Set<QueryRow> resultData = new LinkedHashSet<>();
resultData.add(row);
return new DistinctQueryResult(queryResultMetaData, columnCaseSensitive, resultData.iterator());
}
}));
}
@Override
public final boolean next() {
if (resultData.hasNext()) {
currentRow = resultData.next();
return true;
}
currentRow = null;
return false;
}
@Override
public Object getValue(final int columnIndex, final Class<?> type) {
return currentRow.getColumnValue(columnIndex);
}
@Override
public Object getValue(final String columnLabel, final Class<?> type) {
return currentRow.getColumnValue(getColumnIndex(columnLabel));
}
@Override
public Object getCalendarValue(final int columnIndex, final Class<?> type, final Calendar calendar) {
return currentRow.getColumnValue(columnIndex);
}
@Override
public Object getCalendarValue(final String columnLabel, final Class<?> type, final Calendar calendar) {
return currentRow.getColumnValue(getColumnIndex(columnLabel));
}
@Override
public InputStream getInputStream(final int columnIndex, final String type) {
return getInputStream(currentRow.getColumnValue(columnIndex));
}
@Override
public InputStream getInputStream(final String columnLabel, final String type) {
return getInputStream(currentRow.getColumnValue(getColumnIndex(columnLabel)));
}
@SneakyThrows
protected InputStream getInputStream(final Object value) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(value);
objectOutputStream.flush();
objectOutputStream.close();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
@Override
public boolean wasNull() {
return null == currentRow;
}
@Override
public boolean isCaseSensitive(final int columnIndex) {
return columnCaseSensitive.get(columnIndex);
}
@Override
public int getColumnCount() {
return queryResultMetaData.getColumnCount();
}
@Override
public String getColumnLabel(final int columnIndex) throws SQLException {
String columnLabel = queryResultMetaData.getColumnLabel(columnIndex);
if (null != columnLabel) {
return columnLabel;
}
throw new SQLException("Column index out of range", "9999");
}
protected Integer getColumnIndex(final String columnLabel) {
return queryResultMetaData.getColumnIndex(columnLabel);
}
}
| sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.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.core.execute.sql.execute.result;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.execute.sql.execute.row.QueryRow;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Distinct query result.
*
* @author panjuan
* @author yangyi
*/
@RequiredArgsConstructor
@Getter(AccessLevel.PROTECTED)
public class DistinctQueryResult implements QueryResult {
@Getter
private final QueryResultMetaData queryResultMetaData;
private final List<Boolean> columnCaseSensitive;
private final Iterator<QueryRow> resultData;
private QueryRow currentRow;
@SneakyThrows
public DistinctQueryResult(final Collection<QueryResult> queryResults, final List<String> distinctColumnLabels) {
QueryResult firstQueryResult = queryResults.iterator().next();
this.queryResultMetaData = firstQueryResult.getQueryResultMetaData();
this.columnCaseSensitive = getColumnCaseSensitive(firstQueryResult);
resultData = getResultData(queryResults, distinctColumnLabels);
}
@SneakyThrows
private List<Boolean> getColumnCaseSensitive(final QueryResult queryResult) {
List<Boolean> result = Lists.newArrayList(false);
for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) {
result.add(queryResult.isCaseSensitive(columnIndex));
}
return result;
}
@SneakyThrows
private Iterator<QueryRow> getResultData(final Collection<QueryResult> queryResults, final List<String> distinctColumnLabels) {
Set<QueryRow> result = new LinkedHashSet<>();
List<Integer> distinctColumnIndexes = Lists.transform(distinctColumnLabels, new Function<String, Integer>() {
@Override
public Integer apply(final String input) {
return getColumnIndex(input);
}
});
for (QueryResult each : queryResults) {
fill(result, each, distinctColumnIndexes);
}
return result.iterator();
}
@SneakyThrows
private void fill(final Set<QueryRow> resultData, final QueryResult queryResult, final List<Integer> distinctColumnIndexes) {
while (queryResult.next()) {
List<Object> rowData = new ArrayList<>(queryResult.getColumnCount());
for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) {
rowData.add(queryResult.getValue(columnIndex, Object.class));
}
resultData.add(new QueryRow(rowData, distinctColumnIndexes));
}
}
/**
* Divide one distinct query result to multiple child ones.
*
* @return multiple child distinct query results
*/
public List<DistinctQueryResult> divide() {
return Lists.newArrayList(Iterators.transform(resultData, new Function<QueryRow, DistinctQueryResult>() {
@Override
public DistinctQueryResult apply(final QueryRow row) {
Set<QueryRow> resultData = new LinkedHashSet<>();
resultData.add(row);
return new DistinctQueryResult(queryResultMetaData, columnCaseSensitive, resultData.iterator());
}
}));
}
@Override
public final boolean next() {
if (resultData.hasNext()) {
currentRow = resultData.next();
return true;
}
currentRow = null;
return false;
}
@Override
public Object getValue(final int columnIndex, final Class<?> type) {
return currentRow.getColumnValue(columnIndex);
}
@Override
public Object getValue(final String columnLabel, final Class<?> type) {
return currentRow.getColumnValue(getColumnIndex(columnLabel));
}
@Override
public Object getCalendarValue(final int columnIndex, final Class<?> type, final Calendar calendar) {
return currentRow.getColumnValue(columnIndex);
}
@Override
public Object getCalendarValue(final String columnLabel, final Class<?> type, final Calendar calendar) {
return currentRow.getColumnValue(getColumnIndex(columnLabel));
}
@Override
public InputStream getInputStream(final int columnIndex, final String type) {
return getInputStream(currentRow.getColumnValue(columnIndex));
}
@Override
public InputStream getInputStream(final String columnLabel, final String type) {
return getInputStream(currentRow.getColumnValue(getColumnIndex(columnLabel)));
}
@SneakyThrows
protected InputStream getInputStream(final Object value) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(value);
objectOutputStream.flush();
objectOutputStream.close();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
@Override
public boolean wasNull() {
return null == currentRow;
}
@Override
public boolean isCaseSensitive(final int columnIndex) {
return columnCaseSensitive.get(columnIndex);
}
@Override
public int getColumnCount() {
return queryResultMetaData.getColumnCount();
}
@Override
public String getColumnLabel(final int columnIndex) throws SQLException {
String columnLabel = queryResultMetaData.getColumnLabel(columnIndex);
if (null != columnLabel) {
return columnLabel;
}
throw new SQLException("Column index out of range", "9999");
}
protected Integer getColumnIndex(final String columnLabel) {
return queryResultMetaData.getColumnIndex(columnLabel);
}
}
| retry check
| sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.java | retry check | <ide><path>harding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.java
<ide> *
<ide> * @author panjuan
<ide> * @author yangyi
<add> * @author sunbufu
<ide> */
<ide> @RequiredArgsConstructor
<ide> @Getter(AccessLevel.PROTECTED) |
|
JavaScript | bsd-3-clause | b676292207aba207666494527478a360d49fe147 | 0 | MalucoMarinero/fixed-data-table-backup,MalucoMarinero/fixed-data-table-backup | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule FixedDataTable.react
* @typechecks
*/
/* jslint bitwise: true */
var FixedDataTableHelper = require('FixedDataTableHelper');
var Locale = require('Locale');
var React = require('React');
var ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');
var ReactWheelHandler = require('ReactWheelHandler');
var Scrollbar = require('Scrollbar.react');
var FixedDataTableBufferedRows = require('FixedDataTableBufferedRows.react');
var FixedDataTableColumnResizeHandle = require('FixedDataTableColumnResizeHandle.react');
var FixedDataTableRow = require('FixedDataTableRow.react');
var FixedDataTableScrollHelper = require('FixedDataTableScrollHelper');
var FixedDataTableWidthHelper = require('FixedDataTableWidthHelper');
var cloneWithProps = require('cloneWithProps');
var cx = require('cx');
var debounceCore = require('debounceCore');
var emptyFunction = require('emptyFunction');
var invariant = require('invariant');
var shallowEqual = require('shallowEqual');
var translateDOMPositionXY = require('translateDOMPositionXY');
var PropTypes = React.PropTypes;
var ReactChildren = React.Children;
var renderToString = FixedDataTableHelper.renderToString;
var EMPTY_OBJECT = {};
var COLUMN_SETTING_NAMES = [
'bodyFixedColumns',
'bodyScrollableColumns',
'headFixedColumns',
'headScrollableColumns',
'footFixedColumns',
'footScrollableColumns',
];
/**
* Data grid component with fixed or scrollable header and columns.
*
* The layout of the data table is as follow:
*
* ```
* +---------------------------------------------------+
* | Fixed Column Group | Scrollable Column Group |
* | Header | Header |
* | | |
* +---------------------------------------------------+
* | | |
* | Fixed Header Columns | Scrollable Header Columns |
* | | |
* +-----------------------+---------------------------+
* | | |
* | Fixed Body Columns | Scrollable Body Columns |
* | | |
* +-----------------------+---------------------------+
* | | |
* | Fixed Footer Columns | Scrollable Footer Columns |
* | | |
* +-----------------------+---------------------------+
* ```
*
* - Fixed Column Group Header: These are the headers for a group
* of columns if included in the table that do not scroll
* vertically or horizontally.
*
* - Scrollable Column Group Header: The header for a group of columns
* that do not move while scrolling vertically, but move horizontally
* with the horizontal scrolling.
*
* - Fixed Header Columns: The header columns that do not move while scrolling
* vertically or horizontally.
*
* - Scrollable Header Columns: The header columns that do not move
* while scrolling vertically, but move horizontally with the horizontal
* scrolling.
*
* - Fixed Body Columns: The body columns that do not move while scrolling
* horizontally, but move vertically with the vertical scrolling.
*
* - Scrollable Body Columns: The body columns that move while scrolling
* vertically or horizontally.
*/
var FixedDataTable = React.createClass({
propTypes: {
/**
* Pixel width of table. If all rows do not fit,
* a horizontal scrollbar will appear.
*/
width: PropTypes.number.isRequired,
/**
* Pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
height: PropTypes.number,
/**
* Maximum pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
maxHeight: PropTypes.number,
/**
* Pixel height of table's owner, This is used to make sure the footer
* and scrollbar of the table are visible when current space for table in
* view is smaller than final height of table. It allows to avoid resizing
* and reflowing table whan it is moving in the view.
*
* This is used if `ownerHeight < height`.
*/
ownerHeight: PropTypes.number,
overflowX: PropTypes.oneOf(['hidden', 'auto']),
overflowY: PropTypes.oneOf(['hidden', 'auto']),
/**
* Number of rows in the table.
*/
rowsCount: PropTypes.number.isRequired,
/**
* Pixel height of rows unless rowHeightGetter is specified and returns
* different value.
*/
rowHeight: PropTypes.number.isRequired,
/**
* If specified, `rowHeightGetter(index)` is called for each row and the
* returned value overrides rowHeight for particular row.
*/
rowHeightGetter: PropTypes.func,
/**
* To get rows to display in table, `rowGetter(index)`
* is called. rowGetter should be smart enough to handle async
* fetching of data and returning temporary objects
* while data is being fetched.
*/
rowGetter: PropTypes.func.isRequired,
/**
* To get any additional css classes that should be added to a row,
* `rowClassNameGetter(index)` is called.
*/
rowClassNameGetter: PropTypes.func,
/**
* Pixel height of the column group header.
*/
groupHeaderHeight: PropTypes.number,
/**
* Pixel height of header.
*/
headerHeight: PropTypes.number.isRequired,
/**
* Function that is called to get the data for the header row.
*/
headerDataGetter: PropTypes.func,
/**
* Pixel height of footer.
*/
footerHeight: PropTypes.number,
/**
* Data that will be passed to footer cell renderers.
*/
footerData: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array,
]),
/**
* Value of horizontal scroll.
*/
scrollLeft: PropTypes.number,
/**
* Index of column to scroll to.
*/
scrollToColumn: PropTypes.number,
/**
* Value of vertical scroll.
*/
scrollTop: PropTypes.number,
/**
* Index of row to scroll to.
*/
scrollToRow: PropTypes.number,
/**
* Callback that is called when scrolling ends or stops with new horizontal
* and vertical scroll values.
*/
onScrollEnd: PropTypes.func,
/**
* Callback that is called when `rowHeightGetter` returns a different height
* for a row than the `rowHeight` prop. This is necessary because initially
* table estimates heights of some parts of the content.
*/
onContentHeightChange: PropTypes.func,
/**
* Callback that is called when a row is clicked.
*/
onRowClick: PropTypes.func,
/**
* Callback that is called when mouse down event happens above a row.
*/
onRowMouseDown: PropTypes.func,
/**
* Callback that is called when the mouse enters a row.
*/
onRowMouseEnter: PropTypes.func,
/**
* Callback that is called when resizer has been released
* and column needs to be updated.
*/
onColumnResizeEndCallback: PropTypes.func,
/**
* Whether a column is currently being resized.
*/
isColumnResizing: PropTypes.bool,
},
getDefaultProps() /*object*/ {
return {
footerHeight: 0,
groupHeaderHeight: 0,
headerHeight: 0,
scrollLeft: 0,
scrollTop: 0,
};
},
getInitialState() /*object*/ {
var props = this.props;
var viewportHeight = props.height -
props.headerHeight -
props.groupHeaderHeight -
props.footerHeight;
this._scrollHelper = new FixedDataTableScrollHelper(
props.rowsCount,
props.rowHeight,
viewportHeight,
props.rowHeightGetter,
props.groupHeaderScrollsOut ? props.groupHeaderHeight : 0
);
if (props.scrollTop) {
this._scrollHelper.scrollTo(props.scrollTop);
}
this._didScrollStop = debounceCore(this._didScrollStop, 160, this);
this.tScroller = new Scroller(this._handleTouchScroll);
return this._calculateState(this.props);
},
componentWillMount() {
var scrollToRow = this.props.scrollToRow;
if (scrollToRow !== undefined && scrollToRow !== null) {
this._rowToScrollTo = scrollToRow;
}
var scrollToColumn = this.props.scrollToColumn;
if (scrollToColumn !== undefined && scrollToColumn !== null) {
this._columnToScrollTo = scrollToColumn;
}
this._wheelHandler = new ReactWheelHandler(
this._onWheel,
this.props.overflowX !== 'hidden', // Should handle horizontal scroll
this.props.overflowY !== 'hidden' // Should handle vertical scroll
);
},
_handleTouchStart(e) {
this.tScroller.doTouchStart(e.touches, e.timeStamp)
e.preventDefault()
},
_handleTouchMove(e) {
this.tScroller.doTouchMove(e.touches, e.timeStamp, e.scale)
e.preventDefault()
},
_handleTouchEnd(e) {
this.tScroller.doTouchEnd(e.timeStamp)
e.preventDefault()
},
_reportContentHeight() {
var scrollContentHeight = this.state.scrollContentHeight;
var reservedHeight = this.state.reservedHeight;
var requiredHeight = scrollContentHeight + reservedHeight;
var contentHeight;
if (this.state.height > requiredHeight && this.props.ownerHeight) {
contentHeight = Math.max(requiredHeight, this.props.ownerHeight);
} else {
var maxScrollY = scrollContentHeight - this.state.bodyHeight;
contentHeight = this.props.height + maxScrollY;
}
if (contentHeight !== this._contentHeight &&
this.props.onContentHeightChange) {
this.props.onContentHeightChange(contentHeight);
}
this._contentHeight = contentHeight;
},
componentDidMount() {
this._reportContentHeight();
},
componentWillReceiveProps(/*object*/ nextProps) {
var scrollToRow = nextProps.scrollToRow;
if (scrollToRow !== undefined && scrollToRow !== null) {
this._rowToScrollTo = scrollToRow;
}
var scrollToColumn = nextProps.scrollToColumn;
if (scrollToColumn !== undefined && scrollToColumn !== null) {
this._columnToScrollTo = scrollToColumn;
}
var newOverflowX = nextProps.overflowX;
var newOverflowY = nextProps.overflowY;
if (newOverflowX !== this.props.overflowX ||
newOverflowY !== this.props.overflowY) {
this._wheelHandler = new ReactWheelHandler(
this._onWheel,
newOverflowX !== 'hidden', // Should handle horizontal scroll
newOverflowY !== 'hidden' // Should handle vertical scroll
);
}
this.setState(this._calculateState(nextProps, this.state));
},
componentDidUpdate() {
this._reportContentHeight();
},
render() /*object*/ {
var state = this.state;
var props = this.props;
var groupHeader;
if (state.useGroupHeader) {
groupHeader = (
<FixedDataTableRow
key="group_header"
className={cx('public/fixedDataTable/header')}
data={state.groupHeaderData}
width={state.width}
height={state.groupHeaderHeight}
index={0}
zIndex={1}
offsetTop={0}
scrollLeft={state.scrollX}
fixedColumns={state.groupHeaderFixedColumns}
scrollableColumns={state.groupHeaderScrollableColumns}
/>
);
}
var maxScrollY = this.state.scrollContentHeight - this.state.bodyHeight;
var showScrollbarX = state.maxScrollX > 0 && state.overflowX !== 'hidden';
var showScrollbarY = maxScrollY > 0 && state.overflowY !== 'hidden';
var scrollbarXHeight = showScrollbarX ? Scrollbar.SIZE : 0;
var scrollbarYHeight = state.height - scrollbarXHeight;
var headerOffsetTop = state.useGroupHeader ? state.groupHeaderHeight : 0;
var bodyOffsetTop = headerOffsetTop + state.headerHeight;
var bottomSectionOffset = 0;
var footOffsetTop = bodyOffsetTop + state.bodyHeight;
var rowsContainerHeight = footOffsetTop + state.footerHeight;
if (props.ownerHeight !== undefined && props.ownerHeight < props.height) {
bottomSectionOffset = props.ownerHeight - props.height;
footOffsetTop = Math.min(
footOffsetTop,
scrollbarYHeight + bottomSectionOffset - state.footerHeight
);
scrollbarYHeight = props.ownerHeight - scrollbarXHeight;
}
var verticalScrollbar;
if (showScrollbarY) {
verticalScrollbar =
<Scrollbar
size={scrollbarYHeight}
contentSize={scrollbarYHeight + maxScrollY}
onScroll={this._onVerticalScroll}
position={state.scrollY}
/>;
}
var horizontalScrollbar;
if (showScrollbarX) {
var scrollbarYWidth = showScrollbarY ? Scrollbar.SIZE : 0;
var scrollbarXWidth = state.width - scrollbarYWidth;
horizontalScrollbar =
<HorizontalScrollbar
contentSize={scrollbarXWidth + state.maxScrollX}
offset={bottomSectionOffset}
onScroll={this._onHorizontalScroll}
position={state.scrollX}
size={scrollbarXWidth}
/>;
}
var dragKnob =
<FixedDataTableColumnResizeHandle
height={state.height}
initialWidth={state.columnResizingData.width || 0}
minWidth={state.columnResizingData.minWidth || 0}
maxWidth={state.columnResizingData.maxWidth || Number.MAX_VALUE}
visible={!!state.isColumnResizing}
leftOffset={state.columnResizingData.left || 0}
knobHeight={state.headerHeight}
initialEvent={state.columnResizingData.initialEvent}
onColumnResizeEnd={props.onColumnResizeEndCallback}
columnKey={state.columnResizingData.key}
/>;
var footer = null;
if (state.footerHeight) {
footer =
<FixedDataTableRow
key="footer"
className={cx('public/fixedDataTable/footer')}
data={state.footerData}
fixedColumns={state.footFixedColumns}
height={state.footerHeight}
index={-1}
zIndex={1}
offsetTop={footOffsetTop}
scrollableColumns={state.footScrollableColumns}
scrollLeft={state.scrollX}
width={state.width}
/>;
}
var rows = this._renderRows(bodyOffsetTop);
var header =
<FixedDataTableRow
key="header"
className={cx('public/fixedDataTable/header')}
data={state.headData}
width={state.width}
height={state.headerHeight}
index={-1}
zIndex={1}
offsetTop={headerOffsetTop}
scrollLeft={state.scrollX}
fixedColumns={state.headFixedColumns}
scrollableColumns={state.headScrollableColumns}
onColumnResize={this._onColumnResize}
/>;
var shadow;
if (state.scrollY) {
shadow =
<div
className={cx('fixedDataTable/shadow')}
style={{top: bodyOffsetTop}}
/>;
}
return (
<div
className={cx('public/fixedDataTable/main')}
onWheel={this._wheelHandler.onWheel}
onTouchStart={this._handleTouchStart}
onTouchMove={this._handleTouchMove}
onTouchEnd={this._handleTouchEnd}
style={{height: state.height, width: state.width}}>
<div
className={cx('fixedDataTable/rowsContainer')}
style={{height: rowsContainerHeight, width: state.width}}>
{dragKnob}
{groupHeader}
{header}
{rows}
{footer}
{shadow}
</div>
{verticalScrollbar}
{horizontalScrollbar}
</div>
);
},
_renderRows(/*number*/ offsetTop) /*object*/ {
var state = this.state;
return (
<FixedDataTableBufferedRows
defaultRowHeight={state.rowHeight}
firstRowIndex={state.firstRowIndex}
firstRowOffset={state.firstRowOffset}
fixedColumns={state.bodyFixedColumns}
height={state.bodyHeight}
offsetTop={offsetTop}
onRowClick={state.onRowClick}
onRowMouseDown={state.onRowMouseDown}
onRowMouseEnter={state.onRowMouseEnter}
rowClassNameGetter={state.rowClassNameGetter}
rowsCount={state.rowsCount}
rowGetter={state.rowGetter}
rowHeightGetter={state.rowHeightGetter}
scrollLeft={state.scrollX}
scrollableColumns={state.bodyScrollableColumns}
showLastRowBorder={!state.footerHeight}
width={state.width}
/>
);
},
/**
* This is called when a cell that is in the header of a column has its
* resizer knob clicked on. It displays the resizer and puts in the correct
* location on the table.
*/
_onColumnResize(
/*number*/ combinedWidth,
/*number*/ leftOffset,
/*number*/ cellWidth,
/*?number*/ cellMinWidth,
/*?number*/ cellMaxWidth,
/*number|string*/ columnKey,
/*object*/ event) {
if (Locale.isRTL()) {
leftOffset = -leftOffset;
}
this.setState({
isColumnResizing: true,
columnResizingData: {
left: leftOffset + combinedWidth - cellWidth,
width: cellWidth,
minWidth: cellMinWidth,
maxWidth: cellMaxWidth,
initialEvent: {
clientX: event.clientX,
clientY: event.clientY,
preventDefault: emptyFunction
},
key: columnKey
}
});
},
_populateColumnsAndColumnData(
/*array*/ columns,
/*?array*/ columnGroups
) /*object*/ {
var columnInfo = {};
var bodyColumnTypes = this._splitColumnTypes(columns);
columnInfo.bodyFixedColumns = bodyColumnTypes.fixed;
columnInfo.bodyScrollableColumns = bodyColumnTypes.scrollable;
columnInfo.headData = this._getHeadData(columns);
var headColumnTypes = this._splitColumnTypes(
this._createHeadColumns(columns)
);
columnInfo.headFixedColumns = headColumnTypes.fixed;
columnInfo.headScrollableColumns = headColumnTypes.scrollable;
var footColumnTypes = this._splitColumnTypes(
this._createFootColumns(columns)
);
columnInfo.footFixedColumns = footColumnTypes.fixed;
columnInfo.footScrollableColumns = footColumnTypes.scrollable;
if (columnGroups) {
columnInfo.groupHeaderData = this._getGroupHeaderData(columnGroups);
columnGroups = this._createGroupHeaderColumns(columnGroups);
var groupHeaderColumnTypes = this._splitColumnTypes(columnGroups);
columnInfo.groupHeaderFixedColumns = groupHeaderColumnTypes.fixed;
columnInfo.groupHeaderScrollableColumns =
groupHeaderColumnTypes.scrollable;
}
return columnInfo;
},
_calculateState(/*object*/ props, /*?object*/ oldState) /*object*/ {
invariant(
props.height !== undefined || props.maxHeight !== undefined,
'You must set either a height or a maxHeight'
);
var firstRowIndex = (oldState && oldState.firstRowIndex) || 0;
var firstRowOffset = (oldState && oldState.firstRowOffset) || 0;
var scrollX, scrollY;
if (oldState && props.overflowX !== 'hidden') {
scrollX = oldState.scrollX;
} else {
scrollX = props.scrollLeft;
}
if (oldState && props.overflowY !== 'hidden') {
scrollY = oldState.scrollY;
} else {
scrollState = this._scrollHelper.scrollTo(props.scrollTop);
firstRowIndex = scrollState.index;
firstRowOffset = scrollState.offset;
scrollY = scrollState.position;
}
if (this._rowToScrollTo !== undefined) {
scrollState =
this._scrollHelper.scrollRowIntoView(this._rowToScrollTo);
firstRowIndex = scrollState.index;
firstRowOffset = scrollState.offset;
scrollY = scrollState.position;
delete this._rowToScrollTo;
}
if (oldState && props.rowsCount !== oldState.rowsCount) {
// Number of rows changed, try to scroll to the row from before the
// change
var viewportHeight = props.height -
props.headerHeight -
props.footerHeight -
props.groupHeaderHeight;
this._scrollHelper = new FixedDataTableScrollHelper(
props.rowsCount,
props.rowHeight,
viewportHeight,
props.rowHeightGetter,
props.groupHeaderScrollsOut ? props.groupHeaderHeight : 0
);
var scrollState =
this._scrollHelper.scrollToRow(firstRowIndex, firstRowOffset);
firstRowIndex = scrollState.index;
firstRowOffset = scrollState.offset;
scrollY = scrollState.position;
} else if (oldState && props.rowHeightGetter !== oldState.rowHeightGetter) {
this._scrollHelper.setRowHeightGetter(props.rowHeightGetter);
}
var columnResizingData;
if (props.isColumnResizing) {
columnResizingData = oldState && oldState.columnResizingData;
} else {
columnResizingData = EMPTY_OBJECT;
}
var children = [];
ReactChildren.forEach(props.children, (child, index) => {
if (child == null) {
return;
}
invariant(
child.type.__TableColumnGroup__ ||
child.type.__TableColumn__,
'child type should be <FixedDataTableColumn /> or ' +
'<FixedDataTableColumnGroup />'
);
children.push(child);
});
var useGroupHeader = false;
if (children.length && children[0].type.__TableColumnGroup__) {
useGroupHeader = true;
}
var columns;
var columnGroups;
if (useGroupHeader) {
var columnGroupSettings =
FixedDataTableWidthHelper.adjustColumnGroupWidths(
children,
props.width
);
columns = columnGroupSettings.columns;
columnGroups = columnGroupSettings.columnGroups;
} else {
columns = FixedDataTableWidthHelper.adjustColumnWidths(
children,
props.width
);
}
var columnInfo = this._populateColumnsAndColumnData(
columns,
columnGroups
);
if (oldState) {
columnInfo = this._tryReusingColumnSettings(columnInfo, oldState);
}
if (this._columnToScrollTo !== undefined) {
// If selected column is a fixed column, don't scroll
var fixedColumnsCount = columnInfo.bodyFixedColumns.length;
if (this._columnToScrollTo >= fixedColumnsCount) {
var totalFixedColumnsWidth = 0;
var i, column;
for (i = 0; i < columnInfo.bodyFixedColumns.length; ++i) {
column = columnInfo.bodyFixedColumns[i];
totalFixedColumnsWidth += column.props.width;
}
var scrollableColumnIndex = this._columnToScrollTo - fixedColumnsCount;
var previousColumnsWidth = 0;
for (i = 0; i < scrollableColumnIndex; ++i) {
column = columnInfo.bodyScrollableColumns[i];
previousColumnsWidth += column.props.width;
}
var availableScrollWidth = props.width - totalFixedColumnsWidth;
var selectedColumnWidth = columnInfo.bodyScrollableColumns[
this._columnToScrollTo - fixedColumnsCount
].props.width;
var minAcceptableScrollPosition =
previousColumnsWidth + selectedColumnWidth - availableScrollWidth;
if (scrollX < minAcceptableScrollPosition) {
scrollX = minAcceptableScrollPosition;
}
if (scrollX > previousColumnsWidth) {
scrollX = previousColumnsWidth;
}
}
delete this._columnToScrollTo;
}
var useMaxHeight = props.height === undefined;
var height = useMaxHeight ? props.maxHeight : props.height;
var totalHeightReserved = props.footerHeight + props.headerHeight +
props.groupHeaderHeight;
var bodyHeight = height - totalHeightReserved;
var scrollContentHeight = this._scrollHelper.getContentHeight();
var totalHeightNeeded = scrollContentHeight + totalHeightReserved;
var scrollContentWidth =
FixedDataTableWidthHelper.getTotalWidth(columns);
var horizontalScrollbarVisible = scrollContentWidth > props.width &&
props.overflowX !== 'hidden';
if (horizontalScrollbarVisible) {
bodyHeight -= Scrollbar.SIZE;
totalHeightNeeded += Scrollbar.SIZE;
totalHeightReserved += Scrollbar.SIZE;
}
var maxScrollX = Math.max(0, scrollContentWidth - props.width);
var maxScrollY = Math.max(0, scrollContentHeight - bodyHeight);
scrollX = Math.min(scrollX, maxScrollX);
scrollY = Math.min(scrollY, maxScrollY);
this.tScroller.setDimensions(
props.width,
bodyHeight,
scrollContentWidth,
scrollContentHeight
);
if (!maxScrollY) {
// no vertical scrollbar necessary, use the totals we tracked so we
// can shrink-to-fit vertically
if (useMaxHeight) {
height = totalHeightNeeded;
}
bodyHeight = totalHeightNeeded - totalHeightReserved;
}
this._scrollHelper.setViewportHeight(bodyHeight);
bodyHeight = this._getHeaderScrollHeight(scrollY);
// autohiding that shizz
var groupHeaderHeight = props.groupHeaderScrollsOut
? Math.max(props.groupHeaderHeight - scrollY, 0)
: props.groupHeaderHeight;
// The order of elements in this object metters and bringing bodyHeight,
// height or useGroupHeader to the top can break various features
var newState = {
isColumnResizing: oldState && oldState.isColumnResizing,
// isColumnResizing should be overwritten by value from props if
// avaialble
...columnInfo,
...props,
columnResizingData,
firstRowIndex,
firstRowOffset,
horizontalScrollbarVisible,
maxScrollX,
reservedHeight: totalHeightReserved,
scrollContentHeight,
scrollX,
scrollY,
// These properties may overwrite properties defined in
// columnInfo and props
bodyHeight,
height,
useGroupHeader,
groupHeaderHeight,
};
// Both `headData` and `groupHeaderData` are generated by
// `FixedDataTable` will be passed to each header cell to render.
// In order to prevent over-rendering the cells, we do not pass the
// new `headData` or `groupHeaderData`
// if they haven't changed.
if (oldState) {
if (shallowEqual(oldState.headData, newState.headData)) {
newState.headData = oldState.headData;
}
if (shallowEqual(oldState.groupHeaderData, newState.groupHeaderData)) {
newState.groupHeaderData = oldState.groupHeaderData;
}
}
return newState;
},
_tryReusingColumnSettings(
/*object*/ columnInfo,
/*object*/ oldState
) /*object*/ {
COLUMN_SETTING_NAMES.forEach(settingName => {
if (columnInfo[settingName].length === oldState[settingName].length) {
var canReuse = true;
for (var index = 0; index < columnInfo[settingName].length; ++index) {
if (!shallowEqual(
columnInfo[settingName][index].props,
oldState[settingName][index].props
)) {
canReuse = false;
break;
}
}
if (canReuse) {
columnInfo[settingName] = oldState[settingName];
}
}
});
return columnInfo;
},
_createGroupHeaderColumns(/*array*/ columnGroups) /*array*/ {
var newColumnGroups = [];
for (var i = 0; i < columnGroups.length; ++i) {
newColumnGroups[i] = cloneWithProps(
columnGroups[i],
{
cellRenderer: columnGroups[i].props.groupHeaderRenderer || renderToString,
dataKey: i,
children: undefined,
columnData: columnGroups[i].props.columnGroupData,
isHeaderCell: true,
}
);
}
return newColumnGroups;
},
_createHeadColumns(/*array*/ columns) /*array*/ {
var headColumns = [];
for (var i = 0; i < columns.length; ++i) {
var columnProps = columns[i].props;
headColumns.push(cloneWithProps(
columns[i],
{
cellRenderer: columnProps.headerRenderer || renderToString,
columnData: columnProps.columnData,
dataKey: columnProps.dataKey,
isHeaderCell: true,
label: columnProps.label,
}
));
}
return headColumns;
},
_createFootColumns(/*array*/ columns) /*array*/ {
var footColumns = [];
for (var i = 0; i < columns.length; ++i) {
var columnProps = columns[i].props;
footColumns.push(cloneWithProps(
columns[i],
{
cellRenderer: columnProps.footerRenderer || renderToString,
columnData: columnProps.columnData,
dataKey: columnProps.dataKey,
isFooterCell: true,
}
));
}
return footColumns;
},
_getHeadData(/*array*/ columns) /*object*/ {
var headData = {};
for (var i = 0; i < columns.length; ++i) {
var columnProps = columns[i].props;
if (this.props.headerDataGetter) {
headData[columnProps.dataKey] =
this.props.headerDataGetter(columnProps.dataKey);
} else {
headData[columnProps.dataKey] = columnProps.label || '';
}
}
return headData;
},
_getGroupHeaderData(/*array*/ columnGroups) /*array*/ {
var groupHeaderData = [];
for (var i = 0; i < columnGroups.length; ++i) {
groupHeaderData[i] = columnGroups[i].props.label || '';
}
return groupHeaderData;
},
_splitColumnTypes(/*array*/ columns) /*object*/ {
var fixedColumns = [];
var scrollableColumns = [];
for (var i = 0; i < columns.length; ++i) {
if (columns[i].props.fixed) {
fixedColumns.push(columns[i]);
} else {
scrollableColumns.push(columns[i]);
}
}
return {
fixed: fixedColumns,
scrollable: scrollableColumns,
};
},
_getHeaderScrollHeight(scrollY) {
var props = this.props;
var useMaxHeight = props.height === undefined;
var height = useMaxHeight ? props.maxHeight : props.height;
var totalHeightReserved = props.footerHeight + props.headerHeight;
var bodyHeight = height - totalHeightReserved;
if (props.groupHeaderScrollsOut) {
return bodyHeight - Math.max(props.groupHeaderHeight - scrollY, 0);
} else {
return bodyHeight - props.groupHeaderHeight;
}
},
_onWheel(/*number*/ deltaX, /*number*/ deltaY) {
if (this.isMounted()) {
var x = this.state.scrollX;
// JLR: allow use of onWheel property, preventing where appropriate
if (this.props.onWheel) {
var result = this.props.onWheel(this.state, deltaX, deltaY);
if (!result) return;
}
if (Math.abs(deltaY) > Math.abs(deltaX) &&
this.props.overflowY !== 'hidden') {
var scrollState = this._scrollHelper.scrollBy(Math.round(deltaY));
this.setState({
firstRowIndex: scrollState.index,
firstRowOffset: scrollState.offset,
scrollY: scrollState.position,
bodyHeight: this._getHeaderScrollHeight(scrollState.position),
groupHeaderHeight: this.props.groupHeaderScrollsOut
? Math.max(this.props.groupHeaderHeight - scrollState.position, 0)
: this.props.groupHeaderHeight,
scrollContentHeight: scrollState.contentHeight,
});
} else if (deltaX && this.props.overflowX !== 'hidden') {
x += deltaX;
x = x < 0 ? 0 : x;
x = x > this.state.maxScrollX ? this.state.maxScrollX : x;
this.setState({
scrollX: x,
});
}
this._didScrollStop();
}
},
_onHorizontalScroll(/*number*/ scrollPos) {
if (this.isMounted() && scrollPos !== this.state.scrollX) {
var result = this._doingScroll(scrollPos, this.state.scrollY);
if (!result) return;
this.setState({
scrollX: scrollPos,
});
this._didScrollStop();
}
},
_onVerticalScroll(/*number*/ scrollPos) {
if (this.isMounted() && scrollPos !== this.state.scrollY) {
var result = this._doingScroll(this.state.scrollX, scrollPos);
if (!result) return;
var scrollState = this._scrollHelper.scrollTo(Math.round(scrollPos));
this.setState({
firstRowIndex: scrollState.index,
firstRowOffset: scrollState.offset,
scrollY: scrollState.position,
scrollContentHeight: scrollState.contentHeight,
bodyHeight: this._getHeaderScrollHeight(scrollState.position),
groupHeaderHeight: this.props.groupHeaderScrollsOut
? Math.max(this.props.groupHeaderHeight - scrollState.position, 0)
: this.props.groupHeaderHeight,
});
this._didScrollStop();
}
},
_handleTouchScroll(scrollX, scrollY) {
if (this.isMounted() && scrollX !== this.state.scrollX) {
this.setState({
scrollX: scrollX,
});
}
if (this.isMounted() && scrollY !== this.state.scrollY) {
var scrollState = this._scrollHelper.scrollTo(Math.round(scrollY));
this.setState({
firstRowIndex: scrollState.index,
firstRowOffset: scrollState.offset,
scrollY: scrollState.position,
scrollContentHeight: scrollState.contentHeight,
bodyHeight: this._getHeaderScrollHeight(scrollState.position),
groupHeaderHeight: this.props.groupHeaderScrollsOut
? Math.max(this.props.groupHeaderHeight - scrollState.position, 0)
: this.props.groupHeaderHeight,
});
}
},
_doingScroll(/*number*/scrollX, /*number*/scrollY) {
if (this.isMounted()) {
if (this.props.onScroll) {
return this.props.onScroll(scrollX, scrollY);
}
}
return true;
},
_didScrollStop() {
if (this.isMounted()) {
if (this.props.onScrollEnd) {
this.props.onScrollEnd(this.state.scrollX, this.state.scrollY);
}
}
}
});
var HorizontalScrollbar = React.createClass({
mixins: [ReactComponentWithPureRenderMixin],
propTypes: {
contentSize: PropTypes.number.isRequired,
offset: PropTypes.number.isRequired,
onScroll: PropTypes.func.isRequired,
position: PropTypes.number.isRequired,
size: PropTypes.number.isRequired,
},
render() /*object*/ {
var outerContainerStyle = {
height: Scrollbar.SIZE,
width: this.props.size,
};
var innerContainerStyle = {
height: Scrollbar.SIZE,
position: 'absolute',
width: this.props.size,
};
translateDOMPositionXY(
innerContainerStyle,
0,
this.props.offset
);
return (
<div
className={cx('fixedDataTable/horizontalScrollbar')}
style={outerContainerStyle}>
<div style={innerContainerStyle}>
<Scrollbar
{...this.props}
isOpaque={true}
orientation="horizontal"
offset={undefined}
/>
</div>
</div>
);
},
});
module.exports = FixedDataTable;
| src/FixedDataTable.react.js | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule FixedDataTable.react
* @typechecks
*/
/* jslint bitwise: true */
var FixedDataTableHelper = require('FixedDataTableHelper');
var Locale = require('Locale');
var React = require('React');
var ReactComponentWithPureRenderMixin = require('ReactComponentWithPureRenderMixin');
var ReactWheelHandler = require('ReactWheelHandler');
var Scrollbar = require('Scrollbar.react');
var FixedDataTableBufferedRows = require('FixedDataTableBufferedRows.react');
var FixedDataTableColumnResizeHandle = require('FixedDataTableColumnResizeHandle.react');
var FixedDataTableRow = require('FixedDataTableRow.react');
var FixedDataTableScrollHelper = require('FixedDataTableScrollHelper');
var FixedDataTableWidthHelper = require('FixedDataTableWidthHelper');
var cloneWithProps = require('cloneWithProps');
var cx = require('cx');
var debounceCore = require('debounceCore');
var emptyFunction = require('emptyFunction');
var invariant = require('invariant');
var shallowEqual = require('shallowEqual');
var translateDOMPositionXY = require('translateDOMPositionXY');
var PropTypes = React.PropTypes;
var ReactChildren = React.Children;
var renderToString = FixedDataTableHelper.renderToString;
var EMPTY_OBJECT = {};
var COLUMN_SETTING_NAMES = [
'bodyFixedColumns',
'bodyScrollableColumns',
'headFixedColumns',
'headScrollableColumns',
'footFixedColumns',
'footScrollableColumns',
];
/**
* Data grid component with fixed or scrollable header and columns.
*
* The layout of the data table is as follow:
*
* ```
* +---------------------------------------------------+
* | Fixed Column Group | Scrollable Column Group |
* | Header | Header |
* | | |
* +---------------------------------------------------+
* | | |
* | Fixed Header Columns | Scrollable Header Columns |
* | | |
* +-----------------------+---------------------------+
* | | |
* | Fixed Body Columns | Scrollable Body Columns |
* | | |
* +-----------------------+---------------------------+
* | | |
* | Fixed Footer Columns | Scrollable Footer Columns |
* | | |
* +-----------------------+---------------------------+
* ```
*
* - Fixed Column Group Header: These are the headers for a group
* of columns if included in the table that do not scroll
* vertically or horizontally.
*
* - Scrollable Column Group Header: The header for a group of columns
* that do not move while scrolling vertically, but move horizontally
* with the horizontal scrolling.
*
* - Fixed Header Columns: The header columns that do not move while scrolling
* vertically or horizontally.
*
* - Scrollable Header Columns: The header columns that do not move
* while scrolling vertically, but move horizontally with the horizontal
* scrolling.
*
* - Fixed Body Columns: The body columns that do not move while scrolling
* horizontally, but move vertically with the vertical scrolling.
*
* - Scrollable Body Columns: The body columns that move while scrolling
* vertically or horizontally.
*/
var FixedDataTable = React.createClass({
propTypes: {
/**
* Pixel width of table. If all rows do not fit,
* a horizontal scrollbar will appear.
*/
width: PropTypes.number.isRequired,
/**
* Pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
height: PropTypes.number,
/**
* Maximum pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
maxHeight: PropTypes.number,
/**
* Pixel height of table's owner, This is used to make sure the footer
* and scrollbar of the table are visible when current space for table in
* view is smaller than final height of table. It allows to avoid resizing
* and reflowing table whan it is moving in the view.
*
* This is used if `ownerHeight < height`.
*/
ownerHeight: PropTypes.number,
overflowX: PropTypes.oneOf(['hidden', 'auto']),
overflowY: PropTypes.oneOf(['hidden', 'auto']),
/**
* Number of rows in the table.
*/
rowsCount: PropTypes.number.isRequired,
/**
* Pixel height of rows unless rowHeightGetter is specified and returns
* different value.
*/
rowHeight: PropTypes.number.isRequired,
/**
* If specified, `rowHeightGetter(index)` is called for each row and the
* returned value overrides rowHeight for particular row.
*/
rowHeightGetter: PropTypes.func,
/**
* To get rows to display in table, `rowGetter(index)`
* is called. rowGetter should be smart enough to handle async
* fetching of data and returning temporary objects
* while data is being fetched.
*/
rowGetter: PropTypes.func.isRequired,
/**
* To get any additional css classes that should be added to a row,
* `rowClassNameGetter(index)` is called.
*/
rowClassNameGetter: PropTypes.func,
/**
* Pixel height of the column group header.
*/
groupHeaderHeight: PropTypes.number,
/**
* Pixel height of header.
*/
headerHeight: PropTypes.number.isRequired,
/**
* Function that is called to get the data for the header row.
*/
headerDataGetter: PropTypes.func,
/**
* Pixel height of footer.
*/
footerHeight: PropTypes.number,
/**
* Data that will be passed to footer cell renderers.
*/
footerData: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array,
]),
/**
* Value of horizontal scroll.
*/
scrollLeft: PropTypes.number,
/**
* Index of column to scroll to.
*/
scrollToColumn: PropTypes.number,
/**
* Value of vertical scroll.
*/
scrollTop: PropTypes.number,
/**
* Index of row to scroll to.
*/
scrollToRow: PropTypes.number,
/**
* Callback that is called when scrolling ends or stops with new horizontal
* and vertical scroll values.
*/
onScrollEnd: PropTypes.func,
/**
* Callback that is called when `rowHeightGetter` returns a different height
* for a row than the `rowHeight` prop. This is necessary because initially
* table estimates heights of some parts of the content.
*/
onContentHeightChange: PropTypes.func,
/**
* Callback that is called when a row is clicked.
*/
onRowClick: PropTypes.func,
/**
* Callback that is called when mouse down event happens above a row.
*/
onRowMouseDown: PropTypes.func,
/**
* Callback that is called when the mouse enters a row.
*/
onRowMouseEnter: PropTypes.func,
/**
* Callback that is called when resizer has been released
* and column needs to be updated.
*/
onColumnResizeEndCallback: PropTypes.func,
/**
* Whether a column is currently being resized.
*/
isColumnResizing: PropTypes.bool,
},
getDefaultProps() /*object*/ {
return {
footerHeight: 0,
groupHeaderHeight: 0,
headerHeight: 0,
scrollLeft: 0,
scrollTop: 0,
};
},
getInitialState() /*object*/ {
var props = this.props;
var viewportHeight = props.height -
props.headerHeight -
props.groupHeaderHeight -
props.footerHeight;
this._scrollHelper = new FixedDataTableScrollHelper(
props.rowsCount,
props.rowHeight,
viewportHeight,
props.rowHeightGetter,
props.groupHeaderScrollsOut ? props.groupHeaderHeight : 0
);
if (props.scrollTop) {
this._scrollHelper.scrollTo(props.scrollTop);
}
this._didScrollStop = debounceCore(this._didScrollStop, 160, this);
this.tScroller = new Scroller(this._handleTouchScroll);
return this._calculateState(this.props);
},
componentWillMount() {
var scrollToRow = this.props.scrollToRow;
if (scrollToRow !== undefined && scrollToRow !== null) {
this._rowToScrollTo = scrollToRow;
}
var scrollToColumn = this.props.scrollToColumn;
if (scrollToColumn !== undefined && scrollToColumn !== null) {
this._columnToScrollTo = scrollToColumn;
}
this._wheelHandler = new ReactWheelHandler(
this._onWheel,
this.props.overflowX !== 'hidden', // Should handle horizontal scroll
this.props.overflowY !== 'hidden' // Should handle vertical scroll
);
},
_handleTouchStart(e) {
this.tScroller.doTouchStart(e.touches, e.timeStamp)
e.preventDefault()
},
_handleTouchMove(e) {
this.tScroller.doTouchMove(e.touches, e.timeStamp, e.scale)
e.preventDefault()
},
_handleTouchEnd(e) {
this.tScroller.doTouchEnd(e.timeStamp)
e.preventDefault()
},
_reportContentHeight() {
var scrollContentHeight = this.state.scrollContentHeight;
var reservedHeight = this.state.reservedHeight;
var requiredHeight = scrollContentHeight + reservedHeight;
var contentHeight;
if (this.state.height > requiredHeight && this.props.ownerHeight) {
contentHeight = Math.max(requiredHeight, this.props.ownerHeight);
} else {
var maxScrollY = scrollContentHeight - this.state.bodyHeight;
contentHeight = this.props.height + maxScrollY;
}
if (contentHeight !== this._contentHeight &&
this.props.onContentHeightChange) {
this.props.onContentHeightChange(contentHeight);
}
this._contentHeight = contentHeight;
},
componentDidMount() {
this._reportContentHeight();
},
componentWillReceiveProps(/*object*/ nextProps) {
var scrollToRow = nextProps.scrollToRow;
if (scrollToRow !== undefined && scrollToRow !== null) {
this._rowToScrollTo = scrollToRow;
}
var scrollToColumn = nextProps.scrollToColumn;
if (scrollToColumn !== undefined && scrollToColumn !== null) {
this._columnToScrollTo = scrollToColumn;
}
var newOverflowX = nextProps.overflowX;
var newOverflowY = nextProps.overflowY;
if (newOverflowX !== this.props.overflowX ||
newOverflowY !== this.props.overflowY) {
this._wheelHandler = new ReactWheelHandler(
this._onWheel,
newOverflowX !== 'hidden', // Should handle horizontal scroll
newOverflowY !== 'hidden' // Should handle vertical scroll
);
}
this.setState(this._calculateState(nextProps, this.state));
},
componentDidUpdate() {
this._reportContentHeight();
},
render() /*object*/ {
var state = this.state;
var props = this.props;
var groupHeader;
if (state.useGroupHeader) {
groupHeader = (
<FixedDataTableRow
key="group_header"
className={cx('public/fixedDataTable/header')}
data={state.groupHeaderData}
width={state.width}
height={state.groupHeaderHeight}
index={0}
zIndex={1}
offsetTop={0}
scrollLeft={state.scrollX}
fixedColumns={state.groupHeaderFixedColumns}
scrollableColumns={state.groupHeaderScrollableColumns}
/>
);
}
var maxScrollY = this.state.scrollContentHeight - this.state.bodyHeight;
var showScrollbarX = state.maxScrollX > 0 && state.overflowX !== 'hidden';
var showScrollbarY = maxScrollY > 0 && state.overflowY !== 'hidden';
var scrollbarXHeight = showScrollbarX ? Scrollbar.SIZE : 0;
var scrollbarYHeight = state.height - scrollbarXHeight;
var headerOffsetTop = state.useGroupHeader ? state.groupHeaderHeight : 0;
var bodyOffsetTop = headerOffsetTop + state.headerHeight;
var bottomSectionOffset = 0;
var footOffsetTop = bodyOffsetTop + state.bodyHeight;
var rowsContainerHeight = footOffsetTop + state.footerHeight;
if (props.ownerHeight !== undefined && props.ownerHeight < props.height) {
bottomSectionOffset = props.ownerHeight - props.height;
footOffsetTop = Math.min(
footOffsetTop,
scrollbarYHeight + bottomSectionOffset - state.footerHeight
);
scrollbarYHeight = props.ownerHeight - scrollbarXHeight;
}
var verticalScrollbar;
if (showScrollbarY) {
verticalScrollbar =
<Scrollbar
size={scrollbarYHeight}
contentSize={scrollbarYHeight + maxScrollY}
onScroll={this._onVerticalScroll}
position={state.scrollY}
/>;
}
var horizontalScrollbar;
if (showScrollbarX) {
var scrollbarYWidth = showScrollbarY ? Scrollbar.SIZE : 0;
var scrollbarXWidth = state.width - scrollbarYWidth;
horizontalScrollbar =
<HorizontalScrollbar
contentSize={scrollbarXWidth + state.maxScrollX}
offset={bottomSectionOffset}
onScroll={this._onHorizontalScroll}
position={state.scrollX}
size={scrollbarXWidth}
/>;
}
var dragKnob =
<FixedDataTableColumnResizeHandle
height={state.height}
initialWidth={state.columnResizingData.width || 0}
minWidth={state.columnResizingData.minWidth || 0}
maxWidth={state.columnResizingData.maxWidth || Number.MAX_VALUE}
visible={!!state.isColumnResizing}
leftOffset={state.columnResizingData.left || 0}
knobHeight={state.headerHeight}
initialEvent={state.columnResizingData.initialEvent}
onColumnResizeEnd={props.onColumnResizeEndCallback}
columnKey={state.columnResizingData.key}
/>;
var footer = null;
if (state.footerHeight) {
footer =
<FixedDataTableRow
key="footer"
className={cx('public/fixedDataTable/footer')}
data={state.footerData}
fixedColumns={state.footFixedColumns}
height={state.footerHeight}
index={-1}
zIndex={1}
offsetTop={footOffsetTop}
scrollableColumns={state.footScrollableColumns}
scrollLeft={state.scrollX}
width={state.width}
/>;
}
var rows = this._renderRows(bodyOffsetTop);
var header =
<FixedDataTableRow
key="header"
className={cx('public/fixedDataTable/header')}
data={state.headData}
width={state.width}
height={state.headerHeight}
index={-1}
zIndex={1}
offsetTop={headerOffsetTop}
scrollLeft={state.scrollX}
fixedColumns={state.headFixedColumns}
scrollableColumns={state.headScrollableColumns}
onColumnResize={this._onColumnResize}
/>;
var shadow;
if (state.scrollY) {
shadow =
<div
className={cx('fixedDataTable/shadow')}
style={{top: bodyOffsetTop}}
/>;
}
return (
<div
className={cx('public/fixedDataTable/main')}
onWheel={this._wheelHandler.onWheel}
onTouchStart={this._handleTouchStart}
onTouchMove={this._handleTouchMove}
onTouchEnd={this._handleTouchEnd}
style={{height: state.height, width: state.width}}>
<div
className={cx('fixedDataTable/rowsContainer')}
style={{height: rowsContainerHeight, width: state.width}}>
{dragKnob}
{groupHeader}
{header}
{rows}
{footer}
{shadow}
</div>
{verticalScrollbar}
{horizontalScrollbar}
</div>
);
},
_renderRows(/*number*/ offsetTop) /*object*/ {
var state = this.state;
return (
<FixedDataTableBufferedRows
defaultRowHeight={state.rowHeight}
firstRowIndex={state.firstRowIndex}
firstRowOffset={state.firstRowOffset}
fixedColumns={state.bodyFixedColumns}
height={state.bodyHeight}
offsetTop={offsetTop}
onRowClick={state.onRowClick}
onRowMouseDown={state.onRowMouseDown}
onRowMouseEnter={state.onRowMouseEnter}
rowClassNameGetter={state.rowClassNameGetter}
rowsCount={state.rowsCount}
rowGetter={state.rowGetter}
rowHeightGetter={state.rowHeightGetter}
scrollLeft={state.scrollX}
scrollableColumns={state.bodyScrollableColumns}
showLastRowBorder={!state.footerHeight}
width={state.width}
/>
);
},
/**
* This is called when a cell that is in the header of a column has its
* resizer knob clicked on. It displays the resizer and puts in the correct
* location on the table.
*/
_onColumnResize(
/*number*/ combinedWidth,
/*number*/ leftOffset,
/*number*/ cellWidth,
/*?number*/ cellMinWidth,
/*?number*/ cellMaxWidth,
/*number|string*/ columnKey,
/*object*/ event) {
if (Locale.isRTL()) {
leftOffset = -leftOffset;
}
this.setState({
isColumnResizing: true,
columnResizingData: {
left: leftOffset + combinedWidth - cellWidth,
width: cellWidth,
minWidth: cellMinWidth,
maxWidth: cellMaxWidth,
initialEvent: {
clientX: event.clientX,
clientY: event.clientY,
preventDefault: emptyFunction
},
key: columnKey
}
});
},
_populateColumnsAndColumnData(
/*array*/ columns,
/*?array*/ columnGroups
) /*object*/ {
var columnInfo = {};
var bodyColumnTypes = this._splitColumnTypes(columns);
columnInfo.bodyFixedColumns = bodyColumnTypes.fixed;
columnInfo.bodyScrollableColumns = bodyColumnTypes.scrollable;
columnInfo.headData = this._getHeadData(columns);
var headColumnTypes = this._splitColumnTypes(
this._createHeadColumns(columns)
);
columnInfo.headFixedColumns = headColumnTypes.fixed;
columnInfo.headScrollableColumns = headColumnTypes.scrollable;
var footColumnTypes = this._splitColumnTypes(
this._createFootColumns(columns)
);
columnInfo.footFixedColumns = footColumnTypes.fixed;
columnInfo.footScrollableColumns = footColumnTypes.scrollable;
if (columnGroups) {
columnInfo.groupHeaderData = this._getGroupHeaderData(columnGroups);
columnGroups = this._createGroupHeaderColumns(columnGroups);
var groupHeaderColumnTypes = this._splitColumnTypes(columnGroups);
columnInfo.groupHeaderFixedColumns = groupHeaderColumnTypes.fixed;
columnInfo.groupHeaderScrollableColumns =
groupHeaderColumnTypes.scrollable;
}
return columnInfo;
},
_calculateState(/*object*/ props, /*?object*/ oldState) /*object*/ {
invariant(
props.height !== undefined || props.maxHeight !== undefined,
'You must set either a height or a maxHeight'
);
var firstRowIndex = (oldState && oldState.firstRowIndex) || 0;
var firstRowOffset = (oldState && oldState.firstRowOffset) || 0;
var scrollX, scrollY;
if (oldState && props.overflowX !== 'hidden') {
scrollX = oldState.scrollX;
} else {
scrollX = props.scrollLeft;
}
if (oldState && props.overflowY !== 'hidden') {
scrollY = oldState.scrollY;
} else {
scrollState = this._scrollHelper.scrollTo(props.scrollTop);
firstRowIndex = scrollState.index;
firstRowOffset = scrollState.offset;
scrollY = scrollState.position;
}
if (this._rowToScrollTo !== undefined) {
scrollState =
this._scrollHelper.scrollRowIntoView(this._rowToScrollTo);
firstRowIndex = scrollState.index;
firstRowOffset = scrollState.offset;
scrollY = scrollState.position;
delete this._rowToScrollTo;
}
if (oldState && props.rowsCount !== oldState.rowsCount) {
// Number of rows changed, try to scroll to the row from before the
// change
var viewportHeight = props.height -
props.headerHeight -
props.footerHeight -
props.groupHeaderHeight;
this._scrollHelper = new FixedDataTableScrollHelper(
props.rowsCount,
props.rowHeight,
viewportHeight,
props.rowHeightGetter
);
var scrollState =
this._scrollHelper.scrollToRow(firstRowIndex, firstRowOffset);
firstRowIndex = scrollState.index;
firstRowOffset = scrollState.offset;
scrollY = scrollState.position;
} else if (oldState && props.rowHeightGetter !== oldState.rowHeightGetter) {
this._scrollHelper.setRowHeightGetter(props.rowHeightGetter);
}
var columnResizingData;
if (props.isColumnResizing) {
columnResizingData = oldState && oldState.columnResizingData;
} else {
columnResizingData = EMPTY_OBJECT;
}
var children = [];
ReactChildren.forEach(props.children, (child, index) => {
if (child == null) {
return;
}
invariant(
child.type.__TableColumnGroup__ ||
child.type.__TableColumn__,
'child type should be <FixedDataTableColumn /> or ' +
'<FixedDataTableColumnGroup />'
);
children.push(child);
});
var useGroupHeader = false;
if (children.length && children[0].type.__TableColumnGroup__) {
useGroupHeader = true;
}
var columns;
var columnGroups;
if (useGroupHeader) {
var columnGroupSettings =
FixedDataTableWidthHelper.adjustColumnGroupWidths(
children,
props.width
);
columns = columnGroupSettings.columns;
columnGroups = columnGroupSettings.columnGroups;
} else {
columns = FixedDataTableWidthHelper.adjustColumnWidths(
children,
props.width
);
}
var columnInfo = this._populateColumnsAndColumnData(
columns,
columnGroups
);
if (oldState) {
columnInfo = this._tryReusingColumnSettings(columnInfo, oldState);
}
if (this._columnToScrollTo !== undefined) {
// If selected column is a fixed column, don't scroll
var fixedColumnsCount = columnInfo.bodyFixedColumns.length;
if (this._columnToScrollTo >= fixedColumnsCount) {
var totalFixedColumnsWidth = 0;
var i, column;
for (i = 0; i < columnInfo.bodyFixedColumns.length; ++i) {
column = columnInfo.bodyFixedColumns[i];
totalFixedColumnsWidth += column.props.width;
}
var scrollableColumnIndex = this._columnToScrollTo - fixedColumnsCount;
var previousColumnsWidth = 0;
for (i = 0; i < scrollableColumnIndex; ++i) {
column = columnInfo.bodyScrollableColumns[i];
previousColumnsWidth += column.props.width;
}
var availableScrollWidth = props.width - totalFixedColumnsWidth;
var selectedColumnWidth = columnInfo.bodyScrollableColumns[
this._columnToScrollTo - fixedColumnsCount
].props.width;
var minAcceptableScrollPosition =
previousColumnsWidth + selectedColumnWidth - availableScrollWidth;
if (scrollX < minAcceptableScrollPosition) {
scrollX = minAcceptableScrollPosition;
}
if (scrollX > previousColumnsWidth) {
scrollX = previousColumnsWidth;
}
}
delete this._columnToScrollTo;
}
var useMaxHeight = props.height === undefined;
var height = useMaxHeight ? props.maxHeight : props.height;
var totalHeightReserved = props.footerHeight + props.headerHeight +
props.groupHeaderHeight;
var bodyHeight = height - totalHeightReserved;
var scrollContentHeight = this._scrollHelper.getContentHeight();
var totalHeightNeeded = scrollContentHeight + totalHeightReserved;
var scrollContentWidth =
FixedDataTableWidthHelper.getTotalWidth(columns);
var horizontalScrollbarVisible = scrollContentWidth > props.width &&
props.overflowX !== 'hidden';
if (horizontalScrollbarVisible) {
bodyHeight -= Scrollbar.SIZE;
totalHeightNeeded += Scrollbar.SIZE;
totalHeightReserved += Scrollbar.SIZE;
}
var maxScrollX = Math.max(0, scrollContentWidth - props.width);
var maxScrollY = Math.max(0, scrollContentHeight - bodyHeight);
scrollX = Math.min(scrollX, maxScrollX);
scrollY = Math.min(scrollY, maxScrollY);
this.tScroller.setDimensions(
props.width,
bodyHeight,
scrollContentWidth,
scrollContentHeight
);
if (!maxScrollY) {
// no vertical scrollbar necessary, use the totals we tracked so we
// can shrink-to-fit vertically
if (useMaxHeight) {
height = totalHeightNeeded;
}
bodyHeight = totalHeightNeeded - totalHeightReserved;
}
this._scrollHelper.setViewportHeight(bodyHeight);
bodyHeight = this._getHeaderScrollHeight(scrollY);
// autohiding that shizz
var groupHeaderHeight = props.groupHeaderScrollsOut
? Math.max(props.groupHeaderHeight - scrollY, 0)
: props.groupHeaderHeight;
// The order of elements in this object metters and bringing bodyHeight,
// height or useGroupHeader to the top can break various features
var newState = {
isColumnResizing: oldState && oldState.isColumnResizing,
// isColumnResizing should be overwritten by value from props if
// avaialble
...columnInfo,
...props,
columnResizingData,
firstRowIndex,
firstRowOffset,
horizontalScrollbarVisible,
maxScrollX,
reservedHeight: totalHeightReserved,
scrollContentHeight,
scrollX,
scrollY,
// These properties may overwrite properties defined in
// columnInfo and props
bodyHeight,
height,
useGroupHeader,
groupHeaderHeight,
};
// Both `headData` and `groupHeaderData` are generated by
// `FixedDataTable` will be passed to each header cell to render.
// In order to prevent over-rendering the cells, we do not pass the
// new `headData` or `groupHeaderData`
// if they haven't changed.
if (oldState) {
if (shallowEqual(oldState.headData, newState.headData)) {
newState.headData = oldState.headData;
}
if (shallowEqual(oldState.groupHeaderData, newState.groupHeaderData)) {
newState.groupHeaderData = oldState.groupHeaderData;
}
}
return newState;
},
_tryReusingColumnSettings(
/*object*/ columnInfo,
/*object*/ oldState
) /*object*/ {
COLUMN_SETTING_NAMES.forEach(settingName => {
if (columnInfo[settingName].length === oldState[settingName].length) {
var canReuse = true;
for (var index = 0; index < columnInfo[settingName].length; ++index) {
if (!shallowEqual(
columnInfo[settingName][index].props,
oldState[settingName][index].props
)) {
canReuse = false;
break;
}
}
if (canReuse) {
columnInfo[settingName] = oldState[settingName];
}
}
});
return columnInfo;
},
_createGroupHeaderColumns(/*array*/ columnGroups) /*array*/ {
var newColumnGroups = [];
for (var i = 0; i < columnGroups.length; ++i) {
newColumnGroups[i] = cloneWithProps(
columnGroups[i],
{
cellRenderer: columnGroups[i].props.groupHeaderRenderer || renderToString,
dataKey: i,
children: undefined,
columnData: columnGroups[i].props.columnGroupData,
isHeaderCell: true,
}
);
}
return newColumnGroups;
},
_createHeadColumns(/*array*/ columns) /*array*/ {
var headColumns = [];
for (var i = 0; i < columns.length; ++i) {
var columnProps = columns[i].props;
headColumns.push(cloneWithProps(
columns[i],
{
cellRenderer: columnProps.headerRenderer || renderToString,
columnData: columnProps.columnData,
dataKey: columnProps.dataKey,
isHeaderCell: true,
label: columnProps.label,
}
));
}
return headColumns;
},
_createFootColumns(/*array*/ columns) /*array*/ {
var footColumns = [];
for (var i = 0; i < columns.length; ++i) {
var columnProps = columns[i].props;
footColumns.push(cloneWithProps(
columns[i],
{
cellRenderer: columnProps.footerRenderer || renderToString,
columnData: columnProps.columnData,
dataKey: columnProps.dataKey,
isFooterCell: true,
}
));
}
return footColumns;
},
_getHeadData(/*array*/ columns) /*object*/ {
var headData = {};
for (var i = 0; i < columns.length; ++i) {
var columnProps = columns[i].props;
if (this.props.headerDataGetter) {
headData[columnProps.dataKey] =
this.props.headerDataGetter(columnProps.dataKey);
} else {
headData[columnProps.dataKey] = columnProps.label || '';
}
}
return headData;
},
_getGroupHeaderData(/*array*/ columnGroups) /*array*/ {
var groupHeaderData = [];
for (var i = 0; i < columnGroups.length; ++i) {
groupHeaderData[i] = columnGroups[i].props.label || '';
}
return groupHeaderData;
},
_splitColumnTypes(/*array*/ columns) /*object*/ {
var fixedColumns = [];
var scrollableColumns = [];
for (var i = 0; i < columns.length; ++i) {
if (columns[i].props.fixed) {
fixedColumns.push(columns[i]);
} else {
scrollableColumns.push(columns[i]);
}
}
return {
fixed: fixedColumns,
scrollable: scrollableColumns,
};
},
_getHeaderScrollHeight(scrollY) {
var props = this.props;
var useMaxHeight = props.height === undefined;
var height = useMaxHeight ? props.maxHeight : props.height;
var totalHeightReserved = props.footerHeight + props.headerHeight;
var bodyHeight = height - totalHeightReserved;
if (props.groupHeaderScrollsOut) {
return bodyHeight - Math.max(props.groupHeaderHeight - scrollY, 0);
} else {
return bodyHeight - props.groupHeaderHeight;
}
},
_onWheel(/*number*/ deltaX, /*number*/ deltaY) {
if (this.isMounted()) {
var x = this.state.scrollX;
// JLR: allow use of onWheel property, preventing where appropriate
if (this.props.onWheel) {
var result = this.props.onWheel(this.state, deltaX, deltaY);
if (!result) return;
}
if (Math.abs(deltaY) > Math.abs(deltaX) &&
this.props.overflowY !== 'hidden') {
var scrollState = this._scrollHelper.scrollBy(Math.round(deltaY));
this.setState({
firstRowIndex: scrollState.index,
firstRowOffset: scrollState.offset,
scrollY: scrollState.position,
bodyHeight: this._getHeaderScrollHeight(scrollState.position),
groupHeaderHeight: this.props.groupHeaderScrollsOut
? Math.max(this.props.groupHeaderHeight - scrollState.position, 0)
: this.props.groupHeaderHeight,
scrollContentHeight: scrollState.contentHeight,
});
} else if (deltaX && this.props.overflowX !== 'hidden') {
x += deltaX;
x = x < 0 ? 0 : x;
x = x > this.state.maxScrollX ? this.state.maxScrollX : x;
this.setState({
scrollX: x,
});
}
this._didScrollStop();
}
},
_onHorizontalScroll(/*number*/ scrollPos) {
if (this.isMounted() && scrollPos !== this.state.scrollX) {
var result = this._doingScroll(scrollPos, this.state.scrollY);
if (!result) return;
this.setState({
scrollX: scrollPos,
});
this._didScrollStop();
}
},
_onVerticalScroll(/*number*/ scrollPos) {
if (this.isMounted() && scrollPos !== this.state.scrollY) {
var result = this._doingScroll(this.state.scrollX, scrollPos);
if (!result) return;
var scrollState = this._scrollHelper.scrollTo(Math.round(scrollPos));
this.setState({
firstRowIndex: scrollState.index,
firstRowOffset: scrollState.offset,
scrollY: scrollState.position,
scrollContentHeight: scrollState.contentHeight,
bodyHeight: this._getHeaderScrollHeight(scrollState.position),
groupHeaderHeight: this.props.groupHeaderScrollsOut
? Math.max(this.props.groupHeaderHeight - scrollState.position, 0)
: this.props.groupHeaderHeight,
});
this._didScrollStop();
}
},
_handleTouchScroll(scrollX, scrollY) {
if (this.isMounted() && scrollX !== this.state.scrollX) {
this.setState({
scrollX: scrollX,
});
}
if (this.isMounted() && scrollY !== this.state.scrollY) {
var scrollState = this._scrollHelper.scrollTo(Math.round(scrollY));
this.setState({
firstRowIndex: scrollState.index,
firstRowOffset: scrollState.offset,
scrollY: scrollState.position,
scrollContentHeight: scrollState.contentHeight,
bodyHeight: this._getHeaderScrollHeight(scrollState.position),
groupHeaderHeight: this.props.groupHeaderScrollsOut
? Math.max(this.props.groupHeaderHeight - scrollState.position, 0)
: this.props.groupHeaderHeight,
});
}
},
_doingScroll(/*number*/scrollX, /*number*/scrollY) {
if (this.isMounted()) {
if (this.props.onScroll) {
return this.props.onScroll(scrollX, scrollY);
}
}
return true;
},
_didScrollStop() {
if (this.isMounted()) {
if (this.props.onScrollEnd) {
this.props.onScrollEnd(this.state.scrollX, this.state.scrollY);
}
}
}
});
var HorizontalScrollbar = React.createClass({
mixins: [ReactComponentWithPureRenderMixin],
propTypes: {
contentSize: PropTypes.number.isRequired,
offset: PropTypes.number.isRequired,
onScroll: PropTypes.func.isRequired,
position: PropTypes.number.isRequired,
size: PropTypes.number.isRequired,
},
render() /*object*/ {
var outerContainerStyle = {
height: Scrollbar.SIZE,
width: this.props.size,
};
var innerContainerStyle = {
height: Scrollbar.SIZE,
position: 'absolute',
width: this.props.size,
};
translateDOMPositionXY(
innerContainerStyle,
0,
this.props.offset
);
return (
<div
className={cx('fixedDataTable/horizontalScrollbar')}
style={outerContainerStyle}>
<div style={innerContainerStyle}>
<Scrollbar
{...this.props}
isOpaque={true}
orientation="horizontal"
offset={undefined}
/>
</div>
</div>
);
},
});
module.exports = FixedDataTable;
| Added scrollsOut to reinstantiation of ScrollHelper.
| src/FixedDataTable.react.js | Added scrollsOut to reinstantiation of ScrollHelper. | <ide><path>rc/FixedDataTable.react.js
<ide> props.rowsCount,
<ide> props.rowHeight,
<ide> viewportHeight,
<del> props.rowHeightGetter
<add> props.rowHeightGetter,
<add> props.groupHeaderScrollsOut ? props.groupHeaderHeight : 0
<ide> );
<ide> var scrollState =
<ide> this._scrollHelper.scrollToRow(firstRowIndex, firstRowOffset);
<ide> } else if (oldState && props.rowHeightGetter !== oldState.rowHeightGetter) {
<ide> this._scrollHelper.setRowHeightGetter(props.rowHeightGetter);
<ide> }
<add>
<ide>
<ide> var columnResizingData;
<ide> if (props.isColumnResizing) {
<ide> var scrollContentWidth =
<ide> FixedDataTableWidthHelper.getTotalWidth(columns);
<ide>
<add>
<ide> var horizontalScrollbarVisible = scrollContentWidth > props.width &&
<ide> props.overflowX !== 'hidden';
<ide>
<ide> useGroupHeader,
<ide> groupHeaderHeight,
<ide> };
<add>
<ide>
<ide> // Both `headData` and `groupHeaderData` are generated by
<ide> // `FixedDataTable` will be passed to each header cell to render. |
|
Java | apache-2.0 | c2166ebafcf522e4f414f0019b186b4a5fe007b7 | 0 | aduprat/james,chibenwa/james,rouazana/james,chibenwa/james,chibenwa/james,aduprat/james,rouazana/james,rouazana/james,chibenwa/james,rouazana/james,aduprat/james,aduprat/james | /*
* 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.james.jcr;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Message.RecipientType;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeMessage;
import org.apache.jackrabbit.util.Text;
/**
* JavaBean that stores messages to a JCR content repository.
* <p>
* After instantiating this bean you should use the
* {@link #setParentNode(Node)} method to specify the root node under
* which all messages should be stored. Then you can call
* {@link #storeMessage(Message)} to store messages in the repository.
* <p>
* The created content structure below the given parent node consists
* of a date based .../year/month/day tree structure, below which the actual
* messages are stored. A stored message consists of an nt:file node whose
* name is based on the subject of the message. The jcr:content child of the
* nt:file node contains the MIME structure and all relevant headers of the
* message. Note that the original message source is <em>not</em> stored,
* which means that some of the message information will be lost.
* <p>
* The messages are stored using the session associated with the specified
* parent node. No locking or synchronization is performed, and it is expected
* that only one thread writing to the message subtree at any given moment.
* You should use JCR locking or some other explicit synchronization mechanism
* if you want to have concurrent writes to the message subtree.
*/
public class JCRStoreBean {
/**
* Parent node where the messages are stored.
*/
private Node parent;
public void setParentNode(Node parent) {
this.parent = parent;
}
/**
* Stores the given mail message to the content repository.
*
* @param message mail message
* @throws MessagingException if the message could not be read
* @throws RepositoryException if the message could not be saved
*/
public void storeMessage(Message message)
throws MessagingException, RepositoryException {
try {
Date date = message.getSentDate();
Node year = getOrAddNode(parent, format("yyyy", date), "nt:folder");
Node month = getOrAddNode(year, format("mm", date), "nt:folder");
Node day = getOrAddNode(month, format("dd", date), "nt:folder");
Node node = createNode(day, getMessageName(message), "nt:file");
importEntity(message, node);
parent.save();
} catch (IOException e) {
throw new MessagingException("Could not read message", e);
}
}
/**
* Import the given entity to the given JCR node.
*
* @param entity the source entity
* @param parent the target node
* @throws MessagingException if the message could not be read
* @throws RepositoryException if the message could not be written
* @throws IOException if the message could not be read
*/
private void importEntity(Part entity, Node parent)
throws MessagingException, RepositoryException, IOException {
Node node = parent.addNode("jcr:content", "nt:unstructured");
setProperty(node, "description", entity.getDescription());
setProperty(node, "disposition", entity.getDisposition());
setProperty(node, "filename", entity.getFileName());
if (entity instanceof MimeMessage) {
MimeMessage mime = (MimeMessage) entity;
setProperty(node, "subject", mime.getSubject());
setProperty(node, "message-id", mime.getMessageID());
setProperty(node, "content-id", mime.getContentID());
setProperty(node, "content-md5", mime.getContentMD5());
setProperty(node, "language", mime.getContentLanguage());
setProperty(node, "sent", mime.getSentDate());
setProperty(node, "received", mime.getReceivedDate());
setProperty(node, "from", mime.getFrom());
setProperty(node, "to", mime.getRecipients(RecipientType.TO));
setProperty(node, "cc", mime.getRecipients(RecipientType.CC));
setProperty(node, "bcc", mime.getRecipients(RecipientType.BCC));
setProperty(node, "reply-to", mime.getReplyTo());
setProperty(node, "sender", mime.getSender());
}
Object content = entity.getContent();
ContentType type = getContentType(entity);
node.setProperty("jcr:mimeType", type.getBaseType());
if (content instanceof Multipart) {
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart part = multipart.getBodyPart(i);
Node child;
if (part.getFileName() != null) {
child = createNode(node, part.getFileName(), "nt:file");
} else {
child = createNode(node, "part", "nt:unstructured");
}
importEntity(part, child);
}
} else if (content instanceof String) {
byte[] bytes = ((String) content).getBytes("UTF-8");
node.setProperty("jcr:encoding", "UTF-8");
node.setProperty("jcr:data", new ByteArrayInputStream(bytes));
} else if (content instanceof InputStream) {
setProperty(
node, "jcr:encoding", type.getParameter("encoding"));
node.setProperty("jcr:data", (InputStream) content);
} else {
node.setProperty("jcr:data", entity.getInputStream());
}
}
/**
* Formats the given date using the given {@link SimpleDateFormat}
* format string.
*
* @param format format string
* @param date date to be formatted
* @return formatted date
*/
private String format(String format, Date date) {
return new SimpleDateFormat(format).format(date);
}
/**
* Suggests a name for the node where the given message will be stored.
*
* @param message mail message
* @return suggested name
* @throws MessagingException if an error occurs
*/
private String getMessageName(Message message)
throws MessagingException {
String name = message.getSubject();
if (name == null) {
name = "unnamed";
} else {
name = name.replaceAll("[^A-Za-z0-9 ]", "").trim();
if (name.length() == 0) {
name = "unnamed";
}
}
return name;
}
/**
* Returns the named child node of the given parent. If the child node
* does not exist, it is automatically created with the given node type.
* The created node is not saved by this method.
*
* @param parent parent node
* @param name name of the child node
* @param type type of the child node
* @return child node
* @throws RepositoryException if the child node could not be accessed
*/
private Node getOrAddNode(Node parent, String name, String type)
throws RepositoryException {
try {
return parent.getNode(name);
} catch (PathNotFoundException e) {
return parent.addNode(name, type);
}
}
/**
* Creates a new node with a name that resembles the given suggestion.
* The created node is not saved by this method.
*
* @param parent parent node
* @param name suggested name
* @param type node type
* @return created node
* @throws RepositoryException if an error occurs
*/
private Node createNode(Node parent, String name, String type)
throws RepositoryException {
String original = name;
name = Text.escapeIllegalJcrChars(name);
for (int i = 2; parent.hasNode(name); i++) {
name = Text.escapeIllegalJcrChars(original + i);
}
return parent.addNode(name, type);
}
/**
* Returns the content type of the given message entity. Returns
* the default "text/plain" content type if a content type is not
* available. Returns "application/octet-stream" if an error occurs.
*
* @param entity the message entity
* @return content type, or <code>text/plain</code> if not available
*/
private static ContentType getContentType(Part entity) {
try {
String type = entity.getContentType();
if (type != null) {
return new ContentType(type);
} else {
return new ContentType("text/plain");
}
} catch (MessagingException e) {
ContentType type = new ContentType();
type.setPrimaryType("application");
type.setSubType("octet-stream");
return type;
}
}
/**
* Sets the named property if the given value is not null.
*
* @param node target node
* @param name property name
* @param value property value
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, String value)
throws RepositoryException {
if (value != null) {
node.setProperty(name, value);
}
}
/**
* Sets the named property if the given array of values is
* not null or empty.
*
* @param node target node
* @param name property name
* @param values property values
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, String[] values)
throws RepositoryException {
if (values != null && values.length > 0) {
node.setProperty(name, values);
}
}
/**
* Sets the named property if the given value is not null.
*
* @param node target node
* @param name property name
* @param value property value
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, Date value)
throws RepositoryException {
if (value != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
node.setProperty(name, calendar);
}
}
/**
* Sets the named property if the given value is not null.
*
* @param node target node
* @param name property name
* @param value property value
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, Address value)
throws RepositoryException {
if (value != null) {
node.setProperty(name, value.toString());
}
}
/**
* Sets the named property if the given array of values is
* not null or empty.
*
* @param node target node
* @param name property name
* @param values property values
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, Address[] values)
throws RepositoryException {
if (values != null && values.length > 0) {
String[] strings = new String[values.length];
for (int i = 0; i < values.length; i++) {
strings[i] = values[i].toString();
}
node.setProperty(name, strings);
}
}
}
| sandbox/james-jcr/src/main/java/org/apache/james/jcr/JCRStoreBean.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.james.jcr;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Message.RecipientType;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeMessage;
import org.apache.jackrabbit.util.Text;
/**
* JavaBean that stores messages to a JCR content repository.
*/
public class JCRStoreBean {
/**
* Parent node where the messages are stored.
*/
private Node parent;
public void setParentNode(Node parent) {
this.parent = parent;
}
/**
* Stores the given mail message to the content repository.
*
* @param message mail message
* @throws MessagingException if the message could not be read
* @throws RepositoryException if the message could not be saved
*/
public void storeMessage(Message message)
throws MessagingException, RepositoryException {
try {
Node node = createNode(parent, getMessageName(message), "nt:file");
importEntity(message, node);
parent.save();
} catch (IOException e) {
throw new MessagingException("Could not read message", e);
}
}
/**
* Import the given entity to the given JCR node.
*
* @param entity the source entity
* @param parent the target node
* @throws MessagingException if the message could not be read
* @throws RepositoryException if the message could not be written
* @throws IOException if the message could not be read
*/
private void importEntity(Part entity, Node parent)
throws MessagingException, RepositoryException, IOException {
Node node = parent.addNode("jcr:content", "nt:unstructured");
setProperty(node, "description", entity.getDescription());
setProperty(node, "disposition", entity.getDisposition());
setProperty(node, "filename", entity.getFileName());
if (entity instanceof MimeMessage) {
MimeMessage mime = (MimeMessage) entity;
setProperty(node, "subject", mime.getSubject());
setProperty(node, "message-id", mime.getMessageID());
setProperty(node, "content-id", mime.getContentID());
setProperty(node, "content-md5", mime.getContentMD5());
setProperty(node, "language", mime.getContentLanguage());
setProperty(node, "sent", mime.getSentDate());
setProperty(node, "received", mime.getReceivedDate());
setProperty(node, "from", mime.getFrom());
setProperty(node, "to", mime.getRecipients(RecipientType.TO));
setProperty(node, "cc", mime.getRecipients(RecipientType.CC));
setProperty(node, "bcc", mime.getRecipients(RecipientType.BCC));
setProperty(node, "reply-to", mime.getReplyTo());
setProperty(node, "sender", mime.getSender());
}
Object content = entity.getContent();
ContentType type = getContentType(entity);
node.setProperty("jcr:mimeType", type.getBaseType());
if (content instanceof Multipart) {
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart part = multipart.getBodyPart(i);
Node child;
if (part.getFileName() != null) {
child = createNode(node, part.getFileName(), "nt:file");
} else {
child = createNode(node, "part", "nt:unstructured");
}
importEntity(part, child);
}
} else if (content instanceof String) {
byte[] bytes = ((String) content).getBytes("UTF-8");
node.setProperty("jcr:encoding", "UTF-8");
node.setProperty("jcr:data", new ByteArrayInputStream(bytes));
} else if (content instanceof InputStream) {
setProperty(
node, "jcr:encoding", type.getParameter("encoding"));
node.setProperty("jcr:data", (InputStream) content);
} else {
node.setProperty("jcr:data", entity.getInputStream());
}
}
/**
* Suggests a name for the node where the given message will be stored.
*
* @param message mail message
* @return suggested name
* @throws MessagingException if an error occurs
*/
private String getMessageName(Message message)
throws MessagingException {
DateFormat format = new SimpleDateFormat("yyyy-mm-dd");
String subject =
message.getSubject().replaceAll("[\\[\\]:;,./?'+-@#*\"%$]", "");
return format.format(message.getSentDate()) + " " + subject;
}
/**
* Creates a new node with a name that resembles the given suggestion.
* The created node is not saved by this method.
*
* @param parent parent node
* @param name suggested name
* @param type node type
* @return created node
* @throws RepositoryException if an error occurs
*/
private Node createNode(Node parent, String name, String type)
throws RepositoryException {
String original = name;
name = Text.escapeIllegalJcrChars(name);
for (int i = 2; parent.hasNode(name); i++) {
name = Text.escapeIllegalJcrChars(original + i);
}
return parent.addNode(name, type);
}
/**
* Returns the content type of the given message entity. Returns
* the default "text/plain" content type if a content type is not
* available. Returns "applicatin/octet-stream" if an error occurs.
*
* @param entity the message entity
* @return content type, or <code>text/plain</code> if not available
*/
private static ContentType getContentType(Part entity) {
try {
String type = entity.getContentType();
if (type != null) {
return new ContentType(type);
} else {
return new ContentType("text/plain");
}
} catch (MessagingException e) {
ContentType type = new ContentType();
type.setPrimaryType("application");
type.setSubType("octet-stream");
return type;
}
}
/**
* Sets the named property if the given value is not null.
*
* @param node target node
* @param name property name
* @param value property value
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, String value)
throws RepositoryException {
if (value != null) {
node.setProperty(name, value);
}
}
/**
* Sets the named property if the given array of values is
* not null or empty.
*
* @param node target node
* @param name property name
* @param values property values
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, String[] values)
throws RepositoryException {
if (values != null && values.length > 0) {
node.setProperty(name, values);
}
}
/**
* Sets the named property if the given value is not null.
*
* @param node target node
* @param name property name
* @param value property value
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, Date value)
throws RepositoryException {
if (value != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
node.setProperty(name, calendar);
}
}
/**
* Sets the named property if the given value is not null.
*
* @param node target node
* @param name property name
* @param value property value
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, Address value)
throws RepositoryException {
if (value != null) {
node.setProperty(name, value.toString());
}
}
/**
* Sets the named property if the given array of values is
* not null or empty.
*
* @param node target node
* @param name property name
* @param values property values
* @throws RepositoryException if an error occurs
*/
private void setProperty(Node node, String name, Address[] values)
throws RepositoryException {
if (values != null && values.length > 0) {
String[] strings = new String[values.length];
for (int i = 0; i < values.length; i++) {
strings[i] = values[i].toString();
}
node.setProperty(name, strings);
}
}
}
| james-jcr: Added some documentation and an intermediate .../year/month/day/... folder structure.
git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@617122 13f79535-47bb-0310-9956-ffa450edef68
| sandbox/james-jcr/src/main/java/org/apache/james/jcr/JCRStoreBean.java | james-jcr: Added some documentation and an intermediate .../year/month/day/... folder structure. | <ide><path>andbox/james-jcr/src/main/java/org/apache/james/jcr/JCRStoreBean.java
<ide> import java.io.ByteArrayInputStream;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<del>import java.text.DateFormat;
<ide> import java.text.SimpleDateFormat;
<ide> import java.util.Calendar;
<ide> import java.util.Date;
<ide>
<ide> import javax.jcr.Node;
<add>import javax.jcr.PathNotFoundException;
<ide> import javax.jcr.RepositoryException;
<ide> import javax.mail.Address;
<ide> import javax.mail.BodyPart;
<ide>
<ide> /**
<ide> * JavaBean that stores messages to a JCR content repository.
<add> * <p>
<add> * After instantiating this bean you should use the
<add> * {@link #setParentNode(Node)} method to specify the root node under
<add> * which all messages should be stored. Then you can call
<add> * {@link #storeMessage(Message)} to store messages in the repository.
<add> * <p>
<add> * The created content structure below the given parent node consists
<add> * of a date based .../year/month/day tree structure, below which the actual
<add> * messages are stored. A stored message consists of an nt:file node whose
<add> * name is based on the subject of the message. The jcr:content child of the
<add> * nt:file node contains the MIME structure and all relevant headers of the
<add> * message. Note that the original message source is <em>not</em> stored,
<add> * which means that some of the message information will be lost.
<add> * <p>
<add> * The messages are stored using the session associated with the specified
<add> * parent node. No locking or synchronization is performed, and it is expected
<add> * that only one thread writing to the message subtree at any given moment.
<add> * You should use JCR locking or some other explicit synchronization mechanism
<add> * if you want to have concurrent writes to the message subtree.
<ide> */
<ide> public class JCRStoreBean {
<ide>
<ide> public void storeMessage(Message message)
<ide> throws MessagingException, RepositoryException {
<ide> try {
<del> Node node = createNode(parent, getMessageName(message), "nt:file");
<add> Date date = message.getSentDate();
<add> Node year = getOrAddNode(parent, format("yyyy", date), "nt:folder");
<add> Node month = getOrAddNode(year, format("mm", date), "nt:folder");
<add> Node day = getOrAddNode(month, format("dd", date), "nt:folder");
<add> Node node = createNode(day, getMessageName(message), "nt:file");
<ide> importEntity(message, node);
<ide> parent.save();
<ide> } catch (IOException e) {
<ide> }
<ide>
<ide> /**
<add> * Formats the given date using the given {@link SimpleDateFormat}
<add> * format string.
<add> *
<add> * @param format format string
<add> * @param date date to be formatted
<add> * @return formatted date
<add> */
<add> private String format(String format, Date date) {
<add> return new SimpleDateFormat(format).format(date);
<add> }
<add>
<add> /**
<ide> * Suggests a name for the node where the given message will be stored.
<ide> *
<ide> * @param message mail message
<ide> */
<ide> private String getMessageName(Message message)
<ide> throws MessagingException {
<del> DateFormat format = new SimpleDateFormat("yyyy-mm-dd");
<del> String subject =
<del> message.getSubject().replaceAll("[\\[\\]:;,./?'+-@#*\"%$]", "");
<del> return format.format(message.getSentDate()) + " " + subject;
<add> String name = message.getSubject();
<add> if (name == null) {
<add> name = "unnamed";
<add> } else {
<add> name = name.replaceAll("[^A-Za-z0-9 ]", "").trim();
<add> if (name.length() == 0) {
<add> name = "unnamed";
<add> }
<add> }
<add> return name;
<add> }
<add>
<add> /**
<add> * Returns the named child node of the given parent. If the child node
<add> * does not exist, it is automatically created with the given node type.
<add> * The created node is not saved by this method.
<add> *
<add> * @param parent parent node
<add> * @param name name of the child node
<add> * @param type type of the child node
<add> * @return child node
<add> * @throws RepositoryException if the child node could not be accessed
<add> */
<add> private Node getOrAddNode(Node parent, String name, String type)
<add> throws RepositoryException {
<add> try {
<add> return parent.getNode(name);
<add> } catch (PathNotFoundException e) {
<add> return parent.addNode(name, type);
<add> }
<ide> }
<ide>
<ide> /**
<ide> /**
<ide> * Returns the content type of the given message entity. Returns
<ide> * the default "text/plain" content type if a content type is not
<del> * available. Returns "applicatin/octet-stream" if an error occurs.
<add> * available. Returns "application/octet-stream" if an error occurs.
<ide> *
<ide> * @param entity the message entity
<ide> * @return content type, or <code>text/plain</code> if not available |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.