answer
stringlengths 17
10.2M
|
|---|
package org.jboss.as.clustering.infinispan.subsystem;
import static org.jboss.as.clustering.infinispan.subsystem.CommonAttributes.*;
import static org.jboss.as.clustering.infinispan.subsystem.CommonAttributes.NAME;
import static org.jboss.as.clustering.infinispan.subsystem.CommonAttributes.PATH;
import static org.jboss.as.clustering.infinispan.subsystem.CommonAttributes.RELATIVE_TO;
import static org.jboss.as.clustering.infinispan.subsystem.CommonAttributes.START;
import static org.jboss.as.clustering.infinispan.subsystem.CommonAttributes.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE;
import java.util.Locale;
import java.util.ResourceBundle;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
public class InfinispanDescriptions {
public static final String RESOURCE_NAME = InfinispanDescriptions.class.getPackage().getName() + ".LocalDescriptions";
private InfinispanDescriptions() {
// Hide
}
// subsystems
static ModelNode getSubsystemDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode subsystem = createDescription(resources, "infinispan");
subsystem.get(HEAD_COMMENT_ALLOWED).set(true);
subsystem.get(TAIL_COMMENT_ALLOWED).set(true);
subsystem.get(NAMESPACE).set(Namespace.CURRENT.getUri());
subsystem.get(CHILDREN, ModelKeys.CACHE_CONTAINER, DESCRIPTION).set(resources.getString("infinispan.container"));
subsystem.get(CHILDREN, ModelKeys.CACHE_CONTAINER, MIN_OCCURS).set(1);
subsystem.get(CHILDREN, ModelKeys.CACHE_CONTAINER, MAX_OCCURS).set(Integer.MAX_VALUE);
subsystem.get(CHILDREN, ModelKeys.CACHE_CONTAINER, MODEL_DESCRIPTION).setEmptyObject();
return subsystem;
}
static ModelNode getSubsystemAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.add");
DEFAULT_CACHE_CONTAINER.addOperationParameterDescription(resources, "infinispan", op);
return op;
}
static ModelNode getSubsystemDescribeDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(DESCRIBE, resources, "infinispan.describe");
op.get(REQUEST_PROPERTIES).setEmptyObject();
op.get(REPLY_PROPERTIES, TYPE).set(ModelType.LIST);
op.get(REPLY_PROPERTIES, VALUE_TYPE).set(ModelType.OBJECT);
return op;
}
static ModelNode getSubsystemRemoveDescription(Locale locale) {
final ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.remove");
op.get(REPLY_PROPERTIES).setEmptyObject();
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
// cache containers
static ModelNode getCacheContainerDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
String keyPrefix = "infinispan.container" ;
final ModelNode container = createDescription(resources, keyPrefix);
// attributes
for (AttributeDefinition attr : CommonAttributes.CACHE_CONTAINER_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, keyPrefix, container);
}
// need to add value type until we replace with a ListAttribute
ALIASES.addResourceAttributeDescription(resources, keyPrefix, container).
get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.STRING);
// information about its child "singleton=transport"
container.get(CHILDREN, ModelKeys.SINGLETON, DESCRIPTION).set(resources.getString(keyPrefix + ".singleton"));
container.get(CHILDREN, ModelKeys.SINGLETON, MIN_OCCURS).set(0);
container.get(CHILDREN, ModelKeys.SINGLETON, MAX_OCCURS).set(1);
container.get(CHILDREN, ModelKeys.SINGLETON, ALLOWED).setEmptyList().add("transport");
container.get(CHILDREN, ModelKeys.SINGLETON, MODEL_DESCRIPTION);
// information about its child "local-cache"
container.get(CHILDREN, ModelKeys.LOCAL_CACHE, DESCRIPTION).set(resources.getString(keyPrefix + ".local-cache"));
container.get(CHILDREN, ModelKeys.LOCAL_CACHE, MIN_OCCURS).set(0);
container.get(CHILDREN, ModelKeys.LOCAL_CACHE, MAX_OCCURS).set(Integer.MAX_VALUE);
container.get(CHILDREN, ModelKeys.LOCAL_CACHE, MODEL_DESCRIPTION);
// information about its child "invalidation-cache"
container.get(CHILDREN, ModelKeys.INVALIDATION_CACHE, DESCRIPTION).set(resources.getString(keyPrefix + ".invalidation-cache"));
container.get(CHILDREN, ModelKeys.INVALIDATION_CACHE, MIN_OCCURS).set(0);
container.get(CHILDREN, ModelKeys.INVALIDATION_CACHE, MAX_OCCURS).set(Integer.MAX_VALUE);
container.get(CHILDREN, ModelKeys.INVALIDATION_CACHE, MODEL_DESCRIPTION);
// information about its child "local-cache"
container.get(CHILDREN, ModelKeys.REPLICATED_CACHE, DESCRIPTION).set(resources.getString(keyPrefix + ".replicated-cache"));
container.get(CHILDREN, ModelKeys.REPLICATED_CACHE, MIN_OCCURS).set(0);
container.get(CHILDREN, ModelKeys.REPLICATED_CACHE, MAX_OCCURS).set(Integer.MAX_VALUE);
container.get(CHILDREN, ModelKeys.REPLICATED_CACHE, MODEL_DESCRIPTION);
// information about its child "local-cache"
container.get(CHILDREN, ModelKeys.DISTRIBUTED_CACHE, DESCRIPTION).set(resources.getString(keyPrefix + ".distributed-cache"));
container.get(CHILDREN, ModelKeys.DISTRIBUTED_CACHE, MIN_OCCURS).set(0);
container.get(CHILDREN, ModelKeys.DISTRIBUTED_CACHE, MAX_OCCURS).set(Integer.MAX_VALUE);
container.get(CHILDREN, ModelKeys.DISTRIBUTED_CACHE, MODEL_DESCRIPTION);
return container;
}
static ModelNode getCacheContainerAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.container.add");
// request parameters
for (AttributeDefinition attr : CommonAttributes.CACHE_CONTAINER_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.container", op);
}
// need to add value type until we replace with a ListAttribute
ALIASES.addOperationParameterDescription(resources, "infinispan.container", op).
get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.STRING);
return op;
}
static ModelNode getCacheContainerRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.container.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
static ModelNode getAddAliasCommandDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription("add-alias", resources, "infinispan.container.alias.add-alias");
NAME.addOperationParameterDescription(resources, "infinispan.container.alias", op);
return op;
}
static ModelNode getRemoveAliasCommandDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription("remove-alias", resources, "infinispan.container.alias.remove-alias");
NAME.addOperationParameterDescription(resources, "infinispan.container.alias", op);
return op;
}
// local caches
static ModelNode getLocalCacheDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode cache = createDescription(resources, "infinispan.container.local-cache");
// attributes
for (AttributeDefinition attr : CommonAttributes.CACHE_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache", cache);
}
// children
addCommonCacheChildren("infinispan.cache", cache, resources);
return cache ;
}
static ModelNode getLocalCacheAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.container.local-cache.add");
addCommonCacheAddRequestProperties("infinispan.cache", op, resources);
return op;
}
// invalidation caches
static ModelNode getInvalidationCacheDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode cache = createDescription(resources, "infinispan.container.invalidation-cache");
// attributes
for (AttributeDefinition attr : CommonAttributes.CACHE_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache", cache);
}
// children
addCommonCacheChildren("infinispan.cache", cache, resources);
addStateTransferCacheChildren("infinispan-cache", cache, resources);
return cache ;
}
static ModelNode getInvalidationCacheAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.container.invalidation-cache.add");
// parameters
addCommonCacheAddRequestProperties("infinispan.cache", op, resources);
addCommonClusteredCacheAddRequestProperties("infinispan.clustered-cache", op, resources);
return op;
}
// replicated caches
static ModelNode getReplicatedCacheDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode cache = createDescription(resources, "infinispan.container.replicated-cache");
// attributes
for (AttributeDefinition attr : CommonAttributes.CACHE_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache", cache);
}
// children
addCommonCacheChildren("infinispan.cache", cache, resources);
addStateTransferCacheChildren("infinispan-cache", cache, resources);
return cache ;
}
static ModelNode getReplicatedCacheAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.container.replicated-cache.add");
// parameters
addCommonCacheAddRequestProperties("infinispan.cache", op, resources);
addCommonClusteredCacheAddRequestProperties("infinispan.clustered-cache", op, resources);
// nested resource initialization
String keyPrefix = "infinispan.replicated-cache.state-transfer" ;
ModelNode requestProperties = op.get(ModelDescriptionConstants.REQUEST_PROPERTIES);
ModelNode stateTransfer = addNode(requestProperties, ModelKeys.STATE_TRANSFER, resources.getString(keyPrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.STATE_TRANSFER_ATTRIBUTES) {
addAttributeDescription(attr, resources, keyPrefix, stateTransfer);
}
return op;
}
// distributed caches
static ModelNode getDistributedCacheDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode cache = createDescription(resources, "infinispan.container.distributed-cache");
// attributes
for (AttributeDefinition attr : CommonAttributes.CACHE_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache", cache);
}
// children
addCommonCacheChildren("infinispan.cache", cache, resources);
addStateTransferCacheChildren("infinispan-cache", cache, resources);
return cache ;
}
static ModelNode getDistributedCacheAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.container.distributed-cache.add");
// parameters
addCommonCacheAddRequestProperties("infinispan.cache", op, resources);
addCommonClusteredCacheAddRequestProperties("infinispan.clustered-cache", op, resources);
for (AttributeDefinition attr : CommonAttributes.DISTRIBUTED_CACHE_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.distributed-cache", op);
}
String keyPrefix = "infinispan.replicated-cache.state-transfer" ;
ModelNode requestProperties = op.get(ModelDescriptionConstants.REQUEST_PROPERTIES);
ModelNode stateTransfer = addNode(requestProperties, ModelKeys.STATE_TRANSFER, resources.getString(keyPrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.STATE_TRANSFER_ATTRIBUTES) {
addAttributeDescription(attr, resources, keyPrefix, stateTransfer);
}
return op;
}
// TODO update me
static ModelNode getCacheRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.cache.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
// cache container transport element
static ModelNode getTransportDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode transport = createDescription(resources, "infinispan.container.transport");
for (AttributeDefinition attr : CommonAttributes.TRANSPORT_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.container.transport", transport);
}
return transport ;
}
static ModelNode getTransportAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.container.transport.add");
for (AttributeDefinition attr : CommonAttributes.TRANSPORT_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.container.transport", op);
}
return op;
}
static ModelNode getTransportRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.container.transport.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
// cache locking element
static ModelNode getLockingDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode locking = createDescription(resources, "infinispan.cache.locking");
for (AttributeDefinition attr : CommonAttributes.LOCKING_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache.locking", locking);
}
return locking ;
}
static ModelNode getLockingAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.cache.locking.add");
for (AttributeDefinition attr : CommonAttributes.LOCKING_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.cache.locking", op);
}
return op;
}
static ModelNode getLockingRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.cache.locking.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
// cache transaction element
static ModelNode getTransactionDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode transaction = createDescription(resources, "infinispan.cache.transaction");
for (AttributeDefinition attr : CommonAttributes.TRANSACTION_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache.transaction", transaction);
}
return transaction ;
}
static ModelNode getTransactionAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.cache.transaction.add");
for (AttributeDefinition attr : CommonAttributes.TRANSACTION_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.cache.transaction", op);
}
return op;
}
static ModelNode getTransactionRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.cache.transaction.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
// cache eviction element
static ModelNode getEvictionDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode eviction = createDescription(resources, "infinispan.cache.eviction");
for (AttributeDefinition attr : CommonAttributes.EVICTION_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache.eviction", eviction);
}
return eviction ;
}
static ModelNode getEvictionAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.cache.eviction.add");
for (AttributeDefinition attr : CommonAttributes.EVICTION_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.cache.eviction", op);
}
return op;
}
static ModelNode getEvictionRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.cache.eviction.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
// cache expiration elemet
static ModelNode getExpirationDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode expiration = createDescription(resources, "infinispan.cache.expiration");
for (AttributeDefinition attr : CommonAttributes.EXPIRATION_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.cache.expiration", expiration);
}
return expiration ;
}
static ModelNode getExpirationAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.cache.expiration.add");
for (AttributeDefinition attr : CommonAttributes.EXPIRATION_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.cache.expiration", op);
}
return op;
}
static ModelNode getExpirationRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.cache.expiration.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
// cache state transfer element
static ModelNode getStateTransferDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode stateTransfer = createDescription(resources, "infinispan.replicated-cache.state-transfer");
for (AttributeDefinition attr : CommonAttributes.STATE_TRANSFER_ATTRIBUTES) {
attr.addResourceAttributeDescription(resources, "infinispan.replicated-cache.state-transfer", stateTransfer);
}
return stateTransfer ;
}
static ModelNode getStateTransferAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.replicated-cache.state-transfer.add");
for (AttributeDefinition attr : CommonAttributes.STATE_TRANSFER_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, "infinispan.replicated-cache.state-transfer", op);
}
return op;
}
static ModelNode getStateTransferRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.replicated-cache.state-transfer.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
static ModelNode getCacheStorePropertyDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode storeProperty = createDescription(resources, "infinispan.cache.store.property");
VALUE.addResourceAttributeDescription(resources, "infinispan.cache.store.property", storeProperty);
return storeProperty ;
}
static ModelNode getCacheStorePropertyAddDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(ADD, resources, "infinispan.cache.store.property.add");
VALUE.addOperationParameterDescription(resources, "infinispan.cache.store.property", op);
return op;
}
static ModelNode getCacheStorePropertyRemoveDescription(Locale locale) {
ResourceBundle resources = getResources(locale);
final ModelNode op = createOperationDescription(REMOVE, resources, "infinispan.cache.store.property.remove");
op.get(REQUEST_PROPERTIES).setEmptyObject();
return op;
}
private static ResourceBundle getResources(Locale locale) {
return ResourceBundle.getBundle(RESOURCE_NAME, (locale == null) ? Locale.getDefault() : locale);
}
private static ModelNode createDescription(ResourceBundle resources, String key) {
return createOperationDescription(null, resources, key);
}
private static ModelNode createOperationDescription(String operation, ResourceBundle resources, String key) {
ModelNode description = new ModelNode();
if (operation != null) {
description.get(OPERATION_NAME).set(operation);
}
description.get(DESCRIPTION).set(resources.getString(key));
return description;
}
private static void addCommonCacheChildren(String keyPrefix, ModelNode description, ResourceBundle resources) {
// information about its child "singleton=*"
description.get(CHILDREN, ModelKeys.SINGLETON, DESCRIPTION).set(resources.getString(keyPrefix+".singleton"));
description.get(CHILDREN, ModelKeys.SINGLETON, MIN_OCCURS).set(0);
description.get(CHILDREN, ModelKeys.SINGLETON, MAX_OCCURS).set(1);
description.get(CHILDREN, ModelKeys.SINGLETON, ALLOWED).setEmptyList();
description.get(CHILDREN, ModelKeys.SINGLETON, ALLOWED).add("locking").add("transaction").add("eviction").add("expiration");
description.get(CHILDREN, ModelKeys.SINGLETON, MODEL_DESCRIPTION);
}
private static void addStateTransferCacheChildren(String keyPrefix, ModelNode description, ResourceBundle resources) {
// information about its child "singleton=*"
description.get(CHILDREN, ModelKeys.SINGLETON, ALLOWED).add("state-transfer");
}
private static void addRehashingCacheChildren(String keyPrefix, ModelNode description, ResourceBundle resources) {
// information about its child "singleton=*"
description.get(CHILDREN, ModelKeys.SINGLETON, ALLOWED).add("rehashing");
}
/**
* Add the set of request parameters which are common to all cache add operations.
*
* @param keyPrefix prefix used to lookup key in resource bundle
* @param operation the operation ModelNode to add the request properties to
* @param resources the resource bundle containing keys and their strings
*/
private static void addCommonCacheAddRequestProperties(String keyPrefix, ModelNode operation, ResourceBundle resources) {
START.addOperationParameterDescription(resources, keyPrefix, operation);
BATCHING.addOperationParameterDescription(resources, keyPrefix, operation);
INDEXING.addOperationParameterDescription(resources, keyPrefix, operation);
ModelNode requestProperties = operation.get(ModelDescriptionConstants.REQUEST_PROPERTIES);
String lockingPrefix = keyPrefix + "." + "locking" ;
ModelNode locking = addNode(requestProperties, ModelKeys.LOCKING, resources.getString(lockingPrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.LOCKING_ATTRIBUTES) {
addAttributeDescription(attr, resources, lockingPrefix, locking);
}
String transactionPrefix = keyPrefix + "." + "transaction" ;
ModelNode transaction = addNode(requestProperties, ModelKeys.TRANSACTION, resources.getString(transactionPrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.TRANSACTION_ATTRIBUTES) {
addAttributeDescription(attr, resources, transactionPrefix, transaction);
}
String evictionPrefix = keyPrefix + "." + "eviction" ;
ModelNode eviction = addNode(requestProperties, ModelKeys.EVICTION, resources.getString(evictionPrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.EVICTION_ATTRIBUTES) {
addAttributeDescription(attr, resources, evictionPrefix, eviction);
}
String expirationPrefix = keyPrefix + ".expiration" ;
ModelNode expiration = addNode(requestProperties, ModelKeys.EXPIRATION, resources.getString(expirationPrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.EXPIRATION_ATTRIBUTES) {
addAttributeDescription(attr, resources, expirationPrefix, expiration);
}
String storePrefix = keyPrefix + "." + "store" ;
ModelNode store = addNode(requestProperties, ModelKeys.STORE, resources.getString(storePrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.STORE_ATTRIBUTES) {
addAttributeDescription(attr, resources, storePrefix, store);
}
// property needs value type
addAttributeDescription(PROPERTY, resources, storePrefix, store).get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.PROPERTY);
String fileStorePrefix = keyPrefix + "." + "file-store" ;
ModelNode fileStore = addNode(requestProperties, ModelKeys.FILE_STORE, resources.getString(fileStorePrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.STORE_ATTRIBUTES) {
addAttributeDescription(attr, resources, storePrefix, fileStore);
}
// property needs value type
addAttributeDescription(PROPERTY, resources, storePrefix, fileStore).get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.PROPERTY);
addAttributeDescription(RELATIVE_TO, resources, fileStorePrefix, fileStore);
addAttributeDescription(PATH, resources, fileStorePrefix, fileStore);
String jdbcStorePrefix = keyPrefix + ".jdbc-store" ;
ModelNode jdbcStore = addNode(requestProperties, ModelKeys.JDBC_STORE, resources.getString(jdbcStorePrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.STORE_ATTRIBUTES) {
addAttributeDescription(attr, resources, storePrefix, jdbcStore);
}
// property needs value type
addAttributeDescription(PROPERTY, resources, storePrefix, jdbcStore).get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.PROPERTY);
addAttributeDescription(DATA_SOURCE, resources, jdbcStorePrefix, jdbcStore);
String remoteStorePrefix = keyPrefix + ".remote-store" ;
ModelNode remoteStore = addNode(requestProperties, ModelKeys.REMOTE_STORE, resources.getString(remoteStorePrefix), ModelType.OBJECT, false).get(ModelDescriptionConstants.VALUE_TYPE);
for (AttributeDefinition attr : CommonAttributes.STORE_ATTRIBUTES) {
addAttributeDescription(attr, resources, storePrefix, remoteStore);
}
// property needs value type
addAttributeDescription(PROPERTY, resources, storePrefix, remoteStore).get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.PROPERTY);
addAttributeDescription(REMOTE_SERVER, resources, remoteStorePrefix, remoteStore).get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.STRING);
}
/**
* Add the set of request parameters which are common to all clustered cache add operations.
*
* @param keyPrefix prefix used to lookup key in resource bundle
* @param operation the operation ModelNode to add the request properties to
* @param resources the resource bundle containing keys and their strings
*/
private static void addCommonClusteredCacheAddRequestProperties(String keyPrefix, ModelNode operation, ResourceBundle resources) {
for (AttributeDefinition attr : CommonAttributes.CLUSTERED_CACHE_ATTRIBUTES) {
attr.addOperationParameterDescription(resources, keyPrefix, operation);
}
// addNode(requestProperties, ModelKeys.MODE, resources.getString(keyPrefix+".mode"), ModelType.STRING, true);
}
private static ModelNode addNode(ModelNode parent, String attribute, String description, ModelType type, boolean required) {
ModelNode node = parent.get(attribute);
node.get(ModelDescriptionConstants.DESCRIPTION).set(description);
node.get(ModelDescriptionConstants.TYPE).set(type);
node.get(ModelDescriptionConstants.REQUIRED).set(required);
return node;
}
/**
* Add an attribute description to an arbitrary node (and not just REQUEST_PROPERTIES or ATTRIBUTES .
*
* @param attribute the attribute definition defining the attribute
* @param bundle
* @param prefix the resource prefix of the attribute
* @param model the ModelNode to add the description to
*
* @return the ModelNode added
*/
private static ModelNode addAttributeDescription(AttributeDefinition attribute, ResourceBundle bundle, String prefix, ModelNode model) {
ModelNode node = model.get(attribute.getName());
node.get(ModelDescriptionConstants.DESCRIPTION).set(bundle.getString(prefix + "." + attribute.getName()));
node.get(ModelDescriptionConstants.TYPE).set(attribute.getType());
node.get(ModelDescriptionConstants.REQUIRED).set(attribute.isRequired(model));
return node;
}
}
|
package com.qiniu.android;
import com.qiniu.android.collect.ReportItem;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.http.request.Request;
import org.json.JSONObject;
import java.util.HashMap;
public class UploadReportItemTest extends BaseTest {
public void testSetAndRemoveValue(){
ReportItem reportItem = new ReportItem();
reportItem.setReport(ReportItem.LogTypeRequest, ReportItem.RequestKeyLogType);
String json = reportItem.toJson();
assertTrue(! json.equals("{}"));
reportItem.removeReportValue(ReportItem.RequestKeyLogType);
json = reportItem.toJson();
assertTrue(json.equals("{}"));
}
public void testReportStatusCode(){
ResponseInfo responseInfo = createResponseInfo(ResponseInfo.Cancelled);
assertTrue(ReportItem.requestReportStatusCode(responseInfo) != null);
responseInfo = createResponseInfo(200);
assertTrue(ReportItem.requestReportStatusCode(responseInfo).equals("200"));
}
public void testReportErrorType(){
ResponseInfo responseInfo = createResponseInfo(200);
assertTrue(ReportItem.qualityResult(responseInfo).equals("ok"));
responseInfo = createResponseInfo(400);
assertTrue(ReportItem.qualityResult(responseInfo).equals("bad_request"));
responseInfo = createResponseInfo(ResponseInfo.ZeroSizeFile);
assertTrue(ReportItem.qualityResult(responseInfo).equals("zero_size_file"));
responseInfo = createResponseInfo(ResponseInfo.InvalidFile);
assertTrue(ReportItem.qualityResult(responseInfo).equals("invalid_file"));
responseInfo = createResponseInfo(ResponseInfo.InvalidToken);
assertTrue(ReportItem.qualityResult(responseInfo).equals("invalid_args"));
responseInfo = createResponseInfo(ResponseInfo.NetworkError);
assertTrue(ReportItem.qualityResult(responseInfo).equals("network_error"));
responseInfo = createResponseInfo(ResponseInfo.TimedOut);
assertTrue(ReportItem.qualityResult(responseInfo).equals("timeout"));
responseInfo = createResponseInfo(ResponseInfo.CannotConnectToHost);
assertTrue(ReportItem.qualityResult(responseInfo).equals("cannot_connect_to_host"));
responseInfo = createResponseInfo(ResponseInfo.NetworkConnectionLost);
assertTrue(ReportItem.qualityResult(responseInfo).equals("transmission_error"));
responseInfo = createResponseInfo(ResponseInfo.NetworkSSLError);
assertTrue(ReportItem.qualityResult(responseInfo).equals("ssl_error"));
responseInfo = createResponseInfo(ResponseInfo.PasrseError);
assertTrue(ReportItem.qualityResult(responseInfo).equals("parse_error"));
responseInfo = createResponseInfo(ResponseInfo.MaliciousResponseError);
assertTrue(ReportItem.qualityResult(responseInfo).equals("malicious_response"));
responseInfo = createResponseInfo(ResponseInfo.Cancelled);
assertTrue(ReportItem.qualityResult(responseInfo).equals("user_canceled"));
responseInfo = createResponseInfo(ResponseInfo.LocalIOError);
assertTrue(ReportItem.qualityResult(responseInfo).equals("local_io_error"));
responseInfo = createResponseInfo(ResponseInfo.NetworkProtocolError);
assertTrue(ReportItem.qualityResult(responseInfo).equals("protocol_error"));
responseInfo = createResponseInfo(ResponseInfo.NetworkSlow);
assertTrue(ReportItem.qualityResult(responseInfo).equals("network_slow"));
responseInfo = createResponseInfo(10000);
assertTrue(ReportItem.qualityResult(responseInfo).equals("unknown_error"));
}
private ResponseInfo createResponseInfo(int statusCode){
HashMap<String, String>requestHeader = new HashMap<>();
Request request = new Request("url", "GET", requestHeader, null, 10);
HashMap<String, String>responseHeader = new HashMap<>();
responseHeader.put("x-reqid", "req-id");
responseHeader.put("x-log", "log");
return ResponseInfo.create(request, statusCode, responseHeader, new JSONObject(), "");
}
}
|
package jycessing.mode;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import jycessing.DisplayType;
import jycessing.IOUtil;
import jycessing.mode.export.ExportDialog;
import jycessing.mode.run.PdeSketch;
import jycessing.mode.run.PdeSketch.LocationType;
import jycessing.mode.run.SketchService;
import jycessing.mode.run.SketchServiceManager;
import jycessing.mode.run.SketchServiceProcess;
import processing.app.Base;
import processing.app.Formatter;
import processing.app.Language;
import processing.app.Library;
import processing.app.Messages;
import processing.app.Mode;
import processing.app.Platform;
import processing.app.SketchCode;
import processing.app.SketchException;
import processing.app.syntax.JEditTextArea;
import processing.app.syntax.PdeTextArea;
import processing.app.syntax.PdeTextAreaDefaults;
import processing.app.ui.Editor;
import processing.app.ui.EditorException;
import processing.app.ui.EditorState;
import processing.app.ui.EditorToolbar;
import processing.app.ui.Toolkit;
@SuppressWarnings("serial")
public class PyEditor extends Editor {
@SuppressWarnings("unused")
private static void log(final String msg) {
if (PythonMode.VERBOSE) {
System.err.println(PyEditor.class.getSimpleName() + ": " + msg);
}
}
/**
* Every PyEditor has a UUID that the {@link SketchServiceManager} uses to route events from the
* {@link SketchService} to its owning editor.
*/
private final String id;
private final PythonMode pyMode;
private final PyInputHandler inputHandler;
private final SketchServiceProcess sketchService;
/**
* If the user runs a dirty sketch, we create a temp dir containing the modified state of the
* sketch and run it from there. We keep track of it in this variable in order to delete it when
* done running.
*/
private Path tempSketch;
protected PyEditor(final Base base, final String path, final EditorState state, final Mode mode)
throws EditorException {
super(base, path, state, mode);
id = UUID.randomUUID().toString();
inputHandler = new PyInputHandler(this);
pyMode = (PythonMode) mode;
// Provide horizontal scrolling.
textarea.addMouseWheelListener(createHorizontalScrollListener());
// Create a sketch service affiliated with this editor.
final SketchServiceManager sketchServiceManager = pyMode.getSketchServiceManager();
sketchService = sketchServiceManager.createSketchService(this);
// Ensure that the sketch service gets properly destroyed when either the
// JVM terminates or this editor closes, whichever comes first.
final Thread cleanup =
new Thread(() -> sketchServiceManager.destroySketchService(PyEditor.this));
Runtime.getRuntime().addShutdownHook(cleanup);
addWindowListener(
new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
cleanup.run();
Runtime.getRuntime().removeShutdownHook(cleanup);
}
});
}
@Override
protected JEditTextArea createTextArea() {
return new PdeTextArea(new PdeTextAreaDefaults(mode), new PyInputHandler(this), this);
}
public String getId() {
return id;
}
private MouseWheelListener createHorizontalScrollListener() {
return new MouseWheelListener() {
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL && e.isShiftDown()) {
final int current = textarea.getHorizontalScrollPosition();
final int delta = e.getUnitsToScroll() * 6;
textarea.setHorizontalScrollPosition(current + delta);
}
}
};
}
@Override
public String getCommentPrefix() {
return "
}
@Override
public void internalCloseRunner() {
try {
sketchService.stopSketch();
} catch (final SketchException e) {
statusError(e);
} finally {
cleanupTempSketch();
}
}
private void cleanupTempSketch() {
if (tempSketch != null) {
if (tempSketch.toFile().exists()) {
try {
log("Deleting " + tempSketch);
IOUtil.rm(tempSketch);
log("Deleted " + tempSketch);
assert (!tempSketch.toFile().exists());
} catch (final IOException e) {
System.err.println(e);
}
}
tempSketch = null;
}
}
/** Build menus. */
@Override
public JMenu buildFileMenu() {
final String appTitle = Language.text("Export Application");
final JMenuItem exportApplication = Toolkit.newJMenuItem(appTitle, 'E');
exportApplication.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
handleExportApplication();
}
});
return buildFileMenu(new JMenuItem[] {exportApplication});
}
@Override
public JMenu buildHelpMenu() {
// I add a zero-width space to the end of the word "Help" in order to
// prevent OS X from auto-disabling everything in the menu when running
// a sketch.
final JMenu menu = new JMenu("Help\u200B");
menu.add(
new JMenuItem(
new AbstractAction("References") {
@Override
public void actionPerformed(final ActionEvent e) {
Platform.openURL("http://py.processing.org/reference/");
}
}));
menu.add(
new JMenuItem(
new AbstractAction("Tutorials") {
@Override
public void actionPerformed(final ActionEvent e) {
Platform.openURL("http://py.processing.org/tutorials/");
}
}));
menu.add(
new JMenuItem(
new AbstractAction("Examples") {
@Override
public void actionPerformed(final ActionEvent e) {
Platform.openURL("http://py.processing.org/examples/");
}
}));
menu.add(
new JMenuItem(
new AbstractAction("Report a bug in Python Mode") {
@Override
public void actionPerformed(final ActionEvent e) {
Platform.openURL("http://github.com/jdf/processing.py-bugs/issues");
}
}));
menu.add(
new JMenuItem(
new AbstractAction("Contribute to Python Mode") {
@Override
public void actionPerformed(final ActionEvent e) {
Platform.openURL("http://github.com/jdf/processing.py");
}
}));
return menu;
}
@Override
public JMenu buildSketchMenu() {
final JMenuItem runItem = Toolkit.newJMenuItem(Language.text("toolbar.run"), 'R');
runItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
handleRun();
}
});
final JMenuItem presentItem = Toolkit.newJMenuItemShift(Language.text("toolbar.present"), 'R');
presentItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
handlePresent();
}
});
final JMenuItem stopItem = new JMenuItem(Language.text("toolbar.stop"));
stopItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
handleStop();
}
});
return buildSketchMenu(new JMenuItem[] {runItem, presentItem, stopItem});
}
@Override
public Formatter createFormatter() {
return pyMode.getFormatter();
}
@Override
public EditorToolbar createToolbar() {
return new PyToolbar(this);
}
/** TODO(James Gilles): Create this! Create export GUI and hand off results to performExport() */
public void handleExportApplication() {
// Leaving this here because it seems like it's more the editor's responsibility
if (sketch.isModified()) {
final Object[] options = {"OK", "Cancel"};
final int result =
JOptionPane.showOptionDialog(
this,
"Save changes before export?",
"Save",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.OK_OPTION) {
handleSave(true);
} else {
statusNotice("Export canceled, changes must first be saved.");
}
}
new ExportDialog(this, sketch).go();
}
public File getModeContentFile(final String filename) {
return pyMode.getContentFile(filename);
}
public File getSplashFile() {
return pyMode.getContentFile("theme/splash.png");
}
/**
* Save the current state of the sketch code into a temp dir, and return the created directory.
*
* @return a new directory containing a saved version of the current (presumably modified) sketch
* code.
* @throws IOException
*/
private Path createTempSketch() throws IOException {
final Path tmp = Files.createTempDirectory(sketch.getName());
for (final SketchCode code : sketch.getCode()) {
Files.write(tmp.resolve(code.getFileName()), code.getProgram().getBytes("utf-8"));
}
return tmp;
}
private void runSketch(final DisplayType displayType) {
prepareRun();
toolbar.activateRun();
final File sketchPath;
if (sketch.isModified()) {
log("Sketch is modified; must copy it to temp dir.");
final String sketchMainFileName = sketch.getCode(0).getFile().getName();
try {
tempSketch = createTempSketch();
sketchPath = tempSketch.resolve(sketchMainFileName).toFile();
} catch (final IOException e) {
Messages.showError(
"Sketchy Behavior", "I can't copy your unsaved work\n" + "to a temp directory.", e);
return;
}
} else {
sketchPath = sketch.getCode(0).getFile().getAbsoluteFile();
}
final LocationType locationType;
final Point location;
if (getSketchLocation() != null) {
locationType = LocationType.SKETCH_LOCATION;
location = new Point(getSketchLocation());
} else { // assume editor has a position - is that safe?
locationType = LocationType.EDITOR_LOCATION;
location = new Point(getLocation());
}
try {
sketchService.runSketch(
new PdeSketch(sketch, sketchPath, displayType, location, locationType));
} catch (final SketchException e) {
statusError(e);
}
}
@Override
public void deactivateRun() {
restoreToolbar();
cleanupTempSketch();
}
public void handleRun() {
runSketch(DisplayType.WINDOWED);
}
public void handlePresent() {
runSketch(DisplayType.PRESENTATION);
}
public void handleStop() {
toolbar.activateStop();
internalCloseRunner();
restoreToolbar();
requestFocus();
}
private void restoreToolbar() {
toolbar.deactivateStop();
toolbar.deactivateRun();
toFront();
}
@Override
public void handleSaveImpl() {
super.handleSaveImpl();
recolor();
}
@Override
public void statusError(final String what) { // sketch died for some reason
super.statusError(what);
restoreToolbar();
}
@Override
public void handleImportLibrary(final String libraryName) {
sketch.ensureExistence();
final Library lib = mode.findLibraryByName(libraryName);
if (lib == null) {
statusError("Unable to locate library: " + libraryName);
return;
}
final String name = new File(lib.getJarPath()).getParentFile().getParentFile().getName();
if (Pattern.compile("^add_library\\(\\s*'" + name + "'\\s*\\)\\s*$", Pattern.MULTILINE)
.matcher(getText())
.find()) {
return;
}
setSelection(0, 0); // scroll to start
setSelectedText(String.format("add_library('%s')\n", name));
sketch.setModified(true);
recolor();
}
@Override
public void handleIndentOutdent(final boolean increase) {
inputHandler.indent(increase ? 1 : -1);
}
@Override
public void handleAutoFormat() {
super.handleAutoFormat();
recolor();
}
@Override
public void handlePaste() {
super.handlePaste();
recolor();
}
@Override
public void handleCut() {
super.handleCut();
recolor();
}
@Override
protected void handleCommentUncomment() {
super.handleCommentUncomment();
recolor();
}
private void recolor() {
textarea.getDocument().tokenizeLines();
}
public void printOut(final String msg) {
console.message(msg, false);
}
public void printErr(final String msg) {
console.message(msg, true);
}
@Override
public void showReference(final String filename) {
Platform.openURL(
String.format("http://py.processing.org/reference/%s", filename.replace("_.", ".")));
}
}
|
package org.gawst.asyncdb.source.typed;
import org.gawst.asyncdb.InvalidDbEntry;
import org.gawst.asyncdb.InvalidEntry;
import org.gawst.asyncdb.MapEntry;
import org.gawst.asyncdb.source.MapDataSource;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public abstract class TypedSqliteMapDataSource<K, V, CURSOR extends Cursor> implements MapDataSource<K, V, Long>, TypedDatabaseSource<Long, Void, CURSOR> {
private final TypedSqliteDataSource<MapEntry<K, V>, CURSOR> source;
/**
* Constructor. (API v14 minimum)
*
* @param context Context used to erase the database file in case it's corrupted.
* @param db The SQL database used to read/write data.
* @param tableName Name of the SQL table that contains the elements to read.
* @param databaseElementHandler Handler to transform {@code Cursor} into ({@link K},{@link V}) pairs or ({@link K},{@link V}) pairs to selections.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public TypedSqliteMapDataSource(@NonNull Context context, @NonNull SQLiteOpenHelper db, @NonNull final String tableName, @NonNull final TypedMapDatabaseElementHandler<K, V, CURSOR> databaseElementHandler) {
this(context, db, tableName, db.getDatabaseName(), databaseElementHandler);
}
/**
* Constructor.
*
* @param context Context used to erase the database file in case it's corrupted.
* @param db The SQL database used to read/write data.
* @param tableName Name of the SQL table that contains the elements to read.
* @param databaseName Name of the database file on disk, in case it's corrupted and needs to be erased.
* @param databaseElementHandler Handler to transform {@code Cursor} into ({@link K},{@link V}) pairs or ({@link K},{@link V}) pairs to selections.
*/
public TypedSqliteMapDataSource(@NonNull Context context, @NonNull SQLiteOpenHelper db, @NonNull final String tableName, @NonNull String databaseName, @NonNull final TypedMapDatabaseElementHandler<K, V, CURSOR> databaseElementHandler) {
if (databaseElementHandler == null) throw new NullPointerException("null TypedMapDatabaseElementHandler in " + this);
this.source = new TypedSqliteDataSource<MapEntry<K, V>, CURSOR>(context, db, tableName, databaseName, new TypedDatabaseElementHandler<MapEntry<K,V>, CURSOR>() {
@NonNull
@Override
public String getItemSelectClause(@Nullable MapEntry<K, V> itemToSelect) {
return databaseElementHandler.getKeySelectClause(null == itemToSelect ? null : itemToSelect.getKey());
}
@NonNull
@Override
public String[] getItemSelectArgs(@NonNull MapEntry<K, V> itemToSelect) {
return databaseElementHandler.getKeySelectArgs(itemToSelect.getKey());
}
@NonNull
@Override
public MapEntry<K, V> cursorToItem(@NonNull CURSOR cursor) throws InvalidDbEntry {
K key = databaseElementHandler.cursorToKey(cursor);
return new MapEntry<K, V>(key, databaseElementHandler.cursorToValue(cursor));
}
}) {
@Override
public CURSOR wrapCursor(Cursor cursor) {
return TypedSqliteMapDataSource.this.wrapCursor(cursor);
}
};
}
@Override
public Void getDatabaseId() {
return null;
}
@Override
public boolean update(MapEntry<K, V> itemToUpdate, ContentValues updateValues) {
return source.update(itemToUpdate, updateValues);
}
@Override
public boolean delete(MapEntry<K, V> itemToDelete) {
return source.delete(itemToDelete);
}
@Override
public Long insert(@NonNull ContentValues values) throws RuntimeException {
return source.insert(values);
}
@Override
public boolean deleteInvalidEntry(InvalidEntry invalidEntry) {
return source.deleteInvalidEntry(invalidEntry);
}
@Override
public CURSOR query(String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) {
return source.query(columns, selection, selectionArgs, groupBy, having, orderBy, limit);
}
@Override
public int update(@NonNull ContentValues updateValues, String selection, String[] selectionArgs) {
return source.update(updateValues, selection, selectionArgs);
}
@Override
public int delete(String selection, String[] selectionArgs) {
return source.delete(selection, selectionArgs);
}
@Override
public final void queryAll(BatchReadingCallback<MapEntry<K, V>> readingCallback) {
source.queryAll(readingCallback);
}
@Override
public int clearAllData() {
return source.clearAllData();
}
@Override
public void eraseSource() {
source.eraseSource();
}
@Override
public String toString() {
return "TypedSqliteMap:"+source;
}
}
|
package liquibase.command.core;
import liquibase.CatalogAndSchema;
import liquibase.Scope;
import liquibase.command.AbstractCommand;
import liquibase.command.CommandResult;
import liquibase.command.CommandValidationErrors;
import liquibase.database.Database;
import liquibase.database.ObjectQuotingStrategy;
import liquibase.database.core.*;
import liquibase.exception.LiquibaseException;
import liquibase.license.LicenseServiceUtils;
import liquibase.logging.LogType;
import liquibase.serializer.SnapshotSerializerFactory;
import liquibase.snapshot.DatabaseSnapshot;
import liquibase.snapshot.SnapshotControl;
import liquibase.snapshot.SnapshotGeneratorFactory;
import liquibase.snapshot.SnapshotListener;
import liquibase.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class SnapshotCommand extends AbstractCommand<SnapshotCommand.SnapshotCommandResult> {
private Database database;
private CatalogAndSchema[] schemas;
private String serializerFormat;
private SnapshotListener snapshotListener;
private Map<String, Object> snapshotMetadata;
@Override
public String getName() {
return "snapshot";
}
public void setDatabase(Database database) {
this.database = database;
}
public Database getDatabase() {
return database;
}
public SnapshotCommand setSchemas(CatalogAndSchema... catalogAndSchema) {
schemas = catalogAndSchema;
return this;
}
public SnapshotCommand setSchemas(String... schemas) {
if ((schemas == null) || (schemas.length == 0) || (schemas[0] == null)) {
this.schemas = null;
return this;
}
schemas = StringUtils.join(schemas, ",").split("\\s*,\\s*");
List<CatalogAndSchema> finalList = new ArrayList<>();
for (String schema : schemas) {
finalList.add(new CatalogAndSchema(null, schema).customize(database));
}
this.schemas = finalList.toArray(new CatalogAndSchema[finalList.size()]);
return this;
}
public String getSerializerFormat() {
return serializerFormat;
}
public SnapshotCommand setSerializerFormat(String serializerFormat) {
this.serializerFormat = serializerFormat;
return this;
}
public SnapshotListener getSnapshotListener() {
return snapshotListener;
}
public void setSnapshotListener(SnapshotListener snapshotListener) {
this.snapshotListener = snapshotListener;
}
public Map<String, Object> getSnapshotMetadata() {
return snapshotMetadata;
}
public void setSnapshotMetadata(Map<String, Object> snapshotMetadata) {
this.snapshotMetadata = snapshotMetadata;
}
@Override
protected SnapshotCommandResult run() throws Exception {
SnapshotCommand.logUnsupportedDatabase(database, this.getClass());
SnapshotControl snapshotControl = new SnapshotControl(database);
snapshotControl.setSnapshotListener(snapshotListener);
CatalogAndSchema[] schemas = this.schemas;
if (schemas == null) {
schemas = new CatalogAndSchema[]{database.getDefaultSchema()};
}
ObjectQuotingStrategy originalQuotingStrategy = database.getObjectQuotingStrategy();
database.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS);
DatabaseSnapshot snapshot;
try {
snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(schemas, database, snapshotControl);
} finally {
database.setObjectQuotingStrategy(originalQuotingStrategy);
}
snapshot.setMetadata(this.getSnapshotMetadata());
return new SnapshotCommandResult(snapshot);
}
@Override
public CommandValidationErrors validate() {
return new CommandValidationErrors(this);
}
public class SnapshotCommandResult extends CommandResult {
public DatabaseSnapshot snapshot;
public SnapshotCommandResult() {
}
public SnapshotCommandResult(DatabaseSnapshot snapshot) {
this.snapshot = snapshot;
}
@Override
public String print() throws LiquibaseException {
String format = getSerializerFormat();
if (format == null) {
format = "txt";
}
return SnapshotSerializerFactory.getInstance().getSerializer(format.toLowerCase(Locale.US)).serialize(snapshot, true);
}
public void merge(SnapshotCommandResult resultToMerge) {
this.snapshot.merge(resultToMerge.snapshot);
}
}
public static void logUnsupportedDatabase(Database database, Class callingClass) {
if (LicenseServiceUtils.checkForValidLicense("Liquibase Pro")) {
if (!(database instanceof MSSQLDatabase
|| database instanceof OracleDatabase)) {
Scope.getCurrentScope().getLog(callingClass).info(LogType.USER_MESSAGE, "INFO This command might not yet capture Liquibase Pro additional object types on " + database.getShortName());
}
}
}
}
|
package com.facebook.litho.widget;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import android.support.annotation.UiThread;
import android.support.annotation.VisibleForTesting;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.view.ViewGroup;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.ComponentInfo;
import com.facebook.litho.ComponentTree;
import com.facebook.litho.ComponentView;
import com.facebook.litho.MeasureComparisonUtils;
import com.facebook.litho.Size;
import com.facebook.litho.SizeSpec;
import com.facebook.litho.ThreadUtils;
import com.facebook.litho.utils.IncrementalMountUtils;
import static android.support.v7.widget.OrientationHelper.HORIZONTAL;
import static android.support.v7.widget.OrientationHelper.VERTICAL;
import static com.facebook.litho.MeasureComparisonUtils.isMeasureSpecCompatible;
/**
* This binder class is used to asynchronously layout Components given a list of {@link Component}
* and attaching them to a {@link RecyclerSpec}.
*/
@ThreadSafe
public class RecyclerBinder implements Binder<RecyclerView>, LayoutInfo.ComponentInfoCollection {
private static final int UNINITIALIZED = -1;
private static final Size sDummySize = new Size();
@GuardedBy("this")
private final List<ComponentTreeHolder> mComponentTreeHolders;
private final LayoutInfo mLayoutInfo;
private final RecyclerView.Adapter mInternalAdapter;
private final ComponentContext mComponentContext;
private final RangeScrollListener mRangeScrollListener = new RangeScrollListener();
private final LayoutHandlerFactory mLayoutHandlerFactory;
private final boolean mUseNewIncrementalMount;
// Data structure to be used to hold Components and ComponentTreeHolders before adding them to
// the RecyclerView. This happens in the case of inserting something inside the current working
// range.
//TODO t15827349
private final List<ComponentTreeHolder> mPendingComponentTreeHolders;
private final float mRangeRatio;
private final AtomicBoolean mIsMeasured = new AtomicBoolean(false);
private int mLastWidthSpec = UNINITIALIZED;
private int mLastHeightSpec = UNINITIALIZED;
private Size mMeasuredSize;
private RecyclerView mMountedView;
private int mCurrentFirstVisiblePosition;
private int mCurrentLastVisiblePosition;
private RangeCalculationResult mRange;
public RecyclerBinder(
ComponentContext componentContext,
float rangeRatio,
LayoutInfo layoutInfo) {
this(componentContext, rangeRatio, layoutInfo, null, false);
}
public RecyclerBinder(
ComponentContext componentContext,
float rangeRatio,
LayoutInfo layoutInfo,
@Nullable LayoutHandlerFactory layoutHandlerFactory) {
this(componentContext, rangeRatio, layoutInfo, layoutHandlerFactory, false);
}
/**
* @param componentContext The {@link ComponentContext} this RecyclerBinder will use.
* @param rangeRatio specifies how big a range this binder should try to compute. The range is
* computed as number of items in the viewport (when the binder is measured) multiplied by the
* range ratio. The ratio is to be intended in both directions. For example a ratio of 1 means
* that if there are currently N components on screen, the binder should try to compute the layout
* for the N components before the first component on screen and for the N components after the
* last component on screen.
* @param layoutInfo an implementation of {@link LayoutInfo} that will expose information about
* the {@link LayoutManager} this RecyclerBinder will use.
* @param layoutHandlerFactory the RecyclerBinder will use this layoutHandlerFactory when creating
* {@link ComponentTree}s in order to specify on which thread layout calculation should happen.
* @param useNewIncrementalMount
*/
public RecyclerBinder(
ComponentContext componentContext,
float rangeRatio,
LayoutInfo layoutInfo,
@Nullable LayoutHandlerFactory layoutHandlerFactory,
boolean useNewIncrementalMount) {
mComponentContext = componentContext;
mUseNewIncrementalMount = useNewIncrementalMount;
mComponentTreeHolders = new ArrayList<>();
mPendingComponentTreeHolders = new ArrayList<>();
mInternalAdapter = new InternalAdapter();
mRangeRatio = rangeRatio;
mLayoutInfo = layoutInfo;
mLayoutHandlerFactory = layoutHandlerFactory;
mCurrentFirstVisiblePosition = mCurrentLastVisiblePosition = 0;
}
public RecyclerBinder(ComponentContext c) {
this(c, 4f, new LinearLayoutInfo(c, VERTICAL, false), null, false);
}
public RecyclerBinder(ComponentContext c, LayoutInfo layoutInfo) {
this(c, 4f, layoutInfo, null, false);
}
/**
* Update the item at index position. The {@link RecyclerView} will only be notified of the item
* being updated after a layout calculation has been completed for the new {@link Component}.
*/
@UiThread
public final void updateItemAtAsync(int position, ComponentInfo componentInfo) {
ThreadUtils.assertMainThread();
// If the binder has not been measured yet we simply fall back on the sync implementation as
// nothing will really happen until we compute the first range.
if (!mIsMeasured.get()) {
updateItemAt(position, componentInfo);
return;
}
//TODO t15827349 implement async operations in RecyclerBinder.
}
/**
* Inserts an item at position. The {@link RecyclerView} will only be notified of the item being
* inserted after a layout calculation has been completed for the new {@link Component}.
*/
@UiThread
public final void insertItemAtAsync(int position, ComponentInfo componentInfo) {
ThreadUtils.assertMainThread();
// If the binder has not been measured yet we simply fall back on the sync implementation as
// nothing will really happen until we compute the first range.
if (!mIsMeasured.get()) {
insertItemAt(position, componentInfo);
return;
}
//TODO t15827349 implement async operations in RecyclerBinder.
}
/**
* Moves an item from fromPosition to toPostion. If there are other pending operations on this
* binder this will only be executed when all the operations have been completed (to ensure index
* consistency).
*/
@UiThread
public final void moveItemAsync(int fromPosition, int toPosition) {
ThreadUtils.assertMainThread();
// If the binder has not been measured yet we simply fall back on the sync implementation as
// nothing will really happen until we compute the first range.
if (!mIsMeasured.get()) {
moveItem(fromPosition, toPosition);
return;
}
//TODO t15827349 implement async operations in RecyclerBinder.
}
/**
* Removes an item from position. If there are other pending operations on this binder this will
* only be executed when all the operations have been completed (to ensure index consistency).
*/
@UiThread
public final void removeItemAtAsync(int position) {
ThreadUtils.assertMainThread();
// If the binder has not been measured yet we simply fall back on the sync implementation as
// nothing will really happen until we compute the first range.
if (!mIsMeasured.get()) {
removeItemAt(position);
return;
}
//TODO t15827349 implement async operations in RecyclerBinder.
}
/**
* See {@link RecyclerBinder#insertItemAt(int, ComponentInfo)}.
*/
@UiThread
public final void insertItemAt(int position, Component component) {
insertItemAt(position, ComponentInfo.create().component(component).build());
}
/**
* Inserts a new item at position. The {@link RecyclerView} gets notified immediately about the
* new item being inserted. If the item's position falls within the currently visible range, the
* layout is immediately computed on the] UiThread.
* The ComponentInfo contains the component that will be inserted in the Binder and extra info
* like isSticky or spanCount.
*/
@UiThread
public final void insertItemAt(int position, ComponentInfo componentInfo) {
ThreadUtils.assertMainThread();
final ComponentTreeHolder holder = ComponentTreeHolder.acquire(
componentInfo,
mLayoutHandlerFactory != null ?
mLayoutHandlerFactory.createLayoutCalculationHandler(componentInfo) :
null);
final boolean computeLayout;
final int childrenWidthSpec, childrenHeightSpec;
synchronized (this) {
mComponentTreeHolders.add(position, holder);
childrenWidthSpec = getActualChildrenWidthSpec(holder);
childrenHeightSpec = getActualChildrenHeightSpec(holder);
if (mIsMeasured.get()) {
if (mRange == null) {
initRange(
mMeasuredSize.width,
mMeasuredSize.height,
position,
childrenWidthSpec,
childrenHeightSpec,
mLayoutInfo.getScrollDirection());
computeLayout = false;
} else {
computeLayout = position >= mCurrentFirstVisiblePosition &&
position < mCurrentFirstVisiblePosition + mRange.estimatedViewportCount;
}
} else {
computeLayout = false;
}
}
if (computeLayout) {
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
}
mInternalAdapter.notifyItemInserted(position);
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
/**
* See {@link RecyclerBinder#updateItemAt(int, Component)}.
*/
@UiThread
public final void updateItemAt(int position, Component component) {
updateItemAt(position, ComponentInfo.create().component(component).build());
}
/**
* Updates the item at position. The {@link RecyclerView} gets notified immediately about the item
* being updated. If the item's position falls within the currently visible range, the layout is
* immediately computed on the UiThread.
*/
@UiThread
public final void updateItemAt(int position, ComponentInfo componentInfo) {
ThreadUtils.assertMainThread();
final ComponentTreeHolder holder;
final boolean shouldComputeLayout;
final int childrenWidthSpec, childrenHeightSpec;
synchronized (this) {
holder = mComponentTreeHolders.get(position);
shouldComputeLayout = mRange != null && position >= mCurrentFirstVisiblePosition &&
position < mCurrentFirstVisiblePosition + mRange.estimatedViewportCount;
holder.setComponentInfo(componentInfo);
childrenWidthSpec = getActualChildrenWidthSpec(holder);
childrenHeightSpec = getActualChildrenHeightSpec(holder);
}
// If we are updating an item that is currently visible we need to calculate a layout
// synchronously.
if (shouldComputeLayout) {
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
}
mInternalAdapter.notifyItemChanged(position);
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
/**
* Moves an item from fromPosition to toPosition. If the new position of the item is within the
* currently visible range, a layout is calculated immediately on the UI Thread.
*/
@UiThread
public final void moveItem(int fromPosition, int toPosition) {
ThreadUtils.assertMainThread();
final ComponentTreeHolder holder;
final boolean isNewPositionInRange, isNewPositionInVisibleRange;
final int childrenWidthSpec, childrenHeightSpec;
synchronized (this) {
holder = mComponentTreeHolders.remove(fromPosition);
mComponentTreeHolders.add(toPosition, holder);
final int mRangeSize = mRange != null ? mRange.estimatedViewportCount : -1;
isNewPositionInRange = mRangeSize > 0 &&
toPosition >= mCurrentFirstVisiblePosition - (mRangeSize * mRangeRatio) &&
toPosition <= mCurrentFirstVisiblePosition + mRangeSize + (mRangeSize * mRangeRatio);
isNewPositionInVisibleRange = mRangeSize > 0 &&
toPosition >= mCurrentFirstVisiblePosition &&
toPosition <= mCurrentFirstVisiblePosition + mRangeSize;
childrenWidthSpec = getActualChildrenWidthSpec(holder);
childrenHeightSpec = getActualChildrenHeightSpec(holder);
}
final boolean isTreeValid = holder.isTreeValid();
if (isTreeValid && !isNewPositionInRange) {
holder.acquireStateHandlerAndReleaseTree();
} else if (isNewPositionInVisibleRange && !isTreeValid) {
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
}
mInternalAdapter.notifyItemMoved(fromPosition, toPosition);
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
/**
* Removes an item from index position.
*/
@UiThread
public final void removeItemAt(int position) {
ThreadUtils.assertMainThread();
final ComponentTreeHolder holder;
synchronized (this) {
holder = mComponentTreeHolders.remove(position);
}
mInternalAdapter.notifyItemRemoved(position);
holder.release();
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
/**
* Returns the {@link ComponentTree} for the item at index position. TODO 16212132 remove
* getComponentAt from binder
*/
@Nullable
@Override
public final synchronized ComponentTree getComponentAt(int position) {
return mComponentTreeHolders.get(position).getComponentTree();
}
@Override
public final synchronized ComponentInfo getComponentInfoAt(int position) {
return mComponentTreeHolders.get(position).getComponentInfo();
}
@Override
public void bind(RecyclerView view) {
// Nothing to do here.
}
@Override
public void unbind(RecyclerView view) {
// Nothing to do here.
}
/**
* A component mounting a RecyclerView can use this method to determine its size. A Recycler that
* scrolls horizontally will leave the width unconstrained and will measure its children with a
* sizeSpec for the height matching the heightSpec passed to this method.
*
* If padding is defined on the parent component it should be subtracted from the parent size
* specs before passing them to this method.
*
* Currently we can't support the equivalent of MATCH_PARENT on the scrollDirection (so for
* example we don't support MATCH_PARENT on width in an horizontal RecyclerView). This is mainly
* because we don't have the equivalent of LayoutParams in components. We can extend the api of
* the binder in the future to provide some more layout hints in order to support this.
*
* @param outSize will be populated with the measured dimensions for this Binder.
* @param widthSpec the widthSpec to be used to measure the RecyclerView.
* @param heightSpec the heightSpec to be used to measure the RecyclerView.
*/
@Override
public synchronized void measure(Size outSize, int widthSpec, int heightSpec) {
final int scrollDirection = mLayoutInfo.getScrollDirection();
switch (scrollDirection) {
case HORIZONTAL:
if (SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException(
"Width mode has to be EXACTLY OR AT MOST for an horizontal scrolling RecyclerView");
}
break;
case VERTICAL:
if (SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED) {
throw new IllegalStateException(
"Height mode has to be EXACTLY OR AT MOST for a vertical scrolling RecyclerView");
}
break;
default:
throw new UnsupportedOperationException(
"The orientation defined by LayoutInfo should be" +
" either OrientationHelper.HORIZONTAL or OrientationHelper.VERTICAL");
}
if (mLastWidthSpec != UNINITIALIZED) {
switch (scrollDirection) {
case VERTICAL:
if (MeasureComparisonUtils.isMeasureSpecCompatible(
mLastWidthSpec,
widthSpec,
mMeasuredSize.width)) {
outSize.width = mMeasuredSize.width;
outSize.height = SizeSpec.getSize(heightSpec);
return;
}
break;
default:
if (MeasureComparisonUtils.isMeasureSpecCompatible(
mLastHeightSpec,
heightSpec,
mMeasuredSize.height)) {
outSize.width = SizeSpec.getSize(widthSpec);
outSize.height = mMeasuredSize.height;
return;
}
}
mIsMeasured.set(false);
invalidateLayoutData();
}
// We have never measured before or the measures are not valid so we need to measure now.
mLastWidthSpec = widthSpec;
mLastHeightSpec = heightSpec;
// We now need to compute the size of the non scrolling side. We try to do this by using the
// calculated range (if we have one) or computing one.
if (mRange == null && mCurrentFirstVisiblePosition < mComponentTreeHolders.size()) {
initRange(
SizeSpec.getSize(widthSpec),
SizeSpec.getSize(heightSpec),
mCurrentFirstVisiblePosition,
getActualChildrenWidthSpec(mComponentTreeHolders.get(mCurrentFirstVisiblePosition)),
getActualChildrenHeightSpec(mComponentTreeHolders.get(mCurrentFirstVisiblePosition)),
scrollDirection);
}
// At this point we might still not have a range. In this situation we should return the best
// size we can detect from the size spec and update it when the first item comes in.
// TODO 16207395.
switch (scrollDirection) {
case VERTICAL:
if (mRange != null
&& (SizeSpec.getMode(widthSpec) == SizeSpec.AT_MOST
|| SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED)) {
outSize.width = mRange.measuredSize;
} else {
outSize.width = SizeSpec.getSize(widthSpec);
}
outSize.height = SizeSpec.getSize(heightSpec);
break;
case HORIZONTAL:
outSize.width = SizeSpec.getSize(widthSpec);
if (mRange != null
&& (SizeSpec.getMode(heightSpec) == SizeSpec.AT_MOST
|| SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED)) {
outSize.height = mRange.measuredSize;
} else {
outSize.height = SizeSpec.getSize(heightSpec);
}
break;
}
mMeasuredSize = new Size(outSize.width, outSize.height);
mIsMeasured.set(true);
if (mRange != null) {
computeRange(mCurrentFirstVisiblePosition, mCurrentLastVisiblePosition);
}
}
/**
* Gets the number of items in this binder.
*/
public int getItemCount() {
return mInternalAdapter.getItemCount();
}
@GuardedBy("this")
private void invalidateLayoutData() {
mRange = null;
for (int i = 0, size = mComponentTreeHolders.size(); i < size; i++) {
mComponentTreeHolders.get(i).invalidateTree();
}
}
@GuardedBy("this")
private void initRange(
int width,
int height,
int rangeStart,
int childrenWidthSpec,
int childrenHeightSpec,
int scrollDirection) {
int nextIndexToPrepare = rangeStart;
if (nextIndexToPrepare >= mComponentTreeHolders.size()) {
return;
}
final Size size = new Size();
final ComponentTreeHolder holder = mComponentTreeHolders.get(nextIndexToPrepare);
holder.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, size);
final int rangeSize = Math.max(
mLayoutInfo.approximateRangeSize(
size.width,
size.height,
width,
height),
1);
mRange = new RangeCalculationResult();
mRange.measuredSize = scrollDirection == HORIZONTAL ? size.height : size.width;
mRange.estimatedViewportCount = rangeSize;
}
/**
* This should be called when the owner {@link Component}'s onBoundsDefined is called. It will
* inform the binder of the final measured size. The binder might decide to re-compute its
* children layouts if the measures provided here are not compatible with the ones receive in
* onMeasure.
*/
@Override
public synchronized void setSize(int width, int height) {
if (mLastWidthSpec == UNINITIALIZED || !isCompatibleSize(
SizeSpec.makeSizeSpec(width, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(height, SizeSpec.EXACTLY))) {
measure(
sDummySize,
SizeSpec.makeSizeSpec(width, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(height, SizeSpec.EXACTLY));
}
}
/**
* Call from the owning {@link Component}'s onMount. This is where the adapter is assigned to the
* {@link RecyclerView}.
*
* @param view the {@link RecyclerView} being mounted.
*/
@UiThread
@Override
public void mount(RecyclerView view) {
ThreadUtils.assertMainThread();
if (mMountedView == view) {
return;
}
if (mMountedView != null) {
unmount(mMountedView);
}
mMountedView = view;
view.setLayoutManager(mLayoutInfo.getLayoutManager());
view.setAdapter(mInternalAdapter);
view.addOnScrollListener(mRangeScrollListener);
mLayoutInfo.setComponentInfoCollection(this);
if (mCurrentFirstVisiblePosition != RecyclerView.NO_POSITION &&
mCurrentFirstVisiblePosition > 0) {
view.scrollToPosition(mCurrentFirstVisiblePosition);
}
}
/**
* Call from the owning {@link Component}'s onUnmount. This is where the adapter is removed from
* the {@link RecyclerView}.
*
* @param view the {@link RecyclerView} being unmounted.
*/
@UiThread
@Override
public void unmount(RecyclerView view) {
ThreadUtils.assertMainThread();
// We might have already unmounted this view when calling mount with a different view. In this
// case we can just return here.
if (mMountedView != view) {
return;
}
mMountedView = null;
view.removeOnScrollListener(mRangeScrollListener);
view.setAdapter(null);
view.setLayoutManager(null);
mLayoutInfo.setComponentInfoCollection(null);
}
@GuardedBy("this")
private boolean isCompatibleSize(int widthSpec, int heightSpec) {
final int scrollDirection = mLayoutInfo.getScrollDirection();
if (mLastWidthSpec != UNINITIALIZED) {
switch (scrollDirection) {
case HORIZONTAL:
return isMeasureSpecCompatible(
mLastHeightSpec,
heightSpec,
mMeasuredSize.height);
case VERTICAL:
return isMeasureSpecCompatible(
mLastWidthSpec,
widthSpec,
mMeasuredSize.width);
}
}
return false;
}
private static class RangeCalculationResult {
// The estimated number of items needed to fill the viewport.
private int estimatedViewportCount;
// The size computed for the first Component.
private int measuredSize;
}
@VisibleForTesting
void onNewVisibleRange(int firstVisiblePosition, int lastVisiblePosition) {
mCurrentFirstVisiblePosition = firstVisiblePosition;
mCurrentLastVisiblePosition = lastVisiblePosition;
computeRange(firstVisiblePosition, lastVisiblePosition);
}
private void computeRange(int firstVisible, int lastVisible) {
final int rangeSize;
final int rangeStart;
final int rangeEnd;
final int treeHoldersSize;
synchronized (this) {
if (!mIsMeasured.get() || mRange == null) {
return;
}
rangeSize = Math.max(mRange.estimatedViewportCount, lastVisible - firstVisible);
rangeStart = firstVisible - (int) (rangeSize * mRangeRatio);
rangeEnd = firstVisible + rangeSize + (int) (rangeSize * mRangeRatio);
treeHoldersSize = mComponentTreeHolders.size();
}
// TODO 16212153 optimize computeRange loop.
for (int i = 0; i < treeHoldersSize; i++) {
final ComponentTreeHolder holder;
final int childrenWidthSpec, childrenHeightSpec;
synchronized (this) {
// Someone modified the ComponentsTreeHolders while we were computing this range. We
// can just bail as another range will be computed.
if (treeHoldersSize != mComponentTreeHolders.size()) {
return;
}
holder = mComponentTreeHolders.get(i);
childrenWidthSpec = getActualChildrenWidthSpec(holder);
childrenHeightSpec = getActualChildrenHeightSpec(holder);
}
if (i >= rangeStart && i <= rangeEnd) {
if (!holder.isTreeValid()) {
holder.computeLayoutAsync(mComponentContext, childrenWidthSpec, childrenHeightSpec);
}
} else if (holder.isTreeValid()) {
holder.acquireStateHandlerAndReleaseTree();
}
}
}
@GuardedBy("this")
private int getActualChildrenWidthSpec(final ComponentTreeHolder treeHolder) {
return mLayoutInfo.getChildWidthSpec(mLastWidthSpec, treeHolder.getComponentInfo());
}
@GuardedBy("this")
private int getActualChildrenHeightSpec(final ComponentTreeHolder treeHolder) {
return mLayoutInfo.getChildHeightSpec(mLastHeightSpec, treeHolder.getComponentInfo());
}
private class RangeScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (!mUseNewIncrementalMount) {
IncrementalMountUtils.performIncrementalMount(recyclerView);
}
final int firstVisiblePosition = mLayoutInfo.findFirstVisiblePosition();
final int lastVisiblePosition = mLayoutInfo.findLastVisiblePosition();
if (firstVisiblePosition != mCurrentFirstVisiblePosition
|| lastVisiblePosition != mCurrentLastVisiblePosition) {
onNewVisibleRange(firstVisiblePosition, lastVisiblePosition);
}
}
}
private class ComponentViewHolder extends RecyclerView.ViewHolder {
public ComponentViewHolder(ComponentView componentView) {
super(componentView);
switch (mLayoutInfo.getScrollDirection()) {
case OrientationHelper.VERTICAL:
componentView.setLayoutParams(
new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
break;
default:
componentView.setLayoutParams(
new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT));
}
}
}
private class InternalAdapter extends RecyclerView.Adapter {
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ComponentViewHolder(
new ComponentView(mComponentContext, null, mUseNewIncrementalMount));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ComponentView componentView = (ComponentView) holder.itemView;
// We can ignore the synchronization here. We'll only add to this from the UiThread.
// This read only happens on the UiThread as well and we are never writing this here.
final ComponentTreeHolder componentTreeHolder = mComponentTreeHolders.get(position);
final int childrenWidthSpec = getActualChildrenWidthSpec(componentTreeHolder);
final int childrenHeightSpec = getActualChildrenHeightSpec(componentTreeHolder);
if (!componentTreeHolder.isTreeValid()) {
componentTreeHolder
.computeLayoutSync(mComponentContext, childrenWidthSpec, childrenHeightSpec, null);
}
componentView.setComponent(componentTreeHolder.getComponentTree());
}
@Override
public int getItemCount() {
// We can ignore the synchronization here. We'll only add to this from the UiThread.
// This read only happens on the UiThread as well and we are never writing this here.
return mComponentTreeHolders.size();
}
}
}
|
package org.elasticsearch.test.rest;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.ResponseListener;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
/**
* Tests that wait for refresh is fired if the index is closed.
*/
public class WaitForRefreshAndCloseIT extends ESRestTestCase {
@Before
public void setupIndex() throws IOException {
Request request = new Request("PUT", "/test");
request.setJsonEntity("{\"settings\":{\"refresh_interval\":-1}}");
client().performRequest(request);
}
@After
public void cleanupIndex() throws IOException {
client().performRequest(new Request("DELETE", "/test"));
}
private String docPath() {
return "test/_doc/1";
}
public void testIndexAndThenClose() throws Exception {
Request request = new Request("PUT", docPath());
request.setJsonEntity("{\"test\":\"test\"}");
closeWhileListenerEngaged(start(request));
}
public void testUpdateAndThenClose() throws Exception {
Request createDoc = new Request("PUT", docPath());
createDoc.setJsonEntity("{\"test\":\"test\"}");
client().performRequest(createDoc);
Request updateDoc = new Request("POST", "test/_update/1");
updateDoc.setJsonEntity("{\"doc\":{\"name\":\"test\"}}");
closeWhileListenerEngaged(start(updateDoc));
}
public void testDeleteAndThenClose() throws Exception {
Request request = new Request("PUT", docPath());
request.setJsonEntity("{\"test\":\"test\"}");
client().performRequest(request);
closeWhileListenerEngaged(start(new Request("DELETE", docPath())));
}
private void closeWhileListenerEngaged(ActionFuture<String> future) throws Exception {
// Wait for the refresh listener to start waiting
assertBusy(() -> {
Map<String, Object> stats;
try {
stats = entityAsMap(client().performRequest(new Request("GET", "/test/_stats/refresh")));
} catch (IOException e) {
throw new RuntimeException(e);
}
Map<?, ?> indices = (Map<?, ?>) stats.get("indices");
Map<?, ?> theIndex = (Map<?, ?>) indices.get("test");
Map<?, ?> total = (Map<?, ?>) theIndex.get("total");
Map<?, ?> refresh = (Map<?, ?>) total.get("refresh");
int listeners = (Integer) refresh.get("listeners");
assertEquals(1, listeners);
}, 30L, TimeUnit.SECONDS);
// Close the index. That should flush the listener.
client().performRequest(new Request("POST", "/test/_close"));
/*
* The request may fail, but we really, really, really want to make
* sure that it doesn't time out.
*/
try {
future.get(1, TimeUnit.MINUTES);
} catch (ExecutionException ee) {
/*
* If it *does* fail it should fail with a FORBIDDEN error because
* it attempts to take an action on a closed index. Again, it'd be
* nice if all requests waiting for refresh came back even though
* the index is closed and most do, but sometimes they bump into
* the index being closed. At least they don't hang forever. That'd
* be a nightmare.
*/
assertThat(ee.getCause(), instanceOf(ResponseException.class));
ResponseException re = (ResponseException) ee.getCause();
assertEquals(403, re.getResponse().getStatusLine().getStatusCode());
assertThat(EntityUtils.toString(re.getResponse().getEntity()), containsString("FORBIDDEN/4/index closed"));
}
}
private ActionFuture<String> start(Request request) {
PlainActionFuture<String> future = new PlainActionFuture<>();
request.addParameter("refresh", "wait_for");
request.addParameter("error_trace", "");
client().performRequestAsync(request, new ResponseListener() {
@Override
public void onSuccess(Response response) {
try {
future.onResponse(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
future.onFailure(e);
}
}
@Override
public void onFailure(Exception exception) {
future.onFailure(exception);
}
});
return future;
}
}
|
package org.jboss.as.logging;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.helpers.ClientConstants;
import org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder;
import org.jboss.as.controller.services.path.PathResourceDefinition;
import org.jboss.as.controller.transform.OperationTransformer.TransformedOperation;
import org.jboss.as.logging.logmanager.ConfigurationPersistence;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.FailedOperationTransformationConfig.RejectExpressionsConfig;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.as.subsystem.test.SubsystemOperations;
import org.jboss.dmr.ModelNode;
import org.jboss.logmanager.LogContext;
import org.junit.Assert;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
public class LoggingSubsystemTestCase extends AbstractLoggingSubsystemTest {
// Color pattern
private static final Pattern COLOR_PATTERN = Pattern.compile("(%K\\{[a-zA-Z]*?})");
@Override
protected String getSubsystemXml() throws IOException {
return readResource("/logging.xml");
}
@Test
public void testExpressions() throws Exception {
standardSubsystemTest("/expressions.xml");
}
@Test
public void testConfiguration() throws Exception {
final KernelServices kernelServices = boot();
final ModelNode currentModel = getSubsystemModel(kernelServices);
compare(currentModel, ConfigurationPersistence.getConfigurationPersistence(LogContext.getLogContext()));
// Compare properties written out to current model
final String dir = resolveRelativePath(kernelServices, "jboss.server.config.dir");
Assert.assertNotNull("jboss.server.config.dir could not be resolved", dir);
final LogContext logContext = LogContext.create();
final ConfigurationPersistence config = ConfigurationPersistence.getOrCreateConfigurationPersistence(logContext);
final FileInputStream in = new FileInputStream(new File(dir, "logging.properties"));
config.configure(in);
compare(currentModel, config);
}
@Test
public void testTransformers712() throws Exception {
testTransformer1_1_0("org.jboss.as:jboss-as-logging:7.1.2.Final");
}
@Test
public void testTransformers713() throws Exception {
testTransformer1_1_0("org.jboss.as:jboss-as-logging:7.1.3.Final");
}
@Test
public void testRejectExpressions712() throws Exception {
testRejectExpressions1_1_0("org.jboss.as:jboss-as-logging:7.1.2.Final");
}
@Test
public void testRejectExpressions713() throws Exception {
testRejectExpressions1_1_0("org.jboss.as:jboss-as-logging:7.1.3.Final");
}
private void testTransformer1_1_0(final String gav) throws Exception {
final String subsystemXml = getSubsystemXml();
final ModelVersion modelVersion = ModelVersion.create(1, 1, 0);
final KernelServicesBuilder builder = createKernelServicesBuilder(LoggingTestEnvironment.getManagementInstance())
.setSubsystemXml(subsystemXml);
// Create the legacy kernel
builder.createLegacyKernelServicesBuilder(LoggingTestEnvironment.getManagementInstance(), modelVersion)
.addMavenResourceURL(gav);
KernelServices mainServices = builder.build();
KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
Assert.assertNotNull(legacyServices);
final ModelNode legacyModel = checkSubsystemModelTransformation(mainServices, modelVersion);
testTransformOperations(mainServices, modelVersion, legacyModel);
}
private void testRejectExpressions1_1_0(final String gav) throws Exception {
final ModelVersion modelVersion = ModelVersion.create(1, 1, 0);
final KernelServicesBuilder builder = createKernelServicesBuilder(LoggingTestEnvironment.getManagementInstance());
// Create the legacy kernel
builder.createLegacyKernelServicesBuilder(LoggingTestEnvironment.getManagementInstance(), modelVersion)
.addMavenResourceURL(gav);
KernelServices mainServices = builder.build();
KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
Assert.assertNotNull(legacyServices);
Assert.assertTrue("main services did not boot", mainServices.isSuccessfulBoot());
Assert.assertTrue(legacyServices.isSuccessfulBoot());
final List<ModelNode> ops = builder.parseXmlResource("/expressions.xml");
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, modelVersion, ops,
new FailedOperationTransformationConfig()
.addFailedAttribute(createRootLoggerAddress(),
new RejectExpressionsConfig(RootLoggerResourceDefinition.EXPRESSION_ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(LoggerResourceDefinition.LOGGER_PATH),
new RejectExpressionsConfig(LoggerResourceDefinition.EXPRESSION_ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(AsyncHandlerResourceDefinition.ASYNC_HANDLER_PATH),
new RejectExpressionsConfig(AsyncHandlerResourceDefinition.ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(ConsoleHandlerResourceDefinition.CONSOLE_HANDLER_PATH),
new RejectExpressionsConfig(ConsoleHandlerResourceDefinition.ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(FileHandlerResourceDefinition.FILE_HANDLER_PATH),
new RejectExpressionsConfig(FileHandlerResourceDefinition.ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(PeriodicHandlerResourceDefinition.PERIODIC_HANDLER_PATH),
new RejectExpressionsConfig(PeriodicHandlerResourceDefinition.ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(SizeRotatingHandlerResourceDefinition.SIZE_ROTATING_HANDLER_PATH),
new RejectExpressionsConfig(SizeRotatingHandlerResourceDefinition.ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(CustomHandlerResourceDefinition.CUSTOM_HANDLE_PATH),
new RejectExpressionsConfig(CustomHandlerResourceDefinition.WRITABLE_ATTRIBUTES))
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(CommonAttributes.LOGGING_PROFILE),
FailedOperationTransformationConfig.DISCARDED_RESOURCE)
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(CommonAttributes.LOGGING_PROFILE).append(ConsoleHandlerResourceDefinition.CONSOLE_HANDLER_PATH),
FailedOperationTransformationConfig.DISCARDED_RESOURCE)
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(CommonAttributes.LOGGING_PROFILE).append(RootLoggerResourceDefinition.ROOT_LOGGER_PATH),
FailedOperationTransformationConfig.DISCARDED_RESOURCE)
.addFailedAttribute(SUBSYSTEM_ADDRESS.append(CommonAttributes.LOGGING_PROFILE).append(LoggerResourceDefinition.LOGGER_PATH),
FailedOperationTransformationConfig.DISCARDED_RESOURCE)
);
}
private void testTransformOperations(final KernelServices mainServices, final ModelVersion modelVersion, final ModelNode legacyModel) throws Exception {
final PathAddress consoleAddress = createConsoleHandlerAddress("CONSOLE");
// Get all the console handler
final ModelNode consoleHandler = legacyModel.get(consoleAddress.getElement(0).getKey(), consoleAddress.getElement(0).getValue(),
consoleAddress.getElement(1).getKey(), consoleAddress.getElement(1).getValue());
String formatPattern = consoleHandler.get(CommonAttributes.FORMATTER.getName()).asString();
Assert.assertFalse("Pattern (" + formatPattern + ") contains a color attribute not supported in legacy models.", COLOR_PATTERN.matcher(formatPattern).find());
// Write a pattern with a %K{level} to ensure it gets removed
ModelNode op = SubsystemOperations.createWriteAttributeOperation(consoleAddress.toModelNode(), CommonAttributes.FORMATTER, "%K{level}" + formatPattern);
executeTransformOperation(mainServices, modelVersion, op);
validateLegacyFormatter(mainServices, modelVersion, consoleAddress.toModelNode());
// Test update properties
op = SubsystemOperations.createOperation(AbstractHandlerDefinition.UPDATE_OPERATION_NAME, consoleAddress.toModelNode());
op.get(CommonAttributes.FORMATTER.getName()).set("%K{level}" + formatPattern);
executeTransformOperation(mainServices, modelVersion, op);
validateLegacyFormatter(mainServices, modelVersion, consoleAddress.toModelNode());
// Write out a filter-spec
final String filterExpression = "not(match(\"ARJUNA\\\\d\"))";
op = SubsystemOperations.createWriteAttributeOperation(consoleAddress.toModelNode(), CommonAttributes.FILTER_SPEC, filterExpression);
executeTransformOperation(mainServices, modelVersion, op);
validateLegacyFilter(mainServices, modelVersion, consoleAddress.toModelNode(), filterExpression);
// update-propertes on a filter spec
op = SubsystemOperations.createOperation(AbstractHandlerDefinition.UPDATE_OPERATION_NAME, consoleAddress.toModelNode());
op.get(CommonAttributes.FILTER_SPEC.getName()).set(filterExpression);
executeTransformOperation(mainServices, modelVersion, op);
validateLegacyFilter(mainServices, modelVersion, consoleAddress.toModelNode(), filterExpression);
final PathAddress loggerAddress = createLoggerAddress("org.jboss.as.logging");
// Verify the logger exists, add if it doesn't
op = SubsystemOperations.createReadResourceOperation(loggerAddress.toModelNode());
if (!SubsystemOperations.isSuccessfulOutcome(mainServices.executeOperation(op))) {
op = SubsystemOperations.createAddOperation(loggerAddress.toModelNode());
executeTransformOperation(mainServices, modelVersion, op);
}
// write a filter-spec
op = SubsystemOperations.createWriteAttributeOperation(loggerAddress.toModelNode(), CommonAttributes.FILTER_SPEC, filterExpression);
executeTransformOperation(mainServices, modelVersion, op);
validateLegacyFilter(mainServices, modelVersion, loggerAddress.toModelNode(), filterExpression);
// create a new handler
final PathAddress handlerAddress = createFileHandlerAddress("fh");
op = SubsystemOperations.createAddOperation(handlerAddress.toModelNode());
op.get(CommonAttributes.FILE.getName(), PathResourceDefinition.RELATIVE_TO.getName()).set("jboss.server.log.dir");
op.get(CommonAttributes.FILE.getName(), PathResourceDefinition.PATH.getName()).set("fh.log");
op.get(CommonAttributes.AUTOFLUSH.getName()).set(true);
executeTransformOperation(mainServices, modelVersion, op);
// add/remove the handler to the root logger
final PathAddress rootLoggerAddress = createRootLoggerAddress();
final String handlerName = handlerAddress.getLastElement().getValue();
addRemoveHandler(mainServices, modelVersion, rootLoggerAddress.toModelNode(), CommonAttributes.HANDLERS, handlerName);
// add/remove the handler to a logger
addRemoveHandler(mainServices, modelVersion, loggerAddress.toModelNode(), CommonAttributes.HANDLERS, handlerName);
// add/remove from an async-handler
final PathAddress asyncHandlerAddress = createAsyncHandlerAddress("async");
addRemoveHandler(mainServices, modelVersion, asyncHandlerAddress.toModelNode(), AsyncHandlerResourceDefinition.SUBHANDLERS, handlerName);
// Test a composite operation
final CompositeOperationBuilder compositeOperationBuilder = CompositeOperationBuilder.create();
// Add a logger which should add a category attribute after transformation
final ModelNode compositeLoggerAddress = createLoggerAddress("compositeLogger").toModelNode();
compositeOperationBuilder.addStep(SubsystemOperations.createAddOperation(compositeLoggerAddress));
// Remove the file handler, then re-add it with the enabled attribute that should be removed
compositeOperationBuilder.addStep(SubsystemOperations.createRemoveOperation(handlerAddress.toModelNode()));
op = SubsystemOperations.createAddOperation(handlerAddress.toModelNode());
op.get(CommonAttributes.FILE.getName(), PathResourceDefinition.RELATIVE_TO.getName()).set("jboss.server.log.dir");
op.get(CommonAttributes.FILE.getName(), PathResourceDefinition.PATH.getName()).set("fh.log");
op.get(CommonAttributes.AUTOFLUSH.getName()).set(true);
op.get(CommonAttributes.ENABLED.getName()).set(true);
compositeOperationBuilder.addStep(op);
compositeOperationBuilder.addStep(SubsystemOperations.createAddOperation(createAddress(CommonAttributes.LOGGING_PROFILE, "composite-profile").toModelNode()));
// Transform the operation
final TransformedOperation transformedOp = mainServices.transformOperation(modelVersion, compositeOperationBuilder.build().getOperation());
op = transformedOp.getTransformedOperation();
// Iterate the steps and look for specific changes in the operation
final List<ModelNode> steps = op.get(ClientConstants.STEPS).asList();
// There should only be 3 steps as the logging-profile should have been removed
Assert.assertEquals("Logging profile step should have been removed", 3, steps.size());
// First step should be the logger
ModelNode stepOp = steps.get(0);
// Verify the category was added
Assert.assertTrue("category attribute should have been added", stepOp.hasDefined(LoggerResourceDefinition.CATEGORY.getName()));
// Third operation should the adding the handler
stepOp = steps.get(2);
// Verify the enabled attribute was removed
Assert.assertFalse("enabled attribute should have been removed", stepOp.hasDefined(CommonAttributes.ENABLED.getName()));
executeTransformOperation(mainServices, modelVersion, transformedOp);
}
private static ModelNode executeTransformOperation(final KernelServices kernelServices, final ModelVersion modelVersion, final ModelNode op) throws OperationFailedException {
return executeTransformOperation(kernelServices, modelVersion, kernelServices.transformOperation(modelVersion, op));
}
private static ModelNode executeTransformOperation(final KernelServices kernelServices, final ModelVersion modelVersion, final TransformedOperation transformedOp) throws OperationFailedException {
ModelNode result = kernelServices.executeOperation(modelVersion, transformedOp);
Assert.assertTrue(result.asString(), SubsystemOperations.isSuccessfulOutcome(result));
return result;
}
private static void addRemoveHandler(final KernelServices kernelServices, final ModelVersion modelVersion, final ModelNode address,
final AttributeDefinition handlerAttribute, final String handlerName) throws OperationFailedException {
// Add the handler
ModelNode op = SubsystemOperations.createOperation(CommonAttributes.ADD_HANDLER_OPERATION_NAME, address);
op.get(CommonAttributes.HANDLER_NAME.getName()).set(handlerName);
executeTransformOperation(kernelServices, modelVersion, op);
// Verify the handler was added
final ModelNode readOp = SubsystemOperations.createReadAttributeOperation(address, handlerAttribute);
ModelNode result = executeTransformOperation(kernelServices, modelVersion, readOp);
Assert.assertTrue("Handler (" + handlerName + ") not found on the resource: " + address, SubsystemOperations.readResultAsList(result).contains(handlerName));
// Remove the handler
op = SubsystemOperations.createOperation(CommonAttributes.REMOVE_HANDLER_OPERATION_NAME, address);
op.get(CommonAttributes.HANDLER_NAME.getName()).set(handlerName);
executeTransformOperation(kernelServices, modelVersion, op);
// Verify the handler was removed
result = executeTransformOperation(kernelServices, modelVersion, readOp);
Assert.assertFalse("Handler (" + handlerName + ") was not removed on the resource: " + address, SubsystemOperations.readResultAsList(result).contains(handlerName));
}
private static void validateLegacyFormatter(final KernelServices kernelServices, final ModelVersion modelVersion, final ModelNode address) throws OperationFailedException {
final ModelNode op = SubsystemOperations.createReadAttributeOperation(address, CommonAttributes.FORMATTER);
final ModelNode result = executeTransformOperation(kernelServices, modelVersion, op);
Assert.assertTrue(result.asString(), SubsystemOperations.isSuccessfulOutcome(result));
final String formatPattern = SubsystemOperations.readResultAsString(result);
Assert.assertFalse("Pattern (" + formatPattern + ") contains a color attribute not supported in legacy models.", COLOR_PATTERN.matcher(formatPattern).find());
}
private static void validateLegacyFilter(final KernelServices kernelServices, final ModelVersion modelVersion, final ModelNode address, final String filterExpression) throws OperationFailedException {
ModelNode op = SubsystemOperations.createReadResourceOperation(address);
ModelNode result = executeTransformOperation(kernelServices, modelVersion, op);
// No filter-spec should be there
Assert.assertFalse("filter-spec found at: " + address.asString(), result.has(CommonAttributes.FILTER_SPEC.getName()));
op = SubsystemOperations.createReadAttributeOperation(address, CommonAttributes.FILTER);
result = executeTransformOperation(kernelServices, modelVersion, op);
Assert.assertEquals("Transformed spec does not match filter expression.", Filters.filterToFilterSpec(SubsystemOperations.readResult(result)), filterExpression);
}
}
|
package com.opcoach.training.e4.rental.ui.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import com.opcoach.e4tester.core.E4TestCase;
import com.opcoach.training.e4.rental.ui.parts.RentalPropertyPart;
import com.opcoach.training.rental.Rental;
import com.opcoach.training.rental.RentalAgency;
public class RentalPropertyTest extends E4TestCase {
MPart part;
@BeforeEach
public void setUp() throws Exception {
System.out.println("execute RentalPropertyTest");
// Create the property part for the test...
part = createTestPart("Rental Property", RentalPropertyPart.VIEW_ID, RentalPropertyPart.class);
}
/** Simulate a rental selection in the UI */
private Rental selectRental(int i) {
Rental r = getContext().get(RentalAgency.class).getRentals().get(i);
System.out.println("Current selected rental is : " + r);
getSync().syncExec(()->getSelectionService().setSelection(r));
wait1second();
return r;
}
@Test
@Order(1)
public void testCreatePart() throws InterruptedException {
Rental r = selectRental(0);
assertNotNull(part, "The rentalPropertyPart must be created");
// Test it must contains the expected value of the default rental object
String objectLabel = getTextWidgetValue(part, "rentedObjectLabel");
assertEquals("Perceuse Electrique", objectLabel, "The default rental must display 'Perceuse Electrique'");
}
@Test
@Order(2)
public void testSetSelection() {
Rental r = selectRental(1);
assertEquals(r.getCustomer().getDisplayName(),
getTextWidgetValue(part, "customerNameLabel"),
"Customer Name displayed is not correct");
}
@Test
@Order(3)
@DisplayName("Test if a rental is selected, and then a customer")
public void testSetTwoSelections() {
// Select a rental (that will update property view)
Rental r = selectRental(1);
assertEquals(r.getCustomer().getDisplayName(),
getTextWidgetValue(part, "customerNameLabel"), "Customer Name displayed is not correct");
// Then select a customer (that must not be received by property view)
}
}
|
package org.fusesource.fabric.apollo.amqp.generator;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.List;
/**
* A Maven Mojo so that the AMQP compiler can be used with maven.
*
* @goal compile
* @phase process-sources
*/
public class AmqpMojo extends AbstractMojo {
/**
* The maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject project;
/**
* The directory containing the project source
*
* @parameter default=value="${basedir}/src/main/java"
*
*/
private File sourceDirectory;
/**
* The directory where the amqp spec files (<code>*.xml</code>) are
* located.
*
* @parameter default-value="${basedir}/src/main/amqp"
*/
private File mainSourceDirectory;
/**
* The directory where the output files will be located.
*
* @parameter default-value="${project.build.directory}/generated-sources/amqp"
*/
private File mainOutputDirectory;
/**
* The directory where the amqp spec files (<code>*.xml</code>) are
* located.
*
* @parameter default-value="${basedir}/src/test/amqp"
*/
private File testSourceDirectory;
/**
* The directory where the output files will be located.
*
* @parameter default-value="${project.build.directory}/test-generated-sources/amqp"
*/
private File testOutputDirectory;
/**
* The package prefix to put the generated Java classes in
*
* @parameter default-value="org.fusesource.fabric.apollo.amqp.codec"
*/
private String packagePrefix;
public void execute() throws MojoExecutionException {
File[] mainFiles = null;
if ( mainSourceDirectory.exists() ) {
mainFiles = mainSourceDirectory.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".xml");
}
});
if (mainFiles==null || mainFiles.length==0) {
getLog().warn("No amqp spec files found in directory: " + mainSourceDirectory.getPath());
} else {
processFiles(mainFiles, mainOutputDirectory);
this.project.addCompileSourceRoot(mainOutputDirectory.getAbsolutePath());
}
}
File[] testFiles = null;
if ( testSourceDirectory.exists() ) {
testFiles = testSourceDirectory.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".xml");
}
});
if (testFiles==null || testFiles.length==0) {
getLog().warn("No amqp spec files found in directory: " + testSourceDirectory.getPath());
} else {
processFiles(testFiles, testOutputDirectory);
this.project.addTestCompileSourceRoot(testOutputDirectory.getAbsolutePath());
}
}
}
private void processFiles(File[] mainFiles, File outputDir) throws MojoExecutionException {
List<File> recFiles = Arrays.asList(mainFiles);
for (File file : recFiles) {
getLog().info("Compiling: "+file.getPath());
}
try {
Utils.LOG = getLog();
Generator gen = new Generator();
gen.setInputFiles(mainFiles);
gen.setOutputDirectory(outputDir);
gen.setSourceDirectory(sourceDirectory);
gen.setPackagePrefix(packagePrefix);
gen.generate();
} catch (Exception e) {
getLog().error("Error generating code : " + e + " - " + e.getMessage(), e);
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
|
package com.nepxion.matrix.aop;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import com.nepxion.matrix.constant.MatrixConstant;
import com.nepxion.matrix.exception.MatrixException;
import com.nepxion.matrix.util.MatrixUtil;
public abstract class AbstractInterceptor implements MethodInterceptor {
// Java8IDEMaven"-parameters"Compiler Argument
private ParameterNameDiscoverer standardReflectionParameterNameDiscoverer = new StandardReflectionParameterNameDiscoverer();
// CGLIG(ASM library)
private ParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
public boolean isCglibAopProxy(MethodInvocation invocation) {
return getProxyClassName(invocation).contains(MatrixConstant.CGLIB);
}
public String getProxyType(MethodInvocation invocation) {
boolean isCglibAopProxy = isCglibAopProxy(invocation);
if (isCglibAopProxy) {
return MatrixConstant.PROXY_TYPE_CGLIB;
} else {
return MatrixConstant.PROXY_TYPE_REFLECTIVE;
}
}
public Class<?> getProxyClass(MethodInvocation invocation) {
return invocation.getClass();
}
public String getProxyClassName(MethodInvocation invocation) {
return getProxyClass(invocation).getCanonicalName();
}
public Object getProxiedObject(MethodInvocation invocation) {
return invocation.getThis();
}
public Class<?> getProxiedClass(MethodInvocation invocation) {
return getProxiedObject(invocation).getClass();
}
public String getProxiedClassName(MethodInvocation invocation) {
return getProxiedClass(invocation).getCanonicalName();
}
public Class<?>[] getProxiedInterfaces(MethodInvocation invocation) {
return getProxiedClass(invocation).getInterfaces();
}
public Annotation[] getProxiedClassAnnotations(MethodInvocation invocation) {
return getProxiedClass(invocation).getAnnotations();
}
public Method getMethod(MethodInvocation invocation) {
return invocation.getMethod();
}
public String getMethodName(MethodInvocation invocation) {
return getMethod(invocation).getName();
}
public Object[] getArguments(MethodInvocation invocation) {
return invocation.getArguments();
}
public String[] getParameterNames(MethodInvocation invocation) {
Method method = getMethod(invocation);
boolean isCglibAopProxy = isCglibAopProxy(invocation);
if (isCglibAopProxy) {
return localVariableTableParameterNameDiscoverer.getParameterNames(method);
} else {
return standardReflectionParameterNameDiscoverer.getParameterNames(method);
}
}
public Annotation[] getMethodAnnotations(MethodInvocation invocation) {
return getMethod(invocation).getAnnotations();
}
// doXX(@MyAnnotation String id)MyAnnotationStringid
// 1. parameterAnnotationType
// 2. parameterAnnotationTypeparameterType
// 3. parameterAnnotationTypenull
@SuppressWarnings("unchecked")
public <T> T getValueByParameterAnnotation(MethodInvocation invocation, Class<?> parameterAnnotationType, Class<T> parameterType) {
Method method = invocation.getMethod();
Class<?>[] parameterTypes = method.getParameterTypes();
String parameterTypesValue = MatrixUtil.toString(parameterTypes);
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Object[] arguments = invocation.getArguments();
if (ArrayUtils.isEmpty(parameterAnnotations)) {
throw new MatrixException("Not found any annotations");
}
T value = null;
int annotationIndex = 0;
int valueIndex = 0;
for (Annotation[] parameterAnnotation : parameterAnnotations) {
for (Annotation annotation : parameterAnnotation) {
if (annotation.annotationType() == parameterAnnotationType) {
// value
if (value != null) {
throw new MatrixException("Only 1 annotation=" + parameterAnnotationType.getName() + " can be added in method [name=" + method.getName() + ", parameterTypes=" + parameterTypesValue + "]");
}
Object object = arguments[valueIndex];
if (object == null) {
throw new MatrixException("Value for annotation=" + parameterAnnotationType.getName() + " in method [name=" + method.getName() + ", parameterTypes=" + parameterTypesValue + "] is null");
}
if (object.getClass() != parameterType) {
throw new MatrixException("Type for annotation=" + parameterAnnotationType.getName() + " in method [name=" + method.getName() + ", parameterTypes=" + parameterTypesValue + "] must be " + parameterType.getName());
}
value = (T) object;
annotationIndex++;
}
}
valueIndex++;
}
if (annotationIndex == 0) {
throw new MatrixException("Not found annotation=" + parameterAnnotationType.getName() + " in method [name=" + method.getName() + ", parameterTypes=" + parameterTypesValue + "]");
}
return value;
}
public String getSpelKey(MethodInvocation invocation, String prefix, String name, String key) {
String[] parameterNames = getParameterNames(invocation);
Object[] arguments = getArguments(invocation);
// SPELKey
ExpressionParser parser = new SpelExpressionParser();
// SPEL
EvaluationContext context = new StandardEvaluationContext();
// SPEL
for (int i = 0; i < parameterNames.length; i++) {
context.setVariable(parameterNames[i], arguments[i]);
}
return prefix + "_" + name + "_" + parser.parseExpression(key).getValue(context, String.class);
}
}
|
package org.multibit.hd.core.dto;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import org.bitcoin.protocols.payments.Protos;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.protocols.payments.PaymentSession;
import org.joda.time.DateTime;
import org.multibit.hd.core.utils.Dates;
import java.util.UUID;
/**
* <p>DTO to provide the following to WalletService:</p>
* <ul>
* <li>Additional payment protocol (BIP70) payment request info</li>
* </ul>
*/
public class PaymentRequestData implements PaymentData {
/**
* A UUID used in persisting the BIP70 payment request and as a foreign key to find data from the transaction hash
*/
private UUID uuid;
/**
* The transaction hash of the transaction that paid this payment request.
* May be absent if the payment request has not been paid yet.
*/
private Optional<Sha256Hash> transactionHash = Optional.absent();
/**
* The fiat payment equivalent of the payment Coin
*/
private Optional<FiatPayment> fiatPayment = Optional.absent();
/**
* The BIP70 PaymentRequest - stored as a file on the file system and provided externally
*/
private Optional<Protos.PaymentRequest> paymentRequest = Optional.absent();
/**
* The BIP70 Payment - stored as a file on the file system when present
*/
private Optional<Protos.Payment> payment = Optional.absent();
/**
* The BIP70 PaymentACK - stored as a file on the file system when present
*/
private Optional<Protos.PaymentACK> paymentACK = Optional.absent();
/**
* The Payment Session Summary wrapping the final state of the BIP70 PaymentSession
* This provides additional PKI verification information and ensures that the
* PaymentSession isn't persisted
*/
private Optional<PaymentSessionSummary> paymentSessionSummary = Optional.absent();
/**
* The date of the payment request
*/
private DateTime date;
/**
* The amount in bitcoin of the payment request
*/
private Coin amountCoin;
/**
* The description of the payment request
*/
private String note = "";
/**
* The display name of the PKI identity
*/
private String identityDisplayName = "";
/**
* The trust status - whether the PKI verify was successful
*/
private PaymentSessionStatus trustStatus;
/**
* If the trust status is ERROR or DOWN, a localised text string describing the problem
*/
private String trustErrorMessage = "";
/**
* The expiration date for the payment request
*/
private DateTime expirationDate;
/**
* For protobuf - you probably do not want to use this
*/
public PaymentRequestData() {
}
/**
* Build the PaymentRequestData from a PaymentSessionSummary
*
* @param paymentSessionSummary The Payment Session Summary with a PaymentSession
*/
public PaymentRequestData(PaymentSessionSummary paymentSessionSummary) {
this(Optional.of(paymentSessionSummary.getPaymentSession().get().getPaymentRequest()), Optional.<Sha256Hash>absent());
this.paymentSessionSummary = Optional.of(paymentSessionSummary);
PaymentSession paymentSession = paymentSessionSummary.getPaymentSession().get();
setDate(new DateTime(paymentSession.getDate()));
if (paymentSession.getExpires() == null) {
// Expire a long way into the future
setExpirationDate(Dates.thenUtc(2199, 12,31, 23, 59 ,59));
} else {
setExpirationDate(new DateTime(paymentSession.getExpires()));
}
setAmountCoin(paymentSession.getValue());
setNote(paymentSession.getMemo());
if (paymentSessionSummary.getPkiVerificationData().isPresent()) {
setIdentityDisplayName(paymentSessionSummary.getPkiVerificationData().get().displayName);
}
}
/**
* See also the
* @param paymentRequest A PaymentRequest
* @param transactionHash A transaction hash if a Bitcoin transaction has been successfully broadcast
*/
public PaymentRequestData(Optional<Protos.PaymentRequest> paymentRequest, Optional<Sha256Hash> transactionHash) {
Preconditions.checkNotNull(paymentRequest);
Preconditions.checkNotNull(transactionHash);
this.paymentRequest = paymentRequest;
this.transactionHash = transactionHash;
this.uuid = UUID.randomUUID();
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public Optional<Sha256Hash> getTransactionHash() {
return transactionHash;
}
public void setTransactionHash(Optional<Sha256Hash> transactionHash) {
this.transactionHash = transactionHash;
}
public Optional<Protos.PaymentRequest> getPaymentRequest() {
return paymentRequest;
}
public void setPaymentRequest(Optional<Protos.PaymentRequest> paymentRequest) {
this.paymentRequest = paymentRequest;
}
public void setPayment(Optional<Protos.Payment> payment) {
this.payment = payment;
}
public void setPaymentACK(Optional<Protos.PaymentACK> paymentACK) {
this.paymentACK = paymentACK;
}
@Override
public PaymentType getType() {
if (transactionHash.isPresent()) {
return PaymentType.PAID;
} else {
return PaymentType.THEY_REQUESTED;
}
}
@Override
public PaymentStatus getStatus() {
if (transactionHash.isPresent()) {
return new PaymentStatus(RAGStatus.GREEN, CoreMessageKey.PAYMENT_PAID);
} else {
return new PaymentStatus(RAGStatus.PINK, CoreMessageKey.PAYMENT_REQUESTED_BY_THEM);
}
}
@Override
public DateTime getDate() {
return date;
}
public void setDate(DateTime date) {
this.date = date;
}
@Override
public Coin getAmountCoin() {
return amountCoin;
}
public void setAmountCoin(Coin amountBTC) {
this.amountCoin = amountBTC;
}
public void setAmountFiat(FiatPayment fiatPayment) {
this.fiatPayment = Optional.of(fiatPayment);
}
@Override
public FiatPayment getAmountFiat() {
if (fiatPayment.isPresent()) {
return fiatPayment.get();
} else {
return new FiatPayment();
}
}
@Override
public String getNote() {
return note;
}
@Override
public String getDescription() {
return getNote();
}
public void setNote(String note) {
this.note = note;
}
@Override
public boolean isCoinBase() {
return false;
}
public String getIdentityDisplayName() {
return identityDisplayName;
}
public void setIdentityDisplayName(String identityDisplayName) {
this.identityDisplayName = identityDisplayName;
}
public PaymentSessionStatus getTrustStatus() {
return trustStatus;
}
public void setTrustStatus(PaymentSessionStatus trustStatus) {
this.trustStatus = trustStatus;
}
public String getTrustErrorMessage() {
return trustErrorMessage;
}
public void setTrustErrorMessage(String trustErrorMessage) {
this.trustErrorMessage = trustErrorMessage;
}
public DateTime getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(DateTime expirationDate) {
this.expirationDate = expirationDate;
}
public Optional<FiatPayment> getFiatPayment() {
return fiatPayment;
}
public Optional<PaymentSessionSummary> getPaymentSessionSummary() {
return paymentSessionSummary;
}
/**
* @return The BIP70 Payment sent to the server once payment was successfully broadcast
*/
public Optional<Protos.Payment> getPayment() {
return payment;
}
/**
* @return The BIP70 PaymentACK received from the server
*/
public Optional<Protos.PaymentACK> getPaymentACK() {
return paymentACK;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaymentRequestData that = (PaymentRequestData) o;
if (!uuid.equals(that.uuid)) {
return false;
}
if (!date.equals(that.date)) {
return false;
}
return amountCoin.equals(that.amountCoin);
}
@Override
public int hashCode() {
int result = uuid.hashCode();
result = 31 * result + date.hashCode();
result = 31 * result + amountCoin.hashCode();
return result;
}
@Override
public String toString() {
return "PaymentRequestData{" +
"amountBTC=" + amountCoin +
", uuid=" + uuid +
", transactionHash=" + transactionHash +
", fiatPayment=" + fiatPayment +
", paymentRequest=" + paymentRequest +
", payment=" + payment +
", paymentACK=" + paymentACK +
", paymentSessionSummary=" + paymentSessionSummary +
", date=" + date +
", note='" + note + '\'' +
", identityDisplayName='" + identityDisplayName + '\'' +
", trustStatus=" + trustStatus +
", trustErrorMessage='" + trustErrorMessage + '\'' +
", expirationDate=" + expirationDate +
'}';
}
}
|
package org.multibit.hd.core.managers;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.common.primitives.Bytes;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import org.bitcoinj.core.*;
import org.bitcoinj.crypto.*;
import org.bitcoinj.script.Script;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.UnreadableWalletException;
import org.bitcoinj.store.WalletProtobufSerializer;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.Protos;
import org.joda.time.DateTime;
import org.multibit.hd.brit.crypto.AESUtils;
import org.multibit.hd.brit.dto.FeeState;
import org.multibit.hd.brit.extensions.MatcherResponseWalletExtension;
import org.multibit.hd.brit.extensions.SendFeeDtoWalletExtension;
import org.multibit.hd.brit.seed_phrase.Bip39SeedPhraseGenerator;
import org.multibit.hd.brit.seed_phrase.SeedPhraseGenerator;
import org.multibit.hd.brit.services.FeeService;
import org.multibit.hd.brit.services.TransactionSentBySelfProvider;
import org.multibit.hd.core.concurrent.SafeExecutors;
import org.multibit.hd.core.config.Configurations;
import org.multibit.hd.core.config.Yaml;
import org.multibit.hd.core.crypto.EncryptedFileReaderWriter;
import org.multibit.hd.core.dto.*;
import org.multibit.hd.core.events.CoreEvents;
import org.multibit.hd.core.events.ShutdownEvent;
import org.multibit.hd.core.events.TransactionSeenEvent;
import org.multibit.hd.core.exceptions.ExceptionHandler;
import org.multibit.hd.core.exceptions.WalletLoadException;
import org.multibit.hd.core.exceptions.WalletVersionException;
import org.multibit.hd.core.files.SecureFiles;
import org.multibit.hd.core.services.BackupService;
import org.multibit.hd.core.services.BitcoinNetworkService;
import org.multibit.hd.core.services.CoreServices;
import org.multibit.hd.core.utils.BitcoinNetwork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.params.KeyParameter;
import javax.annotation.Nullable;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static org.multibit.hd.core.dto.WalletId.*;
/**
* <p>Manager to provide the following to core users:</p>
* <ul>
* <li>create wallet</li>
* <li>save wallet wallet</li>
* <li>load wallet wallet</li>
* <li>tracks the current wallet and the list of wallet directories</li>
* </ul>
* <p/>
*/
public enum WalletManager implements WalletEventListener {
INSTANCE {
@Override
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
// Emit an event so that GUI elements can update as required
Coin value = tx.getValue(wallet);
CoreEvents.fireTransactionSeenEvent(new TransactionSeenEvent(tx, value));
}
@Override
public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
// Emit an event so that GUI elements can update as required
Coin value = tx.getValue(wallet);
CoreEvents.fireTransactionSeenEvent(new TransactionSeenEvent(tx, value));
}
@Override
public void onReorganize(Wallet wallet) {
}
@Override
public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) {
// Emit an event so that GUI elements can update as required
Coin value = tx.getValue(wallet);
CoreEvents.fireTransactionSeenEvent(new TransactionSeenEvent(tx, value));
}
@Override
public void onWalletChanged(Wallet wallet) {
}
@Override
public void onKeysAdded(List<ECKey> keys) {
}
@Override
public void onScriptsChanged(Wallet wallet, List<Script> scripts, boolean isAddingScripts) {
}
};
private static final int AUTO_SAVE_DELAY = 30000; // milliseconds
// TODO (GR) Refactor this to be injected
private static final NetworkParameters networkParameters = BitcoinNetwork.current().get();
private static final Logger log = LoggerFactory.getLogger(WalletManager.class);
public static final String EARLIEST_HD_WALLET_DATE = "2014-10-01"; // TODO refine this
/**
* How much a block time might drift
*/
public static final int DRIFT_TIME = 3600; // seconds
public static final String WALLET_DIRECTORY_PREFIX = "mbhd";
// The format of the wallet directories is WALLET_DIRECTORY_PREFIX + a wallet id.
// A wallet id is 5 groups of 4 bytes in lowercase hex, with a "-' separator e.g. mbhd-11111111-22222222-33333333-44444444-55555555
private static final String REGEX_FOR_WALLET_DIRECTORY = "^"
+ WALLET_DIRECTORY_PREFIX
+ WALLET_ID_SEPARATOR
+ "[0-9a-f]{8}"
+ WALLET_ID_SEPARATOR
+ "[0-9a-f]{8}"
+ WALLET_ID_SEPARATOR
+ "[0-9a-f]{8}"
+ WALLET_ID_SEPARATOR
+ "[0-9a-f]{8}"
+ WALLET_ID_SEPARATOR
+ "[0-9a-f]{8}$";
private static final Pattern walletDirectoryPattern = Pattern.compile(REGEX_FOR_WALLET_DIRECTORY);
/**
* The wallet version number for protobuf encrypted wallets - compatible with MultiBit Classic
*/
public static final int MBHD_WALLET_VERSION = 1;
public static final String MBHD_WALLET_PREFIX = "mbhd";
public static final String MBHD_WALLET_SUFFIX = ".wallet";
public static final String MBHD_AES_SUFFIX = ".aes";
public static final String MBHD_SUMMARY_SUFFIX = ".yaml";
public static final String MBHD_WALLET_NAME = MBHD_WALLET_PREFIX + MBHD_WALLET_SUFFIX;
public static final String MBHD_SUMMARY_NAME = MBHD_WALLET_PREFIX + MBHD_SUMMARY_SUFFIX;
public static final int LOOK_AHEAD_SIZE = 50; // A smaller look ahead size than the bitcoinj default of 100 (speeds up syncing as te bloom filters are smaller)
public static final long MAXIMUM_WALLET_CREATION_DELTA = 180 * 1000; // 3 minutes in millis
private Optional<WalletSummary> currentWalletSummary = Optional.absent();
private static final SecureRandom random = new SecureRandom();
/**
* The initialisation vector to use for AES encryption of output files (such as wallets)
* There is no particular significance to the value of these bytes
*/
public static final byte[] AES_INITIALISATION_VECTOR = new byte[]{(byte) 0xa3, (byte) 0x44, (byte) 0x39, (byte) 0x1f, (byte) 0x53, (byte) 0x83, (byte) 0x11,
(byte) 0xb3, (byte) 0x29, (byte) 0x54, (byte) 0x86, (byte) 0x16, (byte) 0xc4, (byte) 0x89, (byte) 0x72, (byte) 0x3e};
/**
* The salt used for deriving the KeyParameter from the credentials in AES encryption for wallets
*/
public static final byte[] SCRYPT_SALT = new byte[]{(byte) 0x35, (byte) 0x51, (byte) 0x03, (byte) 0x80, (byte) 0x75, (byte) 0xa3, (byte) 0xb0, (byte) 0xc5};
private FeeService feeService;
private ListeningExecutorService walletExecutorService = null;
/**
* Open the given wallet and hook it up to the blockchain and peergroup so that it receives notifications
*
* @param applicationDataDirectory The application data directory
* @param walletId The wallet ID to locate the wallet
* @param password The credentials to use to decrypt the wallet
*
* @return The wallet summary if found
*/
public Optional<WalletSummary> openWalletFromWalletId(File applicationDataDirectory, WalletId walletId, CharSequence password) throws WalletLoadException {
log.debug("openWalletFromWalletId called");
Preconditions.checkNotNull(walletId, "'walletId' must be present");
Preconditions.checkNotNull(password, "'credentials' must be present");
this.currentWalletSummary = Optional.absent();
// Ensure BackupManager knows where the wallets are
BackupManager.INSTANCE.setApplicationDataDirectory(applicationDataDirectory);
// Work out the list of available wallets in the application data directory
List<File> walletDirectories = findWalletDirectories(applicationDataDirectory);
// If a wallet directory is present try to load the wallet
if (!walletDirectories.isEmpty()) {
String walletIdPath = walletId.toFormattedString();
// Match the wallet directory to the wallet data
for (File walletDirectory : walletDirectories) {
verifyWalletDirectory(walletDirectory);
String walletDirectoryPath = walletDirectory.getAbsolutePath();
if (walletDirectoryPath.contains(walletIdPath)) {
// Found the required wallet directory - attempt to present the wallet
WalletSummary walletSummary = loadFromWalletDirectory(walletDirectory, password);
setCurrentWalletSummary(walletSummary);
try {
// Wallet is now created - finish off other configuration
updateConfigurationAndCheckSync(createWalletRoot(walletId), walletDirectory, walletSummary, false);
} catch (IOException ioe) {
throw new WalletLoadException("Cannot load wallet with id: " + walletId, ioe);
}
break;
}
}
} else {
currentWalletSummary = Optional.absent();
}
return currentWalletSummary;
}
public WalletSummary getOrCreateMBHDSoftWalletSummaryFromSeed(
File applicationDataDirectory,
byte[] seed,
long creationTimeInSeconds,
String password,
String name,
String notes
) throws WalletLoadException, WalletVersionException, IOException {
log.debug("getOrCreateMBHDSoftWalletSummaryFromSeed called");
final WalletSummary walletSummary;
// Create a wallet id from the seed to work out the wallet root directory
final WalletId walletId = new WalletId(seed);
String walletRoot = createWalletRoot(walletId);
final File walletDirectory = WalletManager.getOrCreateWalletDirectory(applicationDataDirectory, walletRoot);
log.debug("Wallet directory:\n'{}'", walletDirectory.getAbsolutePath());
final File walletFile = new File(walletDirectory.getAbsolutePath() + File.separator + MBHD_WALLET_NAME);
final File walletFileWithAES = new File(walletDirectory.getAbsolutePath() + File.separator + MBHD_WALLET_NAME + MBHD_AES_SUFFIX);
boolean saveWalletYaml = false;
if (walletFileWithAES.exists()) {
log.debug("Discovered AES encrypted wallet file. Loading...");
// There is already a wallet created with this root - if so load it and return that
walletSummary = loadFromWalletDirectory(walletDirectory, password);
walletSummary.setWalletType(WalletType.MBHD_SOFT_WALLET);
setCurrentWalletSummary(walletSummary);
} else {
// Wallet file does not exist so create it below the known good wallet directory
log.debug("Creating new wallet file...");
// Create a wallet using the seed (no salt passphrase)
DeterministicSeed deterministicSeed = new DeterministicSeed(seed, "", creationTimeInSeconds);
Wallet walletToReturn = Wallet.fromSeed(networkParameters, deterministicSeed);
walletToReturn.setKeychainLookaheadSize(LOOK_AHEAD_SIZE);
walletToReturn.encrypt(password);
walletToReturn.setVersion(MBHD_WALLET_VERSION);
// Save it now to ensure it is on the disk
walletToReturn.saveToFile(walletFile);
EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(walletFile, password);
// Create a new wallet summary
walletSummary = new WalletSummary(walletId, walletToReturn);
walletSummary.setName(name);
walletSummary.setNotes(notes);
walletSummary.setPassword(password);
walletSummary.setWalletType(WalletType.MBHD_SOFT_WALLET);
walletSummary.setWalletFile(walletFile);
setCurrentWalletSummary(walletSummary);
// Save the wallet YAML
saveWalletYaml = true;
try {
WalletManager.writeEncryptedPasswordAndBackupKey(walletSummary, seed, password);
} catch (NoSuchAlgorithmException e) {
throw new WalletLoadException("Could not store encrypted credentials and backup AES key", e);
}
}
// Wallet is now created - finish off other configuration and check if wallet needs syncing
updateConfigurationAndCheckSync(walletRoot, walletDirectory, walletSummary, saveWalletYaml);
return walletSummary;
}
public WalletSummary getOrCreateTrezorHardWalletSummaryFromRootNode(
File applicationDataDirectory,
DeterministicKey rootNode,
long creationTimeInSeconds,
String password,
String name,
String notes
) throws WalletLoadException, WalletVersionException, IOException {
log.debug("getOrCreateTrezorHardWalletSummaryFromRootNode called");
// Create a wallet id from the rootNode to work out the wallet root directory
final WalletId walletId = new WalletId(rootNode.getIdentifier());
String walletRoot = createWalletRoot(walletId);
final File walletDirectory = WalletManager.getOrCreateWalletDirectory(applicationDataDirectory, walletRoot);
final File walletFile = new File(walletDirectory.getAbsolutePath() + File.separator + MBHD_WALLET_NAME);
final File walletFileWithAES = new File(walletDirectory.getAbsolutePath() + File.separator + MBHD_WALLET_NAME + MBHD_AES_SUFFIX);
WalletSummary walletSummary = null;
if (walletFileWithAES.exists()) {
try {
// There is already a wallet created with this root - if so load it and return that
log.debug("Opening AES wallet:\n'{}'", walletFileWithAES.getAbsolutePath());
walletSummary = loadFromWalletDirectory(walletDirectory, password);
} catch (WalletLoadException e) {
// Failed to decrypt the existing wallet/backups
log.error("Failed to load from wallet directory.");
}
} else {
log.debug("Wallet file does not exist. Creating...");
// Create the containing directory if it does not exist
if (!walletDirectory.exists()) {
if (!walletDirectory.mkdir()) {
throw new IllegalStateException("The directory for the wallet '" + walletDirectory.getAbsoluteFile() + "' could not be created");
}
}
// Create a wallet using the root node
DeterministicKey rootNodePubOnly = rootNode.getPubOnly();
log.debug("Watching wallet based on: {}", rootNodePubOnly);
Wallet walletToReturn = Wallet.fromWatchingKey(networkParameters, rootNodePubOnly, creationTimeInSeconds, rootNodePubOnly.getPath());
walletToReturn.setKeychainLookaheadSize(LOOK_AHEAD_SIZE);
walletToReturn.setVersion(MBHD_WALLET_VERSION);
// Save it now to ensure it is on the disk
walletToReturn.saveToFile(walletFile);
EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(walletFile, password);
// Create a new wallet summary
walletSummary = new WalletSummary(walletId, walletToReturn);
}
if (walletSummary != null) {
walletSummary.setWalletType(WalletType.TREZOR_HARD_WALLET);
walletSummary.setWalletFile(walletFile);
walletSummary.setName(name);
walletSummary.setNotes(notes);
walletSummary.setPassword(password);
setCurrentWalletSummary(walletSummary);
}
try {
// The entropy based password from the Trezor is used for both the wallet password and for the backup's password
WalletManager.writeEncryptedPasswordAndBackupKey(walletSummary, password.getBytes(Charsets.UTF_8), password);
} catch (NoSuchAlgorithmException e) {
throw new WalletLoadException("Could not store encrypted credentials and backup AES key", e);
}
// Wallet is now created - finish off other configuration and check if wallet needs syncing
// (Always save the wallet yaml as there was a bug in early Trezor wallets where it was not written out)
updateConfigurationAndCheckSync(walletRoot, walletDirectory, walletSummary, true);
return walletSummary;
}
public WalletSummary getOrCreateTrezorSoftWalletSummaryFromSeedPhrase(
File applicationDataDirectory,
String seedPhrase,
long creationTimeInSeconds,
String password,
String name,
String notes
) throws UnreadableWalletException, WalletLoadException, WalletVersionException, IOException {
log.debug("getOrCreateTrezorSoftWalletSummaryFromSeedPhrase called");
// Create a wallet id from the seed to work out the wallet root directory
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
List<String> seedPhraseList = Bip39SeedPhraseGenerator.split(seedPhrase);
byte[] seed = seedGenerator.convertToSeed(seedPhraseList);
final WalletId walletId = new WalletId(seed, WALLET_ID_SALT_USED_IN_SCRYPT_FOR_TREZOR_SOFT_WALLETS);
String walletRoot = createWalletRoot(walletId);
final File walletDirectory = WalletManager.getOrCreateWalletDirectory(applicationDataDirectory, walletRoot);
final File walletFile = new File(walletDirectory.getAbsolutePath() + File.separator + MBHD_WALLET_NAME);
final File walletFileWithAES = new File(walletDirectory.getAbsolutePath() + File.separator + MBHD_WALLET_NAME + MBHD_AES_SUFFIX);
WalletSummary walletSummary = null;
if (walletFileWithAES.exists()) {
try {
// There is already a wallet created with this root - if so load it and return that
log.debug("A wallet with name {} exists. Opening...", walletFileWithAES.getAbsolutePath());
walletSummary = loadFromWalletDirectory(walletDirectory, password);
} catch (WalletLoadException e) {
// Failed to decrypt the existing wallet/backups
// TODO (JB) This causes an NPE later on load fails
log.error("Failed to load from wallet directory.");
}
} else {
log.debug("Wallet file does not exist. Creating...");
// Create the containing directory if it does not exist
if (!walletDirectory.exists()) {
if (!walletDirectory.mkdir()) {
throw new IllegalStateException("The directory for the wallet '" + walletDirectory.getAbsoluteFile() + "' could not be created");
}
}
// Trezor uses BIP-44
// BIP-44 starts from M/44h/0h/0h for soft wallets
List<ChildNumber> trezorRootNodePathList = new ArrayList<>();
trezorRootNodePathList.add(new ChildNumber(44 | ChildNumber.HARDENED_BIT));
trezorRootNodePathList.add(new ChildNumber(ChildNumber.HARDENED_BIT));
DeterministicKey trezorRootNode = HDKeyDerivation.createRootNodeWithPrivateKey(ImmutableList.copyOf(trezorRootNodePathList), seed);
log.debug("Creating Trezor soft wallet with root node with path {}", trezorRootNode.getPath());
// Create a KeyCrypter to encrypt the waller
KeyCrypterScrypt keyCrypterScrypt = new KeyCrypterScrypt(EncryptedFileReaderWriter.makeScryptParameters(WalletManager.SCRYPT_SALT));
// Create a wallet using the seed phrase and Trezor root node
DeterministicSeed deterministicSeed = new DeterministicSeed(seed, seedPhraseList, creationTimeInSeconds);
Wallet walletToReturn = Wallet.fromSeed(networkParameters, deterministicSeed, trezorRootNode.getPath(), password, keyCrypterScrypt);
walletToReturn.setKeychainLookaheadSize(LOOK_AHEAD_SIZE);
walletToReturn.setVersion(MBHD_WALLET_VERSION);
// Save it now to ensure it is on the disk
walletToReturn.saveToFile(walletFile);
EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(walletFile, password);
// Create a new wallet summary
walletSummary = new WalletSummary(walletId, walletToReturn);
}
if (walletSummary != null) {
walletSummary.setWalletType(WalletType.TREZOR_SOFT_WALLET);
walletSummary.setWalletFile(walletFile);
walletSummary.setName(name);
walletSummary.setNotes(notes);
walletSummary.setPassword(password);
setCurrentWalletSummary(walletSummary);
}
try {
WalletManager.writeEncryptedPasswordAndBackupKey(walletSummary, seed, password);
} catch (NoSuchAlgorithmException e) {
throw new WalletLoadException("Could not store encrypted credentials and backup AES key", e);
}
// Wallet is now created - finish off other configuration and check if wallet needs syncing
// (Always save the wallet yaml as there was a bug in early Trezor wallets where it was not written out)
updateConfigurationAndCheckSync(walletRoot, walletDirectory, walletSummary, true);
return walletSummary;
}
/**
* Update configuration with new wallet information
*/
private void updateConfigurationAndCheckSync(String walletRoot, File walletDirectory, WalletSummary walletSummary, boolean saveWalletYaml) throws IOException {
if (saveWalletYaml) {
File walletSummaryFile = WalletManager.getOrCreateWalletSummaryFile(walletDirectory);
log.debug("Writing wallet YAML to file:\n'{}'", walletSummaryFile.getAbsolutePath());
WalletManager.updateWalletSummary(walletSummaryFile, walletSummary);
}
// Remember the current soft wallet root
if (WalletType.TREZOR_HARD_WALLET != walletSummary.getWalletType()) {
if (Configurations.currentConfiguration != null) {
Configurations.currentConfiguration.getWallet().setLastSoftWalletRoot(walletRoot);
}
}
// See if there is a checkpoints file - if not then get the InstallationManager to copy one in
File checkpointsFile = new File(walletDirectory.getAbsolutePath() + File.separator + InstallationManager.MBHD_PREFIX + InstallationManager.CHECKPOINTS_SUFFIX);
InstallationManager.copyCheckpointsTo(checkpointsFile);
// Set up auto-save on the wallet.
addAutoSaveListener(walletSummary.getWallet(), walletSummary.getWalletFile());
// Check if the wallet needs to sync
checkIfWalletNeedsToSync(walletSummary);
}
/**
* Check if the wallet needs to sync and, if so, work out the sync date and fire off the synchronise
*
* @param walletSummary The wallet summary containing the wallet that may need syncing
*/
private void checkIfWalletNeedsToSync(WalletSummary walletSummary) {
// See if the wallet and blockstore are at the same height - in which case perform a regular download blockchain
// Else perform a sync from the last seen block date to ensure all tx are seen
log.debug("Seeing if wallet needs to sync");
if (walletSummary != null) {
Wallet walletBeingReturned = walletSummary.getWallet();
if (walletBeingReturned == null) {
log.debug("There is no wallet to examine");
} else {
boolean performRegularSync = false;
BlockStore blockStore = null;
try {
// Get the bitcoin network service
BitcoinNetworkService bitcoinNetworkService = CoreServices.getOrCreateBitcoinNetworkService();
log.debug("bitcoinNetworkService: {}", bitcoinNetworkService);
int walletBlockHeight = walletBeingReturned.getLastBlockSeenHeight();
Date walletLastSeenBlockTime = walletBeingReturned.getLastBlockSeenTime();
log.debug("Wallet lastBlockSeenHeight: {}, lastSeenBlockTime: {}, earliestKeyCreationTime: {}", walletBlockHeight, walletLastSeenBlockTime, walletBeingReturned.getEarliestKeyCreationTime());
// See if the bitcoinNetworkService already has an open blockstore
blockStore = bitcoinNetworkService.getBlockStore();
if (blockStore == null) {
// Open the blockstore with no checkpointing (this is to get the chain height)
blockStore = bitcoinNetworkService.openBlockStore(InstallationManager.getOrCreateApplicationDataDirectory(), Optional.<Date>absent());
}
log.debug("blockStore = {}", blockStore);
int blockStoreBlockHeight = -2; // -2 is just a dummy value
if (blockStore != null) {
StoredBlock chainHead = blockStore.getChainHead();
blockStoreBlockHeight = chainHead == null ? -2 : chainHead.getHeight();
}
log.debug("The blockStore is at height {}", blockStoreBlockHeight);
long earliestKeyCreationTimeInSeconds = walletBeingReturned.getEarliestKeyCreationTime();
if (walletBlockHeight > 0 && walletBlockHeight == blockStoreBlockHeight) {
if (walletLastSeenBlockTime == null ||
earliestKeyCreationTimeInSeconds == -1 ||
(walletLastSeenBlockTime.getTime() / 1000 > earliestKeyCreationTimeInSeconds - DRIFT_TIME)) {
// Regular sync is ok - no need to use checkpoints
log.debug("Will perform a regular sync");
performRegularSync = true;
}
}
} catch (BlockStoreException bse) {
// Carry on - it's just logging
bse.printStackTrace();
} finally {
// Close the blockstore - it will get opened again later but may or may not be checkpointed
if (blockStore != null) {
try {
blockStore.close();
} catch (BlockStoreException bse) {
bse.printStackTrace();
}
}
}
if (performRegularSync) {
synchroniseWallet(Optional.<Date>absent());
} else {
// Work out the date to sync from from the last block seen, the earliest key creation date and the earliest HD wallet date
DateTime syncDate = null;
if (walletBeingReturned.getLastBlockSeenTime() != null) {
syncDate = new DateTime(walletBeingReturned.getLastBlockSeenTime());
}
if (walletBeingReturned.getEarliestKeyCreationTime() != -1) {
DateTime keyCreationTime = new DateTime(walletBeingReturned.getEarliestKeyCreationTime() * 1000);
if (syncDate == null) {
syncDate = keyCreationTime;
} else {
syncDate = keyCreationTime.isBefore(syncDate) ? syncDate : keyCreationTime;
}
}
DateTime earliestHDWalletDate = DateTime.parse(EARLIEST_HD_WALLET_DATE);
if (syncDate == null || syncDate.isBefore(earliestHDWalletDate)) {
syncDate = earliestHDWalletDate;
}
log.debug("Syncing wallet from date {}", syncDate);
if (syncDate != null) {
synchroniseWallet(Optional.of(syncDate.toDate()));
}
}
}
}
}
/**
* Load a wallet from a file and decrypt it
* (but don't hook it up to the Bitcoin network or sync it)
*
* @param walletFile wallet file to load
* @param password password to use to decrypt the wallet
*
* @return the loaded wallet
*
* @throws IOException
* @throws UnreadableWalletException
*/
public Wallet loadWalletFromFile(File walletFile, CharSequence password) throws IOException, UnreadableWalletException {
// Read the encrypted file in and decrypt it.
byte[] encryptedWalletBytes = Files.toByteArray(walletFile);
Preconditions.checkNotNull(encryptedWalletBytes, "'encryptedWalletBytes' must be present");
log.trace("Encrypted wallet bytes after load:\n{}", Utils.HEX.encode(encryptedWalletBytes));
log.debug("Loaded the encrypted wallet bytes with length: {}", encryptedWalletBytes.length);
KeyCrypterScrypt keyCrypterScrypt = new KeyCrypterScrypt(EncryptedFileReaderWriter.makeScryptParameters(SCRYPT_SALT));
KeyParameter keyParameter = keyCrypterScrypt.deriveKey(password);
// Decrypt the wallet bytes
byte[] decryptedBytes = AESUtils.decrypt(encryptedWalletBytes, keyParameter, AES_INITIALISATION_VECTOR);
log.debug("Successfully decrypted wallet bytes, length is now: {}", decryptedBytes.length);
final int walletSampleLength = 128;
if (decryptedBytes.length >= walletSampleLength) {
log.debug("The first 128 bytes of the wallet are\n{}", Utils.HEX.encode(Arrays.copyOfRange(decryptedBytes, 0, walletSampleLength)));
log.debug("The last 128 bytes of the wallet are\n{}", Utils.HEX.encode(Arrays.copyOfRange(decryptedBytes, decryptedBytes.length - walletSampleLength, decryptedBytes.length)));
}
InputStream inputStream = new ByteArrayInputStream(decryptedBytes);
Protos.Wallet walletProto = WalletProtobufSerializer.parseToProto(inputStream);
WalletExtension[] walletExtensions = new WalletExtension[]{new SendFeeDtoWalletExtension(), new MatcherResponseWalletExtension()};
Wallet wallet = new WalletProtobufSerializer().readWallet(BitcoinNetwork.current().get(), walletExtensions, walletProto);
wallet.setKeychainLookaheadSize(LOOK_AHEAD_SIZE);
//System.out.println("WalletManager#loadWalletFromFile: Just loaded wallet:\n" + wallet.toString());
return wallet;
}
/**
* <p>Load up an encrypted Wallet from a specified wallet directory.</p>
* <p>Reduced visibility for testing</p>
*
* @param walletDirectory The wallet directory containing the various wallet files to load
* @param password The credentials to use to decrypt the wallet
*
* @return Wallet - the loaded wallet
*
* @throws WalletLoadException If the wallet could not be loaded
* @throws WalletVersionException If the wallet has an unsupported version number
*/
WalletSummary loadFromWalletDirectory(File walletDirectory, CharSequence password) throws WalletLoadException, WalletVersionException {
Preconditions.checkNotNull(walletDirectory, "'walletDirectory' must be present");
Preconditions.checkNotNull(password, "'credentials' must be present");
verifyWalletDirectory(walletDirectory);
try {
String walletFilenameNoAESSuffix = walletDirectory.getAbsolutePath() + File.separator + MBHD_WALLET_NAME;
File walletFile = new File(walletFilenameNoAESSuffix + MBHD_AES_SUFFIX);
WalletId walletId = parseWalletFilename(walletFile.getAbsolutePath());
if (walletFile.exists() && isWalletSerialised(walletFile)) {
// Serialised wallets are no longer supported.
throw new WalletLoadException(
"Could not load wallet '"
+ walletFile
+ "'. Serialized wallets are no longer supported."
);
}
Wallet wallet;
try {
wallet = loadWalletFromFile(walletFile, password);
} catch (WalletVersionException wve) {
// We want this exception to propagate out.
// Don't bother trying to load the rolling backups as they will most likely be an unreadable version too.
throw wve;
} catch (Exception e) {
// Log the initial error
log.error(e.getClass().getCanonicalName() + " " + e.getMessage(), e);
System.out.println("WalletManager error: " + e.getClass().getCanonicalName() + " " + e.getMessage());
// Try loading one of the rolling backups - this will send a BackupWalletLoadedEvent containing the initial error
// If the rolling backups don't load then loadRollingBackup will throw a WalletLoadException which will propagate out
wallet = BackupManager.INSTANCE.loadRollingBackup(walletId, password);
}
// Create the wallet summary with its wallet
WalletSummary walletSummary = getOrCreateWalletSummary(walletDirectory, walletId);
walletSummary.setWallet(wallet);
walletSummary.setWalletFile(new File(walletFilenameNoAESSuffix));
walletSummary.setPassword(password);
log.debug("Loaded the wallet successfully from \n{}", walletDirectory);
log.debug("Wallet:{}", wallet);
return walletSummary;
} catch (WalletVersionException wve) {
// We want this to propagate out as is
throw wve;
} catch (Exception e) {
throw new WalletLoadException(e.getMessage(), e);
}
}
/**
* Set up auto-save on the wallet.
* This ensures the wallet is saved on modification
* The listener has a 'after save' callback which ensures rolling backups and local/ cloud backups are also saved where necessary
*
* @param wallet The wallet to add the autosave listener to
* @param file The file to add the autoSaveListener to - this should be WITHOUT the AES suffix
*/
private void addAutoSaveListener(Wallet wallet, File file) {
if (file != null) {
WalletAutoSaveListener walletAutoSaveListener = new WalletAutoSaveListener();
wallet.autosaveToFile(file, AUTO_SAVE_DELAY, TimeUnit.MILLISECONDS, walletAutoSaveListener);
log.debug("WalletAutoSaveListener {} on file {} just added to wallet {}", System.identityHashCode(this), file.getAbsolutePath(), System.identityHashCode(wallet));
} else {
log.debug("Not adding autoSaveListener to wallet {} as no wallet file is specified", System.identityHashCode(wallet));
}
}
private void synchroniseWallet(final Optional<Date> syncDateOptional) {
log.debug("Synchronise wallet called with syncDate {}", syncDateOptional);
if (walletExecutorService == null) {
walletExecutorService = SafeExecutors.newSingleThreadExecutor("sync-wallet");
}
// Start the Bitcoin network synchronization operation
ListenableFuture future = walletExecutorService.submit(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
log.debug("synchroniseWallet called with replay date {}", syncDateOptional);
// Replay wallet - this also bounces the Bitcoin network connection
CoreServices.getOrCreateBitcoinNetworkService().replayWallet(InstallationManager.getOrCreateApplicationDataDirectory(), syncDateOptional);
return true;
}
});
Futures.addCallback(
future, new FutureCallback() {
@Override
public void onSuccess(@Nullable Object result) {
// Do nothing this just means that the block chain download has begun
log.debug("Sync has begun");
}
@Override
public void onFailure(Throwable t) {
// Have a failure
log.debug("Sync failed, error was " + t.getClass().getCanonicalName() + " " + t.getMessage());
}
});
}
/**
* @param walletFile the wallet to test serialisation for
*
* @return true if the wallet file specified is serialised (this format is no longer supported)
*/
private boolean isWalletSerialised(File walletFile) {
Preconditions.checkNotNull(walletFile, "'walletFile' must be present");
Preconditions.checkState(walletFile.isFile(), "'walletFile' must be a file");
boolean isWalletSerialised = false;
InputStream stream = null;
try {
// Determine what kind of wallet stream this is: Java serialization or protobuf format
stream = new BufferedInputStream(new FileInputStream(walletFile));
isWalletSerialised = stream.read() == 0xac && stream.read() == 0xed;
} catch (IOException e) {
log.error(e.getClass().getCanonicalName() + " " + e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
log.error(e.getClass().getCanonicalName() + " " + e.getMessage());
}
}
}
return isWalletSerialised;
}
/**
* Create the name of the directory in which the wallet is stored
*
* @param walletId The wallet id to use (e.g. "11111111-22222222-33333333-44444444-55555555")
*
* @return A wallet root
*/
public static String createWalletRoot(WalletId walletId) {
return WALLET_DIRECTORY_PREFIX + WALLET_ID_SEPARATOR + walletId.toFormattedString();
}
public static File getOrCreateWalletDirectory(File applicationDataDirectory, String walletRoot) {
// Create wallet directory under application directory
File walletDirectory = SecureFiles.verifyOrCreateDirectory(applicationDataDirectory, walletRoot);
// Sanity check the wallet directory name and existence
verifyWalletDirectory(walletDirectory);
return walletDirectory;
}
/**
* @return A list of wallet summaries based on the current application directory contents (never null)
*/
public static List<WalletSummary> getWalletSummaries() {
List<File> walletDirectories = findWalletDirectories(InstallationManager.getOrCreateApplicationDataDirectory());
Optional<String> walletRoot = INSTANCE.getCurrentWalletRoot();
return findWalletSummaries(walletDirectories, walletRoot);
}
/**
* <p>Work out what wallets are available in a directory (typically the user data directory).
* This is achieved by looking for directories with a name like <code>"mbhd-walletId"</code>
*
* @param directoryToSearch The directory to search
*
* @return A list of files of wallet directories (never null)
*/
public static List<File> findWalletDirectories(File directoryToSearch) {
Preconditions.checkNotNull(directoryToSearch);
File[] files = directoryToSearch.listFiles();
List<File> walletDirectories = Lists.newArrayList();
// Look for file names with format "mbhd"-"walletId" and are not empty
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
String filename = file.getName();
if (filename.matches(REGEX_FOR_WALLET_DIRECTORY)) {
// The name matches so add it
walletDirectories.add(file);
}
}
}
}
return walletDirectories;
}
/**
* <p>Find Wallet summaries for all the wallet directories provided</p>
*
* @param walletDirectories The candidate wallet directory references
* @param walletRoot The wallet root of the first entry
*
* @return A list of wallet summaries (never null)
*/
public static List<WalletSummary> findWalletSummaries(List<File> walletDirectories, Optional walletRoot) {
Preconditions.checkNotNull(walletDirectories, "'walletDirectories' must be present");
List<WalletSummary> walletList = Lists.newArrayList();
for (File walletDirectory : walletDirectories) {
if (walletDirectory.isDirectory()) {
String directoryName = walletDirectory.getName();
if (directoryName.matches(REGEX_FOR_WALLET_DIRECTORY)) {
// The name matches so process it
WalletId walletId = new WalletId(directoryName.substring(MBHD_WALLET_PREFIX.length() + 1));
WalletSummary walletSummary = getOrCreateWalletSummary(walletDirectory, walletId);
// Check if the wallet root is present and matches the file name
if (walletRoot.isPresent() && directoryName.equals(walletRoot.get())) {
walletList.add(0, walletSummary);
} else {
walletList.add(walletSummary);
}
}
}
}
return walletList;
}
/**
* Get the balance of the current wallet (this does not include a decrement due to the BRIT fees)
* This is Optional.absent() if there is no wallet
*/
public Optional<Coin> getCurrentWalletBalance() {
Optional<WalletSummary> currentWalletSummary = getCurrentWalletSummary();
if (currentWalletSummary.isPresent()) {
// Use the real wallet data
return Optional.of(currentWalletSummary.get().getWallet().getBalance());
} else {
// Unknown at this time
return Optional.absent();
}
}
/**
* @return The BRIT fee state for the current wallet - this includes things like how much is
* currently owed to BRIT
* @param includeOneExtraFee include an extra fee to include a tx currently being constructed that isn't in the wallet yet
*/
public Optional<FeeState> calculateBRITFeeState(boolean includeOneExtraFee) {
if (feeService == null) {
feeService = CoreServices.createFeeService();
}
if (getCurrentWalletSummary() != null && getCurrentWalletSummary().isPresent()) {
Wallet wallet = getCurrentWalletSummary().get().getWallet();
// Set the transaction sent by self provider to use TransactionInfos
TransactionSentBySelfProvider transactionSentBySelfProvider = new TransactionInfoSentBySelfProvider(getCurrentWalletSummary().get().getWalletId());
feeService.setTransactionSentBySelfProvider(transactionSentBySelfProvider);
File applicationDataDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
Optional<File> walletFileOptional = getCurrentWalletFile(applicationDataDirectory);
if (walletFileOptional.isPresent()) {
log.debug("Wallet file prior to calculateFeeState is " + walletFileOptional.get().length() + " bytes");
}
FeeState feeState = feeService.calculateFeeState(wallet, false);
if (includeOneExtraFee) {
feeState.setFeeOwed(feeState.getFeeOwed().add(FeeService.FEE_PER_SEND));
}
Optional<FeeState> feeStateOptional = Optional.of(feeState);
if (walletFileOptional.isPresent()) {
log.debug("Wallet file after to calculateFeeState is " + walletFileOptional.get().length() + " bytes");
}
return feeStateOptional;
} else {
return Optional.absent();
}
}
/**
* @return The current wallet summary (present only if a wallet has been unlocked)
*/
public Optional<WalletSummary> getCurrentWalletSummary() {
return currentWalletSummary;
}
/**
* @param walletSummary The current wallet summary (null if a reset is required)
*/
public void setCurrentWalletSummary(WalletSummary walletSummary) {
if (walletSummary != null && walletSummary.getWallet() != null) {
// Remove the previous WalletEventListener
walletSummary.getWallet().removeEventListener(this);
// Add the wallet event listener
walletSummary.getWallet().addEventListener(this);
}
this.currentWalletSummary = Optional.fromNullable(walletSummary);
}
/**
* @return The current wallet file (e.g. "/User/example/Application Support/MultiBitHD/mbhd-1111-2222-3333-4444/mbhd.wallet")
*/
public Optional<File> getCurrentWalletFile(File applicationDataDirectory) {
if (applicationDataDirectory != null && currentWalletSummary.isPresent()) {
String walletFilename =
applicationDataDirectory
+ File.separator
+ WALLET_DIRECTORY_PREFIX
+ WALLET_ID_SEPARATOR
+ currentWalletSummary.get().getWalletId().toFormattedString()
+ File.separator
+ MBHD_WALLET_NAME;
return Optional.of(new File(walletFilename));
} else {
return Optional.absent();
}
}
/**
* @return The current wallet summary file (e.g. "/User/example/Application Support/MultiBitHD/mbhd-1111-2222-3333-4444/mbhd.yaml")
*/
public Optional<File> getCurrentWalletSummaryFile(File applicationDataDirectory) {
if (applicationDataDirectory != null && currentWalletSummary.isPresent()) {
String walletFilename =
applicationDataDirectory
+ File.separator
+ WALLET_DIRECTORY_PREFIX
+ WALLET_ID_SEPARATOR
+ currentWalletSummary.get().getWalletId().toFormattedString()
+ File.separator
+ MBHD_SUMMARY_NAME;
return Optional.of(new File(walletFilename));
} else {
return Optional.absent();
}
}
/**
* @param walletDirectory The wallet directory containing the various wallet files
*
* @return A wallet summary file
*/
public static File getOrCreateWalletSummaryFile(File walletDirectory) {
return SecureFiles.verifyOrCreateFile(walletDirectory, MBHD_SUMMARY_NAME);
}
/**
* @return The current wallet root as defined in the configuration, or absent
*/
public Optional<String> getCurrentWalletRoot() {
return Optional.fromNullable(Configurations.currentConfiguration.getWallet().getLastSoftWalletRoot());
}
/**
* @param walletSummary The wallet summary to write
*/
public static void updateWalletSummary(File walletSummaryFile, WalletSummary walletSummary) {
if (walletSummary == null) {
log.warn("WalletSummary is missing. The wallet configuration file is NOT being overwritten.");
return;
}
// Persist the new configuration
try (FileOutputStream fos = new FileOutputStream(walletSummaryFile)) {
Yaml.writeYaml(fos, walletSummary);
} catch (IOException e) {
ExceptionHandler.handleThrowable(e);
}
}
/**
* @param walletDirectory The wallet directory to read
*
* @return The wallet summary if present, or a default if not
*/
public static WalletSummary getOrCreateWalletSummary(File walletDirectory, WalletId walletId) {
log.debug("getOrCreateWalletSummary called");
verifyWalletDirectory(walletDirectory);
Optional<WalletSummary> walletSummaryOptional = Optional.absent();
File walletSummaryFile = new File(walletDirectory.getAbsolutePath() + File.separator + MBHD_SUMMARY_NAME);
if (walletSummaryFile.exists()) {
try (InputStream is = new FileInputStream(walletSummaryFile)) {
// Load configuration (providing a default if none exists)
walletSummaryOptional = Yaml.readYaml(is, WalletSummary.class);
} catch (IOException e) {
// A full stack trace is too much here
log.warn("Could not read wallet summary:\n'{}'\nException: {}", walletDirectory.getAbsolutePath(), e.getMessage());
}
}
final WalletSummary walletSummary;
if (walletSummaryOptional.isPresent()) {
walletSummary = walletSummaryOptional.get();
} else {
walletSummary = new WalletSummary();
// TODO No localiser available in core to localise core_default_wallet_name.
String shortWalletDirectory = walletDirectory.getName().substring(0, 13); // The mbhd and the first group of digits
walletSummary.setName("Wallet (" + shortWalletDirectory + "...)");
walletSummary.setNotes("");
}
walletSummary.setWalletId(walletId);
return walletSummary;
}
/**
* Write the encrypted wallet credentials and backup AES key to the wallet configuration.
* You probably want to save it afterwards with an updateSummary
*/
public static void writeEncryptedPasswordAndBackupKey(WalletSummary walletSummary, byte[] entropy, String password) throws NoSuchAlgorithmException {
// Save the wallet credentials, AES encrypted with a key derived from the wallet seed/ entropy
KeyParameter entropyDerivedAESKey = org.multibit.hd.core.crypto.AESUtils.createAESKey(entropy, SCRYPT_SALT);
byte[] passwordBytes = password.getBytes(Charsets.UTF_8);
byte[] paddedPasswordBytes = padPasswordBytes(passwordBytes);
byte[] encryptedPaddedPassword = org.multibit.hd.brit.crypto.AESUtils.encrypt(paddedPasswordBytes, entropyDerivedAESKey, AES_INITIALISATION_VECTOR);
walletSummary.setEncryptedPassword(encryptedPaddedPassword);
// Save the backupAESKey, AES encrypted with a key generated from the wallet password
KeyParameter walletPasswordDerivedAESKey = org.multibit.hd.core.crypto.AESUtils.createAESKey(passwordBytes, SCRYPT_SALT);
byte[] encryptedBackupAESKey = org.multibit.hd.brit.crypto.AESUtils.encrypt(entropyDerivedAESKey.getKey(), walletPasswordDerivedAESKey, AES_INITIALISATION_VECTOR);
walletSummary.setEncryptedBackupKey(encryptedBackupAESKey);
}
private static void verifyWalletDirectory(File walletDirectory) {
log.trace("Verifying wallet directory: '{}'", walletDirectory.getAbsolutePath());
Preconditions.checkState(walletDirectory.isDirectory(), "'walletDirectory' must be a directory: '" + walletDirectory.getAbsolutePath() + "'");
// Use the pre-compiled regex
boolean result = walletDirectoryPattern.matcher(walletDirectory.getName()).matches();
Preconditions.checkState(result, "'walletDirectory' is not named correctly: '" + walletDirectory.getAbsolutePath() + "'");
log.trace("Wallet directory verified ok");
}
/**
* Method to determine whether a message is 'mine', meaning an existing address in the current wallet
*
* @param address The address to test for wallet inclusion
*
* @return true if address is in current wallet, false otherwise
*/
public boolean isAddressMine(Address address) {
try {
Optional<WalletSummary> walletSummaryOptional = WalletManager.INSTANCE.getCurrentWalletSummary();
if (walletSummaryOptional.isPresent()) {
WalletSummary walletSummary = walletSummaryOptional.get();
Wallet wallet = walletSummary.getWallet();
ECKey signingKey = wallet.findKeyFromPubHash(address.getHash160());
return signingKey != null;
} else {
// No wallet present
return false;
}
} catch (Exception e) {
// Some other problem
return false;
}
}
/**
* @return True if current wallet is unlocked and represents a Trezor "hard" wallet
*/
public boolean isUnlockedTrezorHardWallet() {
try {
Optional<WalletSummary> walletSummaryOptional = WalletManager.INSTANCE.getCurrentWalletSummary();
if (walletSummaryOptional.isPresent()) {
WalletSummary walletSummary = walletSummaryOptional.get();
return WalletType.TREZOR_HARD_WALLET.equals(walletSummary.getWalletType());
} else {
// No wallet present
return false;
}
} catch (Exception e) {
// Some other problem
return false;
}
}
/**
* <p>Method to sign a message</p>
*
* @param addressText Text address to use to sign (makes UI Address conversion code DRY)
* @param messageText The message to sign
* @param walletPassword The wallet credentials
*
* @return A "sign message result" describing the outcome
*/
public SignMessageResult signMessage(String addressText, String messageText, String walletPassword) {
if (Strings.isNullOrEmpty(addressText)) {
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_ENTER_ADDRESS, null);
}
if (Strings.isNullOrEmpty(messageText)) {
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_ENTER_MESSAGE, null);
}
if (Strings.isNullOrEmpty(walletPassword)) {
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_ENTER_PASSWORD, null);
}
try {
Address signingAddress = new Address(BitcoinNetwork.current().get(), addressText);
Optional<WalletSummary> walletSummaryOptional = WalletManager.INSTANCE.getCurrentWalletSummary();
if (walletSummaryOptional.isPresent()) {
WalletSummary walletSummary = walletSummaryOptional.get();
Wallet wallet = walletSummary.getWallet();
ECKey signingKey = wallet.findKeyFromPubHash(signingAddress.getHash160());
if (signingKey != null) {
if (signingKey.getKeyCrypter() != null) {
KeyParameter aesKey = signingKey.getKeyCrypter().deriveKey(walletPassword);
ECKey decryptedSigningKey = signingKey.decrypt(aesKey);
String signatureBase64 = decryptedSigningKey.signMessage(messageText);
return new SignMessageResult(Optional.of(signatureBase64), true, CoreMessageKey.SIGN_MESSAGE_SUCCESS, null);
} else {
// The signing key is not encrypted but it should be
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_SIGNING_KEY_NOT_ENCRYPTED, null);
}
} else {
// No signing key found.
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_NO_SIGNING_KEY, new Object[]{addressText});
}
} else {
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_NO_WALLET, null);
}
} catch (KeyCrypterException e) {
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_NO_PASSWORD, null);
} catch (Exception e) {
e.printStackTrace();
return new SignMessageResult(Optional.<String>absent(), false, CoreMessageKey.SIGN_MESSAGE_FAILURE, null);
}
}
/**
* <p>Method to verify a message</p>
*
* @param addressText Text address to use to sign (makes UI Address conversion code DRY)
* @param messageText The message to sign
* @param signatureText The signature text (can include CRLF characters which will be stripped)
*
* @return A "verify message result" describing the outcome
*/
public VerifyMessageResult verifyMessage(String addressText, String messageText, String signatureText) {
if (Strings.isNullOrEmpty(addressText)) {
return new VerifyMessageResult(false, CoreMessageKey.VERIFY_MESSAGE_ENTER_ADDRESS, null);
}
if (Strings.isNullOrEmpty(messageText)) {
return new VerifyMessageResult(false, CoreMessageKey.VERIFY_MESSAGE_ENTER_MESSAGE, null);
}
if (Strings.isNullOrEmpty(signatureText)) {
return new VerifyMessageResult(false, CoreMessageKey.VERIFY_MESSAGE_ENTER_SIGNATURE, null);
}
try {
Address signingAddress = new Address(BitcoinNetwork.current().get(), addressText);
// Strip CRLF from signature text
signatureText = signatureText.replaceAll("\n", "").replaceAll("\r", "");
ECKey key = ECKey.signedMessageToKey(messageText, signatureText);
Address gotAddress = key.toAddress(BitcoinNetwork.current().get());
if (signingAddress.equals(gotAddress)) {
return new VerifyMessageResult(true, CoreMessageKey.VERIFY_MESSAGE_VERIFY_SUCCESS, null);
} else {
return new VerifyMessageResult(false, CoreMessageKey.VERIFY_MESSAGE_VERIFY_FAILURE, null);
}
} catch (Exception e) {
e.printStackTrace();
return new VerifyMessageResult(false, CoreMessageKey.VERIFY_MESSAGE_FAILURE, null);
}
}
/**
* Password short passwords with extra bytes - this is done so that the existence of short passwords is not leaked by
* the length of the encrypted credentials (which is always a multiple of the AES block size (16 bytes).
*
* @param passwordBytes the credentials bytes to pad
*
* @return paddedPasswordBytes - this is guaranteed to be longer than 48 bytes. Byte 0 indicates the number of padding bytes,
* which are random bytes stored from byte 1 to byte <number of padding bytes). The real credentials is stored int he remaining bytes
*/
public static byte[] padPasswordBytes(byte[] passwordBytes) {
if (passwordBytes.length > AESUtils.BLOCK_LENGTH * 3) {
// No padding required - add a zero to the beginning of the credentials bytes (to indicate no padding bytes)
return Bytes.concat(new byte[]{(byte) 0x0}, passwordBytes);
} else {
if (passwordBytes.length > AESUtils.BLOCK_LENGTH * 2) {
// Pad with 16 random bytes
byte[] paddingBytes = new byte[16];
random.nextBytes(paddingBytes);
return Bytes.concat(new byte[]{(byte) 0x10}, paddingBytes, passwordBytes);
} else {
if (passwordBytes.length > AESUtils.BLOCK_LENGTH) {
// Pad with 32 random bytes
byte[] paddingBytes = new byte[32];
random.nextBytes(paddingBytes);
return Bytes.concat(new byte[]{(byte) 0x20}, paddingBytes, passwordBytes);
} else {
// Pad with 48 random bytes
byte[] paddingBytes = new byte[48];
random.nextBytes(paddingBytes);
return Bytes.concat(new byte[]{(byte) 0x30}, paddingBytes, passwordBytes);
}
}
}
}
/**
* Unpad credentials bytes, removing the random prefix bytes length marker byte and te random bytes themselves
*/
public static byte[] unpadPasswordBytes(byte[] paddedPasswordBytes) {
Preconditions.checkNotNull(paddedPasswordBytes);
Preconditions.checkState(paddedPasswordBytes.length > 0);
// Get the length of the pad
int lengthOfPad = (int) paddedPasswordBytes[0];
if (lengthOfPad > paddedPasswordBytes.length - 1) {
throw new IllegalStateException("Stored encrypted credentials is not in the correct format");
}
return Arrays.copyOfRange(paddedPasswordBytes, 1 + lengthOfPad, paddedPasswordBytes.length);
}
/**
* Generate the DeterministicKey from the private master key for a Trezor wallet
* <p/>
* For a real Trezor device this will be the result of a GetPublicKey of the M/44'/0'/0' path, received as an xpub and then converted to a DeterministicKey
*
* @param privateMasterKey the private master key derived from the wallet seed
*
* @return the public only DeterministicSeed corresponding to the root Trezor wallet node e.g. M/44'/0'/0'
*/
public static DeterministicKey generateTrezorWalletRootNode(DeterministicKey privateMasterKey) {
DeterministicKey key_m_44h = HDKeyDerivation.deriveChildKey(privateMasterKey, new ChildNumber(44 | ChildNumber.HARDENED_BIT));
log.debug("key_m_44h deterministic key = " + key_m_44h);
DeterministicKey key_m_44h_0h = HDKeyDerivation.deriveChildKey(key_m_44h, ChildNumber.ZERO_HARDENED);
log.debug("key_m_44h_0h deterministic key = " + key_m_44h_0h);
DeterministicKey key_m_44h_0h_0h = HDKeyDerivation.deriveChildKey(key_m_44h_0h, ChildNumber.ZERO_HARDENED);
log.debug("key_m_44h_0h_0h = " + key_m_44h_0h_0h);
return key_m_44h_0h_0h;
}
/**
* @param shutdownType The shutdown type
*/
public void shutdownNow(ShutdownEvent.ShutdownType shutdownType) {
log.debug("Received shutdown: {}", shutdownType.name());
currentWalletSummary = Optional.absent();
}
/**
* <p>Save the current wallet to application directory, create a rolling backup and a cloud backup</p>
*/
public void saveWallet() {
// Save the current wallet immediately
if (getCurrentWalletSummary().isPresent()) {
WalletSummary walletSummary = WalletManager.INSTANCE.getCurrentWalletSummary().get();
WalletId walletId = walletSummary.getWalletId();
log.debug("Saving wallet with id : {}, height : {}", walletId, walletSummary.getWallet().getLastBlockSeenHeight());
try {
File applicationDataDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
File currentWalletFile = WalletManager.INSTANCE.getCurrentWalletFile(applicationDataDirectory).get();
walletSummary.getWallet().saveToFile(currentWalletFile);
File encryptedAESCopy = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(currentWalletFile, walletSummary.getPassword());
log.debug(
"Created AES encrypted wallet as file:\n'{}'\nSize: {} bytes", encryptedAESCopy == null ? "null" : encryptedAESCopy.getAbsolutePath(),
encryptedAESCopy == null ? "null" : encryptedAESCopy.length());
BackupService backupService = CoreServices.getOrCreateBackupService();
backupService.rememberWalletSummaryAndPasswordForRollingBackup(walletSummary, walletSummary.getPassword());
backupService.rememberWalletIdAndPasswordForLocalZipBackup(walletSummary.getWalletId(), walletSummary.getPassword());
backupService.rememberWalletIdAndPasswordForCloudZipBackup(walletSummary.getWalletId(), walletSummary.getPassword());
} catch (IOException ioe) {
log.error("Could not write wallet and backups for wallet with id '" + walletId + "' successfully. The error was '" + ioe.getMessage() + "'");
}
}
}
/**
* Closes the wallet
*/
public void closeWallet() {
if (WalletManager.INSTANCE.getCurrentWalletSummary().isPresent()) {
try {
Wallet wallet = WalletManager.INSTANCE.getCurrentWalletSummary().get().getWallet();
log.debug("Shutdown wallet autosave at height: {} ", wallet.getLastBlockSeenHeight());
wallet.shutdownAutosaveAndWait();
} catch (IllegalStateException ise) {
// If there is no autosaving set up yet then that is ok
if (!ise.getMessage().contains("Auto saving not enabled.")) {
throw ise;
}
}
} else {
log.info("No current wallet summary to provide wallet");
}
}
}
|
//FILE: VirtualAcquisitionDisplay.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.acquisition;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.micromanager.api.DisplayControls;
import java.lang.reflect.InvocationTargetException;
import org.micromanager.api.ImageCacheListener;
import ij.ImageStack;
import ij.process.LUT;
import ij.CompositeImage;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.gui.ScrollbarWithLabel;
import ij.gui.StackWindow;
import ij.gui.Toolbar;
import ij.io.FileInfo;
import ij.measure.Calibration;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import mmcorej.TaggedImage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.ImageCache;
import org.micromanager.utils.AcqOrderMode;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
public final class VirtualAcquisitionDisplay implements ImageCacheListener {
public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) {
ImageStack stack = imgp.getStack();
if (stack instanceof AcquisitionVirtualStack) {
return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay();
} else {
return null;
}
}
final static Color[] rgb = {Color.red, Color.green, Color.blue};
final static String[] rgbNames = {"Red", "Blue", "Green"};
final ImageCache imageCache_;
final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass());
private static final String SIMPLE_WIN_X = "simple_x";
private static final String SIMPLE_WIN_Y = "simple_y";
private static final String PREF_WIN_LENGTH = "preferred_window_max_length";
private AcquisitionEngine eng_;
private boolean finished_ = false;
private boolean promptToSave_ = true;
private String name_;
private long lastDisplayTime_;
private int lastFrameShown_ = 0;
private int lastSliceShown_ = 0;
private int lastPositionShown_ = 0;
private boolean updating_ = false;
private int[] channelInitiated_;
private int preferredSlice_ = -1;
private int preferredPosition_ = -1;
private int preferredChannel_ = -1;
private Timer preferredPositionTimer_;
private int numComponents_;
private ImagePlus hyperImage_;
private ScrollbarWithLabel pSelector_;
private ScrollbarWithLabel tSelector_;
private ScrollbarWithLabel zSelector_;
private ScrollbarWithLabel cSelector_;
private DisplayControls controls_;
public AcquisitionVirtualStack virtualStack_;
private boolean simple_ = false;
private boolean mda_ = false; //flag if display corresponds to MD acquisition
private MetadataPanel mdPanel_;
private boolean newDisplay_ = true; //used for autostretching on window opening
private double framesPerSec_ = 7;
private Timer zAnimationTimer_;
private Timer tAnimationTimer_;
private int animatedSliceIndex_ = -1;
private Component zIcon_, pIcon_, tIcon_, cIcon_;
private HashMap<Integer, Integer> zStackMins_;
private HashMap<Integer, Integer> zStackMaxes_;
/* This interface and the following two classes
* allow us to manipulate the dimensions
* in an ImagePlus without it throwing conniptions.
*/
public interface IMMImagePlus {
public int getNChannelsUnverified();
public int getNSlicesUnverified();
public int getNFramesUnverified();
public void setNChannelsUnverified(int nChannels);
public void setNSlicesUnverified(int nSlices);
public void setNFramesUnverified(int nFrames);
public void drawWithoutUpdate();
}
public class MMCompositeImage extends CompositeImage implements IMMImagePlus {
public VirtualAcquisitionDisplay display_;
MMCompositeImage(ImagePlus imgp, int type, VirtualAcquisitionDisplay disp) {
super(imgp, type);
display_ = disp;
}
@Override
public String getTitle() {
return name_;
}
@Override
public int getImageStackSize() {
return super.nChannels * super.nSlices * super.nFrames;
}
@Override
public int getStackSize() {
return getImageStackSize();
}
@Override
public int getNChannelsUnverified() {
return super.nChannels;
}
@Override
public int getNSlicesUnverified() {
return super.nSlices;
}
@Override
public int getNFramesUnverified() {
return super.nFrames;
}
@Override
public void setNChannelsUnverified(int nChannels) {
super.nChannels = nChannels;
}
@Override
public void setNSlicesUnverified(int nSlices) {
super.nSlices = nSlices;
}
@Override
public void setNFramesUnverified(int nFrames) {
super.nFrames = nFrames;
}
private void superReset() {
super.reset();
}
@Override
public void reset() {
if (SwingUtilities.isEventDispatchThread()) {
super.reset();
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
superReset();
}
});
}
}
/*
* ImageJ workaround: the following two functions set the currentChannel field to -1, which can lead to a null
* pointer exception if the function is called while CompositeImage.updateImage is also running on a different
* Thread. So we make sure they are all on the EDT so this never happens
*/
@Override
public synchronized void setMode(final int mode) {
Runnable runnable = new Runnable() {
@Override
public void run() {
superSetMode(mode);
}
};
invokeLaterIfNotEDT(runnable);
}
private void superSetMode(int mode) {
super.setMode(mode);
}
@Override
public synchronized void setChannelLut(final LUT lut) {
Runnable runnable = new Runnable() {
@Override
public void run() {
superSetLut(lut);
}
};
invokeLaterIfNotEDT(runnable);
}
private void superSetLut(LUT lut) {
super.setChannelLut(lut);
}
@Override
public synchronized void updateImage() {
Runnable runnable = new Runnable() {
@Override
public void run() {
superUpdateImage();
}
};
invokeLaterIfNotEDT(runnable);
}
private void superUpdateImage() {
super.updateImage();
}
@Override
public void updateAndDraw() {
Runnable runnable = new Runnable() {
@Override
public void run() {
imageChangedUpdate();
superUpdateImage();
try {
JavaUtils.invokeRestrictedMethod(this, ImagePlus.class, "notifyListeners", 2);
} catch (Exception ex) { }
superDraw();
}
};
invokeLaterIfNotEDT(runnable);
}
private void superDraw() {
super.draw();
}
@Override
public void draw() {
Runnable runnable = new Runnable() {
public void run() {
imageChangedUpdate();
superDraw();
}
};
invokeLaterIfNotEDT(runnable);
}
@Override
public void drawWithoutUpdate() {
super.getWindow().getCanvas().setImageUpdated();
super.draw();
}
}
public class MMImagePlus extends ImagePlus implements IMMImagePlus {
public VirtualAcquisitionDisplay display_;
MMImagePlus(String title, ImageStack stack, VirtualAcquisitionDisplay disp) {
super(title, stack);
display_ = disp;
}
@Override
public String getTitle() {
return name_;
}
@Override
public int getImageStackSize() {
return super.nChannels * super.nSlices * super.nFrames;
}
@Override
public int getStackSize() {
return getImageStackSize();
}
@Override
public int getNChannelsUnverified() {
return super.nChannels;
}
@Override
public int getNSlicesUnverified() {
return super.nSlices;
}
@Override
public int getNFramesUnverified() {
return super.nFrames;
}
@Override
public void setNChannelsUnverified(int nChannels) {
super.nChannels = nChannels;
}
@Override
public void setNSlicesUnverified(int nSlices) {
super.nSlices = nSlices;
}
@Override
public void setNFramesUnverified(int nFrames) {
super.nFrames = nFrames;
}
private void superDraw() {
super.draw();
}
@Override
public void draw() {
if (!SwingUtilities.isEventDispatchThread()) {
Runnable onEDT = new Runnable() {
public void run() {
imageChangedUpdate();
superDraw();
}
};
SwingUtilities.invokeLater(onEDT);
} else {
imageChangedUpdate();
super.draw();
}
}
@Override
public void drawWithoutUpdate() {
//ImageJ requires this
super.getWindow().getCanvas().setImageUpdated();
super.draw();
}
}
public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) {
this(imageCache, eng, WindowManager.getUniqueName("Untitled"));
}
public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) {
name_ = name;
imageCache_ = imageCache;
eng_ = eng;
pSelector_ = createPositionScrollbar();
imageCache_.setDisplay(this);
mda_ = eng != null;
zStackMins_ = new HashMap<Integer, Integer>();
zStackMaxes_ = new HashMap<Integer, Integer>();
}
//used for snap and live
public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException {
simple_ = true;
imageCache_ = imageCache;
name_ = name;
System.out.println();
imageCache_.setDisplay(this);
mda_ = false;
}
private void invokeAndWaitIfNotEDT(Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
} catch (InvocationTargetException ex) {
System.out.println(ex.getCause());
}
}
}
private void invokeLaterIfNotEDT(Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
SwingUtilities.invokeLater(runnable);
}
}
private void startup(JSONObject firstImageMetadata) {
mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel();
JSONObject summaryMetadata = getSummaryMetadata();
int numSlices = 1;
int numFrames = 1;
int numChannels = 1;
int numGrayChannels;
int numPositions = 0;
int width = 0;
int height = 0;
int numComponents = 1;
try {
if (firstImageMetadata != null) {
width = MDUtils.getWidth(firstImageMetadata);
height = MDUtils.getHeight(firstImageMetadata);
} else {
width = MDUtils.getWidth(summaryMetadata);
height = MDUtils.getHeight(summaryMetadata);
}
numSlices = Math.max(summaryMetadata.getInt("Slices"), 1);
numFrames = Math.max(summaryMetadata.getInt("Frames"), 1);
int imageChannelIndex;
try {
imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata);
} catch (Exception e) {
imageChannelIndex = -1;
}
numChannels = Math.max(1 + imageChannelIndex,
Math.max(summaryMetadata.getInt("Channels"), 1));
numPositions = Math.max(summaryMetadata.getInt("Positions"), 0);
numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1);
} catch (Exception e) {
ReportingUtils.showError(e);
}
numComponents_ = numComponents;
numGrayChannels = numComponents_ * numChannels;
channelInitiated_ = new int[numGrayChannels];
if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) {
imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata));
}
int type = 0;
try {
if (firstImageMetadata != null) {
type = MDUtils.getSingleChannelType(firstImageMetadata);
} else {
type = MDUtils.getSingleChannelType(summaryMetadata);
}
} catch (Exception ex) {
ReportingUtils.showError(ex, "Unable to determine acquisition type.");
}
virtualStack_ = new AcquisitionVirtualStack(width, height, type, null,
imageCache_, numGrayChannels * numSlices * numFrames, this);
if (summaryMetadata.has("PositionIndex")) {
try {
virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata));
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
if (simple_) {
controls_ = new SimpleWindowControls(this);
} else {
controls_ = new HyperstackControls(this);
}
hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_),
numGrayChannels, numSlices, numFrames, virtualStack_, controls_);
applyPixelSizeCalibration(hyperImage_);
mdPanel_.setup(null);
createWindow();
//Make sure contrast panel sets up correctly here
windowToFront();
setupMetadataPanel();
cSelector_ = getSelector("c");
if (!simple_) {
tSelector_ = getSelector("t");
zSelector_ = getSelector("z");
if (zSelector_ != null) {
zSelector_.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
preferredSlice_ = zSelector_.getValue();
}
});
}
if (cSelector_ != null) {
cSelector_.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
preferredChannel_ = cSelector_.getValue();
}
});
}
if (imageCache_.lastAcquiredFrame() > 1) {
setNumFrames(1 + imageCache_.lastAcquiredFrame());
} else {
setNumFrames(1);
}
configureAnimationControls();
//cant use these function because of an imageJ bug
// setNumSlices(numSlices);
setNumPositions(numPositions);
}
updateAndDraw();
updateWindowTitleAndStatus();
forcePainting();
}
private void forcePainting() {
Runnable forcePaint = new Runnable() {
public void run() {
if (zIcon_ != null) {
zIcon_.paint(zIcon_.getGraphics());
}
if (tIcon_ != null) {
tIcon_.paint(tIcon_.getGraphics());
}
if (cIcon_ != null) {
cIcon_.paint(cIcon_.getGraphics());
}
if (controls_ != null) {
controls_.paint(controls_.getGraphics());
}
if (pIcon_ != null && pIcon_.isValid()) {
pIcon_.paint(pIcon_.getGraphics());
}
}
};
if (SwingUtilities.isEventDispatchThread()) {
forcePaint.run();
} else {
try {
SwingUtilities.invokeAndWait(forcePaint);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
}
private void animateSlices(boolean animate) {
if (zAnimationTimer_ == null) {
zAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int slice = hyperImage_.getSlice();
if (slice >= zSelector_.getMaximum() - 1) {
hyperImage_.setPosition(hyperImage_.getChannel(), 1, hyperImage_.getFrame());
} else {
hyperImage_.setPosition(hyperImage_.getChannel(), slice + 1, hyperImage_.getFrame());
}
}
});
}
if (!animate) {
zAnimationTimer_.stop();
refreshAnimationIcons();
return;
}
if (tAnimationTimer_ != null) {
animateFrames(false);
}
zAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_));
zAnimationTimer_.start();
refreshAnimationIcons();
}
private void animateFrames(boolean animate) {
if (tAnimationTimer_ == null) {
tAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int frame = hyperImage_.getFrame();
if (frame >= tSelector_.getMaximum() - 1) {
hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), 1);
} else {
hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame + 1);
}
}
});
}
if (!animate) {
tAnimationTimer_.stop();
refreshAnimationIcons();
return;
}
if (zAnimationTimer_ != null) {
animateSlices(false);
}
tAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_));
tAnimationTimer_.start();
refreshAnimationIcons();
}
private void refreshAnimationIcons() {
if (zIcon_ != null) {
zIcon_.repaint();
}
if (tIcon_ != null) {
tIcon_.repaint();
}
}
private void configureAnimationControls() {
if (zIcon_ != null) {
zIcon_.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
animateSlices(zAnimationTimer_ == null || !zAnimationTimer_.isRunning());
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
if (tIcon_ != null) {
tIcon_.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
animateFrames(tAnimationTimer_ == null || !tAnimationTimer_.isRunning());
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
}
/**
* Allows bypassing the prompt to Save
* @param promptToSave boolean flag
*/
public void promptToSave(boolean promptToSave) {
promptToSave_ = promptToSave;
}
/*
* Method required by ImageCacheListener
*/
@Override
public void imageReceived(final TaggedImage taggedImage) {
if (eng_ != null) {
updateDisplay(taggedImage, false);
}
}
/*
* Method required by ImageCacheListener
*/
@Override
public void imagingFinished(String path) {
updateDisplay(null, true);
updateAndDraw();
if (eng_ != null && !eng_.abortRequested()) {
updateWindowTitleAndStatus();
}
}
private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) {
try {
long t = System.currentTimeMillis();
JSONObject tags;
if (taggedImage != null) {
tags = taggedImage.tags;
} else {
tags = imageCache_.getLastImageTags();
}
if (tags == null) {
return;
}
int frame = MDUtils.getFrameIndex(tags);
int ch = MDUtils.getChannelIndex(tags);
int slice = MDUtils.getSliceIndex(tags);
int position = MDUtils.getPositionIndex(tags);
boolean show = finalUpdate || frame == 0 || (Math.abs(t - lastDisplayTime_) > 30)
|| (ch == getNumChannels() - 1 && lastFrameShown_ == frame
&& lastSliceShown_ == slice && lastPositionShown_ == position)
|| (slice == getNumSlices() - 1 && frame == 0 && position == 0 && ch == getNumChannels() - 1);
if (show) {
showImage(tags, true);
lastFrameShown_ = frame;
lastSliceShown_ = slice;
lastPositionShown_ = position;
lastDisplayTime_ = t;
forceImagePaint();
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
}
private void forceImagePaint() {
hyperImage_.getWindow().getCanvas().paint(hyperImage_.getWindow().getCanvas().getGraphics());
}
public int rgbToGrayChannel(int channelIndex) {
try {
if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) {
return channelIndex * 3;
}
return channelIndex;
} catch (Exception ex) {
ReportingUtils.logError(ex);
return 0;
}
}
public int grayToRGBChannel(int grayIndex) {
try {
if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) {
return grayIndex / 3;
}
return grayIndex;
} catch (Exception ex) {
ReportingUtils.logError(ex);
return 0;
}
}
public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) {
try {
JSONObject displaySettings = new JSONObject();
JSONArray chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors");
JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames");
JSONArray chMaxes, chMins;
if ( summaryMetadata.has("ChContrastMin")) {
chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin");
} else {
chMins = new JSONArray();
for (int i = 0; i < chNames.length(); i++)
chMins.put(0);
}
if ( summaryMetadata.has("ChContrastMax")) {
chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax");
} else {
int max = 65536;
if (summaryMetadata.has("BitDepth"))
max = (int) (Math.pow(2, summaryMetadata.getInt("BitDepth"))-1);
chMaxes = new JSONArray();
for (int i = 0; i < chNames.length(); i++)
chMaxes.put(max);
}
int numComponents = MDUtils.getNumberOfComponents(summaryMetadata);
JSONArray channels = new JSONArray();
if (numComponents > 1) //RGB
{
int rgbChannelBitDepth = summaryMetadata.getString("PixelType").endsWith("32") ? 8 : 16;
for (int k = 0; k < 3; k++) {
JSONObject channelObject = new JSONObject();
channelObject.put("Color", rgb[k].getRGB());
channelObject.put("Name", rgbNames[k]);
channelObject.put("Gamma", 1.0);
channelObject.put("Min", 0);
channelObject.put("Max", Math.pow(2, rgbChannelBitDepth) - 1);
channels.put(channelObject);
}
} else {
for (int k = 0; k < chNames.length(); ++k) {
String name = (String) chNames.get(k);
int color = chColors.getInt(k);
int min = chMins.getInt(k);
int max = chMaxes.getInt(k);
JSONObject channelObject = new JSONObject();
channelObject.put("Color", color);
channelObject.put("Name", name);
channelObject.put("Gamma", 1.0);
channelObject.put("Min", min);
channelObject.put("Max", max);
channels.put(channelObject);
}
}
displaySettings.put("Channels", channels);
JSONObject comments = new JSONObject();
String summary = "";
try {
summary = summaryMetadata.getString("Comment");
} catch (JSONException ex) {
summaryMetadata.put("Comment", "");
}
comments.put("Summary", summary);
displaySettings.put("Comments", comments);
return displaySettings;
} catch (Exception e) {
ReportingUtils.showError("Error creating display settigns from summary metadata");
return null;
}
}
/**
* Sets ImageJ pixel size calibration
* @param hyperImage
*/
private void applyPixelSizeCalibration(final ImagePlus hyperImage) {
try {
double pixSizeUm = getSummaryMetadata().getDouble("PixelSize_um");
if (pixSizeUm > 0) {
Calibration cal = new Calibration();
cal.setUnit("um");
cal.pixelWidth = pixSizeUm;
cal.pixelHeight = pixSizeUm;
hyperImage.setCalibration(cal);
}
} catch (JSONException ex) {
// no pixelsize defined. Nothing to do
}
}
private void setNumPositions(int n) {
if (simple_) {
return;
}
pSelector_.setMinimum(0);
pSelector_.setMaximum(n);
ImageWindow win = hyperImage_.getWindow();
if (n > 1 && pSelector_.getParent() == null) {
win.add(pSelector_, win.getComponentCount() - 1);
} else if (n <= 1 && pSelector_.getParent() != null) {
win.remove(pSelector_);
}
win.pack();
}
private void setNumFrames(int n) {
if (simple_) {
return;
}
if (tSelector_ != null) {
//ImageWindow win = hyperImage_.getWindow();
((IMMImagePlus) hyperImage_).setNFramesUnverified(n);
tSelector_.setMaximum(n + 1);
// JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n);
}
}
private void setNumSlices(int n) {
if (simple_) {
return;
}
if (zSelector_ != null) {
((IMMImagePlus) hyperImage_).setNSlicesUnverified(n);
zSelector_.setMaximum(n + 1);
}
}
private void setNumChannels(int n) {
if (cSelector_ != null) {
((IMMImagePlus) hyperImage_).setNChannelsUnverified(n);
cSelector_.setMaximum(n);
}
}
public ImagePlus getHyperImage() {
return hyperImage_;
}
public int getStackSize() {
if (hyperImage_ == null) {
return -1;
}
int s = hyperImage_.getNSlices();
int c = hyperImage_.getNChannels();
int f = hyperImage_.getNFrames();
if ((s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1)) {
return s * c * f;
}
return Math.max(Math.max(s, c), f);
}
private void imageChangedWindowUpdate() {
if (hyperImage_ != null && hyperImage_.isVisible()) {
TaggedImage ti = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice());
if (ti != null) {
controls_.newImageUpdate(ti.tags);
}
}
}
public void updateAndDraw() {
if (!updating_) {
updating_ = true;
setupMetadataPanel();
if (hyperImage_ != null && hyperImage_.isVisible()) {
hyperImage_.updateAndDraw();
}
updating_ = false;
}
}
public void updateWindowTitleAndStatus() {
if (simple_) {
int mag = (int) (100 * hyperImage_.getCanvas().getMagnification());
String title = hyperImage_.getTitle() + " ("+mag+"%)";
hyperImage_.getWindow().setTitle(title);
return;
}
if (controls_ == null) {
return;
}
String status = "";
final AcquisitionEngine eng = eng_;
if (eng != null) {
if (acquisitionIsRunning()) {
if (!abortRequested()) {
controls_.acquiringImagesUpdate(true);
if (isPaused()) {
status = "paused";
} else {
status = "running";
}
} else {
controls_.acquiringImagesUpdate(false);
status = "interrupted";
}
} else {
controls_.acquiringImagesUpdate(false);
if (!status.contentEquals("interrupted")) {
if (eng.isFinished()) {
status = "finished";
eng_ = null;
}
}
}
status += ", ";
if (eng.isFinished()) {
eng_ = null;
finished_ = true;
}
} else {
if (finished_ == true) {
status = "finished, ";
}
controls_.acquiringImagesUpdate(false);
}
if (isDiskCached()) {
status += "on disk";
} else {
status += "not yet saved";
}
controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null);
String path = isDiskCached()
? new File(imageCache_.getDiskLocation()).getName() : name_;
if (hyperImage_.isVisible()) {
int mag = (int) (100 * hyperImage_.getCanvas().getMagnification());
hyperImage_.getWindow().setTitle(path + " (" + status + ") (" + mag + "%)" );
}
}
private void windowToFront() {
if (hyperImage_ == null || hyperImage_.getWindow() == null) {
return;
}
hyperImage_.getWindow().toFront();
}
private void setupMetadataPanel() {
if (hyperImage_ == null || hyperImage_.getWindow() == null) {
return;
}
//call this explicitly because it isn't fired immediately
mdPanel_.setup(hyperImage_.getWindow());
}
/**
* Displays tagged image in the multi-D viewer
* Will wait for the screen update
*
* @param taggedImg
* @throws Exception
*/
public void showImage(TaggedImage taggedImg) throws Exception {
showImage(taggedImg, true);
}
/**
* Displays tagged image in the multi-D viewer
* Optionally waits for the display to draw the image
* *
* @param taggedImg
* @throws Exception
*/
public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws InterruptedException, InvocationTargetException {
showImage(taggedImg.tags, waitForDisplay);
}
public void showImage(JSONObject tags, boolean waitForDisplay) throws InterruptedException, InvocationTargetException {
updateWindowTitleAndStatus();
if (tags == null) {
return;
}
if (hyperImage_ == null) {
startup(tags);
}
int channel = 0, frame = 0, slice = 0, position = 0, superChannel = 0;
try {
frame = MDUtils.getFrameIndex(tags);
slice = MDUtils.getSliceIndex(tags);
channel = MDUtils.getChannelIndex(tags);
position = MDUtils.getPositionIndex(tags);
superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(tags));
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
//This block allows animation to be reset to where it was before iamges were added
final boolean framesAnimated = isTAnimated(), slicesAnimated = isZAnimated();
final int animatedFrameIndex = hyperImage_.getFrame();
if (slice == 0)
animatedSliceIndex_ = hyperImage_.getSlice();
if (framesAnimated || slicesAnimated) {
animateFrames(false);
animateSlices(false);
}
//make sure pixels get properly set
if (hyperImage_ != null && frame == 0) {
IMMImagePlus img = (IMMImagePlus) hyperImage_;
if (img.getNChannelsUnverified() == 1) {
if (img.getNSlicesUnverified() == 1) {
hyperImage_.getProcessor().setPixels(virtualStack_.getPixels(1));
}
} else if (hyperImage_ instanceof MMCompositeImage) {
//reset rebuilds each of the channel ImageProcessors with the correct pixels
//from AcquisitionVirtualStack
MMCompositeImage ci = ((MMCompositeImage) hyperImage_);
ci.reset();
//This line is neccessary for image processor to have correct pixels in grayscale mode
ci.getProcessor().setPixels(virtualStack_.getPixels(ci.getCurrentSlice()));
}
} else if (hyperImage_ instanceof MMCompositeImage) {
MMCompositeImage ci = ((MMCompositeImage) hyperImage_);
ci.reset();
}
if (cSelector_ != null) {
if (cSelector_.getMaximum() <= (1 + superChannel)) {
this.setNumChannels(1 + superChannel);
((CompositeImage) hyperImage_).reset();
//JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class,
// "setupLuts", 1 + superChannel, Integer.TYPE);
}
}
initializeContrast(channel, slice);
if (!simple_) {
if (tSelector_ != null) {
if (tSelector_.getMaximum() <= (1 + frame)) {
this.setNumFrames(1 + frame);
}
}
if (position + 1 >= getNumPositions()) {
setNumPositions(position + 1);
}
setPosition(position);
hyperImage_.setPosition(1 + superChannel, 1 + slice, 1 + frame);
}
Runnable updateAndDraw = new Runnable() {
public void run() {
updateAndDraw();
restartAnimationAfterShowing(animatedFrameIndex, animatedSliceIndex_, framesAnimated, slicesAnimated);
}
};
if (!SwingUtilities.isEventDispatchThread()) {
if (waitForDisplay) {
SwingUtilities.invokeAndWait(updateAndDraw);
} else {
SwingUtilities.invokeLater(updateAndDraw);
}
} else {
updateAndDraw();
restartAnimationAfterShowing(animatedFrameIndex, animatedSliceIndex_, framesAnimated, slicesAnimated);
}
if (eng_!= null)
setPreferredScrollbarPositions();
}
/**
* If animation was running prior to showImage, restarts it with sliders at appropriate positions
*/
private void restartAnimationAfterShowing(int frame, int slice, boolean framesAnimated, boolean slicesAnimated) {
if (framesAnimated) {
hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame+1);
animateFrames(true);
} else if (slicesAnimated) {
hyperImage_.setPosition(hyperImage_.getChannel(), slice+1, hyperImage_.getFrame());
animateSlices(true);
System.out.println(slice);
}
}
/*
* Live/snap should load window contrast settings
* MDA should autoscale on frist image
* Opening dataset should load from disoplay and comments
*/
private void initializeContrast(final int channel, final int slice) {
Runnable autoscaleOrLoadContrast = new Runnable() {
public void run() {
if (!newDisplay_) {
return;
}
if (simple_) { //Snap/live
if (hyperImage_ instanceof MMCompositeImage
&& ((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) {
return;
}
mdPanel_.loadSimpleWinContrastWithoutDraw(imageCache_, hyperImage_);
} else if (mda_) { //Multi D acquisition
IMMImagePlus immImg = ((IMMImagePlus) hyperImage_);
if (immImg.getNSlicesUnverified() > 1) { //Z stacks
mdPanel_.autoscaleOverStackWithoutDraw(imageCache_, hyperImage_, channel, zStackMins_, zStackMaxes_);
if (channel != immImg.getNChannelsUnverified() - 1 || slice != immImg.getNSlicesUnverified() - 1) {
return; //don't set new display to false until all channels autscaled
}
} else { //No z stacks
mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_);
if (immImg.getNChannelsUnverified() - 1 != channel) {
return;
}
}
} else //Acquire button
if (hyperImage_ instanceof MMCompositeImage) {
if (((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) {
return;
}
mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_);
} else {
mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); // else do nothing because contrast automatically loaded from cache
}
newDisplay_ = false;
}
};
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(autoscaleOrLoadContrast);
} else {
autoscaleOrLoadContrast.run();
}
}
private void setPreferredScrollbarPositions() {
if (preferredPositionTimer_ == null) {
preferredPositionTimer_ = new Timer(250, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int c = preferredChannel_ == -1 ? hyperImage_.getChannel() : preferredChannel_;
int s = preferredSlice_ == -1 ? hyperImage_.getSlice() : preferredSlice_;
boolean zAnimated = zAnimationTimer_ != null && zAnimationTimer_.isRunning();
hyperImage_.setPosition(c, zAnimated ? hyperImage_.getSlice() : s ,hyperImage_.getFrame());
if (pSelector_ != null && preferredPosition_ > -1) {
if (eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_CHANNEL_SLICE
&& eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_SLICE_CHANNEL) {
setPosition(preferredPosition_);
}
}
preferredPositionTimer_.stop();
}
});
}
if (preferredPositionTimer_.isRunning()) {
preferredPositionTimer_.restart();
} else {
preferredPositionTimer_.start();
}
}
private void updatePosition(int p) {
if (simple_) {
return;
}
virtualStack_.setPositionIndex(p);
if (!hyperImage_.isComposite()) {
Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice());
hyperImage_.getProcessor().setPixels(pixels);
} else {
CompositeImage ci = (CompositeImage) hyperImage_;
if (ci.getMode() == CompositeImage.COMPOSITE) {
for (int i = 0; i < ((MMCompositeImage) ci).getNChannelsUnverified(); i++) {
ci.getProcessor(i + 1).setPixels(virtualStack_.getPixels(
ci.getCurrentSlice() - ci.getChannel() + i + 1));
}
}
ci.getProcessor().setPixels(virtualStack_.getPixels(hyperImage_.getCurrentSlice()));
}
//need to call this even though updateAndDraw also calls it to get autostretch to work properly
imageChangedUpdate();
updateAndDraw();
}
public void setPosition(int p) {
if (simple_) {
return;
}
pSelector_.setValue(p);
}
public void setSliceIndex(int i) {
if (simple_) {
return;
}
final int f = hyperImage_.getFrame();
final int c = hyperImage_.getChannel();
hyperImage_.setPosition(c, i + 1, f);
}
public int getSliceIndex() {
return hyperImage_.getSlice() - 1;
}
boolean pause() {
if (eng_ != null) {
if (eng_.isPaused()) {
eng_.setPause(false);
} else {
eng_.setPause(true);
}
updateWindowTitleAndStatus();
return (eng_.isPaused());
}
return false;
}
boolean abort() {
if (eng_ != null) {
if (eng_.abortRequest()) {
updateWindowTitleAndStatus();
return true;
}
}
return false;
}
public boolean acquisitionIsRunning() {
if (eng_ != null) {
return eng_.isAcquisitionRunning();
} else {
return false;
}
}
public long getNextWakeTime() {
return eng_.getNextWakeTime();
}
public boolean abortRequested() {
if (eng_ != null) {
return eng_.abortRequested();
} else {
return false;
}
}
private boolean isPaused() {
if (eng_ != null) {
return eng_.isPaused();
} else {
return false;
}
}
boolean saveAs() {
String prefix;
String root;
for (;;) {
File f = FileDialogs.save(hyperImage_.getWindow(),
"Please choose a location for the data set",
MMStudioMainFrame.MM_DATA_SET);
if (f == null) // Canceled.
{
return false;
}
prefix = f.getName();
root = new File(f.getParent()).getAbsolutePath();
if (f.exists()) {
ReportingUtils.showMessage(prefix
+ " is write only! Please choose another name.");
} else {
break;
}
}
TaggedImageStorageDiskDefault newFileManager = new TaggedImageStorageDiskDefault(root + "/" + prefix, true,
getSummaryMetadata());
imageCache_.saveAs(newFileManager, mda_);
MMStudioMainFrame.getInstance().setAcqDirectory(root);
updateWindowTitleAndStatus();
return true;
}
final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) {
MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack, this);
FileInfo fi = new FileInfo();
fi.width = virtualStack.getWidth();
fi.height = virtualStack.getHeight();
fi.fileName = virtualStack.getDirectory();
fi.url = null;
img.setFileInfo(fi);
return img;
}
final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices,
int frames, final AcquisitionVirtualStack virtualStack,
DisplayControls hc) {
final ImagePlus hyperImage;
mmIP.setNChannelsUnverified(channels);
mmIP.setNFramesUnverified(frames);
mmIP.setNSlicesUnverified(slices);
if (channels > 1) {
hyperImage = new MMCompositeImage(mmIP, CompositeImage.COMPOSITE, this);
hyperImage.setOpenAsHyperStack(true);
} else {
hyperImage = mmIP;
mmIP.setOpenAsHyperStack(true);
}
return hyperImage;
}
public void liveModeEnabled(boolean enabled) {
if (simple_) {
controls_.acquiringImagesUpdate(enabled);
}
}
public void storeWindowSizeAfterZoom(ImageWindow win) {
int currentLength = (win.getSize().width + win.getSize().height) / 2;
prefs_.putInt(PREF_WIN_LENGTH, Math.max(currentLength, 512));
}
private void createWindow() {
final DisplayWindow win = new DisplayWindow(hyperImage_);
win.getCanvas().addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent me) {
}
//used to store preferred zoom
public void mousePressed(MouseEvent me) {
if (Toolbar.getToolId() == 11) {//zoom tool selected
storeWindowSizeAfterZoom(win);
}
updateWindowTitleAndStatus();
}
//updates the histogram after an ROI is drawn
public void mouseReleased(MouseEvent me) {
mdPanel_.refresh();
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
});
win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor());
MMStudioMainFrame.getInstance().addMMBackgroundListener(win);
win.add(controls_);
win.pack();
if (simple_) {
win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0), prefs_.getInt(SIMPLE_WIN_Y, 0));
}
//Set magnification
zoomToPreferredSize(win);
}
private void zoomToPreferredSize(DisplayWindow win) {
int prefLength = prefs_.getInt(PREF_WIN_LENGTH, 512);
int winLength = (int) Math.sqrt(win.getSize().width * win.getSize().height);
double percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength));
ImageCanvas canvas = win.getCanvas();
if (winLength < prefLength) {
while (winLength < prefLength) {
percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength));
canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2);
int newWinLength = (int) Math.sqrt(win.getSize().width * win.getSize().height);
if (newWinLength == winLength)
break;
winLength = newWinLength;
}
double newPercentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength));
if (newPercentDiff > percentDiff) {
canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2);
}
} else if (winLength > prefLength) {
while (winLength > prefLength) {
percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength));
canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2);
int newWinLength = (int) Math.sqrt(win.getSize().width * win.getSize().height);
if (newWinLength == winLength)
break;
winLength = newWinLength;
}
double newPercentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength));
if (newPercentDiff > percentDiff) {
canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2);
}
}
Rectangle rect = canvas.getSrcRect();
if (rect != null) {
while (rect.width < canvas.getImage().getWidth() || rect.height < canvas.getImage().getHeight()) {
if (rect.width > 0.9 * canvas.getImage().getWidth() && rect.height > 0.9 * canvas.getImage().getHeight()) {
canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2);
canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2);
break;
} else {
canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2);
}
rect = canvas.getSrcRect();
if (rect == null) {
break;
}
}
}
}
private ScrollbarWithLabel getSelector(String label) {
// label should be "t", "z", or "c"
ScrollbarWithLabel selector = null;
ImageWindow win = hyperImage_.getWindow();
int slices = ((IMMImagePlus) hyperImage_).getNSlicesUnverified();
int frames = ((IMMImagePlus) hyperImage_).getNFramesUnverified();
int channels = ((IMMImagePlus) hyperImage_).getNChannelsUnverified();
if (win instanceof StackWindow) {
try {
//ImageJ bug workaround
if (frames > 1 && slices == 1 && channels == 1 && label.equals("t")) {
selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector");
} else {
selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector");
}
} catch (NoSuchFieldException ex) {
selector = null;
ReportingUtils.logError(ex);
}
}
//replace default icon with custom one
if (selector != null) {
try {
Component icon = (Component) JavaUtils.getRestrictedFieldValue(
selector, ScrollbarWithLabel.class, "icon");
selector.remove(icon);
} catch (NoSuchFieldException ex) {
ReportingUtils.logError(ex);
}
ScrollbarIcon newIcon = new ScrollbarIcon(label.charAt(0), this);
if (label.equals("z")) {
zIcon_ = newIcon;
} else if (label.equals("t")) {
tIcon_ = newIcon;
} else if (label.equals("c")) {
cIcon_ = newIcon;
}
selector.add(newIcon, BorderLayout.WEST);
selector.invalidate();
selector.validate();
}
return selector;
}
private ScrollbarWithLabel createPositionScrollbar() {
final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') {
@Override
public void setValue(int v) {
if (this.getValue() != v) {
super.setValue(v);
updatePosition(v);
}
}
};
// prevents scroll bar from blinking on Windows:
pSelector.setFocusable(false);
pSelector.setUnitIncrement(1);
pSelector.setBlockIncrement(1);
pSelector.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
updatePosition(pSelector.getValue());
preferredPosition_ = pSelector_.getValue();
}
});
if (pSelector != null) {
try {
Component icon = (Component) JavaUtils.getRestrictedFieldValue(
pSelector, ScrollbarWithLabel.class, "icon");
pSelector.remove(icon);
} catch (NoSuchFieldException ex) {
ReportingUtils.logError(ex);
}
pIcon_ = new ScrollbarIcon('p', this);
pSelector.add(pIcon_, BorderLayout.WEST);
pSelector.invalidate();
pSelector.validate();
}
return pSelector;
}
public JSONObject getCurrentMetadata() {
try {
if (hyperImage_ != null) {
TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice());
if (image != null) {
return image.tags;
} else {
return null;
}
} else {
return null;
}
} catch (NullPointerException ex) {
return null;
}
}
public int getCurrentPosition() {
return virtualStack_.getPositionIndex();
}
public int getNumSlices() {
if (simple_) {
return 1;
}
return ((IMMImagePlus) hyperImage_).getNSlicesUnverified();
}
public int getNumFrames() {
if (simple_) {
return 1;
}
return ((IMMImagePlus) hyperImage_).getNFramesUnverified();
}
public int getNumPositions() {
if (simple_) {
return 1;
}
return pSelector_.getMaximum();
}
public ImagePlus getImagePlus() {
return hyperImage_;
}
public ImageCache getImageCache() {
return imageCache_;
}
public ImagePlus getImagePlus(int position) {
ImagePlus iP = new ImagePlus();
iP.setStack(virtualStack_);
iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames());
iP.setFileInfo(hyperImage_.getFileInfo());
return iP;
}
public void setComment(String comment) throws MMScriptException {
try {
getSummaryMetadata().put("Comment", comment);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public final JSONObject getSummaryMetadata() {
return imageCache_.getSummaryMetadata();
}
public void close() {
if (hyperImage_ != null) {
//call this so when one window closes and is replaced by another
//the md panel gets rid of the first before doing stuff with
//the second
if (WindowManager.getCurrentImage() == hyperImage_) {
mdPanel_.setup(null);
}
hyperImage_.getWindow().windowClosing(null);
hyperImage_.close();
}
}
public synchronized boolean windowClosed() {
ImageWindow win = hyperImage_.getWindow();
return (win == null || win.isClosed());
}
public void showFolder() {
if (isDiskCached()) {
try {
File location = new File(imageCache_.getDiskLocation());
if (JavaUtils.isWindows()) {
Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath());
} else if (JavaUtils.isMac()) {
if (!location.isDirectory()) {
location = location.getParentFile();
}
Runtime.getRuntime().exec("open " + location.getAbsolutePath());
}
} catch (IOException ex) {
ReportingUtils.logError(ex);
}
}
}
public void setPlaybackFPS(double fps) {
framesPerSec_ = fps;
if (zAnimationTimer_ != null && zAnimationTimer_.isRunning()) {
animateSlices(false);
animateSlices(true);
} else if (tAnimationTimer_ != null && tAnimationTimer_.isRunning()) {
animateFrames(false);
animateFrames(true);
}
}
public double getPlaybackFPS() {
return framesPerSec_;
}
public boolean isZAnimated() {
if (zAnimationTimer_ != null && zAnimationTimer_.isRunning()) {
return true;
}
return false;
}
public boolean isTAnimated() {
if (tAnimationTimer_ != null && tAnimationTimer_.isRunning()) {
return true;
}
return false;
}
public boolean isAnimated() {
return isTAnimated() || isZAnimated();
}
public String getSummaryComment() {
return imageCache_.getComment();
}
public void setSummaryComment(String comment) {
imageCache_.setComment(comment);
}
void setImageComment(String comment) {
imageCache_.setImageComment(comment, getCurrentMetadata());
}
String getImageComment() {
try {
return imageCache_.getImageComment(getCurrentMetadata());
} catch (NullPointerException ex) {
return "";
}
}
public boolean isDiskCached() {
ImageCache imageCache = imageCache_;
if (imageCache == null) {
return false;
} else {
return imageCache.getDiskLocation() != null;
}
}
public void show() {
if (hyperImage_ == null) {
startup(null);
}
hyperImage_.show();
hyperImage_.getWindow().toFront();
}
public int getNumChannels() {
return ((IMMImagePlus) hyperImage_).getNChannelsUnverified();
}
public int getNumGrayChannels() {
return getNumChannels();
}
public void setWindowTitle(String name) {
name_ = name;
updateWindowTitleAndStatus();
}
public boolean isSimpleDisplay() {
return simple_;
}
public void displayStatusLine(String status) {
controls_.setStatusLabel(status);
}
public void setChannelContrast(int channelIndex, int min, int max, double gamma) {
mdPanel_.setChannelContrast(channelIndex, min, max, gamma);
}
public void setChannelHistogramDisplayMax(int channelIndex, int histMax) {
mdPanel_.setChannelHistogramDisplayMax(channelIndex, histMax);
}
private void imageChangedUpdate() {
mdPanel_.imageChangedUpdate(hyperImage_, imageCache_);
imageChangedWindowUpdate(); //used to update status line
}
public void refreshContrastPanel() {
mdPanel_.refresh();
}
public void drawWithoutUpdate() {
if (hyperImage_ != null) {
((IMMImagePlus) hyperImage_).drawWithoutUpdate();
}
}
public class DisplayWindow extends StackWindow {
private boolean windowClosingDone_ = false;
private boolean closed_ = false;
public DisplayWindow(ImagePlus ip) {
super(ip);
}
@Override
public boolean close() {
windowClosing(null);
return closed_;
}
@Override
public void windowClosing(WindowEvent e) {
if (windowClosingDone_) {
return;
}
if (eng_ != null && eng_.isAcquisitionRunning()) {
if (!abort()) {
return;
}
}
if (imageCache_.getDiskLocation() == null && promptToSave_) {
int result = JOptionPane.showConfirmDialog(this,
"This data set has not yet been saved.\n"
+ "Do you want to save it?",
"Micro-Manager",
JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.YES_OPTION) {
if (!saveAs()) {
return;
}
} else if (result == JOptionPane.CANCEL_OPTION) {
return;
}
}
//for some reason window focus listener doesn't always fire, so call
//explicitly here
mdPanel_.setup(null);
if (simple_ && hyperImage_ != null && hyperImage_.getWindow() != null && hyperImage_.getWindow().getLocation() != null) {
Point loc = hyperImage_.getWindow().getLocation();
prefs_.putInt(SIMPLE_WIN_X, loc.x);
prefs_.putInt(SIMPLE_WIN_Y, loc.y);
mdPanel_.saveContrastSettings(imageCache_);
}
if (imageCache_ != null) {
imageCache_.close();
}
if (!closed_) {
try {
super.close();
} catch (NullPointerException ex) {
ReportingUtils.logError("Null pointer error in ImageJ code while closing window");
}
}
super.windowClosing(e);
MMStudioMainFrame.getInstance().removeMMBackgroundListener(this);
windowClosingDone_ = true;
closed_ = true;
}
@Override
public void windowClosed(WindowEvent E) {
this.windowClosing(E);
super.windowClosed(E);
}
@Override
public void windowActivated(WindowEvent e) {
if (!isClosed()) {
super.windowActivated(e);
}
}
@Override
public void setAnimate(boolean b) {
if (((IMMImagePlus) hyperImage_).getNFramesUnverified() > 1) {
animateFrames(b);
} else {
animateSlices(b);
}
}
@Override
public boolean getAnimate() {
return isAnimated();
}
};
}
|
//FILE: VirtualAcquisitionDisplay.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.acquisition;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.micromanager.api.DisplayControls;
import java.lang.reflect.InvocationTargetException;
import org.micromanager.api.ImageCacheListener;
import ij.ImageStack;
import ij.process.LUT;
import ij.CompositeImage;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.ScrollbarWithLabel;
import ij.gui.StackWindow;
import ij.io.FileInfo;
import ij.measure.Calibration;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import mmcorej.TaggedImage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.ImageCache;
import org.micromanager.utils.AcqOrderMode;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
public final class VirtualAcquisitionDisplay implements ImageCacheListener {
public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) {
ImageStack stack = imgp.getStack();
if (stack instanceof AcquisitionVirtualStack) {
return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay();
} else {
return null;
}
}
final static Color[] rgb = {Color.red, Color.green, Color.blue};
final static String[] rgbNames = {"Red", "Blue", "Green"};
final ImageCache imageCache_;
final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass());
private static final String SIMPLE_WIN_X = "simple_x";
private static final String SIMPLE_WIN_Y = "simple_y";
private AcquisitionEngine eng_;
private boolean finished_ = false;
private boolean promptToSave_ = true;
private String name_;
private long lastDisplayTime_;
private int lastFrameShown_ = 0;
private int lastSliceShown_ = 0;
private int lastPositionShown_ = 0;
private boolean updating_ = false;
private int[] channelInitiated_;
private int preferredSlice_ = -1;
private int preferredPosition_ = -1;
private int preferredChannel_ = -1;
private Timer preferredPositionTimer_;
private int numComponents_;
private ImagePlus hyperImage_;
private ScrollbarWithLabel pSelector_;
private ScrollbarWithLabel tSelector_;
private ScrollbarWithLabel zSelector_;
private ScrollbarWithLabel cSelector_;
private DisplayControls controls_;
public AcquisitionVirtualStack virtualStack_;
private boolean simple_ = false;
private boolean mda_ = false; //flag if display corresponds to MD acquisition
private MetadataPanel mdPanel_;
private boolean newDisplay_ = true; //used for autostretching on window opening
private double framesPerSec_ = 7;
private int firstFrame_;
private int lastFrame_;
private Timer zAnimationTimer_;
private Timer tAnimationTimer_;
private Component zIcon_, pIcon_, tIcon_, cIcon_;
private HashMap<Integer,Integer> zStackMins_;
private HashMap<Integer,Integer> zStackMaxes_;
/* This interface and the following two classes
* allow us to manipulate the dimensions
* in an ImagePlus without it throwing conniptions.
*/
public interface IMMImagePlus {
public int getNChannelsUnverified();
public int getNSlicesUnverified();
public int getNFramesUnverified();
public void setNChannelsUnverified(int nChannels);
public void setNSlicesUnverified(int nSlices);
public void setNFramesUnverified(int nFrames);
public void drawWithoutUpdate();
}
public class MMCompositeImage extends CompositeImage implements IMMImagePlus {
public VirtualAcquisitionDisplay display_;
private boolean updatingImage_, settingMode_, settingLut_;
MMCompositeImage(ImagePlus imgp, int type, VirtualAcquisitionDisplay disp) {
super(imgp, type);
display_ = disp;
}
@Override
public String getTitle() {
return name_;
}
private void superReset() {
super.reset();
}
@Override
public void reset() {
if (SwingUtilities.isEventDispatchThread())
super.reset();
else
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
superReset();
}
});
}
/*
* ImageJ workaround: the following two functions set the currentChannel field to -1, which can lead to a null
* pointer exception if the function is called while CompositeImage.updateImage is also running on a different
* Thread. So we make sure they are all on the EDT so this never happens
*/
@Override
public synchronized void setMode(final int mode) {
Runnable runnable = new Runnable() {
@Override
public void run() {
superSetMode(mode);
}
};
invokeLaterIfNotEDT(runnable);
}
private void superSetMode(int mode) {
super.setMode(mode);
}
@Override
public synchronized void setChannelLut(final LUT lut) {
Runnable runnable = new Runnable() {
@Override
public void run() {
superSetLut(lut);
}
};
invokeLaterIfNotEDT(runnable);
}
private void superSetLut(LUT lut) {
super.setChannelLut(lut);
}
@Override
public synchronized void updateImage() {
Runnable runnable = new Runnable() {
@Override
public void run() {
superUpdateImage();
}
};
invokeLaterIfNotEDT(runnable);
}
private void superUpdateImage() {
super.updateImage();
}
@Override
public int getImageStackSize() {
return super.nChannels * super.nSlices * super.nFrames;
}
@Override
public int getStackSize() {
return getImageStackSize();
}
@Override
public int getNChannelsUnverified() {
return super.nChannels;
}
@Override
public int getNSlicesUnverified() {
return super.nSlices;
}
@Override
public int getNFramesUnverified() {
return super.nFrames;
}
@Override
public void setNChannelsUnverified(int nChannels) {
super.nChannels = nChannels;
}
@Override
public void setNSlicesUnverified(int nSlices) {
super.nSlices = nSlices;
}
@Override
public void setNFramesUnverified(int nFrames) {
super.nFrames = nFrames;
}
private void superDraw() {
super.draw();
}
@Override
public void draw() {
Runnable runnable = new Runnable() {
public void run() {
imageChangedUpdate();
superDraw();
}
};
invokeLaterIfNotEDT(runnable);
}
@Override
public void drawWithoutUpdate() {
super.getWindow().getCanvas().setImageUpdated();
super.draw();
}
}
public class MMImagePlus extends ImagePlus implements IMMImagePlus {
public VirtualAcquisitionDisplay display_;
MMImagePlus(String title, ImageStack stack, VirtualAcquisitionDisplay disp) {
super(title, stack);
display_ = disp;
}
@Override
public String getTitle() {
return name_;
}
@Override
public int getImageStackSize() {
return super.nChannels * super.nSlices * super.nFrames;
}
@Override
public int getStackSize() {
return getImageStackSize();
}
@Override
public int getNChannelsUnverified() {
return super.nChannels;
}
@Override
public int getNSlicesUnverified() {
return super.nSlices;
}
@Override
public int getNFramesUnverified() {
return super.nFrames;
}
@Override
public void setNChannelsUnverified(int nChannels) {
super.nChannels = nChannels;
}
@Override
public void setNSlicesUnverified(int nSlices) {
super.nSlices = nSlices;
}
@Override
public void setNFramesUnverified(int nFrames) {
super.nFrames = nFrames;
}
private void superDraw() {
super.draw();
}
@Override
public void draw() {
if (!SwingUtilities.isEventDispatchThread()) {
Runnable onEDT = new Runnable() {
public void run() {
imageChangedUpdate();
superDraw();
}
};
SwingUtilities.invokeLater(onEDT);
} else {
imageChangedUpdate();
super.draw();
}
}
@Override
public void drawWithoutUpdate() {
//ImageJ requires this
super.getWindow().getCanvas().setImageUpdated();
super.draw();
}
}
public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) {
this(imageCache, eng, WindowManager.getUniqueName("Untitled"));
}
public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) {
name_ = name;
imageCache_ = imageCache;
eng_ = eng;
pSelector_ = createPositionScrollbar();
imageCache_.setDisplay(this);
mda_ = eng != null;
zStackMins_ = new HashMap<Integer,Integer>();
zStackMaxes_ = new HashMap<Integer,Integer>();
}
//used for snap and live
public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException {
simple_ = true;
imageCache_ = imageCache;
name_ = name;
imageCache_.setDisplay(this);
mda_ = false;
}
private void invokeAndWaitIfNotEDT(Runnable runnable) {
if (SwingUtilities.isEventDispatchThread())
runnable.run();
else
try {
SwingUtilities.invokeAndWait(runnable);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
} catch (InvocationTargetException ex) {
System.out.println(ex.getCause());
}
}
private void invokeLaterIfNotEDT(Runnable runnable) {
if (SwingUtilities.isEventDispatchThread())
runnable.run();
else
SwingUtilities.invokeLater(runnable);
}
private void startup(JSONObject firstImageMetadata) {
mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel();
JSONObject summaryMetadata = getSummaryMetadata();
int numSlices = 1;
int numFrames = 1;
int numChannels = 1;
int numGrayChannels;
int numPositions = 0;
int width = 0;
int height = 0;
int numComponents = 1;
try {
if (firstImageMetadata != null) {
width = MDUtils.getWidth(firstImageMetadata);
height = MDUtils.getHeight(firstImageMetadata);
} else {
width = MDUtils.getWidth(summaryMetadata);
height = MDUtils.getHeight(summaryMetadata);
}
numSlices = Math.max(summaryMetadata.getInt("Slices"), 1);
numFrames = Math.max(summaryMetadata.getInt("Frames"), 1);
int imageChannelIndex;
try {
imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata);
} catch (Exception e) {
imageChannelIndex = -1;
}
numChannels = Math.max(1 + imageChannelIndex,
Math.max(summaryMetadata.getInt("Channels"), 1));
numPositions = Math.max(summaryMetadata.getInt("Positions"), 0);
numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1);
} catch (Exception e) {
ReportingUtils.showError(e);
}
numComponents_ = numComponents;
numGrayChannels = numComponents_ * numChannels;
channelInitiated_ = new int[numGrayChannels];
if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) {
imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata));
}
int type = 0;
try {
if (firstImageMetadata != null) {
type = MDUtils.getSingleChannelType(firstImageMetadata);
} else {
type = MDUtils.getSingleChannelType(summaryMetadata);
}
} catch (Exception ex) {
ReportingUtils.showError(ex, "Unable to determine acquisition type.");
}
virtualStack_ = new AcquisitionVirtualStack(width, height, type, null,
imageCache_, numGrayChannels * numSlices * numFrames, this);
if (summaryMetadata.has("PositionIndex")) {
try {
virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata));
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
if (simple_) {
controls_ = new SimpleWindowControls(this);
} else {
controls_ = new HyperstackControls(this);
}
hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_),
numGrayChannels, numSlices, numFrames, virtualStack_, controls_);
applyPixelSizeCalibration(hyperImage_);
mdPanel_.setup(null);
createWindow();
//Make sure contrast panel sets up correctly here
windowToFront();
setupMetadataPanel();
cSelector_ = getSelector("c");
if (!simple_) {
tSelector_ = getSelector("t");
zSelector_ = getSelector("z");
if (zSelector_ != null)
zSelector_.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
preferredSlice_ = zSelector_.getValue();
}
});
if (cSelector_ != null)
cSelector_.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
preferredChannel_ = cSelector_.getValue();
}
});
if (imageCache_.lastAcquiredFrame() > 1) {
setNumFrames(1 + imageCache_.lastAcquiredFrame());
} else {
setNumFrames(1);
}
configureAnimationControls();
//cant use these function because of an imageJ bug
// setNumSlices(numSlices);
setNumPositions(numPositions);
}
updateAndDraw();
updateWindowTitleAndStatus();
}
private void animateSlices(boolean animate) {
if (!animate) {
zAnimationTimer_.stop();
refreshAnimationIcons();
return;
}
if (tAnimationTimer_ != null)
animateFrames(false);
if (zAnimationTimer_ == null)
zAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int slice = hyperImage_.getSlice();
if (slice >= zSelector_.getMaximum() - 1)
hyperImage_.setPosition(hyperImage_.getChannel(), 1, hyperImage_.getFrame());
else
hyperImage_.setPosition(hyperImage_.getChannel(), slice + 1, hyperImage_.getFrame());
}
});
zAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_));
zAnimationTimer_.start();
refreshAnimationIcons();
}
private void animateFrames(boolean animate) {
if (!animate) {
tAnimationTimer_.stop();
refreshAnimationIcons();
return;
}
if (zAnimationTimer_ != null)
animateSlices(false);
if (tAnimationTimer_ == null)
tAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int frame = hyperImage_.getFrame();
if (frame >= lastFrame_)
hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), firstFrame_);
else
hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame + 1);
}
});
tAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_));
tAnimationTimer_.start();
refreshAnimationIcons();
}
private void refreshAnimationIcons() {
if (zIcon_ != null)
zIcon_.repaint();
if (tIcon_ != null)
tIcon_.repaint();
}
private void configureAnimationControls() {
firstFrame_ = 1;
lastFrame_ = tSelector_ != null ? tSelector_.getMaximum() - 1 : 1;
if (zIcon_ != null) {
zIcon_.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
animateSlices(zAnimationTimer_ == null || !zAnimationTimer_.isRunning());
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
if (tIcon_ != null) {
tIcon_.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
animateFrames(tAnimationTimer_ == null || !tAnimationTimer_.isRunning());
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
}
/**
* Allows bypassing the prompt to Save
* @param promptToSave boolean flag
*/
public void promptToSave(boolean promptToSave) {
promptToSave_ = promptToSave;
}
/*
* Method required by ImageCacheListener
*/
@Override
public void imageReceived(final TaggedImage taggedImage) {
if (eng_ != null)
updateDisplay(taggedImage, false);
}
/*
* Method required by ImageCacheListener
*/
@Override
public void imagingFinished(String path) {
updateDisplay(null, true);
updateAndDraw();
updateWindowTitleAndStatus();
}
private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) {
try {
long t = System.currentTimeMillis();
JSONObject tags;
if (taggedImage != null)
tags = taggedImage.tags;
else
tags = imageCache_.getLastImageTags();
if (tags == null)
return;
int frame = MDUtils.getFrameIndex(tags);
int ch = MDUtils.getChannelIndex(tags);
int slice = MDUtils.getSliceIndex(tags);
int position = MDUtils.getPositionIndex(tags);
boolean show = finalUpdate || frame == 0 || (Math.abs(t - lastDisplayTime_) > 30)
|| (ch == getNumChannels() - 1 && lastFrameShown_ == frame
&& lastSliceShown_ == slice && lastPositionShown_ == position)
|| (slice == getNumSlices() - 1 && frame == 0 && position == 0 && ch == getNumChannels() - 1);
if (show) {
showImage(tags, true);
lastFrameShown_ = frame;
lastSliceShown_ = slice;
lastPositionShown_ = position;
lastDisplayTime_ = t;
forceImagePaint();
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
}
private void forceImagePaint() {
hyperImage_.getWindow().getCanvas().paint(hyperImage_.getWindow().getCanvas().getGraphics());
}
public int rgbToGrayChannel(int channelIndex) {
try {
if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) {
return channelIndex * 3;
}
return channelIndex;
} catch (Exception ex) {
ReportingUtils.logError(ex);
return 0;
}
}
public int grayToRGBChannel(int grayIndex) {
try {
if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) {
return grayIndex / 3;
}
return grayIndex;
} catch (Exception ex) {
ReportingUtils.logError(ex);
return 0;
}
}
public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) {
try {
JSONObject displaySettings = new JSONObject();
JSONArray chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors");
JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames");
JSONArray chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax");
JSONArray chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin");
int numComponents = MDUtils.getNumberOfComponents(summaryMetadata);
JSONArray channels = new JSONArray();
if (numComponents > 1) //RGB
{
int rgbChannelBitDepth = summaryMetadata.getString("PixelType").endsWith("32") ? 8 : 16;
for (int k = 0; k < 3; k++) {
JSONObject channelObject = new JSONObject();
channelObject.put("Color", rgb[k].getRGB());
channelObject.put("Name", rgbNames[k]);
channelObject.put("Gamma", 1.0);
channelObject.put("Min", 0);
channelObject.put("Max", Math.pow(2, rgbChannelBitDepth) - 1);
channels.put(channelObject);
}
} else {
for (int k = 0; k < chNames.length(); ++k) {
String name = (String) chNames.get(k);
int color = chColors.getInt(k);
int min = chMins.getInt(k);
int max = chMaxes.getInt(k);
JSONObject channelObject = new JSONObject();
channelObject.put("Color", color);
channelObject.put("Name", name);
channelObject.put("Gamma", 1.0);
channelObject.put("Min", min);
channelObject.put("Max", max);
channels.put(channelObject);
}
}
displaySettings.put("Channels", channels);
JSONObject comments = new JSONObject();
String summary = "";
try {
summary = summaryMetadata.getString("Comment");
} catch (JSONException ex) {
summaryMetadata.put("Comment", "");
}
comments.put("Summary", summary);
displaySettings.put("Comments", comments);
return displaySettings;
} catch (Exception e) {
ReportingUtils.showError("Error creating display settigns from summary metadata");
return null;
}
}
/**
* Sets ImageJ pixel size calibration
* @param hyperImage
*/
private void applyPixelSizeCalibration(final ImagePlus hyperImage) {
try {
double pixSizeUm = getSummaryMetadata().getDouble("PixelSize_um");
if (pixSizeUm > 0) {
Calibration cal = new Calibration();
cal.setUnit("um");
cal.pixelWidth = pixSizeUm;
cal.pixelHeight = pixSizeUm;
hyperImage.setCalibration(cal);
}
} catch (JSONException ex) {
// no pixelsize defined. Nothing to do
}
}
private void setNumPositions(int n) {
if (simple_)
return;
pSelector_.setMinimum(0);
pSelector_.setMaximum(n);
ImageWindow win = hyperImage_.getWindow();
if (n > 1 && pSelector_.getParent() == null) {
win.add(pSelector_, win.getComponentCount() - 1);
} else if (n <= 1 && pSelector_.getParent() != null) {
win.remove(pSelector_);
}
win.pack();
}
private void setNumFrames(int n) {
if (simple_)
return;
if (tSelector_ != null) {
//ImageWindow win = hyperImage_.getWindow();
((IMMImagePlus) hyperImage_).setNFramesUnverified(n);
tSelector_.setMaximum(n + 1);
// JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n);
}
}
private void setNumSlices(int n) {
if (simple_)
return;
if (zSelector_ != null) {
((IMMImagePlus) hyperImage_).setNSlicesUnverified(n);
zSelector_.setMaximum(n + 1);
}
}
private void setNumChannels(int n) {
if (cSelector_ != null) {
((IMMImagePlus) hyperImage_).setNChannelsUnverified(n);
cSelector_.setMaximum(n);
}
}
public ImagePlus getHyperImage() {
return hyperImage_;
}
public int getStackSize() {
if (hyperImage_ == null)
return -1;
int s = hyperImage_.getNSlices();
int c = hyperImage_.getNChannels();
int f = hyperImage_.getNFrames();
if ((s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1))
return s * c * f;
return Math.max(Math.max(s, c), f);
}
private void imageChangedWindowUpdate() {
if (hyperImage_ != null && hyperImage_.isVisible()) {
TaggedImage ti = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice());
if (ti != null)
controls_.newImageUpdate(ti.tags);
}
}
public void updateAndDraw() {
if (!updating_) {
updating_ = true;
setupMetadataPanel();
if (hyperImage_ != null && hyperImage_.isVisible()) {
hyperImage_.updateAndDraw();
imageChangedWindowUpdate();
}
updating_ = false;
}
}
public void updateWindowTitleAndStatus() {
if (simple_) {
if (hyperImage_ != null && hyperImage_.getWindow() != null)
hyperImage_.getWindow().setTitle(name_);
return;
}
if (controls_ == null) {
return;
}
String status = "";
final AcquisitionEngine eng = eng_;
if (eng != null) {
if (acquisitionIsRunning()) {
if (!abortRequested()) {
controls_.acquiringImagesUpdate(true);
if (isPaused()) {
status = "paused";
} else {
status = "running";
}
} else {
controls_.acquiringImagesUpdate(false);
status = "interrupted";
}
} else {
controls_.acquiringImagesUpdate(false);
if (!status.contentEquals("interrupted")) {
if (eng.isFinished()) {
status = "finished";
eng_ = null;
}
}
}
status += ", ";
if (eng.isFinished()) {
eng_ = null;
finished_ = true;
}
} else {
if (finished_ == true) {
status = "finished, ";
}
controls_.acquiringImagesUpdate(false);
}
if (isDiskCached()) {
status += "on disk";
} else {
status += "not yet saved";
}
controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null);
String path = isDiskCached()
? new File(imageCache_.getDiskLocation()).getName() : name_;
if (hyperImage_.isVisible())
hyperImage_.getWindow().setTitle(path + " (" + status + ")");
}
private void windowToFront() {
if (hyperImage_ == null || hyperImage_.getWindow() == null)
return;
hyperImage_.getWindow().toFront();
}
private void setupMetadataPanel() {
if (hyperImage_ == null || hyperImage_.getWindow() == null)
return;
//call this explicitly because it isn't fired immediately
mdPanel_.setup(hyperImage_.getWindow());
}
/**
* Displays tagged image in the multi-D viewer
* Will wait for the screen update
*
* @param taggedImg
* @throws Exception
*/
public void showImage(TaggedImage taggedImg) throws Exception {
showImage(taggedImg, true);
}
/**
* Displays tagged image in the multi-D viewer
* Optionally waits for the display to draw the image
* *
* @param taggedImg
* @throws Exception
*/
public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws InterruptedException, InvocationTargetException {
showImage(taggedImg.tags, waitForDisplay);
}
public void showImage(JSONObject tags, boolean waitForDisplay) throws InterruptedException, InvocationTargetException {
updateWindowTitleAndStatus();
if (tags == null)
return;
if (hyperImage_ == null)
startup(tags);
int channel = 0, frame = 0, slice = 0, position = 0, superChannel = 0;
try {
frame = MDUtils.getFrameIndex(tags);
slice = MDUtils.getSliceIndex(tags);
channel = MDUtils.getChannelIndex(tags);
position = MDUtils.getPositionIndex(tags);
superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(tags));
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
//make sure pixels get properly set
if (hyperImage_ != null && frame == 0) {
IMMImagePlus img = (IMMImagePlus) hyperImage_;
if (img.getNChannelsUnverified() == 1) {
if (img.getNSlicesUnverified() == 1) {
hyperImage_.getProcessor().setPixels(virtualStack_.getPixels(1));
}
} else if (hyperImage_ instanceof MMCompositeImage) {
//reset rebuilds each of the channel ImageProcessors with the correct pixels
//from AcquisitionVirtualStack
MMCompositeImage ci = ((MMCompositeImage) hyperImage_);
ci.reset();
//This line is neccessary for image processor to have correct pixels in grayscale mode
ci.getProcessor().setPixels(virtualStack_.getPixels(ci.getCurrentSlice()));
}
} else if (hyperImage_ instanceof MMCompositeImage) {
MMCompositeImage ci = ((MMCompositeImage) hyperImage_);
ci.reset();
}
if (frame + 1 > lastFrame_)
lastFrame_ = frame + 1;
if (cSelector_ != null) {
if (cSelector_.getMaximum() <= (1 + superChannel)) {
this.setNumChannels(1 + superChannel);
((CompositeImage) hyperImage_).reset();
//JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class,
// "setupLuts", 1 + superChannel, Integer.TYPE);
}
}
initializeContrast(channel, slice);
if (!simple_) {
if (tSelector_ != null) {
if (tSelector_.getMaximum() <= (1 + frame)) {
this.setNumFrames(1 + frame);
}
}
if (position + 1 >= getNumPositions()) {
setNumPositions(position + 1);
}
setPosition(position);
hyperImage_.setPosition(1 + superChannel, 1 + slice, 1 + frame);
}
Runnable updateAndDraw = new Runnable() {
public void run() {
updateAndDraw();
}
};
if (!SwingUtilities.isEventDispatchThread()) {
if (waitForDisplay) {
SwingUtilities.invokeAndWait(updateAndDraw);
} else {
SwingUtilities.invokeLater(updateAndDraw);
}
} else {
updateAndDraw();
}
setPreferredScrollbarPositions();
}
/*
* Live/snap should load window contrast settings
* MDA should autoscale on frist image
* Opening dataset should load from disoplay and comments
*/
private void initializeContrast(final int channel, final int slice) {
Runnable autoscaleOrLoadContrast = new Runnable() {
public void run() {
if (!newDisplay_)
return;
if (simple_) { //Snap/live
if (hyperImage_ instanceof MMCompositeImage
&& ((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel)
return;
mdPanel_.loadSimpleWinContrastWithoutDraw(imageCache_, hyperImage_);
} else if (mda_) { //Multi D acquisition
IMMImagePlus immImg = ((IMMImagePlus) hyperImage_);
if (immImg.getNSlicesUnverified() > 1) { //Z stacks
mdPanel_.autoscaleOverStackWithoutDraw(imageCache_, hyperImage_, channel, zStackMins_, zStackMaxes_);
if (channel != immImg.getNChannelsUnverified() - 1 || slice != immImg.getNSlicesUnverified() - 1)
return; //don't set new display to false until all channels autscaled
} else { //No z stacks
mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_);
if (immImg.getNChannelsUnverified() - 1 != channel)
return;
}
} else //Acquire button
if (hyperImage_ instanceof MMCompositeImage) {
if (((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel)
return;
mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_);
} else
mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); // else do nothing because contrast automatically loaded from cache
newDisplay_ = false;
}
};
if (!SwingUtilities.isEventDispatchThread())
SwingUtilities.invokeLater(autoscaleOrLoadContrast);
else
autoscaleOrLoadContrast.run();
}
private void setPreferredScrollbarPositions() {
if (this.acquisitionIsRunning()) {
long nextImageTime = eng_.getNextWakeTime();
if (System.nanoTime() / 1000000 - nextImageTime < -1000) { //1 sec or more until next start
if (preferredPositionTimer_ == null)
preferredPositionTimer_ = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IMMImagePlus ip = ((IMMImagePlus) hyperImage_);
int c = ip.getNChannelsUnverified(), s = ip.getNSlicesUnverified(), f = ip.getNFramesUnverified();
hyperImage_.setPosition(preferredChannel_ == -1 ? c : preferredChannel_,
preferredSlice_ == -1 ? s : preferredSlice_, f);
if (pSelector_ != null && preferredPosition_ > -1)
if (eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_CHANNEL_SLICE
&& eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_SLICE_CHANNEL)
setPosition(preferredPosition_);
preferredPositionTimer_.stop();;
}
});
if (preferredPositionTimer_.isRunning())
return;
preferredPositionTimer_.start();
}
}
}
private void updatePosition(int p) {
if (simple_)
return;
virtualStack_.setPositionIndex(p);
if (!hyperImage_.isComposite()) {
Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice());
hyperImage_.getProcessor().setPixels(pixels);
} else {
CompositeImage ci = (CompositeImage) hyperImage_;
if (ci.getMode() == CompositeImage.COMPOSITE)
for (int i = 0; i < ((MMCompositeImage) ci).getNChannelsUnverified(); i++ )
ci.getProcessor(i + 1).setPixels(virtualStack_.getPixels(
ci.getCurrentSlice() - ci.getChannel() + i + 1));
ci.getProcessor().setPixels(virtualStack_.getPixels(hyperImage_.getCurrentSlice()));
}
updateAndDraw();
}
public void setPosition(int p) {
if (simple_)
return;
pSelector_.setValue(p);
}
public void setSliceIndex(int i) {
if (simple_)
return;
final int f = hyperImage_.getFrame();
final int c = hyperImage_.getChannel();
hyperImage_.setPosition(c, i + 1, f);
}
public int getSliceIndex() {
return hyperImage_.getSlice() - 1;
}
boolean pause() {
if (eng_ != null) {
if (eng_.isPaused()) {
eng_.setPause(false);
} else {
eng_.setPause(true);
}
updateWindowTitleAndStatus();
return (eng_.isPaused());
}
return false;
}
boolean abort() {
if (eng_ != null) {
if (eng_.abortRequest()) {
updateWindowTitleAndStatus();
return true;
}
}
return false;
}
public boolean acquisitionIsRunning() {
if (eng_ != null) {
return eng_.isAcquisitionRunning();
} else {
return false;
}
}
public long getNextWakeTime() {
return eng_.getNextWakeTime();
}
public boolean abortRequested() {
if (eng_ != null) {
return eng_.abortRequested();
} else {
return false;
}
}
private boolean isPaused() {
if (eng_ != null) {
return eng_.isPaused();
} else {
return false;
}
}
boolean saveAs() {
String prefix;
String root;
for (;;) {
File f = FileDialogs.save(hyperImage_.getWindow(),
"Please choose a location for the data set",
MMStudioMainFrame.MM_DATA_SET);
if (f == null) // Canceled.
{
return false;
}
prefix = f.getName();
root = new File(f.getParent()).getAbsolutePath();
if (f.exists()) {
ReportingUtils.showMessage(prefix
+ " is write only! Please choose another name.");
} else {
break;
}
}
TaggedImageStorageDiskDefault newFileManager = new TaggedImageStorageDiskDefault(root + "/" + prefix, true,
getSummaryMetadata());
imageCache_.saveAs(newFileManager);
MMStudioMainFrame.getInstance().setAcqDirectory(root);
updateWindowTitleAndStatus();
return true;
}
final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) {
MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack, this);
FileInfo fi = new FileInfo();
fi.width = virtualStack.getWidth();
fi.height = virtualStack.getHeight();
fi.fileName = virtualStack.getDirectory();
fi.url = null;
img.setFileInfo(fi);
return img;
}
final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices,
int frames, final AcquisitionVirtualStack virtualStack,
DisplayControls hc) {
final ImagePlus hyperImage;
mmIP.setNChannelsUnverified(channels);
mmIP.setNFramesUnverified(frames);
mmIP.setNSlicesUnverified(slices);
if (channels > 1) {
hyperImage = new MMCompositeImage(mmIP, CompositeImage.COMPOSITE, this);
hyperImage.setOpenAsHyperStack(true);
} else {
hyperImage = mmIP;
mmIP.setOpenAsHyperStack(true);
}
return hyperImage;
}
public void liveModeEnabled(boolean enabled) {
if (simple_) {
controls_.acquiringImagesUpdate(enabled);
}
}
private void createWindow() {
DisplayWindow win = new DisplayWindow(hyperImage_);
//This mouse listener updates the histogram after an ROI is drawn
win.getCanvas().addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
mdPanel_.refresh();
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
});
win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor());
MMStudioMainFrame.getInstance().addMMBackgroundListener(win);
win.add(controls_);
win.pack();
if (simple_)
win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0), prefs_.getInt(SIMPLE_WIN_Y, 0));
}
private ScrollbarWithLabel getSelector(String label) {
// label should be "t", "z", or "c"
ScrollbarWithLabel selector = null;
ImageWindow win = hyperImage_.getWindow();
int slices = ((IMMImagePlus) hyperImage_).getNSlicesUnverified();
int frames = ((IMMImagePlus) hyperImage_).getNFramesUnverified();
int channels = ((IMMImagePlus) hyperImage_).getNChannelsUnverified();
if (win instanceof StackWindow) {
try {
//ImageJ bug workaround
if (frames > 1 && slices == 1 && channels == 1 && label.equals("t"))
selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector");
else
selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector");
} catch (NoSuchFieldException ex) {
selector = null;
ReportingUtils.logError(ex);
}
}
//replace default icon with custom one
if (selector != null) {
try {
Component icon = (Component) JavaUtils.getRestrictedFieldValue(
selector, ScrollbarWithLabel.class, "icon");
selector.remove(icon);
} catch (NoSuchFieldException ex) {
ReportingUtils.logError(ex);
}
ScrollbarIcon newIcon = new ScrollbarIcon(label.charAt(0), this);
if (label.equals("z")) {
zIcon_ = newIcon;
} else if (label.equals("t")) {
tIcon_ = newIcon;
} else if (label.equals("c")) {
cIcon_ = newIcon;
}
selector.add(newIcon, BorderLayout.WEST);
selector.invalidate();
selector.validate();
}
return selector;
}
private ScrollbarWithLabel createPositionScrollbar() {
final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') {
@Override
public void setValue(int v) {
if (this.getValue() != v) {
super.setValue(v);
updatePosition(v);
}
}
};
// prevents scroll bar from blinking on Windows:
pSelector.setFocusable(false);
pSelector.setUnitIncrement(1);
pSelector.setBlockIncrement(1);
pSelector.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
updatePosition(pSelector.getValue());
preferredPosition_ = pSelector_.getValue();
}
});
if (pSelector != null) {
try {
Component icon = (Component) JavaUtils.getRestrictedFieldValue(
pSelector, ScrollbarWithLabel.class, "icon");
pSelector.remove(icon);
} catch (NoSuchFieldException ex) {
ReportingUtils.logError(ex);
}
pIcon_ = new ScrollbarIcon('p', this);
pSelector.add(pIcon_, BorderLayout.WEST);
pSelector.invalidate();
pSelector.validate();
}
return pSelector;
}
public JSONObject getCurrentMetadata() {
try {
if (hyperImage_ != null) {
TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice());
if (image != null) {
return image.tags;
} else {
return null;
}
} else {
return null;
}
} catch (NullPointerException ex) {
return null;
}
}
public int getCurrentPosition() {
return virtualStack_.getPositionIndex();
}
public int getNumSlices() {
if (simple_)
return 1;
return ((IMMImagePlus) hyperImage_).getNSlicesUnverified();
}
public int getNumFrames() {
if (simple_)
return 1;
return ((IMMImagePlus) hyperImage_).getNFramesUnverified();
}
public int getNumPositions() {
if (simple_)
return 1;
return pSelector_.getMaximum();
}
public ImagePlus getImagePlus() {
return hyperImage_;
}
public ImageCache getImageCache() {
return imageCache_;
}
public ImagePlus getImagePlus(int position) {
ImagePlus iP = new ImagePlus();
iP.setStack(virtualStack_);
iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames());
iP.setFileInfo(hyperImage_.getFileInfo());
return iP;
}
public void setComment(String comment) throws MMScriptException {
try {
getSummaryMetadata().put("Comment", comment);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public final JSONObject getSummaryMetadata() {
return imageCache_.getSummaryMetadata();
}
public void close() {
if (hyperImage_ != null) {
//call this so when one window closes and is replaced by another
//the md panel gets rid of the first before doing stuff with
//the second
if (WindowManager.getCurrentImage() == hyperImage_)
mdPanel_.setup(null);
hyperImage_.getWindow().windowClosing(null);
hyperImage_.close();
}
}
public synchronized boolean windowClosed() {
ImageWindow win = hyperImage_.getWindow();
return (win == null || win.isClosed());
}
public void showFolder() {
if (isDiskCached()) {
try {
File location = new File(imageCache_.getDiskLocation());
if (JavaUtils.isWindows()) {
Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath());
} else if (JavaUtils.isMac()) {
if (!location.isDirectory()) {
location = location.getParentFile();
}
Runtime.getRuntime().exec("open " + location.getAbsolutePath());
}
} catch (IOException ex) {
ReportingUtils.logError(ex);
}
}
}
public void setPlaybackFPS(double fps) {
framesPerSec_ = fps;
if (zAnimationTimer_ != null && zAnimationTimer_.isRunning()) {
animateSlices(false);
animateSlices(true);
} else if (tAnimationTimer_ != null && tAnimationTimer_.isRunning()) {
animateFrames(false);
animateFrames(true);
}
}
public void setPlaybackLimits(int firstFrame, int lastFrame) {
firstFrame_ = firstFrame;
lastFrame_ = lastFrame;
}
public double getPlaybackFPS() {
return framesPerSec_;
}
public boolean isZAnimated() {
if (zAnimationTimer_ != null && zAnimationTimer_.isRunning())
return true;
return false;
}
public boolean isTAnimated() {
if (tAnimationTimer_ != null && tAnimationTimer_.isRunning())
return true;
return false;
}
public boolean isAnimated() {
return isTAnimated() || isZAnimated();
}
public String getSummaryComment() {
return imageCache_.getComment();
}
public void setSummaryComment(String comment) {
imageCache_.setComment(comment);
}
void setImageComment(String comment) {
imageCache_.setImageComment(comment, getCurrentMetadata());
}
String getImageComment() {
try {
return imageCache_.getImageComment(getCurrentMetadata());
} catch (NullPointerException ex) {
return "";
}
}
public boolean isDiskCached() {
ImageCache imageCache = imageCache_;
if (imageCache == null) {
return false;
} else {
return imageCache.getDiskLocation() != null;
}
}
public void show() {
if (hyperImage_ == null) {
startup(null);
}
hyperImage_.show();
hyperImage_.getWindow().toFront();
}
public int getNumChannels() {
return ((IMMImagePlus) hyperImage_).getNChannelsUnverified();
}
public int getNumGrayChannels() {
return getNumChannels();
}
public void setWindowTitle(String name) {
name_ = name;
updateWindowTitleAndStatus();
}
public boolean isSimpleDisplay() {
return simple_;
}
public void displayStatusLine(String status) {
controls_.setStatusLabel(status);
}
public void setChannelContrast(int channelIndex, int min, int max, double gamma) {
mdPanel_.setChannelContrast(channelIndex, min, max, gamma);
}
private void imageChangedUpdate() {
mdPanel_.imageChangedUpdate(hyperImage_, imageCache_);
imageChangedWindowUpdate(); //used to update status line
}
public void refreshContrastPanel() {
mdPanel_.refresh();
}
public void drawWithoutUpdate() {
if (hyperImage_ != null) {
((IMMImagePlus) hyperImage_).drawWithoutUpdate();
}
}
public class DisplayWindow extends StackWindow {
private boolean windowClosingDone_ = false;
private boolean closed_ = false;
public DisplayWindow(ImagePlus ip) {
super(ip);
}
@Override
public boolean close() {
windowClosing(null);
return closed_;
}
@Override
public void windowClosing(WindowEvent e) {
if (windowClosingDone_) {
return;
}
if (eng_ != null && eng_.isAcquisitionRunning()) {
if (!abort()) {
return;
}
}
if (imageCache_.getDiskLocation() == null && promptToSave_) {
int result = JOptionPane.showConfirmDialog(this,
"This data set has not yet been saved.\n"
+ "Do you want to save it?",
"Micro-Manager",
JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.YES_OPTION) {
if (!saveAs()) {
return;
}
} else if (result == JOptionPane.CANCEL_OPTION) {
return;
}
}
//for some reason window focus listener doesn't always fire, so call
//explicitly here
mdPanel_.setup(null);
if (simple_ && hyperImage_ != null && hyperImage_.getWindow() != null && hyperImage_.getWindow().getLocation() != null) {
Point loc = hyperImage_.getWindow().getLocation();
prefs_.putInt(SIMPLE_WIN_X, loc.x);
prefs_.putInt(SIMPLE_WIN_Y, loc.y);
mdPanel_.saveContrastSettings(imageCache_);
}
if (imageCache_ != null) {
imageCache_.close();
}
if (!closed_) {
try {
super.close();
} catch (NullPointerException ex) {
ReportingUtils.logError("Null pointer error in ImageJ code while closing window");
}
}
super.windowClosing(e);
MMStudioMainFrame.getInstance().removeMMBackgroundListener(this);
windowClosingDone_ = true;
closed_ = true;
}
@Override
public void windowClosed(WindowEvent E) {
this.windowClosing(E);
super.windowClosed(E);
}
@Override
public void windowActivated(WindowEvent e) {
if (!isClosed()) {
super.windowActivated(e);
}
}
@Override
public void setAnimate(boolean b) {
if (((IMMImagePlus) hyperImage_).getNFramesUnverified() > 1)
animateFrames(b);
else
animateSlices(b);
}
@Override
public boolean getAnimate() {
return isAnimated();
}
};
}
|
package com.github.dreamhead.moco.resource;
import com.github.dreamhead.moco.ConfigApplier;
import com.github.dreamhead.moco.MocoConfig;
import com.github.dreamhead.moco.Request;
import com.github.dreamhead.moco.model.MessageContent;
import com.google.common.base.Optional;
public class Resource implements Identifiable, ConfigApplier<Resource>, ResourceReader {
private final Identifiable identifiable;
private final ResourceConfigApplier configApplier;
private final ResourceReader reader;
public Resource(final Identifiable identifiable,
final ResourceConfigApplier configApplier,
final ResourceReader reader) {
this.identifiable = identifiable;
this.configApplier = configApplier;
this.reader = reader;
}
@Override
public final Resource apply(final MocoConfig config) {
return configApplier.apply(config, this);
}
@Override
public final String id() {
return identifiable.id();
}
@Override
public final MessageContent readFor(final Optional<? extends Request> request) {
return reader.readFor(request);
}
@Override
public final MessageContent readFor(final Request request) {
return reader.readFor(request);
}
public final <T extends ResourceReader> T reader(final Class<T> clazz) {
return clazz.cast(reader);
}
}
|
package com.opengamma.strata.market.id;
import java.io.Serializable;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.strata.basics.market.FieldName;
import com.opengamma.strata.basics.market.MarketDataFeed;
import com.opengamma.strata.basics.market.ObservableId;
import com.opengamma.strata.collect.id.StandardId;
import com.opengamma.strata.market.key.QuoteKey;
/**
* The ID of a market quote.
* <p>
* A quote ID identifies a piece of data in an external data provider.
* <p>
* Where possible, applications should use higher level IDs, instead of this class.
* Higher level market data keys allow the system to associate the market data with metadata when
* applying scenario definitions. If quote IDs are used directly, the system has no way to
* perturb the market data using higher level rules that rely on metadata.
* <p>
* The {@link StandardId} in a quote ID is typically the ID from an underlying data provider (e.g.
* Bloomberg or Reuters). However the field name is a generic name which is mapped to the field name
* in the underlying provider by the market data system.
* <p>
* The reason for this difference is the different sources of the ID and field name data. The ID is typically
* taken from an object which is provided to any calculations, for example a security linked to the
* trade. The calculation rarely has to make up an ID for an object it doesn't have access to.
* <p>
* In contrast, calculations will often have to reference field names that aren't part their arguments. For
* example, if a calculation requires the last closing price of a security, it could take the ID from
* the security, but it needs a way to specify the field name containing the last closing price.
* <p>
* If the field name were specific to the market data provider, the calculation would have to be aware
* of the source of its market data. However, if it uses a generic field name from {@code FieldNames}
* the market data source can change without affecting the calculation.
*
* @see FieldName
*/
@BeanDefinition(builderScope = "private")
public final class QuoteId implements ObservableId, ImmutableBean, Serializable {
/** The ID of the data, typically an ID from an external data provider. */
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final StandardId standardId;
/** The field name in the market data record that contains the data. */
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final FieldName fieldName;
/** The market data feed from which the market data should be retrieved. */
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final MarketDataFeed marketDataFeed;
/**
* Returns an ID representing a market quote with a field name of {@link FieldName#MARKET_VALUE}
* and a market data feed of {@link MarketDataFeed#NONE}.
*
* @param id the ID of the data in the underlying data provider
* @return an ID representing a market quote
*/
public static QuoteId of(StandardId id) {
return new QuoteId(id, FieldName.MARKET_VALUE, MarketDataFeed.NONE);
}
/**
* Returns an ID representing a market quote with a field name of {@link FieldName#MARKET_VALUE}.
*
* @param id the ID of the data in the underlying data provider
* @param feed the market data feed from which the market data should be retrieved
* @return an ID representing a market quote
*/
public static QuoteId of(StandardId id, MarketDataFeed feed) {
return new QuoteId(id, FieldName.MARKET_VALUE, feed);
}
/**
* Returns an ID representing a market quote.
*
* @param id the ID of the data in the underlying data provider
* @param feed the market data feed from which the market data should be retrieved
* @param fieldName the name of the field in the market data record holding the data
* @return an ID representing a market quote
*/
public static QuoteId of(StandardId id, MarketDataFeed feed, FieldName fieldName) {
return new QuoteId(id, fieldName, feed);
}
@Override
public QuoteKey toMarketDataKey() {
return QuoteKey.of(standardId, fieldName);
}
///CLOVER:OFF
/**
* The meta-bean for {@code QuoteId}.
* @return the meta-bean, not null
*/
public static QuoteId.Meta meta() {
return QuoteId.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(QuoteId.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
private QuoteId(
StandardId standardId,
FieldName fieldName,
MarketDataFeed marketDataFeed) {
JodaBeanUtils.notNull(standardId, "standardId");
JodaBeanUtils.notNull(fieldName, "fieldName");
JodaBeanUtils.notNull(marketDataFeed, "marketDataFeed");
this.standardId = standardId;
this.fieldName = fieldName;
this.marketDataFeed = marketDataFeed;
}
@Override
public QuoteId.Meta metaBean() {
return QuoteId.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
/**
* Gets the ID of the data, typically an ID from an external data provider.
* @return the value of the property, not null
*/
@Override
public StandardId getStandardId() {
return standardId;
}
/**
* Gets the field name in the market data record that contains the data.
* @return the value of the property, not null
*/
@Override
public FieldName getFieldName() {
return fieldName;
}
/**
* Gets the market data feed from which the market data should be retrieved.
* @return the value of the property, not null
*/
@Override
public MarketDataFeed getMarketDataFeed() {
return marketDataFeed;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
QuoteId other = (QuoteId) obj;
return JodaBeanUtils.equal(standardId, other.standardId) &&
JodaBeanUtils.equal(fieldName, other.fieldName) &&
JodaBeanUtils.equal(marketDataFeed, other.marketDataFeed);
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(standardId);
hash = hash * 31 + JodaBeanUtils.hashCode(fieldName);
hash = hash * 31 + JodaBeanUtils.hashCode(marketDataFeed);
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("QuoteId{");
buf.append("standardId").append('=').append(standardId).append(',').append(' ');
buf.append("fieldName").append('=').append(fieldName).append(',').append(' ');
buf.append("marketDataFeed").append('=').append(JodaBeanUtils.toString(marketDataFeed));
buf.append('}');
return buf.toString();
}
/**
* The meta-bean for {@code QuoteId}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code standardId} property.
*/
private final MetaProperty<StandardId> standardId = DirectMetaProperty.ofImmutable(
this, "standardId", QuoteId.class, StandardId.class);
/**
* The meta-property for the {@code fieldName} property.
*/
private final MetaProperty<FieldName> fieldName = DirectMetaProperty.ofImmutable(
this, "fieldName", QuoteId.class, FieldName.class);
/**
* The meta-property for the {@code marketDataFeed} property.
*/
private final MetaProperty<MarketDataFeed> marketDataFeed = DirectMetaProperty.ofImmutable(
this, "marketDataFeed", QuoteId.class, MarketDataFeed.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"standardId",
"fieldName",
"marketDataFeed");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -1284477768: // standardId
return standardId;
case 1265009317: // fieldName
return fieldName;
case 842621124: // marketDataFeed
return marketDataFeed;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends QuoteId> builder() {
return new QuoteId.Builder();
}
@Override
public Class<? extends QuoteId> beanType() {
return QuoteId.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
/**
* The meta-property for the {@code standardId} property.
* @return the meta-property, not null
*/
public MetaProperty<StandardId> standardId() {
return standardId;
}
/**
* The meta-property for the {@code fieldName} property.
* @return the meta-property, not null
*/
public MetaProperty<FieldName> fieldName() {
return fieldName;
}
/**
* The meta-property for the {@code marketDataFeed} property.
* @return the meta-property, not null
*/
public MetaProperty<MarketDataFeed> marketDataFeed() {
return marketDataFeed;
}
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -1284477768: // standardId
return ((QuoteId) bean).getStandardId();
case 1265009317: // fieldName
return ((QuoteId) bean).getFieldName();
case 842621124: // marketDataFeed
return ((QuoteId) bean).getMarketDataFeed();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
/**
* The bean-builder for {@code QuoteId}.
*/
private static final class Builder extends DirectFieldsBeanBuilder<QuoteId> {
private StandardId standardId;
private FieldName fieldName;
private MarketDataFeed marketDataFeed;
/**
* Restricted constructor.
*/
private Builder() {
}
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case -1284477768: // standardId
return standardId;
case 1265009317: // fieldName
return fieldName;
case 842621124: // marketDataFeed
return marketDataFeed;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case -1284477768: // standardId
this.standardId = (StandardId) newValue;
break;
case 1265009317: // fieldName
this.fieldName = (FieldName) newValue;
break;
case 842621124: // marketDataFeed
this.marketDataFeed = (MarketDataFeed) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.setString(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public QuoteId build() {
return new QuoteId(
standardId,
fieldName,
marketDataFeed);
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("QuoteId.Builder{");
buf.append("standardId").append('=').append(JodaBeanUtils.toString(standardId)).append(',').append(' ');
buf.append("fieldName").append('=').append(JodaBeanUtils.toString(fieldName)).append(',').append(' ');
buf.append("marketDataFeed").append('=').append(JodaBeanUtils.toString(marketDataFeed));
buf.append('}');
return buf.toString();
}
}
///CLOVER:ON
}
|
package com.timgroup.filesystem.filefeedcache;
import com.timgroup.eventstore.api.EventCategoryReader;
import com.timgroup.eventstore.api.EventReader;
import com.timgroup.eventstore.api.EventRecord;
import com.timgroup.eventstore.api.EventSource;
import com.timgroup.eventstore.api.EventStreamReader;
import com.timgroup.eventstore.api.EventStreamWriter;
import com.timgroup.eventstore.api.Position;
import com.timgroup.eventstore.api.PositionCodec;
import com.timgroup.eventstore.api.ResolvedEvent;
import com.timgroup.eventstore.api.StreamId;
import com.timgroup.eventstore.archiver.EventStoreArchiverProtos;
import com.timgroup.eventstore.archiver.ProtobufsEventIterator;
import com.timgroup.eventstore.archiver.S3ArchiveKeyFormat;
import com.timgroup.eventstore.archiver.S3ArchivePosition;
import com.timgroup.filefeed.reading.ReadableFeedStorage;
import com.timgroup.tucker.info.Component;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import static com.timgroup.filefeed.reading.StorageLocation.TimGroupEventStoreFeedStore;
import static java.util.Objects.requireNonNull;
public final class FileFeedCacheEventSource implements EventReader, EventSource {
private final ReadableFeedStorage downloadableStorage;
private final S3ArchiveKeyFormat s3ArchiveKeyFormat; // TODO rename class and field to ArchiveKeyFormat? also, S3ArchivePosition to ArchivePosition?
public FileFeedCacheEventSource(ReadableFeedStorage downloadableStorage, S3ArchiveKeyFormat s3ArchiveKeyFormat) {
this.downloadableStorage = downloadableStorage;
this.s3ArchiveKeyFormat = s3ArchiveKeyFormat;
}
@Override
public Stream<ResolvedEvent> readAllForwards(Position positionExclusive) {
S3ArchivePosition toReadFrom = (S3ArchivePosition) requireNonNull(positionExclusive);
return listFeedFiles()
.filter(fileName -> s3ArchiveKeyFormat.positionValueFrom(fileName) > toReadFrom.value)
.flatMap(fileName -> loadEventMessages(fileName).stream())
.filter(event -> event.getPosition() > toReadFrom.value)
.map(FileFeedCacheEventSource::toResolvedEvent);
}
@Override
public Optional<ResolvedEvent> readLastEvent() {
return listFeedFiles()
.reduce((olderFile, newerFile) -> newerFile)
.flatMap(file -> lastElementOf(loadEventMessages(file)))
.map(FileFeedCacheEventSource::toResolvedEvent);
}
@Override
public Position emptyStorePosition() {
return S3ArchivePosition.EMPTY_STORE_POSITION;
}
@Override
public PositionCodec storePositionCodec() {
return S3ArchivePosition.CODEC;
}
private Stream<String> listFeedFiles() {
return downloadableStorage.list(TimGroupEventStoreFeedStore, s3ArchiveKeyFormat.eventStorePrefix()).stream();
}
private List<EventStoreArchiverProtos.Event> loadEventMessages(String fileName) {
try (InputStream inputStream = downloadableStorage.get(TimGroupEventStoreFeedStore, fileName)) {
return parseEventMessages(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static List<EventStoreArchiverProtos.Event> parseEventMessages(InputStream inputStream) throws IOException {
List<EventStoreArchiverProtos.Event> events = new ArrayList<>();
try (GZIPInputStream decompressor = new GZIPInputStream(inputStream)) {
new ProtobufsEventIterator<>(EventStoreArchiverProtos.Event.parser(), decompressor).forEachRemaining(events::add);
}
return events;
}
private static ResolvedEvent toResolvedEvent(EventStoreArchiverProtos.Event event) {
return new ResolvedEvent(
new S3ArchivePosition(event.getPosition()),
EventRecord.eventRecord(
Instant.ofEpochSecond(event.getTimestamp().getSeconds(), event.getTimestamp().getNanos()),
StreamId.streamId(event.getStreamCategory(), event.getStreamId()),
event.getEventNumber(),
event.getEventType(),
event.getData().toByteArray(),
event.getMetadata().toByteArray()
));
}
private static <T> Optional<T> lastElementOf(List<? extends T> list) {
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
}
@Nonnull @Override
public EventReader readAll() {
return this;
}
@Nonnull @Override
public EventCategoryReader readCategory() {
throw new UnsupportedOperationException();
}
@Nonnull @Override
public EventStreamReader readStream() {
throw new UnsupportedOperationException();
}
@Nonnull @Override
public EventStreamWriter writeStream() {
throw new UnsupportedOperationException();
}
@Nonnull @Override
public Collection<Component> monitoring() {
return Collections.emptyList();
}
}
|
package org.innovateuk.ifs.transactional;
import org.innovateuk.ifs.address.repository.AddressTypeRepository;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.repository.CompetitionRepository;
import org.innovateuk.ifs.form.domain.Question;
import org.innovateuk.ifs.form.domain.Section;
import org.innovateuk.ifs.form.repository.QuestionRepository;
import org.innovateuk.ifs.form.repository.SectionRepository;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.project.core.domain.PartnerOrganisation;
import org.innovateuk.ifs.project.core.domain.Project;
import org.innovateuk.ifs.project.core.repository.PartnerOrganisationRepository;
import org.innovateuk.ifs.project.core.repository.ProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.function.Supplier;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_NOT_OPEN;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_NOT_OPEN_OR_LATER;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.competition.resource.CompetitionStatus.OPEN;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
/**
* This class represents the base class for transactional services. Method calls within this service will have
* transaction boundaries provided to allow for safe atomic operations and persistence cascading.
*/
public abstract class BaseTransactionalService extends RootTransactionalService {
@Autowired
protected CompetitionRepository competitionRepository;
@Autowired
protected ApplicationRepository applicationRepository;
@Autowired
protected ProjectRepository projectRepository;
@Autowired
protected SectionRepository sectionRepository;
@Autowired
protected OrganisationRepository organisationRepository;
@Autowired
protected PartnerOrganisationRepository partnerOrganisationRepository;
@Autowired
protected AddressTypeRepository addressTypeRepository;
@Autowired
private QuestionRepository questionRepository;
protected Supplier<ServiceResult<Section>> section(long id) {
return () -> getSection(id);
}
protected Supplier<ServiceResult<Application>> application(long id) {
return () -> getApplication(id);
}
protected Supplier<ServiceResult<Project>> project(long id) {
return () -> getProject(id);
}
protected ServiceResult<Project> getProject(long id) {
return find(projectRepository.findById(id), notFoundError(Project.class, id));
}
protected final Supplier<ServiceResult<Application>> openApplication(long applicationId) {
return () -> getOpenApplication(applicationId);
}
protected final ServiceResult<Application> getOpenApplication(long applicationId) {
return find(application(applicationId)).andOnSuccess(application -> {
if (application.getCompetition() != null && !OPEN.equals(application.getCompetition().getCompetitionStatus())) {
return serviceFailure(COMPETITION_NOT_OPEN);
} else {
return serviceSuccess(application);
}
}
);
}
protected final ServiceResult<Application> getOpenOrLaterApplication(long applicationId) {
return find(application(applicationId)).andOnSuccess(application -> {
if (application.getCompetition() != null && application.getCompetition().getCompetitionStatus().ordinal() >= OPEN.ordinal()) {
return serviceSuccess(application);
} else {
return serviceFailure(COMPETITION_NOT_OPEN_OR_LATER);
}
}
);
}
protected ServiceResult<Application> getApplication(long id) {
return find(applicationRepository.findById(id), notFoundError(Application.class, id));
}
protected ServiceResult<Section> getSection(long id) {
return find(sectionRepository.findById(id), notFoundError(Section.class, id));
}
protected Supplier<ServiceResult<Competition>> competition(long id) {
return () -> getCompetition(id);
}
protected ServiceResult<Competition> getCompetition(long id) {
return find(competitionRepository.findById(id), notFoundError(Competition.class, id));
}
protected Supplier<ServiceResult<Organisation>> organisation(long id) {
return () -> getOrganisation(id);
}
protected ServiceResult<Organisation> getOrganisation(long id) {
return find(organisationRepository.findById(id), notFoundError(Organisation.class, id));
}
protected ServiceResult<PartnerOrganisation> getPartnerOrganisation(long projectId, long organisationId) {
return find(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId), notFoundError(PartnerOrganisation.class, projectId, organisationId));
}
protected Supplier<ServiceResult<Question>> question(long questionId) {
return () -> getQuestion(questionId);
}
protected ServiceResult<Question> getQuestion(long questionId) {
return find(questionRepository.findById(questionId), notFoundError(Question.class));
}
}
|
package org.broadinstitute.sting.playground.gatk.walkers.varianteval;
import org.broadinstitute.sting.WalkerTest;
import org.junit.Test;
import java.io.File;
import java.util.*;
/**
* @author aaron
* <p/>
* Class VariantEvalWalkerTest
* <p/>
* test out the variant eval walker under different runtime conditions.
*/
public class VariantEvalWalkerIntegrationTest extends WalkerTest {
@Test
public void testEvalVariantROD() {
HashMap<String, String> md5 = new HashMap<String, String>();
md5.put("", "d6b8c2d6c37d42d1ca2288799a8bd8e4");
md5.put("-A", "0294b2e3915e88dfe2547e9db64ed1b3");
/**
* the above MD5 was calculated from running the following command:
*
* java -jar ./dist/GenomeAnalysisTK.jar \
* -R /broad/1KG/reference/human_b36_both.fasta \
* -T VariantEval \
* --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod \
* -L 1:10,000,000-11,000,000 \
* --outerr myVariantEval \
* --supressDateInformation \
* --rodBind eval,Variants,/humgen/gsa-scr1/GATK_Data/Validation_Data/NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.variants.geli.calls
*
*/
for ( Map.Entry<String, String> e : md5.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R " + oneKGLocation + "reference/human_b36_both.fasta" +
" --rodBind eval,Variants," + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.variants.geli.calls" +
" -T VariantEval" +
" --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod" +
" -L 1:10,000,000-11,000,000" +
" --outerr %s" +
" --supressDateInformation " + e.getKey(),
1, // just one output file
Arrays.asList(e.getValue()));
List<File> result = executeTest("testEvalVariantROD", spec).getFirst();
}
}
@Test
public void testEvalVariantRODConfSix() {
List<String> md5 = new ArrayList<String>();
md5.add("85cfefcac2dfb06545792605a3043a52");
/**
* the above MD5 was calculated from running the following command:
*
* java -jar ./dist/GenomeAnalysisTK.jar \
* -R /broad/1KG/reference/human_b36_both.fasta \
* -T VariantEval \
* --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod \
* -L 1:10,000,000-11,000,000 \
* --outerr myVariantEval \
* --supressDateInformation \
* --rodBind eval,Variants,/humgen/gsa-scr1/GATK_Data/Validation_Data/NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.variants.geli.calls \
* -minConfidenceScore 6
*/
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R " + oneKGLocation + "reference/human_b36_both.fasta" +
" --rodBind eval,Variants," + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.variants.geli.calls" +
" -T VariantEval" +
" --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod" +
" -L 1:10,000,000-11,000,000" +
" --outerr %s" +
" --supressDateInformation" +
" -minPhredConfidenceScore 60",
1, // just one output file
md5);
List<File> result = executeTest("testEvalVariantRODConfSixty", spec).getFirst();
}
@Test
public void testEvalVariantRODOutputViolations() {
List<String> md5 = new ArrayList<String>();
md5.add("e24732ffd95a78385a2c6986d1d3a359");
/**
* the above MD5 was calculated from running the following command:
*
* java -jar ./dist/GenomeAnalysisTK.jar \
* -R /broad/1KG/reference/human_b36_both.fasta \
* -T VariantEval \
* --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod \
* -L 1:10,000,000-11,000,000 \
* --outerr myVariantEval \
* --supressDateInformation \
* --rodBind eval,Variants,/humgen/gsa-scr1/GATK_Data/Validation_Data/NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.variants.geli.calls \
* --includeViolations
*/
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R " + oneKGLocation + "reference/human_b36_both.fasta" +
" --rodBind eval,Variants," + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.variants.geli.calls" +
" -T VariantEval" +
" --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod" +
" -L 1:10,000,000-11,000,000" +
" --outerr %s" +
" --supressDateInformation" +
" --includeViolations",
1, // just one output file
md5);
List<File> result = executeTest("testEvalVariantRODOutputViolations", spec).getFirst();
}
@Test
public void testEvalGenotypeROD() {
List<String> md5 = new ArrayList<String>();
md5.add("010d1c7ce773b39f3de1355eb9682e4d");
/**
* the above MD5 was calculated after running the following command:
*
* java -jar ./dist/GenomeAnalysisTK.jar \
* -R /broad/1KG/reference/human_b36_both.fasta \
* -T VariantEval \
* --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod \
* -L 1:10,000,000-11,000,000 \
* --outerr myVariantEval \
* --supressDateInformation \
* --evalContainsGenotypes \
* --rodBind eval,Variants,/humgen/gsa-scr1/GATK_Data/Validation_Data/NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.genotypes.geli.calls \
* --rodBind hapmap-chip,GFF,/humgen/gsa-scr1/GATK_Data/1KG_gffs/NA12878.1kg.gff
*/
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R " + oneKGLocation + "reference/human_b36_both.fasta" +
" --rodBind eval,Variants," + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.lod5.genotypes.geli.calls" +
" -T VariantEval" +
" --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod" +
" -L 1:10,000,000-11,000,000" +
" --outerr %s" +
" --supressDateInformation" +
" --evalContainsGenotypes" +
" --rodBind hapmap-chip,GFF,/humgen/gsa-scr1/GATK_Data/1KG_gffs/NA12878.1kg.gff",
1, // just one output file
md5);
List<File> result = executeTest("testEvalGenotypeROD", spec).getFirst();
}
@Test
public void testEvalMarksGenotypingExample() {
List<String> md5 = new ArrayList<String>();
md5.add("7d5a98c01051f96a684a383786da3d76");
/**
* Run with the following commands:
*
* java -Xmx2048m -jar /humgen/gsa-hphome1/depristo/dev/GenomeAnalysisTK/trunk/dist/GenomeAnalysisTK.jar
* -T VariantEval -R /broad/1KG/reference/human_b36_both.fasta -l INFO
* -B eval,Variants,/humgen/gsa-scr1/ebanks/concordanceForMark/UMichVsBroad.venn.set1Only.calls
* -D /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod -hc /humgen/gsa-scr1/GATK_Data/1KG_gffs/NA12878.1kg.gff
* -G -L 1 -o /humgen/gsa-scr1/ebanks/concordanceForMark/UMichVsBroad.venn.set1Only.calls.eval
*/
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T VariantEval -R " + oneKGLocation + "reference/human_b36_both.fasta " +
"-B eval,Variants," + validationDataLocation + "UMichVsBroad.venn.set1Only.calls " +
"-D /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod -hc /humgen/gsa-scr1/GATK_Data/1KG_gffs/NA12878.1kg.gff " +
"-G " +
"--supressDateInformation " +
"-L 1:1-10,000,000 " +
"--outerr %s",
1, // just one output file
md5);
List<File> result = executeTest("testEvalMarksGenotypingExample", spec).getFirst();
}
@Test
public void testEvalRuntimeWithLotsOfIntervals() {
List<String> md5 = new ArrayList<String>();
md5.add("d11ea079fc1835514d392056a2c2a28d");
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-T VariantEval -R " + oneKGLocation + "reference/human_b36_both.fasta " +
"-B eval,Variants," + validationDataLocation + "NA12878.pilot_3.all.geli.calls " +
"-D /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod " +
"--supressDateInformation " +
"-L /humgen/gsa-scr1/GATK_Data/thousand_genomes_alpha_redesign.targets.b36.interval_list " +
"--outerr %s",
1, // just one output file
md5);
List<File> result = executeTest("testEvalRuntimeWithLotsOfIntervals", spec).getFirst();
}
@Test
public void testVCFVariantEvals() {
HashMap<String, String> md5 = new HashMap<String, String>();
md5.put("", "3dda57ac7a9c8f3800726c9affb9d9bd");
md5.put("-A", "d985e61fd0d7fc34c9c1a553e2881c67");
md5.put("-A --includeFilteredRecords", "434c60986aa54c5fd07c22df1910ec44");
md5.put("-A --sampleName NA12878", "aff844b88f71824a6cd3cce553325b17");
md5.put("-A -vcfInfoSelector AF=0.50", "9ab9fa5d89cd6e3278d0d2b13cabbd51");
for ( Map.Entry<String, String> e : md5.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R " + oneKGLocation + "reference/human_b36_both.fasta" +
" --rodBind eval,VCF," + validationDataLocation + "NA12878.example1.vcf" +
" -T VariantEval" +
" --DBSNP /humgen/gsa-scr1/GATK_Data/dbsnp_129_b36.rod" +
" -hc /humgen/gsa-scr1/GATK_Data/1KG_gffs/NA12878.1kg.gff" +
" -G" +
" -L 1:1-10,000" +
" --outerr %s" +
" --supressDateInformation " + e.getKey(),
1, // just one output file
Arrays.asList(e.getValue()));
List<File> result = executeTest("testVCFVariantEvals", spec).getFirst();
}
}
}
|
package com.werdpressed.partisan.reallyusefulnotes.localsaveandload;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.werdpressed.partisan.reallyusefulnotes.localsaveandload.databasetasks.AddTask;
import com.werdpressed.partisan.reallyusefulnotes.localsaveandload.databasetasks.DeleteTask;
import com.werdpressed.partisan.reallyusefulnotes.localsaveandload.databasetasks.FilesDatabaseHelper;
import com.werdpressed.partisan.reallyusefulnotes.localsaveandload.databasetasks.LoadTask;
import com.werdpressed.partisan.reallyusefulnotes.localsaveandload.databasetasks.SaveTask;
public class MainActivity extends AppCompatActivity implements
LoadTask.LoadComplete, AddTask.AddComplete
{
private static final String NOTE_TAG = "note_fragment_tag";
private AddTask at = null;
private LoadTask lt = null;
private SaveTask st = null;
private DeleteTask dt = null;
private TextView welcomeMessage;
private Cursor data = null;
private AlertDialog loadingDialog;
private NoteFragment mNoteFragment;
private long keyId;
private String title, content;
private CursorStatus cursorStatus = CursorStatus.DEFAULT;
private enum CursorStatus {
ADD, DELETE, NO_DATA, DEFAULT
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
welcomeMessage = (TextView) findViewById(R.id.ma_welcome);
welcomeMessage.setVisibility(View.GONE);
if (data == null) {
loadingDialog = loadingDialog();
loadingDialog.show();
lt = new LoadTask(this);
lt.execute();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (!data.isClosed()) {
data.close();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
Toast.makeText(this, getString(R.string.action_settings), Toast.LENGTH_SHORT).show();
break;
case R.id.action_add_note:
cursorStatus = CursorStatus.ADD;
buildAddDialog().show();
break;
case R.id.action_save_note:
mNoteFragment = (NoteFragment) getFragmentManager()
.findFragmentById(R.id.note_fragment_container);
st = new SaveTask(this, mNoteFragment.getKeyId());
st.execute(mNoteFragment.getCurrentText());
break;
case R.id.action_view_notes:
buildViewNoteDialog().show();
break;
case R.id.action_delete_notes:
cursorStatus = CursorStatus.DELETE;
deleteDialog().show();
break;
}
return super.onOptionsItemSelected(item);
}
public Cursor getData(){
return data;
}
@Override
public void loadComplete(Cursor cursor) {
data = cursor;
if(loadingDialog.isShowing()) loadingDialog.dismiss();
mNoteFragment = (NoteFragment) getFragmentManager().findFragmentById(R.id.note_fragment_container);
if (!data.moveToFirst()) {
cursorStatus = CursorStatus.NO_DATA;
welcomeMessage.setVisibility(View.VISIBLE);
if (mNoteFragment != null) {
getFragmentManager()
.beginTransaction()
.remove(mNoteFragment)
.commit();
}
getSupportActionBar().setTitle(getString(R.string.app_name));
}
switch (cursorStatus) {
case ADD:
if(welcomeMessage.getVisibility() == View.VISIBLE) welcomeMessage.setVisibility(View.GONE);
if (mNoteFragment != null) {
loadNoteFragment(keyId, title, null);
} else {
getFragmentManager()
.beginTransaction()
.add(R.id.note_fragment_container, NoteFragment.newInstance(keyId, title, content))
.addToBackStack(null)
.commit();
}
break;
case DEFAULT:
if (mNoteFragment != null) {
break;
} else {
data.moveToFirst();
keyId = data.getInt(data.getColumnIndex(FilesDatabaseHelper.KEY_ID));
title = data.getString(data.getColumnIndex(FilesDatabaseHelper.TITLE));
content = data.getString(data.getColumnIndex(FilesDatabaseHelper.CONTENT));
getFragmentManager()
.beginTransaction()
.add(R.id.note_fragment_container, NoteFragment.newInstance(keyId, title, content))
.addToBackStack(null)
.commit();
}
case DELETE:
data.moveToFirst();
keyId = data.getInt(data.getColumnIndex(FilesDatabaseHelper.KEY_ID));
title = data.getString(data.getColumnIndex(FilesDatabaseHelper.TITLE));
content = data.getString(data.getColumnIndex(FilesDatabaseHelper.CONTENT));
loadNoteFragment(keyId, title, content);
break;
}
cursorStatus = CursorStatus.DEFAULT;
}
@Override
public void addComplete(Long newKeyId) {
keyId = newKeyId;
}
private AlertDialog buildAddDialog() {
return new AlertDialog.Builder(this, R.style.AlertDialogStyle)
.setTitle(getString(R.string.and_title))
.setView(R.layout.add_note_dialog)
.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText newTitle = (EditText) ((AlertDialog) dialog).findViewById(R.id.and_title_entry);
title = newTitle.getText().toString();
at = new AddTask(MainActivity.this);
at.execute(title);
}
})
.setNegativeButton(getString(R.string.cancel), null)
.create();
}
private AlertDialog buildViewNoteDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
final ListAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
data,
new String[] {FilesDatabaseHelper.TITLE},
new int[] {android.R.id.text1},
0);
builder.setTitle(getString(R.string.app_name));
builder.setView(R.layout.view_notes_df);
builder.setAdapter(listAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
data.moveToPosition(which);
keyId = data.getInt(data.getColumnIndex(FilesDatabaseHelper.KEY_ID));
title = data.getString(data.getColumnIndex(FilesDatabaseHelper.TITLE));
content = data.getString(data.getColumnIndex(FilesDatabaseHelper.CONTENT));
loadNoteFragment(keyId, title, content);
}
});
builder.setPositiveButton(getString(R.string.cancel), null);
return builder.create();
}
private AlertDialog loadingDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
builder.setTitle(getString(R.string.app_name));
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage(getString(R.string.loading));
return builder.create();
}
private AlertDialog deleteDialog(){
mNoteFragment = (NoteFragment) getFragmentManager().findFragmentById(R.id.note_fragment_container);
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
builder.setTitle(R.string.dnd_title);
builder.setMessage(getString(R.string.dnd_content, mNoteFragment.getTitle()));
builder.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dt = new DeleteTask(MainActivity.this, mNoteFragment.getKeyId());
dt.execute();
}
});
return builder.create();
}
private void loadNoteFragment(long keyId, String title, String content) {
getFragmentManager()
.beginTransaction()
.replace(R.id.note_fragment_container, NoteFragment.newInstance(keyId, title, content))
.addToBackStack(null)
.commit();
}
}
|
package org.zalando.nakadiproducer.tests;
import org.junit.*;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.zalando.nakadiproducer.transmission.MockNakadiPublishingClient;
import org.zalando.nakadiproducer.transmission.impl.EventTransmitter;
import java.io.File;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(
// This line looks like that by intention: We want to test that the MockNakadiPublishingClient will be picked up
// by our starter *even if* it has been defined *after* the application itself. This has been a problem until
// this commit.
classes = { Application.class, MockNakadiConfig.class },
properties = { "nakadi-producer.transmission-polling-delay=30"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
public class ApplicationIT {
@LocalManagementPort
private int localManagementPort;
@ClassRule
public static final EnvironmentVariables environmentVariables
= new EnvironmentVariables();
@BeforeClass
public static void fakeCredentialsDir() {
environmentVariables.set("CREDENTIALS_DIR", new File("src/main/test/tokens").getAbsolutePath());
}
@Autowired
private MockNakadiPublishingClient mockClient;
@Autowired
private EventTransmitter eventTransmitter;
@Before
@After
public void cleanUpMock() {
eventTransmitter.sendEvents();
mockClient.clearSentEvents();
}
@Test
public void shouldSuccessfullyStartAndSnapshotCanBeTriggered() throws InterruptedException {
given().baseUri("http://localhost:" + localManagementPort).contentType("application/json")
.when().post("/actuator/snapshot-event-creation/eventtype")
.then().statusCode(204);
// leave some time for the scheduler to run
Thread.sleep(200);
List<String> events = mockClient.getSentEvents("eventtype");
assertThat(events, hasSize(2));
}
}
|
package org.opendaylight.ovsdb.openstack.netvirt.impl;
import com.google.common.base.Preconditions;
import java.util.List;
import org.opendaylight.neutron.spi.INeutronNetworkCRUD;
import org.opendaylight.neutron.spi.INeutronPortCRUD;
import org.opendaylight.neutron.spi.NeutronNetwork;
import org.opendaylight.neutron.spi.NeutronPort;
import org.opendaylight.ovsdb.openstack.netvirt.ConfigInterface;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
import org.opendaylight.ovsdb.openstack.netvirt.api.TenantNetworkManager;
import org.opendaylight.ovsdb.openstack.netvirt.api.VlanConfigurationCache;
import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TenantNetworkManagerImpl implements ConfigInterface, TenantNetworkManager {
static final Logger logger = LoggerFactory.getLogger(TenantNetworkManagerImpl.class);
private INeutronNetworkCRUD neutronNetworkCache;
private INeutronPortCRUD neutronPortCache;
private VlanConfigurationCache vlanConfigurationCache;
private Southbound southbound;
@Override
public int getInternalVlan(Node node, String networkId) {
Integer vlan = vlanConfigurationCache.getInternalVlan(node, networkId);
if (vlan == null) {
return 0;
}
return vlan;
}
@Override
public void reclaimInternalVlan(Node node, NeutronNetwork network) {
int vlan = vlanConfigurationCache.reclaimInternalVlan(node, network.getID());
if (vlan <= 0) {
logger.debug("Unable to get an internalVlan for Network {}", network);
return;
}
logger.debug("Removed Vlan {} on {}", vlan);
}
@Override
public void programInternalVlan(Node node, OvsdbTerminationPointAugmentation tp, NeutronNetwork network) {
int vlan = vlanConfigurationCache.getInternalVlan(node, network.getID());
logger.debug("Programming Vlan {} on {}", vlan, tp);
if (vlan <= 0) {
logger.debug("Unable to get an internalVlan for Network {}", network);
return;
}
southbound.addVlanToTp(vlan);
}
@Override
public boolean isTenantNetworkPresentInNode(Node node, String segmentationId) {
String networkId = this.getNetworkId(segmentationId);
if (networkId == null) {
logger.debug("Tenant Network not found with Segmenation-id {}",segmentationId);
return false;
}
try {
List<OvsdbTerminationPointAugmentation> ports = southbound.getTerminationPointsOfBridge(node);
for (OvsdbTerminationPointAugmentation port : ports) {
String ifaceId = southbound.getInterfaceExternalIdsValue(port, Constants.EXTERNAL_ID_INTERFACE_ID);
if (ifaceId != null && isInterfacePresentInTenantNetwork(ifaceId, networkId)) {
logger.debug("Tenant Network {} with Segmentation-id {} is present in Node {} / Interface {}",
networkId, segmentationId, node, port);
return true;
}
}
} catch (Exception e) {
logger.error("Error while trying to determine if network is present on node", e);
return false;
}
logger.debug("Tenant Network {} with Segmenation-id {} is NOT present in Node {}",
networkId, segmentationId, node);
return false;
}
@Override
public String getNetworkId(String segmentationId) {
Preconditions.checkNotNull(neutronNetworkCache);
List <NeutronNetwork> networks = neutronNetworkCache.getAllNetworks();
for (NeutronNetwork network : networks) {
if (network.getProviderSegmentationID() != null &&
network.getProviderSegmentationID().equalsIgnoreCase(segmentationId)) {
return network.getNetworkUUID();
}
}
return null;
}
@Override
public NeutronNetwork getTenantNetwork(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
Preconditions.checkNotNull(neutronNetworkCache);
Preconditions.checkNotNull(neutronPortCache);
NeutronNetwork neutronNetwork = null;
logger.debug("getTenantNetwork for {}", terminationPointAugmentation);
String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
Constants.EXTERNAL_ID_INTERFACE_ID);
if (neutronPortId != null) {
NeutronPort neutronPort = neutronPortCache.getPort(neutronPortId);
if (neutronPort != null) {
neutronNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID());
if (neutronNetwork != null) {
logger.debug("mapped to {}", neutronNetwork);
} else {
logger.debug("getTenantNetwork: did not find neutronNetwork in cache from neutronPort {}",
neutronPortId);
}
} else {
logger.info("getTenantNetwork did not find neutronPort {} from termination point {}",
neutronPortId, terminationPointAugmentation.getName());
}
} else {
logger.debug("getTenantNetwork: did not find {} in external_ids", Constants.EXTERNAL_ID_INTERFACE_ID);
}
return neutronNetwork;
}
@Override
public NeutronPort getTenantPort(OvsdbTerminationPointAugmentation terminationPointAugmentation) {
Preconditions.checkNotNull(neutronPortCache);
NeutronPort neutronPort = null;
logger.trace("getTenantPort for {}", terminationPointAugmentation.getName());
String neutronPortId = southbound.getInterfaceExternalIdsValue(terminationPointAugmentation,
Constants.EXTERNAL_ID_INTERFACE_ID);
if (neutronPortId != null) {
neutronPort = neutronPortCache.getPort(neutronPortId);
}
if (neutronPort != null) {
logger.debug("mapped to {}", neutronPort);
} else {
logger.warn("getTenantPort did not find port for {}", terminationPointAugmentation.getName());
}
return neutronPort;
}
@Override
public int networkCreated (Node node, String networkId) {
return vlanConfigurationCache.assignInternalVlan(node, networkId);
}
@Override
public void networkDeleted(String id) {
//ToDo: Delete? This method does nothing since container support was dropped...
}
private boolean isInterfacePresentInTenantNetwork (String portId, String networkId) {
NeutronPort neutronPort = neutronPortCache.getPort(portId);
return neutronPort != null && neutronPort.getNetworkUUID().equalsIgnoreCase(networkId);
}
@Override
public void setDependencies(BundleContext bundleContext, ServiceReference serviceReference) {
vlanConfigurationCache =
(VlanConfigurationCache) ServiceHelper.getGlobalInstance(VlanConfigurationCache.class, this);
southbound =
(Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
}
@Override
public void setDependencies(Object impl) {
if (impl instanceof INeutronNetworkCRUD) {
neutronNetworkCache = (INeutronNetworkCRUD)impl;
} else if (impl instanceof INeutronPortCRUD) {
neutronPortCache = (INeutronPortCRUD)impl;
}
}
}
|
package com.poco.PoCoRuntime;
import org.aspectj.lang.JoinPoint;
/**
* Represents an action/result intercepted by AspectJ for use by PoCo policies.
* This object is created from an AspectJ JoinPoint object and provides all necessary
* information for PoCo policies to make a decision.
*/
public class Event {
private String signature;
/**
* Construct an event from explicitly passed details. Used when testing.
* @param signature method signature of event
*/
public Event(String signature) {
this.signature = signature;
}
public Event(JoinPoint joinPoint) {
this.signature = joinPoint.getSignature().toString();
}
public String getSignature() {
return signature;
}
}
|
package org.zstack.network.l2.vxlan.vxlanNetworkPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.asyncbatch.While;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.Q;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.header.core.Completion;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.WhileDoneCompletion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.ErrorCodeList;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.HostConstant;
import org.zstack.header.host.HostVO;
import org.zstack.header.host.HostVO_;
import org.zstack.header.host.HypervisorType;
import org.zstack.header.message.MessageReply;
import org.zstack.header.network.l2.*;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.vm.InstantiateResourceOnAttachingNicExtensionPoint;
import org.zstack.header.vm.VmInstanceSpec;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.kvm.*;
import org.zstack.network.l2.vxlan.vtep.CreateVtepMsg;
import org.zstack.network.l2.vxlan.vtep.VtepVO;
import org.zstack.network.l2.vxlan.vtep.VtepVO_;
import org.zstack.network.l2.vxlan.vxlanNetwork.L2VxlanNetworkInventory;
import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkConstant;
import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkVO;
import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkVO_;
import org.zstack.network.service.MtuGetter;
import org.zstack.tag.SystemTagCreator;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import java.util.*;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.operr;
import static org.zstack.network.l2.vxlan.vxlanNetworkPool.VxlanNetworkPoolConstant.*;
import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
public class KVMRealizeL2VxlanNetworkBackend implements L2NetworkRealizationExtensionPoint, KVMCompleteNicInformationExtensionPoint, InstantiateResourceOnAttachingNicExtensionPoint {
private static CLogger logger = Utils.getLogger(KVMRealizeL2VxlanNetworkBackend.class);
@Autowired
private DatabaseFacade dbf;
@Autowired
private CloudBus bus;
private static String VTEP_IP = "vtepIp";
private static String NEED_POPULATE = "needPopulate";
public static String makeBridgeName(int vxlan) {
return String.format("br_vx_%s",vxlan);
}
@Override
public void realize(final L2NetworkInventory l2Network, final String hostUuid, final Completion completion) {
realize(l2Network, hostUuid, false, completion);
}
@Override
public void realize(final L2NetworkInventory l2Network, final String hostUuid, boolean noStatusCheck, final Completion completion) {
final L2VxlanNetworkInventory l2vxlan = (L2VxlanNetworkInventory) l2Network;
final List<String> vtepIps = Q.New(VtepVO.class).select(VtepVO_.vtepIp).eq(VtepVO_.hostUuid, hostUuid).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).listValues();
if (vtepIps != null && vtepIps.size() > 1) {
throw new OperationFailureException(operr("find multiple vtep ips[%s] for one host[uuid:%s], need to delete host and add again",
vtepIps, hostUuid));
}
if (vtepIps.size() == 0) {
ErrorCode err = operr("failed to find vtep on host[uuid: %s], please re-attach vxlanpool[uuid: %s] to cluster.",
hostUuid, l2vxlan.getPoolUuid());
completion.fail(err);
return;
}
String vtepIp = vtepIps.get(0);
List<String> peers = Q.New(VtepVO.class).select(VtepVO_.vtepIp).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).listValues();
Set<String> p = new HashSet<String>(peers);
p.remove(vtepIp);
peers.clear();
peers.addAll(p);
String info = String.format(
"get vtep peers [%s] and vtep ip [%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s]", peers,
vtepIp, l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid);
logger.debug(info);
List<Integer> dstports = Q.New(VtepVO.class).select(VtepVO_.port)
.eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid())
.eq(VtepVO_.hostUuid,hostUuid)
.eq(VtepVO_.vtepIp,vtepIp)
.listValues();
Integer dstport = dstports.get(0);
final VxlanKvmAgentCommands.CreateVxlanBridgeCmd cmd = new VxlanKvmAgentCommands.CreateVxlanBridgeCmd();
cmd.setVtepIp(vtepIp);
cmd.setBridgeName(makeBridgeName(l2vxlan.getVni()));
cmd.setVni(l2vxlan.getVni());
cmd.setL2NetworkUuid(l2Network.getUuid());
cmd.setPeers(peers);
cmd.setDstport(dstport);
cmd.setMtu(new MtuGetter().getL2Mtu(l2Network));
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setHostUuid(hostUuid);
msg.setCommand(cmd);
msg.setNoStatusCheck(noStatusCheck);
msg.setPath(VXLAN_KVM_REALIZE_L2VXLAN_NETWORK_PATH);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
KVMHostAsyncHttpCallReply hreply = reply.castReply();
VxlanKvmAgentCommands.CreateVxlanBridgeResponse rsp = hreply.toResponse(VxlanKvmAgentCommands.CreateVxlanBridgeResponse.class);
if (!rsp.isSuccess()) {
ErrorCode err = operr("failed to create bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s], because %s",
cmd.getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid, rsp.getError());
completion.fail(err);
return;
}
String info = String.format(
"successfully realize bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s]", cmd
.getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid);
logger.debug(info);
SystemTagCreator creator = KVMSystemTags.L2_BRIDGE_NAME.newSystemTagCreator(l2Network.getUuid());
creator.inherent = true;
creator.ignoreIfExisting = true;
creator.setTagByTokens(map(e(KVMSystemTags.L2_BRIDGE_NAME_TOKEN, cmd.getBridgeName())));
creator.create();
completion.success();
}
});
}
@Override
public void check(final L2NetworkInventory l2Network, final String hostUuid, final Completion completion) {
check(l2Network, hostUuid, false, completion);
}
public void check(L2NetworkInventory l2Network, String hostUuid, boolean noStatusCheck, Completion completion) {
final L2VxlanNetworkInventory l2vxlan = (L2VxlanNetworkInventory) l2Network;
final String clusterUuid = Q.New(HostVO.class).select(HostVO_.clusterUuid).eq(HostVO_.uuid, hostUuid).findValue();
final VxlanNetworkPoolVO poolVO = Q.New(VxlanNetworkPoolVO.class).eq(VxlanNetworkPoolVO_.uuid, l2vxlan.getPoolUuid()).find();
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("check-l2-vxlan-%s-on-host-%s", l2Network.getUuid(), hostUuid));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
VxlanKvmAgentCommands.CheckVxlanCidrCmd cmd = new VxlanKvmAgentCommands.CheckVxlanCidrCmd();
cmd.setCidr(getAttachedCidrs(l2vxlan.getPoolUuid()).get(clusterUuid));
if (!poolVO.getPhysicalInterface().isEmpty()) {
cmd.setPhysicalInterfaceName(poolVO.getPhysicalInterface());
}
VtepVO vtep = Q.New(VtepVO.class).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).eq(VtepVO_.hostUuid, hostUuid).find();
if (vtep != null) {
cmd.setVtepip(vtep.getVtepIp());
}
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setHostUuid(hostUuid);
msg.setCommand(cmd);
msg.setPath(VXLAN_KVM_CHECK_L2VXLAN_NETWORK_PATH);
msg.setNoStatusCheck(noStatusCheck);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
KVMHostAsyncHttpCallReply hreply = reply.castReply();
VxlanKvmAgentCommands.CheckVxlanCidrResponse rsp = hreply.toResponse(VxlanKvmAgentCommands.CheckVxlanCidrResponse.class);
if (!rsp.isSuccess()) {
ErrorCode err = operr("failed to check cidr[%s] for l2VxlanNetwork[uuid:%s, name:%s] on kvm host[uuid:%s], %s",
cmd.getCidr(), l2vxlan.getUuid(), l2vxlan.getName(), hostUuid, rsp.getError());
trigger.fail(err);
return;
}
String info = String.format("successfully checked cidr[%s] for l2VxlanNetwork[uuid:%s, name:%s] on kvm host[uuid:%s]",
cmd.getCidr(), l2vxlan.getUuid(), l2vxlan.getName(), hostUuid);
logger.debug(info);
data.put(VTEP_IP, rsp.getVtepIp());
trigger.next();
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
List<VtepVO> vtepVOS = Q.New(VtepVO.class)
.eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid())
.eq(VtepVO_.hostUuid, hostUuid)
.list();
if (vtepVOS == null || vtepVOS.isEmpty()) {
/* vtep is not created, no action here */
} else if (vtepVOS.size() > 1) {
/* more than 1 vtep, shoult not happen */
throw new CloudRuntimeException(String.format("multiple vteps[ips: %s] found on host[uuid: %s]",
vtepVOS.stream().map(v -> v.getVtepIp()).collect(Collectors.toSet()), hostUuid));
} else if (vtepVOS.get(0).getVtepIp().equals(data.get(VTEP_IP))) {
/* vtep is already created */
logger.debug(String.format(
"vtep[ip:%s] from host[uuid:%s] for l2 vxlan network pool[uuid:%s] checks successfully",
vtepVOS.get(0).getVtepIp(), hostUuid, l2Network.getUuid()));
data.put(NEED_POPULATE, false);
trigger.next();
return;
} else {
/* remove old vtep */
logger.debug(String.format(
"remove deprecated vtep[ip:%s] from host[uuid:%s] for l2 vxlan network pool[uuid:%s]",
vtepVOS.get(0).getVtepIp(), hostUuid, l2Network.getUuid()));
dbf.remove(vtepVOS.get(0));
}
data.put(NEED_POPULATE, true);
CreateVtepMsg cmsg = new CreateVtepMsg();
cmsg.setPoolUuid(l2vxlan.getPoolUuid());
cmsg.setClusterUuid(clusterUuid);
cmsg.setHostUuid(hostUuid);
cmsg.setPort(VXLAN_PORT);
cmsg.setVtepIp((String) data.get(VTEP_IP));
cmsg.setType(KVM_VXLAN_TYPE);
bus.makeTargetServiceIdByResourceUuid(cmsg, L2NetworkConstant.SERVICE_ID, l2vxlan.getPoolUuid());
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
logger.warn(reply.getError().toString());
trigger.fail(reply.getError());
return;
}
logger.debug(String.format("created new vtep [%s] on vxlan network pool [%s]", cmsg.getVtepIp(), ((L2VxlanNetworkInventory) l2Network).getPoolUuid()));
trigger.next();
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
if (data.get(NEED_POPULATE).equals(false)) {
trigger.next();
return;
}
List<VtepVO> vteps = Q.New(VtepVO.class).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).list();
if (vteps.size() == 1) {
logger.debug("no need to populate fdb since there are only one vtep");
trigger.next();
return;
}
new While<>(vteps).all((vtep, completion1) -> {
List<String> peers = new ArrayList<>();
for (VtepVO vo : vteps) {
if (peers.contains(vo.getVtepIp()) || vo.getVtepIp().equals(vtep.getVtepIp())) {
continue;
} else {
peers.add(vo.getVtepIp());
}
}
logger.info(String.format("populate fdb for vtep %s in vxlan network %s", vtep.getVtepIp(), l2vxlan.getUuid()));
VxlanKvmAgentCommands.PopulateVxlanFdbCmd cmd = new VxlanKvmAgentCommands.PopulateVxlanFdbCmd();
cmd.setPeers(peers);
cmd.setVni(l2vxlan.getVni());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setHostUuid(vtep.getHostUuid());
msg.setCommand(cmd);
msg.setPath(VXLAN_KVM_POPULATE_FDB_L2VXLAN_NETWORK_PATH);
msg.setNoStatusCheck(noStatusCheck);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
bus.send(msg, new CloudBusCallBack(completion1) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
logger.warn(reply.getError().toString());
}
completion1.done();
}
});
}).run(new WhileDoneCompletion(trigger) {
@Override
public void done(ErrorCodeList errorCodeList) {
trigger.next();
}
});
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
}).start();
}
@Override
public L2NetworkType getSupportedL2NetworkType() {
return L2NetworkType.valueOf(VxlanNetworkConstant.VXLAN_NETWORK_TYPE);
}
@Override
public HypervisorType getSupportedHypervisorType() {
return HypervisorType.valueOf(KVMConstant.KVM_HYPERVISOR_TYPE);
}
@Override
public L2NetworkType getL2NetworkTypeVmNicOn() {
return getSupportedL2NetworkType();
}
@Override
public KVMAgentCommands.NicTO completeNicInformation(L2NetworkInventory l2Network, L3NetworkInventory l3Network, VmNicInventory nic) {
final Integer vni = getVni(l2Network.getUuid());
KVMAgentCommands.NicTO to = new KVMAgentCommands.NicTO();
to.setMac(nic.getMac());
to.setUuid(nic.getUuid());
to.setBridgeName(makeBridgeName(vni));
to.setDeviceId(nic.getDeviceId());
to.setNicInternalName(nic.getInternalName());
to.setMetaData(String.valueOf(vni));
to.setMtu(new MtuGetter().getMtu(l3Network.getUuid()));
return to;
}
@Override
public String getBridgeName(L2NetworkInventory l2Network) {
final Integer vni = getVni(l2Network.getUuid());
return makeBridgeName(vni);
}
public Map<String, String> getAttachedCidrs(String l2NetworkUuid) {
List<Map<String, String>> tokenList = VxlanSystemTags.VXLAN_POOL_CLUSTER_VTEP_CIDR.getTokensOfTagsByResourceUuid(l2NetworkUuid);
Map<String, String> attachedClusters = new HashMap<>();
for (Map<String, String> tokens : tokenList) {
attachedClusters.put(tokens.get(VxlanSystemTags.CLUSTER_UUID_TOKEN),
tokens.get(VxlanSystemTags.VTEP_CIDR_TOKEN).split("[{}]")[1]);
}
return attachedClusters;
}
private Integer getVni(String l2NetworkUuid) {
return Q.New(VxlanNetworkVO.class)
.eq(VxlanNetworkVO_.uuid, l2NetworkUuid)
.select(VxlanNetworkVO_.vni)
.findValue();
}
@Override
public void instantiateResourceOnAttachingNic(VmInstanceSpec spec, L3NetworkInventory l3, Completion completion) {
L2NetworkVO vo = Q.New(L2NetworkVO.class).eq(L2NetworkVO_.uuid, l3.getL2NetworkUuid()).find();
if (!vo.getType().equals(VxlanNetworkConstant.VXLAN_NETWORK_TYPE)) {
completion.success();
return;
} else {
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
L2VxlanNetworkInventory l2 = L2VxlanNetworkInventory.valueOf((VxlanNetworkVO) Q.New(VxlanNetworkVO.class).eq(VxlanNetworkVO_.uuid, vo.getUuid()).find());
chain.setName(String.format("attach-l2-vxlan-%s-on-host-%s", l2.getUuid(), spec.getDestHost().getUuid()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
check(l2, spec.getDestHost().getUuid(), new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
logger.debug(String.format("check l2 vxlan failed for %s", errorCode.toString()));
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
realize(l2, spec.getDestHost().getUuid(), new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
logger.debug(String.format("realize l2 vxlan failed for %s", errorCode.toString()));
trigger.fail(errorCode);
}
});
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
}).start();
}
}
@Override
public void releaseResourceOnAttachingNic(VmInstanceSpec spec, L3NetworkInventory l3, NoErrorCompletion completion) {
completion.done();
}
public void delete(L2NetworkInventory l2Network, String hostUuid, Completion completion) {
L2VxlanNetworkInventory l2vxlan = (L2VxlanNetworkInventory) l2Network;
final VxlanKvmAgentCommands.DeleteVxlanBridgeCmd cmd = new VxlanKvmAgentCommands.DeleteVxlanBridgeCmd();
cmd.setBridgeName(makeBridgeName(l2vxlan.getVni()));
cmd.setVni(l2vxlan.getVni());
cmd.setL2NetworkUuid(l2Network.getUuid());
final List<String> vtepIps = Q.New(VtepVO.class).select(VtepVO_.vtepIp).eq(VtepVO_.hostUuid, hostUuid).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).listValues();
String vtepIp = vtepIps.get(0);
cmd.setVtepIp(vtepIp);
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setHostUuid(hostUuid);
msg.setCommand(cmd);
msg.setPath(VXLAN_KVM_DELETE_L2VXLAN_NETWORK_PATH);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
KVMHostAsyncHttpCallReply hreply = reply.castReply();
VxlanKvmAgentCommands.DeleteVxlanBridgeResponse rsp = hreply.toResponse(VxlanKvmAgentCommands.DeleteVxlanBridgeResponse.class);
if (!rsp.isSuccess()) {
ErrorCode err = operr("failed to delete bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s], because %s",
cmd.getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid, rsp.getError());
completion.fail(err);
return;
}
String message = String.format(
"successfully delete bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s]", cmd
.getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid);
logger.debug(message);
completion.success();
}
});
}
}
|
package org.yakindu.sct.refactoring.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.yakindu.sct.refactoring.refactor.AbstractRefactoring;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public abstract class AbstractRefactoringHandler<T extends EObject> extends AbstractHandler {
private AbstractRefactoring<T> refactoring;
public abstract AbstractRefactoring<T> createRefactoring();
public abstract void setContext(AbstractRefactoring<T> refactoring, ISelection selection);
public AbstractRefactoringHandler() {
refactoring = createRefactoring();
}
protected Object getFirstElement(ISelection selection) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
return structuredSelection.getFirstElement();
}
/**
* Calculates the enabled state based on the refactoring state
*/
@Override
public boolean isEnabled() {
IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (activeWorkbenchWindow == null)
return false;
ISelection selection = activeWorkbenchWindow.getActivePage().getSelection();
if (selection == null)
return false;
setContext(refactoring, selection);
return refactoring.isExecutable();
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
refactoring.execute();
return null;
}
}
|
package com.silverpeas.processManager.record;
import com.silverpeas.form.DataRecord;
import com.silverpeas.form.FieldTemplate;
import com.silverpeas.form.FormException;
import com.silverpeas.form.RecordTemplate;
import com.silverpeas.form.fieldType.TextField;
import com.silverpeas.form.record.GenericFieldTemplate;
import com.stratelia.webactiv.util.ResourceLocator;
public class QuestionTemplate implements RecordTemplate {
private static ResourceLocator label = null;
private String language;
private boolean readonly;
/**
* A UserTemplate is built from a language : use addFieldTemplate for each field.
* @see addFieldTemplate
*/
public QuestionTemplate(String language, boolean readonly) {
label = new ResourceLocator(
"com.silverpeas.processManager.multilang.processManagerBundle",
language);
this.language = language;
this.readonly = readonly;
}
/**
* Returns all the field names of the UserRecord built on this template.
*/
public String[] getFieldNames() {
String[] fieldNames = new String[1];
fieldNames[0] = "Content";
return fieldNames;
}
/**
* Returns all the field templates.
*/
public FieldTemplate[] getFieldTemplates() {
try {
FieldTemplate[] templates = new FieldTemplate[1];
templates[0] = getFieldTemplate("Content");
return templates;
} catch (FormException fe) {
return null;
}
}
/**
* Returns the FieldTemplate of the named field.
* @throw FormException if the field name is unknown.
*/
public FieldTemplate getFieldTemplate(String fieldName) throws FormException {
GenericFieldTemplate fieldTemplate = null;
fieldTemplate = new GenericFieldTemplate(fieldName, "text");
fieldTemplate.addLabel(label.getString("processManager." + fieldName),
language);
if (readonly) {
fieldTemplate.setDisplayerName("simpletext");
} else {
fieldTemplate.setDisplayerName("textarea");
fieldTemplate.setMandatory(true);
fieldTemplate.setReadOnly(readonly);
fieldTemplate.addParameter(TextField.PARAM_MAXLENGTH, "500");
}
return fieldTemplate;
}
/**
* Returns the field index of the named field.
* @throw FormException if the field name is unknown.
*/
public int getFieldIndex(String fieldName) throws FormException {
if (fieldName.equals("Content"))
return 0;
else
return -1;
}
/**
* Returns an empty DataRecord built on this template.
*/
public DataRecord getEmptyRecord() throws FormException {
return new QuestionRecord("");
}
/**
* Returns true if the data record is built on this template and all the constraints are ok.
*/
public boolean checkDataRecord(DataRecord record) {
try {
String value = (String) (record.getField("Content").getObjectValue());
return (value != null && value.length() > 0);
} catch (FormException fe) {
return false;
}
}
}
|
package com.oracle.truffle.llvm.nodes.impl.memory;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.NodeChildren;
import com.oracle.truffle.api.dsl.NodeField;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.interop.ForeignAccess;
import com.oracle.truffle.api.interop.Message;
import com.oracle.truffle.api.interop.TruffleObject;
import com.oracle.truffle.api.interop.UnknownIdentifierException;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.interop.UnsupportedTypeException;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.llvm.nodes.base.LLVMNode;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMAddressNode;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMFunctionNode;
import com.oracle.truffle.llvm.nodes.impl.base.floating.LLVM80BitFloatNode;
import com.oracle.truffle.llvm.nodes.impl.base.floating.LLVMDoubleNode;
import com.oracle.truffle.llvm.nodes.impl.base.floating.LLVMFloatNode;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI16Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI1Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI32Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI64Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI8Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMIVarBitNode;
import com.oracle.truffle.llvm.types.LLVMAddress;
import com.oracle.truffle.llvm.types.LLVMFunctionDescriptor;
import com.oracle.truffle.llvm.types.LLVMIVarBit;
import com.oracle.truffle.llvm.types.LLVMTruffleObject;
import com.oracle.truffle.llvm.types.floating.LLVM80BitFloat;
import com.oracle.truffle.llvm.types.memory.LLVMHeap;
import com.oracle.truffle.llvm.types.memory.LLVMMemory;
@NodeChildren(value = {@NodeChild(type = LLVMAddressNode.class, value = "pointerNode")})
public abstract class LLVMStoreNode extends LLVMNode {
@Child protected Node foreignWrite = Message.WRITE.createNode();
protected void doForeignAccess(VirtualFrame frame, LLVMTruffleObject addr, int stride, Object value) {
try {
ForeignAccess.sendWrite(foreignWrite, frame, addr.getObject(), (int) (addr.getOffset() / stride), value);
} catch (UnknownIdentifierException | UnsupportedMessageException | UnsupportedTypeException e) {
throw new IllegalStateException(e);
}
}
protected void doForeignAccess(VirtualFrame frame, TruffleObject addr, Object value) {
try {
ForeignAccess.sendWrite(foreignWrite, frame, addr, 0, value);
} catch (UnknownIdentifierException | UnsupportedMessageException | UnsupportedTypeException e) {
throw new IllegalStateException(e);
}
}
@NodeChild(type = LLVMI1Node.class, value = "valueNode")
public abstract static class LLVMI1StoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, boolean value) {
LLVMMemory.putI1(address, value);
}
}
@NodeChild(type = LLVMI8Node.class, value = "valueNode")
public abstract static class LLVMI8StoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, byte value) {
LLVMMemory.putI8(address, value);
}
@Specialization
public void execute(VirtualFrame frame, LLVMTruffleObject address, byte value) {
doForeignAccess(frame, address, 1, value);
}
@Specialization
public void execute(VirtualFrame frame, TruffleObject address, byte value) {
execute(frame, new LLVMTruffleObject(address), value);
}
}
@NodeChild(type = LLVMI16Node.class, value = "valueNode")
public abstract static class LLVMI16StoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, short value) {
LLVMMemory.putI16(address, value);
}
}
@NodeChild(type = LLVMI32Node.class, value = "valueNode")
public abstract static class LLVMI32StoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, int value) {
LLVMMemory.putI32(address, value);
}
@Specialization
public void execute(VirtualFrame frame, LLVMTruffleObject address, int value) {
doForeignAccess(frame, address, LLVMI32Node.BYTE_SIZE, value);
}
@Specialization
public void execute(VirtualFrame frame, TruffleObject address, int value) {
execute(frame, new LLVMTruffleObject(address), value);
}
}
@NodeChild(type = LLVMI64Node.class, value = "valueNode")
public abstract static class LLVMI64StoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, long value) {
LLVMMemory.putI64(address, value);
}
}
@NodeChild(type = LLVMIVarBitNode.class, value = "valueNode")
public abstract static class LLVMIVarBitStoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, LLVMIVarBit value) {
LLVMMemory.putIVarBit(address, value);
}
}
@NodeChild(type = LLVMFloatNode.class, value = "valueNode")
public abstract static class LLVMFloatStoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, float value) {
LLVMMemory.putFloat(address, value);
}
}
@NodeChild(type = LLVMDoubleNode.class, value = "valueNode")
public abstract static class LLVMDoubleStoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, double value) {
LLVMMemory.putDouble(address, value);
}
@Specialization
public void execute(VirtualFrame frame, LLVMTruffleObject address, double value) {
doForeignAccess(frame, address, LLVMDoubleNode.BYTE_SIZE, value);
}
@Specialization
public void execute(VirtualFrame frame, TruffleObject address, double value) {
doForeignAccess(frame, address, value);
}
}
@NodeChild(type = LLVM80BitFloatNode.class, value = "valueNode")
public abstract static class LLVM80BitFloatStoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, LLVM80BitFloat value) {
LLVMMemory.put80BitFloat(address, value);
}
}
@NodeChild(type = LLVMAddressNode.class, value = "valueNode")
public abstract static class LLVMAddressStoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, LLVMAddress value) {
LLVMMemory.putAddress(address, value);
}
}
@NodeChild(type = LLVMFunctionNode.class, value = "valueNode")
public abstract static class LLVMFunctionStoreNode extends LLVMStoreNode {
@Specialization
public void execute(LLVMAddress address, LLVMFunctionDescriptor function) {
LLVMHeap.putFunctionIndex(address, function.getFunctionIndex());
}
}
@NodeChild(type = LLVMAddressNode.class, value = "valueNode")
@NodeField(type = int.class, name = "structSize")
public abstract static class LLVMStructStoreNode extends LLVMStoreNode {
public abstract int getStructSize();
@Specialization
public void execute(LLVMAddress address, LLVMAddress value) {
LLVMMemory.putStruct(address, value, getStructSize());
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMI1ArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMI1Node[] values;
private final int stride;
public LLVMI1ArrayLiteralNode(LLVMI1Node[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeI8(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
boolean currentValue = values[i].executeI1(frame);
LLVMMemory.putI1(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMI8ArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMI8Node[] values;
private final int stride;
public LLVMI8ArrayLiteralNode(LLVMI8Node[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeI8(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
byte currentValue = values[i].executeI8(frame);
LLVMMemory.putI8(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMI16ArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMI16Node[] values;
private final int stride;
public LLVMI16ArrayLiteralNode(LLVMI16Node[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeI8(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
short currentValue = values[i].executeI16(frame);
LLVMMemory.putI16(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMI32ArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMI32Node[] values;
private final int stride;
public LLVMI32ArrayLiteralNode(LLVMI32Node[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeI32(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
int currentValue = values[i].executeI32(frame);
LLVMMemory.putI32(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMI64ArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMI64Node[] values;
private final int stride;
public LLVMI64ArrayLiteralNode(LLVMI64Node[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeI64(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
long currentValue = values[i].executeI64(frame);
LLVMMemory.putI64(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMFloatArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMFloatNode[] values;
private final int stride;
public LLVMFloatArrayLiteralNode(LLVMFloatNode[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeI64(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
float currentValue = values[i].executeFloat(frame);
LLVMMemory.putFloat(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMDoubleArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMDoubleNode[] values;
private final int stride;
public LLVMDoubleArrayLiteralNode(LLVMDoubleNode[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeDouble(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
double currentValue = values[i].executeDouble(frame);
LLVMMemory.putDouble(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVM80BitFloatArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVM80BitFloatNode[] values;
private final int stride;
public LLVM80BitFloatArrayLiteralNode(LLVM80BitFloatNode[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress write80BitFloat(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
LLVM80BitFloat currentValue = values[i].execute80BitFloat(frame);
LLVMMemory.put80BitFloat(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMAddressArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMAddressNode[] values;
private final int stride;
public LLVMAddressArrayLiteralNode(LLVMAddressNode[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeDouble(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
LLVMAddress currentValue = values[i].executePointee(frame);
LLVMMemory.putAddress(currentAddress, currentValue);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMFunctionArrayLiteralNode extends LLVMAddressNode {
@Children private final LLVMFunctionNode[] values;
private final int stride;
public LLVMFunctionArrayLiteralNode(LLVMFunctionNode[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeDouble(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
LLVMFunctionDescriptor currentValue = values[i].executeFunction(frame);
LLVMHeap.putFunctionIndex(currentAddress, currentValue.getFunctionIndex());
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
@NodeChild(value = "address", type = LLVMAddressNode.class)
public abstract static class LLVMAddressArrayCopyNode extends LLVMAddressNode {
@Children private final LLVMAddressNode[] values;
private final int stride;
public LLVMAddressArrayCopyNode(LLVMAddressNode[] values, int stride) {
this.values = values;
this.stride = stride;
}
@Specialization
@ExplodeLoop
protected LLVMAddress writeDouble(VirtualFrame frame, LLVMAddress addr) {
LLVMAddress currentAddress = addr;
for (int i = 0; i < values.length; i++) {
LLVMAddress currentValue = values[i].executePointee(frame);
LLVMHeap.memCopy(currentAddress, currentValue, stride);
currentAddress = currentAddress.increment(stride);
}
return addr;
}
}
}
|
// 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,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.canvas.core.codegen;
import phasereditor.canvas.core.AssetSpriteModel;
import phasereditor.canvas.core.CanvasModel;
import phasereditor.inspect.core.InspectCore;
import phasereditor.inspect.core.jsdoc.PhaserJSDoc;
/**
* @author arian
*
*/
public class JSSpriteCodeGenerator extends JSLikeBaseSpriteCodeGenerator {
public JSSpriteCodeGenerator(CanvasModel model) {
super(model);
}
@Override
protected void generateHeader() {
String classname = _settings.getClassName();
String baseclass = _settings.getBaseClass();
PhaserJSDoc help = InspectCore.getPhaserHelp();
line("/**");
line(" * " + classname + ".");
line(" * @param {Phaser.Game} aGame " + help.getMethodArgHelp("Phaser.Sprite", "game"));
line(" * @param {number} aX " + help.getMethodArgHelp("Phaser.Sprite", "x"));
line(" * @param {number} aY " + help.getMethodArgHelp("Phaser.Sprite", "y"));
line(" * @param {any} aKey " + help.getMethodArgHelp("Phaser.Sprite", "key"));
line(" * @param {any} aFrame " + help.getMethodArgHelp("Phaser.Sprite", "frame"));
line(" */");
openIndent("function " + classname + "(aGame, aX, aY, aKey, aFrame) {");
AssetSpriteModel<?> sprite = (AssetSpriteModel<?>) _model.getWorld().findFirstSprite();
String key = "null";
String frame = "null";
if (sprite != null) {
TextureArgs info = getTextureArgs(sprite.getAssetKey());
key = info.key;
frame = info.frame;
}
line();
line("var pKey = aKey === undefined? " + key + " : aKey;");
line("var pFrame = aFrame === undefined? " + frame + " : aFrame;");
line();
line(baseclass + ".call(this, aGame, aX, aY, pKey, pFrame);");
trim( ()->{
line();
userCode(_settings.getUserCode().getCreate_before());
} );
}
@Override
protected void generateFooter() {
String classname = _settings.getClassName();
String baseclass = _settings.getBaseClass();
trim( ()->{
line();
userCode(_settings.getUserCode().getCreate_after());
} );
closeIndent("}");
line();
line("/** @type " + baseclass + " */");
line("var " + classname + "_proto = Object.create(" + baseclass + ".prototype);");
line(classname + ".prototype = " + classname + "_proto;");
line(classname + ".prototype.constructor = " + classname + ";");
line();
section(END_GENERATED_CODE, getYouCanInsertCodeHere());
}
}
|
// 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,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.assetpack.core;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IStatus;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import phasereditor.assetpack.core.animations.AnimationModel;
import phasereditor.assetpack.core.animations.AnimationsModel;
/**
* @author arian
*
*/
public class AnimationsAssetModel extends AssetModel {
private String _url;
private String _dataKey;
private List<AnimationAssetElementModel> _animationElements;
public AnimationsAssetModel(JSONObject jsonData, AssetSectionModel section) throws JSONException {
super(jsonData, section);
_url = jsonData.optString("url", null);
_dataKey = jsonData.optString("dataKey", null);
}
protected AnimationsAssetModel(String key, AssetSectionModel section) throws JSONException {
super(key, AssetType.animation, section);
}
@Override
public IFile[] computeUsedFiles() {
return new IFile[] { getFileFromUrl(_url) };
}
@Override
protected void writeParameters(JSONObject obj) {
super.writeParameters(obj);
obj.put("url", _url);
obj.put("dataKey", _dataKey);
}
public String getUrl() {
return _url;
}
public void setUrl(String url) {
_url = url;
firePropertyChange("url");
}
public String getDataKey() {
return _dataKey;
}
public void setDataKey(String dataKey) {
_dataKey = dataKey;
firePropertyChange("dataKey");
}
public IFile getUrlFile() {
return getFileFromUrl(_url);
}
@Override
public void internalBuild(List<IStatus> problems) {
validateUrl(problems, "url", _url);
_animationElements = new ArrayList<>();
IFile file = getUrlFile();
if (file != null) {
try (InputStream input = file.getContents()) {
var jsonData = new JSONObject(new JSONTokener(input));
try {
if (_dataKey != null && _dataKey.trim().length() > 0) {
var keys = _dataKey.split("\\.");
for (var key : keys) {
jsonData = jsonData.getJSONObject(key);
}
}
} catch (Exception e) {
problems.add(errorStatus(
"The data key '" + _dataKey + "' is not found in the animation file '" + _url + "'."));
throw e;
}
var animationsModel = new AnimationsModel(jsonData);
_animationElements = new ArrayList<>();
for (var anim : animationsModel.getAnimations()) {
_animationElements.add(new AnimationAssetElementModel(anim));
}
buildAnimationFrames(problems);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void buildSecondPass(List<IStatus> problems) {
buildAnimationFrames(problems);
}
private void buildAnimationFrames(List<IStatus> problems) {
for (var animElement : _animationElements) {
animElement.build(problems);
}
}
@Override
public List<AnimationAssetElementModel> getSubElements() {
if (_animationElements == null) {
build(new ArrayList<>());
}
return _animationElements;
}
public class AnimationAssetElementModel implements IAssetElementModel {
private AnimationModel _animation;
public AnimationAssetElementModel(AnimationModel animation) {
super();
_animation = animation;
}
public void build(List<IStatus> problems) {
Map<String, IAssetFrameModel> cache = new HashMap<>();
for (var animFrame : _animation.getFrames()) {
var textureKey = animFrame.getTextureKey();
var frameName = animFrame.getFrameName();
var cacheKey = frameName + "@" + textureKey;
var frame = cache.get(cacheKey);
if (frame != null) {
animFrame.setFrame(frame);
break;
}
frame = getPack().findFrame(textureKey, frameName);
if (frame == null) {
var packs = AssetPackCore.getAssetPackModels(getPack().getFile().getProject());
for (var pack : packs) {
frame = pack.findFrame(textureKey, frameName);
}
}
if (frame == null) {
problems.add(errorStatus(
"Cannot find the frame '" + frameName + "' in the texture '" + textureKey + "'."));
} else {
cache.put(cacheKey, frame);
}
animFrame.setFrame(frame);
}
}
public AnimationModel getAnimation() {
return _animation;
}
@Override
public String getName() {
return _animation.getKey();
}
@Override
public AnimationsAssetModel getAsset() {
return AnimationsAssetModel.this;
}
}
@Override
public void fileChanged(IFile file, IFile newFile) {
String url = getUrlFromFile(file);
if (url.equals(_url)) {
_url = getUrlFromFile(newFile);
}
}
}
|
package net.simonvt.widget;
import net.simonvt.menudrawer.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.Scroller;
public class MenuDrawer extends ViewGroup {
/**
* Callback interface for changing state of the drawer.
*/
public interface OnDrawerStateChangeListener {
/**
* Called when the drawer state changes.
*
* @param oldState The old drawer state.
* @param newState The new drawer state.
*/
void onDrawerStateChange(int oldState, int newState);
}
/**
* Tag used when logging.
*/
private static final String TAG = "MenuDrawer";
/**
* Indicates whether debug code should be enabled.
*/
private static final boolean DEBUG = false;
/**
* Key used when saving menu visibility state.
*/
private static final String STATE_MENU_VISIBLE = "net.simonvt.menudrawer.view.menu.menuVisible";
/**
* The time between each frame when animating the drawer.
*/
private static final int ANIMATION_DELAY = 1000 / 60;
/**
* Interpolator used for stretching/retracting the arrow indicator.
*/
private static final Interpolator ARROW_INTERPOLATOR = new AccelerateInterpolator();
/**
* Interpolator used for peeking at the drawer.
*/
private static final Interpolator PEEK_INTERPOLATOR = new PeekInterpolator();
/**
* Interpolator used when animating the drawer open/closed.
*/
private static final Interpolator SMOOTH_INTERPOLATOR = new SmoothInterpolator();
/**
* Default delay from {@link #peekDrawer()} is called until first animation is run.
*/
private static final long DEFAULT_PEEK_START_DELAY = 5000;
/**
* Default delay between each subsequent animation, after {@link #peekDrawer()} has been called.
*/
private static final long DEFAULT_PEEK_DELAY = 10000;
/**
* The duration of the peek animation.
*/
private static final int PEEK_DURATION = 5000;
/**
* The maximum touch area width of the drawer in dp.
*/
private static final int MAX_DRAG_BEZEL_DP = 16;
/**
* The maximum animation duration.
*/
private static final int DURATION_MAX = 600;
/**
* The maximum alpha of the dark menu overlay used for dimming the menu.
*/
private static final int MAX_MENU_OVERLAY_ALPHA = 185;
/**
* Drag mode for sliding only the content view.
*/
public static final int MENU_DRAG_CONTENT = 0;
/**
* Drag mode for sliding the entire window.
*/
public static final int MENU_DRAG_WINDOW = 1;
/**
* Indicates that the drawer is currently closed.
*/
public static final int STATE_CLOSED = 0;
/**
* Indicates that the drawer is currently closing.
*/
public static final int STATE_CLOSING = 1;
/**
* Indicates that the drawer is currently being dragged by the user.
*/
public static final int STATE_DRAGGING = 2;
/**
* Indicates that the drawer is currently opening.
*/
public static final int STATE_OPENING = 4;
/**
* Indicates that the drawer is currently open.
*/
public static final int STATE_OPEN = 8;
/**
* Distance in dp from closed position from where the drawer is considered closed with regards to touch events.
*/
private static final int CLOSE_ENOUGH = 3;
/**
* Indicates whether to use {@link View#setTranslationX(float)} when positioning views.
*/
static final boolean USE_TRANSLATIONS = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
/**
* Drawable used as menu overlay.
*/
private Drawable mMenuOverlay;
/**
* Defines whether the drop shadow is enabled.
*/
private boolean mDropShadowEnabled;
/**
* Drawable used as content drop shadow onto the menu.
*/
private Drawable mDropShadowDrawable;
/**
* The width of the content drop shadow.
*/
private int mDropShadowWidth;
/**
* Arrow bitmap used to indicate the active view.
*/
private Bitmap mArrowBitmap;
/**
* The currently active view.
*/
private View mActiveView;
/**
* Position of the active view. This is compared to View#getTag(R.id.mdActiveViewPosition) when drawing the arrow.
*/
private int mActivePosition;
/**
* Used when reading the position of the active view.
*/
private Rect mActiveRect = new Rect();
/**
* The parent of the menu view.
*/
private FrameLayout mMenuContainer;
/**
* The parent of the content view.
*/
private FrameLayout mContentView;
/**
* The width of the menu.
*/
private int mMenuWidth;
/**
* Indicates whether the menu width has been set in the theme.
*/
private boolean mMenuWidthFromTheme;
/**
* Current left position of the content.
*/
private int mContentLeft;
/**
* Indicates whether the menu is currently visible.
*/
private boolean mMenuVisible;
/**
* The drag mode of the drawer. Can be either {@link #MENU_DRAG_CONTENT} or {@link #MENU_DRAG_WINDOW}.
*/
private int mDragMode;
/**
* The current drawer state.
*
* @see #STATE_CLOSED
* @see #STATE_CLOSING
* @see #STATE_DRAGGING
* @see #STATE_OPENING
* @see #STATE_OPEN
*/
private int mDrawerState = STATE_CLOSED;
/**
* The maximum touch area width of the drawer in px.
*/
private int mMaxDragBezelSize;
/**
* The touch area width of the drawer in px.
*/
private int mDragBezelSize;
/**
* Indicates whether the drawer is currently being dragged.
*/
private boolean mIsDragging;
/**
* Slop before starting a drag.
*/
private final int mTouchSlop;
/**
* The initial X position of a drag.
*/
private float mInitialMotionX;
/**
* The last X position of a drag.
*/
private float mLastMotionX = -1;
/**
* The last Y position of a drag.
*/
private float mLastMotionY = -1;
/**
* Runnable used when animating the drawer open/closed.
*/
private final Runnable mDragRunnable = new Runnable() {
public void run() {
postAnimationInvalidate();
}
};
/**
* Runnable used when the peek animation is running.
*/
private final Runnable mPeekRunnable = new Runnable() {
@Override
public void run() {
peekDrawerInvalidate();
}
};
/**
* Runnable used for first call to {@link #startPeek()} after {@link #peekDrawer()} has been called.
*/
private Runnable mPeekStartRunnable;
/**
* Default delay between each subsequent animation, after {@link #peekDrawer()} has been called.
*/
private long mPeekDelay;
/**
* Scroller used when animating the drawer open/closed.
*/
private Scroller mScroller;
/**
* Scroller used for the peek drawer animation.
*/
private Scroller mPeekScroller;
/**
* Velocity tracker used when animating the drawer open/closed after a drag.
*/
private VelocityTracker mVelocityTracker;
/**
* Maximum velocity allowed when animating the drawer open/closed.
*/
private int mMaxVelocity;
/**
* Listener used to dispatch state change events.
*/
private OnDrawerStateChangeListener mOnDrawerStateChangeListener;
/**
* Indicates whether the menu should be offset when dragging the drawer.
*/
private boolean mOffsetMenu = true;
/**
* Distance in px from closed position from where the drawer is considered closed with regards to touch events.
*/
private int mCloseEnough;
/**
* Indicates whether the current layer type is {@link View#LAYER_TYPE_HARDWARE}.
*/
private boolean mLayerTypeHardware;
public MenuDrawer(Context context) {
this(context, null);
}
public MenuDrawer(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.menuDrawerStyle);
}
public MenuDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setWillNotDraw(false);
setFocusable(false);
TypedArray a =
context.obtainStyledAttributes(attrs, R.styleable.MenuDrawer, defStyle, R.style.Widget_MenuDrawer);
final Drawable contentBackground = a.getDrawable(R.styleable.MenuDrawer_mdContentBackground);
final Drawable menuBackground = a.getDrawable(R.styleable.MenuDrawer_mdMenuBackground);
mMenuWidth = a.getDimensionPixelSize(R.styleable.MenuDrawer_mdMenuWidth, -1);
mMenuWidthFromTheme = mMenuWidth != -1;
final int arrowResId = a.getResourceId(R.styleable.MenuDrawer_mdArrowDrawable, 0);
if (arrowResId != 0) {
mArrowBitmap = BitmapFactory.decodeResource(getResources(), arrowResId);
}
mDropShadowEnabled = a.getBoolean(R.styleable.MenuDrawer_mdDropShadowEnabled, true);
final int dropShadowColor = a.getColor(R.styleable.MenuDrawer_mdDropShadowColor, 0xFF000000);
setDropShadowColor(dropShadowColor);
mDropShadowWidth = a.getDimensionPixelSize(R.styleable.MenuDrawer_mdDropShadowWidth, dpToPx(6));
a.recycle();
mMenuContainer = new BuildLayerFrameLayout(context);
mMenuContainer.setId(R.id.md__menu);
mMenuContainer.setBackgroundDrawable(menuBackground);
addView(mMenuContainer);
mContentView = new NoClickThroughFrameLayout(context);
mContentView.setId(R.id.md__content);
mContentView.setBackgroundDrawable(contentBackground);
addView(mContentView);
mMenuOverlay = new ColorDrawable(0xFF000000);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = configuration.getScaledTouchSlop();
mMaxVelocity = configuration.getScaledMaximumFlingVelocity();
mScroller = new Scroller(context, SMOOTH_INTERPOLATOR);
mPeekScroller = new Scroller(context, PEEK_INTERPOLATOR);
final float density = getResources().getDisplayMetrics().density;
mMaxDragBezelSize = (int) (MAX_DRAG_BEZEL_DP * density + 0.5f);
mCloseEnough = (int) (CLOSE_ENOUGH * density);
}
private int dpToPx(int dp) {
return (int) (getResources().getDisplayMetrics().density * dp + 0.5f);
}
/**
* Toggles the menu open and close.
*/
public void toggleMenu() {
if (mDrawerState == STATE_OPEN || mDrawerState == STATE_OPENING) {
closeMenu();
} else if (mDrawerState == STATE_CLOSED || mDrawerState == STATE_CLOSING) {
openMenu();
}
}
/**
* Opens the menu.
*/
public void openMenu() {
animateContent(true, 0);
}
/**
* Closes the menu.
*/
public void closeMenu() {
animateContent(false, 0);
}
/**
* Indicates whether the menu is currently visible.
*
* @return True if the menu is open, false otherwise.
*/
public boolean isMenuVisible() {
return mMenuVisible;
}
/**
* Set the active view. If the mdArrowDrawable attribute is set, this View will have an arrow drawn next to it.
*
* @param v The active view.
* @param position Optional position, usually used with ListView. v.setTag(R.id.mdActiveViewPosition, position)
* must be called first.
*/
public void setActiveView(View v, int position) {
mActiveView = v;
mActivePosition = position;
invalidate();
}
/**
* Enables or disables offsetting the menu when dragging the drawer.
*
* @param offsetMenu True to offset the menu, false otherwise.
*/
public void setOffsetMenuEnabled(boolean offsetMenu) {
if (offsetMenu != mOffsetMenu) {
mOffsetMenu = offsetMenu;
requestLayout();
invalidate();
}
}
/**
* Indicates whether the menu is being offset when dragging the drawer.
*
* @return True if the menu is being offset, false otherwise.
*/
public boolean getOffsetMenuEnabled() {
return mOffsetMenu;
}
/**
* Returns the state of the drawer. Can be one of {@link #STATE_CLOSED}, {@link #STATE_CLOSING},
* {@link #STATE_DRAGGING}, {@link #STATE_OPENING} or {@link #STATE_OPEN}.
*
* @return The drawers state.
*/
public int getDrawerState() {
return mDrawerState;
}
/**
* Register a callback to be invoked when the drawer state changes.
*
* @param listener The callback that will run.
*/
public void setOnDrawerStateChangeListener(OnDrawerStateChangeListener listener) {
mOnDrawerStateChangeListener = listener;
}
/**
* Defines whether the drop shadow is enabled.
*
* @param enabled Whether the drop shadow is enabled.
*/
public void setDropShadowEnabled(boolean enabled) {
mDropShadowEnabled = enabled;
invalidate();
}
/**
* Sets the color of the drop shadow.
*
* @param color The color of the drop shadow.
*/
public void setDropShadowColor(int color) {
final int endColor = color & 0x00FFFFFF;
mDropShadowDrawable = new GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, new int[] {
color,
endColor,
});
invalidate();
}
/**
* Sets the width of the drop shadow.
*
* @param width The width of the drop shadow in px.
*/
public void setDropShadowWidth(int width) {
mDropShadowWidth = width;
invalidate();
}
/**
* Animates the drawer slightly open until the user opens the drawer.
*/
public void peekDrawer() {
peekDrawer(DEFAULT_PEEK_START_DELAY, DEFAULT_PEEK_DELAY);
}
/**
* Animates the drawer slightly open. If delay is larger than 0, this happens until the user opens the drawer.
*
* @param delay The delay (in milliseconds) between each run of the animation. If 0, this animation is only run
* once.
*/
public void peekDrawer(long delay) {
peekDrawer(DEFAULT_PEEK_START_DELAY, delay);
}
/**
* Animates the drawer slightly open. If delay is larger than 0, this happens until the user opens the drawer.
*
* @param startDelay The delay (in milliseconds) until the animation is first run.
* @param delay The delay (in milliseconds) between each run of the animation. If 0, this animation is only run
* once.
*/
public void peekDrawer(final long startDelay, final long delay) {
if (startDelay < 0) {
throw new IllegalArgumentException("startDelay must be zero or lager.");
}
if (delay < 0) {
throw new IllegalArgumentException("delay must be zero or lager");
}
removeCallbacks(mPeekRunnable);
removeCallbacks(mPeekStartRunnable);
mPeekDelay = delay;
mPeekStartRunnable = new Runnable() {
@Override
public void run() {
startPeek();
}
};
postDelayed(mPeekStartRunnable, startDelay);
}
/**
* Sets the drawer state.
*
* @param state The drawer state. Must be one of {@link #STATE_CLOSED}, {@link #STATE_CLOSING},
* {@link #STATE_DRAGGING}, {@link #STATE_OPENING} or {@link #STATE_OPEN}.
*/
private void setDrawerState(int state) {
if (state != mDrawerState) {
final int oldState = mDrawerState;
mDrawerState = state;
if (mOnDrawerStateChangeListener != null) mOnDrawerStateChangeListener.onDrawerStateChange(oldState, state);
if (DEBUG) logDrawerState(state);
}
}
private void logDrawerState(int state) {
switch (state) {
case STATE_CLOSED:
Log.d(TAG, "[DrawerState] STATE_CLOSED");
break;
case STATE_CLOSING:
Log.d(TAG, "[DrawerState] STATE_CLOSING");
break;
case STATE_DRAGGING:
Log.d(TAG, "[DrawerState] STATE_DRAGGING");
break;
case STATE_OPENING:
Log.d(TAG, "[DrawerState] STATE_OPENING");
break;
case STATE_OPEN:
Log.d(TAG, "[DrawerState] STATE_OPEN");
break;
default:
}
}
/**
* Sets the drawer drag mode. Can be either {@link #MENU_DRAG_CONTENT} or {@link #MENU_DRAG_WINDOW}.
*
* @param dragMode The drag mode.
*/
public void setDragMode(int dragMode) {
mDragMode = dragMode;
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
final int height = getHeight();
final int contentLeft = mContentLeft;
final int dropShadowWidth = mDropShadowWidth;
final float openRatio = ((float) contentLeft) / mMenuWidth;
mMenuOverlay.setBounds(0, 0, contentLeft, height);
mMenuOverlay.setAlpha((int) (MAX_MENU_OVERLAY_ALPHA * (1.f - openRatio)));
mMenuOverlay.draw(canvas);
if (mDropShadowEnabled) {
mDropShadowDrawable.setBounds(contentLeft - dropShadowWidth, 0, contentLeft, height);
mDropShadowDrawable.draw(canvas);
}
if (mArrowBitmap != null) drawArrow(canvas, contentLeft, openRatio);
}
/**
* Draws the arrow indicating the currently active view.
*
* @param canvas The canvas on which to draw.
* @param openRatio [0..1] value indicating how open the drawer is.
*/
private void drawArrow(Canvas canvas, int contentLeft, float openRatio) {
if (mActiveView != null && mActiveView.getParent() != null) {
Integer position = (Integer) mActiveView.getTag(R.id.mdActiveViewPosition);
final int pos = position == null ? 0 : position;
if (pos == mActivePosition) {
mActiveView.getDrawingRect(mActiveRect);
offsetDescendantRectToMyCoords(mActiveView, mActiveRect);
final float interpolatedRatio = 1.f - ARROW_INTERPOLATOR.getInterpolation((1.f - openRatio));
final int interpolatedArrowWidth = (int) (mArrowBitmap.getWidth() * interpolatedRatio);
final int top = mActiveRect.top + ((mActiveRect.height() - mArrowBitmap.getHeight()) / 2);
final int right = contentLeft;
final int left = right - interpolatedArrowWidth;
canvas.save();
canvas.clipRect(left, 0, right, getHeight());
canvas.drawBitmap(mArrowBitmap, left, top, null);
canvas.restore();
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = r - l;
final int height = b - t;
final int contentLeft = mContentLeft;
mMenuContainer.layout(0, 0, mMenuWidth, height);
offsetMenu(contentLeft);
if (USE_TRANSLATIONS) {
mContentView.layout(0, 0, width, height);
} else {
mContentView.layout(contentLeft, 0, width + contentLeft, height);
}
}
/**
* Offsets the menu relative to its original position based on the left position of the content.
*
* @param contentLeft The left position of the content.
*/
private void offsetMenu(float contentLeft) {
if (mOffsetMenu && mMenuWidth != 0) {
final int menuWidth = mMenuWidth;
final float openRatio = (menuWidth - contentLeft) / menuWidth;
if (USE_TRANSLATIONS) {
final int menuLeft = (int) (0.25f * (-openRatio * menuWidth));
mMenuContainer.setTranslationX(menuLeft);
} else {
final int oldMenuLeft = mMenuContainer.getLeft();
final int offset = (int) (0.25f * (-openRatio * menuWidth)) - oldMenuLeft;
mMenuContainer.offsetLeftAndRight(offset);
}
}
}
/**
* Set the left position of the content view.
*
* @param contentLeft The left position of the content view.
*/
private void setContentLeft(int contentLeft) {
if (contentLeft != mContentLeft) {
if (USE_TRANSLATIONS) {
mContentView.setTranslationX(contentLeft);
offsetMenu(contentLeft);
invalidate();
} else {
mContentView.offsetLeftAndRight(contentLeft - mContentView.getLeft());
offsetMenu(contentLeft);
invalidate();
}
mContentLeft = contentLeft;
mMenuVisible = contentLeft != 0;
}
}
/**
* If possible, set the layer type to {@link View#LAYER_TYPE_HARDWARE}.
*/
private void startLayerTranslation() {
if (USE_TRANSLATIONS && !mLayerTypeHardware) {
mLayerTypeHardware = true;
mContentView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mMenuContainer.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
}
/**
* If the current layer type is {@link View#LAYER_TYPE_HARDWARE}, this will set it to @link View#LAYER_TYPE_NONE}.
*/
private void stopLayerTranslation() {
if (mLayerTypeHardware) {
mLayerTypeHardware = false;
mContentView.setLayerType(View.LAYER_TYPE_NONE, null);
mMenuContainer.setLayerType(View.LAYER_TYPE_NONE, null);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Must measure with an exact size");
}
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = MeasureSpec.getSize(heightMeasureSpec);
if (!mMenuWidthFromTheme) mMenuWidth = (int) (width * 0.8f);
if (mContentLeft == -1) setContentLeft(mMenuWidth);
final int menuWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, mMenuWidth);
final int menuHeightMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, height);
mMenuContainer.measure(menuWidthMeasureSpec, menuHeightMeasureSpec);
final int contentWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, width);
final int contentHeightMeasureSpec = getChildMeasureSpec(widthMeasureSpec, 0, height);
mContentView.measure(contentWidthMeasureSpec, contentHeightMeasureSpec);
setMeasuredDimension(width, height);
final int measuredWidth = getMeasuredWidth();
mDragBezelSize = Math.min(measuredWidth / 10, mMaxDragBezelSize);
}
@Override
protected boolean fitSystemWindows(Rect insets) {
if (mDragMode == MENU_DRAG_WINDOW) {
mMenuContainer.setPadding(0, insets.top, 0, 0);
}
return super.fitSystemWindows(insets);
}
/**
* Called when a drag has been ended.
*/
private void endDrag() {
mIsDragging = false;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
/**
* Stops ongoing animation of the drawer.
*/
private void stopAnimation() {
removeCallbacks(mDragRunnable);
mScroller.abortAnimation();
stopLayerTranslation();
}
/**
* Called when a drawer animation has successfully completed.
*/
private void completeAnimation() {
mScroller.abortAnimation();
final int finalX = mScroller.getFinalX();
setContentLeft(finalX);
setDrawerState(finalX == 0 ? STATE_CLOSED : STATE_OPEN);
stopLayerTranslation();
}
/**
* Animates the drawer open or closed.
*
* @param open Indicates whether the drawer should be opened.
* @param velocity Optional velocity if called by releasing a drag event.
*/
private void animateContent(boolean open, int velocity) {
endDrag();
final int startX = mContentLeft;
int dx = open ? mMenuWidth - startX : startX;
if (dx == 0) {
setDrawerState(startX == 0 ? STATE_CLOSED : STATE_OPEN);
stopLayerTranslation();
return;
}
int duration;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));
} else {
duration = (int) (600.f * ((float) dx / mMenuWidth));
}
duration = Math.min(duration, DURATION_MAX);
if (open) {
setDrawerState(STATE_OPENING);
mScroller.startScroll(startX, 0, dx, 0, duration);
} else {
setDrawerState(STATE_CLOSING);
mScroller.startScroll(startX, 0, -startX, 0, duration);
}
startLayerTranslation();
postAnimationInvalidate();
}
/**
* Callback when each frame in the drawer animation should be drawn.
*/
private void postAnimationInvalidate() {
if (mScroller.computeScrollOffset()) {
final int oldX = mContentLeft;
final int x = mScroller.getCurrX();
if (x != oldX) setContentLeft(x);
if (x != mScroller.getFinalX()) {
postDelayed(mDragRunnable, ANIMATION_DELAY);
return;
}
}
completeAnimation();
}
/**
* Starts peek drawer animation.
*/
private void startPeek() {
final int menuWidth = mMenuWidth;
final int dx = menuWidth / 3;
mPeekScroller.startScroll(0, 0, dx, 0, PEEK_DURATION);
startLayerTranslation();
peekDrawerInvalidate();
}
/**
* Callback when each frame in the peek drawer animation should be drawn.
*/
private void peekDrawerInvalidate() {
if (mPeekScroller.computeScrollOffset()) {
final int oldX = mContentLeft;
final int x = mPeekScroller.getCurrX();
if (x != oldX) setContentLeft(x);
if (!mPeekScroller.isFinished()) {
postDelayed(mPeekRunnable, ANIMATION_DELAY);
return;
} else {
mPeekStartRunnable = new Runnable() {
@Override
public void run() {
startPeek();
}
};
postDelayed(mPeekStartRunnable, mPeekDelay);
}
}
completePeek();
}
/**
* Called when the peek drawer animation has successfully completed.
*/
private void completePeek() {
mPeekScroller.abortAnimation();
setContentLeft(0);
setDrawerState(STATE_CLOSED);
stopLayerTranslation();
}
/**
* Stops ongoing peek drawer animation.
*/
private void stopPeek() {
removeCallbacks(mPeekStartRunnable);
removeCallbacks(mPeekRunnable);
stopLayerTranslation();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction() & MotionEvent.ACTION_MASK;
if (action == MotionEvent.ACTION_DOWN && mMenuVisible && mContentLeft <= mCloseEnough) {
setContentLeft(0);
stopAnimation();
stopPeek();
setDrawerState(STATE_CLOSED);
}
// Always intercept events over the content while menu is visible.
if (mMenuVisible && ev.getX() > mContentLeft) return true;
if (action != MotionEvent.ACTION_DOWN) {
if (mIsDragging) return true;
}
switch (action) {
case MotionEvent.ACTION_DOWN: {
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = ev.getY();
final int contentLeft = mContentLeft;
final boolean allowDrag = (!mMenuVisible && mInitialMotionX < mDragBezelSize) ||
(mMenuVisible && mInitialMotionX > contentLeft);
if (allowDrag) {
setDrawerState(mMenuVisible ? STATE_OPEN : STATE_CLOSED);
stopAnimation();
stopPeek();
mIsDragging = false;
}
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
final float y = ev.getY();
final float yDiff = Math.abs(y - mLastMotionY);
final int contentLeft = mContentLeft;
if (xDiff > mTouchSlop && xDiff > yDiff) {
final boolean allowDrag = (!mMenuVisible && mInitialMotionX < mDragBezelSize)
|| (mMenuVisible && mInitialMotionX >= contentLeft);
if (allowDrag) {
setDrawerState(STATE_DRAGGING);
mIsDragging = true;
mLastMotionX = x;
mLastMotionY = y;
}
}
break;
}
/**
* If you click really fast, an up or cancel event is delivered here.
* Just snap content to whatever is closest.
* */
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
final int contentLeft = mContentLeft;
animateContent(contentLeft > mMenuWidth / 2, 0);
break;
}
}
if (mVelocityTracker == null) mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(ev);
return mIsDragging;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction() & MotionEvent.ACTION_MASK;
if (mVelocityTracker == null) mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
mLastMotionX = mInitialMotionX = ev.getX();
final int contentLeft = mContentLeft;
final boolean allowDrag = (!mMenuVisible && mInitialMotionX <= mDragBezelSize)
|| (mMenuVisible && mInitialMotionX >= contentLeft);
if (allowDrag) {
stopAnimation();
stopPeek();
setDrawerState(STATE_DRAGGING);
mIsDragging = true;
startLayerTranslation();
}
break;
}
case MotionEvent.ACTION_MOVE: {
final int contentLeft = mContentLeft;
if (!mIsDragging) {
final float x = ev.getX();
final float xDiff = Math.abs(x - mLastMotionX);
final float y = ev.getY();
final float yDiff = Math.abs(y - mLastMotionY);
if (xDiff > mTouchSlop && xDiff > yDiff) {
final boolean allowDrag = (!mMenuVisible && mInitialMotionX <= mDragBezelSize)
|| (mMenuVisible && mInitialMotionX >= contentLeft);
if (allowDrag) {
setDrawerState(STATE_DRAGGING);
mIsDragging = true;
mLastMotionX = x - mInitialMotionX > 0
? mInitialMotionX + mTouchSlop
: mInitialMotionX - mTouchSlop;
}
}
}
if (mIsDragging) {
startLayerTranslation();
final float x = ev.getX();
final float dx = x - mLastMotionX;
mLastMotionX = x;
setContentLeft(Math.min(Math.max(contentLeft + (int) dx, 0), mMenuWidth));
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
final int contentLeft = mContentLeft;
if (mIsDragging) {
mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity);
final int initialVelocity = (int) mVelocityTracker.getXVelocity();
mLastMotionX = ev.getX();
animateContent(mVelocityTracker.getXVelocity() > 0, initialVelocity);
// Close the menu when content is clicked while the menu is visible.
} else if (mMenuVisible && ev.getX() > contentLeft) {
closeMenu();
}
break;
}
}
return true;
}
/**
* Saves the state of the drawer.
*
* @return Returns a Parcelable containing the drawer state.
*/
public Parcelable saveState() {
Bundle state = new Bundle();
final boolean menuVisible = mDrawerState == STATE_OPEN || mDrawerState == STATE_OPENING;
state.putBoolean(STATE_MENU_VISIBLE, menuVisible);
return state;
}
/**
* Restores the state of the drawer.
*
* @param in A parcelable containing the drawer state.
*/
public void restoreState(Parcelable in) {
Bundle state = (Bundle) in;
final boolean menuOpen = state.getBoolean(STATE_MENU_VISIBLE);
setContentLeft(menuOpen ? mMenuWidth : 0);
mDrawerState = menuOpen ? STATE_OPEN : STATE_CLOSED;
}
}
|
package controllers;
import com.google.common.base.Joiner;
import com.sun.syndication.io.FeedException;
import models.Game;
import models.Player;
import models.Timeline;
import models.Versus;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ApplicationController extends Controller {
public static Result index() {
return ok(index.render(new Timeline()));
}
private static void recompute() {
List<Game> all = Game.findAll();
for (Game game : all) {
game.recomputeRankings();
}
}
private static void reverseVersus() {
Map<Player, List<Player>> counts = new HashMap<Player, List<Player>>();
List<Player> all = Player.findAll();
for (Player player1 : all) {
Versus bestVersus = player1.getBestVersus();
Player player2 = bestVersus.player2;
List<Player> opponents = counts.get(player2);
if (opponents == null) {
opponents = new ArrayList<Player>();
counts.put(player2, opponents);
}
if (!player1.scores.isEmpty()) {
opponents.add(player1);
}
}
List<Map.Entry<Player, List<Player>>> list = new ArrayList<Map.Entry<Player, List<Player>>>(counts.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Player, List<Player>>>() {
@Override
public int compare(Map.Entry<Player, List<Player>> o1, Map.Entry<Player, List<Player>> o2) {
return o2.getValue().size() - o1.getValue().size();
}
});
for (Map.Entry<Player, List<Player>> playerIntegerEntry : list) {
System.err.println(playerIntegerEntry.getKey().name + " -> " + playerIntegerEntry.getValue().size() + " " + Joiner.on(", ").join(playerIntegerEntry.getValue()));
}
}
public static Result indexRss() throws IOException, FeedException {
return ok(new Timeline().rss());
}
}
|
package com.astoev.cave.survey.service.bluetooth.device.ble.mileseey;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothGattCharacteristic;
import android.os.Build;
import android.util.Log;
import com.astoev.cave.survey.Constants;
import com.astoev.cave.survey.exception.DataException;
import com.astoev.cave.survey.service.bluetooth.Measure;
import com.astoev.cave.survey.service.bluetooth.device.ble.AbstractBluetoothLEDevice;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public abstract class AbstractMileseeyBluetoothLeDevice extends AbstractBluetoothLEDevice {
protected static final UUID SERVICE_UUID = UUID.fromString("0000FFB0-0000-1000-8000-00805f9b34fb");
protected static final UUID DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
// private static final UUID CHAR_CMD_UUID = UUID.fromString("0000FFB1-0000-1000-8000-00805f9b34fb");
public static final UUID CHAR_DATA_UUID = UUID.fromString("0000FFB2-0000-1000-8000-00805f9b34fb");
@Override
public boolean isMeasureSupported(Constants.MeasureTypes aMeasureType) {
// distance and inclination supported
return Constants.MeasureTypes.distance.equals(aMeasureType);
}
@Override
public List<UUID> getServices() {
return Arrays.asList(SERVICE_UUID);
}
@Override
public List<UUID> getCharacteristics() {
return Arrays.asList(CHAR_DATA_UUID);
}
@Override
public List<UUID> getDescriptors() {
return Arrays.asList(DESCRIPTOR_UUID);
}
@Override
public UUID getService(Constants.MeasureTypes aMeasureType) {
switch (aMeasureType) {
case distance:
return SERVICE_UUID;
default:
return null;
}
}
@Override
public UUID getCharacteristic(Constants.MeasureTypes aMeasureType) {
switch (aMeasureType) {
case distance:
return CHAR_DATA_UUID;
default:
return null;
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public Measure characteristicToMeasure(BluetoothGattCharacteristic aCharacteristic, List<Constants.MeasureTypes> aMeasureTypes) throws DataException {
if (CHAR_DATA_UUID.equals(aCharacteristic.getUuid())) {
byte [] data = aCharacteristic.getValue();
String dataString = new String(data).trim();
Log.i(Constants.LOG_TAG_BT, "Got distance " + dataString);
if (!dataString.endsWith("m")) {
Log.i(Constants.LOG_TAG_BT, "Please measure in meters!");
throw new DataException("Please use meters");
}
String valueString = dataString.substring(0, dataString.length() - 1);
Float distance = Float.valueOf(valueString);
Measure measure = new Measure();
measure.setMeasureUnit(Constants.MeasureUnits.meters);
measure.setMeasureType(Constants.MeasureTypes.distance);
measure.setValue(distance);
return measure;
} else {
Log.d(Constants.LOG_TAG_BT, "Unnone characteristic received " + aCharacteristic.getUuid());
}
return null;
}
}
|
package org.wyona.yanel.impl.resources.yaneluser;
import org.wyona.yanel.core.ResourceConfiguration;
import org.wyona.yanel.core.util.MailUtil;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.User;
import org.wyona.yanel.servlet.YanelServlet;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.wyona.commons.xml.XMLHelper;
/**
* A resource to edit/update the profile of a user
*/
public class EditYanelUserProfileResource extends BasicXMLResource {
private static Logger log = LogManager.getLogger(EditYanelUserProfileResource.class);
private String transformerParameterName;
private String transformerParameterValue;
private static final String USER_PROP_NAME = "user";
/*
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
protected InputStream getContentXML(String viewId) throws Exception {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
String oldPassword = getEnvironment().getRequest().getParameter("oldPassword");
if (oldPassword != null) {
String newPassword = getEnvironment().getRequest().getParameter("newPassword");
String newPasswordConfirmed = getEnvironment().getRequest().getParameter("newPasswordConfirmation");
updatePassword(oldPassword, newPassword, newPasswordConfirmed);
}
String email = getEnvironment().getRequest().getParameter("email");
boolean emailUpdated = false;
if (email != null) {
emailUpdated = updateProfile(email);
log.info("Email '" + email + "' has been updated: " + emailUpdated);
}
try {
return getXMLAsStream(emailUpdated);
} catch(Exception e) {
log.error(e, e);
return null;
}
}
/**
* Get user profile as XML as stream
* @param emailUpdated Flag whether email got updated successfully
*/
private java.io.InputStream getXMLAsStream(boolean emailUpdated) throws Exception {
String userId = getUserId();
if (userId != null) {
Document doc = getUserProfile(userId, emailUpdated);
return XMLHelper.getInputStream(doc, false, true, null);
} else {
return new java.io.StringBufferInputStream("<no-user-id/>");
}
}
/**
* Get user profile as DOM XML
* @param userID ID of user
* @param emailUpdated Flag whether email got updated successfully
*/
protected Document getUserProfile(String userId, boolean emailUpdated) throws Exception {
User user = realm.getIdentityManager().getUserManager().getUser(userId);
Document doc = XMLHelper.createDocument(null, "user");
Element rootEl = doc.getDocumentElement();
rootEl.setAttribute("id", userId);
rootEl.setAttribute("email", user.getEmail());
rootEl.setAttribute("lamguage", user.getLanguage()); // DEPRECATED
rootEl.setAttribute("language", user.getLanguage());
if (emailUpdated) {
rootEl.setAttribute("email-saved-successfully", "true");
}
Element nameEl = doc.createElement("name");
nameEl.setTextContent(user.getName());
rootEl.appendChild(nameEl);
Element realmEl = doc.createElement("realm");
rootEl.appendChild(realmEl);
String[] languages = getRealm().getLanguages();
if (languages != null && languages.length > 0) {
Element supportedLanguagesEl = doc.createElement("languages");
// TODO: Set default language
String defaultLanguage = getRealm().getDefaultLanguage();
realmEl.appendChild(supportedLanguagesEl);
for (int i = 0; i < languages.length; i++) {
Element languageEl = doc.createElement("language");
languageEl.setTextContent(languages[i]);
supportedLanguagesEl.appendChild(languageEl);
}
}
Element expirationDateEl = doc.createElement("expiration-date");
expirationDateEl.setTextContent("" + user.getExpirationDate());
rootEl.appendChild(expirationDateEl);
Element descEl = doc.createElement("description");
descEl.setTextContent("" + user.getDescription());
rootEl.appendChild(descEl);
org.wyona.security.core.api.Group[] groups = user.getGroups();
if (groups != null && groups.length > 0) {
Element groupsEl = doc.createElement("groups");
rootEl.appendChild(groupsEl);
for (int i = 0; i < groups.length; i++) {
Element groupEl = doc.createElement("group");
groupEl.setAttribute("id", groups[i].getID());
groupsEl.appendChild(groupEl);
}
}
String[] aliases = user.getAliases();
if (aliases != null && aliases.length > 0) {
Element aliasesEl = (Element) rootEl.appendChild(doc.createElement("aliases"));
for (int i = 0; i < aliases.length; i++) {
Element aliasEl = (Element) aliasesEl.appendChild(doc.createElement("alias"));
aliasEl.appendChild(doc.createTextNode(aliases[i]));
}
} else {
rootEl.appendChild(doc.createElement("no-aliases"));
}
org.wyona.security.core.UserHistory history = user.getHistory();
if (history != null) {
java.util.List<org.wyona.security.core.UserHistory.HistoryEntry> entries = history.getHistory();
if (entries != null) {
for (org.wyona.security.core.UserHistory.HistoryEntry entry: entries) {
Element historyEl = (Element) rootEl.appendChild(doc.createElement("history"));
Element eventEl = (Element) historyEl.appendChild(doc.createElement("event"));
eventEl.setAttribute("usecase", entry.getUsecase());
eventEl.setAttribute("description", entry.getDescription());
eventEl.setAttribute("date", "" + entry.getDate());
}
}
}
return doc;
}
/**
* Get user ID, whereas check various options, such as 1) query string, 2) resource configuration, 3) URL and 4) session
*/
protected String getUserId() throws Exception {
String userId = null;
userId = getEnvironment().getRequest().getParameter("id");
if (userId != null) {
return userId;
/*
if (getRealm().getPolicyManager().authorize("/yanel/users/" + userId + ".html", getEnvironment().getIdentity(), new org.wyona.security.core.api.Usecase("view"))) { // INFO: Because the policymanager has no mean to check (or interpret) query strings we need to recheck programmatically
return userId;
} else {
//throw new Exception("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!");
log.warn("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!");
}
*/
} else {
log.debug("User ID is not part of query string.");
}
userId = getResourceConfigProperty(USER_PROP_NAME);
if (userId != null) {
return userId;
} else {
log.debug("User ID is not configured inside resource configuration.");
}
userId = getPath().substring(getPath().lastIndexOf("/") + 1, getPath().lastIndexOf(".html"));
if (userId != null && getRealm().getIdentityManager().getUserManager().existsUser(userId)) {
return userId;
} else {
log.debug("Could not retrieve user ID from URL.");
}
userId = getEnvironment().getIdentity().getUsername();
if (userId != null) {
return userId;
} else {
log.warn("User does not seem to be signed in!");
}
throw new Exception("Cannot retrieve user ID!");
}
/**
* Change user password
* @param oldPassword Existing current password
*/
protected void updatePassword(String oldPassword, String newPassword, String newPasswordConfirmed) throws Exception {
String userId = getUserId();
if (!getRealm().getIdentityManager().getUserManager().getUser(userId).authenticate(oldPassword)) {
setTransformerParameter("error", "Authentication of user '" +userId + "' failed!");
log.error("Authentication of user '" + userId + "' failed!");
return;
}
if (newPassword != null && !newPassword.equals("")) {
if (newPassword.equals(newPasswordConfirmed)) {
User user = getRealm().getIdentityManager().getUserManager().getUser(userId);
user.setPassword(newPassword);
user.save();
setTransformerParameter("success", "Password updated successfully");
} else {
setTransformerParameter("error", "New password and its confirmation do not match!");
}
} else {
setTransformerParameter("error", "No new password was specified!");
}
}
/**
* Update the email address (and possibly also the alias) inside user profile
* @param email New email address of user (and possibly also alias)
* @return true if update was successful and false otherwise
*/
protected boolean updateProfile(String email) throws Exception {
if (email == null || ("").equals(email)) {
setTransformerParameter("error", "emailNotSet");
log.warn("No email (or empty email) specified, hence do not update email address!");
return false;
} else if (!validateEmail(email)) {
setTransformerParameter("error", "emailNotValid");
log.warn("Email '" + email + "' is not valid!");
return false;
} else {
try {
String userId = getUserId();
org.wyona.security.core.api.UserManager userManager = realm.getIdentityManager().getUserManager();
User user = userManager.getUser(userId);
user.setName(getEnvironment().getRequest().getParameter("userName"));
user.setLanguage(getEnvironment().getRequest().getParameter("user-profile-language"));
user.save();
updateSession(user);
String previousEmailAddress = user.getEmail();
if (!previousEmailAddress.equals(email)) {
user.setEmail(email);
user.save();
if (userManager.existsAlias(previousEmailAddress)) {
if (!userManager.existsAlias(email)) {
userManager.createAlias(email, userId);
} else {
if (hasAlias(user, email)) {
log.warn("DEBUG: User '" + userId + "' already has alias '" + email + "'.");
} else {
throw new Exception("Alias '" + email + "' already exists, but is not associated with user '" + userId + "'!");
}
}
if (hasAlias(user, previousEmailAddress)) {
userManager.removeAlias(previousEmailAddress);
log.warn("Previous alias '" + previousEmailAddress + "' removed, which means user needs to use new email '" + email + "' to login.");
sendNotification(previousEmailAddress, email);
// TODO/TBD: Logout user and tell user why he/she was signed out
}
} else {
log.warn("Previous email '" + previousEmailAddress + "' was not used as alias, hence we also use new email '" + email + "' not as alias.");
}
} else {
log.warn("DEBUG: Current email and new email are the same.");
if (!userManager.existsAlias(email)) {
log.warn("Email '" + email + "' is not used as alias yet!");
}
}
setTransformerParameter("success", "E-Mail (and alias) updated successfully");
return true;
} catch (Exception e) {
log.error(e, e);
setTransformerParameter("error", e.getMessage());
return false;
}
}
}
/**
* Send notifications to previous and new emails that login alias has changed
*/
private void sendNotification(String previousEmail, String newEmail) throws Exception {
String from = getResourceConfigProperty("fromEmail");
if (from != null) {
String subject = "[" + getRealm().getName() + "] Username changed";
String body = "Please note that you must use '" + newEmail + "' instead '" + previousEmail + "' to login.";
try {
MailUtil.send(from, previousEmail, subject, body);
} catch(Exception e) {
log.error(e, e);
}
try {
MailUtil.send(from, newEmail, subject, body);
} catch(Exception e) {
log.error(e, e);
}
} else {
log.warn("No 'from' email address inside resource configuration set, hence no notifications about changed username will be sent!");
}
}
/**
* Update identity attached to session
*/
private void updateSession(User user) throws Exception {
YanelServlet.setIdentity(new Identity(user, user.getEmail()), getEnvironment().getRequest().getSession(true), getRealm());
}
/**
* Check whether user has a specific alias
* @return true when user has a specific alias
*/
private boolean hasAlias(User user, String alias) throws Exception {
String[] aliases = user.getAliases();
for (int i = 0; i < aliases.length; i++) {
if (aliases[i].equals(alias)) {
return true;
}
}
return false;
}
private void setTransformerParameter(String name, String value) {
transformerParameterName = name;
transformerParameterValue = value;
}
/**
* @see org.wyona.yanel.impl.resources.BasicXMLResource#passTransformerParameters(Transformer)
*/
@Override
protected void passTransformerParameters(javax.xml.transform.Transformer transformer) throws Exception {
super.passTransformerParameters(transformer);
try {
if (transformerParameterName != null && transformerParameterValue != null) {
transformer.setParameter(transformerParameterName, transformerParameterValue);
transformerParameterName = null;
transformerParameterValue = null;
}
} catch (Exception e) {
log.error(e, e);
}
}
/**
* This method checks if the specified email is valid against a regex
*
* @param email
* @return true if email is valid
*/
private boolean validateEmail(String email) {
String emailRegEx = "(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*";
Pattern pattern = Pattern.compile(emailRegEx);
Matcher matcher = pattern.matcher(email);
return matcher.find();
}
}
|
package org.sagebionetworks.web.unitclient.widget.table.modal.download;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import org.sagebionetworks.repo.model.table.CsvTableDescriptor;
import org.sagebionetworks.repo.model.table.DownloadFromTableRequest;
import org.sagebionetworks.repo.model.table.DownloadFromTableResult;
import org.sagebionetworks.repo.model.table.FacetColumnRequest;
import org.sagebionetworks.web.client.widget.table.modal.download.CreateDownloadPageImpl;
import org.sagebionetworks.web.client.widget.table.modal.download.CreateDownloadPageView;
import org.sagebionetworks.web.client.widget.table.modal.download.DownloadFilePage;
import org.sagebionetworks.web.client.widget.table.modal.download.FileType;
import org.sagebionetworks.web.client.widget.table.modal.wizard.ModalPage.ModalPresenter;
import org.sagebionetworks.web.unitclient.widget.asynch.JobTrackingWidgetStub;
public class CreateDownloadPageImplTest {
CreateDownloadPageView mockView;
JobTrackingWidgetStub jobTrackingWidgetStub;
DownloadFilePage mockNextPage;
ModalPresenter mockModalPresenter;
CreateDownloadPageImpl page;
String sql;
String tableId;
List<FacetColumnRequest> selectedFacets;
@Mock
FacetColumnRequest mockFacetColumnRequest;
@Before
public void before(){
MockitoAnnotations.initMocks(this);
mockView = Mockito.mock(CreateDownloadPageView.class);
jobTrackingWidgetStub = new JobTrackingWidgetStub();
mockNextPage = Mockito.mock(DownloadFilePage.class);
mockModalPresenter = Mockito.mock(ModalPresenter.class);
selectedFacets = new ArrayList<FacetColumnRequest>();
page = new CreateDownloadPageImpl(mockView, jobTrackingWidgetStub, mockNextPage);
tableId = "syn123";
sql = "select * from " + tableId;
page.configure(sql, tableId, selectedFacets);
}
@Test
public void testSetModalPresenter(){
// This is the main entry to the page
page.setModalPresenter(mockModalPresenter);
verify(mockModalPresenter).setPrimaryButtonText(CreateDownloadPageImpl.NEXT);
verify(mockView).setFileType(FileType.CSV);
verify(mockView).setIncludeHeaders(true);
verify(mockView).setIncludeRowMetadata(true);
verify(mockView).setTrackerVisible(false);
}
@Test
public void testgetDownloadFromTableRequest(){
selectedFacets.add(mockFacetColumnRequest);
page.setModalPresenter(mockModalPresenter);
DownloadFromTableRequest expected = new DownloadFromTableRequest();
CsvTableDescriptor descriptor = new CsvTableDescriptor();
descriptor.setSeparator("\t");
expected.setCsvTableDescriptor(descriptor);
expected.setIncludeRowIdAndRowVersion(false);
expected.setSql(sql);
expected.setWriteHeader(true);
expected.setSelectedFacets(selectedFacets);
when(mockView.getFileType()).thenReturn(FileType.TSV);
when(mockView.getIncludeHeaders()).thenReturn(true);
when(mockView.getIncludeRowMetadata()).thenReturn(false);
DownloadFromTableRequest request = page.getDownloadFromTableRequest();
assertEquals(expected, request);
}
@Test
public void testOnPrimarySuccess(){
page.setModalPresenter(mockModalPresenter);
when(mockView.getFileType()).thenReturn(FileType.TSV);
when(mockView.getIncludeHeaders()).thenReturn(true);
when(mockView.getIncludeRowMetadata()).thenReturn(false);
String fileHandle = "45678";
DownloadFromTableResult results = new DownloadFromTableResult();
results.setResultsFileHandleId(fileHandle);
jobTrackingWidgetStub.setResponse(results);
page.onPrimary();
verify(mockModalPresenter).setLoading(true);
verify(mockView).setTrackerVisible(true);
verify(mockNextPage).configure(fileHandle);
verify(mockModalPresenter).setNextActivePage(mockNextPage);
}
@Test
public void testOnPrimaryCancel(){
page.setModalPresenter(mockModalPresenter);
when(mockView.getFileType()).thenReturn(FileType.TSV);
when(mockView.getIncludeHeaders()).thenReturn(true);
when(mockView.getIncludeRowMetadata()).thenReturn(false);
String fileHandle = "45678";
DownloadFromTableResult results = new DownloadFromTableResult();
results.setResultsFileHandleId(fileHandle);
jobTrackingWidgetStub.setOnCancel(true);
page.onPrimary();
verify(mockModalPresenter).setLoading(true);
verify(mockView).setTrackerVisible(true);
verify(mockNextPage, never()).configure(fileHandle);
verify(mockModalPresenter).onCancel();
}
@Test
public void testOnPrimaryFailure(){
page.setModalPresenter(mockModalPresenter);
when(mockView.getFileType()).thenReturn(FileType.TSV);
when(mockView.getIncludeHeaders()).thenReturn(true);
when(mockView.getIncludeRowMetadata()).thenReturn(false);
String fileHandle = "45678";
DownloadFromTableResult results = new DownloadFromTableResult();
results.setResultsFileHandleId(fileHandle);
String error = "failure";
jobTrackingWidgetStub.setError(new Throwable(error));
page.onPrimary();
verify(mockModalPresenter).setLoading(true);
verify(mockView).setTrackerVisible(true);
verify(mockNextPage, never()).configure(fileHandle);
verify(mockModalPresenter).setErrorMessage(error);
}
}
|
package org.apache.derby.impl.sql.execute.operations;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import com.splicemachine.derby.test.framework.SpliceDataWatcher;
import com.splicemachine.derby.test.framework.SpliceSchemaWatcher;
import com.splicemachine.derby.test.framework.SpliceTableWatcher;
import com.splicemachine.derby.test.framework.SpliceUnitTest;
import com.splicemachine.derby.test.framework.SpliceWatcher;
import com.splicemachine.homeless.TestUtils;
public class GroupedAggregateOperationIT extends SpliceUnitTest {
public static final String CLASS_NAME = GroupedAggregateOperationIT.class.getSimpleName().toUpperCase();
public static final SpliceWatcher spliceClassWatcher = new SpliceWatcher();
public static final SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(CLASS_NAME);
public static final SpliceTableWatcher spliceTableWatcher = new SpliceTableWatcher("OMS_LOG",CLASS_NAME,"(swh_date date, i integer)");
public static final SpliceTableWatcher spliceTableWatcher2 = new SpliceTableWatcher("T8",CLASS_NAME,"(c1 int, c2 int)");
private static Logger LOG = Logger.getLogger(GroupedAggregateOperationIT.class);
@ClassRule
public static TestRule rule = RuleChain.outerRule(spliceSchemaWatcher)
.around(TestUtils.createFileDataWatcher(spliceClassWatcher, "test_data/employee-2table.sql", CLASS_NAME))
.around(spliceTableWatcher)
.around(spliceTableWatcher2)
.around(new SpliceDataWatcher() {
@Override
protected void starting(Description description) {
try {
spliceClassWatcher.setAutoCommit(true);
spliceClassWatcher.executeUpdate(format("insert into %s values (date('2012-01-01'),1)", spliceTableWatcher));
spliceClassWatcher.executeUpdate(format("insert into %s values (date('2012-02-01'),1)", spliceTableWatcher));
spliceClassWatcher.executeUpdate(format("insert into %s values (date('2012-03-01'),1)", spliceTableWatcher));
spliceClassWatcher.executeUpdate(format("insert into %s values (date('2012-03-01'),2)", spliceTableWatcher));
spliceClassWatcher.executeUpdate(format("insert into %s values (date('2012-03-01'),3)", spliceTableWatcher));
spliceClassWatcher.executeUpdate(format("insert into %s values (date('2012-04-01'),3)", spliceTableWatcher));
spliceClassWatcher.executeUpdate(format("insert into %s values (date('2012-05-01'),3)", spliceTableWatcher));
spliceClassWatcher.executeUpdate(format("insert into %s values (null, null), (1,1), (null, null), (2,1), (3,1),(10,10)", spliceTableWatcher2));
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
spliceClassWatcher.closeAll();
}
}
});
@Rule
public SpliceWatcher methodWatcher = new SpliceWatcher();
@Test
// Confirm baseline HAVING support
public void testHaving() throws Exception {
ResultSet rs = methodWatcher.executeQuery(
format("SELECT T1.PNUM FROM %s.T1 T1 GROUP BY T1.PNUM " +
"HAVING T1.PNUM IN ('P1', 'P2', 'P3')",
CLASS_NAME));
Assert.assertEquals(3, TestUtils.resultSetToMaps(rs).size());
}
@Test
// Bugzilla #376: nested sub-query in HAVING
public void testHavingWithSubQuery() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("SELECT T1.PNUM FROM %1$s.T1 T1 GROUP BY T1.PNUM " +
"HAVING T1.PNUM IN " +
// Progressively more simple sub-queries:
"(SELECT T2.PNUM FROM %1$s.T2 T2 GROUP BY T2.PNUM HAVING SUM(T2.BUDGET) > 25000)",
//"(SELECT T2.PNUM FROM %s.T2 T2 WHERE T2.PNUM IN ('P1', 'P2', 'P3'))",
//"(SELECT 'P1' FROM %s.T2)",
CLASS_NAME, CLASS_NAME));
Assert.assertEquals(3, TestUtils.resultSetToMaps(rs).size());
}
@Test
// Bugzilla #377: nested sub-query in HAVING with ORDER BY
public void testHavingWithSubQueryAndOrderby() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("SELECT T1.PNUM FROM %1$s.T1 T1 GROUP BY T1.PNUM " +
"HAVING T1.PNUM IN (SELECT T2.PNUM FROM %1$s.T2 T2 GROUP BY T2.PNUM HAVING SUM(T2.BUDGET) > 25000)" +
"ORDER BY T1.PNUM",
CLASS_NAME));
List<Map> maps = TestUtils.resultSetToMaps(rs);
Assert.assertEquals(3, maps.size());
Assert.assertEquals("P2", maps.get(0).get("PNUM"));
}
@Test()
// Bugzilla #581: WORKDAY: count(distinct()) fails in a GROUP BY clause
public void countDistinctInAGroupByClause() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select distinct month(swh_date), count(distinct(i)) from %s " +
"group by month(swh_date) order by month(swh_date)",
spliceTableWatcher.toString()));
int i = 0;
while (rs.next()) {
i++;
if (rs.getInt(1) == 3 && rs.getInt(2) != 3) {
Assert.assertTrue("count distinct did not return 3 for month 3",false);
}
}
Assert.assertEquals("Should return only rows for the group by columns",5, i);
}
@Test()
// Bugzilla #786
public void testCountOfNullsAndBooleanSet() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select (1 in (1,2)), count(c1) from %s group by c1",spliceTableWatcher2));
int i =0;
while (rs.next()) {
i++;
}
Assert.assertEquals("Should return only rows for the group by columns",5, i);
}
@Test()
// Bugzilla #787
public void testNoExplicitAggregationFunctions() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select c1+10, c2, c1*1, c1, c2*5 from %s group by c1, c2",spliceTableWatcher2));
int i =0;
while (rs.next()) {
i++;
}
Assert.assertEquals("Should return 5 rows",5, i);
}
@Test()
// Bugzilla #790
public void testAggregateWithSingleReturnedValue() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select tmpC1 from (select max(c1+10) from %s group by c2) as tmp (tmpC1)",spliceTableWatcher2));
int i =0;
while (rs.next()) {
i++;
}
Assert.assertEquals("Should return 3 rows",3, i);
}
}
|
package de.uni_hildesheim.sse.monitoring.runtime.instrumentation;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import de.uni_hildesheim.sse.codeEraser.annotations.Variability;
import de.uni_hildesheim.sse.monitoring.runtime.AnnotationConstants;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.EndSystem;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.
ExcludeFromMonitoring;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.Helper;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.Instrumented;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.Timer;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.NotifyValue;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.ConfigurationChange;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.StartSystem;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.Monitor;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.TimerPosition;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.TimerState;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.ValueChange;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.VariabilityHandler;
import de.uni_hildesheim.sse.monitoring.runtime.annotations.internal.
MethodInstrumented;
import de.uni_hildesheim.sse.monitoring.runtime.boot.GroupAccountingType;
import de.uni_hildesheim.sse.monitoring.runtime.boot.MainDefaultType;
import de.uni_hildesheim.sse.monitoring.runtime.boot.MonitoringGroupSettings;
import de.uni_hildesheim.sse.monitoring.runtime.boot.RecorderFrontend;
import de.uni_hildesheim.sse.monitoring.runtime.boot.ResourceType;
import de.uni_hildesheim.sse.monitoring.runtime.utils.HashMap;
import de.uni_hildesheim.sse.monitoring.runtime.wrap.
InstrumentedFileOutputStream;
import de.uni_hildesheim.sse.monitoring.runtime.configuration.
AnnotationSearchType;
import de.uni_hildesheim.sse.monitoring.runtime.configuration.Configuration;
import de.uni_hildesheim.sse.monitoring.runtime.configuration.
MemoryAccountingType;
import de.uni_hildesheim.sse.monitoring.runtime.configuration.ScopeType;
import de.uni_hildesheim.sse.monitoring.runtime.configuration.xml.
XMLConfiguration;
import de.uni_hildesheim.sse.monitoring.runtime.instrumentation.lib.*;
import de.uni_hildesheim.sse.monitoring.runtime.recording.ElschaLogger;
import de.uni_hildesheim.sse.monitoring.runtime.recording.Recorder;
/**
* Implements the class file transformer introducing additional code
* for instrumentation. Note that some methods in this class require the class
* name to be given in in the internal form of fully qualified class and
* interface names as defined in The Java Virtual Machine Specification. This is
* due to performance reasons for runtime instrumentation.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.13
*/
public class AbstractClassTransformer implements ISemanticsCollector {
/**
* The fully qualified name of the delegating random access file.
* Do not refer this class directly because otherwise it is loaded
* before self-instrumentation.
*/
static final String DELEGATING_RANDOM_ACCESS_FILE =
InstrumentedFileOutputStream.class.getPackage().getName()
+ ".DelegatingRandomAccessFile";
// otherways loaded here before instrumentation
/**
* Stores if static instrumentation should be done.
*/
private boolean isStatic;
/**
* Stores registered classes.
*/
private HashSet<String> registeredClasses = new HashSet<String>();
/**
* Counts the number of main methods (usually only the first one
* is relevant).
*/
private int mainCount = 0;
/**
* Stores classes to be excluded.
* @since 1.13
*/
private String[] excludeClasses = null;
/**
* Analyze the members of the individual classes.
* @since 1.13
*/
private HashMap<String, Boolean> analyzeMembers;
/**
* Stores the assignments.
*/
private final HashMap<String, HashMap<String, Monitor>> assignments
= new HashMap<String, HashMap<String, Monitor>>();
/**
* Creates a new monitoring class file transformer.
*
* @param isStatic denotes if static instrumentation should be done or
* dynamic
*
* @since 1.00
*/
public AbstractClassTransformer(boolean isStatic) {
Recorder.initialize();
this.isStatic = isStatic;
Configuration cfg = Configuration.INSTANCE;
excludeClasses = cfg.getExcludeClasses();
XMLConfiguration xmlCfg = cfg.getXMLConfig();
if (null != xmlCfg && !cfg.allClassMembers()) {
analyzeMembers = xmlCfg.getAnalyzeMembers();
}
}
/**
* Returns if the given class name denotes the random access file.
*
* @param className the class name to be tested given in the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification. For example,
* "java/util/List".
* @return <code>false</code> if it is not the random access file,
* <code>true</code> else
*
* @since 1.00
*/
@Variability(id = AnnotationConstants.MONITOR_FILE_IO, value = "false")
private final boolean isRandomAccessFile(String className) {
return className.equals("java/io/RandomAccessFile");
}
/**
* Returns if the given class name denotes the socket input stream.
*
* @param className the class name to be tested given in the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification. For example,
* "java/util/List".
* @return <code>false</code> if it is not the socket input stream,
* <code>true</code> else
*
* @since 1.00
*/
@Variability(id = AnnotationConstants.MONITOR_NET_IO, value = "false")
private final boolean isSocketInputStream(String className) {
return className.equals("java/net/SocketInputStream");
}
/**
* Returns if the given class name denotes the socket output stream.
*
* @param className the class name to be tested given in the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification. For example,
* "java/util/List".
* @return <code>false</code> if it is not the socket output stream,
* <code>true</code> else
*
* @since 1.00
*/
@Variability(id = AnnotationConstants.MONITOR_NET_IO, value = "false")
private final boolean isSocketOutputStream(String className) {
return className.equals("java/net/SocketOutputStream");
}
/**
* Returns if the given class name denotes a recorder class.
*
* @param className the class name to be tested given in the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification. For example,
* "java/util/List".
* @return <code>false</code> if it is not a recorder class,
* <code>true</code> else
*
* @since 1.00
*/
private final boolean isRecorderClass(String className) {
return className.startsWith(
"de/uni_hildesheim/sse/monitoring/runtime/");
}
/**
* Converts a given fully qualified class name in the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification (slash separated) to a Java
* fully qualified name (dot separated).
*
* @param vmFqn the fully qualified name according to the Java Virtual
* Machine Specification
* @return the Java typical name
*
* @since 1.00
*/
public static final String internalVmFqnToJavaFqn(String vmFqn) {
return vmFqn.replace('/', '.');
}
/**
* Converts a given Java fully qualified class name (dot separated) to the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification (slash separated).
*
* @param fqn the fully qualified Java name
* @return the fully qualified name according to the Java Virtual
* Machine Specification
*
* @since 1.00
*/
public static final String javaFqnToInternalVmFqnTo(String fqn) {
return fqn.replace('.', '/');
}
/**
* Returns if the class given by its class name should be instrumented.
*
* @param className the name of the class to be checked given in the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification. For example,
* "java/util/List".
* @return <code>true</code> if the class should be instrumented,
* <code>false</code> else
*
* @since 1.00
*/
public final boolean shouldInstrument(String className) {
if (Configuration.INSTANCE.instrumentJavaLib()
&& (isSocketInputStream(className)
|| isSocketOutputStream(className)
|| isRandomAccessFile(className))) {
return true;
}
if (isRecorderClass(className)) {
return false;
}
boolean isJavaClass = className.equals("sun/misc/Cleaner");
if (!Configuration.INSTANCE.instrumentJavaLib()) {
// be more precise
isJavaClass |= className.startsWith("javax/");
isJavaClass |= className.startsWith("com/sun/");
isJavaClass |= className.startsWith("com/oracle/");
isJavaClass |= className.startsWith("sun/");
isJavaClass |= className.startsWith("sunw/");
isJavaClass |= className.startsWith("org/xml");
isJavaClass |= className.startsWith("org/w3c");
isJavaClass |= className.startsWith("org/omg");
isJavaClass |= className.startsWith("org/jcp");
isJavaClass |= className.startsWith("org/ietf");
}
boolean additional = false;
if (Configuration.INSTANCE.instrumentInstrumenter()) {
// TODO: be careful with existing results but should be excluded
// there as it is overhead
additional |= className.startsWith("javassist/");
}
additional |= className.startsWith("com/sun/jmx/remote/internal/");
// accesses private constructors in other classes
additional |= className.startsWith("sun/reflect/Generated");
boolean instr = !(className.startsWith("de/uni_hildesheim/sse/system")
|| isJavaClass || additional);
if (instr && null != excludeClasses) {
for (int i = 0; instr && i < excludeClasses.length; i++) {
instr &= !className.startsWith(excludeClasses[i]);
}
}
return instr;
}
/**
* Returns the {@link Monitor} annotation for <code>cl</code>. This method
* considers whether <code>cl</code> or its (outer) declaring class has a
* {@link Monitor} annotation and returns it or stops at a
* {@link ExcludeFromMonitoring} annotation.
*
* @param cl the class to be queried for the annotation
* @return the related annotation or <b>null</b> in case that none was found
* or the class is explicitly excluded from monitoring.
* @throws InstrumenterException in case that some class cannot be found
*
* @since 1.00
*/
private static final Monitor getMonitorAnnotation(IClass cl)
throws InstrumenterException {
AnnotationSearchType asType =
Configuration.INSTANCE.getAnnotationSearchType();
Monitor result = getAnnotation(cl, Monitor.class, asType);
if (null == result) {
if (null == getAnnotation(cl,
ExcludeFromMonitoring.class, asType)) {
IClass outer = cl;
do {
IClass decl = outer.getDeclaringClass();
if (outer != cl) {
// not our responsiblity
outer.release();
}
outer = decl;
if (null != outer) {
result = getAnnotation(outer, Monitor.class, asType);
if (null == result) {
if (null != getAnnotation(outer,
ExcludeFromMonitoring.class, asType)) {
outer.release();
outer = null;
}
}
}
} while (null != outer && null == result);
if (null != outer) {
outer.release();
}
}
}
return result;
}
// below:
/*
MemoryAccountingType memAccounting = Configuration.INSTANCE
.getMemoryAccountingType();
if (memAccounting.atFinalizer()) {
CtMethod[] methods = cl.getMethods();
boolean hasFinalize = false;
for (int m = 0; m < methods.length; m++) {
CtMethod method = methods[m];
if (InstrumentationFragments.isFinalize(method)) {
hasFinalize = true;
InstrumentationFragments.instrumentFinalize(method);
}
}
if (!hasFinalize) {
InstrumentationFragments.addFinalizer(cl, false);
}
}
return;
}*/
/**
* Returns whether the members of a class shall be analyzed. Prerequisite
* is that {@link #analyzeMembers} is not <b>null</b>.
*
* @param clName the class name
* @param cl the class itself for further inspection
* @return <code>true</code> if the
* @throws InstrumenterException in case of problems with the bytecode
*
* @since 1.00
*/
private boolean analyzeMembers(String clName, IClass cl)
throws InstrumenterException {
boolean analyze;
if (null != analyzeMembers) {
analyze = analyzeMembers.containsKey(clName);
if (!analyze) {
// for inner classes
String decl = cl.getDeclaringClassName();
if (null != decl) {
analyze = analyzeMembers.containsKey(decl);
}
}
} else {
analyze = true;
}
return analyze;
}
/**
* Processes a class of the system under monitoring.
*
* @param name the name of the class given in the
* internal form of fully qualified class and interface names as defined
* in The Java Virtual Machine Specification. For example,
* "java/util/List".
* @param cl the class
* @param type the type of the transformation
* @return <code>true</code> if the class was modified,
* <code>false</code> else
*
* @throws InstrumenterException in case that any error occurs
* while processing bytecode
*
* @since 1.00
*/
public final boolean transform(String name, IClass cl,
TransformationType type) throws InstrumenterException {
boolean transformed = false;
HashMap<String, Monitor> assignedSemantics;
Configuration config = Configuration.INSTANCE;
String clName = cl.getName();
if (ScopeType.GROUP_INHERIT == config.getScopeType()) {
assignedSemantics = assignments.remove(clName);
} else {
assignedSemantics = null;
}
boolean mayAlterStructure = type.mayAlterStructure();
ICodeModifier modifier = IFactory.getInstance().getCodeModifier();
if (null == getAnnotation(cl, Instrumented.class,
AnnotationSearchType.NONE)) {
boolean done = false;
if (isSocketInputStream(name) && ResourceType.contains(
config.getAccountableResources(), ResourceType.NET_IO)) {
modifier.instrumentSocketInputStream(cl);
transformed = true;
done = true;
} else if (isSocketOutputStream(name) && ResourceType.contains(
config.getAccountableResources(), ResourceType.NET_IO)) {
modifier.instrumentSocketOutputStream(cl);
transformed = true;
done = true;
} else if (isRandomAccessFile(name) && ResourceType.contains(
config.getAccountableResources(), ResourceType.FILE_IO)) {
modifier.instrumentRandomAccessFile(cl);
transformed = true;
done = true;
} else if (isRecorderClass(name)) {
done = true;
}
boolean inherited = false;
Monitor mGroup = null;
if (!done && TransformationType.REDEFINITION != type) {
mGroup = getMonitorAnnotation(cl);
}
if (!done && !cl.isInterface() && (null != assignedSemantics
|| analyzeMembers(clName, cl))) {
// long memSize = ObjectSizeCache.INSTANCE.getSize(
// cl.getSuperclass().getName(), false);
int fCount = cl.getDeclaredFieldCount();
for (int f = 0; f < fCount; f++) {
IField field = cl.getDeclaredField(f);
// memSize = ObjectSizeEstimator.getTypeSize(
// field.getTypeName());
ValueChange change = getAnnotation(field,
ValueChange.class, AnnotationSearchType.NONE);
if (null != change) {
MethodEditor.put(field, Helper.trimId(change.id()));
}
field.release();
}
// ObjectSizeCache.INSTANCE.setSize(cl.getName(),
// ObjectSizeEstimator.getClassSize(memSize));
int bCount = cl.getDeclaredBehaviorCount();
boolean hasFinalizer = false;
MethodEditor methodEditor =
MethodEditor.getFromPool(mGroup, false, this, false);
for (int m = 0; m < bCount; m++) {
IBehavior behavior = cl.getDeclaredBehavior(m);
if (!behavior.isAbstract() && !behavior.isNative()) {
Monitor mSem = mGroup;
if (null != assignedSemantics) {
Monitor iSem = assignedSemantics.get(
behavior.getName()
+ behavior.getJavaSignature());
inherited = (null != iSem);
mSem = iSem;
methodEditor.setGroup(mSem, false, this, inherited);
}
try {
ElschaLogger.info("Transforming " + cl.getName());
transformed |= doMethod(behavior, mSem, inherited,
type, methodEditor);
ElschaLogger.info("Transformed " + cl.getName() + " = " + transformed);
if (0 == mainCount && "main".equals(
behavior.getName())) {
int pCount = behavior.getParameterCount();
if (pCount == 1
&& Constants.JAVA_LANG_STRING_ARRAY1.equals(
behavior.getParameterTypeName(0))) {
transformed |= doFirstMain(cl, behavior,
mSem, type);
mainCount++;
}
}
} catch (InstrumenterException e) {
if (!handleMethodInstrumentationException(e)) {
throw e;
}
}
if (mSem != mGroup) {
methodEditor.setGroup(mGroup, false, this, false);
}
}
hasFinalizer |= behavior.isFinalize();
behavior.release();
}
MethodEditor.release(methodEditor);
if (mayAlterStructure && !hasFinalizer && Configuration.
INSTANCE.getMemoryAccountingType().atFinalizer()) {
modifier.addFinalizer(cl, false);
transformed = true;
}
// nested classes are considered by default
}
if (!done) {
if (cl.isInstanceOf(Constants.JAVA_LANG_THREAD)
|| cl.isInstanceOf(Constants.JAVA_LANG_RUNNABLE)) {
transformed |= instrumentThreadRun(cl, type);
}
if (cl.getDeclaringClassName().contains("FamilyElement")) {
ElschaLogger.info("Registering " + cl.getDeclaringClassName() + ", isInterface = " + cl.isInterface() + ", assignedSemantics = " + assignedSemantics + ", mGroup = " + mGroup);
}
if (!cl.isInterface() && null == assignedSemantics) {
transformed |= registerRecorderId(mGroup, cl);
}
}
} // has Instrumented annotation
Configuration.INSTANCE.instrumented(clName);
assignments.remove(clName);
// trigger retransformation
if (mayAlterStructure) {
// concurrent modification!!!
int size = assignments.keySize();
if (size > 0) {
String[] classes = new String[size];
assignments.keysToArray(classes);
retransformAssigned(classes);
}
}
//assignments.clear();
return transformed;
}
/**
* Retransforms the specified classes.
*
* @param classNames the class names
*
* @since 1.00
*/
protected void retransformAssigned(String[] classNames) {
}
/**
* Instruments the run method of a thread. This method is called only
* if JMX is not supported, e.g. on Android.
*
* @param cl the class to analyze
* @param type the type of the transformation
* @return <code>true</code> if the class was modified,
* <code>false</code> else
* @throws InstrumenterException in case that the new code cannot be
* compiled
*
* @since 1.00
*/
private final boolean instrumentThreadRun(IClass cl,
TransformationType type) throws InstrumenterException {
boolean modified = false;
if (!cl.isInterface() && !cl.isAbstract()) {
// sufficient for instantiable classes, avoid problems with
// TODO serializable classes without SerialVersionUID
int bCount = cl.getDeclaredBehaviorCount();
boolean found = false;
for (int m = 0; m < bCount; m++) {
IBehavior behavior = cl.getDeclaredBehavior(m);
if ("run".equals(behavior.getName())) {
if (0 == behavior.getParameterCount()) {
if (!behavior.isAbstract()) {
modified = IFactory.getInstance().getCodeModifier().
notifyRegisterThread(cl, behavior, false);
}
found = true;
}
}
behavior.release();
}
if (!found && type.mayAlterStructure()) {
boolean doit = true;
if (cl.isInstanceOf(Constants.JAVA_IO_SERIALIZABLE)) {
// this is a fix... alternative - calculate original uid
doit = false;
for (int f = 0; !doit && f < cl.getDeclaredFieldCount();
f++) {
IField field = cl.getDeclaredField(f);
doit = "long".equals(field.getTypeName())
&& Constants.SERIAL_VERSION_FIELD_NAME.equals(
field.getName());
}
}
if (doit) {
modified = IFactory.getInstance().getCodeModifier().
notifyRegisterThread(cl, null, false);
}
}
}
return modified;
}
/**
* Registers a monitoring element (class or method) for monitoring.
*
* @param mGroup the monitoring annotation
* @param cl the containing class
* @return <code>true</code> if the class was modified,
* <code>false</code> else
* @throws InstrumenterException in case of any byte code error
*
* @since 1.00
*/
private final synchronized boolean registerRecorderId(
Monitor mGroup, IClass cl) throws InstrumenterException {
boolean modified = false;
ElschaLogger.info("First register call " + cl.getDeclaringClassName() + ", !Helper.ignore(mGroup) = " + !Helper.ignore(mGroup) + ", Helper.isId(mGroup, Helper.PROGRAM_ID) || Helper.isId(mGroup, Helper.RECORDER_ID) = " + (Helper.isId(mGroup, Helper.PROGRAM_ID) || Helper.isId(mGroup, Helper.RECORDER_ID)) + ", isStatic = " + isStatic + ", mGroup = " + mGroup);
if (null != mGroup) {
if (Helper.isId(mGroup, Helper.PROGRAM_ID)
|| Helper.isId(mGroup, Helper.RECORDER_ID)) {
Configuration.LOG.warning("@Monitor for " + cl.getName()
+ "uses internal recorder id - ignored");
} else if (!Helper.ignore(mGroup)) {
if (isStatic) {
String className = cl.getName();
if (!registeredClasses.contains(className)) {
// avoid duplicated registering initializers
IFactory.getInstance().getCodeModifier().
addRegisteringInitializer(cl, mGroup);
registeredClasses.add(className);
modified = true;
}
} else {
MonitoringGroupSettings settings
= MonitoringGroupSettings.getFromPool();
String[] ids = mGroup.id();
for (int i = 0; i < ids.length; i++) {
// usually arrays returned by annotations (in our case)
// should not be modified, because in the XML case
// they are generate dynamically an values are
// overwritten in memory
ids[i] = ids[i].trim();
if (0 == ids[i].length()) {
ids[i] = cl.getName();
}
}
settings.setBasics(ids, mGroup.debug(), mGroup.groupAccounting(),
mGroup.resources(), mGroup.instanceIdentifierKind());
if (ids.length > 1) {
settings.setMulti(mGroup.distributeValues(),
mGroup.considerContained());
}
RecorderFrontend.instance.registerForRecording(
cl.getName(), settings);
MonitoringGroupSettings.release(settings);
}
}
}
return modified;
}
/**
* Returns whether the specified annotation may be pruned, i.e. removed
* from resulting bytecode. The results depends on the current configuration
* and the concrete type of the annotation, i.e. no pruning happens, if
* pruning is disabled by default. If pruning is enabled, it is enabled for
* all annotations except of the {@link Instrumented} annotation, which
* is enabled only in case of dynamic instrumentation (for staged static
* instrumentations).
*
* @param <T> the type of the annotation
* @param annotation the type of the annotation (meta class)
* @return <code>true</code> if the given annotation (type) may be pruned,
* <code>false</code> else
*
* @since 1.00
*/
protected static final <T extends Annotation> boolean pruneAnnotation(
Class<T> annotation) {
boolean result = false;
// pruning would lead to problems finding the value contexts
Configuration config = Configuration.INSTANCE;
if (config.pruneAnnotations()) {
if (annotation == Instrumented.class) {
result = !config.isStaticInstrumentation();
} else {
result = true;
}
}
return result;
}
/**
* Returns the annotation of the specified <code>annotation</code> type
* if it is defined for <code>member</code>.
*
* @param <T> the type of the annotation
* @param member the member to be considered for querying the
* <code>annotation</code>
* @param annotation the type of the annotation to be searched for (meta
* class)
* @param search the annotation search type
* @return the instance of the annotation if it is defined on
* <code>method</code>, <b>null</b> otherwise
*
* @since 1.00
*/
protected static final <T extends Annotation> T getAnnotation(
IField member, Class<T> annotation, AnnotationSearchType search) {
// check AllDelegatingEditor
T result = null;
boolean done = false;
XMLConfiguration config = Configuration.INSTANCE.getXMLConfig();
if (null != config) {
IClass declaring = member.getDeclaringClass();
result = config.getAnnotation(member.getSignature(),
declaring, annotation, IFactory.getInstance());
declaring.release();
done = config.isExclusive();
}
if (!done && null == result) {
result = member.getAnnotation(annotation,
pruneAnnotation(annotation));
}
return result;
}
/**
* Returns the annotation of the specified <code>annotation</code> type
* if it is defined for <code>member</code>.
*
* @param <T> the type of the annotation
* @param member the member to be considered for querying the
* <code>annotation</code>
* @param annotation the type of the annotation to be searched for (meta
* class)
* @param search the annotation search type
* @return the instance of the annotation if it is defined on
* <code>method</code>, <b>null</b> otherwise
*
* @since 1.00
*/
protected static final <T extends Annotation> T getAnnotation(
IBehavior member, Class<T> annotation, AnnotationSearchType search) {
IClass declaring = member.getDeclaringClass();
T result = getAnnotation(member, declaring, annotation, search, true);
declaring.release();
return result;
}
/**
* Returns the annotation of the specified <code>annotation</code> type
* if it is defined for <code>member</code>.
*
* @param <T> the type of the annotation
* @param member the member to be considered for querying the
* <code>annotation</code>
* @param searchIn the class / interface to search in
* @param annotation the type of the annotation to be searched for (meta
* class)
* @param search the annotation search type
* @param topCall is this method called from the top of the current
* recursion or from within
* @return the instance of the annotation if it is defined on
* <code>method</code>, <b>null</b> otherwise
*
* @since 1.00
*/
private static final <T extends Annotation> T getAnnotation(
IBehavior member, IClass searchIn, Class<T> annotation,
AnnotationSearchType search, boolean topCall) {
T result = null;
IBehavior sMember = member;
try {
boolean done = false;
XMLConfiguration config = Configuration.INSTANCE.getXMLConfig();
if (!topCall) {
sMember = searchIn.findSignature(member);
}
if (null != config) {
result = config.getAnnotation(sMember.getSignature(),
searchIn, annotation, IFactory.getInstance());
done = config.isExclusive();
}
if (!done && null == result) {
result = sMember.getAnnotation(annotation,
pruneAnnotation(annotation));
}
if (AnnotationSearchType.NONE != search && null == result) {
if (search.considerSuperclass()) {
IClass su = searchIn.getSuperclass();
if (null != su) {
IBehavior mem = su.findSignature(member);
if (null != mem) {
result = getAnnotation(mem, su, annotation,
search, false);
mem.release();
}
su.release();
}
}
if (null == result && search.considerInterface()) {
int iCount = searchIn.getInterfaceCount();
if (iCount > 0) {
for (int i = 0; null == result && i < iCount; i++) {
IClass iface = searchIn.getInterface(i);
IBehavior mem = iface.findSignature(member);
if (null != mem) {
result = getAnnotation(mem, iface, annotation,
search, false);
mem.release();
}
iface.release();
}
}
}
}
} catch (InstrumenterException e) {
} finally {
if (!topCall && null != sMember) {
sMember.release();
}
}
return result;
}
/**
* Returns the annotation of the specified <code>annotation</code> type
* if it is defined for <code>cls</code>.
*
* @param <T> the type of the annotation
* @param cls the class to be considered for querying the
* <code>annotation</code>
* @param annotation the type of the annotation to be searched for (meta
* class)
* @param search the annotation search type
* @return the instance of the annotation if it is defined on
* <code>method</code>, <b>null</b> otherwise
*
* @since 1.00
*/
protected static final <T extends Annotation> T getAnnotation(
IClass cls, Class<T> annotation, AnnotationSearchType search) {
T result = null;
XMLConfiguration config = Configuration.INSTANCE.getXMLConfig();
boolean done = false;
if (null != config) {
result = config.getAnnotation(cls.getName(), cls,
annotation, IFactory.getInstance());
done = config.isExclusive();
}
if (!done && null == result) {
result = cls.getAnnotation(annotation,
pruneAnnotation(annotation));
}
if (AnnotationSearchType.NONE != search && null == result) {
try {
if (search.considerSuperclass()) {
IClass su = cls.getSuperclass();
if (null != su) {
result = getAnnotation(su, annotation, search);
su.release();
}
}
if (null == result && search.considerInterface()) {
int ifCount = cls.getInterfaceCount();
if (ifCount > 0) {
for (int i = 0; null == result && i < ifCount; i++) {
IClass iface = cls.getInterface(i);
result = getAnnotation(iface, annotation, search);
iface.release();
}
}
}
} catch (InstrumenterException e) {
}
}
return result;
}
/**
* Processes the first main method which occurs during instrumentation of a
* program.
*
* @param cls the class
* @param behavior the behavior to be modified
* @param mGroupClass the annotation on class level as cause for
* instrumenting this method (may be <b>null</b>)
* @param type the type of the transformation
* @return <code>true</code> if the class was modified,
* <code>false</code> else
* @throws InstrumenterException in case that the code added by
* instrumentation does not compile
*
* @since 1.00
*/
private final boolean doFirstMain(IClass cls, IBehavior behavior,
Monitor mGroupClass, TransformationType type)
throws InstrumenterException {
boolean modified = false;
MainDefaultType dType = Configuration.INSTANCE.getMainDefault();
ICodeModifier modifier = IFactory.getInstance().getCodeModifier();
if (MainDefaultType.NONE != dType) {
if (dType.atStart() || dType.atShutdown()) {
StartSystem startSystem = getAnnotation(behavior,
StartSystem.class, AnnotationSearchType.NONE);
if (null == startSystem) {
modifier.instrumentStartSystem(behavior,
dType.atShutdown(), "");
modified = true;
}
}
if (dType.atStop()) {
EndSystem endSystem = getAnnotation(behavior,
EndSystem.class, AnnotationSearchType.NONE);
if (null == endSystem) {
modifier.instrumentEndSystem(behavior,
Configuration.INSTANCE.printStatistics(), "");
modified = true;
}
}
}
if (cls.isInstanceOf(Constants.JAVA_LANG_THREAD)) {
modified = modifier.notifyRegisterThread(cls, null, false);
}
return modified;
}
/**
* Processes a method of a regular class (system under measurement).
*
* @param behavior the behavior to be modified
* @param mGroupClass the annotation on class level as cause for
* instrumenting this method (may be <b>null</b>)
* @param inherited whether <code>mGroupClass</code> is inherited
* @param type the type of the transformation
* @param editor the editor for modifications
* @return <code>true</code> if the behavior was modified,
* <code>false</code> else
* @throws InstrumenterException in case that the code added by
* instrumentation does not compile
*
* @since 1.00
*/
private final boolean doMethod(IBehavior behavior, Monitor mGroupClass,
boolean inherited, TransformationType type, MethodEditor editor)
throws InstrumenterException {
boolean modified = false;
ICodeModifier modifier = IFactory.getInstance().getCodeModifier();
AnnotationSearchType asType = Configuration.INSTANCE.
getAnnotationSearchType();
EndSystem endSystem =
getAnnotation(behavior, EndSystem.class, AnnotationSearchType.NONE);
ConfigurationChange configurationChangeAnnotation =
getAnnotation(behavior, ConfigurationChange.class, asType);
Monitor mGroup = getAnnotation(behavior, Monitor.class, asType);
Timer notifyTimer = getAnnotation(behavior, Timer.class, asType);
VariabilityHandler varHandler = getAnnotation(behavior,
VariabilityHandler.class, asType);
boolean isExcluded = (null != getAnnotation(behavior,
ExcludeFromMonitoring.class, asType));
boolean manualDetectionWithConfigChange =
!Configuration.INSTANCE.configurationDetection()
&& null != configurationChangeAnnotation;
if (null != mGroup && !isExcluded) {
// local annotation has higher priority, excluded even higher
mGroupClass = mGroup;
IClass decl = behavior.getDeclaringClass();
// TODO may happen in multiple cases during static initialization!
registerRecorderId(mGroup, decl);
decl.release();
}
StartSystem startSystem = getAnnotation(behavior,
StartSystem.class, AnnotationSearchType.NONE);
if (null != notifyTimer && !inherited) {
modified |= instrumentNotifyTimer(behavior, notifyTimer);
}
MemoryAccountingType memAccounting = editor.getMemoryAccountingType();
if (memAccounting.atFinalizer()) {
modifier.instrumentFinalize(behavior);
modified = true;
}
if (memAccounting.atConstructor() && behavior.isConstructor()) {
modifier.instrumentConstructor(behavior);
modified = true;
}
if (behavior.getDeclaringClassName().contains("FamilyElement")) {
ElschaLogger.info("doMethod with excluded = " + isExcluded + ", mGroup = " + mGroupClass + ", inherited = " + inherited);
}
if (!isExcluded) {
if (null != mGroupClass && !inherited) {
modifier.instrumentTiming(behavior, mGroupClass, false,
null != mGroup);
modified = true;
if (behavior.getDeclaringClassName().contains("FamilyElement")) {
ElschaLogger.info("timing instrumented for " + behavior.getDeclaringClassName() + " with " + modifier);
}
}
boolean configLocal = (GroupAccountingType.LOCAL
== editor.getGroupAccountingType());
if (!configLocal || (configLocal && null != mGroup)) {
boolean isRedefinition =
TransformationType.REDEFINITION == type;
// do deeper instrumentation only if non-local or local with
// appropriate annotation
if (isRedefinition) {
MethodInstrumented instrumented = getAnnotation(behavior,
MethodInstrumented.class, AnnotationSearchType.NONE);
if (null != instrumented) {
editor.setInstrumentationRecord(instrumented);
}
}
behavior.instrument(editor);
if (isRedefinition) {
int record = editor.getMemRecord();
if (record > 0) {
HashMap<String, Object> map
= new HashMap<String, Object>();
map.put("mem", record);
modifier.addAnnotation(behavior,
MethodInstrumented.class, map);
modified = true;
}
editor.setInstrumentationRecord(null);
}
}
if (null != varHandler && !inherited
&& !manualDetectionWithConfigChange) {
modifier.instrumentVariabilityHandler(behavior);
modified = true;
}
} else {
if (null != mGroupClass && !inherited) {
modifier.instrumentTiming(behavior, mGroupClass, true, true);
modified = true;
}
}
if (null != configurationChangeAnnotation && !inherited) {
modifier.instrumentConfigurationChange(behavior,
configurationChangeAnnotation);
modified = true;
}
modified |= processNotifications(behavior, mGroupClass, modifier);
if (null != startSystem) {
modifier.notifyRegisterThread(behavior.getDeclaringClass(),
behavior, true);
modifier.instrumentStartSystem(behavior,
startSystem.shutdownHook(), startSystem.invoke());
modified = true;
}
if (null != endSystem) {
modifier.instrumentEndSystem(behavior,
Configuration.INSTANCE.printStatistics(), endSystem.invoke());
modified = true;
}
return modified;
}
/**
* Processes value notifications on the given method.
*
* @param behavior the method to be changed
* @param mGroup the annotation which indicated recording (may be
* <b>null</b>)
* @param modifier the code modifier to be used
* @return <code>true</code> if the behavior was modified,
* <code>false</code> else
* @throws InstrumenterException if any instrumented code is not valid
*
* @since 1.00
*/
private boolean processNotifications(IBehavior behavior,
Monitor mGroup, ICodeModifier modifier) throws InstrumenterException {
boolean modified = false;
NotifyValue ann = getAnnotation(behavior,
NotifyValue.class, AnnotationSearchType.NONE);
if (null != ann) {
String recId = null;
String annId = Helper.trimId(ann.id());
if (annId.length() > 0) {
recId = annId;
} else if (null != mGroup) {
recId = Configuration.INSTANCE.getRecId(mGroup.id());
}
modifier.valueNotification(behavior, recId, ann);
modified = true;
}
return modified;
}
/**
* Performs the instrumentation for the timer notification. This method
* determines the point within the method / constructor to affect existing
* code at, constructs the call to the recorder and inserts the call
* accordingly.
*
* @param behavior the method / constructor being processed
* @param notifyTimer the timer annotation appended to
* <code>behaviorInfo</code>
* @return <code>true</code> if the behavior was modified,
* <code>false</code> else
* @throws InstrumenterException in case that new code cannot be compiled
*
* @since 1.00
*/
@Variability(id = AnnotationConstants.MONITOR_TIMERS)
private boolean instrumentNotifyTimer(
IBehavior behavior, Timer notifyTimer)
throws InstrumenterException {
boolean modified = false;
TimerPosition position = notifyTimer.affectAt();
if (TimerPosition.DEFAULT == position
|| TimerPosition.BOTH == notifyTimer.state().getDefaultPosition()) {
position = notifyTimer.state().getDefaultPosition();
}
TimerState beginningState = null;
TimerState endState = null;
switch (position) {
case BOTH:
if (TimerState.RESUME_SUSPEND == notifyTimer.state()) {
beginningState = TimerState.RESUME;
endState = TimerState.SUSPEND;
}
if (TimerState.SUSPEND_RESUME == notifyTimer.state()) {
beginningState = TimerState.SUSPEND;
endState = TimerState.RESUME;
}
if (TimerState.START_FINISH == notifyTimer.state()) {
beginningState = TimerState.START;
endState = TimerState.FINISH;
}
break;
case BEGINNING:
beginningState = notifyTimer.state();
break;
case END:
endState = notifyTimer.state();
break;
default:
assert false;
break;
}
if (null != beginningState) {
IFactory.getInstance().getCodeModifier().notifyTimerCall(behavior,
beginningState, notifyTimer, true);
modified = true;
}
if (null != endState) {
IFactory.getInstance().getCodeModifier().notifyTimerCall(behavior,
endState, notifyTimer, false);
modified = true;
}
return modified;
}
/**
* Is called to handle an instrumentation which occurred during
* instrumenting a method. By default, this method does not handle this
* exception and causes throwing for further handling
*
* @param exception the exception occurred
* @return <code>true</code> if the exception was handled and
* instrumentation can continue with the next method, <code>false</code>
* if the exception should be thrown by the caller for further handling
*
* @since 1.00
*/
protected boolean handleMethodInstrumentationException(
InstrumenterException exception) {
return false;
}
/**
* Assigns the monitoring semantics for the method <code>methodName</code>
* in class <code>cls</code>.
*
* @param cls the name of the class the monitoring semantics is defined for
* @param methodSignature the name of the method to assign the semantics to
* @param semantics the monitoring semantics
*
* @since 1.00
*/
public void assignSemantics(String cls, String methodSignature,
Monitor semantics) {
if (null != semantics && !Configuration.INSTANCE.isInstrumented(cls)) {
boolean exclude = false;
exclude |= cls.equals("int");
exclude |= cls.equals("boolean");
exclude |= cls.equals("byte");
exclude |= cls.equals("short");
exclude |= cls.equals("float");
exclude |= cls.equals("double");
exclude |= cls.equals("long");
exclude |= cls.startsWith(
"de.uni_hildesheim.sse.monitoring.runtime.");
exclude |= cls.equals("java.lang.Object");
exclude |= cls.equals("java.lang.Class");
exclude |= cls.equals("java.lang.String");
exclude |= cls.equals("java.lang.StringBuilder");
exclude |= cls.equals("java.lang.StringBuffer");
exclude |= cls.equals("java.io.PrintStream");
if (!exclude) {
HashMap<String, Monitor> sem = assignments.get(cls);
if (null == sem) {
sem = new HashMap<String, Monitor>();
assignments.put(cls, sem);
}
sem.put(methodSignature, semantics);
}
}
}
/**
* Removes the assigned semantics for <code>cls</code>.
*
* @param cls the name of the class the monitoring semantics shall be
* removed for
*
* @since 1.00
*/
public void deleteSemantics(String cls) {
assignments.remove(cls);
}
}
|
package eu.bcvsolutions.idm.acc.service.impl;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.idm.acc.domain.AccResultCode;
import eu.bcvsolutions.idm.acc.domain.AccountOperationType;
import eu.bcvsolutions.idm.acc.domain.MappingAttribute;
import eu.bcvsolutions.idm.acc.domain.SystemEntityType;
import eu.bcvsolutions.idm.acc.domain.SystemOperationType;
import eu.bcvsolutions.idm.acc.dto.IdentityAccountFilter;
import eu.bcvsolutions.idm.acc.dto.MappingAttributeDto;
import eu.bcvsolutions.idm.acc.dto.RoleSystemAttributeFilter;
import eu.bcvsolutions.idm.acc.dto.RoleSystemFilter;
import eu.bcvsolutions.idm.acc.entity.AccAccount;
import eu.bcvsolutions.idm.acc.entity.AccIdentityAccount;
import eu.bcvsolutions.idm.acc.entity.SysRoleSystem;
import eu.bcvsolutions.idm.acc.entity.SysRoleSystemAttribute;
import eu.bcvsolutions.idm.acc.entity.SysSchemaAttribute;
import eu.bcvsolutions.idm.acc.entity.SysSchemaAttributeHandling;
import eu.bcvsolutions.idm.acc.entity.SysSystem;
import eu.bcvsolutions.idm.acc.entity.SysSystemEntity;
import eu.bcvsolutions.idm.acc.entity.SysSystemEntityHandling;
import eu.bcvsolutions.idm.acc.exception.ProvisioningException;
import eu.bcvsolutions.idm.acc.service.api.AccAccountManagementService;
import eu.bcvsolutions.idm.acc.service.api.AccAccountService;
import eu.bcvsolutions.idm.acc.service.api.AccIdentityAccountService;
import eu.bcvsolutions.idm.acc.service.api.SysProvisioningService;
import eu.bcvsolutions.idm.acc.service.api.SysRoleSystemAttributeService;
import eu.bcvsolutions.idm.acc.service.api.SysRoleSystemService;
import eu.bcvsolutions.idm.acc.service.api.SysSchemaAttributeHandlingService;
import eu.bcvsolutions.idm.acc.service.api.SysSystemEntityHandlingService;
import eu.bcvsolutions.idm.acc.service.api.SysSystemEntityService;
import eu.bcvsolutions.idm.acc.service.api.SysSystemService;
import eu.bcvsolutions.idm.core.api.entity.AbstractEntity;
import eu.bcvsolutions.idm.core.api.service.ConfidentialStorage;
import eu.bcvsolutions.idm.core.model.dto.PasswordChangeDto;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentity;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole;
import eu.bcvsolutions.idm.core.model.service.api.IdmIdentityService;
import eu.bcvsolutions.idm.eav.entity.AbstractFormValue;
import eu.bcvsolutions.idm.eav.entity.FormableEntity;
import eu.bcvsolutions.idm.eav.entity.IdmFormAttribute;
import eu.bcvsolutions.idm.eav.service.api.FormService;
import eu.bcvsolutions.idm.icf.api.IcfAttribute;
import eu.bcvsolutions.idm.icf.api.IcfConnectorConfiguration;
import eu.bcvsolutions.idm.icf.api.IcfConnectorKey;
import eu.bcvsolutions.idm.icf.api.IcfConnectorObject;
import eu.bcvsolutions.idm.icf.api.IcfObjectClass;
import eu.bcvsolutions.idm.icf.api.IcfUidAttribute;
import eu.bcvsolutions.idm.icf.impl.IcfAttributeImpl;
import eu.bcvsolutions.idm.icf.impl.IcfConnectorObjectImpl;
import eu.bcvsolutions.idm.icf.impl.IcfObjectClassImpl;
import eu.bcvsolutions.idm.icf.impl.IcfPasswordAttributeImpl;
import eu.bcvsolutions.idm.icf.impl.IcfUidAttributeImpl;
import eu.bcvsolutions.idm.icf.service.api.IcfConnectorFacade;
import eu.bcvsolutions.idm.security.api.domain.GuardedString;
/**
* Service for do provisioning or synchronisation or reconciliation
*
* @author svandav
*
*/
@Service
public class DefaultSysProvisioningService implements SysProvisioningService {
public static final String PASSWORD_IDM_PROPERTY_NAME = "password";
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultSysProvisioningService.class);
private final SysSystemEntityHandlingService entityHandlingService;
private final SysSchemaAttributeHandlingService attributeHandlingService;
private final IcfConnectorFacade connectorFacade;
private final SysSystemService systemService;
private final AccIdentityAccountService identityAccountService;
private final ConfidentialStorage confidentialStorage;
private final FormService formService;
private final SysRoleSystemService roleSystemService;
private final AccAccountManagementService accountManagementService;
private final SysRoleSystemAttributeService roleSystemAttributeService;
private final SysSystemEntityService systemEntityService;
private final AccAccountService accountService;
@Autowired
public DefaultSysProvisioningService(SysSystemEntityHandlingService entityHandlingService,
SysSchemaAttributeHandlingService attributeHandlingService, IcfConnectorFacade connectorFacade,
SysSystemService systemService, ConfidentialStorage confidentialStorage, FormService formService,
SysRoleSystemService roleSystemService, AccAccountManagementService accountManagementService,
SysRoleSystemAttributeService roleSystemAttributeService, SysSystemEntityService systemEntityService,
AccAccountService accountService, AccIdentityAccountService identityAccountService) {
Assert.notNull(entityHandlingService);
Assert.notNull(attributeHandlingService);
Assert.notNull(connectorFacade);
Assert.notNull(systemService);
Assert.notNull(confidentialStorage);
Assert.notNull(formService);
Assert.notNull(roleSystemService);
Assert.notNull(accountManagementService);
Assert.notNull(roleSystemAttributeService);
Assert.notNull(systemEntityService);
Assert.notNull(accountService);
Assert.notNull(identityAccountService);
this.entityHandlingService = entityHandlingService;
this.attributeHandlingService = attributeHandlingService;
this.connectorFacade = connectorFacade;
this.systemService = systemService;
this.confidentialStorage = confidentialStorage;
this.formService = formService;
this.roleSystemService = roleSystemService;
this.accountManagementService = accountManagementService;
this.roleSystemAttributeService = roleSystemAttributeService;
this.systemEntityService = systemEntityService;
this.accountService = accountService;
this.identityAccountService = identityAccountService;
}
@Override
public void doProvisioning(IdmIdentity identity) {
Assert.notNull(identity);
IdentityAccountFilter filter = new IdentityAccountFilter();
filter.setIdentityId(identity.getId());
Page<AccIdentityAccount> identityAccounts = identityAccountService.find(filter, null);
List<AccIdentityAccount> idenityAccoutnList = identityAccounts.getContent();
if (idenityAccoutnList == null) {
return;
}
List<AccAccount> accounts = new ArrayList<>();
idenityAccoutnList.stream().filter(ia -> {
return ia.isOwnership();
}).forEach((identityAccount) -> {
if (!accounts.contains(identityAccount.getAccount())) {
accounts.add(identityAccount.getAccount());
}
});
accounts.stream().forEach(account -> {
this.doProvisioning(account, identity);
});
}
@Override
public void doDeleteProvisioning(AccAccount account) {
Assert.notNull(account);
SysSystem system = account.getSystem();
String uid = account.getUid();
SysSystemEntity systemEntity = account.getSystemEntity();
if (systemEntity != null && account.getUid() != null) {
uid = systemEntity.getUid();
}
doOperation(uid, null, AccountOperationType.DELETE, SystemOperationType.PROVISIONING,
SystemEntityType.IDENTITY, system, null);
// We successfully deleted account on target system.
// If SysSystemEntity exist, we delete him.
if(systemEntity != null){
systemEntityService.delete(systemEntity);
}
}
@Override
public void doProvisioning(AccAccount account) {
Assert.notNull(account);
IdentityAccountFilter filter = new IdentityAccountFilter();
filter.setAccountId(account.getId());
Page<AccIdentityAccount> identityAccounts = identityAccountService.find(filter, null);
List<AccIdentityAccount> idenittyAccoutnList = identityAccounts.getContent();
if (idenittyAccoutnList == null) {
return;
}
idenittyAccoutnList.stream().filter(identityAccount -> {
return identityAccount.isOwnership();
}).forEach((identityAccount) -> {
doProvisioning(account, identityAccount.getIdentity());
});
}
@Override
public void doProvisioning(AccAccount account, IdmIdentity identity) {
Assert.notNull(account);
Assert.notNull(identity);
// TODO: remove this after remove list form account. List not contains current data (can contains deleted items)
account.setIdentityAccounts(null);
SysSystem system = account.getSystem();
SysSystemEntity systemEntity = account.getSystemEntity();
// find uid from system entity or form account
String uid = getRealUid(account);
IdentityAccountFilter filter = new IdentityAccountFilter();
filter.setIdentityId(identity.getId());
filter.setSystemId(system.getId());
filter.setOwnership(Boolean.TRUE);
filter.setAccountId(account.getId());
Page<AccIdentityAccount> identityAccounts = identityAccountService.find(filter, null);
List<AccIdentityAccount> idenityAccoutnList = identityAccounts.getContent();
if (idenityAccoutnList == null) {
return;
}
SystemOperationType operationType = SystemOperationType.PROVISIONING;
SystemEntityType entityType = SystemEntityType.IDENTITY;
// All identity account with flag ownership on true
// All role system attributes (overloading) for this uid and same system
List<SysRoleSystemAttribute> roleSystemAttributesAll = findOverloadingAttributes(uid, identity, system,
idenityAccoutnList, operationType, entityType);
// All default mapped attributes from system
List<? extends MappingAttribute> defaultAttributes = findAttributesHandling(operationType, entityType, system);
// Final list of attributes use for provisioning
List<MappingAttribute> finalAttributes = compileAttributes(defaultAttributes, roleSystemAttributesAll);
String uidFromOperation = doOperation(uid, identity, AccountOperationType.UPDATE, operationType, entityType, system,
finalAttributes);
if (systemEntity == null) {
systemEntity = new SysSystemEntity();
systemEntity.setEntityType(SystemEntityType.IDENTITY);
systemEntity.setSystem(system);
}
account.setSystemEntity(systemEntity);
systemEntity.setUid(uidFromOperation);
systemEntityService.save(systemEntity);
accountService.save(account);
}
@Override
public void fillOverloadedAttribute(SysRoleSystemAttribute overloadingAttribute,
MappingAttribute overloadedAttribute) {
overloadedAttribute.setName(overloadingAttribute.getName());
overloadedAttribute.setEntityAttribute(overloadingAttribute.isEntityAttribute());
overloadedAttribute.setConfidentialAttribute(overloadingAttribute.isConfidentialAttribute());
overloadedAttribute.setExtendedAttribute(overloadingAttribute.isExtendedAttribute());
overloadedAttribute.setIdmPropertyName(overloadingAttribute.getIdmPropertyName());
overloadedAttribute.setTransformToResourceScript(overloadingAttribute.getTransformScript());
overloadedAttribute.setUid(overloadingAttribute.isUid());
overloadedAttribute.setDisabledAttribute(overloadingAttribute.isDisabledDefaultAttribute());
}
@Override
public void changePassword(IdmIdentity identity, PasswordChangeDto passwordChange) {
Assert.notNull(identity);
Assert.notNull(passwordChange);
IdentityAccountFilter filter = new IdentityAccountFilter();
filter.setIdentityId(identity.getId());
Page<AccIdentityAccount> identityAccounts = identityAccountService.find(filter, null);
List<AccIdentityAccount> identityAccountList = identityAccounts.getContent();
if (identityAccountList == null) {
return;
}
// TODO: ? add into IdentityAccountFilter: accountId IN (..., ...);
identityAccountList.stream().filter(identityAccount -> {
return identityAccount.isOwnership() && (passwordChange.isAll() || passwordChange.getAccounts().contains(identityAccount.getId().toString()));
}).forEach(identityAccount -> {
// find uid from system entity or form account
String uid = getRealUid(identityAccount.getAccount());
doProvisioningForAttribute(uid, PASSWORD_IDM_PROPERTY_NAME,
passwordChange.getNewPassword(), identityAccount.getAccount().getSystem(),
AccountOperationType.UPDATE, SystemEntityType.IDENTITY, identity);
});
}
@Override
public void doProvisioningForAttribute(String uid, String idmPropertyName, Object value, SysSystem system,
AccountOperationType operationType, SystemEntityType entityType, AbstractEntity entity) {
Assert.notNull(uid);
Assert.notNull(system);
Assert.notNull(entityType);
List<? extends MappingAttribute> attributes = findAttributesHandling(SystemOperationType.PROVISIONING,
entityType, system);
if (attributes == null || attributes.isEmpty()) {
return;
}
// Find connector identification persisted in system
IcfConnectorKey connectorKey = system.getConnectorKey();
if (connectorKey == null) {
throw new ProvisioningException(AccResultCode.CONNECTOR_KEY_FOR_SYSTEM_NOT_FOUND,
ImmutableMap.of("system", system.getName()));
}
// Find connector configuration persisted in system
IcfConnectorConfiguration connectorConfig = systemService.getConnectorConfiguration(system);
if (connectorConfig == null) {
throw new ProvisioningException(AccResultCode.CONNECTOR_CONFIGURATION_FOR_SYSTEM_NOT_FOUND,
ImmutableMap.of("system", system.getName()));
}
IcfUidAttribute uidAttribute = new IcfUidAttributeImpl(null, uid, null);
Optional<? extends MappingAttribute> attriubuteHandlingOptional = attributes.stream().filter((attribute) -> {
return idmPropertyName.equals(attribute.getIdmPropertyName());
}).findFirst();
if (!attriubuteHandlingOptional.isPresent()) {
throw new ProvisioningException(AccResultCode.PROVISIONING_IDM_FIELD_NOT_FOUND,
ImmutableMap.of("property", idmPropertyName, "uid", uid));
}
MappingAttribute attributeHandling = attriubuteHandlingOptional.get();
if (!attributeHandling.getSchemaAttribute().isUpdateable()) {
throw new ProvisioningException(AccResultCode.PROVISIONING_SCHEMA_ATTRIBUTE_IS_NOT_UPDATEABLE,
ImmutableMap.of("property", idmPropertyName, "uid", uid));
}
String objectClassName = attributeHandling.getSchemaAttribute().getObjectClass().getObjectClassName();
IcfAttribute icfAttributeForCreate = createIcfAttribute(attributeHandling, value, entity);
IcfObjectClass icfObjectClass = new IcfObjectClassImpl(objectClassName);
// Call icf modul for update single attribute
connectorFacade.updateObject(connectorKey, connectorConfig, icfObjectClass, uidAttribute,
ImmutableList.of(icfAttributeForCreate));
}
@Override
public IcfUidAttribute authenticate(AccIdentityAccount identityAccount, SysSystem system) {
GuardedString password = confidentialStorage.getGuardedString(identityAccount.getIdentity(),
IdmIdentityService.CONFIDENTIAL_PROPERTY_PASSWORD);
if (password == null) {
password = new GuardedString(); // TODO: empty password or null?
}
return authenticate(identityAccount.getAccount().getUid(), password, system, SystemOperationType.PROVISIONING,
SystemEntityType.IDENTITY);
}
@Override
public IcfUidAttribute authenticate(String username, GuardedString password, SysSystem system,
SystemOperationType operationType, SystemEntityType entityType) {
Assert.notNull(username);
Assert.notNull(system);
Assert.notNull(entityType);
Assert.notNull(operationType);
List<? extends MappingAttribute> attributes = findAttributesHandling(operationType, entityType, system);
if (attributes == null || attributes.isEmpty()) {
return null;
}
// Find connector identification persisted in system
IcfConnectorKey connectorKey = system.getConnectorKey();
if (connectorKey == null) {
throw new ProvisioningException(AccResultCode.CONNECTOR_KEY_FOR_SYSTEM_NOT_FOUND,
ImmutableMap.of("system", system.getName()));
}
// Find connector configuration persisted in system
IcfConnectorConfiguration connectorConfig = systemService.getConnectorConfiguration(system);
if (connectorConfig == null) {
throw new ProvisioningException(AccResultCode.CONNECTOR_CONFIGURATION_FOR_SYSTEM_NOT_FOUND,
ImmutableMap.of("system", system.getName()));
}
// Find attribute handling mapped on schema password attribute
Optional<? extends MappingAttribute> passwordAttributeHandlingOptional = attributes.stream()
.filter((attribute) -> {
return IcfConnectorFacade.PASSWORD_ATTRIBUTE_NAME.equals(attribute.getSchemaAttribute().getName());
}).findFirst();
if (!passwordAttributeHandlingOptional.isPresent()) {
throw new ProvisioningException(AccResultCode.PROVISIONING_IDM_FIELD_NOT_FOUND,
ImmutableMap.of("property", IcfConnectorFacade.PASSWORD_ATTRIBUTE_NAME, "uid", username));
}
MappingAttribute passwordAttributeHandling = passwordAttributeHandlingOptional.get();
String objectClassName = passwordAttributeHandling.getSchemaAttribute().getObjectClass().getObjectClassName();
IcfObjectClass icfObjectClass = new IcfObjectClassImpl(objectClassName);
// Call ICF module for check authenticate
return connectorFacade.authenticateObject(connectorKey, connectorConfig, icfObjectClass, username, password);
}
/**
* Create final list of attributes for provisioning.
*
* @param identityAccount
* @param defaultAttributes
* @param overloadingAttributes
* @return
*/
private List<MappingAttribute> compileAttributes(List<? extends MappingAttribute> defaultAttributes,
List<SysRoleSystemAttribute> overloadingAttributes) {
List<MappingAttribute> finalAttributes = new ArrayList<>();
if (defaultAttributes == null) {
return null;
}
defaultAttributes.stream().forEach(defaultAttribute -> {
Optional<SysRoleSystemAttribute> overloadingAttributeOptional = overloadingAttributes.stream()
.filter(roleSystemAttribute -> {
// Search attribute override same schema attribute
return roleSystemAttribute.getSchemaAttributeHandling().equals(defaultAttribute);
}).sorted((att1, att2) -> {
// Sort attributes by role name
return att2.getRoleSystem().getRole().getName()
.compareTo(att1.getRoleSystem().getRole().getName());
}).findFirst();
if (overloadingAttributeOptional.isPresent()) {
SysRoleSystemAttribute overloadingAttribute = overloadingAttributeOptional.get();
// Disabled attribute will be skipped
if (!overloadingAttribute.isDisabledDefaultAttribute()) {
// We can't use instance of SchemaAttributeHandling and set
// up overloaded value (it is entity).
// We have to create own dto and set up all values
// (overloaded and default)
MappingAttribute overloadedAttribute = new MappingAttributeDto();
// Default values (values from schema attribute
// handling)
overloadedAttribute.setSchemaAttribute(defaultAttribute.getSchemaAttribute());
overloadedAttribute
.setTransformFromResourceScript(defaultAttribute.getTransformFromResourceScript());
// Overloaded values
fillOverloadedAttribute(overloadingAttribute, overloadedAttribute);
// Add modified attribute to final list
finalAttributes.add(overloadedAttribute);
}
} else {
// We don't have overloading attribute, we will use default
// If is default attribute disabled, then we don't use him
if (!defaultAttribute.isDisabledAttribute()) {
finalAttributes.add(defaultAttribute);
}
}
});
return finalAttributes;
}
/**
* Return list of all overloading attributes for given identity, system and
* uid
*
* @param identityAccount
* @param uid
* @param idenityAccoutnList
* @param operationType
* @param entityType
* @return
*/
private List<SysRoleSystemAttribute> findOverloadingAttributes(String uid, IdmIdentity identity, SysSystem system,
List<AccIdentityAccount> idenityAccoutnList, SystemOperationType operationType,
SystemEntityType entityType) {
List<SysRoleSystemAttribute> roleSystemAttributesAll = new ArrayList<>();
idenityAccoutnList.stream().filter(ia -> {
return ia.getIdentityRole() != null && ia.getAccount().getSystem() != null
&& ia.getAccount().getSystem().equals(system)
&& ia.isOwnership();
}).forEach((identityAccountInner) -> {
// All identity account with same system and with filled
// identityRole
IdmIdentityRole identityRole = identityAccountInner.getIdentityRole();
RoleSystemFilter roleSystemFilter = new RoleSystemFilter();
roleSystemFilter.setRoleId(identityRole.getRole().getId());
roleSystemFilter.setSystemId(identityAccountInner.getAccount().getSystem().getId());
List<SysRoleSystem> roleSystems = roleSystemService.find(roleSystemFilter, null).getContent();
List<SysRoleSystem> roleSystemsForSameAccount = roleSystems.stream().filter(roleSystem -> {
String roleSystemUID = accountManagementService.generateUID(identity, roleSystem);
SysSystemEntityHandling entityHandling = roleSystem.getSystemEntityHandling();
return (operationType == entityHandling.getOperationType()
&& entityType == entityHandling.getEntityType() && roleSystemUID.equals(uid));
}).collect(Collectors.toList());
if (roleSystemsForSameAccount.size() > 1) {
throw new ProvisioningException(AccResultCode.PROVISIONING_DUPLICATE_ROLE_MAPPING,
ImmutableMap.of("role", roleSystemsForSameAccount.get(0).getRole().getName(), "system",
roleSystemsForSameAccount.get(0).getSystem().getName(), "entityType", entityType));
}
if (!roleSystemsForSameAccount.isEmpty()) {
RoleSystemAttributeFilter roleSystemAttributeFilter = new RoleSystemAttributeFilter();
roleSystemAttributeFilter.setRoleSystemId(roleSystemsForSameAccount.get(0).getId());
List<SysRoleSystemAttribute> roleAttributes = roleSystemAttributeService
.find(roleSystemAttributeFilter, null).getContent();
if (!CollectionUtils.isEmpty(roleAttributes)) {
roleSystemAttributesAll.addAll(roleAttributes);
}
}
});
return roleSystemAttributesAll;
}
/**
* Do provisioning/synchronisation/reconciliation on given system for given
* entity
*
* @param uid
* @param entity
* @param provisioningType
* @param entityType
* @param system
*/
public String doOperation(String uid, AbstractEntity entity, AccountOperationType operationType,
SystemOperationType provisioningType, SystemEntityType entityType, SysSystem system,
List<? extends MappingAttribute> attributes) {
Assert.notNull(uid);
Assert.notNull(provisioningType);
Assert.notNull(system);
Assert.notNull(entityType);
// If are input attributes null, then we load default mapped attributes
if (attributes == null) {
attributes = findAttributesHandling(provisioningType, entityType, system);
}
if (attributes == null || attributes.isEmpty()) {
return uid;
}
// Find connector identification persisted in system
IcfConnectorKey connectorKey = system.getConnectorKey();
if (connectorKey == null) {
throw new ProvisioningException(AccResultCode.CONNECTOR_KEY_FOR_SYSTEM_NOT_FOUND,
ImmutableMap.of("system", system.getName()));
}
// Find connector configuration persisted in system
IcfConnectorConfiguration connectorConfig = systemService.getConnectorConfiguration(system);
if (connectorConfig == null) {
throw new ProvisioningException(AccResultCode.CONNECTOR_CONFIGURATION_FOR_SYSTEM_NOT_FOUND,
ImmutableMap.of("system", system.getName()));
}
IcfUidAttribute uidAttribute = new IcfUidAttributeImpl(null, uid, null);
Map<String, IcfConnectorObject> objectByClassMap = new HashMap<>();
for (MappingAttribute ah : attributes) {
String objectClassName = ah.getSchemaAttribute().getObjectClass().getObjectClassName();
if (!objectByClassMap.containsKey(objectClassName)) {
IcfObjectClass icfObjectClass = new IcfObjectClassImpl(objectClassName);
IcfConnectorObject connectorObject = connectorFacade.readObject(connectorKey, connectorConfig,
icfObjectClass, uidAttribute);
objectByClassMap.put(objectClassName, connectorObject);
}
}
if (SystemOperationType.PROVISIONING == provisioningType) {
// Provisioning
return doProvisioning(uid, entity, operationType, attributes, connectorKey, connectorConfig,
objectByClassMap);
} else {
// TODO Synchronisation or reconciliation
}
return uid;
}
/**
* Find list of {@link SysSchemaAttributeHandling} by provisioning type and
* entity type on given system
*
* @param provisioningType
* @param entityType
* @param system
* @return
*/
private List<? extends MappingAttribute> findAttributesHandling(SystemOperationType provisioningType,
SystemEntityType entityType, SysSystem system) {
List<SysSystemEntityHandling> entityHandlingList = entityHandlingService.findBySystem(system, provisioningType,
entityType);
if (entityHandlingList == null || entityHandlingList.size() != 1) {
return null;
}
SysSystemEntityHandling entityHandling = entityHandlingList.get(0);
List<SysSchemaAttributeHandling> attributes = attributeHandlingService.findByEntityHandling(entityHandling);
return attributes;
}
/**
* Do provisioning for given entity
*
* @param uid
* @param entity
* @param attributes
* @param connectorKey
* @param connectorConfig
* @param uidAttribute
* @param objectByClassMap
*/
private String doProvisioning(String uid, AbstractEntity entity, AccountOperationType operationType,
List<? extends MappingAttribute> attributes, IcfConnectorKey connectorKey,
IcfConnectorConfiguration connectorConfig, Map<String, IcfConnectorObject> objectByClassMap) {
Map<String, IcfConnectorObject> objectByClassMapForUpdate = new HashMap<>();
Map<String, IcfConnectorObject> objectByClassMapForCreate = new HashMap<>();
Map<String, IcfConnectorObject> objectByClassMapForDelete = new HashMap<>();
IcfUidAttribute uidAttribute = new IcfUidAttributeImpl(null, uid, null);
// One IDM account can be mapped to more then one connector object (on
// more connector class).
// We have to iterate via all mapped attribute and do operation for all
// object class
for (MappingAttribute attributeHandling : attributes) {
SysSchemaAttribute schemaAttribute = attributeHandling.getSchemaAttribute();
String objectClassName = schemaAttribute.getObjectClass().getObjectClassName();
IcfConnectorObject connectorObject = objectByClassMap.get(objectClassName);
if (AccountOperationType.UPDATE == operationType && connectorObject == null) {
/**
* Create new connector object for this object class
*/
IcfConnectorObject connectorObjectForCreate = initConnectorObject(objectByClassMapForCreate,
objectClassName);
createAttribute(uid, entity, connectorObjectForCreate, attributeHandling, schemaAttribute,
objectClassName);
} else if (AccountOperationType.UPDATE == operationType && connectorObject != null) {
/**
* Update connector object
*/
if (schemaAttribute.isUpdateable()) {
if (!schemaAttribute.isReturnedByDefault()) {
// TODO update for attributes not returned by default
// (for example __PASSWORD__)
} else {
// Update attribute on resource by given handling
// attribute and mapped value in entity
updateAttribute(uid, entity, objectByClassMapForUpdate, attributeHandling, schemaAttribute,
objectClassName, connectorObject);
}
}
} else if (AccountOperationType.DELETE == operationType) {
/**
* Delete connector object for this object class
*/
if (connectorObject != null && !objectByClassMapForDelete.containsKey(objectClassName)) {
objectByClassMapForDelete.put(objectClassName, connectorObject);
}
}
}
final List<String> uids = new ArrayList<>();
// call create on ICF module
objectByClassMapForCreate.forEach((objectClassName, connectorObject) -> {
LOG.debug("Provisioning - create object with uid {} and connector object {}", uid,
connectorObject.getObjectClass().getType());
IcfUidAttribute icfUid = connectorFacade.createObject(connectorKey, connectorConfig,
connectorObject.getObjectClass(), connectorObject.getAttributes());
if (icfUid != null && icfUid.getUidValue() != null) {
uids.add(icfUid.getUidValue());
}
});
// call update on ICF module
objectByClassMapForUpdate.forEach((objectClassName, connectorObject) -> {
LOG.debug("Provisioning - update object with uid {} and connector object {}", uid,
connectorObject.getObjectClass().getType());
IcfUidAttribute icfUid = connectorFacade.updateObject(connectorKey, connectorConfig,
connectorObject.getObjectClass(), uidAttribute, connectorObject.getAttributes());
if (icfUid != null && icfUid.getUidValue() != null) {
uids.add(icfUid.getUidValue());
}
});
// call delete on ICF module
objectByClassMapForDelete.forEach((objectClassName, connectorObject) -> {
LOG.debug("Provisioning - delete object with uid {} and connector object {}", uid,
connectorObject.getObjectClass().getType());
connectorFacade.deleteObject(connectorKey, connectorConfig, connectorObject.getObjectClass(), uidAttribute);
});
// We have to validate returned uids form connector.
// Different uids are inconsistent state, we will throw exception
if (uids.isEmpty()) {
return uid;
}
final String firstUidConnector = uids.get(0);
boolean foundDiffUid = uids.stream().filter(uidConnector -> {
return !uidConnector.equals(firstUidConnector);
}).findFirst().isPresent();
if (foundDiffUid) {
throw new ProvisioningException(AccResultCode.PROVISIONING_DIFFERENT_UIDS_FROM_CONNECTOR,
ImmutableMap.of("uid", uid, "connectorUids", uids));
}
return firstUidConnector;
}
/**
* Return connector object from map by object class. If object for object
* class is missing, then will be create.
*
* @param objectByClassMap
* @param objectClassName
* @return
*/
private IcfConnectorObject initConnectorObject(Map<String, IcfConnectorObject> objectByClassMap,
String objectClassName) {
IcfConnectorObject connectorObject = null;
if (objectByClassMap != null) {
connectorObject = objectByClassMap.get(objectClassName);
}
if (connectorObject == null) {
IcfObjectClass ioc = new IcfObjectClassImpl(objectClassName);
connectorObject = new IcfConnectorObjectImpl(ioc, null);
if (objectByClassMap != null) {
objectByClassMap.put(objectClassName, connectorObject);
}
}
return connectorObject;
}
/**
* Create ICF attribute by schema attribute. ICF attribute will be set with
* value obtained form given entity. This value will be transformed to
* system value first.
*
* @param uid
* @param entity
* @param connectorObjectForCreate
* @param attributeHandling
* @param schemaAttribute
* @param objectClassName
*/
private void createAttribute(String uid, AbstractEntity entity, IcfConnectorObject connectorObjectForCreate,
MappingAttribute attributeHandling, SysSchemaAttribute schemaAttribute, String objectClassName) {
if (schemaAttribute.isCreateable()) {
try {
Object idmValue = getAttributeValue(uid, entity, attributeHandling);
IcfAttribute icfAttributeForCreate = createIcfAttribute(attributeHandling, idmValue, entity);
connectorObjectForCreate.getAttributes().add(icfAttributeForCreate);
} catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new ProvisioningException(AccResultCode.PROVISIONING_IDM_FIELD_NOT_FOUND,
ImmutableMap.of("uid", uid, "property", attributeHandling.getIdmPropertyName()), e);
}
}
}
/**
* Update attribute on resource by given handling attribute and mapped value
* in entity
*
* @param uid
* @param entity
* @param objectByClassMapForUpdate
* @param attributeHandling
* @param schemaAttribute
* @param objectClassName
* @param connectorObject
*/
private void updateAttribute(String uid, AbstractEntity entity,
Map<String, IcfConnectorObject> objectByClassMapForUpdate, MappingAttribute attributeHandling,
SysSchemaAttribute schemaAttribute, String objectClassName, IcfConnectorObject connectorObject) {
List<IcfAttribute> icfAttributes = connectorObject.getAttributes();
Optional<IcfAttribute> icfAttributeOptional = icfAttributes.stream().filter(icfa -> {
return schemaAttribute.getName().equals(icfa.getName());
}).findFirst();
IcfAttribute icfAttribute = null;
if (icfAttributeOptional.isPresent()) {
icfAttribute = icfAttributeOptional.get();
}
updateAttributeValue(uid, entity, objectByClassMapForUpdate, attributeHandling, objectClassName,
icfAttribute, icfAttributes);
}
/**
* Check difference of attribute value on resource and in entity for given
* attribute. When is value changed, then add update of this attribute to
* map
*
* @param uid
* @param entity
* @param objectByClassMapForUpdate
* @param attributeHandling
* @param objectClassName
* @param icfAttribute
*/
private void updateAttributeValue(String uid, AbstractEntity entity,
Map<String, IcfConnectorObject> objectByClassMapForUpdate, MappingAttribute attributeHandling,
String objectClassName, IcfAttribute icfAttribute, List<IcfAttribute> icfAttributes) {
Object icfValueTransformed = null;
if (attributeHandling.getSchemaAttribute().isMultivalued()) {
// Multi value
List<Object> icfValues = icfAttribute != null ? icfAttribute.getValues() : null;
icfValueTransformed = attributeHandlingService.transformValueFromResource(icfValues, attributeHandling,
icfAttributes);
} else {
// Single value
Object icfValue = icfAttribute != null ? icfAttribute.getValue() : null;
icfValueTransformed = attributeHandlingService.transformValueFromResource(icfValue, attributeHandling,
icfAttributes);
}
try {
Object idmValue = getAttributeValue(uid, entity, attributeHandling);
if (!Objects.equals(idmValue, icfValueTransformed)) {
// values is not equals
IcfAttribute icfAttributeForUpdate = createIcfAttribute(attributeHandling, idmValue, entity);
IcfConnectorObject connectorObjectForUpdate = initConnectorObject(objectByClassMapForUpdate,
objectClassName);
connectorObjectForUpdate.getAttributes().add(icfAttributeForUpdate);
}
} catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new ProvisioningException(AccResultCode.PROVISIONING_IDM_FIELD_NOT_FOUND,
ImmutableMap.of("uid", uid, "property", attributeHandling.getIdmPropertyName()), e);
}
}
private Object getAttributeValue(String uid, AbstractEntity entity, MappingAttribute attributeHandling)
throws IntrospectionException, IllegalAccessException, InvocationTargetException {
if (attributeHandling.isExtendedAttribute()) {
// TODO: new method to form service to read concrete attribute definition
IdmFormAttribute defAttribute = formService.getDefinition(((FormableEntity) entity).getClass())
.getMappedAttributeByName(attributeHandling.getIdmPropertyName());
if (defAttribute == null) {
// eav definition could be changed
LOG.warn("Form attribute defininion [{}] was not found, returning null", attributeHandling.getIdmPropertyName());
return null;
}
List<AbstractFormValue<FormableEntity>> formValues = formService.getValues((FormableEntity) entity,
defAttribute.getFormDefinition(), defAttribute.getName());
if (formValues.isEmpty()) {
return null;
}
if(defAttribute.isMultiple()){
// Multivalue extended attribute
List<Object> values = new ArrayList<>();
formValues.stream().forEachOrdered(formValue -> {
values.add(formValue.getValue());
});
return values;
}else{
// Singlevalue extended attribute
AbstractFormValue<FormableEntity> formValue = formValues.get(0);
if (formValue.isConfidential()) {
return formService.getConfidentialPersistentValue(formValue);
}
return formValue.getValue();
}
}
// Find value from entity
if (attributeHandling.isEntityAttribute()) {
if (attributeHandling.isConfidentialAttribute()) {
// If is attribute isConfidential, then we will find value in
// secured storage
return confidentialStorage.getGuardedString(entity, attributeHandling.getIdmPropertyName());
}
// We will search value directly in entity by property name
return getEntityValue(entity, attributeHandling.getIdmPropertyName());
}
// Attribute value is not in entity nor in extended attribute.
// It means attribute is static ... we will call transformation to resource.
return attributeHandlingService.transformValueToResource(null, attributeHandling, entity);
}
/**
* Create instance of ICF attribute for given name. Given idm value will be
* transformed to resource.
*
* @param attributeHandling
* @param icfAttribute
* @param idmValue
* @param entity
* @return
*/
private IcfAttribute createIcfAttribute(MappingAttribute attributeHandling, Object idmValue,
AbstractEntity entity) {
Object idmValueTransformed = null;
if(!attributeHandling.isEntityAttribute() && !attributeHandling.isExtendedAttribute()){
// If is attribute handling resolve as constant, then we don't want do transformation again (was did in getAttributeValue)
idmValueTransformed = idmValue;
} else {
idmValueTransformed = attributeHandlingService.transformValueToResource(idmValue, attributeHandling,
entity);
}
SysSchemaAttribute schemaAttribute = attributeHandling.getSchemaAttribute();
// Check type of value
try {
Class<?> classType = Class.forName(schemaAttribute.getClassType());
// If is multivalue and value is list, then we will iterate list and check every item on correct type
if (schemaAttribute.isMultivalued() && idmValueTransformed instanceof List){
((List<?>)idmValueTransformed).stream().forEachOrdered(value ->{
if (value != null && !(classType.isAssignableFrom(value.getClass()))) {
throw new ProvisioningException(AccResultCode.PROVISIONING_ATTRIBUTE_VALUE_WRONG_TYPE,
ImmutableMap.of("attribute", attributeHandling.getIdmPropertyName(), "schemaAttributeType",
schemaAttribute.getClassType(), "valueType", value.getClass().getName()));
}
});
// Check single value on correct type
}else if (idmValueTransformed != null && !(classType.isAssignableFrom(idmValueTransformed.getClass()))) {
throw new ProvisioningException(AccResultCode.PROVISIONING_ATTRIBUTE_VALUE_WRONG_TYPE,
ImmutableMap.of("attribute", attributeHandling.getIdmPropertyName(), "schemaAttributeType",
schemaAttribute.getClassType(), "valueType", idmValueTransformed.getClass().getName()));
}
} catch (ClassNotFoundException e) {
throw new ProvisioningException(AccResultCode.PROVISIONING_ATTRIBUTE_TYPE_NOT_FOUND,
ImmutableMap.of("attribute", attributeHandling.getIdmPropertyName(), "schemaAttributeType",
schemaAttribute.getClassType()),
e);
}
IcfAttribute icfAttributeForUpdate = null;
if (IcfConnectorFacade.PASSWORD_ATTRIBUTE_NAME.equals(schemaAttribute.getName())) {
// Attribute is password type
icfAttributeForUpdate = new IcfPasswordAttributeImpl((GuardedString) idmValueTransformed);
} else {
if(idmValueTransformed instanceof List){
@SuppressWarnings("unchecked")
List<Object> values = (List<Object>)idmValueTransformed;
icfAttributeForUpdate = new IcfAttributeImpl(schemaAttribute.getName(), values, true);
}else{
icfAttributeForUpdate = new IcfAttributeImpl(schemaAttribute.getName(), idmValueTransformed);
}
}
return icfAttributeForUpdate;
}
private Object getEntityValue(AbstractEntity entity, String propertyName)
throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Optional<PropertyDescriptor> propertyDescriptionOptional = Arrays
.asList(Introspector.getBeanInfo(entity.getClass(), AbstractEntity.class).getPropertyDescriptors())
.stream().filter(propertyDescriptor -> {
return propertyName.equals(propertyDescriptor.getName());
}).findFirst();
if (!propertyDescriptionOptional.isPresent()) {
throw new IllegalAccessException("Field " + propertyName + " not found!");
}
PropertyDescriptor propertyDescriptor = propertyDescriptionOptional.get();
return propertyDescriptor.getReadMethod().invoke(entity);
}
/**
* Return real uid from system entity.
* If system entity do not exist, then return uid from account.
* @param account
* @return
*/
private String getRealUid(AccAccount account){
Assert.notNull(account);
String uid = account.getUid();
SysSystemEntity systemEntity = account.getSystemEntity();
if (systemEntity != null && account.getUid() != null) {
uid = systemEntity.getUid();
}
return uid;
}
}
|
package org.eclipse.birt.report.designer.data.ui.util;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBaseDataSetDesign;
import org.eclipse.birt.data.engine.api.IBaseDataSourceDesign;
import org.eclipse.birt.data.engine.api.IJointDataSetDesign;
import org.eclipse.birt.data.engine.api.IPreparedQuery;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.api.IQueryResults;
import org.eclipse.birt.data.engine.api.IResultMetaData;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.ParameterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.report.data.adapter.api.DataRequestSession;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.designer.data.ui.dataset.DataSetViewData;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ScriptLibHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.elements.structures.ResultSetColumn;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
/**
*
* Utility class to get meta data and data from data set
*
*/
public final class DataSetProvider
{
private static final String BIRT_SCRIPTLIB = "/birt/scriptlib";
private static final String BIRT_CLASSES = "/birt/WEB-INF/classes/";
private static final String VIEWER_NAMESPACE = "org.eclipse.birt.report.viewer";
private static DataSetProvider instance = null;
// column hash table
private transient Hashtable htColumns = new Hashtable( 10 );
private static Hashtable htDataSourceExtensions = new Hashtable( 10 );
private transient Hashtable sessionTable = new Hashtable( 10 );
// constant value
private static final char RENAME_SEPARATOR = '_';
private static String UNNAME_PREFIX = "UNNAMED"; //$NON-NLS-1$
/**
* @return
*/
private static DataSetProvider newInstance( )
{
return new DataSetProvider( );
}
/**
*
* @return
*/
public static DataSetProvider getCurrentInstance( )
{
if ( instance == null )
instance = newInstance( );
return instance;
}
/**
* get columns data by data set name
* @param dataSetName
* @param refresh
* @return
*/
public DataSetViewData[] getColumns( String dataSetName, boolean refresh )
{
ModuleHandle handle = Utility.getReportModuleHandle( );
DataSetHandle dataSet = handle.findDataSet( dataSetName );
if ( dataSet == null )
{
return new DataSetViewData[]{};
}
return getColumns( dataSet, refresh );
}
/**
* get column data by data set handle
* @param dataSet
* @param refresh
* @return
*/
public DataSetViewData[] getColumns( DataSetHandle dataSet, boolean refresh )
{
return getColumns( dataSet, refresh, true, false );
}
/**
*
* @param dataSet
* @param refresh
* @param useColumnHints
* Only applicable if the list is refreshed.
* @return
*/
public DataSetViewData[] getColumns( DataSetHandle dataSet,
boolean refresh, boolean useColumnHints,
boolean suppressErrorMessage )
{
if ( dataSet == null )
{
return new DataSetViewData[0];
}
DataSetViewData[] columns = null;
try
{
DataSessionContext context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION,
dataSet.getModuleHandle( ) );
DataRequestSession session = DataRequestSession.newSession( context );
// Find the data set in the hashtable
columns = (DataSetViewData[]) htColumns.get( dataSet );
// If there are not cached get them from the column hints
if ( columns == null || refresh )
{
columns = this.populateAllOutputColumns( dataSet, session );
htColumns.put( dataSet, columns );
}
session.shutdown( );
}
catch ( BirtException e )
{
if ( !suppressErrorMessage )
{
ExceptionHandler.handle( e );
}
columns = null;
}
// If the columns array is still null
// just initialize it to an empty array
if ( columns == null )
{
columns = new DataSetViewData[]{};
//updateModel( dataSet, columns );
htColumns.put( dataSet, columns );
}
return columns;
}
/**
* populate all output columns in viewer display. The output columns is
* retrieved from oda dataset handles's RESULT_SET_PROP and
* COMPUTED_COLUMNS_PROP.
*
* @throws BirtException
*/
public DataSetViewData[] populateAllOutputColumns(
DataSetHandle dataSetHandle, DataRequestSession session ) throws BirtException
{
IResultMetaData metaData = session.getDataSetMetaData( dataSetHandle,
false );
if( metaData == null )
return new DataSetViewData[0];
DataSetViewData[] items = new DataSetViewData[metaData.getColumnCount( )];
for ( int i = 0; i < metaData.getColumnCount( ); i++ )
{
items[i] = new DataSetViewData( );
items[i].setName( metaData.getColumnName( i + 1 ) );
items[i].setDataTypeName( metaData.getColumnTypeName( i + 1 ) );
items[i].setAlias( metaData.getColumnAlias( i + 1 ) );
items[i].setComputedColumn( metaData.isComputedColumn( i + 1 ) );
items[i].setPosition( i + 1 );
items[i].setDataType( metaData.getColumnType( i + 1 ) );
}
updateModel( dataSetHandle, items );
return items;
}
/**
* get Cached metadata
*
* @throws BirtException
*/
public DataSetViewData[] populateAllCachedMetaData(
DataSetHandle dataSetHandle, DataRequestSession session )
throws BirtException
{
IResultMetaData metaData = session.getDataSetMetaData( dataSetHandle,
true );
DataSetViewData[] items = new DataSetViewData[metaData.getColumnCount( )];
for ( int i = 0; i < metaData.getColumnCount( ); i++ )
{
items[i] = new DataSetViewData( );
items[i].setName( metaData.getColumnName( i + 1 ) );
items[i].setDataTypeName( metaData.getColumnTypeName( i + 1 ) );
items[i].setAlias( metaData.getColumnAlias( i + 1 ) );
items[i].setComputedColumn( metaData.isComputedColumn( i + 1 ) );
items[i].setPosition( i + 1 );
items[i].setDataType( metaData.getColumnType( i + 1 ) );
}
return items;
}
/**
* update the columns of the DataSetHandle and put the new DataSetViewData[] into htColumns
*
* @param dataSet
* @param dsItemModel
*/
public void updateColumnsOfDataSetHandle( DataSetHandle dataSet,
DataSetViewData[] dsItemModel )
{
if ( dataSet == null || dsItemModel == null || dsItemModel.length == 0 )
return;
htColumns.put( dataSet, dsItemModel );
}
/**
* This function should be called very carefully. Presently it is only
* called in DataSetEditorDialog#performCancel.
*
* @param dataSet
* @param itemModel
*/
public void setModelOfDataSetHandle( DataSetHandle dataSet,
DataSetViewData[] dsItemModel )
{
if ( dataSet == null || dsItemModel == null )
return;
updateModel( dataSet, dsItemModel );
cleanUnusedResultSetColumn( dataSet, dsItemModel );
cleanUnusedComputedColumn( dataSet, dsItemModel );
htColumns.put( dataSet, dsItemModel );
}
/**
* To rollback original datasetHandle, clean unused resultset columm
*
* @param dataSetHandle
* @param dsItemModel
*/
private void cleanUnusedResultSetColumn( DataSetHandle dataSetHandle,
DataSetViewData[] dsItemModel )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( DataSetHandle.RESULT_SET_PROP );
if ( handle != null && handle.getListValue( ) != null )
{
ArrayList list = handle.getListValue( );
int count = list.size( );
for ( int n = count - 1; n >= 0; n
{
ResultSetColumn rsColumn = (ResultSetColumn) list.get( n );
String columnName = (String) rsColumn.getColumnName( );
boolean found = false;
for ( int m = 0; m < dsItemModel.length; m++ )
{
if ( columnName.equals( dsItemModel[m].getName( ) ) )
{
found = true;
break;
}
}
if ( !found )
{
try
{
// remove the item
handle.removeItem( rsColumn );
}
catch ( PropertyValueException e )
{
}
}
}
}
}
/**
* To rollback original datasetHandle, clean unused computed columm
*
* @param dataSetHandle
* @param dsItemModel
*/
private void cleanUnusedComputedColumn( DataSetHandle dataSetHandle,
DataSetViewData[] dsItemModel )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( DataSetHandle.COMPUTED_COLUMNS_PROP );
if ( handle != null && handle.getListValue( ) != null )
{
ArrayList list = handle.getListValue( );
int count = list.size( );
for ( int n = count - 1; n >= 0; n
{
ComputedColumn rsColumn = (ComputedColumn) list.get( n );
String columnName = (String) rsColumn.getName( );
boolean found = false;
for ( int m = 0; m < dsItemModel.length; m++ )
{
if ( columnName.equals( dsItemModel[m].getName( ) ) )
{
found = true;
break;
}
}
if ( !found )
{
try
{
// remove the item
handle.removeItem( rsColumn );
}
catch ( PropertyValueException e )
{
}
}
}
}
}
/**
* @param dataSet
* @return
* @throws BirtException
*/
public IQueryResults execute( DataSetHandle dataSet, DataRequestSession session ) throws BirtException
{
return execute( dataSet, true, true, -1, session );
}
/**
* execute query definition
* @param dataSet
* @param useColumnHints
* @param rowsToReturn
* @return
* @throws BirtException
*/
public IQueryResults execute( DataSetHandle dataSet,
boolean useColumnHints, boolean useFilters, int rowsToReturn,
DataRequestSession session ) throws BirtException
{
populateAllOutputColumns( dataSet, session );
IBaseDataSetDesign dataSetDesign = session.getModelAdaptor( )
.adaptDataSet( dataSet );
if ( !useColumnHints )
{
dataSetDesign.getResultSetHints( ).clear( );
}
if ( !useFilters )
{
dataSetDesign.getFilters( ).clear( );
}
QueryDefinition queryDefn = getQueryDefinition( dataSetDesign,
rowsToReturn );
IQueryResults resultSet = executeQuery( session, queryDefn );
saveResultToDataItems( dataSet, resultSet );
return resultSet;
}
/**
*
* @param dataSet
* @param queryDefn
* @param useColumnHints
* @param useFilters
* @return
* @throws BirtException
*/
public IQueryResults execute( DataSetHandle dataSet,
QueryDefinition queryDefn, boolean useColumnHints,
boolean useFilters, DataRequestSession session )
throws BirtException
{
return this.execute( dataSet,
queryDefn,
useColumnHints,
useFilters,
false,
session );
}
/**
*
* @param dataSet
* @param queryDefn
* @param useColumnHints
* @return
* @throws BirtException
*/
public IQueryResults execute( DataSetHandle dataSet,
IQueryDefinition queryDefn, boolean useColumnHints,
boolean useFilters, boolean clearCache,
DataRequestSession session ) throws BirtException
{
IBaseDataSetDesign dataSetDesign = session.getModelAdaptor( )
.adaptDataSet( dataSet );
if ( clearCache )
{
IBaseDataSourceDesign dataSourceDesign = session.getModelAdaptor( )
.adaptDataSource( dataSet.getDataSource( ) );
session.clearCache( dataSourceDesign, dataSetDesign );
}
if ( !useColumnHints )
{
dataSetDesign.getResultSetHints( ).clear( );
}
if ( !useFilters )
{
dataSetDesign.getFilters( ).clear( );
}
IQueryResults resultSet = executeQuery( session, queryDefn );
saveResultToDataItems( dataSet, resultSet );
return resultSet;
}
/**
*
* @param dataSet
* @param resultSet
* @throws BirtException
*/
private void saveResultToDataItems( DataSetHandle dataSet,
IQueryResults resultSet ) throws BirtException
{
// Get the metadata
IResultMetaData metaData = resultSet.getResultMetaData( );
// Put the columns into the hashtable
int columnCount = 0;
if ( metaData != null )
columnCount = metaData.getColumnCount( );
DataSetViewData[] columns = new DataSetViewData[columnCount];
// check whether the column name has been changed,due to changes in
// query text.
// clear modle resultsetColumn,then execute again.
// a Set of original column name
HashSet orgColumnNameSet = new HashSet( );
// a Set of new column name
HashSet uniqueColumnNameSet = new HashSet( );
for ( int n = 0; n < columns.length; n++ )
{
orgColumnNameSet.add( metaData.getColumnName( n + 1 ) );
}
for ( int n = 0; n < columns.length; n++ )
{
columns[n] = new DataSetViewData( );
columns[n].setParent( dataSet );
columns[n].setDataType( metaData.getColumnType( n + 1 ) );
columns[n].setDataTypeName( metaData.getColumnTypeName( n + 1 ) );
columns[n].setPosition( n + 1 );
columns[n].setAlias( metaData.getColumnAlias( n + 1 ) );
columns[n].setComputedColumn( metaData.isComputedColumn( n + 1 ) );
String columnName = metaData.getColumnName( n + 1 );
// give this column a unique name
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
n );
// Update the column in UI layer
columns[n].setDataSetColumnName( uniqueColumnName );
uniqueColumnNameSet.add( uniqueColumnName );
// Update the column in Model if necessary
if ( !uniqueColumnName.equals( columnName ) )
updateModelColumn( dataSet, columns[n] );
}
updateModel( dataSet, columns );
htColumns.put( dataSet, columns );
}
/**
*
* @param ds
* @param column
*/
private void updateModelColumn( DataSetHandle ds, DataSetViewData column )
{
PropertyHandle resultSetColumns = ds.getPropertyHandle( DataSetHandle.RESULT_SET_PROP );
if ( resultSetColumns == null )
return;
// update result set columns
Iterator iterator = resultSetColumns.iterator( );
if ( iterator == null )
return;
while ( iterator.hasNext( ) )
{
ResultSetColumnHandle rsColumnHandle = (ResultSetColumnHandle) iterator.next( );
assert rsColumnHandle.getPosition( ) != null;
if ( rsColumnHandle.getPosition( ).intValue( ) == column.getPosition( ) )
{
if ( rsColumnHandle.getColumnName( ) != null
&& !rsColumnHandle.getColumnName( )
.equals( column.getDataSetColumnName( ) ) )
{
try
{
rsColumnHandle.setColumnName( column.getDataSetColumnName( ) );
}
catch ( SemanticException e )
{
}
}
break;
}
}
}
/**
*
* @param session
* @param queryDefn
* @return
* @throws BirtException
*/
private IQueryResults executeQuery( DataRequestSession session,
IQueryDefinition queryDefn ) throws BirtException
{
IQueryResults resultSet = session.executeQuery( queryDefn,
null,
null,
null );
return resultSet;
}
/**
*
* @param dataSetDesign
* @param rowsToReturn
* @return
*/
public final QueryDefinition getQueryDefinition(
IBaseDataSetDesign dataSetDesign, int rowsToReturn )
{
if ( dataSetDesign != null )
{
QueryDefinition defn = new QueryDefinition( null );
defn.setDataSetName( dataSetDesign.getName( ) );
if ( rowsToReturn > 0 )
{
defn.setMaxRows( rowsToReturn );
}
List parameters = dataSetDesign.getParameters( );
Iterator iter = parameters.iterator( );
while ( iter.hasNext( ) )
{
ParameterDefinition paramDefn = (ParameterDefinition) iter.next( );
if ( paramDefn.isInputMode( ) )
{
if ( paramDefn.getDefaultInputValue( ) != null )
{
InputParameterBinding binding = new InputParameterBinding( paramDefn.getName( ),
new ScriptExpression( paramDefn.getDefaultInputValue( )
.toString( ) ) );
defn.addInputParamBinding( binding );
}
}
}
return defn;
}
return null;
}
/**
* @param dataSetDesign
* @param bindingParams
* @return
*/
public final QueryDefinition getQueryDefinition(
IBaseDataSetDesign dataSetDesign, ParamBindingHandle[] bindingParams )
{
return getQueryDefinition( dataSetDesign, bindingParams, -1 );
}
/**
* @param dataSetDesign
* @param bindingParams
* @param i
* @return
*/
private QueryDefinition getQueryDefinition(
IBaseDataSetDesign dataSetDesign,
ParamBindingHandle[] bindingParams, int rowsToReturn )
{
if ( bindingParams == null || bindingParams.length == 0 )
{
return getQueryDefinition( dataSetDesign, rowsToReturn );
}
if ( dataSetDesign != null )
{
QueryDefinition defn = new QueryDefinition( null );
defn.setDataSetName( dataSetDesign.getName( ) );
if ( rowsToReturn > 0 )
{
defn.setMaxRows( rowsToReturn );
}
for ( int i = 0; i < bindingParams.length; i++ )
{
ParamBindingHandle param = bindingParams[i];
InputParameterBinding binding = new InputParameterBinding( param.getParamName( ),
new ScriptExpression( param.getExpression( ) ) );
defn.addInputParamBinding( binding );
}
return defn;
}
return null;
}
/**
*
* @param orgColumnNameSet
* @param newColumnNameSet
* @param columnName
* @param index
* @return
*/
private String getUniqueName( HashSet orgColumnNameSet,
HashSet newColumnNameSet, String columnName, int index )
{
String newColumnName;
if ( columnName == null
|| columnName.trim( ).length( ) == 0
|| newColumnNameSet.contains( columnName ) )
{
// name conflict or no name,give this column a unique name
if ( columnName == null || columnName.trim( ).length( ) == 0 )
newColumnName = UNNAME_PREFIX
+ RENAME_SEPARATOR + String.valueOf( index + 1 );
else
newColumnName = columnName
+ RENAME_SEPARATOR + String.valueOf( index + 1 );
int i = 1;
while ( orgColumnNameSet.contains( newColumnName )
|| newColumnNameSet.contains( newColumnName ) )
{
newColumnName += String.valueOf( RENAME_SEPARATOR ) + i;
i++;
}
}
else
{
newColumnName = columnName;
}
return newColumnName;
}
/**
* @param ds
* @param columns
*/
public void updateModel( DataSetHandle ds, DataSetViewData[] columns )
{
// get the column hints
PropertyHandle handle = ds.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP );
PropertyHandle resultSetColumnHandle = ds.getPropertyHandle( DataSetHandle.RESULT_SET_HINTS_PROP );
Iterator iter = handle.iterator( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
ColumnHintHandle hint = (ColumnHintHandle) iter.next( );
// Find this column in the list of columns passed and update the
for ( int n = 0; n < columns.length; n++ )
{
// If the column name is not present then get the column
// name from
// the result set column definition if any
String columnName = columns[n].getName( );
if ( resultSetColumnHandle != null
&& ( columnName == null || columnName.trim( )
.length( ) == 0 ) )
{
Iterator resultIter = resultSetColumnHandle.iterator( );
if ( resultIter != null )
{
while ( resultIter.hasNext( ) )
{
ResultSetColumnHandle column = (ResultSetColumnHandle) resultIter.next( );
if ( column.getPosition( ).intValue( ) == n + 1 )
{
columnName = column.getColumnName( );
break;
}
}
}
if ( columnName == null )
{
columnName = ""; //$NON-NLS-1$
}
columns[n].setName( columnName );
}
if ( columns[n].getName( ).equals( hint.getColumnName( ) ) )
{
columns[n].setDisplayName( hint.getDisplayName( ) );
columns[n].setDisplayNameKey( hint.getDisplayNameKey( ) );
columns[n].setAlias( hint.getAlias( ) );
columns[n].setHelpText( hint.getHelpText( ) );
break;
}
}
}
}
}
/**
*
* @param dataSet
* @return
* @throws BirtException
*/
public IBaseDataSetDesign createDataSetDesign( DataSetHandle dataSet )
throws BirtException
{
DataSessionContext context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION,
dataSet.getModuleHandle( ) );
DataRequestSession session = DataRequestSession.newSession( context );
return session.getModelAdaptor( ).adaptDataSet( dataSet );
}
/**
*
* @param dataSource
* @return
* @throws BirtException
*/
public IBaseDataSourceDesign createDataSourceDesign(
DataSourceHandle dataSource ) throws BirtException
{
DataSessionContext context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION,
dataSource.getModuleHandle( ) );
DataRequestSession session = DataRequestSession.newSession( context );
return session.getModelAdaptor( ).adaptDataSource( dataSource );
}
/**
* Get cached data set item model. If none is cached, return null;
*
* @param ds
* @param columns
*/
public DataSetViewData[] getCachedDataSetItemModel( DataSetHandle ds )
{
DataSetViewData[] result = (DataSetViewData[]) this.htColumns.get( ds );
if ( result == null )
{
DataRequestSession session;
try
{
DataSessionContext context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION,
ds.getModuleHandle( ) );
session = DataRequestSession.newSession( context );
result = this.populateAllOutputColumns( ds, session );
session.shutdown();
return result;
}
catch ( BirtException e )
{
result = new DataSetViewData[0];
}
}
return result;
}
/**
* @param dataSetType
* @param dataSourceType
* @return
*/
public static IConfigurationElement findDataSetElement( String dataSetType,
String dataSourceType )
{
// NOTE: multiple data source types can support the same data set type
IConfigurationElement dataSourceElem = findDataSourceElement( dataSourceType );
if ( dataSourceElem != null )
{
// Find data set declared in the same extension
IExtension ext = dataSourceElem.getDeclaringExtension( );
IConfigurationElement[] elements = ext.getConfigurationElements( );
for ( int n = 0; n < elements.length; n++ )
{
if ( elements[n].getAttribute( "id" ).equals( dataSetType ) ) //$NON-NLS-1$
{
return elements[n];
}
}
}
return null;
}
/**
* @param dataSourceType
* @return
*/
public static IConfigurationElement findDataSourceElement(
String dataSourceType )
{
assert ( dataSourceType != null );
// Find it in the hashtable
IConfigurationElement element = (IConfigurationElement) htDataSourceExtensions.get( dataSourceType );
if ( element == null )
{
IConfigurationElement[] elements = Platform.getExtensionRegistry( )
.getConfigurationElementsFor( "org.eclipse.birt.report.designer.ui.odadatasource" ); //$NON-NLS-1$
for ( int n = 0; n < elements.length; n++ )
{
if ( elements[n].getAttribute( "id" ).equals( dataSourceType ) ) //$NON-NLS-1$
{
element = elements[n];
htDataSourceExtensions.put( dataSourceType, element );
break;
}
}
elements = Platform.getExtensionRegistry( )
.getConfigurationElementsFor( "org.eclipse.datatools.connectivity.oda.design.ui.dataSource" ); //$NON-NLS-1$
for ( int n = 0; n < elements.length; n++ )
{
if ( elements[n].getAttribute( "id" ).equals( dataSourceType ) ) //$NON-NLS-1$
{
element = elements[n];
htDataSourceExtensions.put( dataSourceType, element );
break;
}
}
}
return element;
}
/**
*
* @param dataSet
* @param useColumnHints
* @param useFilters
* @return
* @throws BirtException
*/
public final IBaseDataSetDesign getDataSetDesign( DataSetHandle dataSet,
boolean useColumnHints, boolean useFilters ) throws BirtException
{
if ( dataSet != null )
{
DataRequestSession session = getDataRequestSession( dataSet );
return getDataSetDesign( dataSet, useColumnHints, useFilters, session );
}
return null;
}
/**
*
* @param session
* @param dataSet
* @param useColumnHints
* @param useFilters
* @return
* @throws BirtException
*/
private IBaseDataSetDesign getDataSetDesign( DataRequestSession session,DataSetHandle dataSet,
boolean useColumnHints, boolean useFilters ) throws BirtException
{
if ( dataSet != null )
{
return getDataSetDesign( dataSet, useColumnHints, useFilters, session );
}
return null;
}
/**
* @param dataSet
* @param useColumnHints
* @param useFilters
* @param session
* @return
* @throws BirtException
*/
private IBaseDataSetDesign getDataSetDesign( DataSetHandle dataSet, boolean useColumnHints, boolean useFilters, DataRequestSession session ) throws BirtException
{
IBaseDataSetDesign dataSetDesign = session.getModelAdaptor( )
.adaptDataSet( dataSet );
if ( !useColumnHints )
{
dataSetDesign.getResultSetHints( ).clear( );
}
if ( !useFilters )
{
dataSetDesign.getFilters( ).clear( );
}
if ( !( dataSet instanceof JointDataSetHandle ) )
{
IBaseDataSourceDesign dataSourceDesign = session.getModelAdaptor( )
.adaptDataSource( dataSet.getDataSource( ) );
session.defineDataSource( dataSourceDesign );
}
if ( dataSet instanceof JointDataSetHandle )
{
defineSourceDataSets( session, dataSet, dataSetDesign );
}
session.defineDataSet( dataSetDesign );
return dataSetDesign;
}
/**
* @param dataSet
* @param dataSetDesign
* @throws BirtException
*/
private void defineSourceDataSets( DataRequestSession session, DataSetHandle dataSet,
IBaseDataSetDesign dataSetDesign ) throws BirtException
{
List dataSets = dataSet.getModuleHandle( ).getAllDataSets( );
for ( int i = 0; i < dataSets.size( ); i++ )
{
DataSetHandle dsHandle = (DataSetHandle) dataSets.get( i );
if ( dsHandle.getName( ) != null )
{
if ( dsHandle.getName( )
.equals( ( (IJointDataSetDesign) dataSetDesign ).getLeftDataSetDesignName( ) )
|| dsHandle.getName( )
.equals( ( (IJointDataSetDesign) dataSetDesign ).getRightDataSetDesignName( ) ) )
{
getDataSetDesign( session,dsHandle, true, true );
}
}
}
}
/**
*
* @param dataSet
* @return
* @throws BirtException
*/
public DataRequestSession getDataRequestSession( DataSetHandle dataSet )
throws BirtException
{
if ( sessionTable.get( dataSet.getName( ) ) != null )
return (DataRequestSession) sessionTable.get( dataSet.getName( ) );
else
{
DataSessionContext context = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION,
dataSet.getModuleHandle( ) );
DataRequestSession session = DataRequestSession.newSession( context );
sessionTable.put( dataSet.getName( ), session );
return session;
}
}
/**
* @param dataSet
* @return
* @throws BirtException
*/
public Collection getParametersFromDataSet( DataSetHandle dataSet )
throws BirtException
{
return prepareQuery( dataSet ).getParameterMetaData( );
}
/**
*
* @param dataSet
* @return
* @throws BirtException
*/
public IPreparedQuery prepareQuery( DataSetHandle dataSet )
throws BirtException
{
DataRequestSession session = getDataRequestSession( dataSet );
IBaseDataSetDesign dataSetDesign = getDataSetDesign( dataSet,
true,
true );
QueryDefinition queryDefn = getQueryDefinition( dataSetDesign, -1 );
return session.prepare( queryDefn, null );
}
/**
*
* @param dataSet
* @return
* @throws BirtException
*/
public IPreparedQuery prepareQuery( DataSetHandle dataSet,
IQueryDefinition query ) throws BirtException
{
DataRequestSession session = getDataRequestSession( dataSet );
getDataSetDesign( dataSet, true, true );
return session.prepare( query, null );
}
/**
*
* @param dataSet
* @return
* @throws BirtException
*/
public IPreparedQuery prepareQuery( DataSetHandle dataSet,
IQueryDefinition query, boolean useColumnHints, boolean useFilters )
throws BirtException
{
DataRequestSession session = getDataRequestSession( dataSet );
getDataSetDesign( dataSet, useColumnHints, useFilters );
return session.prepare( query, null );
}
/**
* Gets prepared query, given Data set, Parameter binding, and
* useColumnHints, useFilters information.
*
* @param dataSet
* Given DataSet providing SQL query and parameters.
* @param bindingParams
* Given Parameter bindings providing binded parameters, null if
* no binded parameters.
* @param useColumnHints
* Using column hints flag.
* @param useFilters
* Using filters flag.
* @return IPreparedQeury
* @throws BirtException
*/
public final IPreparedQuery prepareQuery( DataSetHandle dataSet,
ParamBindingHandle[] bindingParams, boolean useColumnHints,
boolean useFilters ) throws BirtException
{
DataRequestSession session = getDataRequestSession( dataSet );
IBaseDataSetDesign dataSetDesign = getDataSetDesign( dataSet,
useColumnHints,
useFilters );
return session.prepare( getQueryDefinition( dataSetDesign,
bindingParams ), null );
}
/**
* @param parent
* @return
*/
public static ClassLoader getCustomScriptClassLoader( ClassLoader parent, ModuleHandle handle )
{
List<URL> urls = getClassPathURLs( );
loadResourceFolderScriptLibs( handle, urls );
if( urls.size() == 0 )
return parent;
return new URLClassLoader( urls.toArray( new URL[0]), parent);
}
private static void loadResourceFolderScriptLibs( ModuleHandle handle,
List<URL> urls )
{
Iterator it = handle.scriptLibsIterator( );
while ( it.hasNext( ) )
{
ScriptLibHandle libHandle = (ScriptLibHandle) it.next( );
URL url = handle.findResource( libHandle.getName( ),
IResourceLocator.LIBRARY );
if ( url != null )
urls.add( url );
}
}
private static List<URL> getClassPathURLs( )
{
List<URL> urls = new ArrayList<URL>();
urls.addAll( getDefaultViewerScriptLibURLs());
urls.addAll( getWorkspaceProjectURLs());
return urls;
}
/**
* Return the URLs of ScriptLib jars.
*
* @return
*/
private static List<URL> getDefaultViewerScriptLibURLs()
{
List<URL> urls = new ArrayList<URL>( );
try
{
Bundle bundle = Platform.getBundle( VIEWER_NAMESPACE );
// Prepare ScriptLib location
Enumeration bundleFile = bundle.getEntryPaths( BIRT_SCRIPTLIB );
while( bundleFile.hasMoreElements())
{
String o = bundleFile.nextElement( ).toString( );
if ( o.endsWith( ".jar" ) )
urls.add( bundle.getResource( o ) );
}
URL classes = bundle.getEntry( BIRT_CLASSES );
if( classes!= null )
{
urls.add( classes );
}
}
catch ( Exception e )
{
}
return urls;
}
/**
* Return the URLs of Workspace projects.
*
* @return
*/
private static List<URL> getWorkspaceProjectURLs()
{
List<URL> urls = new ArrayList<URL>();
// For Bugzilla 106580: in order for Data Set Preview to locate POJO, we
// need to set current thread's context class loader to a custom loader
// which has the following path:
// All workspace Java project's class path (this class path is already
// has already calculated byorg.eclipse.birt.report.debug.ui plugin, and
// set as system property "workspace.projectclasspath"
String classPath = System.getProperty( "workspace.projectclasspath" ); //$NON-NLS-1$
if ( classPath == null || classPath.length( ) == 0 )
return urls;
String[] classPathArray = classPath.split( File.pathSeparator, -1 );
int count = classPathArray.length;
for ( int i = 0; i < count; i++ )
{
File file = new File( classPathArray[i] );
try
{
urls.add( file.toURL( ));
} catch ( MalformedURLException e )
{
}
}
return urls;
}
}
|
package org.eclipse.birt.report.designer.ui.dialogs;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.core.data.DateFormatISO8601;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.extension.ExtendedDataModelUIAdapterHelper;
import org.eclipse.birt.report.designer.internal.ui.extension.IExtendedDataModelUIAdapter;
import org.eclipse.birt.report.designer.internal.ui.script.JSDocumentProvider;
import org.eclipse.birt.report.designer.internal.ui.script.JSEditorInput;
import org.eclipse.birt.report.designer.internal.ui.script.JSSourceViewerConfiguration;
import org.eclipse.birt.report.designer.internal.ui.script.PreferenceNames;
import org.eclipse.birt.report.designer.internal.ui.script.ScriptValidator;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.IReportGraphicConstants;
import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.expressions.ISortableExpressionProvider;
import org.eclipse.birt.report.designer.ui.preferences.PreferenceFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.designer.util.DNDUtil;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.LevelAttributeHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.TabularMeasureGroupHandle;
import org.eclipse.birt.report.model.api.olap.TabularMeasureHandle;
import org.eclipse.birt.report.model.api.util.UnicodeUtil;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.source.AnnotationModel;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.ACC;
import org.eclipse.swt.accessibility.Accessible;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import com.ibm.icu.text.Collator;
/**
* The expression builder
*/
public class ExpressionBuilder extends BaseTitleAreaDialog
{
private static final String DIALOG_TITLE = Messages.getString( "ExpressionBuidler.Dialog.Title" ); //$NON-NLS-1$
private static final String TITLE = Messages.getString( "ExpressionBuidler.Title" ); //$NON-NLS-1$
private static final String PROMRT_MESSAGE = Messages.getString( "ExpressionBuilder.Message.Prompt" ); //$NON-NLS-1$
private static final String LABEL_FUNCTIONS = Messages.getString( "ExpressionBuilder.Label.Functions" ); //$NON-NLS-1$
private static final String LABEL_SUB_CATEGORY = Messages.getString( "ExpressionBuilder.Label.SubCategory" ); //$NON-NLS-1$
private static final String LABEL_CATEGORY = Messages.getString( "ExpressionBuilder.Label.Category" ); //$NON-NLS-1$
private static final String LABEL_OPERATORS = Messages.getString( "ExpressionBuilder.Label.Operators" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_REDO = Messages.getString( "TextEditDialog.toolTipText.redo" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_UNDO = Messages.getString( "TextEditDialog.toolTipText.undo" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_DELETE = Messages.getString( "TextEditDialog.toolTipText.delete" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_PASTE = Messages.getString( "TextEditDialog.toolTipText.paste" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_CUT = Messages.getString( "TextEditDialog.toolTipText.cut" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_COPY = Messages.getString( "TextEditDialog.toolTipText.copy" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_VALIDATE = Messages.getString( "ExpressionBuilder.toolTipText.validate" ); //$NON-NLS-1$
private static final String TOOL_TIP_TEXT_CALENDAR = Messages.getString( "ExpressionBuilder.toolTipText.calendar" ); //$NON-NLS-1$
private static final Object[] EMPTY = new Object[0];
private static final String SORTING_PREFERENCE_KEY = "ExpressionBuilder.preference.enable.sorting"; //$NON-NLS-1$
private TableViewer categoryTable, functionTable;
private TreeViewer subCategoryTable;
private IExpressionProvider provider;
private SourceViewer sourceViewer;
private JSSourceViewerConfiguration sourceViewerConfiguration = new JSSourceViewerConfiguration( );
private IPreferenceStore preferenceStore;
private Color backgroundColor;
private Color foregroundColor;
private FormText messageLine;
protected String expression = null;
protected String title;
private boolean useSorting = false;
private boolean showLeafOnlyInFunctionTable = false;
private Object[] defaultSelection;
private Map<ToolItem, Integer> toolItemType = new HashMap<ToolItem, Integer>( );
/**
* Create an expression builder under the given parent shell with the given
* initial expression
*
* @param parentShell
* the parent shell
* @param initExpression
* the initial expression
*/
public ExpressionBuilder( Shell parentShell, String initExpression )
{
super( parentShell );
title = DIALOG_TITLE;
this.expression = UIUtil.convertToGUIString( initExpression );
this.preferenceStore = new ScopedPreferenceStore( new InstanceScope( ),
"org.eclipse.ui.editors" ); //$NON-NLS-1$
}
protected void setShellStyle( int newShellStyle )
{
newShellStyle |= SWT.MAX | SWT.RESIZE;
super.setShellStyle( newShellStyle );
}
/**
* Create an expression builder under the default parent shell with the
* given initial expression
*
* @param initExpression
* the initial expression
*/
public ExpressionBuilder( String initExpression )
{
this( UIUtil.getDefaultShell( ), initExpression );
}
/**
* Create an expression builder under the default parent shell without an
* initail expression
*
*/
public ExpressionBuilder( )
{
this( null );
}
/**
* TableContentProvider
*/
private class TableContentProvider implements IStructuredContentProvider
{
private Viewer viewer;
private boolean leafOnly;
public TableContentProvider( Viewer viewer, boolean leafOnly )
{
this.viewer = viewer;
this.leafOnly = leafOnly;
}
public Object[] getElements( Object inputElement )
{
if ( viewer == categoryTable )
{
return provider.getCategory( );
}
// does not show groups/measures in third column.
if ( inputElement instanceof IAdaptable )
{
inputElement = DNDUtil.unwrapToModel( inputElement );
}
if ( inputElement instanceof PropertyHandle
|| inputElement instanceof TabularMeasureGroupHandle
|| inputElement instanceof DimensionHandle )
{
return EMPTY;
}
// ignore items that cannot be inserted as (part of) expression.
else if ( inputElement instanceof DesignElementHandle
&& getAdapter() != null
&& getAdapter( ).resolveExtendedData( (DesignElementHandle) inputElement ) != null
&& provider.getChildren(inputElement).length > 1
&& provider.getChildren(inputElement)[0] instanceof ReportElementHandle
&& !getAdapter().isExtendedDataItem( (ReportElementHandle) provider.getChildren(inputElement)[0] ))
{
return EMPTY;
}
else if (inputElement instanceof ReportElementHandle
&& getAdapter( ) != null
&& getAdapter( ).isExtendedDataItem( (ReportElementHandle) inputElement ))
{
return new Object[]{inputElement};
}
else if ( inputElement instanceof LevelHandle )
{
List<Object> childrenList = new ArrayList<Object>( );
childrenList.add( inputElement );
List<LevelAttributeHandle> attribs = new ArrayList<LevelAttributeHandle>( );
for ( Iterator iterator = ( (LevelHandle) inputElement ).attributesIterator( ); iterator.hasNext( ); )
{
attribs.add( (LevelAttributeHandle) iterator.next( ) );
}
if ( useSorting )
{
// sort attribute list
Collections.sort( attribs,
new Comparator<LevelAttributeHandle>( ) {
public int compare( LevelAttributeHandle o1,
LevelAttributeHandle o2 )
{
return Collator.getInstance( )
.compare( o1.getName( ),
o2.getName( ) );
}
} );
}
childrenList.addAll( attribs );
return childrenList.toArray( );
}
else if ( inputElement instanceof TabularMeasureHandle )
{
return new Object[]{
inputElement
};
}
if ( useSorting && provider instanceof ISortableExpressionProvider )
{
return ( (ISortableExpressionProvider) provider ).getSortedChildren( inputElement );
}
Object[] elements = provider.getChildren( inputElement );
if ( leafOnly && !isLeaf( elements ) )
{
return new Object[0];
}
return elements;
}
private boolean isLeaf( Object[] elements )
{
for ( Object element : elements )
{
if ( provider.hasChildren( element ) )
{
return false;
}
}
return true;
}
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
if ( viewer == subCategoryTable )
{
functionTable.setInput( null );
}
}
}
private ISelectionChangedListener selectionListener = new ISelectionChangedListener( ) {
public void selectionChanged( SelectionChangedEvent event )
{
IStructuredSelection selection = (IStructuredSelection) event.getSelection( );
Viewer target = null;
if ( event.getSource( ) == categoryTable )
{
target = subCategoryTable;
}
else if ( event.getSource( ) == subCategoryTable )
{
target = functionTable;
}
if ( target != null )
{
target.setInput( selection == null ? null
: selection.getFirstElement( ) );
}
if ( event.getSource( ) == functionTable )
{
Table table = functionTable.getTable( );
if ( table.getSelectionCount( ) == 1 )
{
messageLine.getParent( ).setVisible( true );
String message = provider.getDisplayText( table.getSelection( )[0].getData( ) );
message = message.replaceAll( "&", "&" ); //$NON-NLS-1$//$NON-NLS-2$
message = message.replaceAll( "<", "<" ); //$NON-NLS-1$ //$NON-NLS-2$
message = message.replaceAll( ">", ">" ); //$NON-NLS-1$//$NON-NLS-2$
messageLine.setText( "<form><p> <b>" //$NON-NLS-1$
+ Messages.getString( "ExpressionBuilder.Label.Hint" ) //$NON-NLS-1$
+ "</b>: " //$NON-NLS-1$
+ message
+ "</p></form>", true, false ); //$NON-NLS-1$
messageLine.getParent( ).layout( );
}
else
{
messageLine.getParent( ).setVisible( false );
}
}
}
};
private class ExpressionLabelProvider implements
ITableLabelProvider,
ILabelProvider
{
public Image getColumnImage( Object element, int columnIndex )
{
return provider.getImage( element );
}
public String getColumnText( Object element, int columnIndex )
{
return provider.getDisplayText( element );
}
public void addListener( ILabelProviderListener listener )
{
}
public void dispose( )
{
}
public boolean isLabelProperty( Object element, String property )
{
return true;
}
public void removeListener( ILabelProviderListener listener )
{
}
public Image getImage( Object element )
{
return provider.getImage( element );
}
public String getText( Object element )
{
return provider.getDisplayText( element );
}
};
private IDoubleClickListener doubleClickListener = new IDoubleClickListener( ) {
public void doubleClick( DoubleClickEvent event )
{
IStructuredSelection selection = (IStructuredSelection) event.getSelection( );
if ( selection.isEmpty( ) )
{
return;
}
if ( event.getSource( ) == functionTable )
{
insertSelection( selection );
return;
}
}
};
private void insertSelection( IStructuredSelection selection )
{
if ( selection.getFirstElement( ) instanceof Object[] )
{
Object[] inputArray = (Object[]) selection.getFirstElement( );
if ( inputArray.length == 2 && inputArray[1] instanceof ReportItemHandle )
{
ReportItemHandle handle = (ReportItemHandle) inputArray[1];
handle.getModuleHandle( )
.getCommandStack( )
.startTrans( Messages.getString( "DataEditPart.stackMsg.edit" ) ); //$NON-NLS-1$
ColumnBindingDialog dialog = new ColumnBindingDialog( handle,
Messages.getString( "DataColumBindingDialog.title.EditDataBinding" ) ); //$NON-NLS-1$
if ( dialog.open( ) == Dialog.OK )
{
handle.getModuleHandle( ).getCommandStack( ).commit( );
functionTable.refresh( );
}
else
{
handle.getModuleHandle( ).getCommandStack( ).rollback( );
}
return;
}
}
String insertText = provider.getInsertText( selection.getFirstElement( ) );
if ( insertText != null )
{
insertText( insertText );
}
}
protected Control createDialogArea( Composite parent )
{
Composite composite = (Composite) super.createDialogArea( parent );
createExpressionField( composite );
if ( provider == null )
{
provider = new ExpressionProvider( );
}
createOperatorsBar( composite );
createMessageLine( composite );
createListArea( composite );
UIUtil.bindHelp( parent, IHelpContextIds.EXPRESSION_BUILDER_ID );
return composite;
}
private void createMessageLine( Composite parent )
{
Composite container = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.marginHeight = layout.marginWidth = 4;
layout.numColumns = 2;
container.setLayout( layout );
container.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
messageLine = new FormText( container, SWT.NONE );
new FormToolkit( Display.getDefault( ) ) {
class BorderPainter implements PaintListener
{
public void paintControl( PaintEvent event )
{
Composite composite = (Composite) event.widget;
Control[] children = composite.getChildren( );
for ( int i = 0; i < children.length; i++ )
{
Control c = children[i];
if ( c.isVisible( ) && c instanceof FormText )
{
Rectangle b = c.getBounds( );
GC gc = event.gc;
gc.setForeground( c.getBackground( ) );
gc.drawRectangle( b.x - 2,
b.y - 2,
b.width + 4,
b.height + 4 );
gc.setForeground( getColors( ).getBorderColor( ) );
gc.drawRectangle( b.x - 2,
b.y - 2,
b.width + 4,
b.height + 4 );
}
}
}
}
private BorderPainter borderPainter;
public void paintBordersFor( Composite parent )
{
if ( borderPainter == null )
borderPainter = new BorderPainter( );
parent.addPaintListener( borderPainter );
}
}.paintBordersFor( container );
messageLine.setText( "<form><p></p></form>", true, false ); //$NON-NLS-1$
container.setVisible( false );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.horizontalIndent = 6;
messageLine.setLayoutData( gridData );
}
private void createToolbar( Composite parent )
{
final ToolBar toolBar = new ToolBar( parent, SWT.FLAT );
toolBar.setLayoutData( new GridData( ) );
toolBar.getAccessible().addAccessibleListener(new AccessibleAdapter() {
public void getName( AccessibleEvent e )
{
if ( e.childID != ACC.CHILDID_SELF )
{
Accessible accessible = (Accessible) e.getSource( );
ToolBar tb = (ToolBar) accessible.getControl( );
ToolItem item = tb.getItem( e.childID );
if ( item != null )
{
e.result = item.getToolTipText( );
}
}
}
} );
ToolItem copy = createToolItem( toolBar, ITextOperationTarget.COPY );
copy.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_COPY ) );
copy.setToolTipText( TOOL_TIP_TEXT_COPY );
ToolItem cut = createToolItem( toolBar, ITextOperationTarget.CUT );
cut.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_CUT ) );
cut.setToolTipText( TOOL_TIP_TEXT_CUT );
ToolItem paste = createToolItem( toolBar, ITextOperationTarget.PASTE );
paste.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_PASTE ) );
paste.setToolTipText( TOOL_TIP_TEXT_PASTE );
ToolItem delete = createToolItem( toolBar, ITextOperationTarget.DELETE );
delete.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_DELETE ) );
delete.setToolTipText( TOOL_TIP_TEXT_DELETE );
ToolItem undo = createToolItem( toolBar, ITextOperationTarget.UNDO );
undo.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_UNDO ) );
undo.setToolTipText( TOOL_TIP_TEXT_UNDO );
ToolItem redo = createToolItem( toolBar, ITextOperationTarget.REDO );
redo.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_REDO ) );
redo.setToolTipText( TOOL_TIP_TEXT_REDO );
ToolItem validate = new ToolItem( toolBar, SWT.NONE );
validate.setImage( ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_EXPRESSION_VALIDATE ) );
validate.setToolTipText( TOOL_TIP_TEXT_VALIDATE );
validate.addSelectionListener( new SelectionAdapter( ) {
/*
* (non-Javadoc)
*
* @see
* org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse
* .swt.events.SelectionEvent)
*/
public void widgetSelected( SelectionEvent e )
{
validateScript( );
}
} );
final ToolItem calendar = new ToolItem( toolBar, SWT.NONE );
calendar.setImage( ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_TOOL_CALENDAR ) );
calendar.setToolTipText( TOOL_TIP_TEXT_CALENDAR );
calendar.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
generateDate( toolBar, calendar );
}
} );
}
private ToolItem createToolItem( ToolBar toolBar, final int operationType )
{
final ToolItem item = new ToolItem( toolBar, SWT.NONE );
toolItemType.put( item, operationType );
item.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
sourceViewer.doOperation( operationType );
updateToolItems( );
}
} );
return item;
}
private void createExpressionField( Composite parent )
{
Composite expressionArea = new Composite( parent, SWT.NONE );
expressionArea.setLayout( new GridLayout( ) );
expressionArea.setLayoutData( new GridData( GridData.FILL_BOTH ) );
createToolbar( expressionArea );
sourceViewer = createSourceViewer( expressionArea );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 150;
sourceViewer.getControl( ).setLayoutData( gd );
JSSourceViewerConfiguration.updateSourceFont( sourceViewer );
sourceViewer.getTextWidget( ).addKeyListener( new KeyAdapter( ) {
public void keyPressed( KeyEvent e )
{
updateToolItems( );
if ( isUndoKeyPress( e ) )
{
sourceViewer.doOperation( ITextOperationTarget.UNDO );
}
else if ( isRedoKeyPress( e ) )
{
sourceViewer.doOperation( ITextOperationTarget.REDO );
}
}
private boolean isUndoKeyPress( KeyEvent e )
{
return ( ( e.stateMask & SWT.CONTROL ) > 0 )
&& ( ( e.keyCode == 'z' ) || ( e.keyCode == 'Z' ) );
}
private boolean isRedoKeyPress( KeyEvent e )
{
return ( ( e.stateMask & SWT.CONTROL ) > 0 )
&& ( ( e.keyCode == 'y' ) || ( e.keyCode == 'Y' ) );
}
} );
sourceViewer.getTextWidget( )
.addBidiSegmentListener( new BidiSegmentListener( ) {
public void lineGetSegments( BidiSegmentEvent event )
{
event.segments = UIUtil.getExpressionBidiSegments( event.lineText );
}
} );
sourceViewer.getTextWidget( ).addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
resetOkButtonStatus( true );
}
} );
sourceViewer.getTextWidget( ).addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
updateToolItems( );
}
});
updateToolItems( );
}
protected void updateToolItems( )
{
for ( ToolItem item : toolItemType.keySet( ) )
{
if ( !item.isDisposed( ) )
{
item.setEnabled( sourceViewer.canDoOperation( toolItemType.get( item ) ) );
}
}
}
private void createOperatorsBar( Composite parent )
{
Operator[] operators = provider.getOperators( );
if ( operators == null || operators.length == 0 )
{
return;
}
Composite operatorsBar = new Composite( parent, SWT.NONE );
operatorsBar.setLayout( new GridLayout( 2, false ) );
operatorsBar.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Label lable = new Label( operatorsBar, SWT.NONE );
lable.setText( LABEL_OPERATORS );
int width = lable.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x;
width = width > 70 ? width : 70;
GridData gd = new GridData( );
gd.widthHint = width;
lable.setLayoutData( gd );
Composite operatorsArea = new Composite( operatorsBar, SWT.NONE );
operatorsArea.setLayout( UIUtil.createGridLayoutWithoutMargin( operators.length,
true ) );
SelectionAdapter selectionAdapter = new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
Button button = (Button) e.getSource( );
insertText( (String) button.getData( ) );
}
};
for ( int i = 0; i < operators.length; i++ )
{
Button button = new Button( operatorsArea, SWT.PUSH );
button.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
if ( operators[i] != IExpressionProvider.OPERATOR_SEPARATOR )
{
button.setData( operators[i].insertString );
String text = operators[i].symbol;
if ( text.indexOf( "&" ) != -1 ) //$NON-NLS-1$
{
text = text.replaceAll( "&", "&&" ); //$NON-NLS-1$ //$NON-NLS-2$
}
button.setText( text );
// button.setToolTipText( operators[i].tooltip );
button.addSelectionListener( selectionAdapter );
}
else
{
button.setVisible( false );
}
}
}
private void initSorting( )
{
// read setting from preference
useSorting = PreferenceFactory.getInstance( )
.getPreferences( ReportPlugin.getDefault( ) )
.getBoolean( SORTING_PREFERENCE_KEY );
}
private void toggleSorting( boolean sorted )
{
useSorting = sorted;
// update preference
PreferenceFactory.getInstance( )
.getPreferences( ReportPlugin.getDefault( ) )
.setValue( SORTING_PREFERENCE_KEY, useSorting );
functionTable.refresh( );
}
private void createListArea( Composite parent )
{
Composite listArea = new Composite( parent, SWT.NONE );
listArea.setLayout( new GridLayout( 3, true ) );
listArea.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Label categoryLabel = new Label( listArea, SWT.NONE );
categoryLabel.setText( LABEL_CATEGORY );
categoryLabel.addTraverseListener( new TraverseListener( ) {
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_MNEMONIC && e.doit )
{
e.detail = SWT.TRAVERSE_NONE;
categoryTable.getControl( ).setFocus( );
}
}
} );
Label subCategoryLabel = new Label( listArea, SWT.NONE );
subCategoryLabel.setText( LABEL_SUB_CATEGORY );
subCategoryLabel.addTraverseListener( new TraverseListener( ) {
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_MNEMONIC && e.doit )
{
e.detail = SWT.TRAVERSE_NONE;
subCategoryTable.getControl( ).setFocus( );
}
}
} );
Composite functionHeader = new Composite( listArea, SWT.NONE );
functionHeader.setLayout( new GridLayout( 2, false ) );
functionHeader.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Label functionLabel = new Label( functionHeader, SWT.NONE );
functionLabel.setText( LABEL_FUNCTIONS );
functionLabel.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
functionLabel.addTraverseListener( new TraverseListener( ) {
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_MNEMONIC && e.doit )
{
e.detail = SWT.TRAVERSE_NONE;
functionTable.getControl( ).setFocus( );
}
}
} );
ToolBar toolBar = new ToolBar( functionHeader, SWT.FLAT );
toolBar.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_END ) );
final ToolItem sortBtn = new ToolItem( toolBar, SWT.CHECK );
sortBtn.setImage( ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_ALPHABETIC_SORT ) );
sortBtn.setToolTipText( Messages.getString( "ExpressionBuilder.tooltip.Sort" ) ); //$NON-NLS-1$
sortBtn.addSelectionListener( new SelectionAdapter( ) {
@Override
public void widgetSelected( SelectionEvent e )
{
toggleSorting( sortBtn.getSelection( ) );
}
} );
if ( provider instanceof ISortableExpressionProvider )
{
initSorting( );
sortBtn.setSelection( useSorting );
}
else
{
sortBtn.setEnabled( false );
}
int style = SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE;
categoryTable = new TableViewer( listArea, style );
subCategoryTable = new TreeViewer( listArea, style );
functionTable = new TableViewer( listArea, style );
// sort table items in alphabetical order
categoryTable.setComparator( new ViewerComparator( ) );
subCategoryTable.setComparator( new ViewerComparator( ) );
functionTable.setComparator( new ViewerComparator( ) );
functionTable.getControl( ).addKeyListener( new KeyListener( ) {
public void keyPressed( KeyEvent e )
{
}
public void keyReleased( KeyEvent e )
{
if ( e.character == ' ' )
{
IStructuredSelection selection = (IStructuredSelection) functionTable.getSelection( );
if ( !selection.isEmpty( ) )
{
insertSelection( selection );
}
}
}
} );
initTable( categoryTable, false );
initTree( subCategoryTable );
initTable( functionTable, showLeafOnlyInFunctionTable);
}
private void handleDefaultSelection( )
{
if ( defaultSelection == null || defaultSelection.length == 0 )
{
return;
}
if ( defaultSelection.length > 0 && defaultSelection[0] != null )
{
categoryTable.setSelection( new StructuredSelection( defaultSelection[0] ),
true );
if ( defaultSelection.length > 1 && defaultSelection[1] != null )
{
subCategoryTable.setSelection( new StructuredSelection( defaultSelection[1] ),
true );
if ( defaultSelection.length > 2 && defaultSelection[2] != null )
{
functionTable.setSelection( new StructuredSelection( defaultSelection[2] ),
true );
}
}
}
}
private void initTree( TreeViewer treeViewer )
{
final Tree tree = treeViewer.getTree( );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 150;
tree.setLayoutData( gd );
tree.setToolTipText( null );
treeViewer.setLabelProvider( new ExpressionLabelProvider( ) );
treeViewer.setContentProvider( new ITreeContentProvider( ) {
public Object[] getChildren( Object parentElement )
{
return provider.getChildren( parentElement );
}
public Object getParent( Object element )
{
return null;
}
public boolean hasChildren( Object element )
{
return provider.hasChildren( element );
}
public Object[] getElements( Object inputElement )
{
return getChildren( inputElement );
}
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
}
} );
treeViewer.addSelectionChangedListener( selectionListener );
treeViewer.addDoubleClickListener( doubleClickListener );
}
private void initTable( TableViewer tableViewer, boolean leafOnly )
{
final Table table = tableViewer.getTable( );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 150;
table.setLayoutData( gd );
table.setToolTipText( null );
final TableColumn column = new TableColumn( table, SWT.NONE );
column.setWidth( 200 );
table.getShell( ).addControlListener( new ControlAdapter( ) {
public void controlResized( ControlEvent e )
{
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
if ( column != null && !column.isDisposed( ) )
{
column.setWidth( table.getSize( ).x > 204 ? table.getSize( ).x - 4
: 200 );
}
}
} );
}
} );
table.addMouseTrackListener( new MouseTrackAdapter( ) {
public void mouseHover( MouseEvent event )
{
Widget widget = event.widget;
if ( widget == table )
{
Point pt = new Point( event.x, event.y );
TableItem item = table.getItem( pt );
if ( item == null )
{
table.setToolTipText( null );
}
else
{
table.setToolTipText( provider.getTooltipText( item.getData( ) ) );
}
}
}
} );
tableViewer.setLabelProvider( new ExpressionLabelProvider( ) );
tableViewer.setContentProvider( new TableContentProvider( tableViewer, leafOnly ) );
tableViewer.addSelectionChangedListener( selectionListener );
tableViewer.addDoubleClickListener( doubleClickListener );
}
/**
* Sets the layout data of the button to a GridData with appropriate heights
* and widths.
* <p>
* The <code>BaseDialog</code> override the method in order to make Help
* button split with other buttons.
*
* @param button
* the button to be set layout data to
*/
protected void setButtonLayoutData( Button button )
{
GridData gridData;
if ( button.getText( ).equals( IDialogConstants.HELP_LABEL ) )
{
gridData = new GridData( GridData.VERTICAL_ALIGN_END
| GridData.HORIZONTAL_ALIGN_CENTER );
gridData.grabExcessVerticalSpace = true;
}
else
{
gridData = new GridData( GridData.VERTICAL_ALIGN_BEGINNING );
}
int widthHint = convertHorizontalDLUsToPixels( IDialogConstants.BUTTON_WIDTH );
gridData.widthHint = Math.max( widthHint,
button.computeSize( SWT.DEFAULT, SWT.DEFAULT, true ).x );
button.setLayoutData( gridData );
}
protected Control createContents( Composite parent )
{
Control control = super.createContents( parent );
getShell( ).setText( title );
setTitle( TITLE );
setMessage( PROMRT_MESSAGE );
categoryTable.setInput( "Dummy" ); //$NON-NLS-1$
handleDefaultSelection( );
//getShell( ).setDefaultButton( null );
sourceViewer.getTextWidget( ).setFocus( );
return control;
}
protected void okPressed( )
{
if ( !validateScript( ) )
{
MessageDialog dialog = new MessageDialog( getShell( ),
Messages.getString( "ExpressionBuilder.Script.Warning" ), //$NON-NLS-1$
null, // Accept the default window icon.
Messages.getString( "ExpressionBuilder.Script.Confirm" ), //$NON-NLS-1$
MessageDialog.WARNING,
new String[]{
IDialogConstants.OK_LABEL,
IDialogConstants.CANCEL_LABEL
},
1 ); // Cancel is the default.
if ( dialog.open( ) != 0 )
{
return;
}
}
expression = sourceViewer.getTextWidget( ).getText( ).trim( );
super.okPressed( );
}
/**
* Returns the result of the expression builder.
*
* @return the result
*/
public String getResult( )
{
return expression;
}
/**
* Sets the expression provider for the expression builder
*
* @param provider
* the expression provider
*/
public void setExpressionProvider( IExpressionProvider provider )
{
this.provider = provider;
}
/**
* Sets the expression provider for the expression builder
*
* @param provider
* the expression provider
*
* @deprecated use {@link #setExpressionProvider(IExpressionProvider)}
*/
public void setExpressionProvier( IExpressionProvider provider )
{
setExpressionProvider( provider );
}
/**
* Sets default seletion for the expression builder
*
* @param selection
*
* @since 2.3.1
*/
public void setDefaultSelection( Object... selection )
{
this.defaultSelection = selection;
}
/**
* Sets the dialog title of the expression builder
*
* @param newTitle
* the new dialog title
*/
public void setDialogTitle( String newTitle )
{
title = newTitle;
}
/**
* Returns the dialog title of the expression builder
*/
public String getDialogTitle( )
{
return title;
}
/**
* Insert a text string into the text area
*
* @param text
*/
protected void insertText( String text )
{
StyledText textWidget = sourceViewer.getTextWidget( );
if ( !textWidget.isEnabled( ) )
{
return;
}
int selectionStart = textWidget.getSelection( ).x;
textWidget.insert( text );
textWidget.setSelection( selectionStart + text.length( ) );
textWidget.setFocus( );
if ( text.endsWith( "()" ) ) //$NON-NLS-1$
{
textWidget.setCaretOffset( textWidget.getCaretOffset( ) - 1 ); // Move
}
}
/**
* Creates the source viewer to be used by this editor.
*
* @param parent
* the parent control
* @return the source viewer
*/
protected SourceViewer createSourceViewer( Composite parent )
{
IVerticalRuler ruler = createVerticalRuler( );
Composite composite = new Composite( parent, SWT.BORDER
| SWT.LEFT_TO_RIGHT );
composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
composite.setLayout( UIUtil.createGridLayoutWithoutMargin( ) );
int styles = SWT.V_SCROLL
| SWT.H_SCROLL
| SWT.MULTI
| SWT.BORDER
| SWT.FULL_SELECTION;
SourceViewer viewer = new SourceViewer( composite, ruler, styles );
viewer.configure( sourceViewerConfiguration );
updateStyledTextColors( viewer.getTextWidget( ) );
JSEditorInput editorInput = new JSEditorInput( expression,
getEncoding( ) );
JSDocumentProvider documentProvider = new JSDocumentProvider( );
try
{
documentProvider.connect( editorInput );
}
catch ( CoreException e )
{
ExceptionHandler.handle( e );
}
viewer.setDocument( documentProvider.getDocument( editorInput ),
ruler == null ? null : ruler.getModel( ) );
return viewer;
}
private void updateStyledTextColors( StyledText styledText )
{
if ( preferenceStore != null )
{
styledText.setForeground( getForegroundColor( preferenceStore ) );
styledText.setBackground( getBackgroundColor( preferenceStore ) );
}
}
private Color getForegroundColor( IPreferenceStore preferenceStore )
{
Color color = preferenceStore.getBoolean( AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT ) ? null
: createColor( preferenceStore,
AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND,
Display.getCurrent( ) );
foregroundColor = color;
return color;
}
private Color getBackgroundColor( IPreferenceStore preferenceStore )
{
Color color = preferenceStore.getBoolean( AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT ) ? null
: createColor( preferenceStore,
AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND,
Display.getCurrent( ) );
backgroundColor = color;
return color;
}
/**
* Creates a color from the information stored in the given preference
* store. Returns <code>null</code> if there is no such information
* available.
*/
private Color createColor( IPreferenceStore store, String key,
Display display )
{
RGB rgb = null;
if ( store.contains( key ) )
{
if ( store.isDefault( key ) )
{
rgb = PreferenceConverter.getDefaultColor( store, key );
}
else
{
rgb = PreferenceConverter.getColor( store, key );
}
if ( rgb != null )
{
return new Color( display, rgb );
}
}
return null;
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*
* @param annotationModel
*
* @return the created line number column
*/
private IVerticalRulerColumn createLineNumberRulerColumn( )
{
LineNumberRulerColumn column = new LineNumberRulerColumn( );
column.setForeground( JSSourceViewerConfiguration.getColorByCategory( PreferenceNames.P_LINENUMBER_COLOR ) );
return column;
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*
* @return the created line number column
*/
private CompositeRuler createCompositeRuler( )
{
CompositeRuler ruler = new CompositeRuler( );
ruler.setModel( new AnnotationModel( ) );
return ruler;
}
/**
* Creates the vertical ruler to be used by this editor.
*
* @return the vertical ruler
*/
private IVerticalRuler createVerticalRuler( )
{
IVerticalRuler ruler = createCompositeRuler( );
if ( ruler instanceof CompositeRuler )
{
CompositeRuler compositeRuler = (CompositeRuler) ruler;
compositeRuler.addDecorator( 0, createLineNumberRulerColumn( ) );
}
return ruler;
}
/**
* Validates the current script.
*
* @return <code>true</code> if no error was found, <code>false</code>
* otherwise.
*/
protected boolean validateScript( )
{
if ( sourceViewer == null )
{
return false;
}
String errorMessage = null;
try
{
new ScriptValidator( sourceViewer ).validate( true, true );
setMessage( Messages.getString( "ExpressionBuilder.Script.NoError" ), IMessageProvider.INFORMATION ); //$NON-NLS-1$
return true;
}
catch ( ParseException e )
{
int offset = e.getErrorOffset( );
int row = sourceViewer.getTextWidget( ).getLineAtOffset( offset ) + 1;
int column = offset
- sourceViewer.getTextWidget( ).getOffsetAtLine( row - 1 )
+ 1;
errorMessage = Messages.getFormattedString( "ExpressionBuilder.Script.Error", new Object[]{Integer.toString( row ), Integer.toString( column ), e.getLocalizedMessage( )} ); //$NON-NLS-1$
return false;
}
finally
{
setErrorMessage( errorMessage );
}
}
private void generateDate( final ToolBar toolBar, final ToolItem calendar )
{
final Shell shell = new Shell( UIUtil.getDefaultShell( ), SWT.NO_FOCUS );
shell.addShellListener( new ShellAdapter( ) {
public void shellDeactivated( ShellEvent e )
{
shell.close( );
}
public void shellIconified( ShellEvent e )
{
shell.close( );
}
} );
Point point = toolBar.toDisplay( 0, 0 );
point.y += toolBar.getBounds( ).height;
for ( int i = 0; i < toolBar.getItemCount( ); i++ )
{
ToolItem item = toolBar.getItem( i );
if ( item != calendar )
point.x += item.getWidth( );
else
break;
}
shell.setLocation( point );
GridLayout layout = new GridLayout( );
layout.marginWidth = layout.marginHeight = layout.verticalSpacing = 0;
layout.numColumns = 1;
shell.setLayout( layout );
final DateTime colorDialog = new DateTime( shell, SWT.CALENDAR
| SWT.FLAT );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.horizontalSpan = 1;
colorDialog.setLayoutData( gd );
new Label( shell, SWT.SEPARATOR | SWT.HORIZONTAL ).setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Composite container = new Composite( shell, SWT.NONE );
container.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
layout = new GridLayout( );
layout.marginWidth = layout.marginHeight = 5;
layout.numColumns = 2;
container.setLayout( layout );
new Label( container, SWT.NONE ).setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Button okBtn = new Button( container, SWT.FLAT );
okBtn.setText( Messages.getString( "ExpressionBuilder.Calendar.Button.OK" ) ); //$NON-NLS-1$
gd = new GridData( );
gd.widthHint = okBtn.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x < 60 ? 60
: okBtn.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x;
okBtn.setLayoutData( gd );
okBtn.setFocus( );
okBtn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
try
{
Calendar cal = Calendar.getInstance( );
cal.set( colorDialog.getYear( ),
colorDialog.getMonth( ),
colorDialog.getDay( ) );
insertText( DEUtil.addQuote( DateFormatISO8601.format( cal.getTime( ) ) ) );
if ( !shell.isDisposed( ) )
shell.close( );
if ( sourceViewer != null
&& !sourceViewer.getTextWidget( ).isDisposed( ) )
sourceViewer.getTextWidget( ).setFocus( );
}
catch ( BirtException e1 )
{
ExceptionHandler.handle( e1 );
}
}
} );
shell.pack( );
shell.open( );
}
private String getEncoding( )
{
String encoding = ""; //$NON-NLS-1$
ModuleHandle module = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( );
if ( module != null )
{
encoding = module.getFileEncoding( );
}
else
{
encoding = UnicodeUtil.SIGNATURE_UTF_8;
}
return encoding;
}
@Override
public boolean close( )
{
if ( foregroundColor != null )
{
foregroundColor.dispose( );
}
if ( backgroundColor != null )
{
backgroundColor.dispose( );
}
return super.close( );
}
private boolean isEditModel = false;
public void setEditModal( boolean isEditModel )
{
this.isEditModel = isEditModel;
}
public boolean isEditModal( )
{
return isEditModel;
}
protected void resetOkButtonStatus( Boolean enabled )
{
Button okButton = getButton( OK );
if ( okButton != null && okButton.isEnabled( ) != enabled )
okButton.setEnabled( enabled );
}
protected void createButtonsForButtonBar( Composite parent )
{
super.createButtonsForButtonBar( parent );
if ( isEditModal( ) )
resetOkButtonStatus( false );
}
protected IExtendedDataModelUIAdapter getAdapter()
{
return ExtendedDataModelUIAdapterHelper.getInstance( ).getAdapter( );
}
public void setShowLeafOnlyInThirdColumn( boolean leafOnly )
{
this.showLeafOnlyInFunctionTable = leafOnly;
}
}
|
package openfoodfacts.github.scrachx.openfood;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import openfoodfacts.github.scrachx.openfood.test.ScreenshotActivityTestRule;
import openfoodfacts.github.scrachx.openfood.views.scan.ContinuousScanActivity;
/**
* Take screenshots...
*/
@RunWith(AndroidJUnit4.class)
public class TakeScreenshotScanActivityTest extends AbstractScreenshotTest {
public static final int MS_TO_WAIT_TO_DISPLAY_PRODUCT_IN_SCAN = 2000;
@Rule
public ScreenshotActivityTestRule<ContinuousScanActivity> activityRule =
new ScreenshotActivityTestRule<>(ContinuousScanActivity.class);
@Test
public void testTakeScreenshotScanActivity() {
activityRule.setAfterActivityLaunchedAction(screenshotActivityTestRule -> {
try {
screenshotActivityTestRule.runOnUiThread(() -> {
final String barcode = screenshotActivityTestRule
.getScreenshotParameter().getProductCodes().get(0);
screenshotActivityTestRule.getActivity()
.showProduct(barcode);
});
Thread.sleep(MS_TO_WAIT_TO_DISPLAY_PRODUCT_IN_SCAN);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
});
startForAllLocales(activityRule);
}
}
|
package org.csstudio.channel.views;
import gov.bnl.channelfinder.api.ChannelQuery;
import gov.bnl.channelfinder.api.ChannelQueryListener;
import gov.bnl.channelfinder.api.ChannelQuery.Result;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.csstudio.channel.widgets.ChannelTreeByPropertyWidget;
import org.csstudio.channel.widgets.PropertyListDialog;
import org.csstudio.ui.util.helpers.ComboHistoryHelper;
import org.csstudio.utility.pvmanager.ui.SWTUtil;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
/**
* View that allows to create a tree view out of the results of a channel query.
*/
public class ChannelTreeByPropertyView extends ViewPart {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "org.csstudio.channel.views.ChannelTreeByPropertyView";
/** Memento */
private IMemento memento = null;
/** Memento tags */
private static final String MEMENTO_QUERY = "ChannelQuery"; //$NON-NLS-1$
private static final String MEMENTO_PROPERTIES = "Property"; //$NON-NLS-1$
private final ChannelQueryListener channelQueryListener = new ChannelQueryListener() {
@Override
public void queryExecuted(final Result result) {
SWTUtil.swtThread().execute(new Runnable() {
@Override
public void run() {
btnProperties.setEnabled(result.channels != null && !result.channels.isEmpty());
}
});
}
};
/**
* The constructor.
*/
public ChannelTreeByPropertyView() {
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
}
@Override
public void init(final IViewSite site, final IMemento memento)
throws PartInitException {
super.init(site, memento);
// Save the memento
this.memento = memento;
}
@Override
public void saveState(final IMemento memento) {
super.saveState(memento);
// Save the currently selected variable
if (combo.getText() != null) {
memento.putString(MEMENTO_QUERY, combo.getText());
if (!treeWidget.getProperties().isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String property : treeWidget.getProperties()) {
sb.append(property).append(",");
}
sb.deleteCharAt(sb.length() - 1);
memento.putString(MEMENTO_PROPERTIES, sb.toString());
}
}
}
private void setQueryText(String text) {
if (text == null)
text = "";
combo.setText(text);
changeQuery(text);
}
private Combo combo;
private ChannelTreeByPropertyWidget treeWidget;
private Composite parent;
private Button btnProperties;
private void changeQuery(String text) {
ChannelQuery oldQuery = treeWidget.getChannelQuery();
if (text == null)
text = "";
text = text.trim();
// Query is the same, do nothing
if (oldQuery != null && oldQuery.getQuery().equals(text)) {
return;
}
ChannelQuery newQuery = ChannelQuery.Builder.query(text).create();
setChannelQuery(newQuery);
}
public void setChannelQuery(ChannelQuery query) {
combo.setText(query.getQuery());
ChannelQuery oldQuery = treeWidget.getChannelQuery();
if (oldQuery != null) {
oldQuery.removeChannelQueryListener(channelQueryListener);
}
query.execute(channelQueryListener);
treeWidget.setChannelQuery(query);
}
@Override
public void createPartControl(Composite parent) {
this.parent = parent;
parent.setLayout(new FormLayout());
Label lblPvName = new Label(parent, SWT.NONE);
FormData fd_lblPvName = new FormData();
fd_lblPvName.left = new FormAttachment(0, 10);
fd_lblPvName.top = new FormAttachment(0, 18);
lblPvName.setLayoutData(fd_lblPvName);
lblPvName.setText("Query:");
ComboViewer comboViewer = new ComboViewer(parent, SWT.NONE);
combo = comboViewer.getCombo();
FormData fd_combo = new FormData();
fd_combo.top = new FormAttachment(0, 15);
fd_combo.left = new FormAttachment(lblPvName, 6);
combo.setLayoutData(fd_combo);
treeWidget = new ChannelTreeByPropertyWidget(parent, SWT.NONE);
FormData fd_waterfallComposite = new FormData();
fd_waterfallComposite.top = new FormAttachment(combo, 6);
fd_waterfallComposite.bottom = new FormAttachment(100, -10);
fd_waterfallComposite.left = new FormAttachment(0, 10);
fd_waterfallComposite.right = new FormAttachment(100, -10);
treeWidget.setLayoutData(fd_waterfallComposite);
ComboHistoryHelper name_helper =
new ComboHistoryHelper(Activator.getDefault()
.getDialogSettings(), "WaterfallPVs", combo, 20, true) {
@Override
public void newSelection(final String pv_name) {
changeQuery(pv_name);
}
};
btnProperties = new Button(parent, SWT.NONE);
fd_combo.right = new FormAttachment(btnProperties, -6);
FormData fd_btnProperties = new FormData();
fd_btnProperties.top = new FormAttachment(0, 13);
fd_btnProperties.right = new FormAttachment(100, -10);
btnProperties.setLayoutData(fd_btnProperties);
btnProperties.setText("Properties");
btnProperties.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
PropertyListDialog dialog = new PropertyListDialog(treeWidget);
dialog.open(e);
}
});
name_helper.loadSettings();
if (memento != null) {
setQueryText(memento.getString(MEMENTO_QUERY));
if (memento.getString(MEMENTO_PROPERTIES) != null) {
treeWidget.setProperties(Arrays.asList(memento.getString(MEMENTO_PROPERTIES).split(",")));
}
}
MenuManager menuMgr = new MenuManager();
menuMgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
Menu menu = menuMgr.createContextMenu(treeWidget.getTree());
treeWidget.getTree().setMenu(menu);
final Tree tree = treeWidget.getTree();
ISelectionProvider provider = new ISelectionProvider() {
private Map<ISelectionChangedListener, SelectionAdapter> map = new HashMap<ISelectionChangedListener, SelectionAdapter>();
@Override
public void setSelection(ISelection selection) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
SelectionAdapter adapter = map.remove(listener);
if (adapter != null)
tree.removeSelectionListener(adapter);
}
@Override
public ISelection getSelection() {
TreeItem[] selection = tree.getSelection();
Object[] data = new Object[selection.length];
for (int i = 0; i < data.length; i++) {
data[i] = selection[i].getData();
}
return new StructuredSelection(data);
}
@Override
public void addSelectionChangedListener(final ISelectionChangedListener listener) {
final ISelectionProvider thisProvider = this;
SelectionAdapter adapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
listener.selectionChanged(new SelectionChangedEvent(thisProvider, getSelection()));
}
};
map.put(listener, adapter);
tree.addSelectionListener(adapter);
}
};
getSite().registerContextMenu(menuMgr, provider);
getSite().setSelectionProvider(provider);
}
}
|
package com.apptentive.android.sdk.notifications;
import com.apptentive.android.sdk.TestCaseBase;
import org.junit.Test;
import java.util.HashMap;
public class ApptentiveNotificationObserverListTest extends TestCaseBase {
private static final boolean WEAK_REFERENCE = true;
private static final boolean STRONG_REFERENCE = false;
@Test
public void testAddObservers() {
ApptentiveNotificationObserverList list = new ApptentiveNotificationObserverList();
Observer o1 = new Observer("observer1");
Observer o2 = new Observer("observer2");
list.addObserver(o1, WEAK_REFERENCE);
list.addObserver(o2, STRONG_REFERENCE);
// trying to add duplicates
list.addObserver(o1, WEAK_REFERENCE);
list.addObserver(o1, STRONG_REFERENCE);
list.addObserver(o2, WEAK_REFERENCE);
list.addObserver(o2, STRONG_REFERENCE);
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult("observer1", "observer2");
}
@Test
public void testRemoveObservers() {
ApptentiveNotificationObserverList list = new ApptentiveNotificationObserverList();
Observer o1 = new Observer("observer1");
Observer o2 = new Observer("observer2");
list.addObserver(o1, WEAK_REFERENCE);
list.addObserver(o2, STRONG_REFERENCE);
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult("observer1", "observer2");
list.removeObserver(o1);
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult("observer2");
list.removeObserver(o2);
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult();
}
@Test
public void testWeakReferences() {
ApptentiveNotificationObserverList list = new ApptentiveNotificationObserverList();
// begin of the scope
{
Observer o1 = new Observer("observer1");
Observer o4 = new Observer("observer4");
list.addObserver(o1, WEAK_REFERENCE); // this reference won't be lost until the end of the current scope
list.addObserver(new Observer("observer2"), WEAK_REFERENCE); // this reference would be lost right away
list.addObserver(new Observer("observer3"), STRONG_REFERENCE); // this reference won't be lost
list.addObserver(o4, STRONG_REFERENCE);
// force GC so the weak reference becomes null
System.gc();
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult("observer1", "observer3", "observer4");
o1 = o4 = null; // this step is necessary for a proper GC
}
// end of the scope
// force GC so the weak reference becomes null
System.gc();
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult("observer3", "observer4");
}
@Test
public void testConcurrentModification() {
final ApptentiveNotificationObserverList list = new ApptentiveNotificationObserverList();
final Observer o1 = new Observer("observer1");
final Observer o2 = new Observer("observer2");
list.addObserver(new ApptentiveNotificationObserver() {
@Override
public void onReceiveNotification(ApptentiveNotification notification) {
list.removeObserver(o1);
addResult("anonymous-observer1");
}
}, STRONG_REFERENCE);
list.addObserver(o1, WEAK_REFERENCE);
list.addObserver(new ApptentiveNotificationObserver() {
@Override
public void onReceiveNotification(ApptentiveNotification notification) {
list.removeObserver(o2);
addResult("anonymous-observer2");
}
}, STRONG_REFERENCE);
list.addObserver(o2, STRONG_REFERENCE);
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult("anonymous-observer1", "observer1", "anonymous-observer2", "observer2");
list.notifyObservers(new ApptentiveNotification("notification", new HashMap<String, Object>()));
assertResult("anonymous-observer1", "anonymous-observer2");
}
private class Observer implements ApptentiveNotificationObserver {
private final String name;
public Observer(String name) {
this.name = name;
}
@Override
public void onReceiveNotification(ApptentiveNotification notification) {
addResult(name);
}
}
}
|
package org.opendaylight.protocol.bgp.parser.impl.message.update;
import io.netty.buffer.ByteBuf;
import java.util.Arrays;
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPError;
import org.opendaylight.protocol.concepts.Ipv4Util;
import org.opendaylight.protocol.util.ByteArray;
import org.opendaylight.protocol.util.ReferenceCache;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.ExtendedCommunities;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.ExtendedCommunitiesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Community;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ShortAsNumber;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.AsSpecificExtendedCommunityCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.Inet4SpecificExtendedCommunityCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.OpaqueExtendedCommunityCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.RouteOriginExtendedCommunityCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.RouteTargetExtendedCommunityCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.as.specific.extended.community._case.AsSpecificExtendedCommunityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.inet4.specific.extended.community._case.Inet4SpecificExtendedCommunityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.opaque.extended.community._case.OpaqueExtendedCommunityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.route.origin.extended.community._case.RouteOriginExtendedCommunityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.extended.community.route.target.extended.community._case.RouteTargetExtendedCommunityBuilder;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.UnsignedBytes;
/**
* Parser for Extended Communities Path Attribute.
*/
public final class CommunitiesParser {
protected static final int EXTENDED_COMMUNITY_LENGTH = 8;
protected static final int COMMUNITY_LENGTH = 4;
private static final int AS_LOCAL_ADMIN_LENGTH = 4;
private static final int INET_LOCAL_ADMIN_LENGTH = 2;
protected static final short AS_TYPE_TRANS = 0;
protected static final short AS_TYPE_NON_TRANS = 40;
protected static final short INET_TYPE_TRANS = 1;
protected static final short INET_TYPE_NON_TRANS = 41;
protected static final short OPAQUE_TYPE_TRANS = 3;
protected static final short OPAQUE_TYPE_NON_TRANS = 43;
protected static final short ROUTE_TYPE_ONLY = 2;
protected static final short ROUTE_TARGET_SUBTYPE = 2;
protected static final short ROUTE_ORIGIN_SUBTYPE = 3;
private static final byte[] NO_EXPORT = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x01 };
private static final byte[] NO_ADVERTISE = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x02 };
private static final byte[] NO_EXPORT_SUBCONFED = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x03 };
private CommunitiesParser() {
}
/**
* Parse known Community, if unknown, a new one will be created.
* @param refCache
*
* @param bytes byte array to be parsed
* @return new Community
* @throws BGPDocumentedException
*/
static Community parseCommunity(final ReferenceCache refCache, final ByteBuf buffer) throws BGPDocumentedException {
if (buffer.readableBytes() != COMMUNITY_LENGTH) {
throw new BGPDocumentedException("Community with wrong length: " + buffer.readableBytes(), BGPError.OPT_ATTR_ERROR);
}
byte[] body = ByteArray.getBytes(buffer, COMMUNITY_LENGTH);
if (Arrays.equals(body, NO_EXPORT)) {
return CommunityUtil.NO_EXPORT;
} else if (Arrays.equals(body, NO_ADVERTISE)) {
return CommunityUtil.NO_ADVERTISE;
} else if (Arrays.equals(body, NO_EXPORT_SUBCONFED)) {
return CommunityUtil.NO_EXPORT_SUBCONFED;
}
return CommunityUtil.create(refCache, buffer.readUnsignedShort(), buffer.readUnsignedShort());
}
/**
* Parse Extended Community according to their type.
*
* @param bytes byte array to be parsed
* @return new Specific Extended Community
* @throws BGPDocumentedException if the type is not recognized
*/
@VisibleForTesting
public static ExtendedCommunities parseExtendedCommunity(final ReferenceCache refCache, final ByteBuf buffer) throws BGPDocumentedException {
final int type = UnsignedBytes.toInt(buffer.readByte());
final int subType = UnsignedBytes.toInt(buffer.readByte());
final ExtendedCommunitiesBuilder comm = new ExtendedCommunitiesBuilder();
switch (type) {
case AS_TYPE_TRANS:
comm.setCommType(AS_TYPE_TRANS);
if (subType == ROUTE_TARGET_SUBTYPE) {
comm.setCommSubType(ROUTE_TARGET_SUBTYPE).setExtendedCommunity(
new RouteTargetExtendedCommunityCaseBuilder().setRouteTargetExtendedCommunity(
new RouteTargetExtendedCommunityBuilder().setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
} else if (subType == ROUTE_ORIGIN_SUBTYPE) {
comm.setCommSubType(ROUTE_ORIGIN_SUBTYPE).setExtendedCommunity(
new RouteOriginExtendedCommunityCaseBuilder().setRouteOriginExtendedCommunity(
new RouteOriginExtendedCommunityBuilder().setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
} else {
comm.setExtendedCommunity(
new AsSpecificExtendedCommunityCaseBuilder().setAsSpecificExtendedCommunity(
new AsSpecificExtendedCommunityBuilder().setTransitive(false).setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
}
break;
case AS_TYPE_NON_TRANS:
comm.setCommType(AS_TYPE_NON_TRANS).setExtendedCommunity(
new AsSpecificExtendedCommunityCaseBuilder().setAsSpecificExtendedCommunity(
new AsSpecificExtendedCommunityBuilder().setTransitive(true).setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
break;
case ROUTE_TYPE_ONLY:
comm.setCommType(ROUTE_TYPE_ONLY);
if (subType == ROUTE_TARGET_SUBTYPE) {
comm.setCommSubType(ROUTE_TARGET_SUBTYPE).setExtendedCommunity(
new RouteTargetExtendedCommunityCaseBuilder().setRouteTargetExtendedCommunity(
new RouteTargetExtendedCommunityBuilder().setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
} else if (subType == ROUTE_ORIGIN_SUBTYPE) {
comm.setCommSubType(ROUTE_ORIGIN_SUBTYPE).setExtendedCommunity(
new RouteOriginExtendedCommunityCaseBuilder().setRouteOriginExtendedCommunity(
new RouteOriginExtendedCommunityBuilder().setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
} else {
throw new BGPDocumentedException("Could not parse Extended Community subtype: " + subType, BGPError.OPT_ATTR_ERROR);
}
break;
case INET_TYPE_TRANS:
comm.setCommType(INET_TYPE_TRANS);
if (subType == ROUTE_TARGET_SUBTYPE) {
comm.setCommSubType(ROUTE_TARGET_SUBTYPE).setExtendedCommunity(
new RouteTargetExtendedCommunityCaseBuilder().setRouteTargetExtendedCommunity(
new RouteTargetExtendedCommunityBuilder().setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
} else if (subType == ROUTE_ORIGIN_SUBTYPE) {
comm.setCommSubType(ROUTE_ORIGIN_SUBTYPE).setExtendedCommunity(
new RouteOriginExtendedCommunityCaseBuilder().setRouteOriginExtendedCommunity(
new RouteOriginExtendedCommunityBuilder().setGlobalAdministrator(
new ShortAsNumber((long) buffer.readUnsignedShort())).setLocalAdministrator(
ByteArray.readBytes(buffer, AS_LOCAL_ADMIN_LENGTH)).build()).build());
} else {
comm.setExtendedCommunity(
new Inet4SpecificExtendedCommunityCaseBuilder().setInet4SpecificExtendedCommunity(
new Inet4SpecificExtendedCommunityBuilder().setTransitive(false).setGlobalAdministrator(
Ipv4Util.addressForBytes(ByteArray.readBytes(buffer, Ipv4Util.IP4_LENGTH))).setLocalAdministrator(
ByteArray.readBytes(buffer, INET_LOCAL_ADMIN_LENGTH)).build()).build());
}
break;
case INET_TYPE_NON_TRANS:
comm.setCommType(INET_TYPE_NON_TRANS).setExtendedCommunity(
new Inet4SpecificExtendedCommunityCaseBuilder().setInet4SpecificExtendedCommunity(
new Inet4SpecificExtendedCommunityBuilder().setTransitive(true).setGlobalAdministrator(
Ipv4Util.addressForBytes(ByteArray.readBytes(buffer, Ipv4Util.IP4_LENGTH))).setLocalAdministrator(
ByteArray.readBytes(buffer, INET_LOCAL_ADMIN_LENGTH)).build()).build());
break;
case OPAQUE_TYPE_TRANS:
comm.setCommType(OPAQUE_TYPE_TRANS).setExtendedCommunity(
new OpaqueExtendedCommunityCaseBuilder().setOpaqueExtendedCommunity(
new OpaqueExtendedCommunityBuilder().setTransitive(false).setValue(ByteArray.readAllBytes(buffer)).build()).build());
break;
case OPAQUE_TYPE_NON_TRANS:
comm.setCommType(OPAQUE_TYPE_NON_TRANS).setExtendedCommunity(
new OpaqueExtendedCommunityCaseBuilder().setOpaqueExtendedCommunity(
new OpaqueExtendedCommunityBuilder().setTransitive(true).setValue(ByteArray.readAllBytes(buffer)).build()).build());
break;
default:
throw new BGPDocumentedException("Could not parse Extended Community type: " + type, BGPError.OPT_ATTR_ERROR);
}
return comm.build();
}
}
|
package com.hilotec.elexis.messwerte.v2.views;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.ViewPart;
import ch.elexis.core.data.events.ElexisEvent;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.core.data.events.ElexisEventListener;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.icons.Images;
import ch.elexis.core.ui.util.SWTHelper;
import ch.elexis.core.ui.util.ViewMenus;
import ch.elexis.data.Patient;
import ch.rgw.tools.TimeTool;
import com.hilotec.elexis.messwerte.v2.data.ExportData;
import com.hilotec.elexis.messwerte.v2.data.Messung;
import com.hilotec.elexis.messwerte.v2.data.MessungKonfiguration;
import com.hilotec.elexis.messwerte.v2.data.MessungTyp;
import com.hilotec.elexis.messwerte.v2.data.Messwert;
import com.hilotec.elexis.messwerte.v2.data.typen.IMesswertTyp;
public class MessungenUebersichtV21 extends ViewPart implements ElexisEventListener {
private static int DEFAULT_COL_WIDTH = 80;
private static String DATA_PATIENT = "patient"; //$NON-NLS-1$
private static String DATA_TYP = "typ"; //$NON-NLS-1$
private static String DATA_VIEWER = "viewer"; //$NON-NLS-1$
private MessungKonfiguration config;
private ScrolledForm form;
private CTabFolder tabfolder;
private final ArrayList<TableViewer> tableViewers;
private Action neuAktion;
private Action editAktion;
private Action copyAktion;
private Action loeschenAktion;
private Action exportAktion;
private Action reloadXMLAction;
public MessungenUebersichtV21(){
config = MessungKonfiguration.getInstance();
tableViewers = new ArrayList<TableViewer>();
}
private class CustomColumnLabelProvider extends ColumnLabelProvider {
private final String messwertName;
public CustomColumnLabelProvider(int columnIndex, String name){
messwertName = name;
}
@Override
public String getText(Object element){
Messung m = (Messung) element;
return m.getMesswert(messwertName).getDarstellungswert();
}
};
private void setCurPatient(Patient patient){
if (patient == null) {
form.setText(Messages.MessungenUebersicht_kein_Patient);
} else {
form.setText(patient.getLabel());
}
CTabItem tab = tabfolder.getSelection();
if (tab == null) {
refreshContent(patient, null);
} else {
Control c = tab.getControl();
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
refreshContent(patient, t);
}
}
public void catchElexisEvent(final ElexisEvent ev){
UiDesk.asyncExec(new Runnable() {
public void run(){
if (ev.getType() == ElexisEvent.EVENT_SELECTED) {
setCurPatient((Patient) ev.getObject());
} else if (ev.getType() == ElexisEvent.EVENT_DESELECTED) {
setCurPatient(null);
}
}
});
}
private final ElexisEvent eetmpl = new ElexisEvent(null, Patient.class,
ElexisEvent.EVENT_SELECTED | ElexisEvent.EVENT_DESELECTED);
public ElexisEvent getElexisEventFilter(){
return eetmpl;
}
@Override
public void createPartControl(Composite parent){
parent.setLayout(new GridLayout());
intializeView(parent);
if (form.getCursor() == null)
form.setCursor(new Cursor(form.getShell().getDisplay(), SWT.CURSOR_WAIT));
config = MessungKonfiguration.getInstance();
erstelleAktionen();
erstelleMenu(getViewSite());
initializeContent();
if (form.getCursor() != null)
form.setCursor(null);
}
@Override
public void setFocus(){
CTabItem tab = tabfolder.getSelection();
if(tab==null) return;
Control c = tab.getControl();
TableViewer tv = (TableViewer) c.getData(DATA_VIEWER);
if (tv != null) {
if (tv.getInput() == null) {
Patient p = (Patient) tabfolder.getData(DATA_PATIENT);
if (p == null) {
p = ElexisEventDispatcher.getSelectedPatient();
}
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
refreshContent(p, t);
}
}
}
private void intializeView(Composite parent){
form = UiDesk.getToolkit().createScrolledForm(parent);
form.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
form.setText(Messages.MessungenUebersicht_kein_Patient);
Composite body = form.getBody();
body.setLayout(new GridLayout());
tabfolder = new CTabFolder(body, SWT.NONE);
tabfolder.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
tabfolder.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e){
CTabFolder tf = (CTabFolder) e.widget;
Patient p = (Patient) tf.getData(DATA_PATIENT);
if (p == null) {
return;
}
CTabItem tab = tf.getSelection();
Control c = tab.getControl();
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
refreshContent(p, t);
}
public void widgetDefaultSelected(SelectionEvent e){
// Auto-generated method stub, but not needed
}
});
ElexisEventDispatcher.getInstance().addListeners(this);
}
private void initializeContent(){
tableViewers.clear();
config.readFromXML();
for (MessungTyp t : config.getTypes()) {
TableViewer tv = createTableViewer(tabfolder, t);
Control c = tv.getControl();
c.setData(DATA_TYP, t);
c.setData(DATA_VIEWER, tv);
tableViewers.add(tv);
CTabItem ti = new CTabItem(tabfolder, SWT.NONE);
ti.setText(t.getTitle());
ti.setControl(c);
tv.setInput(null);
tv.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event){
editAktion.run();
}
});
ViewMenus menu = new ViewMenus(getViewSite());
menu.createControlContextMenu(tv.getControl(), editAktion, copyAktion, loeschenAktion,
neuAktion, exportAktion);
}
tabfolder.setSelection(0);
}
private void refreshContent(Patient patient, MessungTyp requestedTyp){
if (patient != null) {
if (form.getCursor() == null)
form.setCursor(new Cursor(form.getShell().getDisplay(), SWT.CURSOR_WAIT));
form.setText(patient.getLabel());
tabfolder.setData(DATA_PATIENT, patient);
MessungTyp typToRefresh = requestedTyp;
TableViewer viewerToRefresh = null;
for (TableViewer tv : tableViewers) {
Control c = tv.getControl();
if (!c.isDisposed()) {
MessungTyp typ = (MessungTyp) c.getData(DATA_TYP);
// bei unbekannten typen (z.B. bei reloadXML) einfach den ersten refreshen
if (typToRefresh == null) {
typToRefresh = typ;
viewerToRefresh = tv;
break;
} else {
if (requestedTyp.getName().equals(typ.getName())) {
typToRefresh = typ;
viewerToRefresh = tv;
break;
}
}
}
}
if(viewerToRefresh!=null) {
viewerToRefresh.setInput(Messung.getPatientMessungen(patient, typToRefresh));
}
if (form.getCursor() != null)
form.setCursor(null);
}
}
private TableViewer createTableViewer(Composite parent, MessungTyp t){
TableViewer viewer =
new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION
| SWT.BORDER);
createColumns(parent, viewer, t);
final Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
viewer.setContentProvider(new ArrayContentProvider());
// Make the selection available to other views
getSite().setSelectionProvider(viewer);
// Set the sorter for the table
// Layout the viewer
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
viewer.setComparator(new MessungenComparator());
return viewer;
}
private void createColumns(final Composite parent, final TableViewer viewer, MessungTyp t){
// First column is for the measure date
TableViewerColumn col;
col =
createTableViewerColumn(viewer, Messages.MessungenUebersicht_Table_Datum,
DEFAULT_COL_WIDTH, 0);
col.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element){
Messung m = (Messung) element;
return m.getDatum();
}
});
int i = 0;
for (IMesswertTyp dft : t.getMesswertTypen()) {
String colTitle = dft.getTitle();
if (!dft.getUnit().equals("")) //$NON-NLS-1$
colTitle += " [" + dft.getUnit() + "]"; //$NON-NLS-1$ //$NON-NLS-2$
col = createTableViewerColumn(viewer, colTitle, DEFAULT_COL_WIDTH, 0);
col.setLabelProvider(new CustomColumnLabelProvider(i, dft.getName()));
i++;
}
}
private TableViewerColumn createTableViewerColumn(final TableViewer viewer, String title,
int bound, final int colNumber){
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
column.addSelectionListener(getSelectionAdapter(viewer, column, colNumber));
return viewerColumn;
}
private SelectionAdapter getSelectionAdapter(final TableViewer viewer,
final TableColumn column, final int index){
SelectionAdapter selectionAdapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
MessungenComparator comparator = (MessungenComparator) viewer.getComparator();
comparator.setColumn(0);
int dir = comparator.getDirection();
viewer.getTable().setSortDirection(dir);
viewer.getTable().setSortColumn(viewer.getTable().getColumn(0));
viewer.refresh();
}
};
return selectionAdapter;
}
/**
* Aktionen fuer Menuleiste und Kontextmenu initialisieren
*/
private void erstelleAktionen(){
neuAktion = new Action(Messages.MessungenUebersicht_action_neu) {
{
setImageDescriptor(Images.IMG_ADDITEM.getImageDescriptor());
setToolTipText(Messages.MessungenUebersicht_action_neu_ToolTip);
}
@Override
public void run(){
Patient p = (Patient) tabfolder.getData(DATA_PATIENT);
if (p == null) {
return;
}
CTabItem tab = tabfolder.getSelection();
Control c = tab.getControl();
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
Messung messung = new Messung(p, t);
MessungBearbeiten dialog = new MessungBearbeiten(getSite().getShell(), messung);
if (dialog.open() != Dialog.OK) {
messung.delete();
}
refreshContent(p, t);
}
};
editAktion = new Action(Messages.MessungenUebersicht_action_edit) {
{
setImageDescriptor(Images.IMG_EDIT.getImageDescriptor());
setToolTipText(Messages.MessungenUebersicht_action_edit_ToolTip);
}
@Override
public void run(){
Patient p = (Patient) tabfolder.getData(DATA_PATIENT);
if (p == null) {
return;
}
CTabItem tab = tabfolder.getSelection();
Control c = tab.getControl();
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
TableItem[] tableitems = ((Table) c).getSelection();
if (tableitems.length == 1) {
Messung messung = (Messung) tableitems[0].getData();
MessungBearbeiten dialog = new MessungBearbeiten(getSite().getShell(), messung);
if (dialog.open() == Dialog.OK) {
refreshContent(p, t);
}
}
}
};
copyAktion = new Action(Messages.MessungenUebersicht_action_copy) {
{
setImageDescriptor(Images.IMG_CLIPBOARD.getImageDescriptor());
setToolTipText(Messages.MessungenUebersicht_action_copy_ToolTip);
}
@Override
public void run(){
Patient p = (Patient) tabfolder.getData(DATA_PATIENT);
if (p == null) {
return;
}
CTabItem tab = tabfolder.getSelection();
Control c = tab.getControl();
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
TableItem[] tableitems = ((Table) c).getSelection();
if (tableitems.length == 1) {
Messung messung = (Messung) tableitems[0].getData();
String messungsdatum = messung.getDatum();
TimeTool date = new TimeTool();
String newdatum = date.toString(TimeTool.DATE_GER);
if (!messungsdatum.equalsIgnoreCase(newdatum)) {
// Nur wenn Messung nich vom selben Tag wie heute!!
System.out.println(messung.getDatum());
System.out.println(date.toString(TimeTool.DATE_GER));
Messung messungnew = new Messung(messung.getPatient(), messung.getTyp());
messungnew.setDatum(date.toString(TimeTool.DATE_GER));
for (Messwert messwert : messung.getMesswerte()) {
Messwert copytemp = messungnew.getMesswert(messwert.getName());
copytemp.setWert(messwert.getWert());
}
messungnew.set("deleted", "0");
refreshContent(p, t);
} else {
SWTHelper.showError(Messages.MessungenUebersicht_action_copy_error,
Messages.MessungenUebersicht_action_copy_errorMessage);
}
}
}
};
loeschenAktion = new Action(Messages.MessungenUebersicht_action_loeschen) {
{
setImageDescriptor(Images.IMG_DELETE.getImageDescriptor());
setToolTipText(Messages.MessungenUebersicht_action_loeschen_ToolTip);
}
@Override
public void run(){
Patient p = (Patient) tabfolder.getData(DATA_PATIENT);
if (p == null) {
return;
}
CTabItem tab = tabfolder.getSelection();
Control c = tab.getControl();
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
TableItem[] tableitems = ((Table) c).getSelection();
if ((tableitems.length > 0)
&& SWTHelper.askYesNo(Messages.MessungenUebersicht_action_loeschen_delete_0,
Messages.MessungenUebersicht_action_loeschen_delete_1)) {
for (TableItem ti : tableitems) {
Messung messung = (Messung) ti.getData();
messung.delete();
}
refreshContent(p, t);
}
}
};
exportAktion = new Action(Messages.MessungenUebersicht_action_export) {
{
setImageDescriptor(Images.IMG_EXPORT.getImageDescriptor());
setToolTipText(Messages.MessungenUebersicht_action_export_ToolTip);
}
@Override
public void run(){
Patient p = (Patient) tabfolder.getData(DATA_PATIENT);
CTabItem tab = tabfolder.getSelection();
Control c = tab.getControl();
MessungTyp t = (MessungTyp) c.getData(DATA_TYP);
ExportData expData = new ExportData();
if (p != null) {
expData.setPatientNumberFrom(Integer.parseInt(p.getPatCode()));
expData.setPatientNumberTo(Integer.parseInt(p.getPatCode()));
}
ExportDialog expDialog = new ExportDialog(form.getShell(), expData);
if (expDialog.open() == Dialog.OK) {
String label = t.getTitle();
String date = new TimeTool().toString(TimeTool.DATE_COMPACT);
String filename = label + "-export-" + date + ".csv"; //$NON-NLS-1$ //$NON-NLS-2$
FileDialog fd = new FileDialog(getSite().getShell(), SWT.SAVE);
String[] extensions = {
"*.csv" //$NON-NLS-1$
};
fd.setOverwrite(true);
fd.setFilterExtensions(extensions);
fd.setFileName(filename);
fd.setFilterPath(System.getProperty("user.home")); //$NON-NLS-1$
String filepath = fd.open();
if (filepath != null) {
try {
Exporter exporter = new Exporter(expData, t, filepath);
new ProgressMonitorDialog(form.getShell()).run(true, true, exporter);
if (!exporter.wasAborted()) {
SWTHelper.showInfo(MessageFormat.format(
Messages.MessungenUebersicht_action_export_title, label),
MessageFormat.format(
Messages.MessungenUebersicht_action_export_success, label,
filepath));
} else {
SWTHelper.showError(MessageFormat.format(
Messages.MessungenUebersicht_action_export_title, label),
MessageFormat.format(
Messages.MessungenUebersicht_action_export_aborted, label,
filepath));
}
} catch (InvocationTargetException e) {
SWTHelper.showError(Messages.MessungenUebersichtV21_Error,
e.getMessage());
} catch (InterruptedException e) {
SWTHelper.showInfo(Messages.MessungenUebersichtV21_Cancelled,
e.getMessage());
}
} else {
SWTHelper.showInfo(Messages.MessungenUebersichtV21_Information,
Messages.MessungenUebersicht_action_export_filepath_error);
}
}
}
};
reloadXMLAction = new Action(Messages.MessungenUebersicht_action_reload) {
{
setImageDescriptor(Images.IMG_REFRESH.getImageDescriptor());
setToolTipText(Messages.MessungenUebersicht_action_reload_ToolTip);
}
@Override
public void run(){
Patient p = (Patient) tabfolder.getData(DATA_PATIENT);
if (p == null) {
return;
}
for (CTabItem ci : tabfolder.getItems()) {
ci.getControl().dispose();
ci.dispose();
}
for (Control ctrl : tabfolder.getChildren()) {
ctrl.dispose();
}
if (form.getCursor() == null)
form.setCursor(new Cursor(form.getShell().getDisplay(), SWT.CURSOR_WAIT));
initializeContent();
refreshContent(p, null);
if (form.getCursor() != null)
form.setCursor(null);
}
};
}
/**
* Menuleiste generieren
*/
private ViewMenus erstelleMenu(IViewSite site){
ViewMenus menu = new ViewMenus(site);
menu.createToolbar(neuAktion, editAktion, copyAktion, loeschenAktion, exportAktion);
menu.createMenu(reloadXMLAction);
return menu;
}
class Exporter implements IRunnableWithProgress {
private final ExportData expData;
private final MessungTyp typ;
private final String filepath;
private Boolean aborted = false;
/**
* LongRunningOperation constructor
*
* @param indeterminate
* whether the animation is unknown
*/
public Exporter(ExportData xpd, MessungTyp t, String fp){
expData = xpd;
typ = t;
filepath = fp;
}
/**
* Runs the long running operation
*
* @param monitor
* the progress monitor
*/
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException{
monitor.beginTask(Messages.MessungenUebersichtV21_Initializing,
IProgressMonitor.UNKNOWN);
try {
FileOutputStream fout = new FileOutputStream(filepath);
OutputStreamWriter writer = new OutputStreamWriter(fout, "ISO-8859-1"); //$NON-NLS-1$
ArrayList<IMesswertTyp> messwertTypen = typ.getMesswertTypen();
String headerstring = "PatientenNr;Name;Vorname;Geburtsdatum;Geschlecht;datum;"; //$NON-NLS-1$
for (IMesswertTyp messwertTyp : messwertTypen) {
headerstring = headerstring + messwertTyp.getName();
String unit = messwertTyp.getUnit();
if (!"".equals(unit))
headerstring += "(" //$NON-NLS-1$
+ messwertTyp.getUnit() + ")"; //$NON-NLS-2$
headerstring += ";"; //$NON-NLS-1$
}
headerstring = headerstring.substring(0, headerstring.length() - 1);
writer.append(headerstring + "\n"); //$NON-NLS-1$
List<Messung> messungen =
Messung.getMessungenForExport(typ, expData.getDateFrom(), expData.getDateTo());
monitor.beginTask(Messages.MessungenUebersicht_action_export_progress,
messungen.size());
for (Messung m : messungen) {
Patient p = Patient.load(m.getPatient().getId());
int curPatNr = -1;
try {
curPatNr = Integer.parseInt(p.getPatCode());
} catch (Exception e) {}
if ((curPatNr >= expData.getPatientNumberFrom())
&& (curPatNr <= expData.getPatientNumberTo())) {
monitor.subTask(p.getLabel() + " - " + m.getDatum()); //$NON-NLS-1$
String messungstring = m.getPatient().getPatCode() + ";"; //$NON-NLS-1$
messungstring += m.getPatient().getName() + ";"; //$NON-NLS-1$
messungstring += m.getPatient().getVorname() + ";"; //$NON-NLS-1$
messungstring += m.getPatient().getGeburtsdatum() + ";"; //$NON-NLS-1$
messungstring += m.getPatient().getGeschlecht() + ";"; //$NON-NLS-1$
messungstring += m.getDatum() + ";"; //$NON-NLS-1$
for (Messwert messwert : m.getMesswerte()) {
messungstring += messwert.getWert() + ";"; //$NON-NLS-1$
}
messungstring = messungstring.substring(0, messungstring.length() - 1);
writer.append(messungstring + "\n"); //$NON-NLS-1$
}
monitor.worked(1);
if (monitor.isCanceled()) {
aborted = true;
break;
}
}
writer.flush();
writer.close();
fout.flush();
fout.close();
} catch (Exception e) {
SWTHelper.showError(Messages.MessungenUebersicht_action_export_error, e.toString());
}
monitor.done();
}
private Boolean wasAborted(){
return aborted;
}
}
}
|
package gov.nih.nci.cabig.caaers.domain.repository;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.dao.OrganizationConverterDao;
import gov.nih.nci.cabig.caaers.dao.OrganizationDao;
import gov.nih.nci.cabig.caaers.dao.query.OrganizationFromStudySiteQuery;
import gov.nih.nci.cabig.caaers.dao.query.OrganizationQuery;
import gov.nih.nci.cabig.caaers.dao.query.StudyOrganizationsQuery;
import gov.nih.nci.cabig.caaers.domain.ConverterOrganization;
import gov.nih.nci.cabig.caaers.domain.LocalOrganization;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.RemoteOrganization;
import gov.nih.nci.cabig.caaers.domain.StudyOrganization;
import gov.nih.nci.cabig.caaers.event.EventFactory;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Srini Akala
* @author Monish Dombla
*
*/
@Transactional
public class OrganizationRepositoryImpl implements OrganizationRepository {
private Logger log = Logger.getLogger(getClass());
private OrganizationDao organizationDao;
private OrganizationConverterDao organizationConverterDao;
private boolean coppaModeForAutoCompleters;
private EventFactory eventFactory;
public void createOrUpdate(Organization organization) {
if (organization.getId() == null) {
create(organization);
} else {
organizationDao.save(organization);
}
}
/**
* Create a new organization. Note that this method must be used when entering a new
* organization (not {@link OrganizationDao#save}). As written, it is not suitable for updating
* an existing organization.
*
* @param site
* @throws CaaersSystemException
*/
public void create(Organization site) throws CaaersSystemException {
organizationDao.save(site);
eventFactory.publishEntityModifiedEvent(new LocalOrganization(), false);
}
/**
* This method is used in the Import Organizations flow. This will avoid calls to COPPA when importing Organization_Codes.txt from CTEP.
* @param organization
* @throws CaaersSystemException
*/
public void saveImportedOrganization(Organization organization) throws CaaersSystemException{
if (organization.getId() == null) {
organizationDao.saveImportedOrganization(organization);
} else {
organizationDao.saveImportedOrganization(organization);
}
}
@Required
public void setOrganizationDao(OrganizationDao organizationDao) {
this.organizationDao = organizationDao;
}
public List<Organization> getOrganizationsHavingStudySites(OrganizationFromStudySiteQuery query ) {
return organizationDao.getOrganizationsHavingStudySites(query);
}
/**
* This method converts a LocalOrganization to a RemoteOrganization.
*
*/
public void convertToRemote(Organization localOrganization,
Organization remoteOrganization) {
ConverterOrganization conOrg = organizationConverterDao.getById(localOrganization.getId());
conOrg.setType("REMOTE");
conOrg.setExternalId(remoteOrganization.getExternalId());
conOrg.setName(remoteOrganization.getName());
conOrg.setNciInstituteCode(remoteOrganization.getNciInstituteCode());
conOrg.setCity(remoteOrganization.getCity());
conOrg.setState(remoteOrganization.getState());
conOrg.setCountry(remoteOrganization.getCountry());
organizationConverterDao.save(conOrg);
}
public List<Organization> getLocalOrganizations(final OrganizationQuery query){
return organizationDao.getLocalOrganizations(query);
}
@SuppressWarnings("unchecked")
public List<Organization> searchRemoteOrganization(String coppaSearchText, String sType){
//List organizations = organizationDao.getLocalOrganizations(query);
Organization searchCriteria = new RemoteOrganization();
if (sType.equals("name")) {
searchCriteria.setName(coppaSearchText);
}
if (sType.equals("nciInstituteCode")) {
searchCriteria.setNciInstituteCode(coppaSearchText);
}
List<Organization> remoteOrganizations = organizationDao.getRemoteOrganizations(searchCriteria);
return remoteOrganizations;
}
@SuppressWarnings("unchecked")
public List<Organization> getApplicableOrganizationsFromStudySites(String text, Integer studyId){
OrganizationFromStudySiteQuery query = new OrganizationFromStudySiteQuery();
if(StringUtils.isNotBlank(text))
query.filterByOrganizationNameOrNciCode(text);
if(studyId != null)
query.filterByStudy(studyId);
List<Organization> organizations = organizationDao.getApplicableOrganizationsFromStudySites(query);
return organizations;
}
@SuppressWarnings("unchecked")
public List<Organization> searchOrganization(final OrganizationQuery query){
List organizations = organizationDao.getLocalOrganizations(query);
// to get remote organizations ...
Organization searchCriteria = new RemoteOrganization();
Map<String, Object> queryParameterMap = query.getParameterMap();
for(Map.Entry<String, Object> entry : queryParameterMap.entrySet()){
if (entry.getKey().equals("name")) {
searchCriteria.setName(entry.getValue().toString());
}
if (entry.getKey().equals("nciInstituteCode")) {
searchCriteria.setNciInstituteCode(entry.getValue().toString());
}
}
List<Organization> remoteOrganizations = organizationDao.getRemoteOrganizations(searchCriteria);
if (remoteOrganizations.size() > 0) {
return mergeOrgs(organizations,remoteOrganizations);
}
return organizations;
}
public List<Organization> restrictBySubnames(final String[] subnames) {
return restrictBySubnames(subnames, false);
}
public List<StudyOrganization> getApplicableOrganizationsFromStudyOrganizations(final String text, Integer studyId) {
StudyOrganizationsQuery query = new StudyOrganizationsQuery();
if(text != null && !text.equals(""))
query.filterByOrganizationName(text);
if(studyId != null)
query.filterByStudyId(studyId);
List<StudyOrganization> organizations = (List<StudyOrganization>)organizationDao.search(query);
return organizations;
}
public List<Organization> restrictBySubnames(final String[] subnames, boolean skipFiltering) {
String text = subnames[0];
OrganizationQuery query = new OrganizationQuery();
query.filterByOrganizationNameOrNciCode(text);
query.setFiltered(skipFiltering);
List<Organization> localOrganizations;
localOrganizations = organizationDao.getBySubnames(query);
//get organizations from remote service
List<Organization> remoteOrganizations = null;
if (coppaModeForAutoCompleters) {
Organization searchCriteria = new RemoteOrganization();
searchCriteria.setNciInstituteCode(subnames[0]);
remoteOrganizations = organizationDao.getRemoteOrganizations(searchCriteria);
} else {
return localOrganizations;
}
return mergeOrgs (localOrganizations,remoteOrganizations);
}
private List<Organization> mergeOrgs(List<Organization> localList , List<Organization> remoteList) {
for (Organization remoteOrganization:remoteList) {
Organization org = organizationDao.getByNCIcode(remoteOrganization.getNciInstituteCode());
if (org == null ) {
createOrUpdate(remoteOrganization);
localList.add(remoteOrganization);
} else {
if (!localList.contains(org)) {
localList.add(org);
}
}
}
return localList;
}
public void setOrganizationConverterDao(
OrganizationConverterDao organizationConverterDao) {
this.organizationConverterDao = organizationConverterDao;
}
public void setCoppaModeForAutoCompleters(boolean coppaModeForAutoCompleters) {
this.coppaModeForAutoCompleters = coppaModeForAutoCompleters;
}
/**
* This method will fetch all the organizations in caAERS database.
*/
public List<Organization> getAllOrganizations() {
return organizationDao.getAll();
}
public List<Organization> getAllNciInstitueCodes() {
return null;
}
/* (non-Javadoc)
* @see gov.nih.nci.cabig.caaers.domain.repository.OrganizationRepository#getById(int)
*/
public Organization getById(int id) {
return organizationDao.getById(id);
}
/* (non-Javadoc)
* @see gov.nih.nci.cabig.caaers.domain.repository.OrganizationRepository#evict(gov.nih.nci.cabig.caaers.domain.Organization)
*/
public void evict(Organization org) {
organizationDao.evict(org);
}
public void setEventFactory(EventFactory eventFactory) {
this.eventFactory = eventFactory;
}
}
|
package io.strimzi.controller.cluster.operations.resource;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet;
import io.fabric8.kubernetes.api.model.extensions.StatefulSet;
import io.fabric8.kubernetes.api.model.extensions.StatefulSetList;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.RollableScalableResource;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Operations for {@code StatefulSets}s, which supports {@link #rollingUpdate(String, String, Handler)}
* in addition to the usual operations.
*/
public class StatefulSetOperations extends AbstractScalableOperations<KubernetesClient, StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>> {
private static final Logger log = LoggerFactory.getLogger(StatefulSetOperations.class.getName());
private final PodOperations podOperations;
/**
* Constructor
* @param vertx The Vertx instance
* @param client The Kubernetes client
*/
public StatefulSetOperations(Vertx vertx, KubernetesClient client) {
super(vertx, client, "StatefulSet");
this.podOperations = new PodOperations(vertx, client);
}
@Override
protected MixedOperation<StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>> operation() {
return client.apps().statefulSets();
}
public void rollingUpdate(String namespace, String name, Handler<AsyncResult<Void>> handler) {
final int replicas = get(namespace, name).getSpec().getReplicas();
vertx.createSharedWorkerExecutor("kubernetes-ops-pool").executeBlocking(
future -> {
try {
log.info("Doing rolling update of stateful set {} in namespace {}", name, namespace);
for (int i = 0; i < replicas; i++) {
String podName = name + "-" + i;
log.info("Rolling pod {}", podName);
Future deleted = Future.future();
Watcher<Pod> watcher = new RollingUpdateWatcher(deleted);
Watch watch = podOperations.watch(namespace, podName, watcher);
Future fut = podOperations.delete(namespace, podName);
// TODO do this async
while (!fut.isComplete() || !deleted.isComplete()) {
log.info("Waiting for pod {} to be deleted", podName);
Thread.sleep(1000);
}
// TODO Check success of fut and deleted futures
watch.close();
while (!podOperations.isPodReady(namespace, podName)) {
log.info("Waiting for pod {} to get ready", podName);
Thread.sleep(1000);
}
log.info("Pod {} rolling update complete", podName);
}
future.complete();
} catch (Exception e) {
log.error("Caught exception while doing manual rolling update of stateful set {} in namespace {}", name, namespace);
future.fail(e);
}
},
false,
res -> {
if (res.succeeded()) {
log.info("Stateful set {} in namespace {} has been rolled", name, namespace);
handler.handle(Future.succeededFuture());
} else {
log.error("Failed to do rolling update of stateful set {} in namespace {}: {}", name, namespace, res.cause().toString());
handler.handle(Future.failedFuture(res.cause()));
}
}
);
}
static class RollingUpdateWatcher implements Watcher<Pod> {
//private static final Logger log = LoggerFactory.getLogger(RollingUpdateWatcher.class.getName());
private final Future deleted;
public RollingUpdateWatcher(Future deleted) {
this.deleted = deleted;
}
@Override
public void eventReceived(Action action, Pod pod) {
switch (action) {
case DELETED:
log.info("Pod has been deleted");
deleted.complete();
break;
case ADDED:
case MODIFIED:
log.info("Ignored action {} while waiting for Pod deletion", action);
break;
case ERROR:
log.error("Error while waiting for Pod deletion");
break;
default:
log.error("Unknown action {} while waiting for pod deletion", action);
}
}
@Override
public void onClose(KubernetesClientException e) {
if (e != null && !deleted.isComplete()) {
log.error("Kubernetes watcher has been closed with exception!", e);
deleted.fail(e);
} else {
log.info("Kubernetes watcher has been closed!");
}
}
}
}
|
package net.sf.mpxj;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import net.sf.mpxj.listener.FieldListener;
import net.sf.mpxj.utility.BooleanUtility;
import net.sf.mpxj.utility.DateUtility;
import net.sf.mpxj.utility.NumberUtility;
/**
* This class represents a task record from an MPX file.
*/
public final class Task extends ProjectEntity implements Comparable, FieldContainer
{
/**
* Default constructor.
*
* @param file Parent file to which this record belongs.
* @param parent Parent task
*/
Task (ProjectFile file, Task parent)
{
super(file);
setType (TaskType.FIXED_UNITS);
m_parent = parent;
if (file.getAutoTaskUniqueID() == true)
{
setUniqueID(new Integer(file.getTaskUniqueID()));
}
if (file.getAutoTaskID() == true)
{
setID(new Integer(file.getTaskID()));
}
if (file.getAutoWBS() == true)
{
generateWBS(parent);
}
if (file.getAutoOutlineNumber() == true)
{
generateOutlineNumber(parent);
}
if (file.getAutoOutlineLevel() == true)
{
if (parent == null)
{
setOutlineLevel(new Integer(1));
}
else
{
setOutlineLevel(new Integer(NumberUtility.getInt(parent.getOutlineLevel()) + 1));
}
}
}
/**
* This method is used to automatically generate a value
* for the WBS field of this task.
*
* @param parent Parent Task
*/
public void generateWBS (Task parent)
{
String wbs;
if (parent == null)
{
if (NumberUtility.getInt(getUniqueID()) == 0)
{
wbs = "0";
}
else
{
wbs = Integer.toString(getParentFile().getChildTaskCount() + 1) + ".0";
}
}
else
{
wbs = parent.getWBS();
int index = wbs.lastIndexOf(".0");
if (index != -1)
{
wbs = wbs.substring(0, index);
}
if (wbs.equals("0") == true)
{
wbs = Integer.toString(parent.getChildTaskCount() + 1);
}
else
{
wbs += ("." + (parent.getChildTaskCount() + 1));
}
}
setWBS(wbs);
}
/**
* This method is used to automatically generate a value
* for the Outline Number field of this task.
*
* @param parent Parent Task
*/
public void generateOutlineNumber (Task parent)
{
String outline;
if (parent == null)
{
if (NumberUtility.getInt(getUniqueID()) == 0)
{
outline = "0";
}
else
{
outline = Integer.toString(getParentFile().getChildTaskCount() + 1) + ".0";
}
}
else
{
outline = parent.getOutlineNumber();
int index = outline.lastIndexOf(".0");
if (index != -1)
{
outline = outline.substring(0, index);
}
if (outline.equals("0") == true)
{
outline = Integer.toString(parent.getChildTaskCount() + 1);
}
else
{
outline += ("." + (parent.getChildTaskCount() + 1));
}
}
setOutlineNumber(outline);
}
/**
* This method is used to add notes to the current task.
*
* @param notes notes to be added
*/
public void setNotes (String notes)
{
set(TaskField.NOTES, notes);
}
/**
* This method allows nested tasks to be added, with the WBS being
* completed automatically.
*
* @return new task
*/
public Task addTask ()
{
ProjectFile parent = getParentFile();
Task task = new Task(parent, this);
m_children.add(task);
parent.addTask(task);
setSummary(true);
return (task);
}
/**
* This method is used to associate a child task with the current
* task instance. It has package access, and has been designed to
* allow the hierarchical outline structure of tasks in an MPX
* file to be constructed as the file is read in.
*
* @param child Child task.
* @param childOutlineLevel Outline level of the child task.
* @throws MPXJException Thrown if an invalid outline level is supplied.
*/
public void addChildTask (Task child, int childOutlineLevel)
throws MPXJException
{
int outlineLevel = NumberUtility.getInt(getOutlineLevel());
if ((outlineLevel + 1) == childOutlineLevel)
{
m_children.add(child);
}
else
{
if (m_children.isEmpty() == false)
{
((Task)m_children.get(m_children.size()-1)).addChildTask(child, childOutlineLevel);
}
}
}
/**
* This method is used to associate a child task with the current
* task instance. It has package access, and has been designed to
* allow the hierarchical outline structure of tasks in an MPX
* file to be updated once all of the task data has been read.
*
* @param child child task
*/
void addChildTask (Task child)
{
child.m_parent = this;
m_children.add(child);
}
/**
* Removes a child task.
*
* @param child child task instance
*/
void removeChildTask (Task child)
{
m_children.remove(child);
setSummary(!m_children.isEmpty());
}
/**
* This method allows the list of child tasks to be cleared in preparation
* for the hierarchical task structure to be built.
*/
void clearChildTasks ()
{
m_children.clear();
}
/**
* This method allows recurring task details to be added to the
* current task.
*
* @return RecurringTask object
* @throws MPXJException thrown if more than one one recurring task is added
*/
public RecurringTask addRecurringTask ()
throws MPXJException
{
if (m_recurringTask != null)
{
throw new MPXJException(MPXJException.MAXIMUM_RECORDS);
}
m_recurringTask = new RecurringTask();
return (m_recurringTask);
}
/**
* This method retrieves the recurring task record. If the current
* task is not a recurring task, then this method will return null.
*
* @return Recurring task record.
*/
public RecurringTask getRecurringTask ()
{
return (m_recurringTask);
}
/**
* This method allows a resource assignment to be added to the
* current task.
*
* @param resource the resource to assign
* @return ResourceAssignment object
*/
public ResourceAssignment addResourceAssignment (Resource resource)
{
Iterator iter = m_assignments.iterator();
ResourceAssignment assignment = null;
Integer resourceUniqueID = resource.getUniqueID();
Integer uniqueID;
while (iter.hasNext() == true)
{
assignment = (ResourceAssignment)iter.next();
uniqueID = assignment.getResourceUniqueID();
if (uniqueID.equals(resourceUniqueID) == true)
{
break;
}
assignment = null;
}
if (assignment == null)
{
assignment = new ResourceAssignment(getParentFile(), this);
m_assignments.add(assignment);
getParentFile().addResourceAssignment(assignment);
assignment.setResourceID(resource.getID());
assignment.setResourceUniqueID(resourceUniqueID);
assignment.setWork(getDuration());
assignment.setUnits(ResourceAssignment.DEFAULT_UNITS);
resource.addResourceAssignment(assignment);
}
return (assignment);
}
/**
* This method allows a resource assignment to be added to the
* current task. The data for the resource assignment is derived from
* an MPX file record.
*
* @return ResourceAssignment object
*/
public ResourceAssignment addResourceAssignment ()
{
ResourceAssignment assignment = new ResourceAssignment(getParentFile(), this);
m_assignments.add(assignment);
getParentFile().getAllResourceAssignments().add(assignment);
return (assignment);
}
/**
* This method allows the list of resource assignments for this
* task to be retrieved.
*
* @return list of resource assignments
*/
public List getResourceAssignments ()
{
return (m_assignments);
}
/**
* Internal method used as part of the process of removing a
* resource assignment.
*
* @param assignment resource assignment to be removed
*/
void removeResourceAssignment (ResourceAssignment assignment)
{
m_assignments.remove(assignment);
}
/**
* This method allows a predecessor relationship to be added to this
* task instance.
*
* @return relationship
*/
public Relation addPredecessor ()
{
return (addPredecessor(null));
}
/**
* This method allows a predecessor relationship to be added to this
* task instance.
*
* @param task the predecessor task
* @return relationship
*/
public Relation addPredecessor (Task task)
{
// Retrieve the list of predecessors
List list = (List)get(TaskField.PREDECESSORS);
if (list == null)
{
list = new LinkedList();
set(TaskField.PREDECESSORS, list);
}
// Ensure that there is only one relationship between
// these two tasks.
Relation rel = null;
if (task != null)
{
Iterator iter = list.iterator();
while (iter.hasNext() == true)
{
rel = (Relation)iter.next();
if (NumberUtility.equals(rel.getTaskID(), task.getID()))
{
break;
}
rel = null;
}
}
// If necessary, create a new relationship
if (rel == null)
{
rel = new Relation(getParentFile());
if (task != null)
{
rel.setTaskID(task.getID());
rel.setTaskUniqueID(task.getUniqueID());
}
list.add(rel);
}
return (rel);
}
/**
* This method allows a predecessor relationship to be added to this
* task instance.
*
* @return relationship
*/
public Relation addUniqueIdPredecessor ()
{
return (addUniqueIdPredecessor(null));
}
/**
* This method allows a predecessor relationship to be added to this
* task instance.
*
* @param task the predecessor task
* @return relationship
*/
public Relation addUniqueIdPredecessor (Task task)
{
// Retrieve the list of predecessors
List list = (List)get(TaskField.UNIQUE_ID_PREDECESSORS);
if (list == null)
{
list = new LinkedList();
set(TaskField.UNIQUE_ID_PREDECESSORS, list);
}
// Ensure that there is only one relationship between
// these two tasks.
Relation rel = null;
if (task != null)
{
Iterator iter = list.iterator();
while (iter.hasNext() == true)
{
rel = (Relation)iter.next();
if (NumberUtility.equals(rel.getTaskUniqueID(), task.getUniqueID()))
{
break;
}
rel = null;
}
}
// If necessary, create a new relationship
if (rel == null)
{
rel = new Relation(getParentFile());
if (task != null)
{
rel.setTaskID(task.getID());
rel.setTaskUniqueID(task.getUniqueID());
}
list.add(rel);
}
return (rel);
}
/**
* This method allows a successor relationship to be added to this
* task instance.
*
* @return relationship
*/
public Relation addSuccessor ()
{
return (addSuccessor(null));
}
/**
* This method allows a successor relationship to be added to this
* task instance.
*
* @param task the successor task
* @return relationship
*/
public Relation addSuccessor (Task task)
{
List list = (List)get(TaskField.SUCCESSORS);
if (list == null)
{
list = new LinkedList();
set(TaskField.SUCCESSORS, list);
}
Relation rel = new Relation(getParentFile());
if (task != null)
{
rel.setTaskID(task.getID());
rel.setTaskUniqueID(task.getUniqueID());
}
list.add(rel);
return (rel);
}
/**
* This method allows a successor relationship to be added to this
* task instance.
*
* @return relationship
*/
public Relation addUniqueIdSuccessor ()
{
return (addUniqueIdSuccessor(null));
}
/**
* This method allows a successor relationship to be added to this
* task instance.
*
* @param task the successor task
* @return relationship
*/
public Relation addUniqueIdSuccessor (Task task)
{
List list = (List)get(TaskField.UNIQUE_ID_SUCCESSORS);
if (list == null)
{
list = new LinkedList();
set(TaskField.UNIQUE_ID_SUCCESSORS, list);
}
Relation rel = new Relation(getParentFile());
if (task != null)
{
rel.setTaskID(task.getID());
rel.setTaskUniqueID(task.getUniqueID());
}
list.add(rel);
return (rel);
}
/**
* The %Complete field contains the current status of a task, expressed
* as the percentage of the
* task's duration that has been completed. You can enter percent complete,
* or you can have
* Microsoft Project calculate it for you based on actual duration.
*
* @param val value to be set
*/
public void setPercentageComplete (Number val)
{
set(TaskField.PERCENT_COMPLETE, val);
}
/**
* The %Work Complete field contains the current status of a task,
* expressed as the
* percentage of the task's work that has been completed. You can enter
* percent work
* complete, or you can have Microsoft Project calculate it for you
* based on actual
* work on the task.
*
* @param val value to be set
*/
public void setPercentageWorkComplete (Number val)
{
set(TaskField.PERCENT_WORK_COMPLETE, val);
}
/**
* The Actual Cost field shows costs incurred for work already performed
* by all resources
* on a task, along with any other recorded costs associated with the task.
* You can enter
* all the actual costs or have Microsoft Project calculate them for you.
*
* @param val value to be set
*/
public void setActualCost (Number val)
{
set(TaskField.ACTUAL_COST, val);
}
/**
* The Actual Duration field shows the span of actual working time for a
* task so far,
* based on the scheduled duration and current remaining work or
* completion percentage.
*
* @param val value to be set
*/
public void setActualDuration (Duration val)
{
set(TaskField.ACTUAL_DURATION, val);
}
/**
* The Actual Finish field shows the date and time that a task actually
* finished.
* Microsoft Project sets the Actual Finish field to the scheduled finish
* date if
* the completion percentage is 100. This field contains "NA" until you
* enter actual
* information or set the completion percentage to 100.
*
* @param val value to be set
*/
public void setActualFinish (Date val)
{
set(TaskField.ACTUAL_FINISH, val);
}
/**
* The Actual Start field shows the date and time that a task actually began.
* When a task is first created, the Actual Start field contains "NA." Once you
* enter the first actual work or a completion percentage for a task, Microsoft
* Project sets the actual start date to the scheduled start date.
* @param val value to be set
*/
public void setActualStart (Date val)
{
set(TaskField.ACTUAL_START, val);
}
/**
* The Actual Work field shows the amount of work that has already been
* done by the
* resources assigned to a task.
* @param val value to be set
*/
public void setActualWork (Duration val)
{
set(TaskField.ACTUAL_WORK, val);
}
/**
* The Baseline Cost field shows the total planned cost for a task.
* Baseline cost is also referred to as budget at completion (BAC).
*
* @param val the amount to be set
*/
public void setBaselineCost (Number val)
{
set(TaskField.BASELINE_COST, val);
}
/**
* The Baseline Duration field shows the original span of time planned to
* complete a task.
*
* @param val duration
*/
public void setBaselineDuration (Duration val)
{
set(TaskField.BASELINE_DURATION, val);
}
/**
* The Baseline Finish field shows the planned completion date for a
* task at the time
* you saved a baseline. Information in this field becomes available
* when you set a
* baseline for a task.
*
* @param val Date to be set
*/
public void setBaselineFinish (Date val)
{
set(TaskField.BASELINE_FINISH, val);
}
/**
* The Baseline Start field shows the planned beginning date for a task at
* the time
* you saved a baseline. Information in this field becomes available when you
* set a baseline.
*
* @param val Date to be set
*/
public void setBaselineStart (Date val)
{
set(TaskField.BASELINE_START, val);
}
/**
* The Baseline Work field shows the originally planned amount of work to
* be performed
* by all resources assigned to a task. This field shows the planned
* person-hours
* scheduled for a task. Information in the Baseline Work field
* becomes available
* when you set a baseline for the project.
*
* @param val the duration to be set.
*/
public void setBaselineWork (Duration val)
{
set(TaskField.BASELINE_WORK, val);
}
/**
* The BCWP (budgeted cost of work performed) field contains the
* cumulative value
* of the assignment's timephased percent complete multiplied by
* the assignments
* timephased baseline cost. BCWP is calculated up to the status
* date or todays
* date. This information is also known as earned value.
*
* @param val the amount to be set
*/
public void setBCWP (Number val)
{
set(TaskField.BCWP, val);
}
/**
* The BCWS (budgeted cost of work scheduled) field contains the cumulative
* timephased baseline costs up to the status date or today's date.
*
* @param val the amount to set
*/
public void setBCWS (Number val)
{
set(TaskField.BCWS, val);
}
/**
* The Confirmed field indicates whether all resources assigned to a task have
* accepted or rejected the task assignment in response to a TeamAssign message
* regarding their assignments.
*
* @param val boolean value
*/
public void setConfirmed (boolean val)
{
set(TaskField.CONFIRMED, val);
}
/**
* The Constraint Date field shows the specific date associated with certain
* constraint types,
* such as Must Start On, Must Finish On, Start No Earlier Than,
* Start No Later Than,
* Finish No Earlier Than, and Finish No Later Than.
* SEE class constants
*
* @param val Date to be set
*/
public void setConstraintDate (Date val)
{
set(TaskField.CONSTRAINT_DATE, val);
}
/**
* Private method for dealing with string parameters from File.
*
* @param type string constraint type
*/
public void setConstraintType (ConstraintType type)
{
set(TaskField.CONSTRAINT_TYPE, type);
}
/**
* The Contact field contains the name of an individual
* responsible for a task.
*
* @param val value to be set
*/
public void setContact (String val)
{
set(TaskField.CONTACT, val);
}
/**
* The Cost field shows the total scheduled, or projected, cost for a task,
* based on costs already incurred for work performed by all resources assigned
* to the task, in addition to the costs planned for the remaining work for the
* assignment. This can also be referred to as estimate at completion (EAC).
*
* @param val amount
*/
public void setCost (Number val)
{
set(TaskField.COST, val);
}
/**
* The Cost1-10 fields show any custom task cost information you want to enter
* in your project.
*
* @param val amount
*/
public void setCost1 (Number val)
{
set(TaskField.COST1, val);
}
/**
* The Cost1-10 fields show any custom task cost information you want to
* enter in your project.
*
* @param val amount
*/
public void setCost2 (Number val)
{
set(TaskField.COST2, val);
}
/**
* The Cost1-10 fields show any custom task cost information you want to
* enter in your project.
*
* @param val amount
*/
public void setCost3 (Number val)
{
set(TaskField.COST3, val);
}
/**
* The Cost Variance field shows the difference between the
* baseline cost and total cost for a task. The total cost is the
* current estimate of costs based on actual costs and remaining costs.
* This is also referred to as variance at completion (VAC).
*
* @param val amount
*/
public void setCostVariance (Number val)
{
set(TaskField.COST_VARIANCE, val);
}
/**
* The Created field contains the date and time when a task was
* added to the project.
*
* @param val date
*/
public void setCreateDate (Date val)
{
set(TaskField.CREATED, val);
}
/**
* The Critical field indicates whether a task has any room in the
* schedule to slip,
* or if a task is on the critical path. The Critical field contains
* Yes if the task
* is critical and No if the task is not critical.
*
* @param val whether task is critical or not
*/
public void setCritical (boolean val)
{
set(TaskField.CRITICAL, val);
}
/**
* The CV (earned value cost variance) field shows the difference
* between how much it should have cost to achieve the current level of
* completion on the task, and how much it has actually cost to achieve the
* current level of completion up to
* the status date or today's date.
*
* @param val value to set
*/
public void setCV (Number val)
{
set(TaskField.CV, val);
}
/**
* Set amount of delay as elapsed real time.
*
* @param val elapsed time
*/
public void setLevelingDelay (Duration val)
{
set(TaskField.LEVELING_DELAY, val);
}
/**
* The Duration field is the total span of active working time for a task.
* This is generally the amount of time from the start to the finish of a task.
* The default for new tasks is 1 day (1d).
*
* @param val duration
*/
public void setDuration (Duration val)
{
set(TaskField.DURATION, val);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration1 (Duration duration)
{
set(TaskField.DURATION1, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration2 (Duration duration)
{
set(TaskField.DURATION2, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration3 (Duration duration)
{
set(TaskField.DURATION3, duration);
}
/**
* The Duration Variance field contains the difference between the
* baseline duration of a task and the forecast or actual duration
* of the task.
*
* @param duration duration value
*/
public void setDurationVariance (Duration duration)
{
set(TaskField.DURATION_VARIANCE, duration);
}
/**
* The Early Finish field contains the earliest date that a task
* could possibly finish, based on early finish dates of predecessor
* and successor tasks, other constraints, and any leveling delay.
*
* @param date Date value
*/
public void setEarlyFinish (Date date)
{
set(TaskField.EARLY_FINISH, date);
}
/**
* The Early Start field contains the earliest date that a task could
* possibly begin, based on the early start dates of predecessor and
* successor tasks, and other constraints.
*
* @param date Date value
*/
public void setEarlyStart (Date date)
{
set(TaskField.EARLY_START, date);
}
/**
* The Finish field shows the date and time that a task is scheduled to be
* completed. MS project allows a finish date to be entered, and will
* calculate the duartion, or a duration can be supplied and MS Project
* will calculate the finish date.
*
* @param date Date value
*/
public void setFinish (Date date)
{
set(TaskField.FINISH, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish1 (Date date)
{
set(TaskField.FINISH1, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish2 (Date date)
{
set(TaskField.FINISH2, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish3 (Date date)
{
set(TaskField.FINISH3, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish4 (Date date)
{
set(TaskField.FINISH4, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish5 (Date date)
{
set(TaskField.FINISH5, date);
}
/**
* The Finish Variance field contains the amount of time that represents the
* difference between a task's baseline finish date and its forecast
* or actual finish date.
*
* @param duration duration value
*/
public void setFinishVariance (Duration duration)
{
set(TaskField.FINISH_VARIANCE, duration);
}
/**
* The Fixed Cost field shows any task expense that is not associated
* with a resource cost.
*
* @param val amount
*/
public void setFixedCost (Number val)
{
set(TaskField.FIXED_COST, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag1 (boolean val)
{
set(TaskField.FLAG1, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag2 (boolean val)
{
set(TaskField.FLAG2, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag3 (boolean val)
{
set(TaskField.FLAG3, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag4 (boolean val)
{
set(TaskField.FLAG4, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag5 (boolean val)
{
set(TaskField.FLAG5, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag6 (boolean val)
{
set(TaskField.FLAG6, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag7 (boolean val)
{
set(TaskField.FLAG7, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag8 (boolean val)
{
set(TaskField.FLAG8, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag9 (boolean val)
{
set(TaskField.FLAG9, val);
}
/**
* User defined flag field.
*
* @param val boolean value
*/
public void setFlag10 (boolean val)
{
set(TaskField.FLAG10, val);
}
/**
* The Free Slack field contains the amount of time that a task can be
* delayed without delaying any successor tasks. If the task has no
* successors, free slack is the amount of time that a task can be delayed
* without delaying the entire project's finish date.
*
* @param duration duration value
*/
public void setFreeSlack (Duration duration)
{
set(TaskField.FREE_SLACK, duration);
}
/**
* The Hide Bar flag indicates whether the Gantt bars and Calendar bars
* for a task are hidden when this project's data is displayed in MS Project.
*
* @param flag boolean value
*/
public void setHideBar (boolean flag)
{
set(TaskField.HIDEBAR, flag);
}
/**
* The ID field contains the identifier number that Microsoft Project
* automatically assigns to each task as you add it to the project.
* The ID indicates the position of a task with respect to the other tasks.
*
* @param val ID
*/
public void setID (Integer val)
{
ProjectFile parent = getParentFile();
Integer previous = getID();
if (previous != null)
{
parent.unmapTaskID(previous);
}
parent.mapTaskID(val, this);
set(TaskField.ID, val);
}
/**
* The Late Finish field contains the latest date that a task can finish
* without delaying the finish of the project. This date is based on the
* task's late start date, as well as the late start and late finish dates
* of predecessor and successor tasks, and other constraints.
*
* @param date date value
*/
public void setLateFinish (Date date)
{
set(TaskField.LATE_FINISH, date);
}
/**
* The Late Start field contains the latest date that a task can start
* without delaying the finish of the project. This date is based on the
* task's start date, as well as the late start and late finish dates of
* predecessor and successor tasks, and other constraints.
*
* @param date date value
*/
public void setLateStart (Date date)
{
set(TaskField.LATE_START, date);
}
/**
* The Linked Fields field indicates whether there are OLE links to the task,
* either from elsewhere in the active project, another Microsoft Project
* file, or from another program.
*
* @param flag boolean value
*/
public void setLinkedFields (boolean flag)
{
set(TaskField.LINKED_FIELDS, flag);
}
/**
* This is a user defined field used to mark a task for some form of
* additional action.
*
* @param flag boolean value
*/
public void setMarked (boolean flag)
{
set(TaskField.MARKED, flag);
}
/**
* The Milestone field indicates whether a task is a milestone.
*
* @param flag boolean value
*/
public void setMilestone (boolean flag)
{
set(TaskField.MILESTONE, flag);
}
/**
* The Name field contains the name of a task.
*
* @param name task name
*/
public void setName (String name)
{
set(TaskField.NAME, name);
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber1 (Number val)
{
set(TaskField.NUMBER1, val);
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber2 (Number val)
{
set(TaskField.NUMBER2, val);
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber3 (Number val)
{
set(TaskField.NUMBER3, val);
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber4 (Number val)
{
set(TaskField.NUMBER4, val);
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber5 (Number val)
{
set(TaskField.NUMBER5, val);
}
/**
* The Objects field contains the number of objects attached to a task.
*
* @param val - integer value
*/
public void setObjects (Integer val)
{
set(TaskField.OBJECTS, val);
}
/**
* The Outline Level field contains the number that indicates the level of
* the task in the project outline hierarchy.
*
* @param val - int
*/
public void setOutlineLevel (Integer val)
{
set(TaskField.OUTLINE_LEVEL, val);
}
/**
* The Outline Number field contains the number of the task in the structure
* of an outline. This number indicates the task's position within the
* hierarchical structure of the project outline. The outline number is
* similar to a WBS (work breakdown structure) number, except that the
* outline number is automatically entered by Microsoft Project.
*
* @param val - text
*/
public void setOutlineNumber (String val)
{
set(TaskField.OUTLINE_NUMBER, val);
}
/**
* The Predecessors field lists the task ID numbers for the predecessor
* tasks on which the task depends before it can be started or finished.
* Each predecessor is linked to the task by a specific type of task
* dependency
* and a lead time or lag time.
*
* @param list list of relationships
*/
public void setPredecessors (List list)
{
set(TaskField.PREDECESSORS, list);
}
/**
* The Priority field provides choices for the level of importance
* assigned to a task, which in turn indicates how readily a task can be
* delayed or split during resource leveling.
* The default priority is Medium. Those tasks with a priority
* of Do Not Level are never delayed or split when Microsoft Project levels
* tasks that have overallocated resources assigned.
*
* @param priority the priority value
*/
public void setPriority (Priority priority)
{
set(TaskField.PRIORITY, priority);
}
/**
* The Project field shows the name of the project from which a
* task originated.
* This can be the name of the active project file. If there are
* other projects
* inserted into the active project file, the name of the
* inserted project appears
* in this field for the task.
*
* @param val - text
*/
public void setProject (String val)
{
set(TaskField.PROJECT, val);
}
/**
* The Remaining Cost field shows the remaining scheduled expense of a task that
* will be incurred in completing the remaining scheduled work by all resources
* assigned to the task.
*
* @param val - currency amount
*/
public void setRemainingCost (Number val)
{
set(TaskField.REMAINING_COST, val);
}
/**
* The Remaining Duration field shows the amount of time required to complete
* the unfinished portion of a task.
*
* @param val - duration.
*/
public void setRemainingDuration (Duration val)
{
set(TaskField.REMAINING_DURATION, val);
}
/**
* The Remaining Work field shows the amount of time, or person-hours,
* still required by all assigned resources to complete a task.
* @param val - duration
*/
public void setRemainingWork (Duration val)
{
set(TaskField.REMAINING_WORK, val);
}
/**
* The Resource Group field contains the list of resource groups to which the
* resources assigned to a task belong.
*
* @param val - String list
*/
public void setResourceGroup (String val)
{
set(TaskField.RESOURCE_GROUP, val);
}
/**
* The Resource Initials field lists the abbreviations for the names of
* resources assigned to a task. These initials can serve as substitutes
* for the names.
*
* Note that MS Project 98 does no normally populate this field when
* it generates an MPX file, and will therefore not expect to see values
* in this field when it reads an MPX file. Supplying values for this
* field will cause MS Project 98, 2000, and 2002 to create new resources
* and ignore any other resource assignments that have been defined
* in the MPX file.
*
* @param val String containing a comma separated list of initials
*/
public void setResourceInitials (String val)
{
set(TaskField.RESOURCE_INITIALS, val);
}
/**
* The Resource Names field lists the names of all resources
* assigned to a task.
*
* Note that MS Project 98 does no normally populate this field when
* it generates an MPX file, and will therefore not expect to see values
* in this field when it reads an MPX file. Supplying values for this
* field will cause MS Project 98, 2000, and 2002 to create new resources
* and ignore any other resource assignments that have been defined
* in the MPX file.
*
* @param val String containing a comma separated list of names
*/
public void setResourceNames (String val)
{
set(TaskField.RESOURCE_NAMES, val);
}
/**
* The Resume field shows the date that the remaining portion of a task is
* scheduled to resume after you enter a new value for the %Complete field.
* The Resume field is also recalculated when the remaining portion of a task
* is moved to a new date.
*
* @param val - Date
*/
public void setResume (Date val)
{
set(TaskField.RESUME, val);
}
/**
* For subtasks, the Rollup field indicates whether information on the subtask
* Gantt bars will be rolled up to the summary task bar. For summary tasks, the
* Rollup field indicates whether the summary task bar displays rolled up bars.
* You must have the Rollup field for summary tasks set to Yes for any subtasks
* to roll up to them.
*
* @param val - boolean
*/
public void setRollup (boolean val)
{
set(TaskField.ROLLUP, val);
}
/**
* The Start field shows the date and time that a task is scheduled to begin.
* You can enter the start date you want, to indicate the date when the task
* should begin. Or, you can have Microsoft Project calculate the start date.
* @param val - Date
*/
public void setStart (Date val)
{
set(TaskField.START, val);
}
/**
* The Start1 through Start10 fields are custom fields that show any specific
* task start date information you want to enter and store separately in
* your project.
*
* @param val - Date
*/
public void setStart1 (Date val)
{
set(TaskField.START1, val);
}
/**
* The Start1 through Start10 fields are custom fields that show any specific
* task start date information you want to enter and store separately in
* your project.
*
* @param val - Date
*/
public void setStart2 (Date val)
{
set(TaskField.START2, val);
}
/**
* The Start1 through Start10 fields are custom fields that show any specific
* task start date information you want to enter and store separately in
* your project.
*
* @param val - Date
*/
public void setStart3 (Date val)
{
set(TaskField.START3, val);
}
/**
* The Start1 through Start10 fields are custom fields that show any specific
* task start date information you want to enter and store separately in
* your project.
*
* @param val - Date
*/
public void setStart4 (Date val)
{
set(TaskField.START4, val);
}
/**
* The Start1 through Start10 fields are custom fields that show any specific
* task start date information you want to enter and store separately in
* your project.
*
* @param val - Date
*/
public void setStart5 (Date val)
{
set(TaskField.START5, val);
}
/**
* The Start Variance field contains the amount of time that represents the
* difference between a task's baseline start date and its currently
* scheduled start date.
*
* @param val - duration
*/
public void setStartVariance (Duration val)
{
set(TaskField.START_VARIANCE, val);
}
/**
* The Stop field shows the date that represents the end of the actual
* portion of a task. Typically, Microsoft Project calculates the stop date.
* However, you can edit this date as well.
*
* @param val - Date
*/
public void setStop (Date val)
{
set(TaskField.STOP, val);
}
/**
* The Subproject File field contains the name of a project inserted into
* the active project file. The Subproject File field contains the inserted
* project's path and file name.
*
* @param val - String
*/
public void setSubprojectName (String val)
{
set(TaskField.SUBPROJECT_FILE, val);
}
/**
* The Successors field lists the task ID numbers for the successor tasks
* to a task.
* A task must start or finish before successor tasks can start or finish.
* Each successor is linked to the task by a specific type of task dependency
* and a lead time or lag time.
*
* @param list list of relationships
*/
public void setSuccessors (List list)
{
set(TaskField.SUCCESSORS, list);
}
/**
* The Summary field indicates whether a task is a summary task.
*
* @param val - boolean
*/
public void setSummary (boolean val)
{
set(TaskField.SUMMARY, val);
}
/**
* The SV (earned value schedule variance) field shows the difference
* in cost terms between the current progress and the baseline plan
* of the task up to the status date or today's date. You can use SV
* to check costs to determine whether tasks are on schedule.
* @param val - currency amount
*/
public void setSV (Number val)
{
set(TaskField.SV, val);
}
/**
* The Text1-30 fields show any custom text information you want to enter
* in your project about tasks.
*
* @param val - String
*/
public void setText1 (String val)
{
set(TaskField.TEXT1, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText2 (String val)
{
set(TaskField.TEXT2, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText3 (String val)
{
set(TaskField.TEXT3, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText4 (String val)
{
set(TaskField.TEXT4, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText5 (String val)
{
set(TaskField.TEXT5, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText6 (String val)
{
set(TaskField.TEXT6, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText7 (String val)
{
set(TaskField.TEXT7, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText8 (String val)
{
set(TaskField.TEXT8, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText9 (String val)
{
set(TaskField.TEXT9, val);
}
/**
* The Text1-30 fields show any custom text information you want to
* enter in your project about tasks.
*
* @param val - String
*/
public void setText10 (String val)
{
set(TaskField.TEXT10, val);
}
/**
* The Total Slack field contains the amount of time a task can be delayed
* without delaying the project's finish date.
*
* @param val - duration
*/
public void setTotalSlack (Duration val)
{
set(TaskField.TOTAL_SLACK, val);
}
/**
* The Unique ID field contains the number that Microsoft Project
* automatically designates whenever a new task is created.
* This number indicates the sequence in which the task was created,
* regardless of placement in the schedule.
*
* @param val unique ID
*/
public void setUniqueID (Integer val)
{
ProjectFile parent = getParentFile();
Integer previous = getUniqueID();
if (previous != null)
{
parent.unmapTaskUniqueID(previous);
}
parent.mapTaskUniqueID(val, this);
set(TaskField.UNIQUE_ID, val);
}
/**
* The Unique ID Predecessors field lists the unique ID numbers for
* the predecessor
* tasks on which a task depends before it can be started or finished.
* Each predecessor is linked to the task by a specific type of
* task dependency
* and a lead time or lag time.
*
* @param list list of relationships
*/
public void setUniqueIDPredecessors (List list)
{
set(TaskField.UNIQUE_ID_PREDECESSORS, list);
}
/**
* The Unique ID Successors field lists the unique ID numbers for the successor
* tasks to a task. A task must start or finish before successor tasks can start
* or finish. Each successor is linked to the task by a specific type of task
* dependency and a lead time or lag time.
*
* @param list list of relationships
*/
public void setUniqueIDSuccessors (List list)
{
set(TaskField.UNIQUE_ID_SUCCESSORS, list);
}
/**
* The Update Needed field indicates whether a TeamUpdate message should
* be sent to the assigned resources because of changes to the start date,
* finish date, or resource reassignments of the task.
*
* @param val - boolean
*/
public void setUpdateNeeded (boolean val)
{
set(TaskField.UPDATE_NEEDED, val);
}
/**
* The work breakdown structure code. The WBS field contains an alphanumeric
* code you can use to represent the task's position within the hierarchical
* structure of the project. This field is similar to the outline number,
* except that you can edit it.
*
* @param val - String
*/
public void setWBS (String val)
{
set(TaskField.WBS, val);
}
/**
* The Work field shows the total amount of work scheduled to be performed
* on a task by all assigned resources. This field shows the total work,
* or person-hours, for a task.
*
* @param val - duration
*/
public void setWork (Duration val)
{
set(TaskField.WORK, val);
}
/**
* The Work Variance field contains the difference between a task's baseline
* work and the currently scheduled work.
*
* @param val - duration
*/
public void setWorkVariance (Duration val)
{
set(TaskField.WORK_VARIANCE, val);
}
/**
* The %Complete field contains the current status of a task,
* expressed as the percentage of the task's duration that has been completed.
* You can enter percent complete, or you can have Microsoft Project calculate
* it for you based on actual duration.
* @return percentage as float
*/
public Number getPercentageComplete ()
{
return ((Number)get(TaskField.PERCENT_COMPLETE));
}
/**
* The %Work Complete field contains the current status of a task,
* expressed as the percentage of the task's work that has been completed.
* You can enter percent work complete, or you can have Microsoft Project
* calculate it for you based on actual work on the task.
*
* @return percentage as float
*/
public Number getPercentageWorkComplete ()
{
return ((Number)get(TaskField.PERCENT_WORK_COMPLETE));
}
/**
* The Actual Cost field shows costs incurred for work already performed
* by all resources on a task, along with any other recorded costs associated
* with the task. You can enter all the actual costs or have Microsoft Project
* calculate them for you.
*
* @return currency amount as float
*/
public Number getActualCost ()
{
return ((Number)get(TaskField.ACTUAL_COST));
}
/**
* The Actual Duration field shows the span of actual working time for a
* task so far, based on the scheduled duration and current remaining work
* or completion percentage.
*
* @return duration string
*/
public Duration getActualDuration ()
{
return ((Duration)get(TaskField.ACTUAL_DURATION));
}
/**
* The Actual Finish field shows the date and time that a task actually
* finished. Microsoft Project sets the Actual Finish field to the scheduled
* finish date if the completion percentage is 100. This field contains "NA"
* until you enter actual information or set the completion percentage to 100.
* If "NA" is entered as value, arbitrary year zero Date is used. Date(0);
*
* @return Date
*/
public Date getActualFinish ()
{
return ((Date)get(TaskField.ACTUAL_FINISH));
}
/**
* The Actual Start field shows the date and time that a task actually began.
* When a task is first created, the Actual Start field contains "NA." Once
* you enter the first actual work or a completion percentage for a task,
* Microsoft Project sets the actual start date to the scheduled start date.
* If "NA" is entered as value, arbitrary year zero Date is used. Date(0);
*
* @return Date
*/
public Date getActualStart ()
{
return ((Date)get(TaskField.ACTUAL_START));
}
/**
* The Actual Work field shows the amount of work that has already been done
* by the resources assigned to a task.
*
* @return duration string
*/
public Duration getActualWork ()
{
return ((Duration)get(TaskField.ACTUAL_WORK));
}
/**
* The Baseline Cost field shows the total planned cost for a task.
* Baseline cost is also referred to as budget at completion (BAC).
* @return currency amount as float
*/
public Number getBaselineCost ()
{
return ((Number)get(TaskField.BASELINE_COST));
}
/**
* The Baseline Duration field shows the original span of time planned
* to complete a task.
*
* @return - duration string
*/
public Duration getBaselineDuration ()
{
return ((Duration)get(TaskField.BASELINE_DURATION));
}
/**
* The Baseline Finish field shows the planned completion date for a task
* at the time you saved a baseline. Information in this field becomes
* available when you set a baseline for a task.
*
* @return Date
*/
public Date getBaselineFinish ()
{
return ((Date)get(TaskField.BASELINE_FINISH));
}
/**
* The Baseline Start field shows the planned beginning date for a task at
* the time you saved a baseline. Information in this field becomes available
* when you set a baseline.
*
* @return Date
*/
public Date getBaselineStart ()
{
return ((Date)get(TaskField.BASELINE_START));
}
/**
* The Baseline Work field shows the originally planned amount of work to be
* performed by all resources assigned to a task. This field shows the planned
* person-hours scheduled for a task. Information in the Baseline Work field
* becomes available when you set a baseline for the project.
*
* @return Duration
*/
public Duration getBaselineWork ()
{
return ((Duration)get(TaskField.BASELINE_WORK));
}
/**
* The BCWP (budgeted cost of work performed) field contains
* the cumulative value of the assignment's timephased percent complete
* multiplied by the assignment's timephased baseline cost.
* BCWP is calculated up to the status date or today's date.
* This information is also known as earned value.
*
* @return currency amount as float
*/
public Number getBCWP ()
{
return ((Number)get(TaskField.BCWP));
}
/**
* The BCWS (budgeted cost of work scheduled) field contains the cumulative
* timephased baseline costs up to the status date or today's date.
*
* @return currency amount as float
*/
public Number getBCWS ()
{
return ((Number)get(TaskField.BCWS));
}
/**
* The Confirmed field indicates whether all resources assigned to a task
* have accepted or rejected the task assignment in response to a TeamAssign
* message regarding their assignments.
*
* @return boolean
*/
public boolean getConfirmed ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.CONFIRMED)));
}
/**
* The Constraint Date field shows the specific date associated with certain
* constraint types, such as Must Start On, Must Finish On,
* Start No Earlier Than,
* Start No Later Than, Finish No Earlier Than, and Finish No Later Than.
*
* @return Date
*/
public Date getConstraintDate ()
{
return ((Date)get(TaskField.CONSTRAINT_DATE));
}
/**
* The Constraint Type field provides choices for the type of constraint you
* can apply for scheduling a task.
*
* @return constraint type
*/
public ConstraintType getConstraintType ()
{
return ((ConstraintType)get(TaskField.CONSTRAINT_TYPE));
}
/**
* The Contact field contains the name of an individual
* responsible for a task.
*
* @return String
*/
public String getContact ()
{
return ((String)get(TaskField.CONTACT));
}
/**
* The Cost field shows the total scheduled, or projected, cost for a task,
* based on costs already incurred for work performed by all resources assigned
* to the task, in addition to the costs planned for the remaining work for the
* assignment. This can also be referred to as estimate at completion (EAC).
*
* @return cost amount
*/
public Number getCost ()
{
return ((Number)get(TaskField.COST));
}
/**
* The Cost1-10 fields show any custom task cost information you
* want to enter in your project.
*
* @return cost amount
*/
public Number getCost1 ()
{
return ((Number)get(TaskField.COST1));
}
/**
* The Cost1-10 fields show any custom task cost information
* you want to enter in your project.
*
* @return amount
*/
public Number getCost2 ()
{
return ((Number)get(TaskField.COST2));
}
/**
* The Cost1-10 fields show any custom task cost information you want to enter
* in your project.
*
* @return amount
*/
public Number getCost3 ()
{
return ((Number)get(TaskField.COST3));
}
/**
* The Cost Variance field shows the difference between the baseline cost
* and total cost for a task. The total cost is the current estimate of costs
* based on actual costs and remaining costs. This is also referred to as
* variance at completion (VAC).
*
* @return amount
*/
public Number getCostVariance ()
{
Number variance = (Number)get(TaskField.COST_VARIANCE);
if (variance == null)
{
Number cost = getCost();
Number baselineCost = getBaselineCost();
if (cost != null && baselineCost != null)
{
variance = NumberUtility.getDouble(cost.doubleValue() - baselineCost.doubleValue());
set(TaskField.COST_VARIANCE, variance);
}
}
return (variance);
}
/**
* The Created field contains the date and time when a task was added
* to the project.
*
* @return Date
*/
public Date getCreateDate ()
{
return ((Date)get(TaskField.CREATED));
}
/**
* The Critical field indicates whether a task has any room in the schedule
* to slip, or if a task is on the critical path. The Critical field contains
* Yes if the task is critical and No if the task is not critical.
*
* @return boolean
*/
public boolean getCritical ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.CRITICAL)));
}
/**
* The CV (earned value cost variance) field shows the difference between
* how much it should have cost to achieve the current level of completion
* on the task, and how much it has actually cost to achieve the current
* level of completion up to the status date or today's date.
* How Calculated CV is the difference between BCWP
* (budgeted cost of work performed) and ACWP
* (actual cost of work performed). Microsoft Project calculates
* the CV as follows: CV = BCWP - ACWP
*
* @return sum of earned value cost variance
*/
public Number getCV ()
{
Number variance = (Number)get(TaskField.CV);
if (variance == null)
{
variance = new Double (NumberUtility.getDouble(getBCWP()) - NumberUtility.getDouble(getACWP()));
set(TaskField.CV, variance);
}
return (variance);
}
/**
* Delay , in MPX files as eg '0ed'. Use duration
*
* @return Duration
*/
public Duration getLevelingDelay ()
{
return ((Duration)get(TaskField.LEVELING_DELAY));
}
/**
* The Duration field is the total span of active working time for a task.
* This is generally the amount of time from the start to the finish of a task.
* The default for new tasks is 1 day (1d).
*
* @return Duration
*/
public Duration getDuration ()
{
return ((Duration)get(TaskField.DURATION));
}
/**
* The Duration1 through Duration10 fields are custom fields that show any
* specialized task duration information you want to enter and store separately
* in your project.
*
* @return Duration
*/
public Duration getDuration1 ()
{
return (Duration)get(TaskField.DURATION1);
}
/**
* The Duration1 through Duration10 fields are custom fields that show any
* specialized task duration information you want to enter and store separately
* in your project.
*
* @return Duration
*/
public Duration getDuration2 ()
{
return ((Duration)get(TaskField.DURATION2));
}
/**
* The Duration1 through Duration10 fields are custom fields that show any
* specialized task duration information you want to enter and store separately
* in your project.
*
* @return Duration
*/
public Duration getDuration3 ()
{
return ((Duration)get(TaskField.DURATION3));
}
/**
* The Duration Variance field contains the difference between the
* baseline duration of a task and the total duration (current estimate)
* of a task.
*
* @return Duration
*/
public Duration getDurationVariance ()
{
Duration variance = (Duration)get(TaskField.DURATION_VARIANCE);
if (variance == null)
{
Duration duration = getDuration();
Duration baselineDuration = getBaselineDuration();
if (duration != null && baselineDuration != null)
{
variance = Duration.getInstance(duration.getDuration() - baselineDuration.convertUnits(duration.getUnits(), getParentFile().getProjectHeader()).getDuration(), duration.getUnits());
set(TaskField.DURATION_VARIANCE, variance);
}
}
return (variance);
}
/**
* The Early Finish field contains the earliest date that a task could
* possibly finish, based on early finish dates of predecessor and
* successor tasks, other constraints, and any leveling delay.
*
* @return Date
*/
public Date getEarlyFinish ()
{
return ((Date)get(TaskField.EARLY_FINISH));
}
/**
* The Early Start field contains the earliest date that a task could
* possibly begin, based on the early start dates of predecessor and
* successor tasks, and other constraints.
*
* @return Date
*/
public Date getEarlyStart ()
{
return ((Date)get(TaskField.EARLY_START));
}
/**
* The Finish field shows the date and time that a task is scheduled to
* be completed. You can enter the finish date you want, to indicate the
* date when the task should be completed. Or, you can have Microsoft
* Project calculate the finish date.
*
* @return Date
*/
public Date getFinish ()
{
return ((Date)get(TaskField.FINISH));
}
/**
* The Finish1 through Finish10 fields are custom fields that show any
* specific task finish date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getFinish1 ()
{
return ((Date)get(TaskField.FINISH1));
}
/**
* The Finish1 through Finish10 fields are custom fields that show any
* specific task finish date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getFinish2 ()
{
return ((Date)get(TaskField.FINISH2));
}
/**
* The Finish1 through Finish10 fields are custom fields that show any
* specific task finish date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getFinish3 ()
{
return ((Date)get(TaskField.FINISH3));
}
/**
* The Finish1 through Finish10 fields are custom fields that show any
* specific task finish date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getFinish4 ()
{
return ((Date)get(TaskField.FINISH4));
}
/**
* The Finish1 through Finish10 fields are custom fields that show any
* specific task finish date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getFinish5 ()
{
return ((Date)get(TaskField.FINISH5));
}
/**
* Calculate the finish variance.
*
* @return finish variance
*/
public Duration getFinishVariance ()
{
Duration variance = (Duration)get(TaskField.FINISH_VARIANCE);
if (variance == null)
{
TimeUnit format = getParentFile().getProjectHeader().getDefaultDurationUnits();
variance = DateUtility.getVariance(this, getBaselineFinish(), getFinish(), format);
set(TaskField.FINISH_VARIANCE, variance);
}
return (variance);
}
/**
* The Fixed Cost field shows any task expense that is not associated
* with a resource cost.
*
* @return currenct amount as float
*/
public Number getFixedCost ()
{
return ((Number)get(TaskField.FIXED_COST));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag1 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG1)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag2 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG2)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag3 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG3)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag4 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG4)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag5 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG5)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag6 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG6)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag7 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG7)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag8 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG8)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag9 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG9)));
}
/**
* The Flag1-20 fields indicate whether a task is marked for further
* action or identification of some kind. To mark a task, click Yes
* in a Flag field. If you don't want a task marked, click No.
*
* @return boolean
*/
public boolean getFlag10 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG10)));
}
/**
* The Free Slack field contains the amount of time that a task can be
* delayed without delaying any successor tasks. If the task has no
* successors, free slack is the amount of time that a task can be
* delayed without delaying the entire project's finish date.
*
* @return Duration
*/
public Duration getFreeSlack ()
{
return ((Duration)get(TaskField.FREE_SLACK));
}
/**
* The Hide Bar field indicates whether the Gantt bars and Calendar bars
* for a task are hidden. Click Yes in the Hide Bar field to hide the
* bar for the task. Click No in the Hide Bar field to show the bar
* for the task.
*
* @return boolean
*/
public boolean getHideBar ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.HIDEBAR)));
}
/**
* The ID field contains the identifier number that Microsoft Project
* automatically assigns to each task as you add it to the project.
* The ID indicates the position of a task with respect to the other tasks.
*
* @return the task ID
*/
public Integer getID ()
{
return ((Integer)get(TaskField.ID));
}
/**
* The Late Finish field contains the latest date that a task can finish
* without delaying the finish of the project. This date is based on the
* task's late start date, as well as the late start and late finish
* dates of predecessor and successor
* tasks, and other constraints.
*
* @return Date
*/
public Date getLateFinish ()
{
return ((Date)get(TaskField.LATE_FINISH));
}
/**
* The Late Start field contains the latest date that a task can start
* without delaying the finish of the project. This date is based on
* the task's start date, as well as the late start and late finish
* dates of predecessor and successor tasks, and other constraints.
*
* @return Date
*/
public Date getLateStart ()
{
return ((Date)get(TaskField.LATE_START));
}
/**
* The Linked Fields field indicates whether there are OLE links to the task,
* either from elsewhere in the active project, another Microsoft Project file,
* or from another program.
*
* @return boolean
*/
public boolean getLinkedFields ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.LINKED_FIELDS)));
}
/**
* The Marked field indicates whether a task is marked for further action or
* identification of some kind. To mark a task, click Yes in the Marked field.
* If you don't want a task marked, click No.
*
* @return true for marked
*/
public boolean getMarked ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.MARKED)));
}
/**
* The Milestone field indicates whether a task is a milestone.
*
* @return boolean
*/
public boolean getMilestone ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.MILESTONE)));
}
/**
* Retrieves the task name.
*
* @return task name
*/
public String getName ()
{
return ((String)get(TaskField.NAME));
}
/**
* The Notes field contains notes that you can enter about a task.
* You can use task notes to help maintain a history for a task.
*
* @return notes
*/
public String getNotes ()
{
String notes = (String)get(TaskField.NOTES);
return (notes==null?"":notes);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber1 ()
{
return ((Number)get(TaskField.NUMBER1));
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber2 ()
{
return ((Number)get(TaskField.NUMBER2));
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber3 ()
{
return ((Number)get(TaskField.NUMBER3));
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber4 ()
{
return ((Number)get(TaskField.NUMBER4));
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber5 ()
{
return ((Number)get(TaskField.NUMBER5));
}
/**
* The Objects field contains the number of objects attached to a task.
* Microsoft Project counts the number of objects linked or embedded to a task.
* However, objects in the Notes box in the Resource Form are not included
* in this count.
*
* @return int
*/
public Integer getObjects ()
{
return ((Integer)get(TaskField.OBJECTS));
}
/**
* The Outline Level field contains the number that indicates the level
* of the task in the project outline hierarchy.
*
* @return int
*/
public Integer getOutlineLevel ()
{
return ((Integer)get(TaskField.OUTLINE_LEVEL));
}
/**
* The Outline Number field contains the number of the task in the structure
* of an outline. This number indicates the task's position within the
* hierarchical structure of the project outline. The outline number is
* similar to a WBS (work breakdown structure) number,
* except that the outline number is automatically entered by
* Microsoft Project.
*
* @return String
*/
public String getOutlineNumber ()
{
return ((String)get(TaskField.OUTLINE_NUMBER));
}
/**
* The Predecessor field in an MPX file lists the task ID numbers for the
* predecessor for a given task. A predecessor task must start or finish
* the current task can be started. Each predecessor is linked to the task
* by a specific type of task dependency and a lead time or lag time.
*
* This method returns a RelationList object which contains a list of
* relationships between tasks. An iterator can be used to traverse
* this list to retrieve each relationship. Note that this method may
* return null if no predecessor relationships have been defined.
*
* @return RelationList instance
*/
public List getPredecessors ()
{
return ((List)get(TaskField.PREDECESSORS));
}
/**
* The Priority field provides choices for the level of importance
* assigned to a task, which in turn indicates how readily a task can be
* delayed or split during resource leveling.
* The default priority is Medium. Those tasks with a priority
* of Do Not Level are never delayed or split when Microsoft Project levels
* tasks that have overallocated resources assigned.
*
* @return priority class instance
*/
public Priority getPriority ()
{
return ((Priority)get(TaskField.PRIORITY));
}
/**
* The Project field shows the name of the project from which a task
* originated.
* This can be the name of the active project file. If there are other
* projects inserted
* into the active project file, the name of the inserted project appears
* in this field
* for the task.
*
* @return name of originating project
*/
public String getProject ()
{
return ((String)get(TaskField.PROJECT));
}
/**
* The Remaining Cost field shows the remaining scheduled expense of a
* task that will be incurred in completing the remaining scheduled work
* by all resources assigned to the task.
*
* @return remaining cost
*/
public Number getRemainingCost ()
{
return ((Number)get(TaskField.REMAINING_COST));
}
/**
* The Remaining Duration field shows the amount of time required
* to complete the unfinished portion of a task.
*
* @return Duration
*/
public Duration getRemainingDuration ()
{
return ((Duration)get(TaskField.REMAINING_DURATION));
}
/**
* The Remaining Work field shows the amount of time, or person-hours,
* still required by all assigned resources to complete a task.
*
* @return the amount of time still required to complete a task
*/
public Duration getRemainingWork ()
{
return ((Duration)get(TaskField.REMAINING_WORK));
}
/**
* The Resource Group field contains the list of resource groups to which
* the resources assigned to a task belong.
*
* @return single string list of groups
*/
public String getResourceGroup ()
{
return ((String)get(TaskField.RESOURCE_GROUP));
}
/**
* The Resource Initials field lists the abbreviations for the names of
* resources assigned to a task. These initials can serve as substitutes
* for the names.
*
* Note that MS Project 98 does not export values for this field when
* writing an MPX file, and the field is not currently populated by MPXJ
* when reading an MPP file.
*
* @return String containing a comma separated list of initials
*/
public String getResourceInitials ()
{
return ((String)get(TaskField.RESOURCE_INITIALS));
}
/**
* The Resource Names field lists the names of all resources assigned
* to a task.
*
* Note that MS Project 98 does not export values for this field when
* writing an MPX file, and the field is not currently populated by MPXJ
* when reading an MPP file.
*
* @return String containing a comma separated list of names
*/
public String getResourceNames ()
{
return ((String)get(TaskField.RESOURCE_NAMES));
}
/**
* The Resume field shows the date that the remaining portion of a task
* is scheduled to resume after you enter a new value for the %Complete
* field. The Resume field is also recalculated when the remaining portion
* of a task is moved to a new date.
*
* @return Date
*/
public Date getResume ()
{
return ((Date)get(TaskField.RESUME));
}
/**
* For subtasks, the Rollup field indicates whether information on the
* subtask Gantt bars
* will be rolled up to the summary task bar. For summary tasks, the
* Rollup field indicates
* whether the summary task bar displays rolled up bars. You must
* have the Rollup field for
* summary tasks set to Yes for any subtasks to roll up to them.
*
* @return boolean
*/
public boolean getRollup ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.ROLLUP)));
}
/**
* The Start field shows the date and time that a task is scheduled to begin.
* You can enter the start date you want, to indicate the date when the task
* should begin. Or, you can have Microsoft Project calculate the start date.
*
* @return Date
*/
public Date getStart ()
{
return ((Date)get(TaskField.START));
}
/**
* The Start1 through Start10 fields are custom fields that show any
* specific task start date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getStart1 ()
{
return ((Date)get(TaskField.START1));
}
/**
* The Start1 through Start10 fields are custom fields that show any
* specific task start date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getStart2 ()
{
return ((Date)get(TaskField.START2));
}
/**
* The Start1 through Start10 fields are custom fields that show any
* specific task start date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getStart3 ()
{
return ((Date)get(TaskField.START3));
}
/**
* The Start1 through Start10 fields are custom fields that show any
* specific task start date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getStart4 ()
{
return ((Date)get(TaskField.START4));
}
/**
* The Start1 through Start10 fields are custom fields that show any
* specific task start date information you want to enter and store
* separately in your project.
*
* @return Date
*/
public Date getStart5 ()
{
return ((Date)get(TaskField.START5));
}
/**
* Calculate the start variance.
*
* @return start variance
*/
public Duration getStartVariance ()
{
Duration variance = (Duration)get(TaskField.START_VARIANCE);
if (variance == null)
{
TimeUnit format = getParentFile().getProjectHeader().getDefaultDurationUnits();
variance = DateUtility.getVariance(this, getBaselineStart(), getStart(), format);
set(TaskField.START_VARIANCE, variance);
}
return (variance);
}
/**
* The Stop field shows the date that represents the end of the actual
* portion of a task. Typically, Microsoft Project calculates the stop date.
* However, you can edit this date as well.
*
* @return Date
*/
public Date getStop ()
{
return ((Date)get(TaskField.STOP));
}
/**
* The Subproject File field contains the name of a project inserted
* into the active project file. The Subproject File field contains the
* inserted project's path and file name.
*
* @return String path
*/
public String getSubprojectName ()
{
return ((String)get(TaskField.SUBPROJECT_FILE));
}
/**
* The Successors field in an MPX file lists the task ID numbers for the
* successor for a given task. A task must start or finish before successor
* tasks can start or finish. Each successor is linked to the task by a
* specific type of task dependency and a lead time or lag time.
*
* This method returns a RelationList object which contains a list of
* relationships between tasks. An iterator can be used to traverse
* this list to retrieve each relationship.
*
* @return RelationList instance
*/
public List getSuccessors ()
{
return ((List)get(TaskField.SUCCESSORS));
}
/**
* The Summary field indicates whether a task is a summary task.
*
* @return boolean, true-is summary task
*/
public boolean getSummary ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.SUMMARY)));
}
/**
* The SV (earned value schedule variance) field shows the difference in
* cost terms between the current progress and the baseline plan of the
* task up to the status date or today's date. You can use SV to
* check costs to determine whether tasks are on schedule.
*
* @return -earned value schedule variance
*/
public Number getSV ()
{
Number variance = (Number)get(TaskField.SV);
if (variance == null)
{
Number bcwp = getBCWP();
Number bcws = getBCWS();
if (bcwp != null && bcws != null)
{
variance = NumberUtility.getDouble(bcwp.doubleValue() - bcws.doubleValue());
set(TaskField.SV, variance);
}
}
return (variance);
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText1 ()
{
return ((String)get(TaskField.TEXT1));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText2 ()
{
return ((String)get(TaskField.TEXT2));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText3 ()
{
return ((String)get(TaskField.TEXT3));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText4 ()
{
return ((String)get(TaskField.TEXT4));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText5 ()
{
return ((String)get(TaskField.TEXT5));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText6 ()
{
return ((String)get(TaskField.TEXT6));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText7 ()
{
return ((String)get(TaskField.TEXT7));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText8 ()
{
return ((String)get(TaskField.TEXT8));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText9 ()
{
return ((String)get(TaskField.TEXT9));
}
/**
* The Text1-30 fields show any custom text information you want
* to enter in your project about tasks.
*
* @return String
*/
public String getText10 ()
{
return ((String)get(TaskField.TEXT10));
}
/**
* The Total Slack field contains the amount of time a task can be
* delayed without delaying the project's finish date.
*
* @return string representing duration
*/
public Duration getTotalSlack ()
{
Duration totalSlack = (Duration)get(TaskField.TOTAL_SLACK);
if (totalSlack == null)
{
Duration duration = getDuration();
if (duration == null)
{
duration = Duration.getInstance(0, TimeUnit.DAYS);
}
TimeUnit units = duration.getUnits();
Duration startSlack = getStartSlack();
if (startSlack == null)
{
startSlack = Duration.getInstance(0, units);
}
else
{
if (startSlack.getUnits() != units)
{
startSlack = startSlack.convertUnits(units, getParentFile().getProjectHeader());
}
}
Duration finishSlack = getFinishSlack();
if (finishSlack == null)
{
finishSlack = Duration.getInstance(0, units);
}
else
{
if (finishSlack.getUnits() != units)
{
finishSlack = finishSlack.convertUnits(units, getParentFile().getProjectHeader());
}
}
double startSlackDuration = startSlack.getDuration();
double finishSlackDuration = finishSlack.getDuration();
if (startSlackDuration == 0 && finishSlackDuration == 0)
{
totalSlack = startSlack;
}
else
{
if (startSlackDuration != 0 && finishSlackDuration != 0)
{
if (startSlackDuration < finishSlackDuration)
{
totalSlack = startSlack;
}
else
{
totalSlack = finishSlack;
}
}
else
{
if (startSlackDuration != 0)
{
totalSlack = startSlack;
}
else
{
totalSlack = finishSlack;
}
}
}
set(TaskField.TOTAL_SLACK, totalSlack);
}
return (totalSlack);
}
/**
* The Unique ID field contains the number that Microsoft Project
* automatically designates whenever a new task is created. This number
* indicates the sequence in which the task was
* created, regardless of placement in the schedule.
*
* @return String
*/
public Integer getUniqueID ()
{
return ((Integer)get(TaskField.UNIQUE_ID));
}
/**
* The Unique ID Predecessors field lists the unique ID numbers for the
* predecessor tasks on which a task depends before it can be started or
* finished. Each predecessor is linked to the task by a specific type of
* task dependency and a lead time or lag time.
*
* @return list of predecessor UniqueIDs
*/
public List getUniqueIDPredecessors ()
{
return ((List)get(TaskField.UNIQUE_ID_PREDECESSORS));
}
/**
* The Unique ID Predecessors field lists the unique ID numbers for the
* predecessor tasks on which a task depends before it can be started or
* finished. Each predecessor is linked to the task by a specific type of
* task dependency and a lead time or lag time.
*
* @return list of predecessor UniqueIDs
*/
public List getUniqueIDSuccessors ()
{
return ((List)get(TaskField.UNIQUE_ID_SUCCESSORS));
}
/**
* The Update Needed field indicates whether a TeamUpdate message
* should be sent to the assigned resources because of changes to the
* start date, finish date, or resource reassignments of the task.
*
* @return true if needed.
*/
public boolean getUpdateNeeded ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.UPDATE_NEEDED)));
}
/**
* The work breakdown structure code. The WBS field contains an
* alphanumeric code you can use to represent the task's position within
* the hierarchical structure of the project. This field is similar to
* the outline number, except that you can edit it.
*
* @return string
*/
public String getWBS ()
{
return ((String)get(TaskField.WBS));
}
/**
* The Work field shows the total amount of work scheduled to be performed
* on a task by all assigned resources. This field shows the total work,
* or person-hours, for a task.
*
* @return Duration representing duration .
*/
public Duration getWork ()
{
return ((Duration)get(TaskField.WORK));
}
/**
* The Work Variance field contains the difference between a task's
* baseline work and the currently scheduled work.
*
* @return Duration representing duration.
*/
public Duration getWorkVariance ()
{
Duration variance = (Duration)get(TaskField.WORK_VARIANCE);
if (variance == null)
{
Duration work = getWork();
Duration baselineWork = getBaselineWork();
if (work != null && baselineWork != null)
{
variance = Duration.getInstance(work.getDuration() - baselineWork.convertUnits(work.getUnits(), getParentFile().getProjectHeader()).getDuration(), work.getUnits());
set(TaskField.WORK_VARIANCE, variance);
}
}
return (variance);
}
/**
* Retrieve count of the number of child tasks.
*
* @return Number of child tasks.
*/
int getChildTaskCount ()
{
return (m_children.size());
}
/**
* This method retrieves a reference to the parent of this task, as
* defined by the outline level. If this task is at the top level,
* this method will return null.
*
* @return parent task
*/
public Task getParentTask ()
{
return (m_parent);
}
/**
* This method retrieves a list of child tasks relative to the
* current task, as defined by the outine level. If there
* are no child tasks, this method will return an empty list.
*
* @return child tasks
*/
public List getChildTasks ()
{
return (m_children);
}
/**
* This method implements the only method in the Comparable interface.
* This allows Tasks to be compared and sorted based on their ID value.
* Note that if the MPX/MPP file has been generated by MSP, the ID value
* will always be in the correct sequence. The Unique ID value will not
* necessarily be in the correct sequence as task insertions and deletions
* will change the order.
*
* @param o object to compare this instance with
* @return result of comparison
*/
public int compareTo (Object o)
{
int id1 = NumberUtility.getInt(getID());
int id2 = NumberUtility.getInt(((Task)o).getID());
return ((id1 < id2) ? (-1) : ((id1 == id2) ? 0 : 1));
}
/**
* This method retrieves a flag indicating whether the duration of the
* task has only been estimated.
*
* @return boolean
*/
public boolean getEstimated ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.ESTIMATED)));
}
/**
* This method retrieves a flag indicating whether the duration of the
* task has only been estimated.
* @param estimated Boolean flag
*/
public void setEstimated (boolean estimated)
{
set(TaskField.ESTIMATED, estimated);
}
/**
* This method retrieves the deadline for this task.
*
* @return Task deadline
*/
public Date getDeadline ()
{
return ((Date)get(TaskField.DEADLINE));
}
/**
* This method sets the deadline for this task.
*
* @param deadline deadline date
*/
public void setDeadline (Date deadline)
{
set(TaskField.DEADLINE, deadline);
}
/**
* This method retrieves the task type.
*
* @return int representing the task type
*/
public TaskType getType ()
{
return ((TaskType)get(TaskField.TYPE));
}
/**
* This method sets the task type.
*
* @param type task type
*/
public void setType (TaskType type)
{
set(TaskField.TYPE, type);
}
/**
* Retrieves the flag indicating if this is a null task.
*
* @return boolean flag
*/
public boolean getNull ()
{
return (m_null);
}
/**
* Sets the flag indicating if this is a null task.
*
* @param isNull boolean flag
*/
public void setNull (boolean isNull)
{
m_null = isNull;
}
/**
* Retrieve the WBS level.
*
* @return WBS level
*/
public String getWBSLevel ()
{
return (m_wbsLevel);
}
/**
* Set the WBS level.
*
* @param wbsLevel WBS level
*/
public void setWBSLevel (String wbsLevel)
{
m_wbsLevel = wbsLevel;
}
/**
* Retrieve the duration format.
*
* @return duration format
*/
public TimeUnit getDurationFormat ()
{
return (m_durationFormat);
}
/**
* Set the duration format.
*
* @param durationFormat duration format
*/
public void setDurationFormat (TimeUnit durationFormat)
{
m_durationFormat = durationFormat;
}
/**
* Retrieve the resume valid flag.
*
* @return resume valie flag
*/
public boolean getResumeValid ()
{
return (m_resumeValid);
}
/**
* Set the resume valid flag.
*
* @param resumeValid resume valid flag
*/
public void setResumeValid (boolean resumeValid)
{
m_resumeValid = resumeValid;
}
/**
* Retrieve the recurring flag.
*
* @return recurring flag
*/
public boolean getRecurring ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.RECURRING)));
}
/**
* Set the recurring flag.
*
* @param recurring recurring flag
*/
public void setRecurring (boolean recurring)
{
set(TaskField.RECURRING, recurring);
}
/**
* Retrieve the over allocated flag.
*
* @return over allocated flag
*/
public boolean getOverAllocated ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.OVERALLOCATED)));
}
/**
* Set the over allocated flag.
*
* @param overAllocated over allocated flag
*/
public void setOverAllocated (boolean overAllocated)
{
set(TaskField.OVERALLOCATED, overAllocated);
}
/**
* Where a task in an MPP file represents a task from a subproject,
* this value will be non-zero. The value itself is the unique ID
* value shown in the parent project. To retrieve the value of the
* task unique ID in the child project, remove the top two bytes:
*
* taskID = (subprojectUniqueID & 0xFFFF)
*
* @return sub project unique task ID
*/
public Integer getSubprojectTaskUniqueID ()
{
return (m_subprojectTaskUniqueID);
}
/**
* Sets the sub project unique task ID.
*
* @param subprojectUniqueTaskID subproject unique task ID
*/
public void setSubprojectTaskUniqueID (Integer subprojectUniqueTaskID)
{
m_subprojectTaskUniqueID = subprojectUniqueTaskID;
}
/**
* Sets the offset added to unique task IDs from sub projects
* to generate the task ID shown in the master project.
*
* @param offset unique ID offset
*/
public void setSubprojectTasksUniqueIDOffset (Integer offset)
{
m_subprojectTasksUniqueIDOffset = offset;
}
/**
* Retrieves the offset added to unique task IDs from sub projects
* to generate the task ID shown in the master project.
*
* @return unique ID offset
*/
public Integer getSubprojectTasksUniqueIDOffset ()
{
return (m_subprojectTasksUniqueIDOffset);
}
/**
* Retrieve the subproject read only flag.
*
* @return subproject read only flag
*/
public boolean getSubprojectReadOnly ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.SUBPROJECT_READ_ONLY)));
}
/**
* Set the subproject read only flag.
*
* @param subprojectReadOnly subproject read only flag
*/
public void setSubprojectReadOnly (boolean subprojectReadOnly)
{
set(TaskField.SUBPROJECT_READ_ONLY, subprojectReadOnly);
}
/**
* Retrieves the external task flag.
*
* @return external task flag
*/
public boolean getExternalTask ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.EXTERNAL_TASK)));
}
/**
* Sets the external task flag.
*
* @param externalTask external task flag
*/
public void setExternalTask (boolean externalTask)
{
set(TaskField.EXTERNAL_TASK, externalTask);
}
/**
* Retrieves the external task project file name.
*
* @return external task project file name
*/
public String getExternalTaskProject ()
{
return (m_externalTaskProject);
}
/**
* Sets the external task project file name.
*
* @param externalTaskProject external task project file name
*/
public void setExternalTaskProject (String externalTaskProject)
{
m_externalTaskProject = externalTaskProject;
}
/**
* Retrieve the ACWP value.
*
* @return ACWP value
*/
public Number getACWP ()
{
return ((Number)get(TaskField.ACWP));
}
/**
* Set the ACWP value.
*
* @param acwp ACWP value
*/
public void setACWP (Number acwp)
{
set(TaskField.ACWP, acwp);
}
/**
* Retrieve the leveling delay format.
*
* @return leveling delay format
*/
public TimeUnit getLevelingDelayFormat ()
{
return (m_levelingDelayFormat);
}
/**
* Set the leveling delay format.
*
* @param levelingDelayFormat leveling delay format
*/
public void setLevelingDelayFormat (TimeUnit levelingDelayFormat)
{
m_levelingDelayFormat = levelingDelayFormat;
}
/**
* Retrieves the ignore resource celandar flag.
*
* @return ignore resource celandar flag
*/
public boolean getIgnoreResourceCalendar ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.IGNORE_RESOURCE_CALENDAR)));
}
/**
* Sets the ignore resource celandar flag.
*
* @param ignoreResourceCalendar ignore resource celandar flag
*/
public void setIgnoreResourceCalendar (boolean ignoreResourceCalendar)
{
set(TaskField.IGNORE_RESOURCE_CALENDAR, ignoreResourceCalendar);
}
/**
* Retrieves the physical percent complete value.
*
* @return physical percent complete value
*/
public Integer getPhysicalPercentComplete ()
{
return (m_physicalPercentComplete);
}
/**
* Srts the physical percent complete value.
*
* @param physicalPercentComplete physical percent complete value
*/
public void setPhysicalPercentComplete (Integer physicalPercentComplete)
{
m_physicalPercentComplete = physicalPercentComplete;
}
/**
* Retrieves the earned value method.
*
* @return earned value method
*/
public EarnedValueMethod getEarnedValueMethod ()
{
return (m_earnedValueMethod);
}
/**
* Sets the earned value method.
*
* @param earnedValueMethod earned value method
*/
public void setEarnedValueMethod (EarnedValueMethod earnedValueMethod)
{
m_earnedValueMethod = earnedValueMethod;
}
/**
* Retrieves the actual work protected value.
*
* @return actual work protected value
*/
public Duration getActualWorkProtected ()
{
return (m_actualWorkProtected);
}
/**
* Sets the actual work protected value.
*
* @param actualWorkProtected actual work protected value
*/
public void setActualWorkProtected (Duration actualWorkProtected)
{
m_actualWorkProtected = actualWorkProtected;
}
/**
* Retrieves the actual overtime work protected value.
*
* @return actual overtime work protected value
*/
public Duration getActualOvertimeWorkProtected ()
{
return (m_actualOvertimeWorkProtected);
}
/**
* Sets the actual overtime work protected value.
*
* @param actualOvertimeWorkProtected actual overtime work protected value
*/
public void setActualOvertimeWorkProtected (Duration actualOvertimeWorkProtected)
{
m_actualOvertimeWorkProtected = actualOvertimeWorkProtected;
}
/**
* Retrieve the amount of regular work.
*
* @return amount of regular work
*/
public Duration getRegularWork ()
{
return ((Duration)get(TaskField.REGULAR_WORK));
}
/**
* Set the amount of regular work.
*
* @param regularWork amount of regular work
*/
public void setRegularWork (Duration regularWork)
{
set(TaskField.REGULAR_WORK, regularWork);
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag11 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG11)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag12 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG12)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag13 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG13)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag14 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG14)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag15 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG15)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag16 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG16)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag17 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG17)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag18 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG18)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag19 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG19)));
}
/**
* Retrieves the flag value.
*
* @return flag value
*/
public boolean getFlag20 ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.FLAG20)));
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag11 (boolean b)
{
set(TaskField.FLAG11, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag12 (boolean b)
{
set(TaskField.FLAG12, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag13 (boolean b)
{
set(TaskField.FLAG13, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag14 (boolean b)
{
set(TaskField.FLAG14, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag15 (boolean b)
{
set(TaskField.FLAG15, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag16 (boolean b)
{
set(TaskField.FLAG16, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag17 (boolean b)
{
set(TaskField.FLAG17, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag18 (boolean b)
{
set(TaskField.FLAG18, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag19 (boolean b)
{
set(TaskField.FLAG19, b);
}
/**
* Sets the flag value.
*
* @param b flag value
*/
public void setFlag20 (boolean b)
{
set(TaskField.FLAG20, b);
}
/**
* Sets the effort driven flag.
*
* @param flag value
*/
public void setEffortDriven (boolean flag)
{
set(TaskField.EFFORT_DRIVEN, flag);
}
/**
* Retrieves the effort friven flag.
*
* @return Flag value
*/
public boolean getEffortDriven ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.EFFORT_DRIVEN)));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText11 ()
{
return ((String)get(TaskField.TEXT11));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText12 ()
{
return ((String)get(TaskField.TEXT12));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText13 ()
{
return ((String)get(TaskField.TEXT13));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText14 ()
{
return ((String)get(TaskField.TEXT14));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText15 ()
{
return ((String)get(TaskField.TEXT15));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText16 ()
{
return ((String)get(TaskField.TEXT16));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText17 ()
{
return ((String)get(TaskField.TEXT17));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText18 ()
{
return ((String)get(TaskField.TEXT18));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText19 ()
{
return ((String)get(TaskField.TEXT19));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText20 ()
{
return ((String)get(TaskField.TEXT20));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText21 ()
{
return ((String)get(TaskField.TEXT21));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText22 ()
{
return ((String)get(TaskField.TEXT22));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText23 ()
{
return ((String)get(TaskField.TEXT23));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText24 ()
{
return ((String)get(TaskField.TEXT24));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText25 ()
{
return ((String)get(TaskField.TEXT25));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText26 ()
{
return ((String)get(TaskField.TEXT26));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText27 ()
{
return ((String)get(TaskField.TEXT27));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText28 ()
{
return ((String)get(TaskField.TEXT28));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText29 ()
{
return ((String)get(TaskField.TEXT29));
}
/**
* Retrieves a text value.
*
* @return Text value
*/
public String getText30 ()
{
return ((String)get(TaskField.TEXT30));
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText11 (String string)
{
set(TaskField.TEXT11, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText12 (String string)
{
set(TaskField.TEXT12, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText13 (String string)
{
set(TaskField.TEXT13, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText14 (String string)
{
set(TaskField.TEXT14, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText15 (String string)
{
set(TaskField.TEXT15, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText16 (String string)
{
set(TaskField.TEXT16, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText17 (String string)
{
set(TaskField.TEXT17, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText18 (String string)
{
set(TaskField.TEXT18, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText19 (String string)
{
set(TaskField.TEXT19, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText20 (String string)
{
set(TaskField.TEXT20, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText21 (String string)
{
set(TaskField.TEXT21, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText22 (String string)
{
set(TaskField.TEXT22, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText23 (String string)
{
set(TaskField.TEXT23, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText24 (String string)
{
set(TaskField.TEXT24, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText25 (String string)
{
set(TaskField.TEXT25, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText26 (String string)
{
set(TaskField.TEXT26, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText27 (String string)
{
set(TaskField.TEXT27, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText28 (String string)
{
set(TaskField.TEXT28, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText29 (String string)
{
set(TaskField.TEXT29, string);
}
/**
* Sets a text value.
*
* @param string Text value
*/
public void setText30 (String string)
{
set(TaskField.TEXT30, string);
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber6 (Number val)
{
set(TaskField.NUMBER6, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber6 ()
{
return ((Number)get(TaskField.NUMBER6));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber7 (Number val)
{
set(TaskField.NUMBER7, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber7 ()
{
return ((Number)get(TaskField.NUMBER7));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber8 (Number val)
{
set(TaskField.NUMBER8, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber8 ()
{
return ((Number)get(TaskField.NUMBER8));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber9 (Number val)
{
set(TaskField.NUMBER9, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber9 ()
{
return ((Number)get(TaskField.NUMBER9));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber10 (Number val)
{
set(TaskField.NUMBER10, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber10 ()
{
return ((Number)get(TaskField.NUMBER10));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber11 (Number val)
{
set(TaskField.NUMBER11, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber11 ()
{
return ((Number)get(TaskField.NUMBER11));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber12 (Number val)
{
set(TaskField.NUMBER12, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber12 ()
{
return ((Number)get(TaskField.NUMBER12));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber13 (Number val)
{
set(TaskField.NUMBER13, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber13 ()
{
return ((Number)get(TaskField.NUMBER13));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber14 (Number val)
{
set(TaskField.NUMBER14, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber14 ()
{
return ((Number)get(TaskField.NUMBER14));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber15 (Number val)
{
set(TaskField.NUMBER15, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber15 ()
{
return ((Number)get(TaskField.NUMBER15));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber16 (Number val)
{
set(TaskField.NUMBER16, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber16 ()
{
return ((Number)get(TaskField.NUMBER16));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber17 (Number val)
{
set(TaskField.NUMBER17, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber17 ()
{
return ((Number)get(TaskField.NUMBER17));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber18 (Number val)
{
set(TaskField.NUMBER18, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber18 ()
{
return ((Number)get(TaskField.NUMBER18));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber19 (Number val)
{
set(TaskField.NUMBER19, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber19 ()
{
return ((Number)get(TaskField.NUMBER19));
}
/**
* Sets a numeric value.
*
* @param val Numeric value
*/
public void setNumber20 (Number val)
{
set(TaskField.NUMBER20, val);
}
/**
* Retrieves a numeric value.
*
* @return Numeric value
*/
public Number getNumber20 ()
{
return ((Number)get(TaskField.NUMBER20));
}
/**
* Retrieves a duration.
*
* @return Duration
*/
public Duration getDuration10 ()
{
return (Duration)get(TaskField.DURATION10);
}
/**
* Retrieves a duration.
*
* @return Duration
*/
public Duration getDuration4 ()
{
return (Duration)get(TaskField.DURATION4);
}
/**
* Retrieves a duration.
*
* @return Duration
*/
public Duration getDuration5 ()
{
return (Duration)get(TaskField.DURATION5);
}
/**
* Retrieves a duration.
*
* @return Duration
*/
public Duration getDuration6 ()
{
return (Duration)get(TaskField.DURATION6);
}
/**
* Retrieves a duration.
*
* @return Duration
*/
public Duration getDuration7 ()
{
return (Duration)get(TaskField.DURATION7);
}
/**
* Retrieves a duration.
*
* @return Duration
*/
public Duration getDuration8 ()
{
return (Duration)get(TaskField.DURATION8);
}
/**
* Retrieves a duration.
*
* @return Duration
*/
public Duration getDuration9 ()
{
return (Duration)get(TaskField.DURATION9);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration10 (Duration duration)
{
set(TaskField.DURATION10, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration4 (Duration duration)
{
set(TaskField.DURATION4, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration5 (Duration duration)
{
set(TaskField.DURATION5, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration6 (Duration duration)
{
set(TaskField.DURATION6, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration7 (Duration duration)
{
set(TaskField.DURATION7, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration8 (Duration duration)
{
set(TaskField.DURATION8, duration);
}
/**
* User defined duration field.
*
* @param duration Duration value
*/
public void setDuration9 (Duration duration)
{
set(TaskField.DURATION9, duration);
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate1 ()
{
return ((Date)get(TaskField.DATE1));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate10 ()
{
return ((Date)get(TaskField.DATE10));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate2 ()
{
return ((Date)get(TaskField.DATE2));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate3 ()
{
return ((Date)get(TaskField.DATE3));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate4 ()
{
return ((Date)get(TaskField.DATE4));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate5 ()
{
return ((Date)get(TaskField.DATE5));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate6 ()
{
return ((Date)get(TaskField.DATE6));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate7 ()
{
return ((Date)get(TaskField.DATE7));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate8 ()
{
return ((Date)get(TaskField.DATE8));
}
/**
* Retrieves a date value.
*
* @return Date value
*/
public Date getDate9 ()
{
return ((Date)get(TaskField.DATE9));
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate1 (Date date)
{
set(TaskField.DATE1, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate10 (Date date)
{
set(TaskField.DATE10, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate2 (Date date)
{
set(TaskField.DATE2, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate3 (Date date)
{
set(TaskField.DATE3, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate4 (Date date)
{
set(TaskField.DATE4, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate5 (Date date)
{
set(TaskField.DATE5, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate6 (Date date)
{
set(TaskField.DATE6, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate7 (Date date)
{
set(TaskField.DATE7, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate8 (Date date)
{
set(TaskField.DATE8, date);
}
/**
* Sets a date value.
*
* @param date Date value
*/
public void setDate9 (Date date)
{
set(TaskField.DATE9, date);
}
/**
* Retrieves a cost.
*
* @return Cost value
*/
public Number getCost10 ()
{
return ((Number)get(TaskField.COST10));
}
/**
* Retrieves a cost.
*
* @return Cost value
*/
public Number getCost4 ()
{
return ((Number)get(TaskField.COST4));
}
/**
* Retrieves a cost.
*
* @return Cost value
*/
public Number getCost5 ()
{
return ((Number)get(TaskField.COST5));
}
/**
* Retrieves a cost.
*
* @return Cost value
*/
public Number getCost6 ()
{
return ((Number)get(TaskField.COST6));
}
/**
* Retrieves a cost.
*
* @return Cost value
*/
public Number getCost7 ()
{
return ((Number)get(TaskField.COST7));
}
/**
* Retrieves a cost.
*
* @return Cost value
*/
public Number getCost8 ()
{
return ((Number)get(TaskField.COST8));
}
/**
* Retrieves a cost.
*
* @return Cost value
*/
public Number getCost9 ()
{
return ((Number)get(TaskField.COST9));
}
/**
* Sets a cost value.
*
* @param number Cost value
*/
public void setCost10 (Number number)
{
set(TaskField.COST10, number);
}
/**
* Sets a cost value.
*
* @param number Cost value
*/
public void setCost4 (Number number)
{
set(TaskField.COST4, number);
}
/**
* Sets a cost value.
*
* @param number Cost value
*/
public void setCost5 (Number number)
{
set(TaskField.COST5, number);
}
/**
* Sets a cost value.
*
* @param number Cost value
*/
public void setCost6 (Number number)
{
set(TaskField.COST6, number);
}
/**
* Sets a cost value.
*
* @param number Cost value
*/
public void setCost7 (Number number)
{
set(TaskField.COST7, number);
}
/**
* Sets a cost value.
*
* @param number Cost value
*/
public void setCost8 (Number number)
{
set(TaskField.COST8, number);
}
/**
* Sets a cost value.
*
* @param number Cost value
*/
public void setCost9 (Number number)
{
set(TaskField.COST9, number);
}
/**
* Retrieves a start date.
*
* @return Date start date
*/
public Date getStart10 ()
{
return ((Date)get(TaskField.START10));
}
/**
* Retrieves a start date.
*
* @return Date start date
*/
public Date getStart6 ()
{
return ((Date)get(TaskField.START6));
}
/**
* Retrieves a start date.
*
* @return Date start date
*/
public Date getStart7 ()
{
return ((Date)get(TaskField.START7));
}
/**
* Retrieves a start date.
*
* @return Date start date
*/
public Date getStart8 ()
{
return ((Date)get(TaskField.START8));
}
/**
* Retrieves a start date.
*
* @return Date start date
*/
public Date getStart9 ()
{
return ((Date)get(TaskField.START9));
}
/**
* Sets a start date.
*
* @param date Start date
*/
public void setStart10 (Date date)
{
set(TaskField.START10, date);
}
/**
* Sets a start date.
*
* @param date Start date
*/
public void setStart6 (Date date)
{
set(TaskField.START6, date);
}
/**
* Sets a start date.
*
* @param date Start date
*/
public void setStart7 (Date date)
{
set(TaskField.START7, date);
}
/**
* Sets a start date.
*
* @param date Start date
*/
public void setStart8 (Date date)
{
set(TaskField.START8, date);
}
/**
* Sets a start date.
*
* @param date Start date
*/
public void setStart9 (Date date)
{
set(TaskField.START9, date);
}
/**
* Retrieves a finish date.
*
* @return Date finish date
*/
public Date getFinish10 ()
{
return ((Date)get(TaskField.FINISH10));
}
/**
* Retrieves a finish date.
*
* @return Date finish date
*/
public Date getFinish6 ()
{
return ((Date)get(TaskField.FINISH6));
}
/**
* Retrieves a finish date.
*
* @return Date finish date
*/
public Date getFinish7 ()
{
return ((Date)get(TaskField.FINISH7));
}
/**
* Retrieves a finish date.
*
* @return Date finish date
*/
public Date getFinish8 ()
{
return ((Date)get(TaskField.FINISH8));
}
/**
* Retrieves a finish date.
*
* @return Date finish date
*/
public Date getFinish9 ()
{
return ((Date)get(TaskField.FINISH9));
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish10 (Date date)
{
set(TaskField.FINISH10, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish6 (Date date)
{
set(TaskField.FINISH6, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish7 (Date date)
{
set(TaskField.FINISH7, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish8 (Date date)
{
set(TaskField.FINISH8, date);
}
/**
* User defined finish date field.
*
* @param date Date value
*/
public void setFinish9 (Date date)
{
set(TaskField.FINISH9, date);
}
/**
* Retrieves the overtime cost.
*
* @return Cost value
*/
public Number getOvertimeCost ()
{
return ((Number)get(TaskField.OVERTIME_COST));
}
/**
* Sets the overtime cost value.
*
* @param number Cost value
*/
public void setOvertimeCost (Number number)
{
set(TaskField.OVERTIME_COST, number);
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode1 (String value)
{
set(TaskField.OUTLINE_CODE1, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode1 ()
{
return ((String)get(TaskField.OUTLINE_CODE1));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode2 (String value)
{
set(TaskField.OUTLINE_CODE2, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode2 ()
{
return ((String)get(TaskField.OUTLINE_CODE2));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode3 (String value)
{
set(TaskField.OUTLINE_CODE3, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode3 ()
{
return ((String)get(TaskField.OUTLINE_CODE3));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode4 (String value)
{
set(TaskField.OUTLINE_CODE4, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode4 ()
{
return ((String)get(TaskField.OUTLINE_CODE4));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode5 (String value)
{
set(TaskField.OUTLINE_CODE5, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode5 ()
{
return ((String)get(TaskField.OUTLINE_CODE5));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode6 (String value)
{
set(TaskField.OUTLINE_CODE6, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode6 ()
{
return ((String)get(TaskField.OUTLINE_CODE6));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode7 (String value)
{
set(TaskField.OUTLINE_CODE7, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode7 ()
{
return ((String)get(TaskField.OUTLINE_CODE7));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode8 (String value)
{
set(TaskField.OUTLINE_CODE8, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode8 ()
{
return ((String)get(TaskField.OUTLINE_CODE8));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode9 (String value)
{
set(TaskField.OUTLINE_CODE9, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode9 ()
{
return ((String)get(TaskField.OUTLINE_CODE9));
}
/**
* Sets the value of an outline code field.
*
* @param value outline code value
*/
public void setOutlineCode10 (String value)
{
set(TaskField.OUTLINE_CODE10, value);
}
/**
* Retrieves the value of an outline code field.
*
* @return outline code value
*/
public String getOutlineCode10 ()
{
return ((String)get(TaskField.OUTLINE_CODE10));
}
/**
* Retrieves the actual overtime cost for this task.
*
* @return actual overtime cost
*/
public Number getActualOvertimeCost ()
{
return ((Number)get(TaskField.ACTUAL_OVERTIME_COST));
}
/**
* Sets the actual overtime cost for this task.
*
* @param cost actual overtime cost
*/
public void setActualOvertimeCost (Number cost)
{
set(TaskField.ACTUAL_OVERTIME_COST, cost);
}
/**
* Retrieves the actual overtime work value.
*
* @return actual overtime work value
*/
public Duration getActualOvertimeWork ()
{
return ((Duration)get(TaskField.ACTUAL_OVERTIME_WORK));
}
/**
* Sets the actual overtime work value.
*
* @param work actual overtime work value
*/
public void setActualOvertimeWork (Duration work)
{
set(TaskField.ACTUAL_OVERTIME_WORK, work);
}
/**
* Retrieves the fixed cost accrual flag value.
*
* @return fixed cost accrual flag
*/
public AccrueType getFixedCostAccrual ()
{
return ((AccrueType)get(TaskField.FIXED_COST_ACCRUAL));
}
/**
* Sets the fixed cost accrual flag value.
*
* @param type fixed cost accrual type
*/
public void setFixedCostAccrual (AccrueType type)
{
set(TaskField.FIXED_COST_ACCRUAL, type);
}
/**
* Retrieves the task hyperlink attribute.
*
* @return hyperlink attribute
*/
public String getHyperlink ()
{
return ((String)get(TaskField.HYPERLINK));
}
/**
* Retrieves the task hyperlink address attribute.
*
* @return hyperlink address attribute
*/
public String getHyperlinkAddress ()
{
return ((String)get(TaskField.HYPERLINK_ADDRESS));
}
/**
* Retrieves the task hyperlink sub-address attribute.
*
* @return hyperlink sub address attribute
*/
public String getHyperlinkSubAddress ()
{
return ((String)get(TaskField.HYPERLINK_SUBADDRESS));
}
/**
* Sets the task hyperlink attribute.
*
* @param text hyperlink attribute
*/
public void setHyperlink (String text)
{
set(TaskField.HYPERLINK, text);
}
/**
* Sets the task hyperlink address attribute.
*
* @param text hyperlink address attribute
*/
public void setHyperlinkAddress (String text)
{
set(TaskField.HYPERLINK_ADDRESS, text);
}
/**
* Sets the task hyperlink sub address attribute.
*
* @param text hyperlink sub address attribute
*/
public void setHyperlinkSubAddress (String text)
{
set(TaskField.HYPERLINK_SUBADDRESS, text);
}
/**
* Retrieves the level assignments flag.
*
* @return level assignments flag
*/
public boolean getLevelAssignments ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.LEVEL_ASSIGNMENTS)));
}
/**
* Sets the level assignments flag.
*
* @param flag level assignments flag
*/
public void setLevelAssignments (boolean flag)
{
set(TaskField.LEVEL_ASSIGNMENTS, flag);
}
/**
* Retrieves the leveling can split flag.
*
* @return leveling can split flag
*/
public boolean getLevelingCanSplit ()
{
return (BooleanUtility.getBoolean((Boolean)get(TaskField.LEVELING_CAN_SPLIT)));
}
/**
* Sets the leveling can split flag.
*
* @param flag leveling can split flag
*/
public void setLevelingCanSplit (boolean flag)
{
set(TaskField.LEVELING_CAN_SPLIT, flag);
}
/**
* Retrieves the overtime work attribute.
*
* @return overtime work value
*/
public Duration getOvertimeWork ()
{
return ((Duration)get(TaskField.OVERTIME_WORK));
}
/**
* Sets the overtime work attribute.
*
* @param work overtime work value
*/
public void setOvertimeWork (Duration work)
{
set(TaskField.OVERTIME_WORK, work);
}
/**
* Retrieves the preleveled start attribute.
*
* @return preleveled start
*/
public Date getPreleveledStart ()
{
return ((Date)get(TaskField.PRELEVELED_START));
}
/**
* Retrieves the preleveled finish attribute.
*
* @return preleveled finish
*/
public Date getPreleveledFinish ()
{
return ((Date)get(TaskField.PRELEVELED_FINISH));
}
/**
* Sets the preleveled start attribute.
*
* @param date preleveled start attribute
*/
public void setPreleveledStart (Date date)
{
set(TaskField.PRELEVELED_START, date);
}
/**
* Sets the preleveled finish attribute.
*
* @param date preleveled finish attribute
*/
public void setPreleveledFinish (Date date)
{
set(TaskField.PRELEVELED_FINISH, date);
}
/**
* Retrieves the remaining overtime work attribute.
*
* @return remaining overtime work
*/
public Duration getRemainingOvertimeWork ()
{
return ((Duration)get(TaskField.REMAINING_OVERTIME_WORK));
}
/**
* Sets the remaining overtime work attribute.
*
* @param work remaining overtime work
*/
public void setRemainingOvertimeWork (Duration work)
{
set(TaskField.REMAINING_OVERTIME_WORK, work);
}
/**
* Retrieves the remaining overtime cost.
*
* @return remaining overtime cost value
*/
public Number getRemainingOvertimeCost ()
{
return ((Number)get(TaskField.REMAINING_OVERTIME_COST));
}
/**
* Sets the remaining overtime cost value.
*
* @param cost overtime cost value
*/
public void setRemainingOvertimeCost (Number cost)
{
set(TaskField.REMAINING_OVERTIME_COST, cost);
}
/**
* Retrieves the base calendar instance associated with this task.
* Note that this attribute appears in MPP9 and MSPDI files.
*
* @return ProjectCalendar instance
*/
public ProjectCalendar getCalendar ()
{
return ((ProjectCalendar)get(TaskField.CALENDAR));
}
/**
* Sets the name of the base calendar associated with this task.
* Note that this attribute appears in MPP9 and MSPDI files.
*
* @param calendar calendar instance
*/
public void setCalendar (ProjectCalendar calendar)
{
set(TaskField.CALENDAR, calendar);
}
/**
* Retrieve a flag indicating if the task is shown as expanded
* in MS Project. If this flag is set to true, any sub tasks
* for this current task will be visible. If this is false,
* any sub tasks will be hidden.
*
* @return boolean flag
*/
public boolean getExpanded ()
{
return (m_expanded);
}
/**
* Set a flag indicating if the task is shown as expanded
* in MS Project. If this flag is set to true, any sub tasks
* for this current task will be visible. If this is false,
* any sub tasks will be hidden.
*
* @param expanded boolean flag
*/
public void setExpanded (boolean expanded)
{
m_expanded = expanded;
}
/**
* Set the start slack.
*
* @param duration start slack
*/
public void setStartSlack (Duration duration)
{
set(TaskField.START_SLACK, duration);
}
/**
* Set the finish slack.
*
* @param duration finish slack
*/
public void setFinishSlack (Duration duration)
{
set(TaskField.FINISH_SLACK, duration);
}
/**
* Retrieve the start slack.
*
* @return start slack
*/
public Duration getStartSlack ()
{
return ((Duration)get(TaskField.START_SLACK));
}
/**
* Retrieve the finish slack.
*
* @return finish slack
*/
public Duration getFinishSlack ()
{
return ((Duration)get(TaskField.FINISH_SLACK));
}
/**
* Retrieve the value of a field using its alias.
*
* @param alias field alias
* @return field value
*/
public Object getFieldByAlias (String alias)
{
return (get(getParentFile().getAliasTaskField(alias)));
}
/**
* Set the value of a field using its alias.
*
* @param alias field alias
* @param value field value
*/
public void setFieldByAlias (String alias, Object value)
{
set(getParentFile().getAliasTaskField(alias), value);
}
/**
* This method retrieves a list of task splits. Each split is represented
* by a number of working hours since the start of the task to the end of
* the current split. The list will always follow the pattern
* task time, split time, task time and so on. For example, if we have a
* 5 day task which is represented as 2 days work, a one day, then three
* days work, the splits list will contain 16h, 24h, 48h. Assuming an 8 hour
* working day, this equates to the end of the first working segment beging
* 2 working days from the task start date (16h), the end of the first split
* being 3 working days from the task start date (24h) and finally, the end
* of the entire task being 6 working days from the task start date (48h).
*
* Note that this method will return null if the task is not split.
*
* @return list of split times
*/
public List getSplits ()
{
return (m_splits);
}
/**
* Internal method used to set the list of splits.
*
* @param splits list of split times
*/
public void setSplits (List splits)
{
m_splits = splits;
}
/**
* Removes this task from the project.
*/
public void remove ()
{
getParentFile().removeTask(this);
}
/**
* Retrieve the sub project represented by this task.
*
* @return sub project
*/
public SubProject getSubProject ()
{
return (m_subProject);
}
/**
* Set the sub project represented by this task.
*
* @param subProject sub project
*/
public void setSubProject (SubProject subProject)
{
m_subProject = subProject;
}
/**
* {@inheritDoc}
*/
public Object get (FieldType field)
{
return (field==null?null:m_array[field.getValue()]);
}
/**
* {@inheritDoc}
*/
public void set (FieldType field, Object value)
{
if (field != null)
{
int index = field.getValue();
fireFieldChangeEvent (field, m_array[index], value);
m_array[index] = value;
}
}
/**
* Handle the change in a field value. Reset any cached calculated
* values affected by this change, pass on the event to any external
* listeners.
*
* @param field field changed
* @param oldValue old field value
* @param newValue new field value
*/
private void fireFieldChangeEvent (FieldType field, Object oldValue, Object newValue)
{
// Internal event handling
switch (field.getValue())
{
case TaskField.START_VALUE:
case TaskField.BASELINE_START_VALUE:
{
m_array[TaskField.START_VARIANCE_VALUE] = null;
break;
}
case TaskField.FINISH_VALUE:
case TaskField.BASELINE_FINISH_VALUE:
{
m_array[TaskField.START_VARIANCE_VALUE] = null;
break;
}
case TaskField.COST_VALUE:
case TaskField.BASELINE_COST_VALUE:
{
m_array[TaskField.COST_VARIANCE_VALUE] = null;
break;
}
case TaskField.DURATION_VALUE:
case TaskField.BASELINE_DURATION_VALUE:
{
m_array[TaskField.DURATION_VARIANCE_VALUE] = null;
break;
}
case TaskField.WORK_VALUE:
case TaskField.BASELINE_WORK_VALUE:
{
m_array[TaskField.WORK_VARIANCE_VALUE] = null;
break;
}
case TaskField.BCWP_VALUE:
case TaskField.ACWP_VALUE:
{
m_array[TaskField.CV_VALUE] = null;
m_array[TaskField.SV_VALUE] = null;
break;
}
case TaskField.BCWS_VALUE:
{
m_array[TaskField.SV_VALUE] = null;
break;
}
case TaskField.START_SLACK_VALUE:
case TaskField.FINISH_SLACK_VALUE:
{
m_array[TaskField.TOTAL_SLACK_VALUE] = null;
break;
}
}
// External event handling
if (m_listeners != null)
{
Iterator iter = m_listeners.iterator();
while (iter.hasNext() == true)
{
((FieldListener)iter.next()).fieldChange(this, field, oldValue, newValue);
}
}
}
/**
* {@inheritDoc}
*/
public void addFieldListener (FieldListener listener)
{
if (m_listeners == null)
{
m_listeners = new LinkedList();
}
m_listeners.add(listener);
}
/**
* {@inheritDoc}
*/
public void removeFieldListener (FieldListener listener)
{
if (m_listeners != null)
{
m_listeners.remove(listener);
}
}
/**
* This method inserts a name value pair into internal storage.
*
* @param field task field
* @param value attribute value
*/
private void set (FieldType field, boolean value)
{
set (field, (value ? Boolean.TRUE : Boolean.FALSE));
}
/**
* {@inheritDoc}
*/
public String toString()
{
return ("[Task id=" + getID() + " name=" + getName() + "]");
}
/**
* Array of field values.
*/
private Object[] m_array = new Object[TaskField.MAX_VALUE];
/**
* This is a reference to the parent task, as specified by the
* outline level.
*/
private Task m_parent;
/**
* This list holds references to all tasks that are children of the
* current task as specified by the outline level.
*/
private List m_children = new LinkedList();
/**
* List of resource assignments for this task.
*/
private List m_assignments = new LinkedList();
/**
* Recurring task details associated with this task.
*/
private RecurringTask m_recurringTask;
private boolean m_null;
private String m_wbsLevel;
private TimeUnit m_durationFormat;
private boolean m_resumeValid;
private Integer m_subprojectTaskUniqueID;
private Integer m_subprojectTasksUniqueIDOffset;
private String m_externalTaskProject;
private TimeUnit m_levelingDelayFormat;
private Integer m_physicalPercentComplete;
private EarnedValueMethod m_earnedValueMethod;
private Duration m_actualWorkProtected;
private Duration m_actualOvertimeWorkProtected;
private boolean m_expanded = true;
private List m_splits;
private SubProject m_subProject;
private List m_listeners;
}
|
package org.eclipse.kapua.app.console.module.user.client.dialog;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import org.eclipse.kapua.app.console.module.api.client.GwtKapuaErrorCode;
import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException;
import org.eclipse.kapua.app.console.module.api.client.util.DialogUtils;
import org.eclipse.kapua.app.console.module.api.client.util.FailureHandler;
import org.eclipse.kapua.app.console.module.api.shared.model.session.GwtSession;
import org.eclipse.kapua.app.console.module.user.shared.model.GwtUser;
import org.eclipse.kapua.app.console.module.user.shared.service.GwtUserService;
import org.eclipse.kapua.app.console.module.user.shared.service.GwtUserServiceAsync;
public class UserEditDialog extends UserAddDialog {
private GwtUser selectedUser;
private GwtUserServiceAsync gwtUserService = GWT.create(GwtUserService.class);
public UserEditDialog(GwtSession currentSession, GwtUser selectedUser) {
super(currentSession);
this.selectedUser = selectedUser;
DialogUtils.resizeDialog(this, 400, 390);
}
@Override
public void createBody() {
super.createBody();
loadUser();
}
private void loadUser() {
maskDialog();
gwtUserService.find(selectedUser.getScopeId(), selectedUser.getId(), new AsyncCallback<GwtUser>() {
@Override
public void onSuccess(GwtUser gwtUser) {
unmaskDialog();
populateEditDialog(gwtUser);
}
@Override
public void onFailure(Throwable cause) {
exitStatus = false;
exitMessage = USER_MSGS.dialogEditLoadFailed(cause.getLocalizedMessage());
unmaskDialog();
hide();
}
});
}
@Override
public void submit() {
selectedUser.setUsername(username.getValue());
selectedUser.setDisplayName(displayName.getValue());
selectedUser.setEmail(email.getValue());
selectedUser.setPhoneNumber(phoneNumber.getValue());
selectedUser.setStatus(userStatus.getValue().getValue().toString());
selectedUser.setExpirationDate(expirationDate.getValue());
gwtUserService.update(xsrfToken, selectedUser, new AsyncCallback<GwtUser>() {
@Override
public void onSuccess(GwtUser arg0) {
exitStatus = true;
exitMessage = USER_MSGS.dialogEditConfirmation();
hide();
}
@Override
public void onFailure(Throwable cause) {
exitStatus = false;
exitMessage = USER_MSGS.dialogEditError(cause.getLocalizedMessage());
FailureHandler.handleFormException(formPanel, cause);
status.hide();
formPanel.getButtonBar().enable();
unmask();
submitButton.enable();
cancelButton.enable();
if (cause instanceof GwtKapuaException) {
GwtKapuaException gwtCause = (GwtKapuaException) cause;
if (gwtCause.getCode().equals(GwtKapuaErrorCode.DUPLICATE_NAME)) {
username.markInvalid(gwtCause.getMessage());
}
}
}
});
}
@Override
public String getHeaderMessage() {
return USER_MSGS.dialogEditHeader(selectedUser.getUsername());
}
@Override
public String getInfoMessage() {
return USER_MSGS.dialogEditInfo();
}
private void populateEditDialog(GwtUser gwtUser) {
infoFieldSet.remove(username);
usernameLabel.setVisible(true);
usernameLabel.setValue(gwtUser.getUsername());
if (password != null) {
password.setVisible(false);
password.setAllowBlank(true);
password.setValidator(null);
}
if (confirmPassword != null) {
confirmPassword.setVisible(false);
confirmPassword.setAllowBlank(true);
confirmPassword.setValidator(null);
}
if (passwordTooltip != null) {
passwordTooltip.hide();
}
username.setValue(gwtUser.getUsername());
displayName.setValue(gwtUser.getDisplayName());
email.setValue(gwtUser.getEmail());
phoneNumber.setValue(gwtUser.getPhoneNumber());
userStatus.setSimpleValue(gwtUser.getStatusEnum());
expirationDate.setValue(gwtUser.getExpirationDate());
expirationDate.setMaxLength(10);
}
}
|
//$HeadURL$
package org.deegree.cs.transformations.coordinate;
import java.util.List;
import javax.vecmath.Point2d;
import javax.vecmath.Point3d;
import org.deegree.commons.annotations.LoggingNotes;
import org.deegree.cs.CRSCodeType;
import org.deegree.cs.CRSIdentifiable;
import org.deegree.cs.CRSResource;
import org.deegree.cs.components.Axis;
import org.deegree.cs.components.IAxis;
import org.deegree.cs.coordinatesystems.IProjectedCRS;
import org.deegree.cs.exceptions.ProjectionException;
import org.deegree.cs.exceptions.TransformationException;
import org.deegree.cs.transformations.Transformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>ProjectionTransform</code> class wraps the access to a projection, by calling it's doProjection.
*
* @author <a href="mailto:[email protected]">Rutger Bezema</a>
*
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*
*/
@LoggingNotes(debug = "Get information about axis of the projection as well as the used projection and the incoming ordinates.")
public class ProjectionTransform extends Transformation {
private static Logger LOG = LoggerFactory.getLogger( ProjectionTransform.class );
private boolean swapAxisTarget = false;
private boolean swapAxisSource = false;
private IProjectedCRS projectedCRS;
/**
* @param projectedCRS
* The crs containing a projection.
* @param id
* an identifiable instance containing information about this transformation
*/
public ProjectionTransform( IProjectedCRS projectedCRS, CRSResource id ) {
super( projectedCRS.getGeographicCRS(), projectedCRS, id );
this.projectedCRS = projectedCRS;
// this.projection = projectedCRS.getProjection();
// expected: lon/lat
swapAxisSource = checkAxisOrientation( getSourceCRS().getAxis() );
// expected: lon/lat
swapAxisTarget = checkAxisOrientation( getTargetCRS().getAxis() );
}
/**
* @param axis
*/
private boolean checkAxisOrientation( IAxis[] axis ) {
boolean result = false;
if ( axis == null || axis.length != 2 ) {
result = false;
} else {
IAxis first = axis[0];
IAxis second = axis[1];
LOG.debug( "First projected crs Axis: " + first );
LOG.debug( "Second projected crs Axis: " + second );
if ( first != null && second != null ) {
if ( Axis.AO_WEST == Math.abs( second.getOrientation() ) ) {
result = true;
if ( Axis.AO_NORTH != Math.abs( first.getOrientation() ) ) {
LOG.warn( "The given projection uses a second axis which is not mappable ( " + second
+ ") please check your configuration, assuming y, x axis-order." );
}
}
}
}
LOG.debug( "Incoming ordinates will" + ( ( result ) ? " " : " not " ) + "be swapped." );
return result;
}
/**
* @param projectedCRS
* The crs containing a projection.
*/
public ProjectionTransform( IProjectedCRS projectedCRS ) {
this(
projectedCRS,
new CRSIdentifiable(
CRSCodeType.valueOf( createFromTo( projectedCRS.getGeographicCRS().getCode().toString(),
projectedCRS.getCode().toString() ) ) ) );
}
@Override
public List<Point3d> doTransform( List<Point3d> srcPts )
throws TransformationException {
// List<Point3d> result = new ArrayList<Point3d>( srcPts.size() );
// if ( LOG.isDebugEnabled() ) {
// StringBuilder sb = new StringBuilder( isInverseTransform() ? "An inverse" : "A" );
// sb.append( " projection transform with incoming points: " );
// sb.append( srcPts );
// sb.append( " and following projection: " );
// sb.append( projectedCRS.getProjection().getImplementationName() );
// LOG.debug( sb.toString() );
if ( isInverseTransform() ) {
doInverseTransform( srcPts );
} else {
doForwardTransform( srcPts );
}
return srcPts;
}
/**
* @param srcPts
*/
private void doForwardTransform( List<Point3d> srcPts ) {
int i = 0;
if ( swapAxisSource ) {
for ( Point3d p : srcPts ) {
try {
Point2d tmp = projectedCRS.doProjection( p.y, p.x );
if ( swapAxisTarget ) {
p.x = tmp.y;
p.y = tmp.x;
} else {
p.x = tmp.x;
p.y = tmp.y;
}
} catch ( ProjectionException e ) {
LOG.trace( "Stack trace:", e );
LOG.warn( "Transformation error: {}", e.getLocalizedMessage() );
}
++i;
}
} else {
for ( Point3d p : srcPts ) {
try {
Point2d tmp = projectedCRS.doProjection( p.x, p.y );
if ( swapAxisTarget ) {
p.x = tmp.y;
p.y = tmp.x;
} else {
p.x = tmp.x;
p.y = tmp.y;
}
} catch ( ProjectionException e ) {
LOG.trace( "Stack trace:", e );
LOG.warn( "Transformation error: {}", e.getLocalizedMessage() );
}
++i;
}
}
}
/**
* @param srcPts
*/
private void doInverseTransform( List<Point3d> srcPts ) {
int i = 0;
if ( swapAxisTarget ) {
for ( Point3d p : srcPts ) {
try {
Point2d tmp = projectedCRS.doInverseProjection( p.y, p.x );
if ( swapAxisSource ) {
p.x = tmp.y;
p.y = tmp.x;
} else {
p.x = tmp.x;
p.y = tmp.y;
}
} catch ( ProjectionException e ) {
LOG.trace( "Stack trace:", e );
LOG.warn( "Transformation error: {}", e.getLocalizedMessage() );
}
++i;
}
} else {
for ( Point3d p : srcPts ) {
try {
Point2d tmp = projectedCRS.doInverseProjection( p.x, p.y );
if ( swapAxisSource ) {
p.x = tmp.y;
p.y = tmp.x;
} else {
p.x = tmp.x;
p.y = tmp.y;
}
} catch ( ProjectionException e ) {
LOG.trace( "Stack trace:", e );
LOG.warn( "Transformation error: {}", e.getLocalizedMessage() );
}
++i;
}
}
}
@Override
public boolean isIdentity() {
// a projection cannot be an identity it doesn't make a lot of sense.
return false;
}
@Override
public String toString() {
return super.toString() + " - Projection: " + projectedCRS.getProjection().getImplementationName();
}
@Override
public String getImplementationName() {
return "Projection-Transform";
}
}
|
package org.jboss.as.domain.http.server;
import static org.jboss.as.domain.http.server.Common.METHOD_NOT_ALLOWED_HANDLER;
import static org.jboss.as.domain.http.server.Common.NOT_FOUND;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
class ManagementRootConsoleRedirectHandler implements HttpHandler {
private static HttpString HTTP_GET = new HttpString("GET");
private final ResourceHandlerDefinition consoleHandler;
ManagementRootConsoleRedirectHandler(ResourceHandlerDefinition consoleHandler) {
this.consoleHandler = consoleHandler;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (!exchange.getRequestMethod().equals(HTTP_GET)) {
METHOD_NOT_ALLOWED_HANDLER.handleRequest(exchange);
return;
}
if (consoleHandler != null && "/".equals(exchange.getRequestPath())) {
consoleHandler.getHandler().handleRequest(exchange);
return;
}
NOT_FOUND.handleRequest(exchange);
}
}
|
/*
* Requirements mandating inclusion:
* */
package model;
import java.io.Serializable;
public class GameSettings implements Serializable {
int minPlayers;
int maxPlayers;
public GameSettings(){
}
public int getMinPlayers() {
return minPlayers;
}
public void setMinPlayers(int minPlayers) {
this.minPlayers = minPlayers;
}
public int getMaxPlayers() {
return maxPlayers;
}
public void setMaxPlayers(int maxPlayers) {
this.maxPlayers = maxPlayers;
}
}
|
public class SlamShuffle
{
public static final String DATA_FILE = "data.txt";
public static final int SIZE_OF_DECK = 10007;
public static final int CARD = 2019;
public static void main (String[] args)
{
boolean debug = false;
boolean verify = false;
for (int i = 0; i < args.length; i++)
{
if ("-help".equals(args[i]))
{
System.out.println("Usage: [-verify] [-debug] [-help]");
System.exit(0);
}
if ("-debug".equals(args[i]))
debug = true;
if ("-verify".equals(args[i]))
verify = true;
}
if (verify)
{
Verifier theVerifier = new Verifier(debug);
if (theVerifier.verify())
System.out.println("\nVerified ok!");
else
System.out.println("\nVerify failed!");
System.exit(0);
}
Dealer theDealer = new Dealer(DATA_FILE, debug);
Deck theDeck = theDealer.dealCards(SIZE_OF_DECK);
int position = theDeck.positionOfCard(CARD);
System.out.println("Position of card "+CARD+" is "+position);
}
}
|
package main;
import robot.Plan;
import world.World;
public class Main {
public static void main(String[] args) {
Plan plan = new Plan(World.grid, World.start, World.goal);
System.out.println(plan);
System.out.println("Test");
}
}
|
package main;
/**
* @author Mr Wolfe
*
*/
public class main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("cats");
System.out.println("dogs");
System.out.println(""fish);
}
}
|
package org.openlca.app.editors.parameters.bigtable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.openlca.app.App;
import org.openlca.app.M;
import org.openlca.app.db.Database;
import org.openlca.app.rcp.images.Icon;
import org.openlca.app.search.ParameterUsagePage;
import org.openlca.app.util.Actions;
import org.openlca.app.util.UI;
import org.openlca.app.viewers.Viewers;
import org.openlca.app.viewers.tables.TableClipboard;
import org.openlca.app.viewers.tables.Tables;
import org.openlca.core.model.ParameterScope;
import org.openlca.expressions.FormulaInterpreter;
import org.openlca.expressions.Scope;
import org.openlca.util.Strings;
class EditorPage extends FormPage {
private final List<Param> params = new ArrayList<>();
private TableViewer table;
private Text filter;
private FilterCombo filterCombo;
public EditorPage(BigParameterTable table) {
super(table, "BigParameterTable", M.Parameters);
}
@Override
protected void createFormContent(IManagedForm mform) {
ScrolledForm form = UI.formHeader(mform, M.Parameters);
FormToolkit tk = mform.getToolkit();
Composite body = UI.formBody(form, tk);
Composite filterComp = tk.createComposite(body);
UI.gridLayout(filterComp, 3);
UI.gridData(filterComp, true, false);
filter = UI.formText(filterComp, tk, M.Filter);
filterCombo = FilterCombo.create(filterComp, tk);
Runnable doFilter = () -> {
String t = filter.getText();
if (Strings.nullOrEmpty(t)
&& filterCombo.type != FilterCombo.ERRORS) {
table.setInput(params);
} else {
List<Param> filtered = params.stream()
.filter(p -> p.matches(t, filterCombo.type))
.collect(Collectors.toList());
table.setInput(filtered);
}
};
filter.addModifyListener(e -> doFilter.run());
filterCombo.onChange = doFilter;
table = Tables.createViewer(body,
M.Name,
M.ParameterScope,
M.Value,
M.Formula,
M.Uncertainty,
M.Description);
double w = 1.0 / 6.0;
Tables.bindColumnWidths(table, w, w, w, w, w, w);
Label label = new Label();
table.setLabelProvider(label);
Viewers.sortByLabels(table, label, 0, 1, 3, 4, 5);
Viewers.sortByDouble(table, (Param p) -> p.parameter.value, 2);
bindActions();
mform.reflow(true);
App.runWithProgress(
"Loading parameters ...",
() -> Param.fetchAll(Database.get(), params),
() -> table.setInput(params));
}
private void bindActions() {
var onOpen = Actions.onOpen(() -> {
Param p = Viewers.getFirstSelected(table);
if (p == null)
return;
if (p.scope() == ParameterScope.GLOBAL) {
App.open(p.parameter);
} else if (p.owner != null) {
App.open(p.owner);
}
});
var onUsage = Actions.create(
M.Usage, Icon.LINK.descriptor(), () -> {
Param p = Viewers.getFirstSelected(table);
if (p == null)
return;
ParameterUsagePage.show(p.parameter, p.owner);
});
var onEvaluate = Actions.create(
M.EvaluateAllFormulas, Icon.RUN.descriptor(), () -> App.runWithProgress(
M.EvaluateAllFormulas, this::evaluateFormulas, () -> {
table.setInput(params);
filter.setText("");
}));
var onEdit = Actions.create(M.Edit, Icon.EDIT.descriptor(), this::onEdit);
var onCopy = TableClipboard.onCopySelected(table);
Actions.bind(table, onOpen, onUsage, onEvaluate, onEdit, onCopy);
Tables.onDoubleClick(table, e -> {
var cell = table.getCell(new Point(e.x, e.y));
if (cell == null)
return;
switch (cell.getColumnIndex()) {
case 0, 1 -> onOpen.run();
case 2, 3, 4 -> onEdit.run();
}
});
}
private void evaluateFormulas() {
var fi = buildInterpreter();
for (var param : params) {
var p = param.parameter;
if (p.isInputParameter) {
param.evalError = false;
continue;
}
var scope = param.isGlobal()
? fi.getGlobalScope()
: fi.getScopeOrGlobal(param.ownerId());
try {
p.value = scope.eval(p.formula);
param.evalError = false;
} catch (Exception e) {
param.evalError = true;
}
}
}
/**
* Bind the parameter values and formulas to the respective scopes of a
* formula interpreter.
*/
FormulaInterpreter buildInterpreter() {
var fi = new FormulaInterpreter();
for (var param : params) {
Scope scope = param.isGlobal()
? fi.getGlobalScope()
: fi.getOrCreate(param.ownerId());
var p = param.parameter;
if (p.isInputParameter) {
scope.bind(p.name, p.value);
} else {
scope.bind(p.name, p.formula);
}
}
return fi;
}
private void onEdit() {
Param param = Viewers.getFirstSelected(table);
if (param == null || param.parameter == null)
return;
if (ValueEditor.edit(this, param)) {
table.refresh();
}
}
}
|
// $Id: TopicType.java,v 1.7 2009/04/30 09:53:41 geir.gronmo Exp $
package ontopoly.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ontopoly.utils.FieldAssignmentOrderComparator;
import ontopoly.utils.OntopolyModelUtils;
import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.topicmaps.core.AssociationIF;
import net.ontopia.topicmaps.core.DataTypes;
import net.ontopia.topicmaps.core.OccurrenceIF;
import net.ontopia.topicmaps.core.TopicIF;
import net.ontopia.topicmaps.core.TopicMapBuilderIF;
import net.ontopia.topicmaps.query.core.QueryResultIF;
import net.ontopia.topicmaps.query.utils.RowMapperIF;
import net.ontopia.utils.StringUtils;
/**
* INTERNAL: Represents a topic type.
*/
public class TopicType extends AbstractTypingTopic {
public TopicType(TopicIF currTopic, TopicMap tm) {
super(currTopic, tm);
}
/**
* Tests whether this topic type is abstract.
*
* @return true if this topic type is abstract.
*/
public boolean isAbstract() {
return isTrueAssociation("is-abstract", "topic-type");
}
// /**
// * Makes this topic type either abstract or turn it off.
// *
// * @param value
// * value indicates whether this topic type is going to
// * be abstract.
// */
// public void setAbstract(boolean value) {
// TopicMap tm = getTopicMap();
// TopicIF topicIF = getTopicIF();
// TopicIF aType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "is-abstract");
// TopicIF rType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "topic-type");
// AssociationIF assoc = OntopolyModelUtils.findUnaryAssociation(tm, aType,
// topicIF, rType);
// if (value && assoc == null)
// OntopolyModelUtils.makeUnaryAssociation(aType, topicIF, rType);
// else if (!value && assoc != null)
// assoc.remove();
// /**
// * Tests whether this topic type can be used as a role type.
// */
// public boolean isValidRoleType() {
// String query = "instance-of(%topic% , on:role-type)?";
// Map params = Collections.singletonMap("topic", getTopicIF());
// return getTopicMap().getQueryWrapper().isTrue(query, params);
// /**
// * Sets whether the topic type can be used as a role type.
// */
// public void setValidRoleType(boolean value) {
// TopicMap tm = getTopicMap();
// TopicIF rType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "role-type");
// boolean validRoleType = isValidRoleType();
// TopicIF topicIF = getTopicIF();
// if (value && !validRoleType)
// topicIF.addType(rType);
// else if (validRoleType)
// topicIF.removeType(rType);
/**
* Tests whether this topic type has a large instance set.
*/
public boolean isLargeInstanceSet() {
return isTrueAssociation("has-large-instance-set", "topic-type");
}
private boolean isTrueAssociation(String atype, String rtype) {
TopicMap tm = getTopicMap();
TopicIF aType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, atype);
TopicIF rType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, rtype);
TopicIF topicIF = getTopicIF();
AssociationIF assoc = OntopolyModelUtils.findUnaryAssociation(tm, aType, topicIF, rType);
return (assoc != null);
}
//! /**
//! * Sets whether the topic type has a large instance set.
//! */
//! public void setLargeInstanceSet(boolean value) {
//! TopicMap tm = getTopicMap();
//! TopicIF aType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-large-instance-set");
//! TopicIF rType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "topic-type");
//! TopicIF topicIF = getTopicIF();
//! AssociationIF assoc = OntopolyModelUtils.findUnaryAssociation(tm, aType,
//! topicIF, rType);
//! if (value && assoc == null)
//! OntopolyModelUtils.makeUnaryAssociation(aType, topicIF, rType);
//! else if (assoc != null)
//! assoc.remove();
/**
* Gets the direct subtypes of this type.
*
* @return A Collection of TopicType objects.
*/
public Collection<TopicType> getDirectSubTypes() {
String query = "xtm:superclass-subclass($SUB : xtm:subclass, %topic% : xtm:superclass)?";
Map<String,TopicIF> params = Collections.singletonMap("topic", getTopicIF());
QueryMapper<TopicType> qm = getTopicMap().newQueryMapper(TopicType.class);
return qm.queryForList(query, params);
}
/**
* Gets the all subtypes (direct and indirect) of this type.
*
* @return A Collection of TopicType objects.
*/
public Collection<TopicType> getAllSubTypes() {
String query = "subclasses-of($SUP, $SUB) :- { "
+ "xtm:superclass-subclass($SUP : xtm:superclass, $SUB : xtm:subclass) | "
+ "xtm:superclass-subclass($SUP : xtm:superclass, $MID : xtm:subclass), "
+ "subclasses-of($MID, $SUB) }. " + "subclasses-of(%topic%, $SUB)?";
Map<String,TopicIF> params = Collections.singletonMap("topic", getTopicIF());
QueryMapper<TopicType> qm = getTopicMap().newQueryMapper(TopicType.class);
return qm.queryForList(query, params);
}
/**
* Returns the supertype of this type, or null if there is none.
*/
public TopicType getSuperType() {
String query = "xtm:superclass-subclass(%topic% : xtm:subclass, $SUP : xtm:superclass)?";
Map<String,TopicIF> params = Collections.singletonMap("topic", getTopicIF());
QueryMapper<TopicType> qm = getTopicMap().newQueryMapper(TopicType.class);
return qm.queryForObject(query, params);
}
// /**
// * Sets the supertype of this type. If parameter topic is null, only remove
// * the current superclass-subclass association without making a new one.
// */
// public void setSuperType(TopicType tt) {
// TopicMap tm = getTopicMap();
// TopicIF topicIF = getTopicIF();
// TopicIF aType = OntopolyModelUtils.getTopicIF(tm, PSI.XTM, "#superclass-subclass");
// TopicIF rType1 = OntopolyModelUtils.getTopicIF(tm, PSI.XTM, "#subclass");
// TopicIF rType2 = OntopolyModelUtils.getTopicIF(tm, PSI.XTM, "#superclass");
// TopicType superType = getSuperType();
// if (superType != null) { // Previous supertype exist
// AssociationIF associationIF = OntopolyModelUtils.findBinaryAssociation(
// tm, aType, topicIF, rType1, getSuperType().getTopicIF(), rType2);
// // remove the old super type association
// if (associationIF != null)
// associationIF.remove();
// // For every FieldAssignment inherited through the old supertype,
// // remove field-order occurrences on the current TopicType and all its
// // subtypes.
// Iterator it = superType.getFieldAssignments().iterator();
// while (it.hasNext()) {
// FieldAssignment fa = (FieldAssignment) it.next();
// FieldDefinition fieldDefinition = fa.getFieldDefinition();
// removeFieldOrder(this, fieldDefinition);
// if (tt != null) { // create the new super type association
// fieldOrderMaintainance(this);
// OntopolyModelUtils.makeBinaryAssociation(aType, getTopicIF(), rType1, tt
// .getTopicIF(), rType2);
// // For every FieldAssignment inherited through the new supertype,
// // create field-order occurrences on the current TopicType and all its
// // subtypes.
// Iterator it = tt.getFieldAssignments().iterator();
// while (it.hasNext()) {
// FieldAssignment fa = (FieldAssignment) it.next();
// FieldDefinition fieldDefinition = fa.getFieldDefinition();
// addFieldOrder(this, fieldDefinition);
public FieldAssignment addField(FieldDefinition fieldDefinition) {
TopicMap tm = getTopicMap();
final TopicIF HAS_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-field");
final TopicIF HAS_CARDINALITY = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-cardinality");
final TopicIF FIELD_DEFINITION = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-definition");
final TopicIF FIELD_OWNER = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-owner");
final TopicIF CARDINALITY = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "cardinality");
TopicIF fieldDefinitionTopic = fieldDefinition.getTopicIF();
TopicIF topicTypeTopic = getTopicIF();
fieldOrderMaintainance(this);
// on:has-field($TT : on:field-owner, $FD : on:field-definition)
OntopolyModelUtils.makeBinaryAssociation(HAS_FIELD,
topicTypeTopic, FIELD_OWNER,
fieldDefinitionTopic, FIELD_DEFINITION);
// on:has-cardinality($TT : on:field-owner, $FD : on:field-definition, $C : on:cardinality)
OntopolyModelUtils.makeTernaryAssociation(HAS_CARDINALITY,
topicTypeTopic, FIELD_OWNER,
fieldDefinitionTopic, FIELD_DEFINITION,
Cardinality.getDefaultCardinality(fieldDefinition).getTopicIF(), CARDINALITY);
// Add field-order occurrence for this topictype and all it's subtypes.
addFieldOrder(this, fieldDefinition);
return new FieldAssignment(this, this, fieldDefinition);
}
public void removeField(FieldDefinition fieldDefinition) {
TopicMap tm = getTopicMap();
final TopicIF HAS_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-field");
final TopicIF HAS_CARDINALITY = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-cardinality");
final TopicIF FIELD_DEFINITION = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-definition");
final TopicIF CARDINALITY = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "cardinality");
final TopicIF FIELD_OWNER = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-owner");
TopicIF fieldDefinitionTopic = fieldDefinition.getTopicIF();
TopicIF topicTypeTopic = getTopicIF();
// find and remove has-cardinality association
AssociationIF associationIF = OntopolyModelUtils.findTernaryAssociation(tm, HAS_CARDINALITY,
topicTypeTopic, FIELD_OWNER,
fieldDefinitionTopic, FIELD_DEFINITION,
Cardinality.getDefaultCardinality(fieldDefinition).getTopicIF(), CARDINALITY);
if (associationIF != null)
associationIF.remove();
// find and remove has-field association
associationIF = OntopolyModelUtils.findBinaryAssociation(tm, HAS_FIELD,
topicTypeTopic, FIELD_OWNER,
fieldDefinitionTopic, FIELD_DEFINITION);
if (associationIF != null)
associationIF.remove();
// See if one of the supertypes have also defined this field. If some of
// the supertypes has defined
// this field, don't remove the field-order occurrence.
boolean removeFieldOrder = true;
Iterator it = getFieldAssignments().iterator();
while (it.hasNext()) {
FieldAssignment fa = (FieldAssignment) it.next();
if (fa.getFieldDefinition().equals(fieldDefinition)) {
removeFieldOrder = false;
break;
}
}
if (removeFieldOrder) {
// Remove field-order occurrence from this topictype and all it's
// subtypes which have defined it.
removeFieldOrder(this, fieldDefinition);
}
}
public NameType createNameType() {
TopicMap tm = getTopicMap();
TopicMapBuilderIF builder = tm.getTopicMapIF().getBuilder();
// create name field
TopicIF nameFieldType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "name-field");
TopicIF nameFieldTopic = builder.makeTopic(nameFieldType);
// create name type
TopicIF nameTypeTopic = builder.makeTopic(OntopolyModelUtils.getTopicIF(tm, PSI.ON, "name-type"));
NameType nameType = new NameType(nameTypeTopic, tm);
// on:has-name-type($TT : on:name-type, $FD : on:name-field)
final TopicIF HAS_NAME_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-name-type");
final TopicIF NAME_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "name-type");
final TopicIF NAME_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "name-field");
OntopolyModelUtils.makeBinaryAssociation(HAS_NAME_TYPE,
nameTypeTopic, NAME_TYPE,
nameFieldTopic, NAME_FIELD);
// TODO: add default cardinality
// add field
NameField nameField = new NameField(nameFieldTopic, tm, nameType);
addField(nameField);
return nameType;
}
public OccurrenceType createOccurrenceType() {
TopicMap tm = getTopicMap();
TopicMapBuilderIF builder = tm.getTopicMapIF().getBuilder();
// create occurrence field
TopicIF occurrenceFieldType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "occurrence-field");
TopicIF occurrenceFieldTopic = builder.makeTopic(occurrenceFieldType);
// create occurrence type
TopicIF occurrenceTypeTopic = builder.makeTopic(OntopolyModelUtils.getTopicIF(tm, PSI.ON, "occurrence-type"));
OccurrenceType occurrenceType = new OccurrenceType(occurrenceTypeTopic, tm);
// on:has-occurrence-type($TT : on:occurrence-type, $FD : on:occurrence-field)
final TopicIF HAS_OCCURRENCE_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-occurrence-type");
final TopicIF OCCURRENCE_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "occurrence-type");
final TopicIF OCCURRENCE_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "occurrence-field");
OntopolyModelUtils.makeBinaryAssociation(HAS_OCCURRENCE_TYPE,
occurrenceTypeTopic, OCCURRENCE_TYPE,
occurrenceFieldTopic, OCCURRENCE_FIELD);
// TODO: add default datatype and cardinality
// add field
OccurrenceField occurrenceField = new OccurrenceField(occurrenceFieldTopic, tm);
addField(occurrenceField);
return occurrenceType;
}
public AssociationType createAssociationType() {
TopicMap tm = getTopicMap();
TopicMapBuilderIF builder = tm.getTopicMapIF().getBuilder();
// create role field
TopicIF roleFieldType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "role-field");
TopicIF roleFieldTopic = builder.makeTopic(roleFieldType);
//! // create role type
//! TopicIF roleTypeTopic = tm.createRoleType(null);
//! // on:has-role-type($TT : on:role-type, $FD : on:role-field)
//! final TopicIF HAS_ROLE_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-role-type");
//! final TopicIF ROLE_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "role-type");
//! final TopicIF ROLE_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "role-field");
//! OntopolyModelUtils.makeBinaryAssociation(HAS_ROLE_TYPE,
//! roleTypeTopic, ROLE_TYPE,
//! roleFieldTopic, ROLE_FIELD);
// create association field
TopicIF associationFieldType = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "association-field");
TopicIF associationFieldTopic = builder.makeTopic(associationFieldType);
// create association type
TopicIF associationTypeTopic = builder.makeTopic(OntopolyModelUtils.getTopicIF(tm, PSI.ON, "association-type"));
AssociationType associationType = new AssociationType(associationTypeTopic, tm);
// on:has-association-type($TT : on:association-type, $FD : on:association-field)
final TopicIF HAS_ASSOCIATION_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-association-type");
final TopicIF ASSOCIATION_TYPE = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "association-type");
final TopicIF ASSOCIATION_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "association-field");
OntopolyModelUtils.makeBinaryAssociation(HAS_ASSOCIATION_TYPE,
associationType.getTopicIF(), ASSOCIATION_TYPE,
associationFieldTopic, ASSOCIATION_FIELD);
// on:has-association-field($AF : on:association-field, $FD : on:role-field)
final TopicIF HAS_ASSOCIATION_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-association-field");
final TopicIF ROLE_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "role-field");
OntopolyModelUtils.makeBinaryAssociation(HAS_ASSOCIATION_FIELD,
roleFieldTopic, ROLE_FIELD,
associationFieldTopic, ASSOCIATION_FIELD);
// TODO: add default cardinality
// add field
RoleField roleField = new RoleField(roleFieldTopic, tm);
addField(roleField);
// create second role field
TopicIF roleFieldTopic2 = builder.makeTopic(roleFieldType);
// on:has-association-field($AF : on:association-field, $FD : on:role-field)
OntopolyModelUtils.makeBinaryAssociation(HAS_ASSOCIATION_FIELD,
roleFieldTopic2, ROLE_FIELD,
associationFieldTopic, ASSOCIATION_FIELD);
return associationType;
}
// Assures that every fieldAssignment assigned to this topic type has a
// fieldOrder
private static void fieldOrderMaintainance(TopicType tt) {
final TopicIF FIELD_ORDER = OntopolyModelUtils.getTopicIF(tt.getTopicMap(), PSI.ON, "field-order");
TopicIF topicIF = tt.getTopicIF();
List fieldAssignments = tt.getFieldAssignments();
Iterator it = fieldAssignments.iterator();
while (it.hasNext()) {
FieldAssignment fa = (FieldAssignment) it.next();
FieldDefinition fieldDefinition = fa.getFieldDefinition();
Collection scope = Collections.singleton(fieldDefinition.getTopicIF());
OccurrenceIF occurrenceIF = OntopolyModelUtils.findOccurrence(
FIELD_ORDER, topicIF, DataTypes.TYPE_STRING, scope);
if (occurrenceIF == null) {
String fieldOrderAsString;
int fieldOrder = fa.getOrder(tt);
if (fieldOrder != Integer.MAX_VALUE)
fieldOrderAsString = StringUtils.pad(fieldOrder + 1, '0', 9);
else
fieldOrderAsString = tt.getNextUnusedFieldOrder();
// create field-order occurrence
OntopolyModelUtils.makeOccurrence(FIELD_ORDER, topicIF,
fieldOrderAsString, DataTypes.TYPE_STRING, scope);
}
}
}
private static void addFieldOrder(TopicType tt, FieldDefinition fieldDefinition) {
final TopicIF FIELD_ORDER = OntopolyModelUtils.getTopicIF(tt.getTopicMap(), PSI.ON, "field-order");
TopicIF topicTypeTopic = tt.getTopicIF();
TopicIF fieldDefinitionTopic = fieldDefinition.getTopicIF();
Collection scope = Collections.singleton(fieldDefinitionTopic);
// see if field-order occurrence already exist for the same field
OccurrenceIF occurrenceIF = OntopolyModelUtils.findOccurrence(FIELD_ORDER,
topicTypeTopic, DataTypes.TYPE_STRING, scope);
if (occurrenceIF != null)
return;
// create field-order occurrence
OntopolyModelUtils.makeOccurrence(FIELD_ORDER, topicTypeTopic,
tt.getNextUnusedFieldOrder(), DataTypes.TYPE_STRING, scope);
// Go through all of TopicType tt's subtypes depth-first.
Iterator it = tt.getDirectSubTypes().iterator();
while (it.hasNext()) {
addFieldOrder((TopicType) it.next(), fieldDefinition);
}
}
private static void removeFieldOrder(TopicType tt, FieldDefinition fieldDefinition) {
// See if the same field is defined on this topic type.
TopicMap tm = tt.getTopicMap();
final TopicIF HAS_FIELD = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "has-field");
final TopicIF FIELD_DEFINITION = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-definition");
final TopicIF FIELD_OWNER = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-owner");
TopicIF topicTypeTopic = tt.getTopicIF();
TopicIF fieldDefinitionTopic = fieldDefinition.getTopicIF();
AssociationIF associationIF = OntopolyModelUtils.findBinaryAssociation(
tt.getTopicMap(), HAS_FIELD,
topicTypeTopic, FIELD_OWNER,
fieldDefinitionTopic, FIELD_DEFINITION);
// The field is defined on this topic type too, hence the field-order
// occurrence can't be removed.
if (associationIF != null)
return;
// find field-order occurrence
Collection scope = Collections.singleton(fieldDefinitionTopic);
OccurrenceIF occurrenceIF = OntopolyModelUtils.findOccurrence(
OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-order"),
tt.getTopicIF(), DataTypes.TYPE_STRING, scope);
// remove field-order occurrence if it exist
if (occurrenceIF != null) {
occurrenceIF.remove();
// Go through all of TopicType tt's subtypes depth-first.
Iterator it = tt.getDirectSubTypes().iterator();
while (it.hasNext()) {
removeFieldOrder((TopicType) it.next(), fieldDefinition);
}
}
}
public List<FieldsView> getFieldViews(boolean includeHiddenViews, boolean includeEmbeddedViews) {
String query =
"subclasses-of($SUP, $SUB) :- { " +
" xtm:superclass-subclass($SUP : xtm:superclass, $SUB : xtm:subclass) | " +
" xtm:superclass-subclass($SUP : xtm:superclass, $MID : xtm:subclass), subclasses-of($MID, $SUB) " +
"}. " +
"select $FIELDSVIEW from " +
"{ $TT = %tt% | subclasses-of($TT, %tt%) }, " +
"on:has-field($TT : on:field-owner, $FD : on:field-definition), " +
"{ on:field-in-view($FD : on:field-definition, $FV : on:fields-view)" +
(includeHiddenViews ? "" : ", not(on:is-hidden-view($FV : on:fields-view))") +
(includeEmbeddedViews ? "" : ", not(on:is-embedded-view($FV : on:fields-view))") +
" }, coalesce($FIELDSVIEW, $FV, on:default-fields-view) order by $FIELDSVIEW?";
Map<String,TopicIF> params = Collections.singletonMap("tt", getTopicIF());
QueryMapper<FieldsView> qm = getTopicMap().newQueryMapperNoWrap();
return qm.queryForList(query,
new RowMapperIF<FieldsView>() {
public FieldsView mapRow(QueryResultIF result, int rowno) {
TopicIF viewTopic = (TopicIF)result.getValue(0);
if (viewTopic == null)
return FieldsView.getDefaultFieldsView(getTopicMap());
else
return new FieldsView(viewTopic, getTopicMap());
}
}, params);
}
/**
* Returns the FieldAssignments for this topic type. These are sorted by the
* field order field on the field types. In addition, fields are inherited
* from all ancestor types.
*
* <p>
* Note that if isSystemTopic(), the list of fields will always contain the
* default name type with the "exactly one" cardinality at the very top
*/
public List<FieldAssignment> getFieldAssignments() {
return getFieldAssignments(null);
}
public List<FieldAssignment> getFieldAssignments(FieldsView view) {
String viewClause = "";
if (view != null) {
if (view.isDefaultView())
viewClause = "{ on:field-in-view($FD : on:field-definition, on:default-fields-view : on:fields-view) | not(on:field-in-view($FD : on:field-definition, $XV : on:fields-view), $XV /= on:default-fields-view) }, ";
else
viewClause = "on:field-in-view($FD : on:field-definition, %view% : on:fields-view), ";
}
String query =
"subclasses-of($SUP, $SUB) :- { " +
" xtm:superclass-subclass($SUP : xtm:superclass, $SUB : xtm:subclass) | " +
" xtm:superclass-subclass($SUP : xtm:superclass, $MID : xtm:subclass), subclasses-of($MID, $SUB) " +
"}. " +
"field-order($T, $FA, $FO) :- " +
" { occurrence($T, $O), type($O, on:field-order), " +
" scope($O, $FA), value($O, $FO) || " +
" xtm:superclass-subclass($T : xtm:subclass, $TT : xtm:superclass), " +
" field-order($TT, $FA, $FO) }. " +
"select $TT, $FD, $FT, $FO from " +
"{ $TT = %tt% | subclasses-of($TT, %tt%) }, " +
"on:has-field($TT : on:field-owner, $FD : on:field-definition), " +
viewClause +
"direct-instance-of($FD, $FT), xtm:superclass-subclass($FT : xtm:subclass, on:field-definition : xtm:superclass), " +
"{ field-order(%tt%, $FD, $FO) }?";
Map<String,TopicIF> params;
if (view == null)
params = Collections.singletonMap("tt", getTopicIF());
else {
params = new HashMap<String,TopicIF>(2);
params.put("tt", getTopicIF());
params.put("view", view.getTopicIF());
}
QueryMapper<FieldAssignment> qm = getTopicMap().newQueryMapperNoWrap();
List<FieldAssignment> fieldAssignments = qm.queryForList(query,
new RowMapperIF<FieldAssignment>() {
public FieldAssignment mapRow(QueryResultIF result, int rowno) {
TopicIF topicType = (TopicIF)result.getValue(0);
TopicIF fieldDefinitionTopic = (TopicIF)result.getValue(1);
TopicIF fieldDefinitionType = (TopicIF)result.getValue(2);
// OPTIMIZATION: retrieving field order here so we can pass it to the constructor
String foValue = (String)result.getValue(3);
int fieldOrder = (foValue != null ? Integer.parseInt(foValue) : Integer.MAX_VALUE);
TopicMap tm = getTopicMap();
TopicType tt = new TopicType(topicType, tm);
FieldDefinition fd = findFieldDefinitionImpl(tm, fieldDefinitionTopic, fieldDefinitionType);
return new FieldAssignment(TopicType.this, tt, fd, fieldOrder);
}
}, params);
Collections.sort(fieldAssignments, FieldAssignmentOrderComparator.INSTANCE);
return fieldAssignments;
}
static FieldDefinition findFieldDefinitionImpl(TopicMap tm, TopicIF fieldDefinitionTopic, TopicIF fieldDefinitionType) {
Collection identities = fieldDefinitionType.getSubjectIdentifiers();
if (identities.contains(PSI.ON_OCCURRENCE_FIELD))
return new OccurrenceField(fieldDefinitionTopic, tm);
else if (identities.contains(PSI.ON_ROLE_FIELD))
return new RoleField(fieldDefinitionTopic, tm);
else if (identities.contains(PSI.ON_NAME_FIELD))
return new NameField(fieldDefinitionTopic, tm);
else if (identities.contains(PSI.ON_IDENTITY_FIELD))
return new IdentityField(fieldDefinitionTopic, tm);
else
throw new OntopolyModelRuntimeException(
"This topic's subjectIndicator address didn't match any FieldDefinition implementations: "
+ identities);
}
private String getNextUnusedFieldOrder() {
int fieldOrder = 0;
// find field-order occurrence
Collection fieldOrderOccurrences = OntopolyModelUtils.findOccurrences(
OntopolyModelUtils.getTopicIF(getTopicMap(), PSI.ON, "field-order"),
getTopicIF(), DataTypes.TYPE_STRING);
Iterator it = fieldOrderOccurrences.iterator();
while (it.hasNext()) {
OccurrenceIF occurrenceIF = (OccurrenceIF) it.next();
int temp = Integer.parseInt(occurrenceIF.getValue());
if (temp > fieldOrder)
fieldOrder = temp;
}
return StringUtils.pad(fieldOrder + 1, '0', 9);
}
//! /**
//! * Returns the set of hierarchical association types associated with this
//! * topic type.
//! *
//! * @return a list of AssociationType objects
//! */
//! public Collection getHierarchicalAssociationTypes() {
//! String query = "on:forms-hierarchy-for($hierAssocTypes : on:association-type, %topic% : on:topic-type)?";
//! Map params = Collections.singletonMap("topic", getTopicIF());
//! TopicMap tm = getTopicMap();
//! Collection result = tm.getQueryWrapper().queryForList(query,
//! OntopolyModelUtils.getRowMapperOneColumn(), params);
//! if (result.isEmpty())
//! return Collections.EMPTY_SET;
//! List hierAssocTypes = new ArrayList();
//! Iterator it = result.iterator();
//! while (it.hasNext()) {
//! hierAssocTypes.add(new AssociationType((TopicIF) it.next(), tm));
//! Collections.sort(hierAssocTypes, TopicComparator.INSTANCE);
//! return hierAssocTypes;
//! /**
//! * Add the hierarchical association type (at) to this topic type
//! */
//! public void addHierarchicalAssociationType(AssociationType at) {
//! // create forms-hierarchy-for association
//! TopicMap tm = getTopicMap();
//! OntopolyModelUtils.makeBinaryAssociation(OntopolyModelUtils.getTopicIF(tm, PSI.ON, "forms-hierarchy-for"),
//! getTopicIF(),
//! OntopolyModelUtils.getTopicIF(tm, PSI.ON, "topic-type"),
//! at.getTopicIF(),
//! OntopolyModelUtils.getTopicIF(tm, PSI.ON, "association-type"));
//! /**
//! * Remove the hierarchical association type (at) from this topic type
//! */
//! public void removeHierarchicalAssociationType(AssociationType at) {
//! // find forms-hierarchy-for association
//! TopicMap tm = getTopicMap();
//! AssociationIF associationIF = OntopolyModelUtils.findBinaryAssociation(tm,
//! OntopolyModelUtils.getTopicIF(tm, PSI.ON, "forms-hierarchy-for"),
//! getTopicIF(), OntopolyModelUtils.getTopicIF(tm, PSI.ON, "topic-type"), at
//! .getTopicIF(), OntopolyModelUtils.getTopicIF(tm,
//! PSI.ON, "association-type"));
//! // remove forms-hierarchy-for association if it exist
//! if (associationIF != null)
//! associationIF.remove();
/**
* Returns the set of all instances of this topic type.
*
* @return A collection of Topic objects.
*/
public Collection<Topic> getInstances() {
String query = "instance-of($instance, %topic%)?";
Map<String,TopicIF> params = Collections.singletonMap("topic", getTopicIF());
QueryMapper<Topic> qm = getTopicMap().newQueryMapper(Topic.class);
return qm.queryForList(query, params);
}
//! public void moveUpInFieldOrder(FieldAssignment fa) {
//! fieldOrderMaintainance(this);
//! // find the fa above the current fa
//! List fieldAssignments = getFieldAssignments();
//! int indexOfCurrent = fieldAssignments.indexOf(fa);
//! int indexOfPrevious = indexOfCurrent - 1;
//! FieldAssignment fa_prev = (FieldAssignment) fieldAssignments
//! .get(indexOfPrevious);
//! // find
//! TopicMap tm = getTopicMap();
//! TopicIF topicIF = getTopicIF();
//! final TopicIF FIELD_ORDER = OntopolyModelUtils.getTopicIF(tm,
//! PSI.ON, "field-order");
//! Collection previousFieldOrderScope = new HashSet(2);
//! previousFieldOrderScope.add(fa_prev.getFieldDefinition().getTopicIF());
//! OccurrenceIF previousFAFieldOrderOccurrenceIF = OntopolyModelUtils
//! .findOccurrence(FIELD_ORDER, topicIF, DataTypes.TYPE_STRING,
//! previousFieldOrderScope);
//! if (previousFAFieldOrderOccurrenceIF == null) {
//! // create field-order occurrence
//! previousFAFieldOrderOccurrenceIF = OntopolyModelUtils.makeOccurrence(
//! FIELD_ORDER, topicIF,
//! StringUtils.pad(fa_prev.getOrder(this), '0', 9),
//! DataTypes.TYPE_STRING, previousFieldOrderScope);
//! String previousValue = previousFAFieldOrderOccurrenceIF.getValue();
//! Collection fieldOrderScope = new HashSet(2);
//! fieldOrderScope.add(fa.getFieldDefinition().getTopicIF());
//! OccurrenceIF currentFAFieldOrderOccurrenceIF = OntopolyModelUtils
//! .findOccurrence(FIELD_ORDER, topicIF, DataTypes.TYPE_STRING,
//! fieldOrderScope);
//! if (currentFAFieldOrderOccurrenceIF == null) {
//! // create field-order occurrence
//! currentFAFieldOrderOccurrenceIF = OntopolyModelUtils.makeOccurrence(
//! FIELD_ORDER, topicIF, StringUtils.pad(fa.getOrder(this), '0', 9),
//! DataTypes.TYPE_STRING, fieldOrderScope);
//! String currentValue = currentFAFieldOrderOccurrenceIF.getValue();
//! System.out.println("MU: " + previousValue + " -> " + currentValue);
//! previousFAFieldOrderOccurrenceIF.setValue(currentValue);
//! currentFAFieldOrderOccurrenceIF.setValue(previousValue);
//! // make sure cached state is updated
//! fa.refresh();
//! fa_prev.refresh();
//! public void moveDownInFieldOrder(FieldAssignment fa) {
//! fieldOrderMaintainance(this);
//! // find the fa below the current fa
//! List fieldAssignments = getFieldAssignments();
//! int indexOfCurrent = fieldAssignments.indexOf(fa);
//! int indexOfNext = indexOfCurrent + 1;
//! FieldAssignment fa_next = (FieldAssignment) fieldAssignments
//! .get(indexOfNext);
//! // find
//! TopicMap tm = getTopicMap();
//! TopicIF topicIF = getTopicIF();
//! final TopicIF FIELD_ORDER = OntopolyModelUtils.getTopicIF(tm, PSI.ON, "field-order");
//! Collection nextFieldOrderScope = new HashSet();
//! nextFieldOrderScope.add(fa_next.getFieldDefinition().getTopicIF());
//! OccurrenceIF nextFAFieldOrderOccurrenceIF = OntopolyModelUtils
//! .findOccurrence(FIELD_ORDER, topicIF, DataTypes.TYPE_STRING,
//! nextFieldOrderScope);
//! if (nextFAFieldOrderOccurrenceIF == null) {
//! // create field-order occurrence
//! nextFAFieldOrderOccurrenceIF = OntopolyModelUtils.makeOccurrence(
//! FIELD_ORDER, topicIF,
//! StringUtils.pad(fa_next.getOrder(this), '0', 9),
//! DataTypes.TYPE_STRING, nextFieldOrderScope);
//! String nextValue = nextFAFieldOrderOccurrenceIF.getValue();
//! Collection fieldOrderScope = new HashSet();
//! fieldOrderScope.add(fa.getFieldDefinition().getTopicIF());
//! OccurrenceIF currentFAFieldOrderOccurrenceIF = OntopolyModelUtils
//! .findOccurrence(FIELD_ORDER, topicIF, DataTypes.TYPE_STRING,
//! fieldOrderScope);
//! if (currentFAFieldOrderOccurrenceIF == null) {
//! // create field-order occurrence
//! currentFAFieldOrderOccurrenceIF = OntopolyModelUtils.makeOccurrence(
//! FIELD_ORDER, topicIF, StringUtils.pad(fa.getOrder(this), '0', 9),
//! DataTypes.TYPE_STRING, fieldOrderScope);
//! String currentValue = currentFAFieldOrderOccurrenceIF.getValue();
//! System.out.println("MD: " + currentValue + " -> " + nextValue);
//! nextFAFieldOrderOccurrenceIF.setValue(currentValue);
//! currentFAFieldOrderOccurrenceIF.setValue(nextValue);
//! // make sure cached state is updated
//! fa.refresh();
//! fa_next.refresh();
//! public static List getHierarchicalRelationTypes(TopicMap tm) {
//! String query = "instance-of($t, tech:hierarchical-relation-type),"
//! + "not (instance-of($t, on:system-topic))?";
//! Collection result = tm.getQueryWrapper().queryForList(query,
//! OntopolyModelUtils.getRowMapperOneColumn());
//! if (result.isEmpty())
//! return Collections.EMPTY_LIST;
//! List hierRelaTypes = new ArrayList();
//! Iterator it = result.iterator();
//! while (it.hasNext()) {
//! hierRelaTypes.add(new AssociationType((TopicIF) it.next(), tm));
//! Collections.sort(hierRelaTypes, TopicComparator.INSTANCE);
//! return hierRelaTypes;
/**
* Create a new topic instance of this topic type.
*/
public Topic createInstance(String name) {
TopicMap tm = getTopicMap();
// delegate to specific create method if known type
Collection subinds = getTopicIF().getSubjectIdentifiers();
if (subinds.contains(PSI.ON_TOPIC_TYPE))
return tm.createTopicType(name);
else if (subinds.contains(PSI.ON_ASSOCIATION_TYPE))
return tm.createAssociationType(name);
else if (subinds.contains(PSI.ON_ROLE_TYPE))
return tm.createRoleType(name);
else if (subinds.contains(PSI.ON_NAME_TYPE))
return tm.createNameType(name);
else if (subinds.contains(PSI.ON_OCCURRENCE_TYPE))
return tm.createOccurrenceType(name);
// use default create method
TopicIF topic = tm.createNamedTopic(name, getTopicIF());
return new Topic(topic, tm);
}
@Override
public LocatorIF getLocatorIF() {
return PSI.ON_TOPIC_TYPE;
}
/**
* Returns the topics that matches the given search term. Only topics of
* allowed player types are returned.
*
* @return a collection of Topic objects
*/
public List<Topic> searchAll(String searchTerm) {
String query = "select $topic, $score from "
+ "value-like($tn, %searchTerm%, $score), topic-name($topic, $tn), instance-of($topic, %topicType%) "
+ "order by $score desc, $topic?";
Map<String,Object> params = new HashMap<String,Object>();
params.put("searchTerm", searchTerm);
params.put("topicType", getTopicIF());
QueryMapper<Topic> qm = getTopicMap().newQueryMapper(Topic.class);
Collection<Topic> rows = qm.queryForList(query, params);
Iterator it = rows.iterator();
List<Topic> results = new ArrayList<Topic>(rows.size());
Set<TopicIF> duplicateChecks = new HashSet<TopicIF>(rows.size());
while (it.hasNext()) {
TopicIF topic = (TopicIF) it.next();
if (duplicateChecks.contains(topic))
continue; // avoid duplicates
results.add(new Topic(topic, getTopicMap()));
duplicateChecks.add(topic);
}
return results;
}
public Collection<? extends FieldDefinition> getDeclaredByFields() {
return Collections.emptyList();
}
// public Collection getUsedBy() {
// return Collections.EMPTY_LIST;
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
package org.opennms.netmgt.mock;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.sql.DataSource;
import org.hsqldb.Server;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.eventd.db.Constants;
import org.opennms.netmgt.utils.Querier;
import org.opennms.netmgt.utils.SingleResultQuerier;
import org.opennms.netmgt.utils.Updater;
import org.opennms.netmgt.xml.event.Event;
/**
* In memory database comparable to the postgres database that can be used for unit
* testing. Can be populated from a MockNetwork
* @author brozow
*/
public class MockDatabase implements DataSource, EventWriter {
private Server m_server;
private String m_dbName = "test";
public MockDatabase(String dbName) {
m_dbName = dbName;
try {
Class.forName("org.hsqldb.jdbcDriver" );
} catch (Exception e) {
throw new RuntimeException("Unable to locate hypersonic driver");
}
create();
}
public MockDatabase() {
this("test");
}
public void create() {
update("shutdown");
update("create table node (" +
"nodeID integer, " +
"dpName varchar(12)," +
"nodeCreateTime timestamp not null," +
"nodeParentID integer," +
"nodeType char(1)," +
"nodeSysOID varchar(256)," +
"nodeSysName varchar(256)," +
"nodeSysDescription varchar(256)," +
"nodeSysLocation varchar(256)," +
"nodeSysContact varchar(256)," +
"nodeLabel varchar(256)," +
"nodeLabelSource char(1)," +
"nodeNetBIOSName varchar(16)," +
"nodeDomainName varchar(16)," +
"operatingSystem varchar(64)," +
"lastCapsdPoll timestamp," +
//"constraint fk_dpName foreign key (dpName) references distPoller," +
"constraint pk_nodeID primary key (nodeID)" +
");");
update("create table ipInterface (" +
"nodeID integer, " +
"ipAddr varchar(16) not null, " +
"ifIndex integer," +
"ipHostname varchar(256)," +
"ipStatus integer," +
"ipLastCapsdPoll timestamp," +
"isSnmpPrimary char(1)," +
"isManaged char(1), " +
"constraint fk_nodeID1 foreign key (nodeID) references node ON DELETE CASCADE" +
");");
update("create table snmpInterface (" +
"nodeID integer, " +
"ipAddr varchar(16) not null, " +
"snmpIpAdEntNetMask varchar(16), " +
"snmpPhysAddr char(12)," +
"snmpIfIndex integer," +
"snmpIfDesc varchar(256)," +
"snmpIfType integer," +
"snmpIfName varchar(32)," +
"snmpIfSpeed bigint," +
"snmpIfAdminStatus integer," +
"snmpIfOperStatus integer," +
"snmpIfAlias varchar(32)," +
"constraint fk_nodeID2 foreign key (nodeID) references node ON DELETE CASCADE" +
");");
update("create table service (" +
"serviceID integer, " +
"serviceName varchar(32) not null, " +
"constraint pk_serviceID primary key (serviceID)" +
");");
update("create table ifServices (" +
"nodeID integer, " +
"ipAddr varchar(16) not null," +
"ifIndex integer," +
"serviceID integer," +
"lastGood timestamp," +
"lastFail timestamp," +
"qualifier char(16)," +
"status char(1)," +
"source char(1)," +
"notify char(1), " +
"constraint fk_nodeID3 foreign key (nodeID) references node ON DELETE CASCADE," +
"constraint fk_serviceID1 foreign key (serviceID) references service ON DELETE CASCADE" +
");");
update("create table events (" +
"eventID integer," +
"eventUei varchar(256) not null," +
"nodeID integer," +
"eventTime timestamp not null," +
"eventHost varchar(256)," +
"eventSource varchar(128) not null," +
"ipAddr varchar(16)," +
"eventDpName varchar(12) not null," +
"eventSnmphost varchar(256)," +
"serviceID integer," +
"eventSnmp varchar(256)," +
"eventParms longvarchar," +
"eventCreateTime timestamp not null," +
"eventDescr varchar(4000)," +
"eventLoggroup varchar(32)," +
"eventLogmsg varchar(256)," +
"eventSeverity integer not null," +
"eventPathOutage varchar(1024)," +
"eventCorrelation varchar(1024)," +
"eventSuppressedCount integer," +
"eventOperInstruct varchar(1024)," +
"eventAutoAction varchar(256)," +
"eventOperAction varchar(256)," +
"eventOperActionMenuText varchar(64)," +
"eventNotification varchar(128)," +
"eventTticket varchar(128)," +
"eventTticketState integer," +
"eventForward varchar(256)," +
"eventMouseOverText varchar(64)," +
"eventLog char(1) not null," +
"eventDisplay char(1) not null," +
"eventAckUser varchar(256)," +
"eventAckTime timestamp," +
"alarmID integer," +
"constraint pk_eventID primary key (eventID)," +
"constraint fk_nodeID6 foreign key (nodeID) references node ON DELETE CASCADE" +
");");
update("create table outages (" +
"outageID integer," +
"svcLostEventID integer," +
"svcRegainedEventID integer," +
"nodeID integer," +
"ipAddr varchar(16) not null," +
"serviceID integer," +
"ifLostService timestamp not null," +
"ifRegainedService timestamp," +
"constraint pk_outageID primary key (outageID)," +
"constraint fk_eventID1 foreign key (svcLostEventID) references events (eventID) ON DELETE CASCADE," +
"constraint fk_eventID2 foreign key (svcRegainedEventID) references events (eventID) ON DELETE CASCADE," +
"constraint fk_nodeID4 foreign key (nodeID) references node (nodeID) ON DELETE CASCADE," +
"constraint fk_serviceID2 foreign key (serviceID) references service (serviceID) ON DELETE CASCADE" +
");");
update("create table notifications (" +
" textMsg varchar(4000) not null," +
" subject varchar(256)," +
" numericMsg varchar(256)," +
" notifyID integer," +
" pageTime timestamp," +
" respondTime timestamp," +
" answeredBy varchar(256)," +
" nodeID integer," +
" interfaceID varchar(16)," +
" serviceID integer," +
" queueID varchar(256), " +
" eventID integer," +
" eventUEI varchar(256) not null," +
" notifConfigName varchar(63), " +
" constraint pk_notifyID primary key (notifyID)," +
" constraint fk_nodeID7 foreign key (nodeID) references node (nodeID) ON DELETE CASCADE," +
" constraint fk_eventID3 foreign key (eventID) references events (eventID) ON DELETE CASCADE" +
" );");
update("create table usersNotified (\n" +
" id integer not null, " +
" userID varchar(256) not null," +
" notifyID integer," +
" notifyTime timestamp," +
" media varchar(32)," +
" contactinfo varchar(64)," +
" autonotify char(1)," +
" constraint pk_userNotificationID primary key (id)," +
" constraint fk_notifID2 foreign key (notifyID) references notifications (notifyID) ON DELETE CASCADE" +
");");
update("create table alarms (\n" +
" alarmID INTEGER, \n" +
" eventUei VARCHAR(256) NOT NULL,\n" +
" dpName VARCHAR(12) NOT NULL,\n" +
" nodeID INTEGER,\n" +
" ipaddr VARCHAR(16),\n" +
" serviceID INTEGER,\n" +
" reductionKey VARCHAR(256),\n" +
" alarmType INTEGER,\n" +
" counter INTEGER NOT NULL,\n" +
" severity INTEGER NOT NULL,\n" +
" lastEventID INTEGER, \n" +
" firstEventTime TIMESTAMP,\n" +
" lastEventTime TIMESTAMP,\n" +
" description VARCHAR(4000),\n" +
" logMsg VARCHAR(256),\n" +
" operInstruct VARCHAR(1024),\n" +
" tticketID VARCHAR(128),\n" +
" tticketState INTEGER,\n" +
" mouseOverText VARCHAR(64),\n" +
" suppressedUntil TIMESTAMP,\n" +
" suppressedUser VARCHAR(256),\n" +
" suppressedTime TIMESTAMP,\n" +
" alarmAckUser VARCHAR(256),\n" +
" alarmAckTime TIMESTAMP,\n" +
" clearUei VARCHAR(256),\n" +
" managedObjectInstance VARCHAR(512),\n" +
" managedObjectType VARCHAR(512),\n" +
" applicationDN VARCHAR(512),\n" +
" ossPrimaryKey VARCHAR(512),\n" +
" x733AlarmType VARCHAR(31),\n" +
" x733ProbableCause INTEGER,\n" +
" qosAlarmState VARCHAR(31),\n" +
"" +
" CONSTRAINT pk_alarmID primary key (alarmID),\n"+
" CONSTRAINT fk_eventIDak2 FOREIGN KEY (lastEventID) REFERENCES events (eventID) ON DELETE CASCADE\n"+
")"
);
update("create table demandPolls (\n" +
" id integer,\n" +
" requestTime timestamp,\n" +
" username varchar(32),\n" +
" description varchar(128),\n" +
" \n" +
" constraint demandpoll_pkey primary key (id)\n" +
" \n" +
");"
);
update("create index demandpoll_request_time on demandPolls(requestTime);");
update("create table pollResults (\n" +
" id integer,\n" +
" pollId integer,\n" +
" nodeId integer,\n" +
" ipAddr varchar(16),\n" +
" ifIndex integer,\n" +
" serviceId integer,\n" +
" statusCode integer,\n" +
" statusName varchar(32),\n" +
" reason varchar(128),\n" +
" \n" +
" constraint pollresult_pkey primary key (id),\n" +
" constraint fk_demandPollId foreign key (pollID) references demandPolls (id) ON DELETE CASCADE\n" +
"\n" +
");\n" +
"");
update("create index pollresults_poll_id on pollResults(pollId);\n");
update("create index pollresults_service on pollResults(nodeId, ipAddr, ifIndex, serviceId);");
update("CREATE UNIQUE INDEX alarm_reductionkey_idx ON alarms(reductionKey);");
update("create sequence outageNxtId start with 1;");
update("create sequence eventNxtId start with 1;");
update("create sequence serviceNxtId start with 1;");
update("create sequence alarmNxtId start with 1;");
update("create sequence notifNxtId start with 1;");
update("create sequence userNotifNxtId start with 1;");
update("create sequence demandPollNxtId start with 1;");
update("create table seqQueryTable (row integer);");
update("insert into seqQueryTable (row) values (0);");
update("CREATE ALIAS iplike FOR \"org.opennms.netmgt.config.SnmpPeerFactory.verifyIpMatch\";");
update("CREATE ALIAS greatest FOR \"java.lang.Math.max\";");
update("CREATE ALIAS least FOR \"java.lang.Math.min\";");
}
public void startServer() {
m_server = new Server();
m_server.setPort(9001);
m_server.setTrace(true);
m_server.setDatabasePath(0, "mem:test");
synchronized(m_server) {
m_server.start();
}
}
public void drop() {
if (m_server != null)
m_server.stop();
update("shutdown;");
}
public void populate(MockNetwork network) {
MockVisitor dbCreater = new MockVisitorAdapter() {
public void visitNode(MockNode node) {
writeNode(node);
}
public void visitInterface(MockInterface iface) {
writeInterface(iface);
}
public void visitService(MockService svc) {
writeService(svc);
}
};
network.visit(dbCreater);
}
public void writeNode(MockNode node) {
Object[] values = { new Integer(node.getNodeId()), node.getLabel(), new Timestamp(System.currentTimeMillis()), "A" };
update("insert into node (nodeID, nodeLabel, nodeCreateTime, nodeType) values (?, ?, ?, ?);", values);
}
public Connection getConnection() throws SQLException {
String dbURL = "jdbc:hsqldb:mem:"+m_dbName;
//String dbURL = "jdbc:hsqldb:file:/tmp/test;shutdown=true";
Connection c = DriverManager.getConnection(dbURL, "sa", "");
return c;
}
public void update(String sql) {
update(sql, new Object[0]);
}
public void update(String stmt, Object[] values) {
// StringBuffer buf = new StringBuffer("[");
// for(int i = 0; i < values.length; i++) {
// if (i != 0)
// buf.append(", ");
// buf.append(values[i]);
// buf.append("]");
// MockUtil.println("Executing "+stmt+" with values "+buf);
Updater updater = new Updater(this, stmt);
updater.execute(values);
}
public void writeInterface(MockInterface iface) {
int ifIndex = writeSnmpInterface(iface);
Object[] values = { new Integer(iface.getNodeId()), iface.getIpAddr(), new Integer(ifIndex), (ifIndex == 1 ? "P" : "N"), "A" };
update("insert into ipInterface (nodeID, ipAddr, ifIndex, isSnmpPrimary, isManaged) values (?, ?, ?, ?, ?);", values);
}
public int writeSnmpInterface(MockInterface iface) {
Object[] values = { new Integer(iface.getNodeId()), iface.getIpAddr(), iface.getIfAlias() };
update("insert into snmpInterface (nodeID, ipAddr, snmpifAlias) values (?, ?, ?);", values);
return 1;
}
public void writeService(MockService svc) {
String svcName = svc.getSvcName();
if (!serviceDefined(svcName)) {
Object[] svcValues = { new Integer(svc.getId()), svcName };
//Object[] svcValues = { getNextServiceId(), svcName };
getNextServiceId();
update("insert into service (serviceID, serviceName) values (?, ?);", svcValues);
}
Object[] values = { new Integer(svc.getNodeId()), svc.getIpAddr(), new Integer(svc.getId()), "A" };
update("insert into ifServices (nodeID, ipAddr, serviceID, status) values (?, ?, ?, ?);", values);
}
public int countRows(String sql) {
return countRows(sql, new Object[0]);
}
public int countRows(String sql, Object[] values) {
Querier querier = new Querier(this, sql);
querier.execute(values);
return querier.getCount();
}
private boolean serviceDefined(String svcName) {
Querier querier = new Querier(this, "select serviceId from service where serviceName = ?");
querier.execute(svcName);
return querier.getCount() > 0;
}
public String getNextOutageIdStatement() {
return "select next value for outageNxtId from seqQueryTable";
}
public Integer getNextOutageId() {
return getNextId(getNextOutageIdStatement());
}
public String getNextSequenceValStatement(String seqName) {
return "select next value for "+seqName+" from seqQueryTable";
}
private Integer getNextId(String nxtIdStmt) {
SingleResultQuerier querier = new SingleResultQuerier(this, nxtIdStmt);
querier.execute();
return (Integer)querier.getResult();
}
public String getNextEventIdStatement() {
return "select next value for eventNxtId from seqQueryTable";
}
public Integer getNextEventId() {
return getNextId(getNextEventIdStatement());
}
public String getNextServiceIdStatement() {
return "select next value for serviceNxtId from seqQueryTable";
}
public Integer getNextServiceId() {
return getNextId(getNextServiceIdStatement());
}
public Integer getServiceID(String serviceName) {
if (serviceName == null) return new Integer(-1);
SingleResultQuerier querier = new SingleResultQuerier(this, "select serviceId from service where serviceName = ?");
querier.execute(serviceName);
return (Integer)querier.getResult();
}
public String getServiceName(int serviceId) {
SingleResultQuerier querier = new SingleResultQuerier(this, "select serviceName from service where serviceId = ?");
querier.execute(new Integer(serviceId));
return (String)querier.getResult();
}
public int countOutagesForService(MockService svc) {
return countOutagesForService(svc, null);
}
public int countOpenOutagesForService(MockService svc) {
return countOutagesForService(svc, "ifRegainedService is null");
}
public int countOutagesForService(MockService svc, String criteria) {
String critSql = (criteria == null ? "" : " and "+criteria);
Object[] values = { new Integer(svc.getNodeId()), svc.getIpAddr(), new Integer(svc.getId()) };
return countRows("select * from outages where nodeId = ? and ipAddr = ? and serviceId = ?"+critSql, values);
}
public void createOutage(MockService svc, Event svcLostEvent) {
createOutage(svc, svcLostEvent.getDbid(), convertEventTimeToTimeStamp(svcLostEvent.getTime()));
}
public void createOutage(MockService svc, int eventId, Timestamp time) {
Object[] values = {
getNextOutageId(), // outageID
new Integer(eventId), // svcLostEventId
new Integer(svc.getNodeId()), // nodeId
svc.getIpAddr(), // ipAddr
new Integer(svc.getId()), // serviceID
time, // ifLostService
};
update("insert into outages (outageId, svcLostEventId, nodeId, ipAddr, serviceId, ifLostService) values (?, ?, ?, ?, ?, ?);", values);
}
public void resolveOutage(MockService svc, Event svcRegainEvent) {
resolveOutage(svc, svcRegainEvent.getDbid(), convertEventTimeToTimeStamp(svcRegainEvent.getTime()));
}
public void resolveOutage(MockService svc, int eventId, Timestamp timestamp) {
Object[] values = {
new Integer(eventId), // svcLostEventId
timestamp, // ifLostService
new Integer(svc.getNodeId()), // nodeId
svc.getIpAddr(), // ipAddr
new Integer(svc.getId()), // serviceID
};
update("UPDATE outages set svcRegainedEventID=?, ifRegainedService=? where (nodeid = ? AND ipAddr = ? AND serviceID = ? and (ifRegainedService IS NULL));", values);
}
public Timestamp convertEventTimeToTimeStamp(String time) {
try {
Date date = EventConstants.parseToDate(time);
Timestamp eventTime = new Timestamp(date.getTime());
return eventTime;
} catch (ParseException e) {
throw new RuntimeException("Invalid date format "+time, e);
}
}
/**
* @param e
*/
public void writeEvent(Event e) {
Integer eventId = getNextEventId();
if (e.getCreationTime() == null)
e.setCreationTime(e.getTime());
Object[] values = {
eventId,
e.getSource(),
e.getUei(),
convertEventTimeToTimeStamp(e.getCreationTime()),
convertEventTimeToTimeStamp(e.getTime()),
new Integer(Constants.getSeverity(e.getSeverity())),
(e.hasNodeid() ? new Long(e.getNodeid()) : null),
e.getInterface(),
getServiceID(e.getService()),
"localhost",
"Y",
"Y",
e.getTticket() == null ? "" : e.getTticket().getContent(),
Integer.valueOf(e.getTticket() == null ? "0" : e.getTticket().getState()),
};
e.setDbid(eventId.intValue());
update("insert into events (" +
"eventId, eventSource, eventUei, eventCreateTime, eventTime, eventSeverity, " +
"nodeId, ipAddr, serviceId, eventDpName, " +
"eventLog, eventDisplay, eventtticket, eventtticketstate) " +
"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", values);
}
public void setServiceStatus(MockService svc, char newStatus) {
Object[] values = { String.valueOf(newStatus), new Integer(svc.getNodeId()), svc.getIpAddr(), new Integer(svc.getId()) };
update("update ifServices set status = ? where nodeId = ? and ipAddr = ? and serviceId = ?", values);
}
public char getServiceStatus(MockService svc) {
SingleResultQuerier querier = new SingleResultQuerier(this, "select status from ifServices where nodeId = ? and ipAddr = ? and serviceID = ?");
querier.execute(new Integer(svc.getNodeId()), svc.getIpAddr(), new Integer(svc.getId()));
String result = (String)querier.getResult();
if (result == null || "".equals(result)) {
return 'X';
}
return result.charAt(0);
}
public void setInterfaceStatus(MockInterface iface, char newStatus) {
Object[] values = { String.valueOf(newStatus), new Integer(iface.getNodeId()), iface.getIpAddr() };
update("update ipInterface set isManaged = ? where nodeId = ? and ipAddr = ?;", values);
}
public char getInterfaceStatus(MockInterface iface) {
SingleResultQuerier querier = new SingleResultQuerier(this, "select isManaged from ipInterface where nodeId = ? and ipAddr = ?");
querier.execute(new Integer(iface.getNodeId()), iface.getIpAddr());
String result = (String)querier.getResult();
if (result == null || "".equals(result)) {
return 'X';
}
return result.charAt(0);
}
public int countOutages() {
return countOutages(null);
}
public int countOpenOutages() {
return countOutages("ifRegainedService is null");
}
public int countOutages(String criteria) {
String critSql = (criteria == null ? "" : " where "+criteria);
return countRows("select * from outages"+critSql);
}
public int countOutagesForInterface(MockInterface iface) {
return countOutagesForInterface(iface, null);
}
public int countOpenOutagesForInterface(MockInterface iface) {
return countOutagesForInterface(iface, "ifRegainedService is null");
}
public int countOutagesForInterface(MockInterface iface, String criteria) {
String critSql = (criteria == null ? "" : " and "+criteria);
Object[] values = { new Integer(iface.getNodeId()), iface.getIpAddr() };
return countRows("select * from outages where nodeId = ? and ipAddr = ? "+critSql, values);
}
public boolean hasOpenOutage(MockService svc) {
return countOpenOutagesForService(svc) > 0;
}
public Collection getOutages() {
return getOutages(null, new Object[0]);
}
public Collection getOutages(String criteria, Object[] values) {
String critSql = (criteria == null ? "" : " where "+criteria);
final List outages = new LinkedList();
Querier loadExisting = new Querier(this, "select * from outages"+critSql) {
public void processRow(ResultSet rs) throws SQLException {
Outage outage = new Outage(rs.getInt("nodeId"), rs.getString("ipAddr"), rs.getInt("serviceId"));
outage.setLostEvent(rs.getInt("svcLostEventID"), rs.getTimestamp("ifLostService"));
boolean open = (rs.getObject("ifRegainedService") == null);
if (!open) {
outage.setRegainedEvent(rs.getInt("svcRegainedEventID"), rs.getTimestamp("ifRegainedService"));
}
outages.add(outage);
}
};
loadExisting.execute(values);
return outages;
}
public Collection getOpenOutages(MockService svc) {
Object[] values = { new Integer(svc.getNodeId()), svc.getIpAddr(), new Integer(svc.getId()) };
return getOutages("nodeId = ? and ipAddr = ? and serviceID = ? and ifRegainedService is null", values);
}
public Collection getOutages(MockService svc) {
Object[] values = { new Integer(svc.getNodeId()), svc.getIpAddr(), new Integer(svc.getId()) };
return getOutages("nodeId = ? and ipAddr = ? and serviceID = ?", values);
}
public Collection getClosedOutages(MockService svc) {
Object[] values = { new Integer(svc.getNodeId()), svc.getIpAddr(), new Integer(svc.getId()) };
return getOutages("nodeId = ? and ipAddr = ? and serviceID = ? and ifRegainedService is not null", values);
}
/**
* @param ipAddr
* @param nodeId
* @param nodeId2
*/
public void reparentInterface(String ipAddr, int oldNode, int newNode) {
Object[] values = { new Integer(newNode), new Integer(oldNode), ipAddr };
update("update ipInterface set nodeId = ? where nodeId = ? and ipAddr = ?;", values);
update("update ifServices set nodeId = ? where nodeId = ? and ipAddr = ?;", values);
}
/**
* @return
*/
public String getNextNotifIdSql() {
return "select next value for notifNxtId from seqQueryTable";
}
/**
* @param e
*/
public void acknowledgeNoticesForEvent(Event e) {
Object[] values = { new Timestamp(System.currentTimeMillis()), new Integer(e.getDbid()) };
update ("update notifications set respondTime = ? where eventID = ? and respondTime is null;", values);
}
/**
* @param event
* @return
*/
public Collection findNoticesForEvent(Event event) {
final List notifyIds = new LinkedList();
Querier loadExisting = new Querier(this, "select notifyId from notifications where eventID = ?") {
public void processRow(ResultSet rs) throws SQLException {
notifyIds.add(rs.getObject(1));
}
};
loadExisting.execute(new Integer(event.getDbid()));
return notifyIds;
}
public Integer getAlarmCount(String reductionKey) {
SingleResultQuerier querier = new SingleResultQuerier(this, "select counter from alarms where reductionKey = ?");
querier.execute(reductionKey);
return (Integer)querier.getResult();
}
public Integer getAlarmId(String reductionKey) {
SingleResultQuerier querier = new SingleResultQuerier(this, "select alarmid from alarms where reductionKey = ?");
querier.execute(reductionKey);
return (Integer)querier.getResult();
}
public Connection getConnection(String username, String password) throws SQLException {
return this.getConnection();
}
public PrintWriter getLogWriter() throws SQLException {
return DriverManager.getLogWriter();
}
public void setLogWriter(PrintWriter out) throws SQLException {
DriverManager.setLogWriter(out);
}
public void setLoginTimeout(int seconds) throws SQLException {
DriverManager.setLoginTimeout(seconds);
}
public int getLoginTimeout() throws SQLException {
return DriverManager.getLoginTimeout();
}
public String getNextUserNotifIdSql() {
return "select next value for userNotifNxtId from seqQueryTable";
}
}
|
package org.jerkar.samples;
import static org.jerkar.api.depmanagement.JkPopularModules.GUAVA;
import static org.jerkar.api.depmanagement.JkPopularModules.JAVAX_SERVLET_API;
import static org.jerkar.api.depmanagement.JkPopularModules.JUNIT;
import static org.jerkar.api.depmanagement.JkPopularModules.MOCKITO_ALL;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jerkar.api.depmanagement.JkDependencies;
import org.jerkar.tool.JkDoc;
import org.jerkar.tool.JkImport;
import org.jerkar.tool.builtins.javabuild.JkJavaBuild;
/**
* This build demonstrates how to use 3rd party dependencies in your build.
*
* @author Jerome Angibaud
* @fprmatter:off
*/
@JkImport("commons-httpclient:commons-httpclient:3.1")
public class HttpClientTaskBuild extends JkJavaBuild {
@Override
protected JkDependencies dependencies() {
return JkDependencies.builder()
.on(GUAVA, "18.0")
.on(JAVAX_SERVLET_API, "2.5", PROVIDED)
.on(JUNIT, "4.11", TEST)
.on(MOCKITO_ALL, "1.9.5", TEST).build();
}
@JkDoc("Performs some load test using http client")
public void seleniumLoadTest() throws HttpException, IOException {
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod("http://my.url");
client.executeMethod(getMethod);
}
}
|
package water.fvec;
import java.util.Arrays;
import water.*;
import water.parser.ParseTime;
/**
* A NEW single distributed vector column.
*
* The NEW vector has no data, and takes no space. It supports distributed
* parallel writes to it, via calls to append2. Such writes happen in parallel
* and all writes are ordered. Writes *will* be local to the node doing them,
* specifically to allow control over locality. By default, writes will go
* local-homed chunks with no compression; there is a final 'close' to the NEW
* vector which may do compression; the final 'close' will return some other
* Vec type. NEW Vectors do NOT support reads!
*/
public class AppendableVec extends Vec {
public long _espc[];
public static final byte NA = 1;
public static final byte ENUM = 2;
public static final byte NUMBER = 3;
public static final byte TIME = 4;
public static final byte UUID = 5;
public static final byte STRING = 6;
byte [] _chunkTypes;
long _naCnt;
long _enumCnt;
long _strCnt;
final long _timCnt[] = new long[ParseTime.TIME_PARSE.length];
long _totalCnt;
public AppendableVec( Key key ) {
super(key, (long[])null);
_espc = new long[4];
_chunkTypes = new byte[4];
}
// A NewVector chunk was "closed" - completed. Add it's info to the roll-up.
// This call is made in parallel across all node-local created chunks, but is
// not called distributed.
synchronized void closeChunk( NewChunk chk ) {
final int cidx = chk._cidx;
while( cidx >= _espc.length ) {
_espc = Arrays.copyOf(_espc,_espc.length<<1);
_chunkTypes = Arrays.copyOf(_chunkTypes,_chunkTypes.length<<1);
}
_espc[cidx] = chk._len;
_chunkTypes[cidx] = chk.type();
_naCnt += chk.naCnt();
_enumCnt += chk.enumCnt();
_strCnt += chk.strCnt();
for( int i=0; i<_timCnt.length; i++ ) _timCnt[i] += chk._timCnt[i];
_totalCnt += chk._len;
}
// What kind of data did we find? NA's? Strings-only? Floats or Ints?
public boolean shouldBeEnum() {
// We declare column to be string/enum only if it does not have ANY numbers in it.
return _enumCnt > 0 && (_enumCnt + _strCnt + _naCnt) == _totalCnt;
}
// Class 'reduce' call on new vectors; to combine the roll-up info.
// Called single-threaded from the M/R framework.
public void reduce( AppendableVec nv ) {
if( this == nv ) return; // Trivially done
// Combine arrays of elements-per-chunk
long e1[] = nv._espc; // Shorter array of longs?
byte t1[] = nv._chunkTypes;
if( e1.length > _espc.length ) {
e1 = _espc; // Keep the shorter one in e1
t1 = _chunkTypes;
_espc = nv._espc; // Keep longer in the object
_chunkTypes = nv._chunkTypes;
}
for( int i=0; i<e1.length; i++ ){ // Copy non-zero elements over
assert _chunkTypes[i] == 0 || t1[i] == 0;
if( e1[i] != 0 && _espc[i]==0 )
_espc[i] = e1[i];
_chunkTypes[i] |= t1[i];
}
_naCnt += nv._naCnt;
_enumCnt += nv._enumCnt;
_strCnt += nv._strCnt;
water.util.ArrayUtils.add(_timCnt,nv._timCnt);
_totalCnt += nv._totalCnt;
}
// "Close" out a NEW vector - rewrite it to a plain Vec that supports random
// reads, plus computes rows-per-chunk, min/max/mean, etc.
public Vec close(Futures fs) {
// Compute #chunks
int nchunk = _espc.length;
DKV.remove(chunkKey(nchunk),fs); // remove potential trailing key
while( nchunk > 0 && _espc[nchunk-1] == 0 ) {
nchunk
DKV.remove(chunkKey(nchunk),fs); // remove potential trailing key
}
// Histogram chunk types
int[] ctypes = new int[STRING+1];
for( int i = 0; i < nchunk; ++i )
ctypes[_chunkTypes[i]]++;
// Make sure enums are consistent
if( domain() != null ) { // If we have a domain, assume the numbers can be mapped into it
ctypes[ENUM] += ctypes[NUMBER]; ctypes[NUMBER]=0;
}
// Make sure time is consistent
int t = -1;
for( int i=0; i<_timCnt.length; i++ )
if( _timCnt[i] != 0 )
if( t== -1 ) t=i; // common time parse
else t = -2; // inconsistent parse
if( t== -2 ) ctypes[TIME] = 0; // Blow off inconsistent time parse
// Find the dominant non-NA Chunk type.
int idx = 0;
for( int i=0; i<ctypes.length; i++ )
if( i != NA && ctypes[i] > ctypes[idx] )
idx = i;
// Make Chunks other than the dominant type fail out to NAs
for(int i = 0; i < nchunk; ++i)
if(_chunkTypes[i] != idx &&
!(idx==ENUM && _chunkTypes[i]==NUMBER)) // Odd case: numeric chunks being forced/treated as a boolean enum
DKV.put(chunkKey(i), new C0DChunk(Double.NaN, (int)_espc[i]),fs);
byte type;
switch( idx ) {
case ENUM : type = T_ENUM; break;
case NUMBER: type = T_NUM ; break;
case TIME : type = (byte)(T_TIME+t); break;
case UUID : type = T_UUID; break;
case STRING: type = T_STR ; break;
default : type = T_BAD ; break;
}
// Compute elems-per-chunk.
// Roll-up elem counts, so espc[i] is the starting element# of chunk i.
long espc[] = new long[nchunk+1]; // Shorter array
long x=0; // Total row count so far
for( int i=0; i<nchunk; i++ ) {
espc[i] = x; // Start elem# for chunk i
x += _espc[i]; // Raise total elem count
}
espc[nchunk]=x; // Total element count in last
// Replacement plain Vec for AppendableVec.
Vec vec = new Vec(_key, espc, domain(), type);
DKV.put(_key,vec,fs); // Inject the header
return vec;
}
// Default read/write behavior for AppendableVecs
@Override protected boolean readable() { return false; }
@Override protected boolean writable() { return true ; }
@Override public NewChunk chunkForChunkIdx(int cidx) { return new NewChunk(this,cidx); }
// None of these are supposed to be called while building the new vector
@Override protected Value chunkIdx( int cidx ) { throw H2O.fail(); }
@Override public long length() { throw H2O.fail(); }
@Override public int nChunks() { throw H2O.fail(); }
@Override int elem2ChunkIdx( long i ) { throw H2O.fail(); }
@Override protected long chunk2StartElem( int cidx ) { throw H2O.fail(); }
@Override public long byteSize() { return 0; }
@Override public String toString() { return "[AppendableVec, unknown size]"; }
}
|
package water.parser;
import water.AutoBuffer;
import water.H2O;
import water.Iced;
import water.util.Log;
import water.nbhm.NonBlockingHashMap;
import water.util.PrettyPrint;
import java.util.concurrent.atomic.AtomicInteger;
/** Class for tracking categorical (enum) columns.
*
* Basically a wrapper around non blocking hash map.
* In the first pass, we just collect set of unique strings per column
* (if there are less than MAX_CATEGORICAL_COUNT unique elements).
*
* After pass1, the keys are sorted and indexed alphabetically.
* In the second pass, map is used only for lookup and never updated.
*
* Categorical objects are shared among threads on the local nodes!
*
* @author tomasnykodym
*
*/
public final class Categorical extends Iced {
public static final int MAX_CATEGORICAL_COUNT = 10000000;
AtomicInteger _id = new AtomicInteger();
int _maxId = -1;
volatile NonBlockingHashMap<ValueString, Integer> _map;
boolean maxEnumExceeded = false;
Categorical() { _map = new NonBlockingHashMap<>(); }
/** Add key to this map (treated as hash set in this case). */
int addKey(ValueString str) {
// _map is shared and be cast to null (if enum is killed) -> grab local copy
NonBlockingHashMap<ValueString, Integer> m = _map;
if( m == null ) return Integer.MAX_VALUE; // Nuked already
Integer res = m.get(str);
if( res != null ) return res; // Recorded already
assert str.length() < 65535; // Length limit so 65535 can be used as a sentinel
int newVal = _id.incrementAndGet();
res = m.putIfAbsent(new ValueString(str), newVal);
if( res != null ) return res;
if( m.size() > MAX_CATEGORICAL_COUNT) maxEnumExceeded = true;
return newVal;
}
final boolean containsKey(ValueString key){ return _map.containsKey(key); }
@Override public String toString() {
return "{"+_map+" }";
}
int getTokenId( ValueString str ) { return _map.get(str); }
int maxId() { return _maxId == -1 ? _id.get() : _maxId; }
int size() { return _map.size(); }
boolean isMapFull() { return maxEnumExceeded; }
ValueString [] getColumnDomain() {
return _map.keySet().toArray(new ValueString[_map.size()]);
}
public static final int MAX_EXAMPLES = 10;
public void convertToUTF8(int col){
int hexConvCnt = 0;
ValueString[] vs = _map.keySet().toArray(new ValueString[_map.size()]);
StringBuilder hexSB = new StringBuilder();
for (int i =0; i < vs.length; i++) {
String s = vs[i].toString();
if (!vs[i].equals(s)) {
if (s.contains("\uFFFD")) { // make weird chars into hex
s = vs[i].bytesToString();
if (hexConvCnt++ < MAX_EXAMPLES) hexSB.append(s +", ");
if (hexConvCnt == MAX_EXAMPLES) hexSB.append("...");
}
int val = _map.get(vs[i]);
_map.remove(vs[i]);
vs[i] = new ValueString(s);
_map.put(vs[i], val);
}
}
if (hexConvCnt > 0) Log.info("Found categoricals with non-UTF-8 characters in the "
+ PrettyPrint.withOrdinalIndicator(col)
+ " column. Converting unrecognized characters into hex: "
+ hexSB.toString());
}
// Since this is a *concurrent* hashtable, writing it whilst its being
// updated is tricky. If the table is NOT being updated, then all is written
// as expected. If the table IS being updated we only promise to write the
// Keys that existed at the time the table write began. If elements are
// being deleted, they may be written anyways. If the Values are changing, a
// random Value is written.
@Override public AutoBuffer write_impl( AutoBuffer ab ) {
if( _map == null ) return ab.put1(1); // Killed map marker
ab.put1(0); // Not killed
ab.put4(maxId());
for( ValueString key : _map.keySet() )
ab.put2((char)key.length()).putA1(key.getBuffer(),key.length()).put4(_map.get(key));
return ab.put2((char)65535); // End of map marker
}
@Override public Categorical read_impl( AutoBuffer ab ) {
assert _map == null || _map.size()==0;
_map = null;
if( ab.get1() == 1 ) return this; // Killed?
_maxId = ab.get4();
_map = new NonBlockingHashMap<>();
int len;
while( (len = ab.get2()) != 65535 ) // Read until end-of-map marker
_map.put(new ValueString(ab.getA1(len)),ab.get4());
return this;
}
@Override public AutoBuffer writeJSON_impl( AutoBuffer ab ) {
throw H2O.unimpl();
}
@Override public Categorical readJSON_impl( AutoBuffer ab ) { throw H2O.unimpl(); }
}
|
package com.worth.ifs.project;
import com.worth.ifs.application.resource.ApplicationResource;
import com.worth.ifs.application.service.ApplicationService;
import com.worth.ifs.application.service.CompetitionService;
import com.worth.ifs.competition.resource.CompetitionResource;
import com.worth.ifs.project.resource.MonitoringOfficerResource;
import com.worth.ifs.project.resource.ProjectResource;
import com.worth.ifs.project.viewmodel.ProjectSetupStatusViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Optional;
/**
* This controller will handle all requests that are related to a project.
*/
@Controller
@RequestMapping("/project")
public class ProjectSetupStatusController {
@Autowired
private ProjectService projectService;
@Autowired
private ApplicationService applicationService;
@Autowired
private CompetitionService competitionService;
@RequestMapping(value = "/{projectId}", method = RequestMethod.GET)
public String projectOverview(Model model, @PathVariable("projectId") final Long projectId) {
model.addAttribute("model", getProjectSetupStatusViewModel(projectId));
return "project/overview";
}
private ProjectSetupStatusViewModel getProjectSetupStatusViewModel(Long projectId) {
ProjectResource project = projectService.getById(projectId);
ApplicationResource applicationResource = applicationService.getById(project.getApplication());
CompetitionResource competition = competitionService.getById(applicationResource.getCompetition());
Optional<MonitoringOfficerResource> monitoringOfficer = projectService.getMonitoringOfficerForProject(projectId);
return new ProjectSetupStatusViewModel(project, competition, monitoringOfficer);
}
}
|
package yuku.alkitab.base;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcEvent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ShareCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.view.ActionMode;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import yuku.afw.V;
import yuku.afw.storage.Preferences;
import yuku.afw.widget.EasyAdapter;
import yuku.alkitab.base.ac.AboutActivity;
import yuku.alkitab.base.ac.BookmarkActivity;
import yuku.alkitab.base.ac.DevotionActivity;
import yuku.alkitab.base.ac.GotoActivity;
import yuku.alkitab.base.ac.HelpActivity;
import yuku.alkitab.base.ac.ReadingPlanActivity;
import yuku.alkitab.base.ac.Search2Activity;
import yuku.alkitab.base.ac.SettingsActivity;
import yuku.alkitab.base.ac.ShareActivity;
import yuku.alkitab.base.ac.SongViewActivity;
import yuku.alkitab.base.ac.VersionsActivity;
import yuku.alkitab.base.ac.VersionsActivity.MVersion;
import yuku.alkitab.base.ac.VersionsActivity.MVersionInternal;
import yuku.alkitab.base.ac.VersionsActivity.MVersionPreset;
import yuku.alkitab.base.ac.VersionsActivity.MVersionYes;
import yuku.alkitab.base.ac.base.BaseActivity;
import yuku.alkitab.base.config.AppConfig;
import yuku.alkitab.base.dialog.ProgressMarkDialog;
import yuku.alkitab.base.dialog.TypeBookmarkDialog;
import yuku.alkitab.base.dialog.TypeHighlightDialog;
import yuku.alkitab.base.dialog.TypeNoteDialog;
import yuku.alkitab.base.dialog.XrefDialog;
import yuku.alkitab.base.storage.Prefkey;
import yuku.alkitab.base.util.BackupManager;
import yuku.alkitab.base.util.History;
import yuku.alkitab.base.util.Jumper;
import yuku.alkitab.base.util.LidToAri;
import yuku.alkitab.base.util.OsisBookNames;
import yuku.alkitab.base.util.Search2Engine.Query;
import yuku.alkitab.base.util.Sqlitil;
import yuku.alkitab.base.widget.AttributeView;
import yuku.alkitab.base.widget.CallbackSpan;
import yuku.alkitab.base.widget.Floater;
import yuku.alkitab.base.widget.FormattedTextRenderer;
import yuku.alkitab.base.widget.GotoButton;
import yuku.alkitab.base.widget.LabeledSplitHandleButton;
import yuku.alkitab.base.widget.ReadingPlanFloatMenu;
import yuku.alkitab.base.widget.SplitHandleButton;
import yuku.alkitab.base.widget.TextAppearancePanel;
import yuku.alkitab.base.widget.TouchInterceptLinearLayout;
import yuku.alkitab.base.widget.VerseInlineLinkSpan;
import yuku.alkitab.base.widget.VerseRenderer;
import yuku.alkitab.base.widget.VersesView;
import yuku.alkitab.base.widget.VersesView.PressResult;
import yuku.alkitab.debug.R;
import yuku.alkitab.model.Book;
import yuku.alkitab.model.FootnoteEntry;
import yuku.alkitab.model.PericopeBlock;
import yuku.alkitab.model.ProgressMark;
import yuku.alkitab.model.SingleChapterVerses;
import yuku.alkitab.model.Version;
import yuku.alkitab.util.Ari;
import yuku.alkitab.util.IntArrayList;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
public class IsiActivity extends BaseActivity implements XrefDialog.XrefDialogListener, ProgressMarkDialog.ProgressMarkDialogListener {
public static final String TAG = IsiActivity.class.getSimpleName();
// The followings are for instant_pref
private static final String PREFKEY_lastBookId = "kitabTerakhir"; //$NON-NLS-1$
private static final String PREFKEY_lastChapter = "pasalTerakhir"; //$NON-NLS-1$
private static final String PREFKEY_lastVerse = "ayatTerakhir"; //$NON-NLS-1$
private static final String PREFKEY_lastVersionId = "edisiTerakhir"; //$NON-NLS-1$
private static final String PREFKEY_lastSplitVersionId = "lastSplitVersionId"; //$NON-NLS-1$
private static final String PREFKEY_devotion_name = "renungan_nama"; //$NON-NLS-1$
private static final int REQCODE_goto = 1;
private static final int REQCODE_bookmark = 2;
private static final int REQCODE_devotion = 3;
private static final int REQCODE_settings = 4;
private static final int REQCODE_version = 5;
private static final int REQCODE_search = 6;
private static final int REQCODE_share = 7;
private static final int REQCODE_textAppearanceGetFonts = 9;
private static final int REQCODE_textAppearanceCustomColors = 10;
private static final int REQCODE_readingPlan = 11;
private static final String EXTRA_verseUrl = "verseUrl"; //$NON-NLS-1$
private boolean uncheckVersesWhenActionModeDestroyed = true;
private GotoButton.FloaterDragListener bGoto_floaterDrag = new GotoButton.FloaterDragListener() {
final int[] floaterLocationOnScreen = {0, 0};
@Override
public void onFloaterDragStart(final float screenX, final float screenY) {
floater.setVisibility(View.VISIBLE);
floater.onDragStart(S.activeVersion);
}
@Override
public void onFloaterDragMove(final float screenX, final float screenY) {
floater.getLocationOnScreen(floaterLocationOnScreen);
floater.onDragMove(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1]);
}
@Override
public void onFloaterDragComplete(final float screenX, final float screenY) {
floater.setVisibility(View.GONE);
floater.onDragComplete(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1]);
}
};
private Floater.Listener floater_listener = new Floater.Listener() {
@Override
public void onSelectComplete(final int ari) {
jumpToAri(ari);
history.add(ari);
}
};
private View.OnTouchListener splitRoot_interceptTouch = new View.OnTouchListener() {
long lastDownTime;
float lastDownX;
float lastDownY;
long lastUpTime;
float lastUpX;
float lastUpY;
int maxDoubleTapDelay = ViewConfiguration.getDoubleTapTimeout();
int maxDoubleTapDistance = -1;
final int[] locationOnScreen = new int[2];
float distSquared(float dx, float dy) {
return dx * dx + dy * dy;
}
@Override
public boolean onTouch(final View v, final MotionEvent event) {
final int action = MotionEventCompat.getActionMasked(event);
// lazy
if (maxDoubleTapDistance == -1) {
maxDoubleTapDistance = ViewConfiguration.get(IsiActivity.this).getScaledDoubleTapSlop();
}
v.getLocationOnScreen(locationOnScreen);
if (action == MotionEvent.ACTION_DOWN) { // check for double click
if (lastUpTime - lastDownTime < maxDoubleTapDelay) { // first tap down to up must be fast enough
long thisDownTime = event.getEventTime();
if (thisDownTime - lastUpTime < maxDoubleTapDelay) { // second tap must be fast enough
if (distSquared(lastUpX - lastDownX, lastUpY - lastDownY) < maxDoubleTapDistance) { // first tap down to up must be within distance
float thisDownX = event.getX() + locationOnScreen[0];
float thisDownY = event.getY() + locationOnScreen[1];
if (distSquared(thisDownX - lastUpX, thisDownY - lastUpY) < maxDoubleTapDistance) { // second tap must be fast enough
// double tap success!
setFullScreen(!fullScreen);
return true;
}
}
}
}
}
if (action == MotionEvent.ACTION_DOWN) {
lastDownTime = event.getEventTime();
lastDownX = event.getX() + locationOnScreen[0];
lastDownY = event.getY() + locationOnScreen[1];
} else if (action == MotionEvent.ACTION_UP) {
lastUpTime = event.getEventTime();
lastUpX = event.getX() + locationOnScreen[0];
lastUpY = event.getY() + locationOnScreen[1];
}
return false;
}
};
@Override
public void onProgressMarkSelected(final int ari) {
jumpToAri(ari);
history.add(ari);
}
@Override
public void onProgressMarkDeleted(final int ari) {
reloadVerse();
}
class FullScreenController {
void hidePermanently() {
getSupportActionBar().hide();
panelNavigation.setVisibility(View.GONE);
}
void showPermanently() {
getSupportActionBar().show();
panelNavigation.setVisibility(View.VISIBLE);
}
}
FrameLayout overlayContainer;
View root;
VersesView lsText;
VersesView lsSplit1;
TextView tSplitEmpty;
TouchInterceptLinearLayout splitRoot;
View splitHandle;
LabeledSplitHandleButton splitHandleButton;
FrameLayout panelNavigation;
GotoButton bGoto;
ImageButton bLeft;
ImageButton bRight;
Floater floater;
ReadingPlanFloatMenu readingPlanFloatMenu;
Book activeBook;
int chapter_1 = 0;
SharedPreferences instant_pref;
boolean fullScreen;
FullScreenController fullScreenController = new FullScreenController();
Toast fullScreenDismissHint;
History history;
NfcAdapter nfcAdapter;
ActionMode actionMode;
TextAppearancePanel textAppearancePanel;
//# state storage for search2
Query search2_query = null;
IntArrayList search2_results = null;
int search2_selectedPosition = -1;
// temporary states
Boolean hasEsvsbAsal;
Version activeSplitVersion;
String activeSplitVersionId;
CallbackSpan.OnClickListener parallelListener = new CallbackSpan.OnClickListener() {
@Override public void onClick(View widget, Object data) {
if (data instanceof String) {
final int ari = jumpTo((String) data);
if (ari != 0) {
history.add(ari);
}
} else if (data instanceof Integer) {
final int ari = (Integer) data;
jumpToAri(ari);
history.add(ari);
}
}
};
public static Intent createIntent(int ari) {
Intent res = new Intent(App.context, IsiActivity.class);
res.setAction("yuku.alkitab.action.VIEW");
res.putExtra("ari", ari);
return res;
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, false);
setContentView(R.layout.activity_isi);
overlayContainer = V.get(this, R.id.overlayContainer);
root = V.get(this, R.id.root);
lsText = V.get(this, R.id.lsSplit0);
lsSplit1 = V.get(this, R.id.lsSplit1);
tSplitEmpty = V.get(this, R.id.tSplitEmpty);
splitRoot = V.get(this, R.id.splitRoot);
splitHandle = V.get(this, R.id.splitHandle);
splitHandleButton = V.get(this, R.id.splitHandleButton);
panelNavigation = V.get(this, R.id.panelNavigation);
bGoto = V.get(this, R.id.bGoto);
bLeft = V.get(this, R.id.bLeft);
bRight = V.get(this, R.id.bRight);
floater = V.get(this, R.id.floater);
readingPlanFloatMenu = V.get(this, R.id.readingPlanFloatMenu);
applyPreferences(false);
splitRoot.setInterceptTouchEventListener(splitRoot_interceptTouch);
bGoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { bGoto_click(); }
});
bGoto.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
bGoto_longClick();
return true;
}
});
bGoto.setFloaterDragListener(bGoto_floaterDrag);
bLeft.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { bLeft_click(); }
});
bRight.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { bRight_click(); }
});
floater.setListener(floater_listener);
lsText.setOnKeyListener(new View.OnKeyListener() {
@Override public boolean onKey(View v, int keyCode, KeyEvent event) {
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
return press(keyCode);
} else if (action == KeyEvent.ACTION_MULTIPLE) {
return press(keyCode);
}
return false;
}
});
// listeners
lsText.setParallelListener(parallelListener);
lsText.setAttributeListener(attributeListener);
lsText.setInlineLinkSpanFactory(new VerseInlineLinkSpanFactory(lsText));
lsText.setSelectedVersesListener(lsText_selectedVerses);
lsText.setOnVerseScrollListener(lsText_verseScroll);
lsText.setOnVerseScrollStateChangeListener(verseScrollState);
// additional setup for split1
lsSplit1.setVerseSelectionMode(VersesView.VerseSelectionMode.multiple);
lsSplit1.setEmptyView(tSplitEmpty);
lsSplit1.setParallelListener(parallelListener);
lsSplit1.setAttributeListener(attributeListener);
lsSplit1.setInlineLinkSpanFactory(new VerseInlineLinkSpanFactory(lsSplit1));
lsSplit1.setSelectedVersesListener(lsSplit1_selectedVerses);
lsSplit1.setOnVerseScrollListener(lsSplit1_verseScroll);
lsSplit1.setOnVerseScrollStateChangeListener(verseScrollState);
// for splitting
splitHandleButton.setListener(splitHandleButton_listener);
history = History.getInstance();
// configure devotion
instant_pref = App.getInstantPreferences();
{
String devotion_name = instant_pref.getString(PREFKEY_devotion_name, null);
if (devotion_name != null) {
for (String nama: DevotionActivity.AVAILABLE_NAMES) {
if (devotion_name.equals(nama)) {
DevotionActivity.Temporaries.devotion_name = devotion_name;
}
}
}
}
// restore the last (version; book; chapter and verse).
final int lastBookId = instant_pref.getInt(PREFKEY_lastBookId, 0);
final int lastChapter = instant_pref.getInt(PREFKEY_lastChapter, 0);
final int lastVerse = instant_pref.getInt(PREFKEY_lastVerse, 0);
final String lastVersionId = instant_pref.getString(PREFKEY_lastVersionId, null);
Log.d(TAG, "Going to the last: versionId=" + lastVersionId + " bookId=" + lastBookId + " chapter=" + lastChapter + " verse=" + lastVerse); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
loadLastVersion(lastVersionId, false);
{ // load book
Book book = S.activeVersion.getBook(lastBookId);
if (book != null) {
this.activeBook = book;
} else { // can't load last book or bookId 0
this.activeBook = S.activeVersion.getFirstBook();
}
}
// load chapter and verse
display(lastChapter, lastVerse);
{ // load last split version. This must be after load book, chapter, and verse.
final String lastSplitVersionId = instant_pref.getString(PREFKEY_lastSplitVersionId, null);
if (lastSplitVersionId != null) {
loadLastVersion(lastSplitVersionId, true);
}
}
if (Build.VERSION.SDK_INT >= 14) {
initNfcIfAvailable();
}
if (S.getDb().countAllBookmarks() != 0) {
BackupManager.startAutoBackup();
}
processIntent(getIntent(), "onCreate");
}
@Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent, "onNewIntent");
}
private void processIntent(Intent intent, String via) {
Log.d(TAG, "Got intent via " + via);
Log.d(TAG, " action: " + intent.getAction());
Log.d(TAG, " data uri: " + intent.getData());
Log.d(TAG, " component: " + intent.getComponent());
Log.d(TAG, " flags: 0x" + Integer.toHexString(intent.getFlags()));
Log.d(TAG, " mime: " + intent.getType());
Bundle extras = intent.getExtras();
Log.d(TAG, " extras: " + (extras == null? "null": extras.size()));
if (extras != null) {
for (String key: extras.keySet()) {
Log.d(TAG, " " + key + " = " + extras.get(key));
}
}
if (Build.VERSION.SDK_INT >= 14) {
checkAndProcessBeamIntent(intent);
}
checkAndProcessViewIntent(intent);
}
/** did we get here from VIEW intent? */
private void checkAndProcessViewIntent(Intent intent) {
if (!U.equals(intent.getAction(), "yuku.alkitab.action.VIEW")) return;
if (intent.hasExtra("ari")) {
int ari = intent.getIntExtra("ari", 0);
if (ari != 0) {
jumpToAri(ari);
history.add(ari);
} else {
new AlertDialog.Builder(this)
.setMessage("Invalid ari: " + ari)
.setPositiveButton(R.string.ok, null)
.show();
}
} else if (intent.hasExtra("lid")) {
int lid = intent.getIntExtra("lid", 0);
int ari = LidToAri.lidToAri(lid);
if (ari != 0) {
jumpToAri(ari);
history.add(ari);
} else {
new AlertDialog.Builder(this)
.setMessage("Invalid lid: " + lid)
.setPositiveButton(R.string.ok, null)
.show();
}
}
}
@TargetApi(14) private void initNfcIfAvailable() {
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
if (nfcAdapter != null) {
nfcAdapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {
@Override public NdefMessage createNdefMessage(NfcEvent event) {
JSONObject obj = new JSONObject();
try {
obj.put("ari", Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, lsText.getVerseBasedOnScroll())); //$NON-NLS-1$
} catch (JSONException e) { // won't happen
}
byte[] payload = obj.toString().getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "application/vnd.yuku.alkitab.nfc.beam".getBytes(), new byte[0], payload); //$NON-NLS-1$
return new NdefMessage(new NdefRecord[] {
record,
NdefRecord.createApplicationRecord(getPackageName()),
});
}
}, this);
}
}
@Override protected void onPause() {
super.onPause();
if (Build.VERSION.SDK_INT >= 14) {
disableNfcForegroundDispatchIfAvailable();
}
}
@TargetApi(14) private void disableNfcForegroundDispatchIfAvailable() {
if (nfcAdapter != null) nfcAdapter.disableForegroundDispatch(this);
}
@Override protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= 14) {
enableNfcForegroundDispatchIfAvailable();
}
}
@TargetApi(14) private void enableNfcForegroundDispatchIfAvailable() {
if (nfcAdapter != null) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, IsiActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("application/vnd.yuku.alkitab.nfc.beam"); //$NON-NLS-1$
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail mime type", e); //$NON-NLS-1$
}
IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
}
}
@TargetApi(14) private void checkAndProcessBeamIntent(Intent intent) {
String action = intent.getAction();
if (U.equals(action, NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
if (rawMsgs != null && rawMsgs.length > 0) {
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
NdefRecord[] records = msg.getRecords();
if (records != null && records.length > 0) {
String json = new String(records[0].getPayload());
try {
JSONObject obj = new JSONObject(json);
int ari = obj.optInt("ari", -1); //$NON-NLS-1$
if (ari != -1) {
jumpToAri(ari);
history.add(ari);
}
} catch (JSONException e) {
Log.e(TAG, "Malformed json from nfc", e); //$NON-NLS-1$
}
}
}
}
}
void loadLastVersion(String versionId, boolean isSplit) {
final AppConfig c = AppConfig.get();
if (versionId == null || MVersionInternal.getVersionInternalId().equals(versionId)) {
// we are now already on internal
if (!isSplit) {
splitHandleButton.setLabel1("\u25b2 " + c.internalShortName);
} else {
if (loadSplitVersion(new MVersionInternal())) {
openSplitDisplay();
displaySplitFollowingMaster();
splitHandleButton.setLabel2(c.internalShortName + " \u25bc");
}
}
return;
}
// try preset versions first
for (MVersionPreset preset: c.presets) { // 2. preset
if (preset.getVersionId().equals(versionId)) {
if (preset.hasDataFile()) {
if (!isSplit) {
if (loadVersion(preset, false)) return;
} else {
if (loadSplitVersion(preset)) {
openSplitDisplay();
displaySplitFollowingMaster();
return;
}
}
} else {
return; // this is the one that should have been chosen, but the data file is not available, so let's fallback.
}
}
}
// still no match, let's look at yes versions
for (MVersionYes yes: S.getDb().listAllVersions()) {
if (yes.getVersionId().equals(versionId)) {
if (yes.hasDataFile()) {
if (!isSplit) {
if (loadVersion(yes, false)) return;
} else {
if (loadSplitVersion(yes)) {
openSplitDisplay();
displaySplitFollowingMaster();
return;
}
}
} else {
return; // this is the one that should have been chosen, but the data file is not available, so let's fallback.
}
}
}
}
boolean loadVersion(final MVersion mv, boolean display) {
try {
Version version = mv.getVersion();
if (version != null) {
if (this.activeBook != null) { // we already have some other version loaded, so make the new version open the same book
int bookId = this.activeBook.bookId;
Book book = version.getBook(bookId);
if (book != null) { // we load the new book succesfully
this.activeBook = book;
} else { // too bad, this book was not found, get any book
this.activeBook = version.getFirstBook();
}
}
S.activeVersion = version;
S.activeVersionId = mv.getVersionId();
splitHandleButton.setLabel1("\u25b2 " + getSplitHandleVersionName(mv, version));
if (display) {
display(chapter_1, lsText.getVerseBasedOnScroll(), false);
}
return true;
} else {
throw new RuntimeException(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId()));
}
} catch (Throwable e) { // so we don't crash on the beginning of the app
Log.e(TAG, "Error opening main version", e);
new AlertDialog.Builder(IsiActivity.this)
.setMessage(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId()))
.setPositiveButton(R.string.ok, null)
.show();
return false;
}
}
boolean loadSplitVersion(final MVersion mv) {
try {
Version version = mv.getVersion();
if (version != null) {
activeSplitVersion = version;
activeSplitVersionId = mv.getVersionId();
splitHandleButton.setLabel2(getSplitHandleVersionName(mv, version) + " \u25bc");
return true;
} else {
throw new RuntimeException(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId()));
}
} catch (Throwable e) { // so we don't crash on the beginning of the app
Log.e(TAG, "Error opening split version", e);
new AlertDialog.Builder(IsiActivity.this)
.setMessage(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId()))
.setPositiveButton(R.string.ok, null)
.show();
return false;
}
}
String getSplitHandleVersionName(MVersion mv, Version version) {
String shortName = version.getShortName();
if (shortName != null) {
return shortName;
} else {
// try to get it from the model
if (mv.shortName != null) {
return mv.shortName;
}
return version.getLongName(); // this will not be null
}
}
boolean press(int keyCode) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
bLeft_click();
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
bRight_click();
return true;
}
PressResult pressResult = lsText.press(keyCode);
switch (pressResult) {
case left:
bLeft_click();
return true;
case right:
bRight_click();
return true;
case consumed:
return true;
default:
return false;
}
}
/**
* Jump to a given verse reference in string format.
* @return ari of the parsed reference
*/
int jumpTo(String reference) {
if (reference.trim().length() == 0) {
return 0;
}
Log.d(TAG, "going to jump to " + reference); //$NON-NLS-1$
Jumper jumper = new Jumper(reference);
if (! jumper.getParseSucceeded()) {
Toast.makeText(this, getString(R.string.alamat_tidak_sah_alamat, reference), Toast.LENGTH_SHORT).show();
return 0;
}
int bookId = jumper.getBookId(S.activeVersion.getConsecutiveBooks());
Book selected;
if (bookId != -1) {
Book book = S.activeVersion.getBook(bookId);
if (book != null) {
selected = book;
} else {
// not avail, just fallback
selected = this.activeBook;
}
} else {
selected = this.activeBook;
}
// set book
this.activeBook = selected;
int chapter = jumper.getChapter();
int verse = jumper.getVerse();
int ari_cv;
if (chapter == -1 && verse == -1) {
ari_cv = display(1, 1);
} else {
ari_cv = display(chapter, verse);
}
return Ari.encode(selected.bookId, ari_cv);
}
/**
* Jump to a given ari
*/
void jumpToAri(int ari) {
if (ari == 0) return;
Log.d(TAG, "will jump to ari 0x" + Integer.toHexString(ari)); //$NON-NLS-1$
int bookId = Ari.toBook(ari);
Book book = S.activeVersion.getBook(bookId);
if (book != null) {
this.activeBook = book;
} else {
Log.w(TAG, "bookId=" + bookId + " not found for ari=" + ari); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
display(Ari.toChapter(ari), Ari.toVerse(ari));
}
private CharSequence referenceFromSelectedVerses(IntArrayList selectedVerses, Book book) {
if (selectedVerses.size() == 0) {
// should not be possible. So we don't do anything.
return book.reference(this.chapter_1);
} else if (selectedVerses.size() == 1) {
return book.reference(this.chapter_1, selectedVerses.get(0));
} else {
return book.reference(this.chapter_1, selectedVerses);
}
}
CharSequence prepareTextForCopyShare(IntArrayList selectedVerses_1, CharSequence reference, boolean isSplitVersion) {
StringBuilder res = new StringBuilder();
res.append(reference);
if (Preferences.getBoolean(getString(R.string.pref_copyWithVerseNumbers_key), false) && selectedVerses_1.size() > 1) {
res.append('\n');
// append each selected verse with verse number prepended
for (int i = 0; i < selectedVerses_1.size(); i++) {
int verse_1 = selectedVerses_1.get(i);
res.append(verse_1);
res.append(' ');
if (isSplitVersion) {
res.append(U.removeSpecialCodes(lsSplit1.getVerse(verse_1)));
} else {
res.append(U.removeSpecialCodes(lsText.getVerse(verse_1)));
}
res.append('\n');
}
} else {
res.append(" "); //$NON-NLS-1$
// append each selected verse without verse number prepended
for (int i = 0; i < selectedVerses_1.size(); i++) {
int verse_1 = selectedVerses_1.get(i);
if (i != 0) res.append('\n');
if (isSplitVersion) {
res.append(U.removeSpecialCodes(lsSplit1.getVerse(verse_1)));
} else {
res.append(U.removeSpecialCodes(lsText.getVerse(verse_1)));
}
}
}
return res;
}
private void applyPreferences(boolean languageToo) {
// appliance of background color
{
root.setBackgroundColor(S.applied.backgroundColor);
lsText.setCacheColorHint(S.applied.backgroundColor);
lsSplit1.setCacheColorHint(S.applied.backgroundColor);
}
if (languageToo) {
App.updateConfigurationWithPreferencesLocale();
}
// necessary
lsText.invalidateViews();
lsSplit1.invalidateViews();
}
@Override protected void onStop() {
super.onStop();
final Editor editor = instant_pref.edit();
editor.putInt(PREFKEY_lastBookId, this.activeBook.bookId);
editor.putInt(PREFKEY_lastChapter, chapter_1);
editor.putInt(PREFKEY_lastVerse, lsText.getVerseBasedOnScroll());
editor.putString(PREFKEY_devotion_name, DevotionActivity.Temporaries.devotion_name);
editor.putString(PREFKEY_lastVersionId, S.activeVersionId);
if (activeSplitVersion == null) {
editor.putString(PREFKEY_lastSplitVersionId, null);
} else {
editor.putString(PREFKEY_lastSplitVersionId, activeSplitVersionId);
}
if (Build.VERSION.SDK_INT >= 9) {
editor.apply();
} else {
editor.commit();
}
history.save();
lsText.setKeepScreenOn(false);
}
@Override protected void onStart() {
super.onStart();
if (Preferences.getBoolean(getString(R.string.pref_keepScreenOn_key), getResources().getBoolean(R.bool.pref_keepScreenOn_default))) {
lsText.setKeepScreenOn(true);
}
}
@Override public void onBackPressed() {
if (fullScreen) {
setFullScreen(false);
} else if (textAppearancePanel != null) {
textAppearancePanel.hide();
textAppearancePanel = null;
} else {
super.onBackPressed();
}
}
void bGoto_click() {
startActivityForResult(GotoActivity.createIntent(this.activeBook.bookId, this.chapter_1, lsText.getVerseBasedOnScroll()), REQCODE_goto);
}
void bGoto_longClick() {
if (history.getSize() > 0) {
new AlertDialog.Builder(this)
.setAdapter(historyAdapter, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
int ari = history.getAri(which);
jumpToAri(ari);
history.add(ari);
Preferences.setBoolean(Prefkey.history_button_understood, true);
}
})
.setNegativeButton(R.string.cancel, null)
.show();
} else {
Toast.makeText(this, R.string.recentverses_not_available, Toast.LENGTH_SHORT).show();
}
}
private ListAdapter historyAdapter = new EasyAdapter() {
private final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(App.context);
private final java.text.DateFormat mediumDateFormat = DateFormat.getMediumDateFormat(App.context);
@Override
public View newView(final int position, final ViewGroup parent) {
return getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
}
@Override
public void bindView(final View view, final int position, final ViewGroup parent) {
TextView textView = (TextView) view;
int ari = history.getAri(position);
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(S.activeVersion.reference(ari));
sb.append(" ");
int sb_len = sb.length();
sb.append(formatTimestamp(history.getTimestamp(position)));
sb.setSpan(new ForegroundColorSpan(0xff666666), sb_len, sb.length(), 0);
sb.setSpan(new RelativeSizeSpan(0.7f), sb_len, sb.length(), 0);
textView.setText(sb);
}
private CharSequence formatTimestamp(final long timestamp) {
{
long now = System.currentTimeMillis();
long delta = now - timestamp;
if (delta <= 200000) {
return getString(R.string.recentverses_just_now);
} else if (delta <= 3600000) {
return getString(R.string.recentverses_min_plural_ago, Math.round(delta / 60000.0));
}
}
{
Calendar now = GregorianCalendar.getInstance();
Calendar that = GregorianCalendar.getInstance();
that.setTimeInMillis(timestamp);
if (now.get(Calendar.YEAR) == that.get(Calendar.YEAR)) {
if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR)) {
return getString(R.string.recentverses_today_time, timeFormat.format(that.getTime()));
} else if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR) + 1) {
return getString(R.string.recentverses_yesterday_time, timeFormat.format(that.getTime()));
}
}
return mediumDateFormat.format(that.getTime());
}
}
@Override
public int getCount() {
return history.getSize();
}
};
public void buildMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_isi, menu);
AppConfig c = AppConfig.get();
//# build config
menu.findItem(R.id.menuDevotion).setVisible(c.menuDevotion);
menu.findItem(R.id.menuVersions).setVisible(c.menuVersions);
menu.findItem(R.id.menuHelp).setVisible(c.menuHelp);
menu.findItem(R.id.menuDonation).setVisible(c.menuDonation);
menu.findItem(R.id.menuSongs).setVisible(c.menuSongs);
// checkable menu items
menu.findItem(R.id.menuNightMode).setChecked(Preferences.getBoolean(Prefkey.is_night_mode, false));
menu.findItem(R.id.menuFullScreen).setChecked(fullScreen);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
buildMenu(menu);
return true;
}
@Override public boolean onPrepareOptionsMenu(Menu menu) {
if (menu != null) {
buildMenu(menu);
}
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuBookmark:
startActivityForResult(new Intent(this, BookmarkActivity.class), REQCODE_bookmark);
return true;
case R.id.menuListProgressMark:
openProgressMarkDialog();
return true;
case R.id.menuSearch:
menuSearch_click();
return true;
case R.id.menuVersions:
openVersionsDialog();
return true;
case R.id.menuSplitVersion:
openSplitVersionsDialog();
return true;
case R.id.menuDevotion:
startActivityForResult(new Intent(this, DevotionActivity.class), REQCODE_devotion);
return true;
case R.id.menuSongs:
startActivity(SongViewActivity.createIntent());
return true;
case R.id.menuReadingPlan:
startActivityForResult(new Intent(this, ReadingPlanActivity.class), REQCODE_readingPlan);
return true;
case R.id.menuAbout:
startActivity(new Intent(this, AboutActivity.class));
return true;
case R.id.menuFullScreen:
setFullScreen(!item.isChecked());
return true;
case R.id.menuTextAppearance:
setShowTextAppearancePanel(textAppearancePanel == null);
return true;
case R.id.menuNightMode: {
setNightMode(! Preferences.getBoolean(Prefkey.is_night_mode, false));
} return true;
case R.id.menuSettings:
startActivityForResult(new Intent(this, SettingsActivity.class), REQCODE_settings);
return true;
case R.id.menuHelp: {
String page;
if (U.equals("in", getResources().getConfiguration().locale.getLanguage())) {
page = "help/html-in/index.html";
} else {
page = "help/html-en/index.html";
}
startActivity(HelpActivity.createIntent(page, false, null, null));
} return true;
case R.id.menuSendMessage: {
String page;
if (U.equals("in", getResources().getConfiguration().locale.getLanguage())) {
page = "help/html-in/faq.html";
} else {
page = "help/html-en/faq.html";
}
startActivity(HelpActivity.createIntent(page, true, getString(R.string.read_faq_before_suggest), new Intent(yuku.afw.App.context, com.example.android.wizardpager.MainActivity.class)));
} return true;
case R.id.menuDonation: {
String donation_url = getString(R.string.alamat_donasi);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(donation_url));
startActivity(HelpActivity.createIntent("help/donation.html", true, getString(R.string.send_donation_confirmation), intent));
} return true;
}
return super.onOptionsItemSelected(item);
}
void setFullScreen(boolean yes) {
if (yes) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
fullScreenController.hidePermanently();
fullScreen = true;
if (fullScreenDismissHint == null) {
fullScreenDismissHint = Toast.makeText(this, R.string.full_screen_dismiss_hint, Toast.LENGTH_SHORT);
}
fullScreenDismissHint.show();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
fullScreenController.showPermanently();
fullScreen = false;
}
}
void setShowTextAppearancePanel(boolean yes) {
if (yes) {
if (textAppearancePanel == null) { // not showing yet
textAppearancePanel = new TextAppearancePanel(this, getLayoutInflater(), overlayContainer, new TextAppearancePanel.Listener() {
@Override public void onValueChanged() {
S.calculateAppliedValuesBasedOnPreferences();
applyPreferences(false);
}
}, REQCODE_textAppearanceGetFonts, REQCODE_textAppearanceCustomColors);
textAppearancePanel.show();
}
} else {
if (textAppearancePanel != null) {
textAppearancePanel.hide();
textAppearancePanel = null;
}
}
}
void setNightMode(boolean yes) {
final boolean previousValue = Preferences.getBoolean(Prefkey.is_night_mode, false);
if (previousValue == yes) return;
Preferences.setBoolean(Prefkey.is_night_mode, yes);
S.calculateAppliedValuesBasedOnPreferences();
applyPreferences(false);
if (textAppearancePanel != null) {
textAppearancePanel.displayValues();
}
}
private Pair<List<String>, List<MVersion>> getAvailableVersions() {
// populate with
// 1. internal
// 2. presets that have been DOWNLOADED and ACTIVE
// 3. yeses that are ACTIVE
AppConfig c = AppConfig.get();
final List<String> options = new ArrayList<String>(); // sync with below line
final List<MVersion> data = new ArrayList<MVersion>(); // sync with above line
options.add(c.internalLongName); // 1. internal
data.add(new MVersionInternal());
for (MVersionPreset preset: c.presets) { // 2. preset
if (preset.hasDataFile() && preset.getActive()) {
options.add(preset.longName);
data.add(preset);
}
}
// 3. active yeses
List<MVersionYes> yeses = S.getDb().listAllVersions();
for (MVersionYes yes: yeses) {
if (yes.hasDataFile() && yes.getActive()) {
options.add(yes.longName);
data.add(yes);
}
}
return Pair.create(options, data);
}
void openVersionsDialog() {
Pair<List<String>, List<MVersion>> versions = getAvailableVersions();
final List<String> options = versions.first;
final List<MVersion> data = versions.second;
int selected = -1;
if (S.activeVersionId == null) {
selected = 0;
} else {
for (int i = 0; i < data.size(); i++) {
MVersion mv = data.get(i);
if (mv.getVersionId().equals(S.activeVersionId)) {
selected = i;
break;
}
}
}
new AlertDialog.Builder(this)
.setSingleChoiceItems(options.toArray(new String[options.size()]), selected, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
final MVersion mv = data.get(which);
loadVersion(mv, true);
dialog.dismiss();
}
})
.setPositiveButton(R.string.versi_lainnya, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
startActivityForResult(VersionsActivity.createIntent(), REQCODE_version);
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
private void openProgressMarkDialog() {
FragmentManager fm = getSupportFragmentManager();
ProgressMarkDialog dialog = new ProgressMarkDialog();
dialog.show(fm, "progress_mark_dialog");
}
void openSplitVersionsDialog() {
Pair<List<String>, List<MVersion>> versions = getAvailableVersions();
final List<String> options = versions.first;
final List<MVersion> data = versions.second;
options.add(0, getString(R.string.split_version_none));
data.add(0, null);
int selected = -1;
if (this.activeSplitVersionId == null) {
selected = 0;
} else {
for (int i = 1 /* because 0 is null */; i < data.size(); i++) {
MVersion mv = data.get(i);
if (mv.getVersionId().equals(this.activeSplitVersionId)) {
selected = i;
break;
}
}
}
new AlertDialog.Builder(this)
.setSingleChoiceItems(options.toArray(new String[options.size()]), selected, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
final MVersion mv = data.get(which);
if (mv == null) { // closing split version
activeSplitVersion = null;
activeSplitVersionId = null;
closeSplitDisplay();
} else {
boolean ok = loadSplitVersion(mv);
if (ok) {
openSplitDisplay();
displaySplitFollowingMaster();
} else {
activeSplitVersion = null;
activeSplitVersionId = null;
closeSplitDisplay();
}
}
dialog.dismiss();
}
})
.setPositiveButton(R.string.versi_lainnya, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
startActivityForResult(VersionsActivity.createIntent(), REQCODE_version);
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
void openSplitDisplay() {
if (splitHandle.getVisibility() == View.VISIBLE) {
return; // it's already split, no need to do anything
}
// do it on after the layout pass
overlayContainer.requestLayout();
overlayContainer.post(new Runnable() {
@Override
public void run() {
splitHandle.setVisibility(View.VISIBLE);
int splitHandleHeight = getResources().getDimensionPixelSize(R.dimen.split_handle_height);
int totalHeight = splitRoot.getHeight();
int masterHeight = totalHeight / 2 - splitHandleHeight / 2;
// divide by 2 the screen space
ViewGroup.LayoutParams lp = lsText.getLayoutParams();
lp.height = masterHeight;
lsText.setLayoutParams(lp);
// no need to set height, because it has been set to match_parent, so it takes
// the remaining space.
lsSplit1.setVisibility(View.VISIBLE);
}
});
}
void closeSplitDisplay() {
if (splitHandle.getVisibility() == View.GONE) {
return; // it's already not split, no need to do anything
}
splitHandle.setVisibility(View.GONE);
lsSplit1.setVisibility(View.GONE);
ViewGroup.LayoutParams lp = lsText.getLayoutParams();
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
lsText.setLayoutParams(lp);
}
private void menuSearch_click() {
startActivityForResult(Search2Activity.createIntent(search2_query, search2_results, search2_selectedPosition, this.activeBook.bookId), REQCODE_search);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQCODE_goto) {
if (resultCode == RESULT_OK) {
GotoActivity.Result result = GotoActivity.obtainResult(data);
if (result != null) {
// change book
Book book = S.activeVersion.getBook(result.bookId);
if (book != null) {
this.activeBook = book;
} else { // no book, just chapter and verse.
result.bookId = this.activeBook.bookId;
}
int ari_cv = display(result.chapter_1, result.verse_1);
history.add(Ari.encode(result.bookId, ari_cv));
}
}
} else if (requestCode == REQCODE_bookmark) {
lsText.reloadAttributeMap();
if (activeSplitVersion != null) {
lsSplit1.reloadAttributeMap();
}
} else if (requestCode == REQCODE_search) {
if (resultCode == RESULT_OK) {
Search2Activity.Result result = Search2Activity.obtainResult(data);
if (result != null) {
if (result.selectedAri != -1) {
jumpToAri(result.selectedAri);
history.add(result.selectedAri);
}
search2_query = result.query;
search2_results = result.searchResults;
search2_selectedPosition = result.selectedPosition;
}
}
} else if (requestCode == REQCODE_devotion) {
if (resultCode == RESULT_OK) {
DevotionActivity.Result result = DevotionActivity.obtainResult(data);
if (result != null && result.ari != 0) {
jumpToAri(result.ari);
history.add(result.ari);
}
}
} else if (requestCode == REQCODE_settings) {
// MUST reload preferences
S.calculateAppliedValuesBasedOnPreferences();
applyPreferences(true);
if (resultCode == SettingsActivity.RESULT_openTextAppearance) {
setShowTextAppearancePanel(true);
}
} else if (requestCode == REQCODE_share) {
if (resultCode == RESULT_OK) {
ShareActivity.Result result = ShareActivity.obtainResult(data);
if (result != null && result.chosenIntent != null) {
Intent chosenIntent = result.chosenIntent;
if (U.equals(chosenIntent.getComponent().getPackageName(), "com.facebook.katana")) { //$NON-NLS-1$
String verseUrl = chosenIntent.getStringExtra(EXTRA_verseUrl);
if (verseUrl != null) {
chosenIntent.putExtra(Intent.EXTRA_TEXT, verseUrl); // change text to url
}
}
startActivity(chosenIntent);
}
}
} else if (requestCode == REQCODE_textAppearanceGetFonts) {
if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data);
} else if (requestCode == REQCODE_textAppearanceCustomColors) {
if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data);
// MUST reload preferences
S.calculateAppliedValuesBasedOnPreferences();
applyPreferences(true);
} else if (requestCode == REQCODE_readingPlan) {
if (data == null && !readingPlanFloatMenu.isActive) {
return;
} else if (data == null) {
if (readingPlanFloatMenu.getReadingPlanId() != Preferences.getLong(Prefkey.active_reading_plan_id, 0)) {
readingPlanFloatMenu.setVisibility(View.GONE);
readingPlanFloatMenu.isActive = false;
return;
}
readingPlanFloatMenu.setVisibility(View.VISIBLE);
readingPlanFloatMenu.fadeoutAnimation(5000);
readingPlanFloatMenu.updateProgress();
readingPlanFloatMenu.updateLayout();
return;
}
readingPlanFloatMenu.setVisibility(View.VISIBLE);
readingPlanFloatMenu.fadeoutAnimation(5000);
readingPlanFloatMenu.isActive = true;
final int ari = data.getIntExtra("ari", 0);
final long id = data.getLongExtra(ReadingPlanActivity.READING_PLAN_ID, 0L);
final int dayNumber = data.getIntExtra(ReadingPlanActivity.READING_PLAN_DAY_NUMBER, 0);
final int[] ariRanges = data.getIntArrayExtra(ReadingPlanActivity.READING_PLAN_ARI_RANGES);
if (ari != 0 && ariRanges != null) {
for (int i = 0; i < ariRanges.length; i++) {
if (ariRanges[i] == ari) {
jumpToAri(ari);
history.add(ari);
int[] ariRangesInThisSequence = new int[2];
ariRangesInThisSequence[0] = ariRanges[i];
ariRangesInThisSequence[1] = ariRanges[i + 1];
lsText.setAriRangesReadingPlan(ariRangesInThisSequence);
lsText.updateAdapter();
lsSplit1.setAriRangesReadingPlan(ariRangesInThisSequence);
lsSplit1.updateAdapter();
readingPlanFloatMenu.load(id, dayNumber, ariRanges, i / 2);
final ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener navigationClickListener = new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() {
@Override
public void onClick(final int ari_start, final int ari_end) {
int ari_jump = ari_start;
if (Ari.toVerse(ari_start) == 0) {
ari_jump |= 1;
}
jumpToAri(ari_jump);
history.add(ari_jump);
lsText.setAriRangesReadingPlan(new int[] {ari_start, ari_end});
lsText.updateAdapter();
lsSplit1.setAriRangesReadingPlan(new int[] {ari_start, ari_end});
lsSplit1.updateAdapter();
}
};
readingPlanFloatMenu.setLeftNavigationClickListener(navigationClickListener);
readingPlanFloatMenu.setRightNavigationClickListener(navigationClickListener);
readingPlanFloatMenu.setDescriptionListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() {
@Override
public void onClick(final int ari_start, final int ari_end) {
startActivityForResult(ReadingPlanActivity.createIntent(dayNumber), REQCODE_readingPlan);
}
});
readingPlanFloatMenu.setCloseReadingModeClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() {
@Override
public void onClick(final int ari_start, final int ari_end) {
readingPlanFloatMenu.clearAnimation();
readingPlanFloatMenu.setVisibility(View.GONE);
readingPlanFloatMenu.isActive = false;
lsText.setAriRangesReadingPlan(null);
lsText.updateAdapter();
lsSplit1.setAriRangesReadingPlan(null);
lsSplit1.updateAdapter();
}
});
break;
}
}
}
}
}
/**
* Display specified chapter and verse of the active book. By default all checked verses will be unchecked.
* @return Ari that contains only chapter and verse. Book always set to 0.
*/
int display(int chapter_1, int verse_1) {
return display(chapter_1, verse_1, true);
}
/**
* Display specified chapter and verse of the active book.
* @param uncheckAllVerses whether we want to always make all verses unchecked after this operation.
* @return Ari that contains only chapter and verse. Book always set to 0.
*/
int display(int chapter_1, int verse_1, boolean uncheckAllVerses) {
int current_chapter_1 = this.chapter_1;
if (chapter_1 < 1) chapter_1 = 1;
if (chapter_1 > this.activeBook.chapter_count) chapter_1 = this.activeBook.chapter_count;
if (verse_1 < 1) verse_1 = 1;
if (verse_1 > this.activeBook.verse_counts[chapter_1 - 1]) verse_1 = this.activeBook.verse_counts[chapter_1 - 1];
{ // main
this.uncheckVersesWhenActionModeDestroyed = false;
try {
boolean ok = loadChapterToVersesView(lsText, S.activeVersion, this.activeBook, chapter_1, current_chapter_1, uncheckAllVerses);
if (!ok) return 0;
} finally {
this.uncheckVersesWhenActionModeDestroyed = true;
}
// tell activity
this.chapter_1 = chapter_1;
lsText.scrollToVerse(verse_1);
}
displaySplitFollowingMaster(verse_1);
// set goto button text
String reference = this.activeBook.reference(chapter_1);
if (Preferences.getBoolean(Prefkey.history_button_understood, false) || history.getSize() == 0) {
bGoto.setText(reference);
} else {
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(reference).append("\n");
int sb_len = sb.length();
sb.append(getString(R.string.recentverses_button_hint));
sb.setSpan(new RelativeSizeSpan(0.6f), sb_len, sb.length(), 0);
bGoto.setText(sb);
}
return Ari.encode(0, chapter_1, verse_1);
}
void displaySplitFollowingMaster() {
displaySplitFollowingMaster(lsText.getVerseBasedOnScroll());
}
private void displaySplitFollowingMaster(int verse_1) {
if (activeSplitVersion != null) { // split1
Book splitBook = activeSplitVersion.getBook(this.activeBook.bookId);
if (splitBook == null) {
tSplitEmpty.setText(getString(R.string.split_version_cant_display_verse, this.activeBook.reference(this.chapter_1), activeSplitVersion.getLongName()));
tSplitEmpty.setTextColor(S.applied.fontColor);
lsSplit1.setDataEmpty();
} else {
this.uncheckVersesWhenActionModeDestroyed = false;
try {
loadChapterToVersesView(lsSplit1, activeSplitVersion, splitBook, this.chapter_1, this.chapter_1, true);
} finally {
this.uncheckVersesWhenActionModeDestroyed = true;
}
lsSplit1.scrollToVerse(verse_1);
}
}
}
static boolean loadChapterToVersesView(VersesView versesView, Version version, Book book, int chapter_1, int current_chapter_1, boolean uncheckAllVerses) {
SingleChapterVerses verses = version.loadChapterText(book, chapter_1);
if (verses == null) {
return false;
}
//# max is set to 30 (one chapter has max of 30 blocks. Already almost impossible)
int max = 30;
int[] pericope_aris = new int[max];
PericopeBlock[] pericope_blocks = new PericopeBlock[max];
int nblock = version.loadPericope(book.bookId, chapter_1, pericope_aris, pericope_blocks, max);
boolean retainSelectedVerses = (!uncheckAllVerses && chapter_1 == current_chapter_1);
versesView.setDataWithRetainSelectedVerses(retainSelectedVerses, book, chapter_1, pericope_aris, pericope_blocks, nblock, verses);
return true;
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if (press(keyCode)) return true;
return super.onKeyDown(keyCode, event);
}
@Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
if (press(keyCode)) return true;
return super.onKeyMultiple(keyCode, repeatCount, event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
String volumeButtonsForNavigation = Preferences.getString(getString(R.string.pref_volumeButtonNavigation_key), getString(R.string.pref_volumeButtonNavigation_default));
if (! U.equals(volumeButtonsForNavigation, "default")) { // consume here //$NON-NLS-1$
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) return true;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) return true;
}
return super.onKeyUp(keyCode, event);
}
void bLeft_click() {
Book currentBook = this.activeBook;
if (chapter_1 == 1) {
// we are in the beginning of the book, so go to prev book
int tryBookId = currentBook.bookId - 1;
while (tryBookId >= 0) {
Book newBook = S.activeVersion.getBook(tryBookId);
if (newBook != null) {
this.activeBook = newBook;
int newChapter_1 = newBook.chapter_count; // to the last chapter
display(newChapter_1, 1);
break;
}
tryBookId
}
// whileelse: now is already Genesis 1. No need to do anything
} else {
int newChapter = chapter_1 - 1;
display(newChapter, 1);
}
}
void bRight_click() {
Book currentBook = this.activeBook;
if (chapter_1 >= currentBook.chapter_count) {
int maxBookId = S.activeVersion.getMaxBookIdPlusOne();
int tryBookId = currentBook.bookId + 1;
while (tryBookId < maxBookId) {
Book newBook = S.activeVersion.getBook(tryBookId);
if (newBook != null) {
this.activeBook = newBook;
display(1, 1);
break;
}
tryBookId++;
}
// whileelse: now is already Revelation (or the last book) at the last chapter. No need to do anything
} else {
int newChapter = chapter_1 + 1;
display(newChapter, 1);
}
}
@Override public boolean onSearchRequested() {
menuSearch_click();
return true;
}
@Override public void onVerseSelected(XrefDialog dialog, int arif_source, int ari_target) {
final int ari_source = arif_source >>> 8;
dialog.dismiss();
jumpToAri(ari_target);
// add both xref source and target, so user can go back to source easily
history.add(ari_source);
history.add(ari_target);
}
/**
* If verse_1_ranges is null, verses will be ignored.
*/
public static String createVerseUrl(final String versionShortName, Book book, int chapter_1, String verse_1_ranges) {
final AppConfig c = AppConfig.get();
String format = c.shareUrlFormat;
String osisBookName = OsisBookNames.getBookName(book.bookId);
if (osisBookName == null) {
osisBookName = book.shortName; // fall back
}
format = format.replace("{book.osis}", osisBookName);
format = format.replace("{chapter}", String.valueOf(chapter_1));
format = format.replace("{verses}", verse_1_ranges == null? "": verse_1_ranges);
String versionShortName2;
if (versionShortName.equals("DRA")) {
versionShortName2 = "DOUAYRHEIMS";
} else {
versionShortName2 = versionShortName;
}
format = format.replace("{version.shortName}", versionShortName2);
return format;
}
VersesView.AttributeListener attributeListener = new VersesView.AttributeListener() {
@Override
public void onBookmarkAttributeClick(final Book book, final int chapter_1, final int verse_1) {
final int ari = Ari.encode(book.bookId, chapter_1, verse_1);
String reference = book.reference(chapter_1, verse_1);
TypeBookmarkDialog dialog = new TypeBookmarkDialog(IsiActivity.this, reference, ari);
dialog.setListener(new TypeBookmarkDialog.Listener() {
@Override public void onOk() {
lsText.reloadAttributeMap();
if (activeSplitVersion != null) {
lsSplit1.reloadAttributeMap();
}
}
});
dialog.show();
}
@Override
public void onNoteAttributeClick(final Book book, final int chapter_1, final int verse_1) {
TypeNoteDialog dialog = new TypeNoteDialog(IsiActivity.this, book, chapter_1, verse_1, new TypeNoteDialog.Listener() {
@Override public void onDone() {
lsText.reloadAttributeMap();
if (activeSplitVersion != null) {
lsSplit1.reloadAttributeMap();
}
}
});
dialog.show();
}
@Override
public void onProgressMarkAttributeClick(final int preset_id) {
ProgressMark progressMark = S.getDb().getProgressMarkByPresetId(preset_id);
int iconRes = AttributeView.getProgressMarkIconResource(preset_id);
String title;
if (progressMark.ari == 0 || TextUtils.isEmpty(progressMark.caption)) {
title = getString(AttributeView.getDefaultProgressMarkStringResource(preset_id));
} else {
title = progressMark.caption;
}
String verseText = "";
int ari = progressMark.ari;
if (ari != 0) {
String date = Sqlitil.toLocaleDateMedium(progressMark.modifyTime);
String reference = S.activeVersion.reference(ari);
verseText = getString(R.string.pm_icon_click_message, reference, date)
;
}
new AlertDialog.Builder(IsiActivity.this)
.setPositiveButton(getString(R.string.ok), null)
.setIcon(iconRes)
.setTitle(title)
.setMessage(verseText)
.show();
}
};
class VerseInlineLinkSpanFactory implements VerseInlineLinkSpan.Factory {
private final Object source;
VerseInlineLinkSpanFactory(final Object source) {
this.source = source;
}
@Override
public VerseInlineLinkSpan create(final VerseInlineLinkSpan.Type type, final int arif) {
return new VerseInlineLinkSpan(type, arif, source) {
@Override
public void onClick(final Type type, final int arif, final Object source) {
if (type == Type.xref) {
final XrefDialog dialog = XrefDialog.newInstance(arif);
// TODO setSourceVersion here is not restored when dialog is restored
if (source == lsText) { // use activeVersion
dialog.setSourceVersion(S.activeVersion);
} else if (source == lsSplit1) { // use activeSplitVersion
dialog.setSourceVersion(activeSplitVersion);
}
FragmentManager fm = getSupportFragmentManager();
dialog.show(fm, XrefDialog.class.getSimpleName());
} else if (type == Type.footnote) {
FootnoteEntry fe = null;
if (source == lsText) { // use activeVersion
fe = S.activeVersion.getFootnoteEntry(arif);
} else if (source == lsSplit1) { // use activeSplitVersion
fe = activeSplitVersion.getFootnoteEntry(arif);
}
if (fe != null) {
final SpannableStringBuilder footnoteText = new SpannableStringBuilder();
VerseRenderer.appendSuperscriptNumber(footnoteText, arif & 0xff);
footnoteText.append(" ");
new AlertDialog.Builder(IsiActivity.this)
.setMessage(FormattedTextRenderer.render(fe.content, footnoteText))
.setPositiveButton("OK", null)
.show();
} else {
new AlertDialog.Builder(IsiActivity.this)
.setMessage(String.format(Locale.US, "Error: footnote arif 0x%08x couldn't be loaded", arif))
.setPositiveButton("OK", null)
.show();
}
} else {
new AlertDialog.Builder(IsiActivity.this)
.setMessage("Error: Unknown inline link type: " + type)
.setPositiveButton("OK", null)
.show();
}
}
};
}
}
VersesView.SelectedVersesListener lsText_selectedVerses = new VersesView.SelectedVersesListener() {
@Override public void onSomeVersesSelected(VersesView v) {
if (activeSplitVersion != null) {
// synchronize the selection with the split view
IntArrayList selectedVerses = v.getSelectedVerses_1();
lsSplit1.checkVerses(selectedVerses, false);
}
if (actionMode == null) {
actionMode = startSupportActionMode(actionMode_callback);
}
if (actionMode != null) {
actionMode.invalidate();
}
}
@Override public void onNoVersesSelected(VersesView v) {
if (activeSplitVersion != null) {
// synchronize the selection with the split view
lsSplit1.uncheckAllVerses(false);
}
if (actionMode != null) {
actionMode.finish();
actionMode = null;
}
}
@Override public void onVerseSingleClick(VersesView v, int verse_1) {}
};
VersesView.SelectedVersesListener lsSplit1_selectedVerses = new VersesView.SelectedVersesListener() {
@Override public void onSomeVersesSelected(VersesView v) {
// synchronize the selection with the main view
IntArrayList selectedVerses = v.getSelectedVerses_1();
lsText.checkVerses(selectedVerses, true);
}
@Override public void onNoVersesSelected(VersesView v) {
lsText.uncheckAllVerses(true);
}
@Override public void onVerseSingleClick(VersesView v, int verse_1) {}
};
VersesView.OnVerseScrollStateChangeListener verseScrollState = new VersesView.OnVerseScrollStateChangeListener() {
@Override
public void onVerseScrollStateChange(final VersesView versesView, final int scrollState) {
if (!readingPlanFloatMenu.isActive) {
return;
}
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
readingPlanFloatMenu.isAnimating = false;
readingPlanFloatMenu.clearAnimation();
readingPlanFloatMenu.setVisibility(View.VISIBLE);
} else if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
readingPlanFloatMenu.setVisibility(View.VISIBLE);
} else if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && readingPlanFloatMenu.getVisibility() != View.GONE) {
readingPlanFloatMenu.fadeoutAnimation(3000);
}
}
};
VersesView.OnVerseScrollListener lsText_verseScroll = new VersesView.OnVerseScrollListener() {
@Override public void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop) {
if (!isPericope && activeSplitVersion != null) {
lsSplit1.scrollToVerse(verse_1, prop);
}
}
@Override public void onScrollToTop(VersesView v) {
if (activeSplitVersion != null) {
lsSplit1.scrollToTop();
}
}
};
VersesView.OnVerseScrollListener lsSplit1_verseScroll = new VersesView.OnVerseScrollListener() {
@Override public void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop) {
if (!isPericope) {
lsText.scrollToVerse(verse_1, prop);
}
}
@Override public void onScrollToTop(VersesView v) {
lsText.scrollToTop();
}
};
ActionMode.Callback actionMode_callback = new ActionMode.Callback() {
@Override public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.context_isi, menu);
/* The following "esvsbasal" thing is a personal thing by yuku that doesn't matter to anyone else.
* Please ignore it and leave it intact. */
if (hasEsvsbAsal == null) {
try {
getPackageManager().getApplicationInfo("yuku.esvsbasal", 0); //$NON-NLS-1$
hasEsvsbAsal = true;
} catch (NameNotFoundException e) {
hasEsvsbAsal = false;
}
}
if (hasEsvsbAsal) {
MenuItem esvsb = menu.findItem(R.id.menuEsvsb);
if (esvsb != null) esvsb.setVisible(true);
}
List<ProgressMark> progressMarks = S.getDb().listAllProgressMarks();
MenuItem item1 = menu.findItem(R.id.menuProgress1);
setProgressMarkMenuItemTitle(progressMarks, item1, 0);
MenuItem item2 = menu.findItem(R.id.menuProgress2);
setProgressMarkMenuItemTitle(progressMarks, item2, 1);
MenuItem item3 = menu.findItem(R.id.menuProgress3);
setProgressMarkMenuItemTitle(progressMarks, item3, 2);
MenuItem item4 = menu.findItem(R.id.menuProgress4);
setProgressMarkMenuItemTitle(progressMarks, item4, 3);
MenuItem item5 = menu.findItem(R.id.menuProgress5);
setProgressMarkMenuItemTitle(progressMarks, item5, 4);
return true;
}
@Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
MenuItem menuAddBookmark = menu.findItem(R.id.menuAddBookmark);
MenuItem menuAddNote = menu.findItem(R.id.menuAddNote);
MenuItem menuProgressMark = menu.findItem(R.id.menuProgressMark);
IntArrayList selected = lsText.getSelectedVerses_1();
boolean single = selected.size() == 1;
boolean changed1 = menuAddBookmark.isVisible() != single;
boolean changed2 = menuAddNote.isVisible() != single;
boolean changed3 = menuProgressMark.isVisible() != single;
boolean changed = changed1 || changed2 || changed3;
if (changed) {
menuAddBookmark.setVisible(single);
menuAddNote.setVisible(single);
menuProgressMark.setVisible(single);
}
return changed;
}
@Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
IntArrayList selected = lsText.getSelectedVerses_1();
if (selected.size() == 0) return true;
CharSequence reference = referenceFromSelectedVerses(selected, activeBook);
IntArrayList selectedSplit = null;
CharSequence referenceSplit = null;
if (activeSplitVersion != null) {
selectedSplit = lsSplit1.getSelectedVerses_1();
referenceSplit = referenceFromSelectedVerses(selectedSplit, activeSplitVersion.getBook(activeBook.bookId));
}
// the main verse (0 if not exist), which is only when only one verse is selected
int mainVerse_1 = 0;
if (selected.size() == 1) {
mainVerse_1 = selected.get(0);
}
int itemId = item.getItemId();
switch (itemId) {
case R.id.menuCopy: { // copy, can be multiple
CharSequence textToCopy = prepareTextForCopyShare(selected, reference, false);
if (activeSplitVersion != null) {
textToCopy = textToCopy + "\n\n" + prepareTextForCopyShare(selectedSplit, referenceSplit, true);
}
U.copyToClipboard(textToCopy);
lsText.uncheckAllVerses(true);
Toast.makeText(App.context, getString(R.string.alamat_sudah_disalin, reference), Toast.LENGTH_SHORT).show();
mode.finish();
} return true;
case R.id.menuShare: {
CharSequence textToShare = prepareTextForCopyShare(selected, reference, false);
if (activeSplitVersion != null) {
textToShare = textToShare + "\n\n" + prepareTextForCopyShare(selectedSplit, referenceSplit, true);
}
String verseUrl;
if (selected.size() == 1) {
verseUrl = createVerseUrl(S.activeVersion.getShortName(), IsiActivity.this.activeBook, IsiActivity.this.chapter_1, String.valueOf(selected.get(0)));
} else {
StringBuilder sb = new StringBuilder();
Book.writeVerseRange(selected, sb);
verseUrl = createVerseUrl(S.activeVersion.getShortName(), IsiActivity.this.activeBook, IsiActivity.this.chapter_1, sb.toString()); // use verse range
}
Intent intent = ShareCompat.IntentBuilder.from(IsiActivity.this)
.setType("text/plain") //$NON-NLS-1$
.setSubject(reference.toString())
.setText(textToShare.toString())
.getIntent();
intent.putExtra(EXTRA_verseUrl, verseUrl);
startActivityForResult(ShareActivity.createIntent(intent, getString(R.string.bagikan_alamat, reference)), REQCODE_share);
lsText.uncheckAllVerses(true);
mode.finish();
} return true;
case R.id.menuVersions: {
openVersionsDialog();
} return true;
case R.id.menuAddBookmark: {
if (mainVerse_1 == 0) {
// no main verse, scroll to show the relevant one!
mainVerse_1 = selected.get(0);
lsText.scrollToShowVerse(mainVerse_1);
}
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, mainVerse_1);
TypeBookmarkDialog dialog = new TypeBookmarkDialog(IsiActivity.this, IsiActivity.this.activeBook.reference(IsiActivity.this.chapter_1, mainVerse_1), ari);
dialog.setListener(new TypeBookmarkDialog.Listener() {
@Override public void onOk() {
reloadVerse();
}
});
dialog.show();
mode.finish();
} return true;
case R.id.menuAddNote: {
if (mainVerse_1 == 0) {
// no main verse, scroll to show the relevant one!
mainVerse_1 = selected.get(0);
lsText.scrollToShowVerse(mainVerse_1);
}
TypeNoteDialog dialog = new TypeNoteDialog(IsiActivity.this, IsiActivity.this.activeBook, IsiActivity.this.chapter_1, mainVerse_1, new TypeNoteDialog.Listener() {
@Override public void onDone() {
reloadVerse();
}
});
dialog.show();
mode.finish();
} return true;
case R.id.menuAddHighlight: {
final int ariKp = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, 0);
int colorRgb = S.getDb().getHighlightColorRgb(ariKp, selected);
new TypeHighlightDialog(IsiActivity.this, ariKp, selected, new TypeHighlightDialog.Listener() {
@Override public void onOk(int colorRgb) {
reloadVerse();
}
}, colorRgb, reference).show();
mode.finish();
} return true;
case R.id.menuEsvsb: {
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, mainVerse_1);
try {
Intent intent = new Intent("yuku.esvsbasal.action.GOTO"); //$NON-NLS-1$
intent.putExtra("ari", ari); //$NON-NLS-1$
startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "ESVSB starting", e); //$NON-NLS-1$
}
} return true;
case R.id.menuProgress1: {
updateProgressMark(mainVerse_1, 0);
} return true;
case R.id.menuProgress2: {
updateProgressMark(mainVerse_1, 1);
} return true;
case R.id.menuProgress3: {
updateProgressMark(mainVerse_1, 2);
} return true;
case R.id.menuProgress4: {
updateProgressMark(mainVerse_1, 3);
} return true;
case R.id.menuProgress5: {
updateProgressMark(mainVerse_1, 4);
} return true;
}
return false;
}
@Override public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
// FIXME even with this guard, verses are still unchecked when switching version while both Fullscreen and Split is active.
// This guard only fixes unchecking of verses when in fullscreen mode.
if (uncheckVersesWhenActionModeDestroyed) {
lsText.uncheckAllVerses(true);
}
}
private void setProgressMarkMenuItemTitle(final List<ProgressMark> progressMarks, final MenuItem item, int position) {
String title = (progressMarks.get(position).ari == 0 || TextUtils.isEmpty(progressMarks.get(position).caption)) ? getString(AttributeView.getDefaultProgressMarkStringResource(position)): progressMarks.get(position).caption;
item.setTitle(getString(R.string.pm_menu_save_progress, title));
}
};
private void reloadVerse() {
lsText.uncheckAllVerses(true);
lsText.reloadAttributeMap();
if (activeSplitVersion != null) {
lsSplit1.reloadAttributeMap();
}
}
private void updateProgressMark(final int mainVerse_1, final int position) {
final int ari = Ari.encode(this.activeBook.bookId, this.chapter_1, mainVerse_1);
List<ProgressMark> progressMarks = S.getDb().listAllProgressMarks();
final ProgressMark progressMark = progressMarks.get(position);
if (progressMark.ari == ari) {
int icon = AttributeView.getProgressMarkIconResource(position);
String title = progressMark.caption;
if (TextUtils.isEmpty(title)) {
title = getString(AttributeView.getDefaultProgressMarkStringResource(position));
}
new AlertDialog.Builder(IsiActivity.this)
.setIcon(icon)
.setTitle(title)
.setMessage(getString(R.string.pm_delete_progress_confirm, title))
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
progressMark.ari = 0;
progressMark.caption = null;
S.getDb().updateProgressMark(progressMark);
reloadVerse();
}
})
.setNegativeButton(getString(R.string.cancel), null)
.show();
} else {
if (progressMark.caption == null) {
ProgressMarkDialog.showRenameProgressDialog(this, progressMark, new ProgressMarkDialog.OnRenameListener() {
@Override
public void okClick() {
saveProgress(progressMark, ari, position);
}
});
} else {
saveProgress(progressMark, ari, position);
}
}
}
public void saveProgress(final ProgressMark progressMark, final int ari, final int position) {
progressMark.ari = ari;
progressMark.modifyTime = new Date();
S.getDb().updateProgressMark(progressMark);
AttributeView.startAnimationForProgressMark(position);
reloadVerse();
}
SplitHandleButton.SplitHandleButtonListener splitHandleButton_listener = new SplitHandleButton.SplitHandleButtonListener() {
int aboveH;
int handleH;
int rootH;
@Override public void onHandleDragStart() {
aboveH = lsText.getHeight();
handleH = splitHandle.getHeight();
rootH = splitRoot.getHeight();
}
@Override public void onHandleDragMove(float dySinceLast, float dySinceStart) {
int newH = (int) (aboveH + dySinceStart);
int maxH = rootH - handleH;
ViewGroup.LayoutParams lp = lsText.getLayoutParams();
lp.height = newH < 0? 0: newH > maxH? maxH: newH;
lsText.setLayoutParams(lp);
}
@Override public void onHandleDragStop() {
}
};
}
|
package io.branch.referral;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.BadParcelableException;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import io.branch.indexing.BranchUniversalObject;
import io.branch.indexing.ContentDiscoverer;
import io.branch.referral.network.BranchRemoteInterface;
import io.branch.referral.util.BRANCH_STANDARD_EVENT;
import io.branch.referral.util.BranchEvent;
import io.branch.referral.util.CommerceEvent;
import io.branch.referral.util.LinkProperties;
/**
* <p>
* The core object required when using Branch SDK. You should declare an object of this type at
* the class-level of each Activity or Fragment that you wish to use Branch functionality within.
* </p>
* <p>
* Normal instantiation of this object would look like this:
* </p>
* <!--
* <pre style="background:#fff;padding:10px;border:2px solid silver;">
* Branch.getInstance(this.getApplicationContext()) // from an Activity
* Branch.getInstance(getActivity().getApplicationContext()) // from a Fragment
* </pre>
* -->
*/
public class Branch implements BranchViewHandler.IBranchViewEvents, SystemObserver.GAdsParamsFetchEvents, InstallListener.IInstallReferrerEvents {
private static final String TAG = "BranchSDK";
/**
* Hard-coded {@link String} that denotes a {@link BranchLinkData#tags}; applies to links that
* are shared with others directly as a user action, via social media for instance.
*/
public static final String FEATURE_TAG_SHARE = "share";
/**
* Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are associated
* with a referral program, incentivized or not.
*/
public static final String FEATURE_TAG_REFERRAL = "referral";
/**
* Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are sent as
* referral actions by users of an app using an 'invite contacts' feature for instance.
*/
public static final String FEATURE_TAG_INVITE = "invite";
/**
* Hard-coded {@link String} that denotes a link that is part of a commercial 'deal' or offer.
*/
public static final String FEATURE_TAG_DEAL = "deal";
/**
* Hard-coded {@link String} that denotes a link tagged as a gift action within a service or
* product.
*/
public static final String FEATURE_TAG_GIFT = "gift";
/**
* The code to be passed as part of a deal or gift; retrieved from the Branch object as a
* tag upon initialisation. Of {@link String} format.
*/
public static final String REDEEM_CODE = "$redeem_code";
/**
* <p>Default value of referral bucket; referral buckets contain credits that are used when users
* are referred to your apps. These can be viewed in the Branch dashboard under Referrals.</p>
*/
public static final String REFERRAL_BUCKET_DEFAULT = "default";
/**
* <p>Hard-coded value for referral code type. Referral codes will always result on "credit" actions.
* Even if they are of 0 value.</p>
*/
public static final String REFERRAL_CODE_TYPE = "credit";
/**
* Branch SDK version for the current release of the Branch SDK.
*/
public static final int REFERRAL_CREATION_SOURCE_SDK = 2;
/**
* Key value for referral code as a parameter.
*/
public static final String REFERRAL_CODE = "referral_code";
/**
* The redirect URL provided when the link is handled by a desktop client.
*/
public static final String REDIRECT_DESKTOP_URL = "$desktop_url";
/**
* The redirect URL provided when the link is handled by an Android device.
*/
public static final String REDIRECT_ANDROID_URL = "$android_url";
/**
* The redirect URL provided when the link is handled by an iOS device.
*/
public static final String REDIRECT_IOS_URL = "$ios_url";
/**
* The redirect URL provided when the link is handled by a large form-factor iOS device such as
* an iPad.
*/
public static final String REDIRECT_IPAD_URL = "$ipad_url";
/**
* The redirect URL provided when the link is handled by an Amazon Fire device.
*/
public static final String REDIRECT_FIRE_URL = "$fire_url";
/**
* The redirect URL provided when the link is handled by a Blackberry device.
*/
public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url";
/**
* The redirect URL provided when the link is handled by a Windows Phone device.
*/
public static final String REDIRECT_WINDOWS_PHONE_URL = "$windows_phone_url";
public static final String OG_TITLE = "$og_title";
public static final String OG_DESC = "$og_description";
public static final String OG_IMAGE_URL = "$og_image_url";
public static final String OG_VIDEO = "$og_video";
public static final String OG_URL = "$og_url";
/**
* Unique identifier for the app in use.
*/
public static final String OG_APP_ID = "$og_app_id";
/**
* {@link String} value denoting the deep link path to override Branch's default one. By
* default, Branch will use yourapp://open?link_click_id=12345. If you specify this key/value,
* Branch will use yourapp://'$deeplink_path'?link_click_id=12345
*/
public static final String DEEPLINK_PATH = "$deeplink_path";
/**
* {@link String} value indicating whether the link should always initiate a deep link action.
* By default, unless overridden on the dashboard, Branch will only open the app if they are
* 100% sure the app is installed. This setting will cause the link to always open the app.
* Possible values are "true" or "false"
*/
public static final String ALWAYS_DEEPLINK = "$always_deeplink";
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, the user applying the referral code receives credit.
*/
public static final int REFERRAL_CODE_LOCATION_REFERREE = 0;
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, the user who created the referral code receives credit.
*/
public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2;
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, both the creator and applicant receive credit
*/
public static final int REFERRAL_CODE_LOCATION_BOTH = 3;
/**
* An {@link Integer} value indicating the calculation type of the referral code. In this case,
* the referral code can be applied continually.
*/
public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1;
/**
* An {@link Integer} value indicating the calculation type of the referral code. In this case,
* a user can only apply a specific referral code once.
*/
public static final int REFERRAL_CODE_AWARD_UNIQUE = 0;
/**
* An {@link Integer} value indicating the link type. In this case, the link can be used an
* unlimited number of times.
*/
public static final int LINK_TYPE_UNLIMITED_USE = 0;
/**
* An {@link Integer} value indicating the link type. In this case, the link can be used only
* once. After initial use, subsequent attempts will not validate.
*/
public static final int LINK_TYPE_ONE_TIME_USE = 1;
private static final int SESSION_KEEPALIVE = 2000;
/**
* <p>An {@link Integer} value defining the timeout period in milliseconds to wait during a
* looping task before triggering an actual connection close during a session close action.</p>
*/
private static final int PREVENT_CLOSE_TIMEOUT = 500;
/* Json object containing key-value pairs for debugging deep linking */
private JSONObject deeplinkDebugParams_;
private static boolean disableDeviceIDFetch_;
private boolean enableFacebookAppLinkCheck_ = false;
private static boolean isSimulatingInstalls_;
private static boolean isLogging_ = false;
static boolean checkInstallReferrer_ = true;
private static long playStoreReferrerFetchTime = 1500;
public static final long NO_PLAY_STORE_REFERRER_WAIT = 0;
/**
* <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of
* the class during application runtime.</p>
*/
private static Branch branchReferral_;
private BranchRemoteInterface branchRemoteInterface_;
private PrefHelper prefHelper_;
private final SystemObserver systemObserver_;
private Context context_;
final Object lock;
private Semaphore serverSema_;
private final ServerRequestQueue requestQueue_;
private int networkCount_;
private boolean hasNetwork_;
private Map<BranchLinkData, String> linkCache_;
/* Set to true when application is instantiating {@BranchApp} by extending or adding manifest entry. */
private static boolean isAutoSessionMode_ = false;
/* Set to true when {@link Activity} life cycle callbacks are registered. */
private static boolean isActivityLifeCycleCallbackRegistered_ = false;
/* Enumeration for defining session initialisation state. */
private enum SESSION_STATE {
INITIALISED, INITIALISING, UNINITIALISED
}
private enum INTENT_STATE {
PENDING,
READY
}
private INTENT_STATE intentState_ = INTENT_STATE.PENDING;
private boolean handleDelayedNewIntents_ = false;
/* Holds the current Session state. Default is set to UNINITIALISED. */
private SESSION_STATE initState_ = SESSION_STATE.UNINITIALISED;
/* Instance of share link manager to share links automatically with third party applications. */
private ShareLinkManager shareLinkManager_;
/* The current activity instance for the application.*/
WeakReference<Activity> currentActivityReference_;
/* Specifies the choice of user for isReferrable setting. used to determine the link click is referrable or not. See getAutoSession for usage */
private enum CUSTOM_REFERRABLE_SETTINGS {
USE_DEFAULT, REFERRABLE, NON_REFERRABLE
}
/* By default assume user want to use the default settings. Update this option when user specify custom referrable settings */
private static CUSTOM_REFERRABLE_SETTINGS customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
/* Key to indicate whether the Activity was launched by Branch or not. */
private static final String AUTO_DEEP_LINKED = "io.branch.sdk.auto_linked";
/* Key for Auto Deep link param. The activities which need to automatically deep linked should define in this in the activity metadata. */
private static final String AUTO_DEEP_LINK_KEY = "io.branch.sdk.auto_link_keys";
/* Path for $deeplink_path or $android_deeplink_path to auto deep link. The activities which need to automatically deep linked should define in this in the activity metadata. */
private static final String AUTO_DEEP_LINK_PATH = "io.branch.sdk.auto_link_path";
/* Key for disabling auto deep link feature. Setting this to true in manifest will disable auto deep linking feature. */
private static final String AUTO_DEEP_LINK_DISABLE = "io.branch.sdk.auto_link_disable";
/*Key for defining a request code for an activity. should be added as a metadata for an activity. This is used as a request code for launching a an activity on auto deep link. */
private static final String AUTO_DEEP_LINK_REQ_CODE = "io.branch.sdk.auto_link_request_code";
/* Request code used to launch and activity on auto deep linking unless DEF_AUTO_DEEP_LINK_REQ_CODE is not specified for teh activity in manifest.*/
private static final int DEF_AUTO_DEEP_LINK_REQ_CODE = 1501;
/* Sets to true when the init session params are reported to the app though call back.*/
boolean isInitReportedThroughCallBack = false;
private final ConcurrentHashMap<String, String> instrumentationExtraData_;
/* Name of the key for getting Fabric Branch API key from string resource */
private static final String FABRIC_BRANCH_API_KEY = "io.branch.apiKey";
private boolean isGAParamsFetchInProgress_ = false;
private List<String> externalUriWhiteList_;
private List<String> skipExternalUriHosts_;
String sessionReferredLink_; // Link which opened this application session if opened by a link click.
private static String cookieBasedMatchDomain_ = "app.link"; // Domain name used for cookie based matching.
private static int LATCH_WAIT_UNTIL = 2500; //used for getLatestReferringParamsSync and getFirstReferringParamsSync, fail after this many milliseconds
/* List of keys whose values are collected from the Intent Extra.*/
private static final String[] EXTERNAL_INTENT_EXTRA_KEY_WHITE_LIST = new String[]{
"extra_launch_uri", // Key for embedded uri in FB ads triggered intents
"branch_intent" // A boolean that specifies if this intent is originated by Branch
};
private CountDownLatch getFirstReferringParamsLatch = null;
private CountDownLatch getLatestReferringParamsLatch = null;
/* Flag for checking of Strong matching is waiting on GAID fetch */
private boolean performCookieBasedStrongMatchingOnGAIDAvailable = false;
boolean isInstantDeepLinkPossible = false;
/* Flag to find if the activity is launched from stack (incase of single top) or created fresh and launched */
private boolean isActivityCreatedAndLaunched = false;
/* Flag to turn on or off instant deeplinking feature. IDL is enabled by default */
private static boolean disableInstantDeepLinking = false;
/**
* <p>The main constructor of the Branch class is private because the class uses the Singleton
* pattern.</p> *
* <p>Use {@link #getInstance(Context) getInstance} method when instantiating.</p>
*
* @param context A {@link Context} from which this call was made.
*/
private Branch(@NonNull Context context) {
prefHelper_ = PrefHelper.getInstance(context);
branchRemoteInterface_ = BranchRemoteInterface.getDefaultBranchRemoteInterface(context);
systemObserver_ = new SystemObserver(context);
requestQueue_ = ServerRequestQueue.getInstance(context);
serverSema_ = new Semaphore(1);
lock = new Object();
networkCount_ = 0;
hasNetwork_ = true;
linkCache_ = new HashMap<>();
instrumentationExtraData_ = new ConcurrentHashMap<>();
isGAParamsFetchInProgress_ = systemObserver_.prefetchGAdsParams(this);
InstallListener.setListener(this);
// newIntent() delayed issue is only with Android M+ devices. So need to handle android M and above
// PRS: Since this seem more reliable and not causing any integration issues adding this to all supported SDK versions
if (android.os.Build.VERSION.SDK_INT >= 15) {
handleDelayedNewIntents_ = true;
intentState_ = INTENT_STATE.PENDING;
} else {
handleDelayedNewIntents_ = false;
intentState_ = INTENT_STATE.READY;
}
externalUriWhiteList_ = new ArrayList<>();
skipExternalUriHosts_ = new ArrayList<>();
}
/**
* Sets a custom Branch Remote interface for handling RESTful requests. Call this for implementing a custom network layer for handling communication between
* Branch SDK and remote Branch server
*
* @param remoteInterface A instance of class extending {@link BranchRemoteInterface} with implementation for abstract RESTful GET or POST methods
*/
public void setBranchRemoteInterface(BranchRemoteInterface remoteInterface) {
branchRemoteInterface_ = remoteInterface;
}
/**
* <p>
* Enables/Disables the test mode for the SDK. This will use the Branch Test Keys.
* This will also enable debug logs.
* Note: This is same as setting "io.branch.sdk.TestMode" to "True" in Manifest file
* </p>
*/
public static void enableTestMode() {
BranchUtil.isCustomDebugEnabled_ = true;
}
public static void disableTestMode() {
BranchUtil.isCustomDebugEnabled_ = false;
}
public void setDebug() {
enableTestMode();
}
/**
* @deprecated This method is deprecated since play store referrer is enabled by default from v2.9.1.
* Please use {@link #setPlayStoreReferrerCheckTimeout(long)} instead.
*/
public static void enablePlayStoreReferrer(long delay) {
setPlayStoreReferrerCheckTimeout(delay);
}
/**
* Since play store referrer broadcast from google play is few millisecond delayed Branch will delay the collecting deep link data on app install by {@link #playStoreReferrerFetchTime} millisecond
* This will allow branch to provide for more accurate tracking and attribution. This will delay branch init only the first time user open the app.
* This method allows to override the maximum wait time for play store referrer to arrive. Set it to {@link Branch#NO_PLAY_STORE_REFERRER_WAIT} if you don't want to wait for play store referrer
* <p>
* Note: as of our testing 4/2017 a 1500 milli sec wait time is enough to capture more than 90% of the install referrer case
*
* @param delay {@link Long} Maximum wait time for install referrer broadcast in milli seconds. Set to {@link Branch#NO_PLAY_STORE_REFERRER_WAIT} if you don't want to wait for play store referrer
*/
public static void setPlayStoreReferrerCheckTimeout(long delay) {
checkInstallReferrer_ = delay > 0;
playStoreReferrerFetchTime = delay;
}
/**
* <p>
* Disables or enables the instant deep link functionality.
* </p>
* @param disableIDL Value {@code true} disables the instant deep linking. Value {@code false} enables the instant deep linking.
*/
public static void disableInstantDeepLinking(boolean disableIDL){
disableInstantDeepLinking = disableIDL;
}
/**
* <p>Singleton method to return the pre-initialised object of the type {@link Branch}.
* Make sure your app is instantiating {@link BranchApp} before calling this method
* or you have created an instance of Branch already by calling getInstance(Context ctx).</p>
*
* @return An initialised singleton {@link Branch} object
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getInstance() {
/* Check if BranchApp is instantiated. */
if (branchReferral_ == null) {
Log.e("BranchSDK", "Branch instance is not created yet. Make sure you have initialised Branch. [Consider Calling getInstance(Context ctx) if you still have issue.]");
} else if (isAutoSessionMode_) {
/* Check if Activity life cycle callbacks are set if in auto session mode. */
if (!isActivityLifeCycleCallbackRegistered_) {
Log.e("BranchSDK", "Branch instance is not properly initialised. Make sure your Application class is extending BranchApp class. " +
"If you are not extending BranchApp class make sure you are initialising Branch in your Applications onCreate()");
}
}
return branchReferral_;
}
public static Branch getInstance(@NonNull Context context, @NonNull String branchKey) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
}
branchReferral_.context_ = context.getApplicationContext();
if (branchKey.startsWith("key_")) {
boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey);
//on setting a new key clear link cache and pending requests
if (isNewBranchKeySet) {
branchReferral_.linkCache_.clear();
branchReferral_.requestQueue_.clear();
}
} else {
Log.e("BranchSDK", "Branch Key is invalid.Please check your BranchKey");
}
return branchReferral_;
}
private static Branch getBranchInstance(@NonNull Context context, boolean isLive) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
String branchKey = branchReferral_.prefHelper_.readBranchKey(isLive);
boolean isNewBranchKeySet;
if (branchKey == null || branchKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) {
// If Branch key is not available check for Fabric provided Branch key
String fabricBranchApiKey = null;
try {
Resources resources = context.getResources();
fabricBranchApiKey = resources.getString(resources.getIdentifier(FABRIC_BRANCH_API_KEY, "string", context.getPackageName()));
} catch (Exception ignore) {
}
if (!TextUtils.isEmpty(fabricBranchApiKey)) {
isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(fabricBranchApiKey);
} else {
Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's Manifest file!");
isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(PrefHelper.NO_STRING_VALUE);
}
} else {
isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey);
}
//on setting a new key clear link cache and pending requests
if (isNewBranchKeySet) {
branchReferral_.linkCache_.clear();
branchReferral_.requestQueue_.clear();
}
branchReferral_.context_ = context.getApplicationContext();
/* If {@link Application} is instantiated register for activity life cycle events. */
if (context instanceof Application) {
isAutoSessionMode_ = true;
branchReferral_.setActivityLifeCycleObserver((Application) context);
}
}
return branchReferral_;
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
public static Branch getInstance(@NonNull Context context) {
return getBranchInstance(context, true);
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object.
*/
public static Branch getTestInstance(@NonNull Context context) {
return getBranchInstance(context, false);
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoInstance(@NonNull Context context) {
isAutoSessionMode_ = true;
customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
boolean isLive = !BranchUtil.isTestModeEnabled(context);
getBranchInstance(context, isLive);
return branchReferral_;
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
* @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance
* should be considered as potentially referrable or not. By default, a user is only referrable
* if initSession results in a fresh install. Overriding this gives you control of who is referrable.
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoInstance(@NonNull Context context, boolean isReferrable) {
isAutoSessionMode_ = true;
customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE;
boolean isDebug = BranchUtil.isTestModeEnabled(context);
getBranchInstance(context, !isDebug);
return branchReferral_;
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
* @param branchKey A {@link String} value used to initialize Branch.
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoInstance(@NonNull Context context, @NonNull String branchKey) {
isAutoSessionMode_ = true;
customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
boolean isLive = !BranchUtil.isTestModeEnabled(context);
getBranchInstance(context, isLive);
if (branchKey.startsWith("key_")) {
boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey);
//on setting a new key clear link cache and pending requests
if (isNewBranchKeySet) {
branchReferral_.linkCache_.clear();
branchReferral_.requestQueue_.clear();
}
} else {
Log.e("BranchSDK", "Branch Key is invalid.Please check your BranchKey");
}
return branchReferral_;
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoTestInstance(@NonNull Context context) {
isAutoSessionMode_ = true;
customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
getBranchInstance(context, false);
return branchReferral_;
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
* @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance
* should be considered as potentially referrable or not. By default, a user is only referrable
* if initSession results in a fresh install. Overriding this gives you control of who is referrable.
* @return An initialised {@link Branch} object.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoTestInstance(@NonNull Context context, boolean isReferrable) {
isAutoSessionMode_ = true;
customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE;
getBranchInstance(context, false);
return branchReferral_;
}
/**
* <p>Initialises an instance of the Branch object.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object.
*/
private static Branch initInstance(@NonNull Context context) {
return new Branch(context.getApplicationContext());
}
/**
* <p>Manually sets the {@link Boolean} value, that indicates that the Branch API connection has
* been initialised, to false - forcing re-initialisation.</p>
*/
public void resetUserSession() {
initState_ = SESSION_STATE.UNINITIALISED;
}
/**
* <p>Sets the number of times to re-attempt a timed-out request to the Branch API, before
* considering the request to have failed entirely. Default 5.</p>
*
* @param retryCount An {@link Integer} specifying the number of times to retry before giving
* up and declaring defeat.
*/
public void setRetryCount(int retryCount) {
if (prefHelper_ != null && retryCount >= 0) {
prefHelper_.setRetryCount(retryCount);
}
}
/**
* <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request
* to the Branch API. Default 3000 ms.</p>
*
* @param retryInterval An {@link Integer} value specifying the number of milliseconds to
* wait before re-attempting a timed-out request.
*/
public void setRetryInterval(int retryInterval) {
if (prefHelper_ != null && retryInterval > 0) {
prefHelper_.setRetryInterval(retryInterval);
}
}
/**
* <p>Sets the duration in milliseconds that the system should wait for a response before considering
* any Branch API call to have timed out. Default 3000 ms.</p>
* <p>Increase this to perform better in low network speed situations, but at the expense of
* responsiveness to error situation.</p>
*
* @param timeout An {@link Integer} value specifying the number of milliseconds to wait before
* considering the request to have timed out.
*/
public void setNetworkTimeout(int timeout) {
if (prefHelper_ != null && timeout > 0) {
prefHelper_.setTimeout(timeout);
}
}
/**
* Method to control reading Android ID from device. Set this to true to disable reading the device id.
* This method should be called from your {@link Application#onCreate()} method before creating Branch auto instance by calling {@link Branch#getAutoInstance(Context)}
*
* @param deviceIdFetch {@link Boolean with value true to disable reading the Android id from device}
*/
public static void disableDeviceIDFetch(Boolean deviceIdFetch) {
disableDeviceIDFetch_ = deviceIdFetch;
}
/**
* Returns true if reading device id is disabled
*
* @return {@link Boolean} with value true to disable reading Andoid ID
*/
public static boolean isDeviceIDFetchDisabled() {
return disableDeviceIDFetch_;
}
/**
* Sets the key-value pairs for debugging the deep link. The key-value set in debug mode is given back with other deep link data on branch init session.
* This method should be called from onCreate() of activity which listens to Branch Init Session callbacks
*
* @param debugParams A {@link JSONObject} containing key-value pairs for debugging branch deep linking
*/
public void setDeepLinkDebugMode(JSONObject debugParams) {
deeplinkDebugParams_ = debugParams;
}
/**
* @deprecated Branch is not listing external apps any more from v2.11.0
*/
public void disableAppList() {
// Do nothing
}
/**
* <p>
* Enable Facebook app link check operation during Branch initialisation.
* </p>
*/
public void enableFacebookAppLinkCheck() {
enableFacebookAppLinkCheck_ = true;
}
/**
* <p>Add key value pairs to all requests</p>
*/
public void setRequestMetadata(@NonNull String key, @NonNull String value) {
prefHelper_.setRequestMetadata(key, value);
}
/**
* <p>Initialises a session with the Branch API, assigning a {@link BranchUniversalReferralInitListener}
* to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called following
* successful (or unsuccessful) initialisation of the session with the Branch API.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback) {
return initSession(callback, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API, assigning a {@link BranchReferralInitListener}
* to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called following
* successful (or unsuccessful) initialisation of the session with the Branch API.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback) {
return initSession(callback, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a
* {@link BranchUniversalReferralInitListener} to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, Activity activity) {
if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) {
initUserSessionInternal(callback, activity, true);
} else {
boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE;
initUserSessionInternal(callback, activity, isReferrable);
}
return true;
}
/**
* <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a
* {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, Activity activity) {
if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) {
initUserSessionInternal(callback, activity, true);
} else {
boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE;
initUserSessionInternal(callback, activity, isReferrable);
}
return true;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data) {
return initSession(callback, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data) {
return initSession(callback, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data, Activity activity) {
readAndStripParam(data, activity);
initSession(callback, activity);
return true;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data, Activity activity) {
readAndStripParam(data, activity);
return initSession(callback, activity);
}
/**
* <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p>
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession() {
return initSession((Activity) null);
}
/**
* <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p>
*
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(Activity activity) {
return initSession((BranchReferralInitListener) null, activity);
}
/**
* <p>Initialises a session with the Branch API, with associated data from the supplied
* {@link Uri}.</p>
*
* @param data A {@link Uri} variable containing the details of the source link that
* led to this
* initialisation action.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSessionWithData(@NonNull Uri data) {
return initSessionWithData(data, null);
}
/**
* <p>Initialises a session with the Branch API, with associated data from the supplied
* {@link Uri}.</p>
*
* @param data A {@link Uri} variable containing the details of the source link that led to this
* initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSessionWithData(Uri data, Activity activity) {
readAndStripParam(data, activity);
return initSession((BranchReferralInitListener) null, activity);
}
/**
* <p>Initialises a session with the Branch API, specifying whether the initialisation can count
* as a referrable action.</p>
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(boolean isReferrable) {
return initSession((BranchReferralInitListener) null, isReferrable, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API, specifying whether the initialisation can count
* as a referrable action, and supplying the calling {@link Activity} for context.</p>
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(boolean isReferrable, @NonNull Activity activity) {
return initSession((BranchReferralInitListener) null, isReferrable, activity);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Uri data) {
return initSession(callback, isReferrable, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data) {
return initSession(callback, isReferrable, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) {
readAndStripParam(data, activity);
return initSession(callback, isReferrable, activity);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) {
readAndStripParam(data, activity);
return initSession(callback, isReferrable, activity);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable) {
return initSession(callback, isReferrable, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) {
return initSession(callback, isReferrable, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Activity activity) {
initUserSessionInternal(callback, activity, isReferrable);
return true;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) {
initUserSessionInternal(callback, activity, isReferrable);
return true;
}
private void initUserSessionInternal(BranchUniversalReferralInitListener callback, Activity activity, boolean isReferrable) {
BranchUniversalReferralInitWrapper branchUniversalReferralInitWrapper = new BranchUniversalReferralInitWrapper(callback);
initUserSessionInternal(branchUniversalReferralInitWrapper, activity, isReferrable);
}
private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity, boolean isReferrable) {
if (activity != null) {
currentActivityReference_ = new WeakReference<>(activity);
}
//If already initialised
if ((hasUser() && hasSession() && initState_ == SESSION_STATE.INITIALISED)) {
reportInitSession(callback);
isInstantDeepLinkPossible = false;
}
//If uninitialised or initialising
else {
// If an instant deeplink is possible then call init session immediately. This should proceed to a normal open call
if (isInstantDeepLinkPossible) {
if (reportInitSession(callback)) {
addExtraInstrumentationData(Defines.Jsonkey.InstantDeepLinkSession.getKey(), "true");
isInstantDeepLinkPossible = false;
checkForAutoDeepLinkConfiguration();
}
}
// In case of Auto session init will be called from Branch before user. So initialising
// State also need to look for isReferrable value
if (isReferrable) {
this.prefHelper_.setIsReferrable();
} else {
this.prefHelper_.clearIsReferrable();
}
//If initialising ,then set new callbacks.
if (initState_ == SESSION_STATE.INITIALISING) {
if (callback != null) {
requestQueue_.setInstallOrOpenCallback(callback);
}
}
//if Uninitialised move request to the front if there is an existing request or create a new request.
else {
initState_ = SESSION_STATE.INITIALISING;
initializeSession(callback);
}
}
}
private boolean reportInitSession(BranchReferralInitListener callback) {
if (callback != null) {
if (isAutoSessionMode_) {
// Since Auto session mode initialise the session by itself on starting the first activity, we need to provide user
// the referring params if they call init session after init is completed. Note that user wont do InitSession per activity in auto session mode.
if (!isInitReportedThroughCallBack) { //Check if session params are reported already in case user call initsession form a different activity(not a normal case)
callback.onInitFinished(getLatestReferringParams(), null);
isInitReportedThroughCallBack = true;
} else {
callback.onInitFinished(new JSONObject(), null);
}
} else {
// Since user will do init session per activity in non auto session mode , we don't want to repeat the referring params with each initSession()call.
callback.onInitFinished(new JSONObject(), null);
}
}
return isInitReportedThroughCallBack;
}
/**
* <p>Closes the current session, dependent on the state of the
* PrefHelper#getSmartSession() {@link Boolean} value. If <i>true</i>, take no action.
* If false, close the session via the {@link #executeClose()} method.</p>
* <p>Note that if smartSession is enabled, closeSession cannot be called within
* a 2 second time span of another Branch action. This has to do with the method that
* Branch uses to keep a session alive during Activity transitions</p>
*
* @deprecated This method is deprecated from SDK v1.14.6. Session Start and close are automatically handled by Branch.
* In case you need to handle sessions manually inorder to support minimum sdk version less than 14 please consider using
* SDK version 1.14.5
*/
public void closeSession() {
Log.w("BranchSDK", "closeSession() method is deprecated from SDK v1.14.6.Session is automatically handled by Branch." +
"In case you need to handle sessions manually inorder to support minimum sdk version less than 14 please consider using " +
" SDK version 1.14.5");
}
/*
* <p>Closes the current session. Should be called by on getting the last actvity onStop() event.
* </p>
*/
private void closeSessionInternal() {
executeClose();
sessionReferredLink_ = null;
}
/**
* <p>
* Enabled Strong matching check using chrome cookies. This method should be called before
* Branch#getAutoInstance(Context).</p>
*
* @param cookieMatchDomain The domain for the url used to match the cookie (eg. example.app.link)
*/
public static void enableCookieBasedMatching(String cookieMatchDomain) {
cookieBasedMatchDomain_ = cookieMatchDomain;
}
/**
* <p>
* Enabled Strong matching check using chrome cookies. This method should be called before
* Branch#getAutoInstance(Context).</p>
*
* @param cookieMatchDomain The domain for the url used to match the cookie (eg. example.app.link)
* @param delay Time in millisecond to wait for the strong match to check to finish before Branch init session is called.
* Default time is 750 msec.
*/
public static void enableCookieBasedMatching(String cookieMatchDomain, int delay) {
cookieBasedMatchDomain_ = cookieMatchDomain;
BranchStrongMatchHelper.getInstance().setStrongMatchUrlHitDelay(delay);
}
/**
* <p>Perform the state-safe actions required to terminate any open session, and report the
* closed application event to the Branch API.</p>
*/
private void executeClose() {
if (initState_ != SESSION_STATE.UNINITIALISED) {
if (!hasNetwork_) {
// if there's no network connectivity, purge the old install/open
ServerRequest req = requestQueue_.peek();
if (req != null && (req instanceof ServerRequestRegisterInstall) || (req instanceof ServerRequestRegisterOpen)) {
requestQueue_.dequeue();
}
} else {
if (!requestQueue_.containsClose()) {
ServerRequest req = new ServerRequestRegisterClose(context_);
handleNewRequest(req);
}
}
initState_ = SESSION_STATE.UNINITIALISED;
}
}
private boolean readAndStripParam(Uri data, Activity activity) {
// PRS: isActivityCreatedAndLaunched usage: Single top activities can be launched from stack and there may be a new intent provided with onNewIntent() call. In this case need to wait till onResume to get the latest intent.
// If activity is created and launched then the intent can be readily consumed.
// NOTE : IDL will not be working if the activity is launched from stack if `initSession` is called from `onStart()`. TODO Need to check for IDL possibility from any #ServerRequestInitSession
if (!disableInstantDeepLinking) {
if (intentState_ == INTENT_STATE.READY || isActivityCreatedAndLaunched) {
// Check for instant deep linking possibility first
if (activity != null && activity.getIntent() != null && initState_ != SESSION_STATE.INITIALISED && !checkIntentForSessionRestart(activity.getIntent())) {
Intent intent = activity.getIntent();
// In case of a cold start by clicking app icon or bringing app to foreground Branch link click is always false.
if (intent.getData() == null || (!isActivityCreatedAndLaunched && isIntentParamsAlreadyConsumed(activity))) {
// Considering the case of a deferred install. In this case the app behaves like a cold start but still Branch can do probabilistic match.
// So skipping instant deep link feature until first Branch open happens
if (!prefHelper_.getInstallParams().equals(PrefHelper.NO_STRING_VALUE)) {
JSONObject nonLinkClickJson = new JSONObject();
try {
nonLinkClickJson.put(Defines.Jsonkey.Clicked_Branch_Link.getKey(), false);
nonLinkClickJson.put(Defines.Jsonkey.IsFirstSession.getKey(), false);
prefHelper_.setSessionParams(nonLinkClickJson.toString());
isInstantDeepLinkPossible = true;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else { // if not check the intent data to see if there is deep link params
if (!TextUtils.isEmpty(intent.getStringExtra(Defines.Jsonkey.BranchData.getKey()))) {
try {
String rawBranchData = intent.getStringExtra(Defines.Jsonkey.BranchData.getKey());
// Make sure the data received is complete and in correct format
JSONObject branchDataJson = new JSONObject(rawBranchData);
branchDataJson.put(Defines.Jsonkey.Clicked_Branch_Link.getKey(), true);
prefHelper_.setSessionParams(branchDataJson.toString());
isInstantDeepLinkPossible = true;
} catch (JSONException e) {
e.printStackTrace();
}
// Remove Branch data from the intent once used
intent.removeExtra(Defines.Jsonkey.BranchData.getKey());
activity.setIntent(intent);
}
}
}
}
}
if (intentState_ == INTENT_STATE.READY) {
// Capture the intent URI and extra for analytics in case started by external intents such as google app search
try {
if (data != null && !isIntentParamsAlreadyConsumed(activity)) {
boolean foundSchemeMatch;
boolean skipThisHost = false;
if (externalUriWhiteList_.size() > 0) {
foundSchemeMatch = externalUriWhiteList_.contains(data.getScheme());
} else {
foundSchemeMatch = true;
}
if (skipExternalUriHosts_.size() > 0) {
for (String host : skipExternalUriHosts_) {
String externalHost = data.getHost();
if (externalHost != null && externalHost.equals(host)) {
skipThisHost = true;
break;
}
}
}
if (foundSchemeMatch && !skipThisHost) {
sessionReferredLink_ = data.toString();
prefHelper_.setExternalIntentUri(data.toString());
if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) {
Bundle bundle = activity.getIntent().getExtras();
Set<String> extraKeys = bundle.keySet();
if (extraKeys.size() > 0) {
JSONObject extrasJson = new JSONObject();
for (String key : EXTERNAL_INTENT_EXTRA_KEY_WHITE_LIST) {
if (extraKeys.contains(key)) {
extrasJson.put(key, bundle.get(key));
}
}
if (extrasJson.length() > 0) {
prefHelper_.setExternalIntentExtra(extrasJson.toString());
}
}
}
}
}
} catch (Exception ignore) {
}
//Check for any push identifier in case app is launched by a push notification
try {
if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) {
if (!isIntentParamsAlreadyConsumed(activity)) {
String pushIdentifier = activity.getIntent().getExtras().getString(Defines.Jsonkey.AndroidPushNotificationKey.getKey()); // This seems producing unmarshalling errors in some corner cases
if (pushIdentifier != null && pushIdentifier.length() > 0) {
prefHelper_.setPushIdentifier(pushIdentifier);
Intent thisIntent = activity.getIntent();
thisIntent.putExtra(Defines.Jsonkey.BranchLinkUsed.getKey(), true);
activity.setIntent(thisIntent);
return false;
}
}
}
} catch (Exception ignore) {
}
//Check for link click id or app link
// On Launching app from the recent apps, Android Start the app with the original intent data. So up in opening app from recent list
// Intent will have App link in data and lead to issue of getting wrong parameters. (In case of link click id since we are looking for actual link click on back end this case will never happen)
if (data != null && data.isHierarchical() && activity != null && !isActivityLaunchedFromHistory(activity)) {
try {
if (data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()) != null) {
prefHelper_.setLinkClickIdentifier(data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()));
String paramString = "link_click_id=" + data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey());
String uriString = null;
if (activity.getIntent() != null) {
uriString = activity.getIntent().getDataString();
}
if (data.getQuery().length() == paramString.length()) {
paramString = "\\?" + paramString;
} else if (uriString != null && (uriString.length() - paramString.length()) == uriString.indexOf(paramString)) {
paramString = "&" + paramString;
} else {
paramString = paramString + "&";
}
if (uriString != null) {
Uri newData = Uri.parse(uriString.replaceFirst(paramString, ""));
activity.getIntent().setData(newData);
activity.getIntent().putExtra(Defines.Jsonkey.BranchLinkUsed.getKey(), true);
} else {
Log.w(TAG, "Branch Warning. URI for the launcher activity is null. Please make sure that intent data is not set to null before calling Branch#InitSession ");
}
return true;
} else {
// Check if the clicked url is an app link pointing to this app
String scheme = data.getScheme();
Intent intent = activity.getIntent();
if (scheme != null && intent != null) {
if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))
&& data.getHost() != null && data.getHost().length() > 0 && !isIntentParamsAlreadyConsumed(activity)) {
prefHelper_.setAppLink(data.toString());
intent.putExtra(Defines.Jsonkey.BranchLinkUsed.getKey(), true);
activity.setIntent(intent);
return false;
}
}
}
} catch (Exception ignore) {
}
}
}
return false;
}
private boolean isIntentParamsAlreadyConsumed(Activity activity) {
return activity != null && activity.getIntent() != null && activity.getIntent().getBooleanExtra(Defines.Jsonkey.BranchLinkUsed.getKey(), false);
}
private boolean isActivityLaunchedFromHistory(Activity activity) {
return activity != null && activity.getIntent() != null && (activity.getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0;
}
@Override
public void onGAdsFetchFinished() {
isGAParamsFetchInProgress_ = false;
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK);
if (performCookieBasedStrongMatchingOnGAIDAvailable) {
performCookieBasedStrongMatch();
performCookieBasedStrongMatchingOnGAIDAvailable = false;
} else {
processNextQueueItem();
}
}
@Override
public void onInstallReferrerEventsFinished() {
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.INSTALL_REFERRER_FETCH_WAIT_LOCK);
processNextQueueItem();
}
/**
* Add the given URI Scheme to the external Uri white list. Branch will collect
* external intent uri only if white list matches with the app opened URL properties
* If no URI is added to the white list branch will collect all external intent uris.
* White list schemes should be added immediately after calling {@link Branch#getAutoInstance(Context)}
*
* @param uriScheme {@link String} Case sensitive Uri scheme to be added to the external intent uri white list.(eg. "my_scheme://")
* @return {@link Branch} instance for successive method calls
*/
public Branch addWhiteListedScheme(String uriScheme) {
if (uriScheme == null) {
return this;
}
uriScheme = uriScheme.replace(":
externalUriWhiteList_.add(uriScheme);
return this;
}
/**
* <p>Set the given list of URI Scheme as the external Uri white list. Branch will collect
* external intent uri only for Uris in white list.
* </p>
* If no URI is added to the white list branch will collect all external intent uris
* White list should be set immediately after calling {@link Branch#getAutoInstance(Context)}
* <!-- @param uriSchemes {@link List<String>} List of case sensitive Uri schemes to set as the white list -->
*
* @return {@link Branch} instance for successive method calls
*/
public Branch setWhiteListedSchemes(List<String> uriSchemes) {
externalUriWhiteList_ = uriSchemes;
return this;
}
* @param hostName {@link String} Case sensitive Uri path to be added to the external Intent uri skip list. (e.g. "product" to skip my-scheme://product/*)
* @return {@link Branch} instance for successive method calls
*/
public Branch addUriHostsToSkip(String hostName) {
if ((hostName != null) && (!hostName.equals("")))
skipExternalUriHosts_.add(hostName);
return this;
}
/**
* <p>Identifies the current user to the Branch API by supplying a unique identifier as a
* {@link String} value. No callback.</p>
*
* @param userId A {@link String} value containing the unique identifier of the user.
*/
public void setIdentity(@NonNull String userId) {
setIdentity(userId, null);
}
/**
* <p>Identifies the current user to the Branch API by supplying a unique identifier as a
* {@link String} value, with a callback specified to perform a defined action upon successful
* response to request.</p>
*
* @param userId A {@link String} value containing the unique identifier of the user.
* @param callback A {@link BranchReferralInitListener} callback instance that will return
* the data associated with the user id being assigned, if available.
*/
public void setIdentity(@NonNull String userId, @Nullable BranchReferralInitListener
callback) {
ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
} else {
if (((ServerRequestIdentifyUserRequest) req).isExistingID()) {
((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_);
}
}
}
/**
* Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs.
* If you call setIdentity, this device will have that identity associated with this user until logout is called.
* This includes persisting through uninstalls, as we track device id.
*
* @return A {@link Boolean} value that will return <i>true</i> only if user already has an identity.
*/
public boolean isUserIdentified() {
return !prefHelper_.getIdentity().equals(PrefHelper.NO_STRING_VALUE);
}
/**
* <p>This method should be called if you know that a different person is about to use the app. For example,
* if you allow users to log out and let their friend use the app, you should call this to notify Branch
* to create a new user for this device. This will clear the first and latest params, as a new session is created.</p>
*/
public void logout() {
logout(null);
}
/**
* <p>This method should be called if you know that a different person is about to use the app. For example,
* if you allow users to log out and let their friend use the app, you should call this to notify Branch
* to create a new user for this device. This will clear the first and latest params, as a new session is created.</p>
*
* @param callback An instance of {@link io.branch.referral.Branch.LogoutStatusListener} to callback with the logout operation status.
*/
public void logout(LogoutStatusListener callback) {
ServerRequest req = new ServerRequestLogout(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Fire-and-forget retrieval of rewards for the current session. Without a callback.</p>
*/
public void loadRewards() {
loadRewards(null);
}
/**
* <p>Retrieves rewards for the current session, with a callback to perform a predefined
* action following successful report of state change. You'll then need to call getCredits
* in the callback to update the credit totals in your UX.</p>
*
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a referral state change.
*/
public void loadRewards(BranchReferralStateChangedListener callback) {
ServerRequest req = new ServerRequestGetRewards(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Retrieve the number of credits available for the "default" bucket.</p>
*
* @return An {@link Integer} value of the number credits available in the "default" bucket.
*/
public int getCredits() {
return prefHelper_.getCreditCount();
}
/**
* Returns an {@link Integer} of the number of credits available for use within the supplied
* bucket name.
*
* @param bucket A {@link String} value indicating the name of the bucket to get credits for.
* @return An {@link Integer} value of the number credits available in the specified
* bucket.
*/
public int getCreditsForBucket(String bucket) {
return prefHelper_.getCreditCount(bucket);
}
/**
* <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the bucket.
*/
public void redeemRewards(int count) {
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, null);
}
/**
* <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the bucket.
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a executing redeem rewards.
*/
public void redeemRewards(int count, BranchReferralStateChangedListener callback) {
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback);
}
/**
* <p>Redeems the specified number of credits from the named bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket to attempt
* to redeem credits from.
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the specified bucket.
*/
public void redeemRewards(@NonNull final String bucket, final int count) {
redeemRewards(bucket, count, null);
}
/**
* <p>Redeems the specified number of credits from the named bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket to attempt
* to redeem credits from.
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the specified bucket.
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a executing redeem rewards.
*/
public void redeemRewards(@NonNull final String bucket,
final int count, BranchReferralStateChangedListener callback) {
ServerRequestRedeemRewards req = new ServerRequestRedeemRewards(context_, bucket, count, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(BranchListResponseListener callback) {
getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket that the
* code will belong to.
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(@NonNull final String bucket, BranchListResponseListener
callback) {
getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param afterId A {@link String} value containing the ID of the history record to begin after.
* This allows for a partial history to be retrieved, rather than the entire
* credit history of the bucket.
* @param length A {@link Integer} value containing the number of credit history records to
* return.
* @param order A {@link CreditHistoryOrder} object indicating which order the results should
* be returned in.
* <p>Valid choices:</p>
* <ul>
* <li>{@link CreditHistoryOrder#kMostRecentFirst}</li>
* <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li>
* </ul>
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(@NonNull final String afterId, final int length,
@NonNull final CreditHistoryOrder order, BranchListResponseListener callback) {
getCreditHistory(null, afterId, length, order, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket that the
* code will belong to.
* @param afterId A {@link String} value containing the ID of the history record to begin after.
* This allows for a partial history to be retrieved, rather than the entire
* credit history of the bucket.
* @param length A {@link Integer} value containing the number of credit history records to
* return.
* @param order A {@link CreditHistoryOrder} object indicating which order the results should
* be returned in.
* <p>Valid choices:</p>
* <ul>
* <li>{@link CreditHistoryOrder#kMostRecentFirst}</li>
* <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li>
* </ul>
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(final String bucket, final String afterId, final int length,
@NonNull final CreditHistoryOrder order, BranchListResponseListener callback) {
ServerRequest req = new ServerRequestGetRewardHistory(context_, bucket, afterId, length, order, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API, with additional app-defined meta data to go along with that action.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
* @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a
* user action that has just been completed.
*/
public void userCompletedAction(@NonNull final String action, JSONObject metadata) {
userCompletedAction(action, metadata, null);
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
*/
public void userCompletedAction(final String action) {
userCompletedAction(action, null, null);
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
* @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events
*/
public void userCompletedAction(final String action, BranchViewHandler.
IBranchViewEvents callback) {
userCompletedAction(action, null, callback);
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API, with additional app-defined meta data to go along with that action.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
* @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a
* user action that has just been completed.
* @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events
*/
public void userCompletedAction(@NonNull final String action, JSONObject
metadata, BranchViewHandler.IBranchViewEvents callback) {
if (metadata != null) {
metadata = BranchUtil.filterOutBadCharacters(metadata);
}
ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
public void sendCommerceEvent(@NonNull CommerceEvent commerceEvent, JSONObject
metadata, BranchViewHandler.IBranchViewEvents callback) {
if (metadata != null) {
metadata = BranchUtil.filterOutBadCharacters(metadata);
}
ServerRequest req = new ServerRequestRActionCompleted(context_, commerceEvent, metadata, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
public void sendCommerceEvent(@NonNull CommerceEvent commerceEvent) {
sendCommerceEvent(commerceEvent, null, null);
}
/**
* <p>Returns the parameters associated with the link that referred the user. This is only set once,
* the first time the user is referred by a link. Think of this as the user referral parameters.
* It is also only set if isReferrable is equal to true, which by default is only true
* on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the
* user already exists from a previous device) and logout.</p>
*
* @return A {@link JSONObject} containing the install-time parameters as configured
* locally.
*/
public JSONObject getFirstReferringParams() {
String storedParam = prefHelper_.getInstallParams();
JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam);
firstReferringParams = appendDebugParams(firstReferringParams);
return firstReferringParams;
}
/**
* <p>This function must be called from a non-UI thread! If Branch has no install link data,
* and this func is called, it will return data upon initializing, or until LATCH_WAIT_UNTIL.
* Returns the parameters associated with the link that referred the user. This is only set once,
* the first time the user is referred by a link. Think of this as the user referral parameters.
* It is also only set if isReferrable is equal to true, which by default is only true
* on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the
* user already exists from a previous device) and logout.</p>
*
* @return A {@link JSONObject} containing the install-time parameters as configured
* locally.
*/
public JSONObject getFirstReferringParamsSync() {
getFirstReferringParamsLatch = new CountDownLatch(1);
if (prefHelper_.getInstallParams().equals(PrefHelper.NO_STRING_VALUE)) {
try {
getFirstReferringParamsLatch.await(LATCH_WAIT_UNTIL, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
}
String storedParam = prefHelper_.getInstallParams();
JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam);
firstReferringParams = appendDebugParams(firstReferringParams);
getFirstReferringParamsLatch = null;
return firstReferringParams;
}
/**
* <p>Returns the parameters associated with the link that referred the session. If a user
* clicks a link, and then opens the app, initSession will return the parameters of the link
* and then set them in as the latest parameters to be retrieved by this method. By default,
* sessions persist for the duration of time that the app is in focus. For example, if you
* minimize the app, these parameters will be cleared when closeSession is called.</p>
*
* @return A {@link JSONObject} containing the latest referring parameters as
* configured locally.
*/
public JSONObject getLatestReferringParams() {
String storedParam = prefHelper_.getSessionParams();
JSONObject latestParams = convertParamsStringToDictionary(storedParam);
latestParams = appendDebugParams(latestParams);
return latestParams;
}
/**
* <p>This function must be called from a non-UI thread! If Branch has not been initialized
* and this func is called, it will return data upon initialization, or until LATCH_WAIT_UNTIL.
* Returns the parameters associated with the link that referred the session. If a user
* clicks a link, and then opens the app, initSession will return the parameters of the link
* and then set them in as the latest parameters to be retrieved by this method. By default,
* sessions persist for the duration of time that the app is in focus. For example, if you
* minimize the app, these parameters will be cleared when closeSession is called.</p>
*
* @return A {@link JSONObject} containing the latest referring parameters as
* configured locally.
*/
public JSONObject getLatestReferringParamsSync() {
getLatestReferringParamsLatch = new CountDownLatch(1);
try {
if (initState_ != SESSION_STATE.INITIALISED) {
getLatestReferringParamsLatch.await(LATCH_WAIT_UNTIL, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
}
String storedParam = prefHelper_.getSessionParams();
JSONObject latestParams = convertParamsStringToDictionary(storedParam);
latestParams = appendDebugParams(latestParams);
getLatestReferringParamsLatch = null;
return latestParams;
}
/**
* Append the deep link debug params to the original params
*
* @param originalParams A {@link JSONObject} original referrer parameters
* @return A new {@link JSONObject} with debug params appended.
*/
private JSONObject appendDebugParams(JSONObject originalParams) {
try {
if (originalParams != null && deeplinkDebugParams_ != null) {
if (deeplinkDebugParams_.length() > 0) {
Log.w(TAG, "You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link");
}
Iterator<String> keys = deeplinkDebugParams_.keys();
while (keys.hasNext()) {
String key = keys.next();
originalParams.put(key, deeplinkDebugParams_.get(key));
}
}
} catch (Exception ignore) {
}
return originalParams;
}
public JSONObject getDeeplinkDebugParams() {
if (deeplinkDebugParams_ != null && deeplinkDebugParams_.length() > 0) {
Log.w(TAG, "You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link");
}
return deeplinkDebugParams_;
}
/**
* <p> Generates a shorl url for the given {@link ServerRequestCreateUrl} object </p>
*
* @param req An instance of {@link ServerRequestCreateUrl} with parameters create the short link.
* @return A url created with the given request if the request is synchronous else null.
* Note : This method can be used only internally. Use {@link BranchUrlBuilder} for creating short urls.
*/
String generateShortLinkInternal(ServerRequestCreateUrl req) {
if (!req.constructError_ && !req.handleErrors(context_)) {
if (linkCache_.containsKey(req.getLinkPost())) {
String url = linkCache_.get(req.getLinkPost());
req.onUrlAvailable(url);
return url;
} else {
if (req.isAsync()) {
generateShortLinkAsync(req);
} else {
return generateShortLinkSync(req);
}
}
}
return null;
}
/**
* <p>Creates options for sharing a link with other Applications. Creates a link with given attributes and shares with the
* user selected clients.</p>
*
* @param builder A {@link io.branch.referral.Branch.ShareLinkBuilder} instance to build share link.
*/
private void shareLink(ShareLinkBuilder builder) {
//Cancel any existing sharing in progress.
if (shareLinkManager_ != null) {
shareLinkManager_.cancelShareLinkDialog(true);
}
shareLinkManager_ = new ShareLinkManager();
shareLinkManager_.shareLink(builder);
}
/**
* <p>Cancel current share link operation and Application selector dialog. If your app is not using auto session management, make sure you are
* calling this method before your activity finishes inorder to prevent any window leak. </p>
*
* @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation.
* A value of true will close the dialog with an animation. Setting this value
* to false will close the Dialog immediately.
*/
public void cancelShareLinkDialog(boolean animateClose) {
if (shareLinkManager_ != null) {
shareLinkManager_.cancelShareLinkDialog(animateClose);
}
}
// PRIVATE FUNCTIONS
private String convertDate(Date date) {
return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString();
}
private String generateShortLinkSync(ServerRequestCreateUrl req) {
if (initState_ == SESSION_STATE.INITIALISED) {
ServerResponse response = null;
try {
int timeOut = prefHelper_.getTimeout() + 2000; // Time out is set to slightly more than link creation time to prevent any edge case
response = new getShortLinkTask().execute(req).get(timeOut, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ignore) {
}
String url = null;
if (req.isDefaultToLongUrl()) {
url = req.getLongUrl();
}
if (response != null && response.getStatusCode() == HttpURLConnection.HTTP_OK) {
try {
url = response.getObject().getString("url");
if (req.getLinkPost() != null) {
linkCache_.put(req.getLinkPost(), url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return url;
} else {
Log.i("BranchSDK", "Branch Warning: User session has not been initialized");
}
return null;
}
private void generateShortLinkAsync(final ServerRequest req) {
handleNewRequest(req);
}
private JSONObject convertParamsStringToDictionary(String paramString) {
if (paramString.equals(PrefHelper.NO_STRING_VALUE)) {
return new JSONObject();
} else {
try {
return new JSONObject(paramString);
} catch (JSONException e) {
byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP);
try {
return new JSONObject(new String(encodedArray));
} catch (JSONException ex) {
ex.printStackTrace();
return new JSONObject();
}
}
}
}
private void processNextQueueItem() {
try {
serverSema_.acquire();
if (networkCount_ == 0 && requestQueue_.getSize() > 0) {
networkCount_ = 1;
ServerRequest req = requestQueue_.peek();
serverSema_.release();
if (req != null) {
if (!req.isWaitingOnProcessToFinish()) {
// All request except Install request need a valid IdentityID
if (!(req instanceof ServerRequestRegisterInstall) && !hasUser()) {
Log.i("BranchSDK", "Branch Error: User session has not been initialized!");
networkCount_ = 0;
handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION);
}
//All request except open and install need a session to execute
else if (!(req instanceof ServerRequestInitSession) && (!hasSession() || !hasDeviceFingerPrint())) {
networkCount_ = 0;
handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION);
} else {
BranchPostTask postTask = new BranchPostTask(req);
postTask.executeTask();
}
} else {
networkCount_ = 0;
}
} else {
requestQueue_.remove(null); //In case there is any request nullified remove it.
}
} else {
serverSema_.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handleFailure(int index, int statusCode) {
ServerRequest req;
if (index >= requestQueue_.getSize()) {
req = requestQueue_.peekAt(requestQueue_.getSize() - 1);
} else {
req = requestQueue_.peekAt(index);
}
handleFailure(req, statusCode);
}
private void handleFailure(final ServerRequest req, int statusCode) {
if (req == null)
return;
req.handleFailure(statusCode, "");
}
private void updateAllRequestsInQueue() {
try {
for (int i = 0; i < requestQueue_.getSize(); i++) {
ServerRequest req = requestQueue_.peekAt(i);
if (req != null) {
JSONObject reqJson = req.getPost();
if (reqJson != null) {
if (reqJson.has(Defines.Jsonkey.SessionID.getKey())) {
req.getPost().put(Defines.Jsonkey.SessionID.getKey(), prefHelper_.getSessionID());
}
if (reqJson.has(Defines.Jsonkey.IdentityID.getKey())) {
req.getPost().put(Defines.Jsonkey.IdentityID.getKey(), prefHelper_.getIdentityID());
}
if (reqJson.has(Defines.Jsonkey.DeviceFingerprintID.getKey())) {
req.getPost().put(Defines.Jsonkey.DeviceFingerprintID.getKey(), prefHelper_.getDeviceFingerPrintID());
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private boolean hasSession() {
return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasDeviceFingerPrint() {
return !prefHelper_.getDeviceFingerPrintID().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasUser() {
return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE);
}
private void insertRequestAtFront(ServerRequest req) {
if (networkCount_ == 0) {
requestQueue_.insert(req, 0);
} else {
requestQueue_.insert(req, 1);
}
}
private void registerInstallOrOpen(ServerRequest req, BranchReferralInitListener callback) {
// If there isn't already an Open / Install request, add one to the queue
if (!requestQueue_.containsInstallOrOpen()) {
insertRequestAtFront(req);
}
// If there is already one in the queue, make sure it's in the front.
// Make sure a callback is associated with this request. This callback can
// be cleared if the app is terminated while an Open/Install is pending.
else {
// Update the callback to the latest one in init session call
if (callback != null) {
requestQueue_.setInstallOrOpenCallback(callback);
}
requestQueue_.moveInstallOrOpenToFront(req, networkCount_, callback);
}
processNextQueueItem();
}
private void initializeSession(final BranchReferralInitListener callback) {
if ((prefHelper_.getBranchKey() == null || prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))) {
initState_ = SESSION_STATE.UNINITIALISED;
//Report Key error on callback
if (callback != null) {
callback.onInitFinished(null, new BranchError("Trouble initializing Branch.", BranchError.ERR_BRANCH_KEY_INVALID));
}
Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's res/values/strings.xml!");
return;
} else if (prefHelper_.getBranchKey() != null && prefHelper_.getBranchKey().startsWith("key_test_")) {
Log.i("BranchSDK", "Branch Warning: You are using your test app's Branch Key. Remember to change it to live Branch Key during deployment.");
}
if (!prefHelper_.getExternalIntentUri().equals(PrefHelper.NO_STRING_VALUE) || !enableFacebookAppLinkCheck_) {
registerAppInit(callback, null);
} else {
// Check if opened by facebook with deferred install data
boolean appLinkRqSucceeded;
appLinkRqSucceeded = DeferredAppLinkDataHandler.fetchDeferredAppLinkData(context_, new DeferredAppLinkDataHandler.AppLinkFetchEvents() {
@Override
public void onAppLinkFetchFinished(String nativeAppLinkUrl) {
prefHelper_.setIsAppLinkTriggeredInit(true); // callback returns when app link fetch finishes with success or failure. Report app link checked in both cases
if (nativeAppLinkUrl != null) {
Uri appLinkUri = Uri.parse(nativeAppLinkUrl);
String bncLinkClickId = appLinkUri.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey());
if (!TextUtils.isEmpty(bncLinkClickId)) {
prefHelper_.setLinkClickIdentifier(bncLinkClickId);
}
}
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.FB_APP_LINK_WAIT_LOCK);
processNextQueueItem();
}
});
if (appLinkRqSucceeded) {
registerAppInit(callback, ServerRequest.PROCESS_WAIT_LOCK.FB_APP_LINK_WAIT_LOCK);
} else {
registerAppInit(callback, null);
}
}
}
private void registerAppInit(BranchReferralInitListener
callback, ServerRequest.PROCESS_WAIT_LOCK lock) {
ServerRequest request;
if (hasUser()) {
// If there is user this is open
request = new ServerRequestRegisterOpen(context_, callback, systemObserver_);
} else {
// If no user this is an Install
request = new ServerRequestRegisterInstall(context_, callback, systemObserver_, InstallListener.getInstallationID());
}
request.addProcessWaitLock(lock);
if (isGAParamsFetchInProgress_) {
request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK);
}
if (intentState_ != INTENT_STATE.READY) {
request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.INTENT_PENDING_WAIT_LOCK);
}
if (checkInstallReferrer_ && request instanceof ServerRequestRegisterInstall) {
request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.INSTALL_REFERRER_FETCH_WAIT_LOCK);
InstallListener.captureInstallReferrer(playStoreReferrerFetchTime);
}
registerInstallOrOpen(request, callback);
}
private void onIntentReady(Activity activity, boolean grabIntentParams) {
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.INTENT_PENDING_WAIT_LOCK);
//if (activity.getIntent() != null) {
if (grabIntentParams) {
Uri intentData = activity.getIntent().getData();
readAndStripParam(intentData, activity);
if (cookieBasedMatchDomain_ != null && prefHelper_.getBranchKey() != null && !prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) {
if (isGAParamsFetchInProgress_) {
// Wait for GAID to Available
performCookieBasedStrongMatchingOnGAIDAvailable = true;
} else {
performCookieBasedStrongMatch();
}
} else {
processNextQueueItem();
}
} else {
processNextQueueItem();
}
}
private void performCookieBasedStrongMatch() {
boolean simulateInstall = (prefHelper_.getExternDebug() || isSimulatingInstalls());
DeviceInfo deviceInfo = DeviceInfo.getInstance(simulateInstall, systemObserver_, disableDeviceIDFetch_);
Activity currentActivity = null;
if (currentActivityReference_ != null) {
currentActivity = currentActivityReference_.get();
}
Context context = (currentActivity != null) ? currentActivity.getApplicationContext() : null;
if (context != null) {
requestQueue_.setStrongMatchWaitLock();
BranchStrongMatchHelper.getInstance().checkForStrongMatch(context, cookieBasedMatchDomain_, deviceInfo, prefHelper_, systemObserver_, new BranchStrongMatchHelper.StrongMatchCheckEvents() {
@Override
public void onStrongMatchCheckFinished() {
requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.STRONG_MATCH_PENDING_WAIT_LOCK);
processNextQueueItem();
}
});
}
}
/**
* Handles execution of a new request other than open or install.
* Checks for the session initialisation and adds a install/Open request in front of this request
* if the request need session to execute.
*
* @param req The {@link ServerRequest} to execute
*/
public void handleNewRequest(ServerRequest req) {
//If not initialised put an open or install request in front of this request(only if this needs session)
if (initState_ != SESSION_STATE.INITIALISED && !(req instanceof ServerRequestInitSession)) {
if ((req instanceof ServerRequestLogout)) {
req.handleFailure(BranchError.ERR_NO_SESSION, "");
Log.i(TAG, "Branch is not initialized, cannot logout");
return;
}
if ((req instanceof ServerRequestRegisterClose)) {
Log.i(TAG, "Branch is not initialized, cannot close session");
return;
} else {
Activity currentActivity = null;
if (currentActivityReference_ != null) {
currentActivity = currentActivityReference_.get();
}
if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) {
initUserSessionInternal((BranchReferralInitListener) null, currentActivity, true);
} else {
boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE;
initUserSessionInternal((BranchReferralInitListener) null, currentActivity, isReferrable);
}
}
}
requestQueue_.enqueue(req);
req.onRequestQueued();
processNextQueueItem();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setActivityLifeCycleObserver(Application application) {
try {
BranchActivityLifeCycleObserver activityLifeCycleObserver = new BranchActivityLifeCycleObserver();
/* Set an observer for activity life cycle events. */
application.unregisterActivityLifecycleCallbacks(activityLifeCycleObserver);
application.registerActivityLifecycleCallbacks(activityLifeCycleObserver);
isActivityLifeCycleCallbackRegistered_ = true;
} catch (NoSuchMethodError | NoClassDefFoundError Ex) {
isActivityLifeCycleCallbackRegistered_ = false;
isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(TAG, new BranchError("", BranchError.ERR_API_LVL_14_NEEDED).getMessage());
}
}
/**
* <p>Class that observes activity life cycle events and determines when to start and stop
* session.</p>
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private class BranchActivityLifeCycleObserver implements Application.ActivityLifecycleCallbacks {
private int activityCnt_ = 0; //Keep the count of live activities.
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
intentState_ = handleDelayedNewIntents_ ? INTENT_STATE.PENDING : INTENT_STATE.READY;
isActivityCreatedAndLaunched = true;
if (BranchViewHandler.getInstance().isInstallOrOpenBranchViewPending(activity.getApplicationContext())) {
BranchViewHandler.getInstance().showPendingBranchView(activity);
}
}
@Override
public void onActivityStarted(Activity activity) {
intentState_ = handleDelayedNewIntents_ ? INTENT_STATE.PENDING : INTENT_STATE.READY;
// If configured on dashboard, trigger content discovery runnable
if (initState_ == SESSION_STATE.INITIALISED) {
try {
ContentDiscoverer.getInstance().discoverContent(activity, sessionReferredLink_);
} catch (Exception ignore) {
}
}
if (activityCnt_ < 1) { // Check if this is the first Activity.If so start a session.
if (initState_ == SESSION_STATE.INITIALISED) {
// Handling case : init session completed previously when app was in background.
initState_ = SESSION_STATE.UNINITIALISED;
}
// Check if debug mode is set in manifest. If so enable debug.
if (BranchUtil.isTestModeEnabled(context_)) {
prefHelper_.setExternDebug();
}
prefHelper_.setLogging(getIsLogging());
startSession(activity);
} else if (checkIntentForSessionRestart(activity.getIntent())) { // Case of opening the app by clicking a push notification while app is in foreground
initState_ = SESSION_STATE.UNINITIALISED;
// no need call close here since it is session forced restart. Don't want to wait till close finish
startSession(activity);
}
activityCnt_++;
isActivityCreatedAndLaunched = false;
}
@Override
public void onActivityResumed(Activity activity) {
// Need to check here again for session restart request in case the intent is created while the activity is already running
if (checkIntentForSessionRestart(activity.getIntent())) {
initState_ = SESSION_STATE.UNINITIALISED;
startSession(activity);
}
currentActivityReference_ = new WeakReference<>(activity);
if (handleDelayedNewIntents_) {
intentState_ = INTENT_STATE.READY;
// Grab the intent only for first activity unless this activity is intent to force new session
boolean grabIntentParams = activity.getIntent() != null && initState_ != SESSION_STATE.INITIALISED;
onIntentReady(activity, grabIntentParams);
}
}
@Override
public void onActivityPaused(Activity activity) {
/* Close any opened sharing dialog.*/
if (shareLinkManager_ != null) {
shareLinkManager_.cancelShareLinkDialog(true);
}
}
@Override
public void onActivityStopped(Activity activity) {
ContentDiscoverer.getInstance().onActivityStopped(activity);
activityCnt_--; // Check if this is the last activity. If so, stop the session.
if (activityCnt_ < 1) {
isInstantDeepLinkPossible = false;
closeSessionInternal();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
if (currentActivityReference_ != null && currentActivityReference_.get() == activity) {
currentActivityReference_.clear();
}
BranchViewHandler.getInstance().onCurrentActivityDestroyed(activity);
}
}
private void startSession(Activity activity) {
Uri intentData = null;
if (activity.getIntent() != null) {
intentData = activity.getIntent().getData();
}
isInitReportedThroughCallBack = false;
initSessionWithData(intentData, activity); // indicate starting of session.
}
private boolean checkIntentForSessionRestart(Intent intent) {
boolean isRestartSessionRequested = false;
if (intent != null) {
try {
isRestartSessionRequested = intent.getBooleanExtra(Defines.Jsonkey.ForceNewBranchSession.getKey(), false);
} catch (Throwable ignore) {
}
if (isRestartSessionRequested) {
intent.putExtra(Defines.Jsonkey.ForceNewBranchSession.getKey(), false);
}
}
return isRestartSessionRequested;
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchReferralInitListener}, defining a single method that takes a list of params in
* {@link JSONObject} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see JSONObject
* @see BranchError
*/
public interface BranchReferralInitListener {
void onInitFinished(JSONObject referringParams, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchUniversalReferralInitListener}, defining a single method that provides
* {@link BranchUniversalObject}, {@link LinkProperties} and an error message of {@link BranchError} format that will be
* returned on failure of the request response.
* In case of an error the value for {@link BranchUniversalObject} and {@link LinkProperties} are set to null.</p>
*
* @see BranchUniversalObject
* @see LinkProperties
* @see BranchError
*/
public interface BranchUniversalReferralInitListener {
void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchReferralStateChangedListener}, defining a single method that takes a value of
* {@link Boolean} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see Boolean
* @see BranchError
*/
public interface BranchReferralStateChangedListener {
void onStateChanged(boolean changed, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchLinkCreateListener}, defining a single method that takes a URL
* {@link String} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see String
* @see BranchError
*/
public interface BranchLinkCreateListener {
void onLinkCreate(String url, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchLinkShareListener}, defining methods to listen for link sharing status.</p>
*/
public interface BranchLinkShareListener {
/**
* <p> Callback method to update when share link dialog is launched.</p>
*/
void onShareLinkDialogLaunched();
/**
* <p> Callback method to update when sharing dialog is dismissed.</p>
*/
void onShareLinkDialogDismissed();
/**
* <p> Callback method to update the sharing status. Called on sharing completed or on error.</p>
*
* @param sharedLink The link shared to the channel.
* @param sharedChannel Channel selected for sharing.
* @param error A {@link BranchError} to update errors, if there is any.
*/
void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error);
/**
* <p>Called when user select a channel for sharing a deep link.
* Branch will create a deep link for the selected channel and share with it after calling this
* method. On sharing complete, status is updated by onLinkShareResponse() callback. Consider
* having a sharing in progress UI if you wish to prevent user activity in the window between selecting a channel
* and sharing complete.</p>
*
* @param channelName Name of the selected application to share the link. An empty string is returned if unable to resolve selected client name.
*/
void onChannelSelected(String channelName);
}
/**
* <p>An interface class for customizing sharing properties with selected channel.</p>
*/
public interface IChannelProperties {
/**
* @param channel The name of the channel selected for sharing.
* @return {@link String} with value for the message title for sharing the link with the selected channel
*/
String getSharingTitleForChannel(String channel);
/**
* @param channel The name of the channel selected for sharing.
* @return {@link String} with value for the message body for sharing the link with the selected channel
*/
String getSharingMessageForChannel(String channel);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchListResponseListener}, defining a single method that takes a list of
* {@link JSONArray} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see JSONArray
* @see BranchError
*/
public interface BranchListResponseListener {
void onReceivingResponse(JSONArray list, BranchError error);
}
/**
* <p>
* Callback interface for listening logout status
* </p>
*/
public interface LogoutStatusListener {
/**
* Called on finishing the the logout process
*
* @param loggedOut A {@link Boolean} which is set to true if logout succeeded
* @param error An instance of {@link BranchError} to notify any error occurred during logout.
* A null value is set if logout succeeded.
*/
void onLogoutFinished(boolean loggedOut, BranchError error);
}
/**
* <p>enum containing the sort options for return of credit history.</p>
*/
public enum CreditHistoryOrder {
kMostRecentFirst, kLeastRecentFirst
}
/**
* Async Task to create a shorlink for synchronous methods
*/
private class getShortLinkTask extends AsyncTask<ServerRequest, Void, ServerResponse> {
@Override
protected ServerResponse doInBackground(ServerRequest... serverRequests) {
String urlExtend = "v1/url";
return branchRemoteInterface_.make_restful_post(serverRequests[0].getPost(), prefHelper_.getAPIBaseUrl() + urlExtend, Defines.RequestPath.GetURL.getPath(), prefHelper_.getBranchKey());
}
}
/**
* Asynchronous task handling execution of server requests. Execute the network task on background
* thread and request are executed in sequential manner. Handles the request execution in
* Synchronous-Asynchronous pattern. Should be invoked only form main thread and the results are
* published in the main thread.
*/
private class BranchPostTask extends BranchAsyncTask<Void, Void, ServerResponse> {
ServerRequest thisReq_;
public BranchPostTask(ServerRequest request) {
thisReq_ = request;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
thisReq_.onPreExecute();
// Update request metadata
thisReq_.updateRequestMetadata();
}
@Override
protected ServerResponse doInBackground(Void... voids) {
if (thisReq_ instanceof ServerRequestInitSession) {
((ServerRequestInitSession) thisReq_).updateLinkReferrerParams();
}
// update queue wait time
addExtraInstrumentationData(thisReq_.getRequestPath() + "-" + Defines.Jsonkey.Queue_Wait_Time.getKey(), String.valueOf(thisReq_.getQueueWaitTime()));
//Google ADs ID and LAT value are updated using reflection. These method need background thread
//So updating them for install and open on background thread.
if (thisReq_.isGAdsParamsRequired() && !BranchUtil.isTestModeEnabled(context_)) {
thisReq_.updateGAdsParams(systemObserver_, thisReq_.getBranchRemoteAPIVersion());
}
if (thisReq_.isGetRequest()) {
return branchRemoteInterface_.make_restful_get(thisReq_.getRequestUrl(), thisReq_.getGetParams(), thisReq_.getRequestPath(), prefHelper_.getBranchKey());
} else {
return branchRemoteInterface_.make_restful_post(thisReq_.getPostWithInstrumentationValues(instrumentationExtraData_), thisReq_.getRequestUrl(), thisReq_.getRequestPath(), prefHelper_.getBranchKey());
}
}
@Override
protected void onPostExecute(ServerResponse serverResponse) {
super.onPostExecute(serverResponse);
if (serverResponse != null) {
try {
int status = serverResponse.getStatusCode();
hasNetwork_ = true;
//If the request is not succeeded
if (status != 200) {
//If failed request is an initialisation request then mark session not initialised
if (thisReq_ instanceof ServerRequestInitSession) {
initState_ = SESSION_STATE.UNINITIALISED;
}
// On a bad request notify with call back and remove the request.
if (status == 409) {
requestQueue_.remove(thisReq_);
if (thisReq_ instanceof ServerRequestCreateUrl) {
((ServerRequestCreateUrl) thisReq_).handleDuplicateURLError();
} else {
Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API");
handleFailure(0, status);
}
}
//On Network error or Branch is down fail all the pending requests in the queue except
//for request which need to be replayed on failure.
else {
hasNetwork_ = false;
//Collect all request from the queue which need to be failed.
ArrayList<ServerRequest> requestToFail = new ArrayList<>();
for (int i = 0; i < requestQueue_.getSize(); i++) {
requestToFail.add(requestQueue_.peekAt(i));
}
//Remove the requests from the request queue first
for (ServerRequest req : requestToFail) {
if (req == null || !req.shouldRetryOnFail()) { // Should remove any nullified request object also from queue
requestQueue_.remove(req);
}
}
// Then, set the network count to zero, indicating that requests can be started again.
networkCount_ = 0;
//Finally call the request callback with the error.
for (ServerRequest req : requestToFail) {
if (req != null) {
req.handleFailure(status, serverResponse.getFailReason());
//If request need to be replayed, no need for the callbacks
if (req.shouldRetryOnFail())
req.clearCallbacks();
}
}
}
}
//If the request succeeded
else {
hasNetwork_ = true;
//On create new url cache the url.
if (thisReq_ instanceof ServerRequestCreateUrl) {
if (serverResponse.getObject() != null) {
final String url = serverResponse.getObject().getString("url");
// cache the link
linkCache_.put(((ServerRequestCreateUrl) thisReq_).getLinkPost(), url);
}
}
//On Logout clear the link cache and all pending requests
else if (thisReq_ instanceof ServerRequestLogout) {
linkCache_.clear();
requestQueue_.clear();
}
requestQueue_.dequeue();
// If this request changes a session update the session-id to queued requests.
if (thisReq_ instanceof ServerRequestInitSession
|| thisReq_ instanceof ServerRequestIdentifyUserRequest) {
// Immediately set session and Identity and update the pending request with the params
JSONObject respJson = serverResponse.getObject();
if (respJson != null) {
boolean updateRequestsInQueue = false;
if (respJson.has(Defines.Jsonkey.SessionID.getKey())) {
prefHelper_.setSessionID(respJson.getString(Defines.Jsonkey.SessionID.getKey()));
updateRequestsInQueue = true;
}
if (respJson.has(Defines.Jsonkey.IdentityID.getKey())) {
String new_Identity_Id = respJson.getString(Defines.Jsonkey.IdentityID.getKey());
if (!prefHelper_.getIdentityID().equals(new_Identity_Id)) {
//On setting a new identity Id clear the link cache
linkCache_.clear();
prefHelper_.setIdentityID(respJson.getString(Defines.Jsonkey.IdentityID.getKey()));
updateRequestsInQueue = true;
}
}
if (respJson.has(Defines.Jsonkey.DeviceFingerprintID.getKey())) {
prefHelper_.setDeviceFingerPrintID(respJson.getString(Defines.Jsonkey.DeviceFingerprintID.getKey()));
updateRequestsInQueue = true;
}
if (updateRequestsInQueue) {
updateAllRequestsInQueue();
}
if (thisReq_ instanceof ServerRequestInitSession) {
initState_ = SESSION_STATE.INITIALISED;
thisReq_.onRequestSucceeded(serverResponse, branchReferral_);
if (!isInitReportedThroughCallBack) {
if (!((ServerRequestInitSession) thisReq_).handleBranchViewIfAvailable((serverResponse))) {
checkForAutoDeepLinkConfiguration();
}
}
// Publish success to listeners
if (((ServerRequestInitSession) thisReq_).hasCallBack()) {
isInitReportedThroughCallBack = true;
}
// Count down the latch holding getLatestReferringParamsSync
if (getLatestReferringParamsLatch != null) {
getLatestReferringParamsLatch.countDown();
}
// Count down the latch holding getFirstReferringParamsSync
if (getFirstReferringParamsLatch != null) {
getFirstReferringParamsLatch.countDown();
}
} else {
// For setting identity just call only request succeeded
thisReq_.onRequestSucceeded(serverResponse, branchReferral_);
}
}
} else {
//Publish success to listeners
thisReq_.onRequestSucceeded(serverResponse, branchReferral_);
}
}
networkCount_ = 0;
if (hasNetwork_ && initState_ != SESSION_STATE.UNINITIALISED) {
processNextQueueItem();
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
}
/**
* <p>Checks if an activity is launched by Branch auto deep link feature. Branch launches activitie configured for auto deep link on seeing matching keys.
* Keys for auto deep linking should be specified to each activity as a meta data in manifest.</p>
* Configure your activity in your manifest to enable auto deep linking as follows
* <!--
* <activity android:name=".YourActivity">
* <meta-data android:name="io.branch.sdk.auto_link" android:value="DeepLinkKey1","DeepLinkKey2" />
* </activity>
* -->
*
* @param activity Instance of activity to check if launched on auto deep link.
* @return A {Boolean} value whose value is true if this activity is launched by Branch auto deeplink feature.
*/
public static boolean isAutoDeepLinkLaunch(Activity activity) {
return (activity.getIntent().getStringExtra(AUTO_DEEP_LINKED) != null);
}
private void checkForAutoDeepLinkConfiguration() {
JSONObject latestParams = getLatestReferringParams();
String deepLinkActivity = null;
try {
//Check if the application is launched by clicking a Branch link.
if (!latestParams.has(Defines.Jsonkey.Clicked_Branch_Link.getKey())
|| !latestParams.getBoolean(Defines.Jsonkey.Clicked_Branch_Link.getKey())) {
return;
}
if (latestParams.length() > 0) {
// Check if auto deep link is disabled.
ApplicationInfo appInfo = context_.getPackageManager().getApplicationInfo(context_.getPackageName(), PackageManager.GET_META_DATA);
if (appInfo.metaData != null && appInfo.metaData.getBoolean(AUTO_DEEP_LINK_DISABLE, false)) {
return;
}
PackageInfo info = context_.getPackageManager().getPackageInfo(context_.getPackageName(), PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
ActivityInfo[] activityInfos = info.activities;
int deepLinkActivityReqCode = DEF_AUTO_DEEP_LINK_REQ_CODE;
if (activityInfos != null) {
for (ActivityInfo activityInfo : activityInfos) {
if (activityInfo != null && activityInfo.metaData != null && (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null || activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null)) {
if (checkForAutoDeepLinkKeys(latestParams, activityInfo) || checkForAutoDeepLinkPath(latestParams, activityInfo)) {
deepLinkActivity = activityInfo.name;
deepLinkActivityReqCode = activityInfo.metaData.getInt(AUTO_DEEP_LINK_REQ_CODE, DEF_AUTO_DEEP_LINK_REQ_CODE);
break;
}
}
}
}
if (deepLinkActivity != null && currentActivityReference_ != null) {
Activity currentActivity = currentActivityReference_.get();
if (currentActivity != null) {
Intent intent = new Intent(currentActivity, Class.forName(deepLinkActivity));
intent.putExtra(AUTO_DEEP_LINKED, "true");
// Put the raw JSON params as extra in case need to get the deep link params as JSON String
intent.putExtra(Defines.Jsonkey.ReferringData.getKey(), latestParams.toString());
// Add individual parameters in the data
Iterator<?> keys = latestParams.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
intent.putExtra(key, latestParams.getString(key));
}
currentActivity.startActivityForResult(intent, deepLinkActivityReqCode);
} else {
// This case should not happen. Adding a safe handling for any corner case
Log.w(TAG, "No activity reference to launch deep linked activity");
}
}
}
} catch (final PackageManager.NameNotFoundException e) {
Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct!");
} catch (ClassNotFoundException e) {
Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct! Error while looking for activity " + deepLinkActivity);
} catch (Exception ignore) {
// Can get TransactionTooLarge Exception here if the Application info exceeds 1mb binder data limit. Usually results with manifest merge from SDKs
}
}
private boolean checkForAutoDeepLinkKeys(JSONObject params, ActivityInfo activityInfo) {
if (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null) {
String[] activityLinkKeys = activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY).split(",");
for (String activityLinkKey : activityLinkKeys) {
if (params.has(activityLinkKey)) {
return true;
}
}
}
return false;
}
private boolean checkForAutoDeepLinkPath(JSONObject params, ActivityInfo activityInfo) {
String deepLinkPath = null;
try {
if (params.has(Defines.Jsonkey.AndroidDeepLinkPath.getKey())) {
deepLinkPath = params.getString(Defines.Jsonkey.AndroidDeepLinkPath.getKey());
} else if (params.has(Defines.Jsonkey.DeepLinkPath.getKey())) {
deepLinkPath = params.getString(Defines.Jsonkey.DeepLinkPath.getKey());
}
} catch (JSONException ignored) {
}
if (activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null && deepLinkPath != null) {
String[] activityLinkPaths = activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH).split(",");
for (String activityLinkPath : activityLinkPaths) {
if (pathMatch(activityLinkPath.trim(), deepLinkPath)) {
return true;
}
}
}
return false;
}
private boolean pathMatch(String templatePath, String path) {
boolean matched = true;
String[] pathSegmentsTemplate = templatePath.split("\\?")[0].split("/");
String[] pathSegmentsTarget = path.split("\\?")[0].split("/");
if (pathSegmentsTemplate.length != pathSegmentsTarget.length) {
return false;
}
for (int i = 0; i < pathSegmentsTemplate.length && i < pathSegmentsTarget.length; i++) {
String pathSegmentTemplate = pathSegmentsTemplate[i];
String pathSegmentTarget = pathSegmentsTarget[i];
if (!pathSegmentTemplate.equals(pathSegmentTarget) && !pathSegmentTemplate.contains("*")) {
matched = false;
break;
}
}
return matched;
}
public static void enableSimulateInstalls() {
isSimulatingInstalls_ = true;
}
public static void disableSimulateInstalls() {
isSimulatingInstalls_ = false;
}
public static boolean isSimulatingInstalls() {
return isSimulatingInstalls_;
}
public static void enableLogging() {
isLogging_ = true;
}
public static void disableLogging() {
isLogging_ = false;
}
public static boolean getIsLogging() {
return isLogging_;
}
/**
* <p> Class for building a share link dialog.This creates a chooser for selecting application for
* sharing a link created with given parameters. </p>
*/
public static class ShareLinkBuilder {
private final Activity activity_;
private final Branch branch_;
private String shareMsg_;
private String shareSub_;
private Branch.BranchLinkShareListener callback_ = null;
private Branch.IChannelProperties channelPropertiesCallback_ = null;
private ArrayList<SharingHelper.SHARE_WITH> preferredOptions_;
private String defaultURL_;
//Customise more and copy url option
private Drawable moreOptionIcon_;
private String moreOptionText_;
private Drawable copyUrlIcon_;
private String copyURlText_;
private String urlCopiedMessage_;
private int styleResourceID_;
private boolean setFullWidthStyle_;
private int dividerHeight = -1;
private String sharingTitle = null;
private View sharingTitleView = null;
private int iconSize_ = 50;
BranchShortLinkBuilder shortLinkBuilder_;
private List<String> includeInShareSheet = new ArrayList<>();
private List<String> excludeFromShareSheet = new ArrayList<>();
/**
* <p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with
* user selected clients</p>
*
* @param activity The {@link Activity} to show the dialog for choosing sharing application.
* @param parameters A {@link JSONObject} value containing the deep link params.
*/
public ShareLinkBuilder(Activity activity, JSONObject parameters) {
this.activity_ = activity;
this.branch_ = branchReferral_;
shortLinkBuilder_ = new BranchShortLinkBuilder(activity);
try {
Iterator<String> keys = parameters.keys();
while (keys.hasNext()) {
String key = keys.next();
shortLinkBuilder_.addParameters(key, (String) parameters.get(key));
}
} catch (Exception ignore) {
}
shareMsg_ = "";
callback_ = null;
channelPropertiesCallback_ = null;
preferredOptions_ = new ArrayList<>();
defaultURL_ = null;
moreOptionIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_more);
moreOptionText_ = "More...";
copyUrlIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_save);
copyURlText_ = "Copy link";
urlCopiedMessage_ = "Copied link to clipboard!";
}
/**
* *<p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with
* user selected clients</p>
*
* @param activity The {@link Activity} to show the dialog for choosing sharing application.
* @param shortLinkBuilder An instance of {@link BranchShortLinkBuilder} to create link to be shared
*/
public ShareLinkBuilder(Activity activity, BranchShortLinkBuilder shortLinkBuilder) {
this(activity, new JSONObject());
shortLinkBuilder_ = shortLinkBuilder;
}
/**
* <p>Sets the message to be shared with the link.</p>
*
* @param message A {@link String} to be shared with the link
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setMessage(String message) {
this.shareMsg_ = message;
return this;
}
/**
* <p>Sets the subject of this message. This will be added to Email and SMS Application capable of handling subject in the message.</p>
*
* @param subject A {@link String} subject of this message.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setSubject(String subject) {
this.shareSub_ = subject;
return this;
}
/**
* <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep
* link.</p>
*
* @param tag A {@link String} to be added to the iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addTag(String tag) {
this.shortLinkBuilder_.addTag(tag);
return this;
}
/**
* <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep
* link.</p>
*
* @param tags A {@link java.util.List} of tags to be added to the iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addTags(ArrayList<String> tags) {
this.shortLinkBuilder_.addTags(tags);
return this;
}
/**
* <p>Adds a feature that make use of the link.</p>
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setFeature(String feature) {
this.shortLinkBuilder_.setFeature(feature);
return this;
}
/**
* <p>Adds a stage application or user flow associated with this link.</p>
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setStage(String stage) {
this.shortLinkBuilder_.setStage(stage);
return this;
}
/**
* <p>Adds a callback to get the sharing status.</p>
*
* @param callback A {@link BranchLinkShareListener} instance for getting sharing status.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setCallback(BranchLinkShareListener callback) {
this.callback_ = callback;
return this;
}
/**
* @param channelPropertiesCallback A {@link io.branch.referral.Branch.IChannelProperties} instance for customizing sharing properties for channels.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setChannelProperties(IChannelProperties channelPropertiesCallback) {
this.channelPropertiesCallback_ = channelPropertiesCallback;
return this;
}
/**
* <p>Adds application to the preferred list of applications which are shown on share dialog.
* Only these options will be visible when the application selector dialog launches. Other options can be
* accessed by clicking "More"</p>
*
* @param preferredOption A list of applications to be added as preferred options on the app chooser.
* Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addPreferredSharingOption(SharingHelper.SHARE_WITH preferredOption) {
this.preferredOptions_.add(preferredOption);
return this;
}
/**
* <p>Adds application to the preferred list of applications which are shown on share dialog.
* Only these options will be visible when the application selector dialog launches. Other options can be
* accessed by clicking "More"</p>
*
* @param preferredOptions A list of applications to be added as preferred options on the app chooser.
* Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addPreferredSharingOptions(ArrayList<SharingHelper.SHARE_WITH> preferredOptions) {
this.preferredOptions_.addAll(preferredOptions);
return this;
}
/**
* Add the given key value to the deep link parameters
*
* @param key A {@link String} with value for the key for the deep link params
* @param value A {@link String} with deep link parameters value
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addParam(String key, String value) {
try {
this.shortLinkBuilder_.addParameters(key, value);
} catch (Exception ignore) {
}
return this;
}
/**
* <p> Set a default url to share in case there is any error creating the deep link </p>
*
* @param url A {@link String} with value of default url to be shared with the selected application in case deep link creation fails.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setDefaultURL(String url) {
defaultURL_ = url;
return this;
}
/**
* <p> Set the icon and label for the option to expand the application list to see more options.
* Default label is set to "More" </p>
*
* @param icon Drawable to set as the icon for more option. Default icon is system menu_more icon.
* @param label A {@link String} with value for the more option label. Default label is "More"
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setMoreOptionStyle(Drawable icon, String label) {
moreOptionIcon_ = icon;
moreOptionText_ = label;
return this;
}
/**
* <p> Set the icon and label for the option to expand the application list to see more options.
* Default label is set to "More" </p>
*
* @param drawableIconID Resource ID for the drawable to set as the icon for more option. Default icon is system menu_more icon.
* @param stringLabelID Resource ID for String label for the more option. Default label is "More"
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setMoreOptionStyle(int drawableIconID, int stringLabelID) {
moreOptionIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID);
moreOptionText_ = activity_.getResources().getString(stringLabelID);
return this;
}
/**
* <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p>
*
* @param icon Drawable to set as the icon for copy url option. Default icon is system menu_save icon
* @param label A {@link String} with value for the copy url option label. Default label is "Copy link"
* @param message A {@link String} with value for a toast message displayed on copying a url.
* Default message is "Copied link to clipboard!"
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setCopyUrlStyle(Drawable icon, String label, String message) {
copyUrlIcon_ = icon;
copyURlText_ = label;
urlCopiedMessage_ = message;
return this;
}
/**
* <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p>
*
* @param drawableIconID Resource ID for the drawable to set as the icon for copy url option. Default icon is system menu_save icon
* @param stringLabelID Resource ID for the string label the copy url option. Default label is "Copy link"
* @param stringMessageID Resource ID for the string message to show toast message displayed on copying a url
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setCopyUrlStyle(int drawableIconID, int stringLabelID, int stringMessageID) {
copyUrlIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID);
copyURlText_ = activity_.getResources().getString(stringLabelID);
urlCopiedMessage_ = activity_.getResources().getString(stringMessageID);
return this;
}
public ShareLinkBuilder setAlias(String alias) {
this.shortLinkBuilder_.setAlias(alias);
return this;
}
/**
* <p> Sets the amount of time that Branch allows a click to remain outstanding.</p>
*
* @param matchDuration A {@link Integer} value specifying the time that Branch allows a click to
* remain outstanding and be eligible to be matched with a new app session.
* @return This Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder setMatchDuration(int matchDuration) {
this.shortLinkBuilder_.setDuration(matchDuration);
return this;
}
/**
* <p>
* Sets the share dialog to full width mode. Full width mode will show a non modal sheet with entire screen width.
* </p>
*
* @param setFullWidthStyle {@link Boolean} With value true if a full width style share sheet is desired.
* @return This Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder setAsFullWidthStyle(boolean setFullWidthStyle) {
this.setFullWidthStyle_ = setFullWidthStyle;
return this;
}
/**
* Set the height for the divider for the sharing channels in the list. Set this to zero to remove the dividers
*
* @param height The new height of the divider in pixels.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder setDividerHeight(int height) {
this.dividerHeight = height;
return this;
}
/**
* Set the title for the sharing dialog
*
* @param title {@link String} containing the value for the title text.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder setSharingTitle(String title) {
this.sharingTitle = title;
return this;
}
/**
* Set the title for the sharing dialog
*
* @param titleView {@link View} for setting the title.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder setSharingTitle(View titleView) {
this.sharingTitleView = titleView;
return this;
}
/**
* Set icon size for the sharing dialog
*
* @param iconSize {@link int} for setting the share sheet icon size.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder setIconSize(int iconSize) {
this.iconSize_ = iconSize;
return this;
}
/**
* Exclude items from the ShareSheet by package name String.
*
* @param packageName {@link String} package name to be excluded.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder excludeFromShareSheet(@NonNull String packageName) {
this.excludeFromShareSheet.add(packageName);
return this;
}
/**
* Exclude items from the ShareSheet by package name array.
*
* @param packageName {@link String[]} package name to be excluded.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder excludeFromShareSheet(@NonNull String[] packageName) {
this.excludeFromShareSheet.addAll(Arrays.asList(packageName));
return this;
}
/**
* Exclude items from the ShareSheet by package name List.
*
* @param packageNames {@link List} package name to be excluded.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder excludeFromShareSheet(@NonNull List<String> packageNames) {
this.excludeFromShareSheet.addAll(packageNames);
return this;
}
/**
* Include items from the ShareSheet by package name String. If only "com.Slack"
* is included, then only preferred sharing options + Slack
* will be displayed, for example.
*
* @param packageName {@link String} package name to be included.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder includeInShareSheet(@NonNull String packageName) {
this.includeInShareSheet.add(packageName);
return this;
}
/**
* Include items from the ShareSheet by package name Array. If only "com.Slack"
* is included, then only preferred sharing options + Slack
* will be displayed, for example.
*
* @param packageName {@link String[]} package name to be included.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder includeInShareSheet(@NonNull String[] packageName) {
this.includeInShareSheet.addAll(Arrays.asList(packageName));
return this;
}
/**
* Include items from the ShareSheet by package name List. If only "com.Slack"
* is included, then only preferred sharing options + Slack
* will be displayed, for example.
*
* @param packageNames {@link List} package name to be included.
* @return this Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder includeInShareSheet(@NonNull List<String> packageNames) {
this.includeInShareSheet.addAll(packageNames);
return this;
}
/**
* <p> Set the given style to the List View showing the share sheet</p>
*
* @param resourceID A Styleable resource to be applied to the share sheet list view
*/
public void setStyleResourceID(@StyleRes int resourceID) {
styleResourceID_ = resourceID;
}
public void setShortLinkBuilderInternal(BranchShortLinkBuilder shortLinkBuilder) {
this.shortLinkBuilder_ = shortLinkBuilder;
}
/**
* <p>Creates an application selector dialog and share a link with user selected sharing option.
* The link is created with the parameters provided to the builder. </p>
*/
public void shareLink() {
branchReferral_.shareLink(this);
}
public Activity getActivity() {
return activity_;
}
public ArrayList<SharingHelper.SHARE_WITH> getPreferredOptions() {
return preferredOptions_;
}
List<String> getExcludedFromShareSheet() {
return excludeFromShareSheet;
}
List<String> getIncludedInShareSheet() {
return includeInShareSheet;
}
public Branch getBranch() {
return branch_;
}
public String getShareMsg() {
return shareMsg_;
}
public String getShareSub() {
return shareSub_;
}
public BranchLinkShareListener getCallback() {
return callback_;
}
public IChannelProperties getChannelPropertiesCallback() {
return channelPropertiesCallback_;
}
public String getDefaultURL() {
return defaultURL_;
}
public Drawable getMoreOptionIcon() {
return moreOptionIcon_;
}
public String getMoreOptionText() {
return moreOptionText_;
}
public Drawable getCopyUrlIcon() {
return copyUrlIcon_;
}
public String getCopyURlText() {
return copyURlText_;
}
public String getUrlCopiedMessage() {
return urlCopiedMessage_;
}
public BranchShortLinkBuilder getShortLinkBuilder() {
return shortLinkBuilder_;
}
public boolean getIsFullWidthStyle() {
return setFullWidthStyle_;
}
public int getDividerHeight() {
return dividerHeight;
}
public String getSharingTitle() {
return sharingTitle;
}
public View getSharingTitleView() {
return sharingTitleView;
}
public int getStyleResourceID() {
return styleResourceID_;
}
public int getIconSize() {
return iconSize_;
}
}
public void registerView(BranchUniversalObject
branchUniversalObject, BranchUniversalObject.RegisterViewStatusListener callback) {
if (context_ != null) {
new BranchEvent(BRANCH_STANDARD_EVENT.VIEW_ITEM)
.addContentItems(branchUniversalObject)
.logEvent(context_);
}
}
/**
* Update the extra instrumentation data provided to Branch
*
* @param instrumentationData A {@link HashMap} with key value pairs for instrumentation data.
*/
public void addExtraInstrumentationData(HashMap<String, String> instrumentationData) {
instrumentationExtraData_.putAll(instrumentationData);
}
/**
* Update the extra instrumentation data provided to Branch
*
* @param key A {@link String} Value for instrumentation data key
* @param value A {@link String} Value for instrumentation data value
*/
public void addExtraInstrumentationData(String key, String value) {
instrumentationExtraData_.put(key, value);
}
@Override
public void onBranchViewVisible(String action, String branchViewID) {
//No Implementation on purpose
}
@Override
public void onBranchViewAccepted(String action, String branchViewID) {
if (ServerRequestInitSession.isInitSessionAction(action)) {
checkForAutoDeepLinkConfiguration();
}
}
@Override
public void onBranchViewCancelled(String action, String branchViewID) {
if (ServerRequestInitSession.isInitSessionAction(action)) {
checkForAutoDeepLinkConfiguration();
}
}
@Override
public void onBranchViewError(int errorCode, String errorMsg, String action) {
if (ServerRequestInitSession.isInitSessionAction(action)) {
checkForAutoDeepLinkConfiguration();
}
}
/**
* Interface for defining optional Branch view behaviour for Activities
*/
public interface IBranchViewControl {
/**
* Defines if an activity is interested to show Branch views or not.
* By default activities are considered as Branch view enabled. In case of activities which are not interested to show a Branch view (Splash screen for example)
* should implement this and return false. The pending Branch view will be shown with the very next Branch view enabled activity
*
* @return A {@link Boolean} whose value is true if the activity don't want to show any Branch view.
*/
boolean skipBranchViewsOnThisActivity();
}
/**
* Checks if this is an Instant app instance
*
* @param context Current {@link Context}
* @return {@code true} if current application is an instance of instant app
*/
public static boolean isInstantApp(@NonNull Context context) {
return InstantAppUtil.isInstantApp(context);
}
/**
* Method shows play store install prompt for the full app. Thi passes the referrer to the installed application. The same deep link params as the instant app are provided to the
* full app up on Branch#initSession()
*
* @param activity Current activity
* @param requestCode Request code for the activity to receive the result
* @return {@code true} if install prompt is shown to user
*/
public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode) {
String installReferrerString = "";
if (Branch.getInstance() != null) {
JSONObject latestReferringParams = Branch.getInstance().getLatestReferringParams();
String referringLinkKey = "~" + Defines.Jsonkey.ReferringLink.getKey();
if (latestReferringParams != null && latestReferringParams.has(referringLinkKey)) {
String referringLink = "";
try {
referringLink = latestReferringParams.getString(referringLinkKey);
// Considering the case that url may contain query params with `=` and `&` with it and may cause issue when parsing play store referrer
referringLink = URLEncoder.encode(referringLink, "UTF-8");
} catch (JSONException | UnsupportedEncodingException e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(referringLink)) {
installReferrerString = Defines.Jsonkey.IsFullAppConv.getKey() + "=true&" + Defines.Jsonkey.ReferringLink.getKey() + "=" + referringLink;
}
}
}
return InstantAppUtil.doShowInstallPrompt(activity, requestCode, installReferrerString);
}
/**
* Method shows play store install prompt for the full app. Use this method only if you have custom parameters to pass to the full app using referrer else use
* {@link #showInstallPrompt(Activity, int)}
*
* @param activity Current activity
* @param requestCode Request code for the activity to receive the result
* @param referrer Any custom referrer string to pass to full app (must be of format "referrer_key1=referrer_value1%26referrer_key2=referrer_value2")
* @return {@code true} if install prompt is shown to user
*/
public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode, @Nullable String referrer) {
String installReferrerString = Defines.Jsonkey.IsFullAppConv.getKey() + "=true&" + referrer;
return InstantAppUtil.doShowInstallPrompt(activity, requestCode, installReferrerString);
}
/**
* Method shows play store install prompt for the full app. Use this method only if you want the full app to receive a custom {@link BranchUniversalObject} to do deferred deep link.
* Please see {@link #showInstallPrompt(Activity, int)}
* NOTE :
* This method will do a synchronous generation of Branch short link for the BUO. So please consider calling this method on non UI thread
* Please make sure your instant app and full ap are using same Branch key in order for the deferred deep link working
*
* @param activity Current activity
* @param requestCode Request code for the activity to receive the result
* @param buo {@link BranchUniversalObject} to pass to the full app up on install
* @return {@code true} if install prompt is shown to user
*/
public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode, @NonNull BranchUniversalObject buo) {
if (buo != null) {
String shortUrl = buo.getShortUrl(activity, new LinkProperties());
String installReferrerString = Defines.Jsonkey.ReferringLink.getKey() + "=" + shortUrl;
if (!TextUtils.isEmpty(installReferrerString)) {
return showInstallPrompt(activity, requestCode, installReferrerString);
} else {
return showInstallPrompt(activity, requestCode, "");
}
}
return false;
}
}
|
package example.springdata.jdbc.howto.idgeneration;
import java.util.UUID;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.relational.core.mapping.event.BeforeConvertCallback;
@SpringBootApplication
class IdGenerationApplication {
public static void main(String[] args) {
SpringApplication.run(IdGenerationApplication.class, args);
}
@Bean
BeforeConvertCallback<StringIdMinion> beforeSaveCallback() {
return (minion) -> {
if (minion.id == null) {
minion.id = UUID.randomUUID().toString();
}
return minion;
};
}
}
|
package org.eclipse.kura.net.admin.monitor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.kura.KuraException;
import org.eclipse.kura.comm.CommURI;
import org.eclipse.kura.core.net.NetworkConfiguration;
import org.eclipse.kura.linux.net.ConnectionInfoImpl;
import org.eclipse.kura.linux.net.modem.SupportedSerialModemInfo;
import org.eclipse.kura.linux.net.modem.SupportedSerialModemsInfo;
import org.eclipse.kura.linux.net.modem.SupportedUsbModemInfo;
import org.eclipse.kura.linux.net.modem.SupportedUsbModemsInfo;
import org.eclipse.kura.linux.net.util.LinuxNetworkUtil;
import org.eclipse.kura.net.ConnectionInfo;
import org.eclipse.kura.net.NetConfig;
import org.eclipse.kura.net.NetConfigIP4;
import org.eclipse.kura.net.NetInterface;
import org.eclipse.kura.net.NetInterfaceAddress;
import org.eclipse.kura.net.NetInterfaceAddressConfig;
import org.eclipse.kura.net.NetInterfaceConfig;
import org.eclipse.kura.net.NetInterfaceStatus;
import org.eclipse.kura.net.NetworkService;
import org.eclipse.kura.net.admin.NetworkConfigurationService;
import org.eclipse.kura.net.admin.event.NetworkConfigurationChangeEvent;
import org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent;
import org.eclipse.kura.net.admin.modem.CellularModemFactory;
import org.eclipse.kura.net.admin.modem.EvdoCellularModem;
import org.eclipse.kura.net.admin.modem.HspaCellularModem;
import org.eclipse.kura.net.admin.modem.IModemLinkService;
import org.eclipse.kura.net.admin.modem.PppFactory;
import org.eclipse.kura.net.admin.modem.PppState;
import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo;
import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo.SerialModemFactoryInfo;
import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo;
import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo.UsbModemFactoryInfo;
import org.eclipse.kura.net.modem.CellularModem;
import org.eclipse.kura.net.modem.ModemAddedEvent;
import org.eclipse.kura.net.modem.ModemConfig;
import org.eclipse.kura.net.modem.ModemDevice;
import org.eclipse.kura.net.modem.ModemGpsDisabledEvent;
import org.eclipse.kura.net.modem.ModemGpsEnabledEvent;
import org.eclipse.kura.net.modem.ModemInterface;
import org.eclipse.kura.net.modem.ModemManagerService;
import org.eclipse.kura.net.modem.ModemMonitorListener;
import org.eclipse.kura.net.modem.ModemMonitorService;
import org.eclipse.kura.net.modem.ModemReadyEvent;
import org.eclipse.kura.net.modem.ModemRemovedEvent;
import org.eclipse.kura.net.modem.ModemTechnologyType;
import org.eclipse.kura.net.modem.SerialModemDevice;
import org.eclipse.kura.system.SystemService;
import org.eclipse.kura.usb.UsbDeviceEvent;
import org.eclipse.kura.usb.UsbModemDevice;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ModemMonitorServiceImpl implements ModemMonitorService, ModemManagerService, EventHandler {
private static final Logger s_logger = LoggerFactory.getLogger(ModemMonitorServiceImpl.class);
private ComponentContext m_ctx;
private static final String[] EVENT_TOPICS = new String[] {
NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC,
ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC,
ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC, };
private static final long THREAD_INTERVAL = 30000;
private static final long THREAD_TERMINATION_TOUT = 1; // in seconds
private static Object s_lock = new Object();
private static Future<?> task;
private static AtomicBoolean stopThread;
private SystemService m_systemService;
private NetworkService m_networkService;
private NetworkConfigurationService m_netConfigService;
private EventAdmin m_eventAdmin;
private List<ModemMonitorListener>m_listeners;
private ExecutorService m_executor;
private Map<String, CellularModem> m_modems;
private Map<String, InterfaceState> m_interfaceStatuses;
private NetworkConfiguration m_networkConfig;
private boolean m_serviceActivated;
private PppState m_pppState;
private long m_resetTimerStart;
public void setNetworkService(NetworkService networkService) {
m_networkService = networkService;
}
public void unsetNetworkService(NetworkService networkService) {
m_networkService = null;
}
public void setEventAdmin(EventAdmin eventAdmin) {
m_eventAdmin = eventAdmin;
}
public void unsetEventAdmin(EventAdmin eventAdmin) {
m_eventAdmin = null;
}
public void setNetworkConfigurationService(NetworkConfigurationService netConfigService) {
m_netConfigService = netConfigService;
}
public void unsetNetworkConfigurationService(NetworkConfigurationService netConfigService) {
m_netConfigService = null;
}
public void setSystemService(SystemService systemService) {
m_systemService = systemService;
}
public void unsetSystemService(SystemService systemService) {
m_systemService = null;
}
protected void activate(ComponentContext componentContext) {
// save the bundle context
m_ctx = componentContext;
m_pppState = PppState.NOT_CONNECTED;
m_resetTimerStart = 0L;
Dictionary<String, String[]> d = new Hashtable<String, String[]>();
d.put(EventConstants.EVENT_TOPIC, EVENT_TOPICS);
m_ctx.getBundleContext().registerService(EventHandler.class.getName(), this, d);
m_modems = new HashMap<String, CellularModem>();
m_interfaceStatuses = new HashMap<String, InterfaceState>();
m_listeners = new ArrayList<ModemMonitorListener>();
stopThread = new AtomicBoolean();
// track currently installed modems
try {
m_networkConfig = m_netConfigService.getNetworkConfiguration();
for(NetInterface<? extends NetInterfaceAddress> netInterface : m_networkService.getNetworkInterfaces()) {
if(netInterface instanceof ModemInterface) {
ModemDevice modemDevice = ((ModemInterface<?>) netInterface).getModemDevice();
trackModem(modemDevice);
}
}
} catch (Exception e) {
s_logger.error("Error getting installed modems", e);
}
stopThread.set(false);
m_executor = Executors.newSingleThreadExecutor();
task = m_executor.submit(new Runnable() {
@Override
public void run() {
while (!stopThread.get()) {
Thread.currentThread().setName("ModemMonitor");
try {
monitor();
monitorWait();
} catch (InterruptedException interruptedException) {
Thread.interrupted();
s_logger.debug("modem monitor interrupted - {}", interruptedException);
} catch (Throwable t) {
s_logger.error("activate() :: Exception while monitoring cellular connection {}", t);
}
}
}});
m_serviceActivated = true;
s_logger.debug("ModemMonitor activated and ready to receive events");
}
protected void deactivate(ComponentContext componentContext) {
m_listeners = null;
PppFactory.releaseAllPppServices();
if ((task != null) && (!task.isDone())) {
stopThread.set(true);
monitorNotity();
s_logger.debug("Cancelling ModemMonitor task ...");
task.cancel(true);
s_logger.info("ModemMonitor task cancelled? = {}", task.isDone());
task = null;
}
if (m_executor != null) {
s_logger.debug("Terminating ModemMonitor Thread ...");
m_executor.shutdownNow();
try {
m_executor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
s_logger.warn("Interrupted", e);
}
s_logger.info("ModemMonitor Thread terminated? - {}", m_executor.isTerminated());
m_executor = null;
}
m_serviceActivated = false;
m_networkConfig = null;
}
@Override
public void handleEvent(Event event) {
s_logger.debug("handleEvent - topic: {}", event.getTopic());
String topic = event.getTopic();
if (topic.equals(NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC)) {
NetworkConfigurationChangeEvent netConfigChangedEvent = (NetworkConfigurationChangeEvent)event;
String [] propNames = netConfigChangedEvent.getPropertyNames();
if ((propNames != null) && (propNames.length > 0)) {
Map<String, Object> props = new HashMap<String, Object>();
for (String propName : propNames) {
Object prop = netConfigChangedEvent.getProperty(propName);
if (prop != null) {
props.put(propName, prop);
}
}
try {
final NetworkConfiguration newNetworkConfig = new NetworkConfiguration(props);
ExecutorService ex = Executors.newSingleThreadExecutor();
ex.submit(new Runnable() {
@Override
public void run() {
processNetworkConfigurationChangeEvent(newNetworkConfig);
}
});
} catch (Exception e) {
s_logger.error("Failed to handle the NetworkConfigurationChangeEvent - {}", e);
}
}
} else if (topic.equals(ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC)) {
ModemAddedEvent modemAddedEvent = (ModemAddedEvent)event;
final ModemDevice modemDevice = modemAddedEvent.getModemDevice();
if (m_serviceActivated) {
ExecutorService ex = Executors.newSingleThreadExecutor();
ex.submit(new Runnable() {
@Override
public void run() {
trackModem(modemDevice);
}});
}
} else if (topic.equals(ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC)) {
ModemRemovedEvent modemRemovedEvent = (ModemRemovedEvent)event;
String usbPort = (String)modemRemovedEvent.getProperty(UsbDeviceEvent.USB_EVENT_USB_PORT_PROPERTY);
m_modems.remove(usbPort);
}
}
@Override
public CellularModem getModemService (String usbPort) {
return m_modems.get(usbPort);
}
@Override
public Collection<CellularModem> getAllModemServices() {
return m_modems.values();
}
private NetInterfaceStatus getNetInterfaceStatus (List<NetConfig> netConfigs) {
NetInterfaceStatus interfaceStatus = NetInterfaceStatus.netIPv4StatusUnknown;
if ((netConfigs != null) && (netConfigs.size() > 0)) {
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof NetConfigIP4) {
interfaceStatus = ((NetConfigIP4) netConfig).getStatus();
break;
}
}
}
return interfaceStatus;
}
@Override
public void registerListener(ModemMonitorListener newListener) {
boolean found = false;
if (m_listeners == null) {
m_listeners = new ArrayList<ModemMonitorListener>();
}
if (!m_listeners.isEmpty()) {
for (ModemMonitorListener listener : m_listeners) {
if (listener.equals(newListener)) {
found = true;
break;
}
}
}
if (!found) {
m_listeners.add(newListener);
}
}
@Override
public void unregisterListener(ModemMonitorListener listenerToUnregister) {
if ((m_listeners != null) && (!m_listeners.isEmpty())) {
for (int i = 0; i < m_listeners.size(); i++) {
if ((m_listeners.get(i)).equals(listenerToUnregister)) {
m_listeners.remove(i);
}
}
}
}
private void processNetworkConfigurationChangeEvent(NetworkConfiguration newNetworkConfig) {
synchronized (s_lock) {
if (m_modems == null || m_modems.isEmpty()){
return;
}
for (Map.Entry<String, CellularModem> modemEntry : m_modems.entrySet()) {
String usbPort = modemEntry.getKey();
CellularModem modem = modemEntry.getValue();
try {
String ifaceName = null;
if (m_networkService != null) {
ifaceName = m_networkService.getModemPppPort(modem.getModemDevice());
}
if (ifaceName != null) {
List<NetConfig> oldNetConfigs = modem.getConfiguration();
NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = newNetworkConfig.getNetInterfaceConfig(ifaceName);
if (netInterfaceConfig == null) {
netInterfaceConfig = newNetworkConfig.getNetInterfaceConfig(usbPort);
}
List<NetConfig>newNetConfigs = null;
IModemLinkService pppService = null;
int ifaceNo = getInterfaceNumber(oldNetConfigs);
if (ifaceNo >= 0) {
pppService = PppFactory.obtainPppService(ifaceNo, modem.getDataPort());
}
if (netInterfaceConfig != null) {
newNetConfigs = getNetConfigs(netInterfaceConfig);
} else {
if ((oldNetConfigs != null) && (pppService != null)) {
if (!ifaceName.equals(pppService.getIfaceName())) {
newNetConfigs = oldNetConfigs;
oldNetConfigs = null;
try {
setInterfaceNumber(ifaceName, newNetConfigs);
} catch (NumberFormatException e) {
s_logger.error("failed to set new interface number - {}", e);
}
}
}
}
if((oldNetConfigs == null) || !isConfigsEqual(oldNetConfigs, newNetConfigs)) {
s_logger.info("new configuration for cellular modem on usb port {} netinterface {}", usbPort, ifaceName);
m_networkConfig = newNetworkConfig;
if (pppService != null) {
PppState pppState = pppService.getPppState();
if ((pppState == PppState.CONNECTED) || (pppState == PppState.IN_PROGRESS)) {
s_logger.info("disconnecting " + pppService.getIfaceName());
pppService.disconnect();
}
PppFactory.releasePppService(pppService.getIfaceName());
}
if (modem.isGpsEnabled()) {
if (!disableModemGps(modem)) {
s_logger.error("processNetworkConfigurationChangeEvent() :: Failed to disable modem GPS");
modem.reset();
}
}
modem.setConfiguration(newNetConfigs);
if (modem instanceof EvdoCellularModem) {
NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(newNetConfigs);
if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) {
if (!((EvdoCellularModem) modem).isProvisioned()) {
s_logger.info("NetworkConfigurationChangeEvent :: The {} is not provisioned, will try to provision it ...", modem.getModel());
if ((task != null) && !task.isCancelled()) {
s_logger.info("NetworkConfigurationChangeEvent :: Cancelling monitor task");
stopThread.set(true);
monitorNotity();
task.cancel(true);
task = null;
}
((EvdoCellularModem) modem).provision();
if (task == null) {
s_logger.info("NetworkConfigurationChangeEvent :: Restarting monitor task");
stopThread.set(false);
task = m_executor.submit(new Runnable() {
@Override
public void run() {
while (!stopThread.get()) {
Thread.currentThread().setName("ModemMonitor");
try {
monitor();
monitorWait();
} catch (InterruptedException interruptedException) {
Thread.interrupted();
s_logger.debug("modem monitor interrupted - {}", interruptedException);
} catch (Throwable t) {
s_logger.error("handleEvent() :: Exception while monitoring cellular connection {}", t);
}
}
}});
} else {
monitorNotity();
}
} else {
s_logger.info("NetworkConfigurationChangeEvent :: The " + modem.getModel() + " is provisioned");
}
}
if (modem.isGpsSupported()) {
if (isGpsEnabledInConfig(newNetConfigs) && !modem.isGpsEnabled()) {
modem.enableGps();
postModemGpsEvent(modem, true);
}
}
}
}
}
} catch (KuraException e) {
s_logger.error("NetworkConfigurationChangeEvent :: Failed to process - {}", e);
}
}
}
}
private boolean isConfigsEqual(List<NetConfig>oldConfig, List<NetConfig> newConfig) {
boolean ret = false;
ModemConfig oldModemConfig = getModemConfig(oldConfig);
ModemConfig newModemConfig = getModemConfig(newConfig);
NetConfigIP4 oldNetConfigIP4 = getNetConfigIp4(oldConfig);
NetConfigIP4 newNetConfigIP4 = getNetConfigIp4(newConfig);
if (oldNetConfigIP4.equals(newNetConfigIP4) && oldModemConfig.equals(newModemConfig)) {
ret = true;
}
return ret;
}
private List<NetConfig> getNetConfigs(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) {
List<NetConfig> netConfigs = null;
if (netInterfaceConfig != null) {
List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig.getNetInterfaceAddresses();
if (netInterfaceAddressConfigs != null && netInterfaceAddressConfigs.size() > 0) {
for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) {
netConfigs = netInterfaceAddressConfig.getConfigs();
}
}
}
return netConfigs;
}
private ModemConfig getModemConfig(List<NetConfig> netConfigs) {
ModemConfig modemConfig = null;
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof ModemConfig) {
modemConfig = (ModemConfig)netConfig;
}
}
return modemConfig;
}
private NetConfigIP4 getNetConfigIp4(List<NetConfig> netConfigs) {
NetConfigIP4 netConfigIP4 = null;
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof NetConfigIP4) {
netConfigIP4 = (NetConfigIP4)netConfig;
}
}
return netConfigIP4;
}
private int getInterfaceNumber (List<NetConfig> netConfigs) {
int ifaceNo = -1;
if ((netConfigs != null) && (netConfigs.size() > 0)) {
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof ModemConfig) {
ifaceNo = ((ModemConfig) netConfig).getPppNumber();
break;
}
}
}
return ifaceNo;
}
private int getInterfaceNumber(String ifaceName) {
return Integer.parseInt(ifaceName.replaceAll("[^0-9]", ""));
}
private void setInterfaceNumber (String ifaceName, List<NetConfig> netConfigs) {
if ((netConfigs != null) && (netConfigs.size() > 0)) {
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof ModemConfig) {
((ModemConfig) netConfig).setPppNumber(getInterfaceNumber(ifaceName));
break;
}
}
}
}
private long getModemResetTimeoutMsec(String ifaceName, List<NetConfig> netConfigs) {
long resetToutMsec = 0L;
if ((ifaceName != null) && (netConfigs != null) && (netConfigs.size() > 0)) {
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof ModemConfig) {
resetToutMsec = ((ModemConfig) netConfig).getResetTimeout() * 60000;
break;
}
}
}
return resetToutMsec;
}
private boolean isGpsEnabledInConfig(List<NetConfig> netConfigs) {
boolean isGpsEnabled = false;
if ((netConfigs != null) && (netConfigs.size() > 0)) {
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof ModemConfig) {
isGpsEnabled = ((ModemConfig) netConfig).isGpsEnabled();
break;
}
}
}
return isGpsEnabled;
}
private void monitor() {
synchronized (s_lock) {
HashMap<String, InterfaceState> newInterfaceStatuses = new HashMap<String, InterfaceState>();
if(m_modems == null || m_modems.isEmpty()){
return;
}
for (Map.Entry<String, CellularModem> modemEntry : m_modems.entrySet()) {
CellularModem modem = modemEntry.getValue();
// get signal strength only if somebody needs it
if ((m_listeners != null) && (!m_listeners.isEmpty())) {
for (ModemMonitorListener listener : m_listeners) {
try {
int rssi = modem.getSignalStrength();
listener.setCellularSignalLevel(rssi);
} catch (KuraException e) {
listener.setCellularSignalLevel(0);
s_logger.error("monitor() :: Failed to obtain signal strength - {}", e);
}
}
}
IModemLinkService pppService = null;
PppState pppState = null;
NetInterfaceStatus netInterfaceStatus = getNetInterfaceStatus(modem.getConfiguration());
try {
String ifaceName = m_networkService.getModemPppPort(modem.getModemDevice());
if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN && ifaceName != null) {
pppService = PppFactory.obtainPppService(ifaceName, modem.getDataPort());
pppState = pppService.getPppState();
if (m_pppState != pppState) {
s_logger.info("monitor() :: previous PppState={}", m_pppState);
s_logger.info("monitor() :: current PppState={}", pppState);
}
if (pppState == PppState.NOT_CONNECTED) {
boolean checkIfSimCardReady = false;
List<ModemTechnologyType> modemTechnologyTypes = modem.getTechnologyTypes();
for (ModemTechnologyType modemTechnologyType : modemTechnologyTypes) {
if ((modemTechnologyType == ModemTechnologyType.GSM_GPRS)
|| (modemTechnologyType == ModemTechnologyType.UMTS)
|| (modemTechnologyType == ModemTechnologyType.HSDPA)
|| (modemTechnologyType == ModemTechnologyType.HSPA)) {
checkIfSimCardReady = true;
break;
}
}
if (checkIfSimCardReady) {
if(((HspaCellularModem)modem).isSimCardReady()) {
s_logger.info("monitor() :: !!! SIM CARD IS READY !!! connecting ...");
pppService.connect();
if (m_pppState == PppState.NOT_CONNECTED) {
m_resetTimerStart = System.currentTimeMillis();
}
} else {
s_logger.warn("monitor() :: ! SIM CARD IS NOT READY !");
}
} else {
s_logger.info("monitor() :: connecting ...");
pppService.connect();
if (m_pppState == PppState.NOT_CONNECTED) {
m_resetTimerStart = System.currentTimeMillis();
}
}
} else if (pppState == PppState.IN_PROGRESS) {
long modemResetTout = getModemResetTimeoutMsec(ifaceName, modem.getConfiguration());
if (modemResetTout > 0) {
long timeElapsed = System.currentTimeMillis() - m_resetTimerStart;
if (timeElapsed > modemResetTout) {
// reset modem
s_logger.info("monitor() :: Modem Reset TIMEOUT !!!");
pppService.disconnect();
if (modem.isGpsEnabled() && !disableModemGps(modem)) {
s_logger.error("monitor() :: Failed to disable modem GPS");
}
modem.reset();
pppState = PppState.NOT_CONNECTED;
} else {
int timeTillReset = (int)(modemResetTout - timeElapsed) / 1000;
s_logger.info("monitor() :: PPP connection in progress. Modem will be reset in {} sec if not connected", timeTillReset);
}
}
} else if (pppState == PppState.CONNECTED) {
m_resetTimerStart = System.currentTimeMillis();
}
m_pppState = pppState;
ConnectionInfo connInfo = new ConnectionInfoImpl(ifaceName);
InterfaceState interfaceState = new InterfaceState(ifaceName,
LinuxNetworkUtil.isUp(ifaceName),
pppState == PppState.CONNECTED,
connInfo.getIpAddress());
newInterfaceStatuses.put(ifaceName, interfaceState);
}
if(modem.isGpsSupported()) {
if (isGpsEnabledInConfig(modem.getConfiguration())) {
if (modem instanceof HspaCellularModem) {
if (!modem.isGpsEnabled()) {
modem.enableGps();
}
}
postModemGpsEvent(modem, true);
}
}
} catch (Exception e) {
s_logger.error("monitor() :: Exception", e);
if ((pppService != null) && (pppState != null)) {
try {
s_logger.info("monitor() :: Exception :: PPPD disconnect");
pppService.disconnect();
} catch (KuraException e1) {
s_logger.error("monitor() :: Exception while disconnect", e1);
}
m_pppState = pppState;
}
if (modem.isGpsEnabled()) {
try {
if (!disableModemGps(modem)) {
s_logger.error("monitor() :: Failed to disable modem GPS");
}
} catch (KuraException e1) {
s_logger.error("monitor() :: Exception disableModemGps", e1);
}
}
try {
s_logger.info("monitor() :: Exception :: modem reset");
modem.reset();
} catch (KuraException e1) {
s_logger.error("monitor() :: Exception modem.reset", e1);
}
}
}
// post event for any status changes
checkStatusChange(m_interfaceStatuses, newInterfaceStatuses);
m_interfaceStatuses = newInterfaceStatuses;
}
}
private void checkStatusChange(Map<String, InterfaceState> oldStatuses, Map<String, InterfaceState> newStatuses) {
if (newStatuses != null) {
// post NetworkStatusChangeEvent on current and new interfaces
for(String interfaceName : newStatuses.keySet()) {
if ((oldStatuses != null) && oldStatuses.containsKey(interfaceName)) {
if (!newStatuses.get(interfaceName).equals(oldStatuses.get(interfaceName))) {
s_logger.debug("Posting NetworkStatusChangeEvent on interface: {}", interfaceName);
m_eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, newStatuses.get(interfaceName), null));
}
} else {
s_logger.debug("Posting NetworkStatusChangeEvent on enabled interface: " + interfaceName);
m_eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, newStatuses.get(interfaceName), null));
}
}
// post NetworkStatusChangeEvent on interfaces that are no longer there
if (oldStatuses != null) {
for(String interfaceName : oldStatuses.keySet()) {
if(!newStatuses.containsKey(interfaceName)) {
s_logger.debug("Posting NetworkStatusChangeEvent on disabled interface: {}", interfaceName);
m_eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, oldStatuses.get(interfaceName), null));
}
}
}
}
}
private void trackModem(ModemDevice modemDevice) {
Class<? extends CellularModemFactory> modemFactoryClass = null;
if (modemDevice instanceof UsbModemDevice) {
SupportedUsbModemInfo supportedUsbModemInfo = SupportedUsbModemsInfo.getModem((UsbModemDevice)modemDevice);
UsbModemFactoryInfo usbModemFactoryInfo = SupportedUsbModemsFactoryInfo.getModem(supportedUsbModemInfo);
modemFactoryClass = usbModemFactoryInfo.getModemFactoryClass();
} else if (modemDevice instanceof SerialModemDevice) {
SupportedSerialModemInfo supportedSerialModemInfo = SupportedSerialModemsInfo.getModem();
SerialModemFactoryInfo serialModemFactoryInfo = SupportedSerialModemsFactoryInfo.getModem(supportedSerialModemInfo);
modemFactoryClass = serialModemFactoryInfo.getModemFactoryClass();
}
if (modemFactoryClass != null) {
CellularModemFactory modemFactoryService = null;
try {
try {
Method getInstanceMethod = modemFactoryClass.getDeclaredMethod("getInstance", (Class<?>[]) null);
getInstanceMethod.setAccessible(true);
modemFactoryService = (CellularModemFactory) getInstanceMethod.invoke(null, (Object[]) null);
} catch (Exception e) {
s_logger.error("Error calling getInstance() method on " + modemFactoryClass.getName() + e);
}
// if unsuccessful in calling getInstance()
if (modemFactoryService == null) {
modemFactoryService = (CellularModemFactory) modemFactoryClass.newInstance();
}
String platform = null;
if(m_systemService != null) {
platform = m_systemService.getPlatform();
}
CellularModem modem = modemFactoryService.obtainCellularModemService(modemDevice, platform);
try {
HashMap<String, String> modemInfoMap = new HashMap<String, String>();
modemInfoMap.put(ModemReadyEvent.IMEI, modem.getSerialNumber());
modemInfoMap.put(ModemReadyEvent.IMSI, modem.getMobileSubscriberIdentity());
modemInfoMap.put(ModemReadyEvent.ICCID, modem.getIntegratedCirquitCardId());
modemInfoMap.put(ModemReadyEvent.RSSI, Integer.toString(modem.getSignalStrength()));
s_logger.info("posting ModemReadyEvent on topic {}", ModemReadyEvent.MODEM_EVENT_READY_TOPIC);
m_eventAdmin.postEvent(new ModemReadyEvent(modemInfoMap));
} catch (Exception e) {
s_logger.error("Failed to post the ModemReadyEvent - {}", e);
}
String ifaceName = m_networkService.getModemPppPort(modemDevice);
List<NetConfig> netConfigs = null;
if (ifaceName != null) {
NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = m_networkConfig
.getNetInterfaceConfig(ifaceName);
if(netInterfaceConfig == null) {
m_networkConfig = m_netConfigService.getNetworkConfiguration();
netInterfaceConfig = m_networkConfig.getNetInterfaceConfig(ifaceName);
}
if (netInterfaceConfig != null) {
netConfigs = getNetConfigs(netInterfaceConfig);
if ((netConfigs != null) && (netConfigs.size() > 0)) {
modem.setConfiguration(netConfigs);
}
}
}
if (modemDevice instanceof UsbModemDevice) {
m_modems.put(((UsbModemDevice)modemDevice).getUsbPort(), modem);
} else if (modemDevice instanceof SerialModemDevice) {
m_modems.put(modemDevice.getProductName(), modem);
}
if (modem instanceof EvdoCellularModem) {
NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(netConfigs);
if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) {
if (modem.isGpsEnabled()) {
if (!disableModemGps(modem)) {
s_logger.error("trackModem() :: Failed to disable modem GPS, resetting modem ...");
modem.reset();
}
}
if (!((EvdoCellularModem) modem).isProvisioned()) {
s_logger.info("trackModem() :: The {} is not provisioned, will try to provision it ...", modem.getModel());
if ((task != null) && !task.isCancelled()) {
s_logger.info("trackModem() :: Cancelling monitor task");
stopThread.set(true);
monitorNotity();
task.cancel(true);
task = null;
}
((EvdoCellularModem) modem).provision();
if (task == null) {
s_logger.info("trackModem() :: Restarting monitor task");
stopThread.set(false);
task = m_executor.submit(new Runnable() {
@Override
public void run() {
while (!stopThread.get()) {
Thread.currentThread().setName("ModemMonitor");
try {
monitor();
monitorWait();
} catch (InterruptedException interruptedException) {
Thread.interrupted();
s_logger.debug("modem monitor interrupted - {}", interruptedException);
} catch (Throwable t) {
s_logger.error("trackModem() :: Exception while monitoring cellular connection {}", t);
}
}
}});
} else {
monitorNotity();
}
} else {
s_logger.info("trackModem() :: The {} is provisioned", modem.getModel());
}
}
if (modem.isGpsSupported()) {
if (isGpsEnabledInConfig(netConfigs) && !modem.isGpsEnabled()) {
modem.enableGps();
postModemGpsEvent(modem, true);
}
}
}
} catch (Exception e) {
s_logger.error("trackModem() :: {}", e);
}
}
}
private boolean disableModemGps(CellularModem modem) throws KuraException {
postModemGpsEvent(modem, false);
boolean portIsReachable = false;
long startTimer = System.currentTimeMillis();
do {
try {
Thread.sleep(3000);
if (modem.isPortReachable(modem.getAtPort())) {
s_logger.debug("disableModemGps() modem is now reachable ...");
portIsReachable = true;
break;
} else {
s_logger.debug("disableModemGps() waiting for PositionService to release serial port ...");
}
} catch (Exception e) {
s_logger.debug("disableModemGps() waiting for PositionService to release serial port: ex={}", e);
}
} while ((System.currentTimeMillis()-startTimer) < 20000L);
modem.disableGps();
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
boolean ret = false;
if (portIsReachable && !modem.isGpsEnabled()) {
s_logger.error("disableModemGps() :: Modem GPS is disabled :: portIsReachable={}, modem.isGpsEnabled()={}",
portIsReachable, modem.isGpsEnabled());
ret = true;
}
return ret;
}
private void postModemGpsEvent(CellularModem modem, boolean enabled) throws KuraException {
if (enabled) {
CommURI commUri = modem.getSerialConnectionProperties(CellularModem.SerialPortType.GPSPORT);
if (commUri != null) {
s_logger.trace("postModemGpsEvent() :: Modem SeralConnectionProperties: {}", commUri.toString());
HashMap<String, Object> modemInfoMap = new HashMap<String, Object>();
modemInfoMap.put(ModemGpsEnabledEvent.Port, modem.getGpsPort());
modemInfoMap.put(ModemGpsEnabledEvent.BaudRate, Integer.valueOf(commUri.getBaudRate()));
modemInfoMap.put(ModemGpsEnabledEvent.DataBits, Integer.valueOf(commUri.getDataBits()));
modemInfoMap.put(ModemGpsEnabledEvent.StopBits, Integer.valueOf(commUri.getStopBits()));
modemInfoMap.put(ModemGpsEnabledEvent.Parity, Integer.valueOf(commUri.getParity()));
s_logger.debug("postModemGpsEvent() :: posting ModemGpsEnabledEvent on topic {}", ModemGpsEnabledEvent.MODEM_EVENT_GPS_ENABLED_TOPIC);
m_eventAdmin.postEvent(new ModemGpsEnabledEvent(modemInfoMap));
}
} else {
s_logger.debug("postModemGpsEvent() :: posting ModemGpsDisableEvent on topic {}", ModemGpsDisabledEvent.MODEM_EVENT_GPS_DISABLED_TOPIC);
HashMap<String, Object> modemInfoMap = new HashMap<String, Object>();
m_eventAdmin.postEvent(new ModemGpsDisabledEvent(modemInfoMap));
}
}
private void monitorNotity() {
if (stopThread != null) {
synchronized (stopThread) {
stopThread.notifyAll();
}
}
}
private void monitorWait() throws InterruptedException {
if (stopThread != null) {
synchronized (stopThread) {
stopThread.wait(THREAD_INTERVAL);
}
}
}
}
|
package liquibase.diff.output.changelog.core;
import liquibase.change.Change;
import liquibase.change.core.LoadDataChange;
import liquibase.change.core.LoadDataColumnConfig;
import liquibase.database.Database;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.database.jvm.JdbcConnection;
import liquibase.diff.output.DiffOutputControl;
import liquibase.diff.output.changelog.ChangeGeneratorChain;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.LiquibaseService;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Data;
import liquibase.structure.core.Table;
import liquibase.util.ISODateFormat;
import liquibase.util.JdbcUtils;
import liquibase.util.csv.CSVWriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@LiquibaseService(skip = true)
public class MissingDataExternalFileChangeGenerator extends MissingDataChangeGenerator {
private String dataDir;
public MissingDataExternalFileChangeGenerator(String dataDir) {
this.dataDir = dataDir;
}
@Override
public int getPriority(Class<? extends DatabaseObject> objectType, Database database) {
if (Data.class.isAssignableFrom(objectType)) {
return PRIORITY_ADDITIONAL;
}
return PRIORITY_NONE;
}
@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl outputControl, Database referenceDatabase, Database comparisionDatabase, ChangeGeneratorChain chain) {
Statement stmt = null;
ResultSet rs = null;
try {
Data data = (Data) missingObject;
Table table = data.getTable();
if (referenceDatabase.isLiquibaseObject(table)) {
return null;
}
String sql = "SELECT * FROM " + referenceDatabase.escapeTableName(table.getSchema().getCatalogName(), table.getSchema().getName(), table.getName());
stmt = ((JdbcConnection) referenceDatabase.getConnection()).createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(100);
rs = stmt.executeQuery(sql);
List<String> columnNames = new ArrayList<String>();
for (int i=0; i< rs.getMetaData().getColumnCount(); i++) {
columnNames.add(rs.getMetaData().getColumnName(i+1));
}
String fileName = table.getName().toLowerCase() + ".csv";
if (dataDir != null) {
fileName = dataDir + "/" + fileName;
}
File parentDir = new File(dataDir);
if (!parentDir.exists()) {
parentDir.mkdirs();
}
if (!parentDir.isDirectory()) {
throw new RuntimeException(parentDir
+ " is not a directory");
}
CSVWriter outputFile = new CSVWriter(new BufferedWriter(new FileWriter(fileName)));
String[] dataTypes = new String[columnNames.size()];
String[] line = new String[columnNames.size()];
for (int i = 0; i < columnNames.size(); i++) {
line[i] = columnNames.get(i);
}
outputFile.writeNext(line);
int rowNum = 0;
while (rs.next()) {
line = new String[columnNames.size()];
for (int i = 0; i < columnNames.size(); i++) {
Object value = JdbcUtils.getResultSetValue(rs, i + 1);
if (dataTypes[i] == null && value != null) {
if (value instanceof Number) {
dataTypes[i] = "NUMERIC";
} else if (value instanceof Boolean) {
dataTypes[i] = "BOOLEAN";
} else if (value instanceof Date) {
dataTypes[i] = "DATE";
} else {
dataTypes[i] = "STRING";
}
}
if (value == null) {
line[i] = "NULL";
} else {
if (value instanceof Date) {
line[i] = new ISODateFormat().format(((Date) value));
} else {
line[i] = value.toString();
}
}
}
outputFile.writeNext(line);
rowNum++;
if (rowNum % 5000 == 0) {
outputFile.flush();
}
}
outputFile.flush();
outputFile.close();
LoadDataChange change = new LoadDataChange();
change.setFile(fileName);
change.setEncoding("UTF-8");
if (outputControl.getIncludeCatalog()) {
change.setCatalogName(table.getSchema().getCatalogName());
}
if (outputControl.getIncludeSchema()) {
change.setSchemaName(table.getSchema().getName());
}
change.setTableName(table.getName());
for (int i = 0; i < columnNames.size(); i++) {
String colName = columnNames.get(i);
LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
columnConfig.setHeader(colName);
columnConfig.setName(colName);
columnConfig.setType(dataTypes[i]);
change.addColumn(columnConfig);
}
return new Change[]{
change
};
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ignore) { }
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ignore) { }
}
}
}
}
|
package eu.liveandgov.wp1.sensor_miner;
import android.content.Intent;
import android.hardware.SensorManager;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import eu.liveandgov.wp1.sensor_miner.configuration.ExtendedIntentAPI;
import eu.liveandgov.wp1.sensor_miner.connectors.sensor_queue.SensorQueue;
public class GlobalContext {
public static ServiceSensorControl context;
public static void set(ServiceSensorControl newContext) {
context = newContext;
}
public static SensorManager getSensorManager(){
if (context == null) throw new IllegalStateException("Context not initialized");
return (SensorManager) context.getSystemService(context.SENSOR_SERVICE);
}
public static WifiManager getWifiManager(){
if (context == null) throw new IllegalStateException("Context not initialized");
return (WifiManager) context.getSystemService(context.WIFI_SERVICE);
}
public static String getUserId() {
if (context == null) throw new IllegalStateException("Context not initialized");
return context.userId;
}
public static SensorQueue getSensorQueue() {
if (context == null) throw new IllegalStateException("Context not initialized");
return context.sensorQueue;
}
public static void sendLog(String message){
if (context == null) throw new IllegalStateException("Context not initialized");
Intent intent = new Intent(ExtendedIntentAPI.RETURN_LOG);
intent.putExtra(ExtendedIntentAPI.FIELD_MESSAGE, message);
context.sendBroadcast(intent);
}
}
|
package org.jnosql.diana.mongodb.document;
import org.jnosql.diana.api.document.Document;
import org.jnosql.diana.api.document.DocumentCollectionManagerAsync;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentEntity;
import org.jnosql.diana.api.document.DocumentQuery;
import org.jnosql.diana.api.document.Documents;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.notNullValue;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
import static org.jnosql.diana.mongodb.document.DocumentConfigurationUtils.getAsync;
import static org.junit.jupiter.api.Assertions.*;
public class MongoDBDocumentCollectionManagerAsyncTest {
public static final String COLLECTION_NAME = "person";
private static DocumentCollectionManagerAsync entityManager;
@BeforeAll
public static void setUp() throws IOException, InterruptedException {
MongoDbHelper.startMongoDb();
entityManager = getAsync().getAsync("database");
}
@Test
public void shouldInsertAsync() throws InterruptedException {
AtomicBoolean condition = new AtomicBoolean(false);
DocumentEntity entity = getEntity();
entityManager.insert(entity, c -> condition.set(true));
await().untilTrue(condition);
assertTrue(condition.get());
}
@Test
public void shouldInsertIterableAsync() throws InterruptedException {
List<DocumentEntity> entities = Collections.singletonList(getEntity());
entityManager.insert(entities);
}
@Test
public void shouldThrowExceptionWhenInsertWithTTL() {
assertThrows(UnsupportedOperationException.class, () -> entityManager.insert(getEntity(), Duration.ofSeconds(10)));
}
@Test
public void shouldThrowExceptionWhenInsertWithTTLWithCallback() {
assertThrows(UnsupportedOperationException.class, () -> entityManager.insert(getEntity(), Duration.ofSeconds(10), r -> {}));
}
@Test
public void shouldUpdateAsync() throws InterruptedException {
Random random = new Random();
long id = random.nextLong();
AtomicBoolean condition = new AtomicBoolean(false);
AtomicReference<DocumentEntity> reference = new AtomicReference<>();
DocumentEntity entity = getEntity();
entity.add("_id", id);
entityManager.insert(entity, c -> {
condition.set(true);
reference.set(c);
});
await().untilTrue(condition);
entityManager.update(reference.get(), c -> condition.set(true));
assertTrue(condition.get());
}
@Test
public void shouldUpdateIterableAsync() throws InterruptedException {
Random random = new Random();
long id = random.nextLong();
AtomicBoolean condition = new AtomicBoolean(false);
AtomicReference<DocumentEntity> reference = new AtomicReference<>();
DocumentEntity entity = getEntity();
entity.add("_id", id);
entityManager.insert(entity, c -> {
condition.set(true);
reference.set(c);
});
await().untilTrue(condition);
entityManager.update(Collections.singletonList(entity));
}
@Test
public void shouldSelect() throws InterruptedException {
DocumentEntity entity = getEntity();
for (int index = 0; index < 10; index++) {
entityManager.insert(entity);
}
AtomicBoolean condition = new AtomicBoolean(false);
DocumentQuery query = select().from(entity.getName()).build();
AtomicReference<List<DocumentEntity>> atomicReference = new AtomicReference<>();
entityManager.select(query, c -> {
condition.set(true);
atomicReference.set(c);
});
await().untilTrue(condition);
List<DocumentEntity> entities = atomicReference.get();
assertTrue(condition.get());
assertFalse(entities.isEmpty());
}
@Test
public void shouldRemoveEntityAsync() throws InterruptedException {
AtomicReference<DocumentEntity> entityAtomic = new AtomicReference<>();
entityManager.insert(getEntity(), entityAtomic::set);
await().until(entityAtomic::get, notNullValue(DocumentEntity.class));
DocumentEntity entity = entityAtomic.get();
Document document = entity.find("name").get();
assertNotNull(entity);
assertNotNull(document);
String collection = entity.getName();
DocumentDeleteQuery deleteQuery = delete().from(collection)
.where("name").eq(document.get())
.build();
AtomicBoolean condition = new AtomicBoolean(false);
entityManager.delete(deleteQuery, c -> condition.set(true));
await().untilTrue(condition);
AtomicBoolean selectCondition = new AtomicBoolean(false);
AtomicReference<List<DocumentEntity>> reference = new AtomicReference<>();
DocumentQuery selectQuery = select().from(collection)
.where("name").eq(document.get())
.build();
entityManager.select(selectQuery, c -> {
selectCondition.set(true);
reference.set(c);
});
await().untilTrue(selectCondition);
assertTrue(reference.get().isEmpty());
}
private DocumentEntity getEntity() {
DocumentEntity entity = DocumentEntity.of(COLLECTION_NAME);
Map<String, Object> map = new HashMap<>();
map.put("name", "Poliana");
map.put("city", "Salvador");
List<Document> documents = Documents.of(map);
documents.forEach(entity::add);
return entity;
}
@AfterAll
public static void end() {
MongoDbHelper.stopMongoDb();
}
}
|
package org.nuxeo.connect.client.jsf;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage;
import org.nuxeo.connect.client.status.ConnectStatusHolder;
import org.nuxeo.connect.client.status.ConnectUpdateStatusInfo;
import org.nuxeo.connect.client.status.SubscriptionStatusWrapper;
import org.nuxeo.connect.connector.NuxeoClientInstanceType;
import org.nuxeo.connect.connector.http.ConnectUrlConfig;
import org.nuxeo.connect.data.SubscriptionStatusType;
import org.nuxeo.connect.identity.LogicalInstanceIdentifier;
import org.nuxeo.connect.identity.LogicalInstanceIdentifier.InvalidCLID;
import org.nuxeo.connect.identity.TechnicalInstanceIdentifier;
import org.nuxeo.connect.registration.ConnectRegistrationService;
import org.nuxeo.connect.update.PackageUpdateService;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.runtime.api.Framework;
/**
* Seam Bean to expose Connect Registration operations.
* <ul>
* <li>getting status
* <li>registering
* <li>...
* </ul>
*
* @author <a href="mailto:[email protected]">Thierry Delprat</a>
*/
@Name("connectStatus")
@Scope(ScopeType.CONVERSATION)
public class ConnectStatusActionBean implements Serializable {
private static final long serialVersionUID = 1L;
public static final String CLIENT_BANNER_TYPE = "clientSideBanner";
public static final String SERVER_BANNER_TYPE = "serverSideBanner";
private static final Log log = LogFactory.getLog(ConnectStatusActionBean.class);
@In(create = true, required = false)
protected FacesMessages facesMessages;
@In(create = true, required = true, value = "appsViews")
protected AppCenterViewsManager appsViews;
@In(create = true)
protected Map<String, String> messages;
protected String CLID;
protected String token;
protected ConnectUpdateStatusInfo connectionStatusCache;
public String getRegistredCLID() throws Exception {
if (isRegistred()) {
return LogicalInstanceIdentifier.instance().getCLID();
} else {
return null;
}
}
public String getCLID() {
return CLID;
}
public void setCLID(String cLID) {
CLID = cLID;
}
public String unregister() {
LogicalInstanceIdentifier.cleanUp();
resetRegister();
return null;
}
public List<SelectItem> getInstanceTypes() {
List<SelectItem> types = new ArrayList<>();
for (NuxeoClientInstanceType itype : NuxeoClientInstanceType.values()) {
SelectItem item = new SelectItem(itype.getValue(),
"label.instancetype." + itype.getValue());
types.add(item);
}
return types;
}
protected ConnectRegistrationService getService() {
return Framework.getLocalService(ConnectRegistrationService.class);
}
@Factory(scope = ScopeType.APPLICATION, value = "registredConnectInstance")
public boolean isRegistred() {
return getService().isInstanceRegistred();
}
protected void flushContextCache() {
// A4J and Event cache don't play well ...
Contexts.getApplicationContext().remove("registredConnectInstance");
Contexts.getApplicationContext().remove("connectUpdateStatusInfo");
appsViews.flushCache();
}
@Factory(value = "connectServerReachable", scope = ScopeType.EVENT)
public boolean isConnectServerReachable() {
return !ConnectStatusHolder.instance().getStatus().isConnectServerUnreachable();
}
public String refreshStatus() {
ConnectStatusHolder.instance().getStatus(true);
flushContextCache();
return null;
}
public SubscriptionStatusWrapper getStatus() {
return ConnectStatusHolder.instance().getStatus();
}
public String resetRegister() {
flushContextCache();
return null;
}
public String getToken() {
return token;
}
public void setToken(String token) throws IOException, InvalidCLID {
if (token != null) {
String tokenData = new String(Base64.decodeBase64(token));
String[] tokenDataLines = tokenData.split("\n");
for (String line : tokenDataLines) {
String[] parts = line.split(":");
if (parts.length > 1 && "CLID".equals(parts[0])) {
getService().localRegisterInstance(parts[1], " ");
// force refresh of connect status info
connectionStatusCache = null;
flushContextCache();
ConnectStatusHolder.instance().flush();
}
}
}
}
public String getCTID() throws Exception {
return TechnicalInstanceIdentifier.instance().getCTID();
}
public String localRegister() {
try {
getService().localRegisterInstance(CLID, "");
} catch (InvalidCLID e) {
facesMessages.addToControl("offline_clid",
StatusMessage.Severity.WARN,
messages.get("label.connect.wrongCLID"));
} catch (IOException e) {
facesMessages.addToControl("offline_clid",
StatusMessage.Severity.ERROR,
messages.get("label.connect.registrationError"));
log.error("Error while registering instance locally", e);
}
flushContextCache();
return null;
}
protected Blob packageToUpload;
protected String packageFileName;
public String getPackageFileName() {
return packageFileName;
}
public void setPackageFileName(String packageFileName) {
this.packageFileName = packageFileName;
}
public Blob getPackageToUpload() {
return packageToUpload;
}
public void setPackageToUpload(Blob packageToUpload) {
this.packageToUpload = packageToUpload;
}
public void uploadPackage() throws Exception {
if (packageToUpload == null) {
facesMessages.add(StatusMessage.Severity.WARN,
"label.connect.nofile");
return;
}
PackageUpdateService pus = Framework.getLocalService(PackageUpdateService.class);
File tmpFile = File.createTempFile("upload", "nxpkg");
packageToUpload.transferTo(tmpFile);
try {
pus.addPackage(tmpFile);
} catch (Exception e) {
facesMessages.add(
StatusMessage.Severity.ERROR,
messages.get("label.connect.wrong.package" + ":"
+ e.getMessage()));
return;
} finally {
tmpFile.delete();
packageFileName = null;
packageToUpload = null;
}
}
public ConnectUpdateStatusInfo getDynamicConnectUpdateStatusInfo() {
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String bannerType = req.getParameter("bannerType");
if ("unregistered".equals(bannerType)) {
return ConnectUpdateStatusInfo.unregistered();
} else if ("notreachable".equals(bannerType)) {
return ConnectUpdateStatusInfo.connectServerUnreachable();
} else if ("notvalid".equals(bannerType)) {
return ConnectUpdateStatusInfo.notValid();
} else if ("ok".equals(bannerType)) {
return ConnectUpdateStatusInfo.ok();
}
return getConnectUpdateStatusInfo();
}
/**
* @since 5.9.2
*/
@Factory(scope = ScopeType.APPLICATION, value = "connectBannerEnabled")
public boolean isConnectBannerEnabled() {
final String testerName = Framework.getProperty("org.nuxeo.ecm.tester.name");
if (testerName != null && testerName.equals("Nuxeo-Selenium-Tester")) {
// disable banner when running selenium tests
return false;
}
return true;
}
@Factory(scope = ScopeType.APPLICATION, value = "connectUpdateStatusInfo")
public ConnectUpdateStatusInfo getConnectUpdateStatusInfo() {
if (connectionStatusCache == null) {
try {
if (!isRegistred()) {
connectionStatusCache = ConnectUpdateStatusInfo.unregistered();
} else {
if (isConnectBannerEnabled() && isConnectServerReachable()) {
if (getStatus().isError()) {
connectionStatusCache = ConnectUpdateStatusInfo.connectServerUnreachable();
} else {
if (ConnectStatusHolder.instance().getStatus().status() == SubscriptionStatusType.OK) {
connectionStatusCache = ConnectUpdateStatusInfo.ok();
} else {
connectionStatusCache = ConnectUpdateStatusInfo.notValid();
}
}
} else {
connectionStatusCache = ConnectUpdateStatusInfo.connectServerUnreachable();
}
}
} catch (Exception e) {
log.error(e);
connectionStatusCache = null;
}
}
return connectionStatusCache;
}
@Factory("nuxeoConnectUrl")
public String getConnectServerUrl() {
return ConnectUrlConfig.getBaseUrl();
}
}
|
package com.salesmanager.shop.store.controller.customer;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.salesmanager.core.business.exception.ConversionException;
import com.salesmanager.core.business.exception.ServiceException;
import com.salesmanager.core.business.modules.email.Email;
import com.salesmanager.core.business.services.catalog.product.PricingService;
import com.salesmanager.core.business.services.customer.CustomerService;
import com.salesmanager.core.business.services.merchant.MerchantStoreService;
import com.salesmanager.core.business.services.reference.country.CountryService;
import com.salesmanager.core.business.services.reference.language.LanguageService;
import com.salesmanager.core.business.services.reference.zone.ZoneService;
import com.salesmanager.core.business.services.services.ServicesService;
import com.salesmanager.core.business.services.shoppingcart.ShoppingCartCalculationService;
import com.salesmanager.core.business.services.system.EmailService;
import com.salesmanager.core.business.utils.CoreConfiguration;
import com.salesmanager.core.model.common.Billing;
import com.salesmanager.core.model.common.VendorAttributes;
import com.salesmanager.core.model.customer.Customer;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.reference.country.Country;
import com.salesmanager.core.model.reference.language.Language;
import com.salesmanager.core.model.reference.zone.Zone;
import com.salesmanager.core.model.services.Services;
import com.salesmanager.core.model.shoppingcart.ShoppingCart;
import com.salesmanager.shop.constants.ApplicationConstants;
import com.salesmanager.shop.constants.Constants;
import com.salesmanager.shop.constants.EmailConstants;
import com.salesmanager.shop.fileupload.services.StorageException;
import com.salesmanager.shop.fileupload.services.StorageService;
import com.salesmanager.shop.model.customer.Address;
import com.salesmanager.shop.model.customer.AnonymousCustomer;
import com.salesmanager.shop.model.customer.CustomerEntity;
import com.salesmanager.shop.model.customer.SecuredShopPersistableCustomer;
import com.salesmanager.shop.model.customer.Vendor;
import com.salesmanager.shop.model.shoppingcart.ShoppingCartData;
import com.salesmanager.shop.populator.shoppingCart.ShoppingCartDataPopulator;
import com.salesmanager.shop.store.controller.AbstractController;
import com.salesmanager.shop.store.controller.ControllerConstants;
import com.salesmanager.shop.store.controller.customer.facade.CustomerFacade;
import com.salesmanager.shop.utils.CaptchaRequestUtils;
import com.salesmanager.shop.utils.DateUtil;
import com.salesmanager.shop.utils.EmailTemplatesUtils;
import com.salesmanager.shop.utils.EmailUtils;
import com.salesmanager.shop.utils.ImageFilePath;
import com.salesmanager.shop.utils.LabelUtils;
//import com.salesmanager.core.business.customer.CustomerRegistrationException;
/**
* Registration of a new customer
* @author Carl Samson
*
*/
@SuppressWarnings( "deprecation" )
@Controller
@CrossOrigin
public class CustomerRegistrationController extends AbstractController {
private static final String VENDOR_CERFIFICATES = "vendorCerfificates";
private static final String SLASH = "/";
private static final String USER_PROFILE_PIC = "userProfilePic";
private static final String TRUE = "true";
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerRegistrationController.class);
@Inject
private CoreConfiguration coreConfiguration;
@Inject
private LanguageService languageService;
@Inject
private CountryService countryService;
@Inject
private ZoneService zoneService;
@Inject
EmailService emailService;
@Inject
private LabelUtils messages;
@Inject
private AuthenticationManager customerAuthenticationManager;
@Inject
private EmailTemplatesUtils emailTemplatesUtils;
@Inject
private CaptchaRequestUtils captchaRequestUtils;
@Inject
@Qualifier("img")
private ImageFilePath imageUtils;
@Inject
private ShoppingCartCalculationService shoppingCartCalculationService;
@Inject
private PricingService pricingService;
@Inject
private EmailUtils emailUtils;
@Inject
private CustomerService customerService;
@Inject
private StorageService storageService;
@Inject
@Named("passwordEncoder")
private PasswordEncoder passwordEncoder;
@Inject
private CustomerFacade customerFacade;
@Inject
ServicesService servicesService;
private final static String RESET_PASSWORD_TPL = "email_template_password_reset_user.ftl";
private final static String NEW_USER_TMPL = "email_template_new_user.ftl";
private final static String FORGOT_PASSWORD_TPL = "email_template_user_password_link.ftl";
private final static String NEW_USER_ACTIVATION_TMPL = "email_template_new_user_activate.ftl";
@RequestMapping(value="/registration.html", method=RequestMethod.GET)
public String displayRegistration(final Model model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
MerchantStore store = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE);
model.addAttribute( "recapatcha_public_key", coreConfiguration.getProperty( ApplicationConstants.RECAPTCHA_PUBLIC_KEY ) );
SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
AnonymousCustomer anonymousCustomer = (AnonymousCustomer)request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
if(anonymousCustomer!=null) {
customer.setBilling(anonymousCustomer.getBilling());
}
model.addAttribute("customer", customer);
/** template **/
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.register).append(".").append(store.getStoreTemplate());
return template.toString();
}
@RequestMapping( value = "/register.html", method = RequestMethod.POST )
public String registerCustomer( @Valid
@ModelAttribute("customer") SecuredShopPersistableCustomer customer, BindingResult bindingResult, Model model,
HttpServletRequest request, HttpServletResponse response, final Locale locale )
throws Exception
{
MerchantStore merchantStore = (MerchantStore) request.getAttribute( Constants.MERCHANT_STORE );
Language language = super.getLanguage(request);
String userName = null;
String password = null;
model.addAttribute( "recapatcha_public_key", coreConfiguration.getProperty( ApplicationConstants.RECAPTCHA_PUBLIC_KEY ) );
if(!StringUtils.isBlank(request.getParameter("g-recaptcha-response"))) {
boolean validateCaptcha = captchaRequestUtils.checkCaptcha(request.getParameter("g-recaptcha-response"));
if ( !validateCaptcha )
{
LOGGER.debug( "Captcha response does not matched" );
FieldError error = new FieldError("captcrehaChallengeField","captchaChallengeField",messages.getMessage("validaion.recaptcha.not.matched", locale));
bindingResult.addError(error);
}
}
if ( StringUtils.isNotBlank( customer.getUserName() ) )
{
if ( customerFacade.checkIfUserExists( customer.getUserName(), merchantStore ) )
{
LOGGER.debug( "Customer with username {} already exists for this store ", customer.getUserName() );
FieldError error = new FieldError("userName","userName",messages.getMessage("registration.username.already.exists", locale));
bindingResult.addError(error);
}
userName = customer.getUserName();
}
if ( StringUtils.isNotBlank( customer.getPassword() ) && StringUtils.isNotBlank( customer.getCheckPassword() ))
{
if (! customer.getPassword().equals(customer.getCheckPassword()) )
{
FieldError error = new FieldError("password","password",messages.getMessage("message.password.checkpassword.identical", locale));
bindingResult.addError(error);
}
password = customer.getPassword();
}
if ( bindingResult.hasErrors() )
{
LOGGER.debug( "found {} validation error while validating in customer registration ",
bindingResult.getErrorCount() );
StringBuilder template =
new StringBuilder().append( ControllerConstants.Tiles.Customer.register ).append( "." ).append( merchantStore.getStoreTemplate() );
return template.toString();
}
@SuppressWarnings( "unused" )
CustomerEntity customerData = null;
try
{
//set user clear password
customer.setClearPassword(password);
customerData = customerFacade.registerCustomer( customer, merchantStore, language );
}
/* catch ( CustomerRegistrationException cre )
{
LOGGER.error( "Error while registering customer.. ", cre);
ObjectError error = new ObjectError("registration",messages.getMessage("registration.failed", locale));
bindingResult.addError(error);
StringBuilder template =
new StringBuilder().append( ControllerConstants.Tiles.Customer.register ).append( "." ).append( merchantStore.getStoreTemplate() );
return template.toString();
}*/
catch ( Exception e )
{
LOGGER.error( "Error while registering customer.. ", e);
ObjectError error = new ObjectError("registration",messages.getMessage("registration.failed", locale));
bindingResult.addError(error);
StringBuilder template =
new StringBuilder().append( ControllerConstants.Tiles.Customer.register ).append( "." ).append( merchantStore.getStoreTemplate() );
return template.toString();
}
/**
* Send registration email
*/
emailTemplatesUtils.sendRegistrationEmail( customer, merchantStore, locale, request.getContextPath() );
/**
* Login user
*/
try {
//refresh customer
Customer c = customerFacade.getCustomerByUserName(customer.getUserName(), merchantStore);
//authenticate
customerFacade.authenticate(c, userName, password);
super.setSessionAttribute(Constants.CUSTOMER, c, request);
StringBuilder cookieValue = new StringBuilder();
cookieValue.append(merchantStore.getCode()).append("_").append(c.getNick());
//set username in the cookie
Cookie cookie = new Cookie(Constants.COOKIE_NAME_USER, cookieValue.toString());
cookie.setMaxAge(60 * 24 * 3600);
cookie.setPath(Constants.SLASH);
response.addCookie(cookie);
String sessionShoppingCartCode= (String)request.getSession().getAttribute( Constants.SHOPPING_CART );
if(!StringUtils.isBlank(sessionShoppingCartCode)) {
ShoppingCart shoppingCart = customerFacade.mergeCart( c, sessionShoppingCartCode, merchantStore, language );
ShoppingCartData shoppingCartData=this.populateShoppingCartData(shoppingCart, merchantStore, language);
if(shoppingCartData !=null) {
request.getSession().setAttribute(Constants.SHOPPING_CART, shoppingCartData.getCode());
}
//set username in the cookie
Cookie c1 = new Cookie(Constants.COOKIE_NAME_CART, shoppingCartData.getCode());
c1.setMaxAge(60 * 24 * 3600);
c1.setPath(Constants.SLASH);
response.addCookie(c1);
}
return "redirect:/shop/customer/dashboard.html";
} catch(Exception e) {
LOGGER.error("Cannot authenticate user ",e);
ObjectError error = new ObjectError("registration",messages.getMessage("registration.failed", locale));
bindingResult.addError(error);
}
StringBuilder template =
new StringBuilder().append( ControllerConstants.Tiles.Customer.register ).append( "." ).append( merchantStore.getStoreTemplate() );
return template.toString();
}
@ModelAttribute("countryList")
public List<Country> getCountries(final HttpServletRequest request){
Language language = (Language) request.getAttribute( "LANGUAGE" );
try
{
if ( language == null )
{
language = (Language) request.getAttribute( "LANGUAGE" );
}
if ( language == null )
{
language = languageService.getByCode( Constants.DEFAULT_LANGUAGE );
}
List<Country> countryList=countryService.getCountries( language );
return countryList;
}
catch ( ServiceException e )
{
LOGGER.error( "Error while fetching country list ", e );
}
return Collections.emptyList();
}
@ModelAttribute("zoneList")
public List<Zone> getZones(final HttpServletRequest request){
return zoneService.list();
}
private ShoppingCartData populateShoppingCartData(final ShoppingCart cartModel , final MerchantStore store, final Language language){
ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator();
shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService );
shoppingCartDataPopulator.setPricingService( pricingService );
try
{
return shoppingCartDataPopulator.populate( cartModel , store, language);
}
catch ( ConversionException ce )
{
LOGGER.error( "Error in converting shopping cart to shopping cart data", ce );
}
return null;
}
/*@RequestMapping( value = "/securedcustomer", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public SecuredShopPersistableCustomer getCustomerData(){
SecuredShopPersistableCustomer c = new SecuredShopPersistableCustomer();
c.setUserName("ram");
c.setPassword("password");
c.setFirstName("ramu");
c.setLastName("m");
c.setGender("M");
c.setEmailAddress("[email protected]");
c.setPassword("ram@1234");
c.setCheckPassword("ram@1234");
c.setLanguage("en");
c.setStoreCode("DEFAULT");
Address billingAdd = new Address();
billingAdd.setAddress("");
billingAdd.setBillingAddress(true);
billingAdd.setCity("Mancherial");
billingAdd.setCompany("Nokia Networks");
billingAdd.setFirstName("ram");
billingAdd.setLastName("m");
billingAdd.setPostalCode("500045");
billingAdd.setCountry("India");
c.setBilling(billingAdd);
c.setDelivery(billingAdd);
return c;
}*/
@Inject
MerchantStoreService merchantStoreService ;
//LanguageService languageService;
@RequestMapping( value = "/customer/user/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<CustomerEntity> registerCustomers(@RequestBody SecuredShopPersistableCustomer customer,HttpServletRequest request)
throws Exception
{ System.out.println("customer ");
final Locale locale = request.getLocale();
System.out.println("Entered registration");
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
System.out.println("merchantStore "+merchantStore);
//Language language = super.getLanguage(request);
Language language = languageService.getByCode( Constants.DEFAULT_LANGUAGE );
String userName = null;
String password = null;
if ( StringUtils.isNotBlank( customer.getUserName() ) )
{
if ( customerFacade.checkIfUserExists( customer.getUserName(), merchantStore ) )
{
LOGGER.debug( "Customer with username {} already exists for this store ", customer.getUserName() );
FieldError error = new FieldError("userName","userName",messages.getMessage("registration.username.already.exists", locale));
System.out.println(" error "+error);
//bindingResult.addError(error);
}
userName = customer.getUserName();
}
if ( StringUtils.isNotBlank( customer.getPassword() ) && StringUtils.isNotBlank( customer.getCheckPassword() ))
{
if (! customer.getPassword().equals(customer.getCheckPassword()) )
{
FieldError error = new FieldError("password","password",messages.getMessage("message.password.checkpassword.identical", locale));
System.out.println("error "+error);
}
password = customer.getPassword();
}
System.out.println("userName "+userName+" password "+password);
@SuppressWarnings( "unused" )
CustomerEntity customerData = null;
try
{
//set user clear password
customer.setClearPassword(password);
customerData = customerFacade.registerCustomer( customer, merchantStore, language );
System.out.println("customerData is "+customerData);
} catch ( Exception e ) {
LOGGER.error( "Error while registering customer.. ", e);
return new ResponseEntity<CustomerEntity>(customerData,HttpStatus.CONFLICT);
}
return new ResponseEntity<CustomerEntity>(customerData,HttpStatus.OK);
}
@RequestMapping(value="/customer/update", method = RequestMethod.POST)
@ResponseBody
public CustomerResponse updateCustomer(@RequestBody CustomerRequest customerRequest)
throws Exception
{
LOGGER.debug("Entered updateCustomer ");
CustomerResponse customerResponse = new CustomerResponse();
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
Customer customer = null;
final Locale locale = new Locale("en");
if ( StringUtils.isNotBlank( customerRequest.getEmail() ) )
{
customer = customerFacade.getCustomerByUserName(customerRequest.getEmail(), merchantStore );
if(customer == null){
customerResponse.setErrorMessage("Customer is not exist, update is not possible ");
return customerResponse;
}
}
if ( StringUtils.isNotBlank( customerRequest.getPassword() ) && StringUtils.isNotBlank( customerRequest.getConfirmPassword() ))
{
if (! customerRequest.getPassword().equals(customerRequest.getConfirmPassword()) )
{
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
}
Address address = new Address();
address.setFirstName(customerRequest.getFirstName());
address.setLastName(customerRequest.getLastName());
address.setAddress(customerRequest.getAddress());
address.setPostalCode(customerRequest.getPostalCode());
address.setCity(customerRequest.getCity());
address.setStateProvince(customerRequest.getState());
address.setPhone(customerRequest.getPhone());
address.setBillingAddress(true);
customer.setArea(customerRequest.getArea());
String dobStr = customerRequest.getDob();
if(StringUtils.isNotBlank(dobStr)){
customer.setDateOfBirth(DateUtil.getDate(dobStr));
}
Language language = languageService.getByCode( Constants.DEFAULT_LANGUAGE );
customerFacade.updateAddress(customer, merchantStore, address, language);
LOGGER.debug("Customer profile updated successfully");
customerResponse.setSuccessMessage("Customer profile updated successfully");
customerResponse.setStatus(TRUE);
LOGGER.debug("Ended updateCustomer");
return customerResponse;
}
@RequestMapping(value="/vendor/register", method = RequestMethod.POST)
@ResponseBody
// public CustomerResponse registerCustomer(@RequestBody VendorRequest vendorRequest) throws Exception {
public CustomerResponse registerVendor(@RequestPart("vendorRequest") String vendorRequestStr,
@RequestPart("file") MultipartFile vendorCertificate) throws Exception {
LOGGER.debug("Entered registerVendor");
VendorRequest vendorRequest = new ObjectMapper().readValue(vendorRequestStr, VendorRequest.class);
CustomerResponse customerResponse = new CustomerResponse();
customerResponse.setStatus("false");
if(!isTermsAndConditionsAccepted(vendorRequest.getTermsAndConditions())){
LOGGER.debug("Accept terms and conditions");
customerResponse.setErrorMessage("Please accept Terms & Conditions ");
return customerResponse;
}
SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
customer.setEmailAddress(vendorRequest.getEmail());
customer.setPassword(vendorRequest.getPassword());
customer.setCheckPassword(vendorRequest.getConfirmPassword());
customer.setFirstName(vendorRequest.getVendorName());
customer.setLastName(vendorRequest.getVendorName());
customer.setUserName(vendorRequest.getEmail());
customer.setStoreCode("DEFAULT");
Address billing = new Address();
billing.setFirstName(vendorRequest.getVendorName());
billing.setLastName(vendorRequest.getVendorName());
billing.setBillingAddress(true);
billing.setAddress(vendorRequest.getVendorOfficeAddress());
billing.setPhone(vendorRequest.getVendorTelephone());
billing.setCountry("IN");
billing.setBillingAddress(true);
/* Address delivery = new Address();
delivery.setFirstName(vendorRequest.getVendorName());
delivery.setLastName(vendorRequest.getVendorName());
delivery.setAddress(vendorRequest.getVendorOfficeAddress());
delivery.setPhone(vendorRequest.getVendorTelephone());
*/
customer.setBilling(billing);
//customer.setDelivery(delivery);
customer.setCustomerType("1");
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
final Locale locale = new Locale("en");
if ( StringUtils.isNotBlank( customer.getUserName() ) )
{
if ( customerFacade.checkIfUserExists( customer.getUserName(), merchantStore ) )
{
LOGGER.debug( "Customer with username {} already exists for this store ", customer.getUserName() );
customerResponse.setErrorMessage(messages.getMessage("registration.username.already.exists", locale));
return customerResponse;
}
}
if ( StringUtils.isNotBlank( customer.getPassword() ) && StringUtils.isNotBlank( customer.getCheckPassword() )) {
if (! customer.getPassword().equals(customer.getCheckPassword()) )
{
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
}
if ( StringUtils.isBlank( vendorRequest.getActivationURL() )) {
customerResponse.setErrorMessage(messages.getMessage("failure.customer.activation.link", locale));
return customerResponse;
}
// Store file into file sytem
Vendor vendorAttrs = new Vendor();
String certFileName = "";
if(vendorCertificate.getSize() != 0) {
try{
LOGGER.debug("Storing vendor certificate");
certFileName = storageService.store(vendorCertificate);
System.out.println("certFileName "+certFileName);
}catch(StorageException se){
LOGGER.error("StoreException occured"+se.getMessage());
}
vendorAttrs.setVendorAuthCert(certFileName);
}
vendorAttrs.setVendorName(vendorRequest.getVendorName());
vendorAttrs.setVendorOfficeAddress(vendorRequest.getVendorOfficeAddress());
vendorAttrs.setVendorMobile(vendorRequest.getVendorMobile());
vendorAttrs.setVendorTelephone(vendorRequest.getVendorTelephone());
vendorAttrs.setVendorFax(vendorRequest.getVendorFax());
vendorAttrs.setVendorConstFirm(vendorRequest.getVendorConstFirm());
vendorAttrs.setVendorCompanyNature(vendorRequest.getVendorCompanyNature());
vendorAttrs.setVendorRegistrationNo(vendorRequest.getVendorRegistrationNo());
vendorAttrs.setVendorPAN(vendorRequest.getVendorPAN());
vendorAttrs.setVendorVatRegNo(vendorRequest.getVatRegNo());
vendorAttrs.setVendorExpLine(vendorRequest.getVendorExpLine());
vendorAttrs.setVendorMajorCust(vendorRequest.getVendorMajorCust());
vendorAttrs.setVendorTIN(vendorRequest.getVendorTIN());
vendorAttrs.setVendorLicense(vendorRequest.getVendorLicense());
customer.setVendor(vendorAttrs);
Language language = languageService.getByCode( Constants.DEFAULT_LANGUAGE );
String userName = null;
String password = null;
if ( StringUtils.isNotBlank( customer.getUserName() ) ) {
if ( customerFacade.checkIfUserExists( customer.getUserName(), merchantStore ) ) {
LOGGER.debug( "Customer with username {} already exists for this store ", customer.getUserName() );
customerResponse.setErrorMessage(messages.getMessage("registration.username.already.exists", locale));
return customerResponse;
}
userName = customer.getUserName();
}
if ( StringUtils.isNotBlank( customer.getPassword() ) && StringUtils.isNotBlank( customer.getCheckPassword() )) {
if (! customer.getPassword().equals(customer.getCheckPassword()) ) {
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
password = customer.getPassword();
}
if ( StringUtils.isBlank( vendorRequest.getActivationURL() ))
{
customerResponse.setErrorMessage(messages.getMessage("failure.vendor.activation.link", locale));
return customerResponse;
}
System.out.println("userName "+userName+" password "+password);
@SuppressWarnings( "unused" )
CustomerEntity customerData = null;
try
{
//set user clear password
customer.setClearPassword(password);
customer.setActivated("0");
customerData = customerFacade.registerCustomer( customer, merchantStore, language );
System.out.println("customerData is "+customerData);
} catch ( Exception e )
{ /// if any exception raised during creation of customer we have to delete the certificate
storageService.deleteFile(certFileName);
LOGGER.error( "Error while registering customer.. ", e);
customerResponse.setErrorMessage(e.getMessage());
return customerResponse;
}
customerResponse.setSuccessMessage("Vendor registration successfull");
customerResponse.setStatus(TRUE);
String activationURL = vendorRequest.getActivationURL()+"?email="+vendorRequest.getEmail();
//sending email
String[] activationURLArg = {activationURL};
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(merchantStore, messages, locale);
templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, customer.getFirstName());
templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, customer.getLastName());
templateTokens.put(EmailConstants.EMAIL_ADMIN_USERNAME_LABEL, messages.getMessage("label.generic.username",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION, messages.getMessage("email.newuser.text.activation",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION_LINK, messages.getMessage("email.newuser.text.activation.link",activationURLArg,locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL, messages.getMessage("label.generic.password",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
Email email = new Email();
email.setFrom(merchantStore.getStorename());
email.setFromEmail(merchantStore.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.newuser.text.activation",locale));
email.setTo(vendorRequest.getEmail());
email.setTemplateName(NEW_USER_ACTIVATION_TMPL);
email.setTemplateTokens(templateTokens);
emailService.sendHtmlEmail(merchantStore, email);
LOGGER.debug("Ended registerVendor");
return customerResponse;
}
private boolean isTermsAndConditionsAccepted(boolean termsAndCond) {
return termsAndCond;
}
@RequestMapping(value="/user/activate", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public CustomerResponse acvitateUser(@RequestBody CustomerRequest customerRequest)
throws Exception
{
LOGGER.debug("Entered Customer activate");
CustomerResponse customerResponse = new CustomerResponse();
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT");
final Locale locale = new Locale("en");
Customer customer = customerFacade.getCustomerByUserName(customerRequest.getEmail(), merchantStore );
if ( customer == null )
{
LOGGER.debug("User not available");
customerResponse.setErrorMessage("User not available");
return customerResponse;
}
customer.setActivated("1");
customerFacade.updateCustomer(customer);
LOGGER.debug("User activated");
customerResponse.setSuccessMessage("User activated");
LOGGER.debug("Ended Customer activate");
return customerResponse;
}
@RequestMapping(value="/user/resetpwd", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ForgotPwdResponse resetPassword(@RequestBody ForgotPwdRequest forgotPwdRequest)
throws Exception
{
LOGGER.debug("Entered resetPassword");
ForgotPwdResponse forgotPwdResponse = new ForgotPwdResponse();
if(("").equals(forgotPwdRequest.getForgotPwdURL())){
LOGGER.debug("Forgot password link not available");
forgotPwdResponse.setErrorMessage("Forgot password link not available");
return forgotPwdResponse;
}
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT");
final Locale locale = new Locale("en");
Customer customer = customerFacade.getCustomerByUserName(forgotPwdRequest.getEmail(), merchantStore );
if ( customer == null )
{
LOGGER.debug("Email not available");
forgotPwdResponse.setErrorMessage("Email not available");
return forgotPwdResponse;
}
long currentTime = System.currentTimeMillis();
String ofid = String.valueOf(Math.round(currentTime * Math.random()));
if(ofid.length() > 40)
ofid = ofid.substring(0, 40);
customer.setOfid(ofid);
customerFacade.updateCustomer(customer);
String forgotPwdURL = forgotPwdRequest.getForgotPwdURL()+"?ofid="+ofid+"&"+"email="+forgotPwdRequest.getEmail();
//sending email
String[] forgotPwdURLArg = {forgotPwdURL};
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(merchantStore, messages, locale);
templateTokens.put(EmailConstants.EMAIL_ADMIN_USERNAME_LABEL, messages.getMessage("label.generic.username",locale));
templateTokens.put(EmailConstants.EMAIL_PASSWORD_LINK, messages.getMessage("email.user.text.forgotpwd.link",forgotPwdURLArg,locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL, messages.getMessage("label.generic.password",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
Email email = new Email();
email.setFrom(merchantStore.getStorename());
email.setFromEmail(merchantStore.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.user.text.forgotpwd",locale));
email.setTo(forgotPwdRequest.getEmail());
email.setTemplateName(FORGOT_PASSWORD_TPL);
email.setTemplateTokens(templateTokens);
emailService.sendHtmlEmail(merchantStore, email);
LOGGER.debug("Reset password email sent to the user");
forgotPwdResponse.setSuccessMessage("Reset password email sent to the user");
return forgotPwdResponse;
}
@RequestMapping(value="/user/updatepwd", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ForgotPwdResponse updatePassword(@RequestBody ForgotPwdRequest forgotPwdRequest)
throws Exception
{
LOGGER.debug("Entered updatePassword");
ForgotPwdResponse forgotPwdResponse = new ForgotPwdResponse();
if(("").equals(forgotPwdRequest.getOfid())){
LOGGER.debug("Invalid update password request");
forgotPwdResponse.setErrorMessage("Invalid update password request");
return forgotPwdResponse;
}
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT");
final Locale locale = new Locale("en");
Customer customer = customerFacade.getCustomerByUserName(forgotPwdRequest.getEmail(), merchantStore );
if ( customer == null )
{
LOGGER.debug("Email not available");
forgotPwdResponse.setErrorMessage("Email not available");
return forgotPwdResponse;
}
if ( !forgotPwdRequest.getOfid().equals(customer.getOfid()) )
{
LOGGER.debug("Invalid update password request");
forgotPwdResponse.setErrorMessage("Invalid update password request");
return forgotPwdResponse;
}
if ( !forgotPwdRequest.getNewPassword().equals(forgotPwdRequest.getConfirmPassword()) )
{
LOGGER.debug("New and Confirm passwords are not matching");
forgotPwdResponse.setErrorMessage("New and Confirm passwords are not matching");
return forgotPwdResponse;
}
String pass = passwordEncoder.encode(forgotPwdRequest.getNewPassword());
customer.setPassword(pass);
customerFacade.updateCustomer(customer);
//sending email
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(merchantStore, messages, locale);
templateTokens.put(EmailConstants.EMAIL_ADMIN_USERNAME_LABEL, messages.getMessage("label.generic.username",locale));
templateTokens.put(EmailConstants.EMAIL_RESET_PASSWORD_TXT, messages.getMessage("email.user.resetpassword.text",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL, messages.getMessage("label.generic.password",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
Email email = new Email();
email.setFrom(merchantStore.getStorename());
email.setFromEmail(merchantStore.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.user.text.forgotpwd.confirmation",locale));
email.setTo(forgotPwdRequest.getEmail());
email.setTemplateName(RESET_PASSWORD_TPL);
email.setTemplateTokens(templateTokens);
emailService.sendHtmlEmail(merchantStore, email);
LOGGER.debug("Password update success. Update password email sent to the user");
forgotPwdResponse.setSuccessMessage("Password update success. Update password email sent to the user");
return forgotPwdResponse;
}
@RequestMapping(value="/getUser/{customerId}", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public CustomerDetailsResponse getUser(@PathVariable String customerId) {
LOGGER.debug("Entered getUser");
Customer customer = customerService.getById(Long.parseLong(customerId));
CustomerDetailsResponse customerDetailsResponse = new CustomerDetailsResponse();
if(customer.getCustomerType().equals("0")){
CustomerDetails custDetails = new CustomerDetails();
custDetails.setEmail(customer.getEmailAddress());
custDetails.setFirstName(customer.getBilling().getFirstName());
custDetails.setLastName(customer.getBilling().getLastName());
custDetails.setPassword(customer.getPassword());
custDetails.setDob(customer.getDateOfBirth());
custDetails.setArea(customer.getArea());
custDetails.setGender(customer.getGender());
custDetails.setStoreCode("DEFAULT");
//if(customer.getBilling() != null){ // It is mandatory to have billing address
Address billing = new Address();
billing.setFirstName(customer.getBilling().getFirstName());
billing.setLastName(customer.getBilling().getLastName());
billing.setAddress(customer.getBilling().getAddress());
billing.setCity(customer.getBilling().getCity());
billing.setStateProvince(customer.getBilling().getState());
billing.setPostalCode(customer.getBilling().getPostalCode());
billing.setPhone(customer.getBilling().getTelephone());
billing.setCountry("IN");
custDetails.setBilling(billing);
if(customer.getDelivery() != null) {
Address delivery = new Address();
delivery.setFirstName(customer.getDelivery().getFirstName());
delivery.setLastName(customer.getDelivery().getLastName());
delivery.setAddress(customer.getDelivery().getAddress());
delivery.setCity(customer.getDelivery().getCity());
delivery.setStateProvince(customer.getDelivery().getState());
delivery.setPostalCode(customer.getDelivery().getPostalCode());
delivery.setPhone(customer.getDelivery().getTelephone());
custDetails.setDelivery(delivery);
}
if(customer.getSecondaryDelivery() != null) {
Address secondaryDeliveryAddr = new Address();
secondaryDeliveryAddr.setFirstName(customer.getSecondaryDelivery().getFirstName());
secondaryDeliveryAddr.setLastName(customer.getSecondaryDelivery().getLastName());
secondaryDeliveryAddr.setAddress(customer.getSecondaryDelivery().getAddress());
secondaryDeliveryAddr.setCity(customer.getSecondaryDelivery().getCity());
secondaryDeliveryAddr.setStateProvince(customer.getSecondaryDelivery().getState());
secondaryDeliveryAddr.setPostalCode(customer.getSecondaryDelivery().getPostalCode());
secondaryDeliveryAddr.setPhone(customer.getSecondaryDelivery().getTelephone());
custDetails.setDelivery(secondaryDeliveryAddr);
}
customerDetailsResponse.setCustomerDetails(custDetails);
LOGGER.debug("Retrieved customer details");
}
if(customer.getCustomerType().equals("1")) {
VendorDetails vendorDetails = new VendorDetails();
vendorDetails.setEmail(customer.getEmailAddress());
vendorDetails.setVendorName(customer.getVendorAttrs().getVendorName());
//vendorDetails.setVendorOfficeAddress(customer.getVendorAttrs().getVendorOfficeAddress());
vendorDetails.setHouseNumber(customer.getVendorAttrs().getVendorOfficeAddress());
vendorDetails.setStreet(customer.getBilling().getAddress());
vendorDetails.setArea(customer.getArea());
vendorDetails.setCity(customer.getBilling().getCity());
vendorDetails.setState(customer.getBilling().getState());
vendorDetails.setCountry(customer.getBilling().getCountry().getName());
vendorDetails.setPinCode(customer.getBilling().getPostalCode());
vendorDetails.setVendorMobile(customer.getVendorAttrs().getVendorMobile());
vendorDetails.setVendorTelephone(customer.getVendorAttrs().getVendorTelephone());
vendorDetails.setVendorFax(customer.getVendorAttrs().getVendorFax());
vendorDetails.setVendorConstFirm(customer.getVendorAttrs().getVendorConstFirm());
vendorDetails.setVendorCompanyNature(customer.getVendorAttrs().getVendorCompanyNature());
vendorDetails.setVendorRegistrationNo(customer.getVendorAttrs().getVendorRegistrationNo());
vendorDetails.setVendorPAN(customer.getVendorAttrs().getVendorPAN());
vendorDetails.setVendorLicense(customer.getVendorAttrs().getVendorLicense());
vendorDetails.setVendorAuthCert(customer.getVendorAttrs().getVendorAuthCert());
vendorDetails.setVendorExpLine(customer.getVendorAttrs().getVendorExpLine());
vendorDetails.setVendorMajorCust(customer.getVendorAttrs().getVendorMajorCust());
vendorDetails.setVatRegNo(customer.getVendorAttrs().getVendorVatRegNo());
vendorDetails.setVendorTIN(customer.getVendorAttrs().getVendorTinNumber());
vendorDetails.setUserProfile(customer.getUserProfile());
customerDetailsResponse.setVendorDetails(vendorDetails);
LOGGER.debug("Retrieved vendor details");
}
if(customer.getCustomerType().equals("2")) {
ServiceDetails serviceDetails = new ServiceDetails();
serviceDetails.setEmail(customer.getEmailAddress());
serviceDetails.setVendorName(customer.getVendorAttrs().getVendorName());
//vendorDetails.setVendorOfficeAddress(customer.getVendorAttrs().getVendorOfficeAddress());
serviceDetails.setHouseNumber(customer.getVendorAttrs().getVendorOfficeAddress());
serviceDetails.setStreet(customer.getBilling().getAddress());
serviceDetails.setArea(customer.getArea());
serviceDetails.setCity(customer.getBilling().getCity());
serviceDetails.setState(customer.getBilling().getState());
serviceDetails.setCountry(customer.getBilling().getCountry().getName());
serviceDetails.setPinCode(customer.getBilling().getPostalCode());
serviceDetails.setVendorMobile(customer.getVendorAttrs().getVendorMobile());
serviceDetails.setVendorTelephone(customer.getVendorAttrs().getVendorTelephone());
serviceDetails.setVendorFax(customer.getVendorAttrs().getVendorFax());
serviceDetails.setVendorConstFirm(customer.getVendorAttrs().getVendorConstFirm());
serviceDetails.setVendorCompanyNature(customer.getVendorAttrs().getVendorCompanyNature());
serviceDetails.setVendorRegistrationNo(customer.getVendorAttrs().getVendorRegistrationNo());
serviceDetails.setVendorPAN(customer.getVendorAttrs().getVendorPAN());
serviceDetails.setVendorLicense(customer.getVendorAttrs().getVendorLicense());
serviceDetails.setVendorAuthCert(customer.getVendorAttrs().getVendorAuthCert());
serviceDetails.setVendorExpLine(customer.getVendorAttrs().getVendorExpLine());
serviceDetails.setVendorMajorCust(customer.getVendorAttrs().getVendorMajorCust());
serviceDetails.setVatRegNo(customer.getVendorAttrs().getVendorVatRegNo());
serviceDetails.setVendorTIN(customer.getVendorAttrs().getVendorTinNumber());
serviceDetails.setUserProfile(customer.getUserProfile());
List<Services> services = customer.getServices();
List<Integer> serviceIds = new ArrayList<Integer>();
for(Services service : services){
Integer serviceId = service.getId();
serviceIds.add(serviceId);
}
serviceDetails.setServiceIds(serviceIds);
customerDetailsResponse.setServiceDetails(serviceDetails);
LOGGER.debug("Retrieved service details");
}
return customerDetailsResponse;
}
@RequestMapping(value="/customer/register", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public CustomerResponse registerCustomer(@RequestBody CustomerRequest customerRequest)
throws Exception
{
LOGGER.debug("Entered registerCustomer");
CustomerResponse customerResponse = new CustomerResponse();
SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
customer.setEmailAddress(customerRequest.getEmail());
customer.setPassword(customerRequest.getPassword());
customer.setCheckPassword(customerRequest.getConfirmPassword());
customer.setFirstName(customerRequest.getFirstName());
customer.setLastName(customerRequest.getLastName());
customer.setGender(customerRequest.getGender());
customer.setUserName(customerRequest.getEmail());
customer.setArea(customerRequest.getArea());
customer.setDob(customerRequest.getDob());
customer.setStoreCode("DEFAULT");
Address billing = new Address();
billing.setFirstName(customerRequest.getFirstName());
billing.setLastName(customerRequest.getLastName());
billing.setBillingAddress(true);
billing.setAddress(customerRequest.getAddress());
billing.setCity(customerRequest.getCity());
billing.setStateProvince(customerRequest.getState());
billing.setPostalCode(customerRequest.getPostalCode());
billing.setPhone(customerRequest.getPhone());
billing.setCountry("IN");
billing.setBillingAddress(true);
/* Address delivery = new Address();
delivery.setFirstName(customerRequest.getFirstName());
delivery.setLastName(customerRequest.getLastName());
delivery.setAddress(customerRequest.getAddress());
delivery.setCity(customerRequest.getCity());
delivery.setStateProvince(customerRequest.getState());
delivery.setPostalCode(customerRequest.getPostalCode());
delivery.setPhone(customerRequest.getPhone());
*/
customer.setBilling(billing);
//customer.setDelivery(delivery);
customer.setCustomerType("0");
final Locale locale = new Locale("en");
LOGGER.debug("Entered registration");
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
//Language language = super.getLanguage(request);
Language language = languageService.getByCode( Constants.DEFAULT_LANGUAGE );
String userName = null;
String password = null;
customerResponse.setStatus("false");
if ( StringUtils.isNotBlank( customer.getUserName() ) )
{
if ( customerFacade.checkIfUserExists( customer.getUserName(), merchantStore ) )
{
LOGGER.debug( "Customer with username {} already exists for this store ", customer.getUserName() );
customerResponse.setErrorMessage(messages.getMessage("registration.username.already.exists", locale));
return customerResponse;
}
userName = customer.getUserName();
}
if ( StringUtils.isNotBlank( customer.getPassword() ) && StringUtils.isNotBlank( customer.getCheckPassword() )) {
if (! customer.getPassword().equals(customer.getCheckPassword()) )
{
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
password = customer.getPassword();
}
if ( StringUtils.isBlank( customerRequest.getActivationURL() )) {
customerResponse.setErrorMessage(messages.getMessage("failure.customer.activation.link", locale));
return customerResponse;
}
System.out.println("userName "+userName+" password "+password);
@SuppressWarnings( "unused" )
CustomerEntity customerData = null;
try
{
//set user clear password
customer.setActivated("0");
customer.setClearPassword(password);
customerData = customerFacade.registerCustomer( customer, merchantStore, language );
} catch ( Exception e )
{
LOGGER.error( "Error while registering customer.. ", e);
customerResponse.setErrorMessage(e.getMessage());
return customerResponse;
}
customerResponse.setSuccessMessage(messages.getMessage("success.newuser.msg",locale));
customerResponse.setStatus(TRUE);
String activationURL = customerRequest.getActivationURL()+"?email="+customerRequest.getEmail();
//sending email
String[] activationURLArg = {activationURL};
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(merchantStore, messages, locale);
templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, customer.getFirstName());
templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, customer.getLastName());
templateTokens.put(EmailConstants.EMAIL_ADMIN_USERNAME_LABEL, messages.getMessage("label.generic.username",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION, messages.getMessage("email.newuser.text.activation",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION_LINK, messages.getMessage("email.newuser.text.activation.link",activationURLArg,locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL, messages.getMessage("label.generic.password",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
Email email = new Email();
email.setFrom(merchantStore.getStorename());
email.setFromEmail(merchantStore.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.newuser.text.activation",locale));
email.setTo(customerRequest.getEmail());
email.setTemplateName(NEW_USER_ACTIVATION_TMPL);
email.setTemplateTokens(templateTokens);
emailService.sendHtmlEmail(merchantStore, email);
LOGGER.debug("Ended registerCustomer");
return customerResponse;
}
@RequestMapping(value="/vendor/update", method = RequestMethod.POST)
@ResponseBody
public CustomerResponse updateVendor(@RequestPart("vendorRequest") String vendorRequestStr,
@RequestPart("file") MultipartFile[] uploadedFiles) throws Exception {
LOGGER.debug("Updating vendor");
VendorRequest vendorRequest = new ObjectMapper().readValue(vendorRequestStr, VendorRequest.class);
CustomerResponse customerResponse = new CustomerResponse();
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
Customer customer = null;
final Locale locale = new Locale("en");
if ( StringUtils.isNotBlank(vendorRequest.getEmail() ) )
{
customer = customerFacade.getCustomerByUserName(vendorRequest.getEmail(), merchantStore );
if(customer == null){
LOGGER.debug("Vendor is not exist, update is not possible");
customerResponse.setErrorMessage("Vendor is not exist, update is not possible ");
return customerResponse;
}
}
if ( StringUtils.isNotBlank( vendorRequest.getPassword() ) && StringUtils.isNotBlank( vendorRequest.getConfirmPassword() ))
{
if (! vendorRequest.getPassword().equals(vendorRequest.getConfirmPassword()) )
{
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
}
String userProfile = "";
String certFileName = "";
VendorAttributes vendorAttrs = customer.getVendorAttrs();
/**
* I assume, we always get only two MultipartFile
* 1st object always represent user profile picture
* 2nd object always represent vendor certificate.
*
*/
MultipartFile profilePicFile = uploadedFiles[0];
MultipartFile vendorCertificateFile = uploadedFiles[1];
String tempVendorProfilePicPath = new StringBuilder("vendor").append(File.separator).append("profiles").toString(); // give file directory path
String tempVendorCertificatePath = new StringBuilder("vendor").append(File.separator).append("certificates").toString(); // give file directory path
//for(MultipartFile file : uploadedFiles){
userProfile = storeFile(profilePicFile, tempVendorProfilePicPath);
if(!StringUtils.isEmpty(userProfile)){
customer.setUserProfile(userProfile);
}
certFileName = storeFile(vendorCertificateFile, tempVendorCertificatePath);
if(!StringUtils.isEmpty(certFileName)){
vendorAttrs.setVendorAuthCert(certFileName);
}
/* vendorAttrs.setVendorAuthCert(certFileName);
customer.setUserProfile(userProfile);
*/
vendorAttrs.setVendorOfficeAddress(vendorRequest.getVendorOfficeAddress());
vendorAttrs.setVendorMobile(vendorRequest.getVendorMobile());
vendorAttrs.setVendorTelephone(vendorRequest.getVendorTelephone());
vendorAttrs.setVendorFax(vendorRequest.getVendorFax());
vendorAttrs.setVendorConstFirm(vendorRequest.getVendorConstFirm());
vendorAttrs.setVendorCompanyNature(vendorRequest.getVendorCompanyNature());
vendorAttrs.setVendorExpLine(vendorRequest.getVendorExpLine());
vendorAttrs.setVendorMajorCust(vendorRequest.getVendorMajorCust());
vendorAttrs.setVendorName(vendorRequest.getVendorName());
vendorAttrs.setVendorTinNumber(vendorRequest.getVendorTIN());
vendorAttrs.setVendorRegistrationNo(vendorRequest.getVendorRegistrationNo());
vendorAttrs.setVendorPAN(vendorRequest.getVendorPAN());
vendorAttrs.setVendorLicense(vendorRequest.getVendorLicense());
//vendorAttrs.setVendorAuthCert(vendorRequest.getVendorAuthCert());
vendorAttrs.setVendorVatRegNo(vendorRequest.getVatRegNo());
customer.setVendorAttrs(vendorAttrs);
try {
customerFacade.updateCustomer(customer);
LOGGER.debug("Vendor Updated");
}catch(Exception e) {
storageService.deleteFile(certFileName);
storageService.deleteFile(userProfile);
LOGGER.error( "Error while updating customer.. ", e);
customerResponse.setErrorMessage(e.getMessage());
return customerResponse;
}
customerResponse.setSuccessMessage("Vendor profile updated successfully");
customerResponse.setStatus(TRUE);
LOGGER.debug("Ended updateVendor");
return customerResponse;
}
private String storeFile(MultipartFile file, String tempPath) {
String filePath = "";
if (!file.isEmpty()) {
String fileName = file.getOriginalFilename();
LOGGER.debug("fileName "+fileName);
try {
filePath = storageService.store(file,tempPath);
}catch(StorageException se){
LOGGER.error("StoreException occured"+se);
throw se;
}
}
return filePath;
}
@RequestMapping(value="/services/register", method = RequestMethod.POST)
@ResponseBody
//public CustomerResponse registerServices(@RequestBody ServicesRequest servicesRequest) throws Exception {
public CustomerResponse registerServices(@RequestPart("vendorRequest") String serviceRequestStr,
@RequestPart("file") MultipartFile vendorCertificate) throws Exception {
LOGGER.debug("Entered registerServices");
ServicesRequest servicesRequest = new ObjectMapper().readValue(serviceRequestStr, ServicesRequest.class);
CustomerResponse customerResponse = new CustomerResponse();
customerResponse.setStatus("false");
if(!isTermsAndConditionsAccepted(servicesRequest.isTermsAndConditions())){
customerResponse.setErrorMessage("Please accept Terms & Conditions ");
return customerResponse;
}
SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
customer.setEmailAddress(servicesRequest.getEmail());
customer.setPassword(servicesRequest.getPassword());
customer.setCheckPassword(servicesRequest.getConfirmPassword());
customer.setFirstName(servicesRequest.getEmail());
customer.setLastName(servicesRequest.getEmail());
customer.setUserName(servicesRequest.getEmail());
customer.setStoreCode("DEFAULT");
customer.setArea(servicesRequest.getArea());
Address billing = new Address();
billing.setFirstName(servicesRequest.getEmail());
billing.setLastName(servicesRequest.getEmail());
billing.setAddress(servicesRequest.getStreet());
billing.setPhone(servicesRequest.getContactNumber());
billing.setCountry("IN");
billing.setBillingAddress(true);
billing.setArea(servicesRequest.getArea()); //area
billing.setCity(servicesRequest.getCity());
billing.setCompany(servicesRequest.getCompanyName());
billing.setStateProvince(servicesRequest.getState());
billing.setPostalCode(servicesRequest.getPinCode());
/* Address delivery = new Address();
delivery.setFirstName(vendorRequest.getVendorName());
delivery.setLastName(vendorRequest.getVendorName());
delivery.setAddress(vendorRequest.getVendorOfficeAddress());
delivery.setPhone(vendorRequest.getVendorTelephone());
*/
customer.setBilling(billing);
//customer.setDelivery(delivery);
customer.setCustomerType("2");
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
final Locale locale = new Locale("en");
String userName = null;
String password = null;
if ( StringUtils.isNotBlank( customer.getUserName() ) ) {
if ( customerFacade.checkIfUserExists( customer.getUserName(), merchantStore ) ) {
LOGGER.debug( "Customer with username {} already exists for this store ", customer.getUserName() );
customerResponse.setErrorMessage(messages.getMessage("registration.username.already.exists", locale));
return customerResponse;
}
userName = customer.getUserName();
}
if ( StringUtils.isNotBlank( customer.getPassword() ) && StringUtils.isNotBlank( customer.getCheckPassword() )) {
if (! customer.getPassword().equals(customer.getCheckPassword()) ) {
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
password = customer.getPassword();
}
if ( StringUtils.isBlank( servicesRequest.getActivationURL() ))
{
customerResponse.setErrorMessage(messages.getMessage("failure.vendor.activation.link", locale));
return customerResponse;
}
// Store file into file sytem
Vendor vendorAttrs = new Vendor();
String certFileName = "";
if(vendorCertificate.getSize() != 0) {
try{
certFileName = storageService.store(vendorCertificate,"service");
LOGGER.debug("certFileName "+certFileName);
}catch(StorageException se){
LOGGER.error("StoreException occured"+se.getMessage());
}
vendorAttrs.setVendorAuthCert(certFileName);
}
vendorAttrs.setVendorName(servicesRequest.getCompanyName());
vendorAttrs.setVendorOfficeAddress(servicesRequest.getHouseNumber());
//vendorAttrs.setVendorMobile(vendorRequest.getVendorMobile());
vendorAttrs.setVendorTelephone(servicesRequest.getContactNumber());
vendorAttrs.setVendorFax(servicesRequest.getServiceFax());
vendorAttrs.setVendorConstFirm(servicesRequest.getConstFirm());
vendorAttrs.setVendorCompanyNature(servicesRequest.getCompanyNature());
vendorAttrs.setVendorRegistrationNo(servicesRequest.getRegistrationNo());
vendorAttrs.setVendorPAN(servicesRequest.getServicePAN());
vendorAttrs.setVendorVatRegNo(servicesRequest.getVatRegNo());
vendorAttrs.setVendorExpLine(servicesRequest.getExpLine());
vendorAttrs.setVendorMajorCust(servicesRequest.getMajorCust());
vendorAttrs.setVendorTIN(servicesRequest.getServiceTIN());
vendorAttrs.setVendorLicense(servicesRequest.getLicense());
customer.setVendor(vendorAttrs);
Language language = languageService.getByCode( Constants.DEFAULT_LANGUAGE );
@SuppressWarnings( "unused" )
CustomerEntity customerData = null;
try
{
//set user clear password
customer.setClearPassword(password);
customer.setActivated("0");
List<Integer> serviceIds = servicesRequest.getServiceIds();
List<Services> servicesList = new ArrayList<Services>();
for(Integer serviceId:serviceIds){
Services services = servicesService.getById(serviceId);
if(services != null){
LOGGER.debug("service id =="+services.getServiceType());
servicesList.add(services);
}
}
if(servicesList.size() > 0)
customer.setServices(servicesList);
customerData = customerFacade.registerCustomer( customer, merchantStore, language );
} catch ( Exception e )
{ /// if any exception raised during creation of customer we have to delete the certificate
//storageService.deleteFile(certFileName);
LOGGER.error( "Error while registering customer.. ", e);
customerResponse.setErrorMessage(e.getMessage());
return customerResponse;
}
LOGGER.debug("Services registration successful");
customerResponse.setSuccessMessage("Services registration successfull");
customerResponse.setStatus(TRUE);
String activationURL = servicesRequest.getActivationURL()+"?email="+servicesRequest.getEmail();
//sending email
String[] activationURLArg = {activationURL};
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(merchantStore, messages, locale);
templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, customer.getFirstName());
templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, customer.getLastName());
templateTokens.put(EmailConstants.EMAIL_ADMIN_USERNAME_LABEL, messages.getMessage("label.generic.username",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION, messages.getMessage("email.newuser.text.activation",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION_LINK, messages.getMessage("email.newuser.text.activation.link",activationURLArg,locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL, messages.getMessage("label.generic.password",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
Email email = new Email();
email.setFrom(merchantStore.getStorename());
email.setFromEmail(merchantStore.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.newuser.text.activation",locale));
email.setTo(servicesRequest.getEmail());
email.setTemplateName(NEW_USER_ACTIVATION_TMPL);
email.setTemplateTokens(templateTokens);
emailService.sendHtmlEmail(merchantStore, email);
LOGGER.debug("Email sent successful");
return customerResponse;
}
@RequestMapping(value="/user/register", method = RequestMethod.POST)
@ResponseBody
public CustomerResponse registerUser(@RequestPart("vendorRequest") String userRequestStr,
@RequestPart("file") MultipartFile vendorCertificate) throws Exception {
LOGGER.debug("Entered registerServices");
UserRequest userRequest = new ObjectMapper().readValue(userRequestStr, UserRequest.class);
CustomerResponse customerResponse = new CustomerResponse();
customerResponse.setStatus("false");
if(!isTermsAndConditionsAccepted(userRequest.isTermsAndConditions())){
customerResponse.setErrorMessage("Please accept Terms & Conditions ");
return customerResponse;
}
SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
customer.setCustomerType("0");
for(String custType:Constants.customerTypes.keySet()){
if(Constants.customerTypes.get(custType).equals(userRequest.getUserType().toUpperCase())){
customer.setCustomerType(custType);
break;
}
}
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
final Locale locale = new Locale("en");
if ( StringUtils.isNotBlank( customer.getUserName() ) ) {
if ( customerFacade.checkIfUserExists( customer.getUserName(), merchantStore ) ) {
LOGGER.debug( "Customer with username {} already exists for this store ", customer.getUserName() );
customerResponse.setErrorMessage(messages.getMessage("registration.username.already.exists", locale));
return customerResponse;
}
}
if ( StringUtils.isNotBlank( customer.getPassword() ) && StringUtils.isNotBlank( customer.getCheckPassword() )) {
if (! customer.getPassword().equals(customer.getCheckPassword()) ) {
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
}
if ( StringUtils.isBlank( userRequest.getActivationURL() ))
{
customerResponse.setErrorMessage(messages.getMessage("failure.vendor.activation.link", locale));
return customerResponse;
}
// Store file into file sytem
Vendor vendorAttrs = new Vendor();
String certFileName = "";
if(vendorCertificate.getSize() != 0) {
try{
certFileName = storageService.store(vendorCertificate,userRequest.getUserType().toLowerCase());
LOGGER.debug("certFileName "+certFileName);
}catch(StorageException se){
LOGGER.error("StoreException occured"+se.getMessage());
}
vendorAttrs.setVendorAuthCert(certFileName);
}
Language language = languageService.getByCode( Constants.DEFAULT_LANGUAGE );
@SuppressWarnings( "unused" )
CustomerEntity customerData = null;
try
{
//set user clear password
customer = setNewCustomerAttributes(customer, userRequest);
vendorAttrs = setNewVendorAttributes(userRequest, vendorAttrs);
customer.setVendor(vendorAttrs);
if(userRequest.getServiceIds() != null) {
List<Integer> serviceIds = userRequest.getServiceIds();
List<Services> servicesList = new ArrayList<Services>();
for(Integer serviceId:serviceIds){
Services services = servicesService.getById(serviceId);
if(services != null){
LOGGER.debug("service id =="+services.getServiceType());
servicesList.add(services);
}
}
if(servicesList.size() > 0)
customer.setServices(servicesList);
}
customerData = customerFacade.registerCustomer( customer, merchantStore, language );
} catch ( Exception e )
{ /// if any exception raised during creation of customer we have to delete the certificate
//storageService.deleteFile(certFileName);
LOGGER.error( "Error while registering customer.. ", e);
customerResponse.setErrorMessage(e.getMessage());
return customerResponse;
}
LOGGER.debug("Registration successful");
customerResponse.setSuccessMessage("Registration successfull");
customerResponse.setStatus(TRUE);
String activationURL = userRequest.getActivationURL()+"?email="+userRequest.getEmail();
//sending email
String[] activationURLArg = {activationURL};
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(merchantStore, messages, locale);
templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, customer.getFirstName());
templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, customer.getLastName());
templateTokens.put(EmailConstants.EMAIL_ADMIN_USERNAME_LABEL, messages.getMessage("label.generic.username",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION, messages.getMessage("email.newuser.text.activation",locale));
templateTokens.put(EmailConstants.EMAIL_TEXT_NEW_USER_ACTIVATION_LINK, messages.getMessage("email.newuser.text.activation.link",activationURLArg,locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL, messages.getMessage("label.generic.password",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
templateTokens.put(EmailConstants.EMAIL_ADMIN_URL_LABEL, messages.getMessage("label.adminurl",locale));
Email email = new Email();
email.setFrom(merchantStore.getStorename());
email.setFromEmail(merchantStore.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.newuser.text.activation",locale));
email.setTo(userRequest.getEmail());
email.setTemplateName(NEW_USER_ACTIVATION_TMPL);
email.setTemplateTokens(templateTokens);
emailService.sendHtmlEmail(merchantStore, email);
LOGGER.debug("Email sent successful");
return customerResponse;
}
@RequestMapping(value="/user/update", method = RequestMethod.POST)
@ResponseBody
public CustomerResponse updateUser(@RequestPart("vendorRequest") String userRequestStr,
@RequestPart("file") MultipartFile[] uploadedFiles) throws Exception {
LOGGER.debug("Updating vendor");
UserRequest userRequest = new ObjectMapper().readValue(userRequestStr, UserRequest.class);
CustomerResponse customerResponse = new CustomerResponse();
MerchantStore merchantStore = merchantStoreService.getByCode("DEFAULT"); //i will come back here
Customer customer = null;
final Locale locale = new Locale("en");
if ( StringUtils.isNotBlank(userRequest.getEmail() ) )
{
customer = customerFacade.getCustomerByUserName(userRequest.getEmail(), merchantStore );
if(customer == null){
LOGGER.debug("Vendor is not exist, update is not possible");
customerResponse.setErrorMessage("User does not exist, update is not possible ");
return customerResponse;
}
}
if ( StringUtils.isNotBlank( userRequest.getPassword() ) && StringUtils.isNotBlank( userRequest.getConfirmPassword() ))
{
if (! userRequest.getPassword().equals(userRequest.getConfirmPassword()) )
{
customerResponse.setErrorMessage(messages.getMessage("message.password.checkpassword.identical", locale));
return customerResponse;
}
}
String userProfile = "";
String certFileName = "";
VendorAttributes vendorAttrs = customer.getVendorAttrs();
Billing billing = customer.getBilling();
/**
* I assume, we always get only two MultipartFile
* 1st object always represent user profile picture
* 2nd object always represent vendor certificate.
*
*/
MultipartFile profilePicFile = uploadedFiles[0];
MultipartFile vendorCertificateFile = uploadedFiles[1];
String tempVendorProfilePicPath = new StringBuilder("vendor").append(File.separator).append("profiles").toString(); // give file directory path
String tempVendorCertificatePath = new StringBuilder("vendor").append(File.separator).append("certificates").toString(); // give file directory path
if(userRequest.getUserType().equals("SERVICE")){
tempVendorProfilePicPath = new StringBuilder("service").append(File.separator).append("profiles").toString(); // give file directory path
tempVendorCertificatePath = new StringBuilder("service").append(File.separator).append("certificates").toString(); // give file directory path
}
userProfile = storeFile(profilePicFile, tempVendorProfilePicPath);
if(!StringUtils.isEmpty(userProfile)){
customer.setUserProfile(userProfile);
}
certFileName = storeFile(vendorCertificateFile, tempVendorCertificatePath);
if(!StringUtils.isEmpty(certFileName)){
vendorAttrs.setVendorAuthCert(certFileName);
}
try {
customer = setCustomerAttributes(customer, userRequest, billing);
vendorAttrs = setUpdateVendorAttributes(userRequest, vendorAttrs);
customer.setVendorAttrs(vendorAttrs);
if(userRequest.getServiceIds() != null) {
List<Integer> serviceIds = userRequest.getServiceIds();
List<Services> servicesList = new ArrayList<Services>();
for(Integer serviceId:serviceIds){
Services services = servicesService.getById(serviceId);
if(services != null){
LOGGER.debug("service id =="+services.getServiceType());
servicesList.add(services);
}
}
if(servicesList.size() > 0)
customer.setServices(servicesList);
}
customerFacade.updateCustomer(customer);
LOGGER.debug("User Updated");
}catch(Exception e) {
storageService.deleteFile(certFileName);
storageService.deleteFile(userProfile);
LOGGER.error( "Error while updating customer.. ", e);
customerResponse.setErrorMessage(e.getMessage());
return customerResponse;
}
customerResponse.setSuccessMessage("Profile updated successfully");
customerResponse.setStatus(TRUE);
LOGGER.debug("Ended user update");
return customerResponse;
}
private Customer setCustomerAttributes(Customer customer,UserRequest userRequest, Billing billing){
if(userRequest.getEmail() != null){
customer.setEmailAddress(userRequest.getEmail());
billing.setFirstName(userRequest.getEmail());
billing.setLastName(userRequest.getEmail());
}
if(userRequest.getArea() != null)
customer.setArea(userRequest.getArea());
if(userRequest.getStreet() != null)
billing.setAddress(userRequest.getStreet());
if(userRequest.getContactNumber() != null)
billing.setTelephone(userRequest.getContactNumber());
if(userRequest.getArea() != null)
customer.setArea(userRequest.getArea());
if(userRequest.getCity() != null)
billing.setCity(userRequest.getCity());
if(userRequest.getCompanyName() != null)
billing.setCompany(userRequest.getCompanyName());
if(userRequest.getState() != null)
billing.setState(userRequest.getState());
if(userRequest.getPinCode() != null)
billing.setPostalCode(userRequest.getPinCode());
customer.setBilling(billing);
return customer;
}
private SecuredShopPersistableCustomer setNewCustomerAttributes(SecuredShopPersistableCustomer customer,UserRequest userRequest){
Address billing = new Address();
if(userRequest.getEmail() != null){
customer.setEmailAddress(userRequest.getEmail());
customer.setFirstName(userRequest.getEmail());
customer.setLastName(userRequest.getEmail());
customer.setUserName(userRequest.getEmail());
billing.setFirstName(userRequest.getEmail());
billing.setLastName(userRequest.getEmail());
}
customer.setClearPassword(userRequest.getPassword());
customer.setStoreCode("DEFAULT");
billing.setCountry("IN");
billing.setBillingAddress(true);
customer.setBilling(billing);
customer.setActivated("0");
if(userRequest.getPassword() != null) {
customer.setPassword(userRequest.getPassword());
customer.setCheckPassword(userRequest.getConfirmPassword());
}
if(userRequest.getArea() != null)
customer.setArea(userRequest.getArea());
if(userRequest.getStreet() != null)
billing.setAddress(userRequest.getStreet());
if(userRequest.getContactNumber() != null)
billing.setPhone(userRequest.getContactNumber());
if(userRequest.getArea() != null)
customer.setArea(userRequest.getArea());
if(userRequest.getCity() != null)
billing.setCity(userRequest.getCity());
if(userRequest.getCompanyName() != null)
billing.setCompany(userRequest.getCompanyName());
if(userRequest.getState() != null)
billing.setStateProvince(userRequest.getState());
if(userRequest.getPinCode() != null)
billing.setPostalCode(userRequest.getPinCode());
customer.setBilling(billing);
return customer;
}
private Vendor setNewVendorAttributes(UserRequest userRequest,Vendor vendorAttrs){
if(userRequest.getCompanyName() != null)
vendorAttrs.setVendorName(userRequest.getCompanyName());
if(userRequest.getHouseNumber() != null)
vendorAttrs.setVendorOfficeAddress(userRequest.getHouseNumber());
if(userRequest.getContactNumber() != null)
vendorAttrs.setVendorTelephone(userRequest.getContactNumber());
if(userRequest.getServiceFax() != null)
vendorAttrs.setVendorFax(userRequest.getServiceFax());
if(userRequest.getConstFirm() != null)
vendorAttrs.setVendorConstFirm(userRequest.getConstFirm());
if(userRequest.getCompanyNature() != null)
vendorAttrs.setVendorCompanyNature(userRequest.getCompanyNature());
if(userRequest.getRegistrationNo() != null)
vendorAttrs.setVendorRegistrationNo(userRequest.getRegistrationNo());
if(userRequest.getServicePAN() != null)
vendorAttrs.setVendorPAN(userRequest.getServicePAN());
if(userRequest.getVatRegNo() != null)
vendorAttrs.setVendorVatRegNo(userRequest.getVatRegNo());
if(userRequest.getExpLine() != null)
vendorAttrs.setVendorExpLine(userRequest.getExpLine());
if(userRequest.getMajorCust() != null)
vendorAttrs.setVendorMajorCust(userRequest.getMajorCust());
if(userRequest.getServiceTIN() != null)
vendorAttrs.setVendorTIN(userRequest.getServiceTIN());
if(userRequest.getLicense() != null)
vendorAttrs.setVendorLicense(userRequest.getLicense());
return vendorAttrs;
}
private VendorAttributes setUpdateVendorAttributes(UserRequest userRequest,VendorAttributes vendorAttrs){
if(userRequest.getCompanyName() != null)
vendorAttrs.setVendorName(userRequest.getCompanyName());
if(userRequest.getHouseNumber() != null)
vendorAttrs.setVendorOfficeAddress(userRequest.getHouseNumber());
if(userRequest.getContactNumber() != null)
vendorAttrs.setVendorTelephone(userRequest.getContactNumber());
if(userRequest.getServiceFax() != null)
vendorAttrs.setVendorFax(userRequest.getServiceFax());
if(userRequest.getConstFirm() != null)
vendorAttrs.setVendorConstFirm(userRequest.getConstFirm());
if(userRequest.getCompanyNature() != null)
vendorAttrs.setVendorCompanyNature(userRequest.getCompanyNature());
if(userRequest.getRegistrationNo() != null)
vendorAttrs.setVendorRegistrationNo(userRequest.getRegistrationNo());
if(userRequest.getServicePAN() != null)
vendorAttrs.setVendorPAN(userRequest.getServicePAN());
if(userRequest.getVatRegNo() != null)
vendorAttrs.setVendorVatRegNo(userRequest.getVatRegNo());
if(userRequest.getExpLine() != null)
vendorAttrs.setVendorExpLine(userRequest.getExpLine());
if(userRequest.getMajorCust() != null)
vendorAttrs.setVendorMajorCust(userRequest.getMajorCust());
if(userRequest.getServiceTIN() != null)
vendorAttrs.setVendorTinNumber(userRequest.getServiceTIN());
if(userRequest.getLicense() != null)
vendorAttrs.setVendorLicense(userRequest.getLicense());
return vendorAttrs;
}
}
|
package org.msf.records;
import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.msf.records.net.BuendiaServer;
import org.msf.records.net.OpenMrsConnectionDetails;
import org.msf.records.net.OpenMrsServer;
import org.msf.records.net.OpenMrsXformsConnection;
import org.msf.records.net.Server;
import org.msf.records.updater.UpdateManager;
import org.msf.records.user.UserManager;
import org.odk.collect.android.application.Collect;
public class App extends Application {
/**
* The current instance of the application.
*/
private static App sInstance;
private static UserManager sUserManager;
private static UpdateManager sUpdateManager;
private static Server mServer;
private static OpenMrsXformsConnection mOpenMrsXformsConnection;
private static OpenMrsConnectionDetails mConnectionDetails;
@Override
public void onCreate() {
Collect.onCreate(this);
super.onCreate();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
synchronized (App.class) {
sInstance = this;
sUserManager = new UserManager();
sUpdateManager = new UpdateManager();
mConnectionDetails =
new OpenMrsConnectionDetails(
preferences.getString("openmrs_root_url", null),
preferences.getString("openmrs_user", null),
preferences.getString("openmrs_password", null),
getApplicationContext());
if (preferences.getBoolean("use_openmrs", true)) {
mServer = new OpenMrsServer(mConnectionDetails);
} else {
String rootUrl = preferences.getString("api_root_url", null);
mServer = new BuendiaServer(getApplicationContext(), rootUrl);
}
}
}
public static synchronized App getInstance() {
return sInstance;
}
public static synchronized UserManager getUserManager() {
return sUserManager;
}
public static synchronized UpdateManager getUpdateManager() {
return sUpdateManager;
}
public static synchronized Server getServer() {
return mServer;
}
public static synchronized OpenMrsConnectionDetails getConnectionDetails() {
return mConnectionDetails;
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app.debug;
import processing.app.Base;
import processing.app.Preferences;
import processing.app.Sketch;
import processing.app.SketchCode;
import processing.core.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.text.MessageFormat;
public class Compiler implements MessageConsumer {
static final String BUGS_URL = "http://code.google.com/p/arduino/issues/list";
static final String SUPER_BADNESS = "Compiler error, please submit this code to "
+ BUGS_URL;
Sketch sketch;
String buildPath;
String primaryClassName;
String platform;
boolean verbose;
String board;
//CommandRunner runner;
RunnerException exception;
HashMap<String, String> configPreferences;
HashMap<String, String> boardPreferences;
HashMap<String, String> platformPreferences;
String avrBasePath;
String corePath;
List<File> objectFiles;
List includePaths;
public Compiler() {
}
/**
* Compile with avr-gcc.
*
* @param sketch
* Sketch object to be compiled.
* @param buildPath
* Where the temporary files live and will be built from.
* @param primaryClassName
* the name of the combined sketch file w/ extension
* @return true if successful.
* @throws RunnerException
* Only if there's a problem. Only then.
*/
public boolean compile(Sketch sketch, String buildPath,String primaryClassName, boolean verbose) throws RunnerException {
this.sketch = sketch;
this.buildPath = buildPath;
this.primaryClassName = primaryClassName;
this.verbose = verbose;
// the pms object isn't used for anything but storage
MessageStream pms = new MessageStream(this);
boardPreferences = new HashMap(Base.getBoardPreferences());
//Check for null platform, and use system default if not found
platform = boardPreferences.get("platform");
if (platform == null)
{
platformPreferences = new HashMap(Base.getPlatformPreferences());
}
else
{
platformPreferences = new HashMap(Base.getPlatformPreferences(platform));
}
avrBasePath = platformPreferences.get("compiler.path");
if (avrBasePath == "")
{
avrBasePath = Base.getAvrBasePath();
}
this.board = boardPreferences.get("board");
if (this.board == "")
{
this.board = "_UNKNOWN";
}
String core = boardPreferences.get("build.core");
if (core == null)
{
RunnerException re = new RunnerException(
"No board selected; please choose a board from the Tools > Board menu.");
re.hideStackTrace();
throw re;
}
//String corePath;
if (core.indexOf(':') == -1)
{
Target t = Base.getTarget();
File coreFolder = new File(new File(t.getFolder(), "cores"), core);
this.corePath = coreFolder.getAbsolutePath();
} else {
Target t = Base.targetsTable.get(core.substring(0,
core.indexOf(':')));
File coresFolder = new File(t.getFolder(), "cores");
File coreFolder = new File(coresFolder, core.substring(core
.indexOf(':') + 1));
this.corePath = coreFolder.getAbsolutePath();
}
this.objectFiles = new ArrayList<File>();
//Put all the global preference configuration into one Master configpreferences
configPreferences = mergePreferences( Preferences.getMap(), platformPreferences, Base.getBoardPreferences());
// 0. include paths for core + all libraries
this.includePaths = new ArrayList();
getIncludes(this.corePath);
// 1. compile the sketch (already in the buildPath)
compileSketch(avrBasePath, buildPath, includePaths, boardPreferences, platformPreferences);
// 2. compile the libraries, outputting .o files to:
// <buildPath>/<library>/
compileLibraries(avrBasePath, buildPath, includePaths, boardPreferences, platformPreferences);
// 3. compile the core, outputting .o files to <buildPath> and then
// collecting them into the core.a library file.
compileCore(avrBasePath, buildPath, this.corePath, boardPreferences, platformPreferences);
// 4. link it all together into the .elf file
compileLink(avrBasePath, buildPath, includePaths, configPreferences);
// 5. extract EEPROM data (from EEMEM directive) to .eep file.
compileEep(avrBasePath, buildPath, includePaths, configPreferences);
// 6. build the .hex file
compileHex(avrBasePath, buildPath, includePaths, configPreferences);
//done
return true;
}
private List<File> compileFiles(String avrBasePath,
String buildPath,
List<File> includePaths,
List<File> sSources, List<File>
cSources,
List<File> cppSources,
Map<String, String> boardPreferences,
Map<String, String> platformPreferences) throws RunnerException {
List<File> objectPaths = new ArrayList<File>();
for (File file : sSources) {
String objectPath = buildPath + File.separator + file.getName()
+ ".o";
objectPaths.add(new File(objectPath));
execAsynchronously(getCommandCompilerS(avrBasePath, includePaths,
file.getAbsolutePath(), objectPath, boardPreferences,
platformPreferences));
}
for (File file : cSources) {
String objectPath = buildPath + File.separator + file.getName()
+ ".o";
objectPaths.add(new File(objectPath));
execAsynchronously(getCommandCompilerC(avrBasePath, includePaths,
file.getAbsolutePath(), objectPath, boardPreferences,
platformPreferences));
}
for (File file : cppSources) {
String objectPath = buildPath + File.separator + file.getName()
+ ".o";
objectPaths.add(new File(objectPath));
execAsynchronously(getCommandCompilerCPP(avrBasePath, includePaths,
file.getAbsolutePath(), objectPath, boardPreferences,
platformPreferences));
}
return objectPaths;
}
boolean firstErrorFound;
boolean secondErrorFound;
/***
* Exec as String instead of Array
*
*/
private void execAsynchronously(String command) throws RunnerException
{
{
String commandString = command;
int result = 0;
if (verbose || Preferences.getBoolean("build.verbose"))
{
System.out.print(commandString);
System.out.println();
}
firstErrorFound = false; // haven't found any errors yet
secondErrorFound = false;
Process process;
try {
process = Runtime.getRuntime().exec(commandString);
} catch (IOException e) {
RunnerException re = new RunnerException(e.getMessage());
re.hideStackTrace();
throw re;
}
MessageSiphon in = new MessageSiphon(process.getInputStream(), this);
MessageSiphon err = new MessageSiphon(process.getErrorStream(), this);
// wait for the process to finish. if interrupted
// before waitFor returns, continue waiting
boolean running = true;
while (running) {
try {
if (in.thread != null)
in.thread.join();
if (err.thread != null)
err.thread.join();
result = process.waitFor();
//System.out.println("result is " + result);
running = false;
} catch (InterruptedException ignored) { }
}
// an error was queued up by message(), barf this back to compile(),
// which will barf it back to Editor. if you're having trouble
// discerning the imagery, consider how cows regurgitate their food
// to digest it, and the fact that they have five stomaches.
//System.out.println("throwing up " + exception);
if (exception != null) { throw exception; }
if (result > 1) {
// a failure in the tool (e.g. unable to locate a sub-executable)
System.err.println(commandString + " returned " + result);
}
if (result != 0) {
RunnerException re = new RunnerException("Error running.");
re.hideStackTrace();
throw re;
}
}
}
/**
* Either succeeds or throws a RunnerException fit for public consumption.
*/
/*
private void execAsynchronously(List commandList) throws RunnerException
{
String[] command = new String[commandList.size()];
commandList.toArray(command);
int result = 0;
if (verbose || Preferences.getBoolean("build.verbose")) {
for (int j = 0; j < command.length; j++) {
System.out.print(command[j] + " ");
}
System.out.println();
}
firstErrorFound = false; // haven't found any errors yet
secondErrorFound = false;
Process process;
try {
process = Runtime.getRuntime().exec(command);
} catch (IOException e) {
RunnerException re = new RunnerException(e.getMessage());
re.hideStackTrace();
throw re;
}
MessageSiphon in = new MessageSiphon(process.getInputStream(), this);
MessageSiphon err = new MessageSiphon(process.getErrorStream(), this);
// wait for the process to finish. if interrupted
// before waitFor returns, continue waiting
boolean compiling = true;
while (compiling) {
try {
if (in.thread != null)
in.thread.join();
if (err.thread != null)
err.thread.join();
result = process.waitFor();
// System.out.println("result is " + result);
compiling = false;
} catch (InterruptedException ignored) {
}
}
// an error was queued up by message(), barf this back to compile(),
// which will barf it back to Editor. if you're having trouble
// discerning the imagery, consider how cows regurgitate their food
// to digest it, and the fact that they have five stomaches.
//
// System.out.println("throwing up " + exception);
if (exception != null) {
throw exception;
}
if (result > 1) {
// a failure in the tool (e.g. unable to locate a sub-executable)
System.err.println(command[0] + " returned " + result);
}
if (result != 0) {
RunnerException re = new RunnerException("Error compiling.");
re.hideStackTrace();
throw re;
}
}
*/
/**
* Part of the MessageConsumer interface, this is called whenever a piece
* (usually a line) of error message is spewed out from the compiler. The
* errors are parsed for their contents and line number, which is then
* reported back to Editor.
*/
public void message(String s) {
int i;
// remove the build path so people only see the filename
// can't use replaceAll() because the path may have characters in it
// which
// have meaning in a regular expression.
if (!verbose) {
while ((i = s.indexOf(buildPath + File.separator)) != -1) {
s = s.substring(0, i)
+ s.substring(i + (buildPath + File.separator).length());
}
}
// look for error line, which contains file name, line number,
// and at least the first line of the error message
String errorFormat = "([\\w\\d_]+.\\w+):(\\d+):\\s*error:\\s*(.*)\\s*";
String[] pieces = PApplet.match(s, errorFormat);
// if (pieces != null && exception == null) {
// exception = sketch.placeException(pieces[3], pieces[1],
// PApplet.parseInt(pieces[2]) - 1);
// if (exception != null) exception.hideStackTrace();
if (pieces != null) {
RunnerException e = sketch.placeException(pieces[3], pieces[1],
PApplet.parseInt(pieces[2]) - 1);
// replace full file path with the name of the sketch tab (unless
// we're
// in verbose mode, in which case don't modify the compiler output)
if (e != null && !verbose) {
SketchCode code = sketch.getCode(e.getCodeIndex());
String fileName = code
.isExtension(sketch.getDefaultExtension()) ? code
.getPrettyName() : code.getFileName();
s = fileName + ":" + e.getCodeLine() + ": error: "
+ e.getMessage();
}
if (pieces[3].trim().equals("SPI.h: No such file or directory")) {
e = new RunnerException(
"Please import the SPI library from the Sketch > Import Library menu.");
s += "\nAs of Arduino 0019, the Ethernet library depends on the SPI library."
+ "\nYou appear to be using it or another library that depends on the SPI library.";
}
if (exception == null && e != null) {
exception = e;
exception.hideStackTrace();
}
}
System.err.print(s);
}
//What conditions is getCommandCompilerS invoke from?
static private String getCommandCompilerS(String avrBasePath,
List includePaths, String sourceName, String objectName,
Map<String, String> boardPreferences,
Map<String, String> platformPreferences)
{
String includes = "";
String baseCommandString = platformPreferences.get("recipe.cpp.o.pattern");
MessageFormat compileFormat = new MessageFormat(baseCommandString);
//getIncludes to String
for (int i = 0; i < includePaths.size(); i++)
{
includes = includes + (" -I" + (String) includePaths.get(i));
}
Object[] Args = {
avrBasePath,
platformPreferences.get("compiler.cpp.cmd"),
platformPreferences.get("compiler.S.flags"),
platformPreferences.get("compiler.cpudef"),
boardPreferences.get("build.mcu"),
boardPreferences.get("build.f_cpu"),
boardPreferences.get("board"),
Base.REVISION,
includes,
sourceName,
objectName
};
return compileFormat.format( Args );
}
//removed static
private String getCommandCompilerC(String avrBasePath,
List includePaths, String sourceName, String objectName,
Map<String, String> boardPreferences,
Map<String, String> platformPreferences)
{
String includes = "";
String baseCommandString = platformPreferences.get("recipe.c.o.pattern");
MessageFormat compileFormat = new MessageFormat(baseCommandString);
//getIncludes to String
for (int i = 0; i < includePaths.size(); i++)
{
includes = includes + (" -I" + (String) includePaths.get(i));
}
Object[] Args = {
avrBasePath,
platformPreferences.get("compiler.c.cmd"),
platformPreferences.get("compiler.c.flags"),
platformPreferences.get("compiler.cpudef"),
boardPreferences.get("build.mcu"),
boardPreferences.get("build.f_cpu"),
boardPreferences.get("board"),
Base.REVISION,
includes,
sourceName,
objectName
};
return compileFormat.format( Args );
}
static private String getCommandCompilerCPP(String avrBasePath,
List includePaths, String sourceName, String objectName,
Map<String, String> boardPreferences,
Map<String, String> platformPreferences)
{
String includes = "";
String baseCommandString = platformPreferences.get("recipe.cpp.o.pattern");
MessageFormat compileFormat = new MessageFormat(baseCommandString);
//getIncludes to String
for (int i = 0; i < includePaths.size(); i++)
{
includes = includes + (" -I" + (String) includePaths.get(i));
}
Object[] Args = {
avrBasePath,
platformPreferences.get("compiler.cpp.cmd"),
platformPreferences.get("compiler.cpp.flags"),
platformPreferences.get("compiler.cpudef"),
boardPreferences.get("build.mcu"),
boardPreferences.get("build.f_cpu"),
boardPreferences.get("board"),
Base.REVISION,
includes,
sourceName,
objectName
};
return compileFormat.format( Args );
}
static private void createFolder(File folder) throws RunnerException {
if (folder.isDirectory())
return;
if (!folder.mkdir())
throw new RunnerException("Couldn't create: " + folder);
}
/**
* Given a folder, return a list of the header files in that folder (but not
* the header files in its sub-folders, as those should be included from
* within the header files at the top-level).
*/
static public String[] headerListFromIncludePath(String path) {
FilenameFilter onlyHFiles = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".h");
}
};
return (new File(path)).list(onlyHFiles);
}
static public ArrayList<File> findFilesInPath(String path,
String extension, boolean recurse) {
return findFilesInFolder(new File(path), extension, recurse);
}
static public ArrayList<File> findFilesInFolder(File folder,
String extension, boolean recurse) {
ArrayList<File> files = new ArrayList<File>();
if (folder.listFiles() == null)
return files;
for (File file : folder.listFiles()) {
if (file.getName().startsWith("."))
continue; // skip hidden files
if (file.getName().endsWith("." + extension))
files.add(file);
if (recurse && file.isDirectory()) {
files.addAll(findFilesInFolder(file, extension, true));
}
}
return files;
}
// 0. include paths for core + all libraries
void getIncludes(String corePath)
{
this.includePaths.add(corePath);
for (File file : sketch.getImportedLibraries())
{
includePaths.add(file.getPath());
}
}
// 1. compile the sketch (already in the buildPath)
void compileSketch(String avrBasePath, String buildPath, List includePaths, Map<String, String> boardPreferences, Map<String, String> platformPreferences)
throws RunnerException
{
this.objectFiles.addAll(compileFiles(avrBasePath, buildPath, includePaths,
findFilesInPath(buildPath, "S", false),
findFilesInPath(buildPath, "c", false),
findFilesInPath(buildPath, "cpp", false), boardPreferences,
platformPreferences));
}
// 2. compile the libraries, outputting .o files to:
// <buildPath>/<library>/
void compileLibraries (String avrBasePath, String buildPath, List includePaths, Map<String, String> boardPreferences, Map<String, String> platformPreferences)
throws RunnerException
{
for (File libraryFolder : sketch.getImportedLibraries())
{
File outputFolder = new File(buildPath, libraryFolder.getName());
File utilityFolder = new File(libraryFolder, "utility");
createFolder(outputFolder);
// this library can use includes in its utility/ folder
this.includePaths.add(utilityFolder.getAbsolutePath());
this.objectFiles.addAll(compileFiles(avrBasePath,
outputFolder.getAbsolutePath(), includePaths,
findFilesInFolder(libraryFolder, "S", false),
findFilesInFolder(libraryFolder, "c", false),
findFilesInFolder(libraryFolder, "cpp", false),
boardPreferences, platformPreferences));
outputFolder = new File(outputFolder, "utility");
createFolder(outputFolder);
this.objectFiles.addAll(compileFiles(avrBasePath,
outputFolder.getAbsolutePath(), includePaths,
findFilesInFolder(utilityFolder, "S", false),
findFilesInFolder(utilityFolder, "c", false),
findFilesInFolder(utilityFolder, "cpp", false),
boardPreferences, platformPreferences));
// other libraries should not see this library's utility/ folder
this.includePaths.remove(includePaths.size() - 1);
}
}
// 3. compile the core, outputting .o files to <buildPath> and then
// collecting them into the core.a library file.
void compileCore (String avrBasePath, String buildPath, String corePath, Map<String, String> boardPreferences, Map<String, String> platformPreferences)
throws RunnerException
{
List includePaths = new ArrayList();
includePaths.add(corePath); //include core path only
String baseCommandString = platformPreferences.get("recipe.ar.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
List<File> coreObjectFiles = compileFiles(
avrBasePath,
buildPath,
includePaths,
findFilesInPath(corePath, "S", true),
findFilesInPath(corePath, "c", true),
findFilesInPath(corePath, "cpp", true),
boardPreferences,
platformPreferences);
for (File file : coreObjectFiles) {
//List commandAR = new ArrayList(baseCommandAR);
//commandAR = commandAR + file.getAbsolutePath();
Object[] Args = {
avrBasePath,
platformPreferences.get("compiler.ar.cmd"),
platformPreferences.get("compiler.ar.flags"),
//corePath,
buildPath + File.separator,
"core.a",
//objectName
file.getAbsolutePath()
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
}
// 4. link it all together into the .elf file
void compileLink(String avrBasePath, String buildPath, List includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
String baseCommandString = configPreferences.get("recipe.c.combine.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
String objectFileList = "";
for (File file : objectFiles) {
objectFileList = objectFileList + file.getAbsolutePath() + " ";
}
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.cpp.cmd"),
configPreferences.get("compiler.c.elf.flags"),
configPreferences.get("compiler.cpudef"),
configPreferences.get("build.mcu"),
buildPath + File.separator,
primaryClassName,
objectFileList,
buildPath + File.separator + "core.a",
buildPath
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
// 5. extract EEPROM data (from EEMEM directive) to .eep file.
void compileEep (String avrBasePath, String buildPath, List includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
String baseCommandString = configPreferences.get("recipe.objcopy.eep.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
String objectFileList = "";
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.objcopy.cmd"),
configPreferences.get("compiler.objcopy.eep.flags"),
buildPath + File.separator + primaryClassName,
buildPath + File.separator + primaryClassName
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
// 6. build the .hex file
void compileHex (String avrBasePath, String buildPath, List includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
String baseCommandString = configPreferences.get("recipe.objcopy.hex.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
String objectFileList = "";
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.elf2hex.cmd"),
configPreferences.get("compiler.elf2hex.flags"),
buildPath + File.separator + primaryClassName,
buildPath + File.separator + primaryClassName
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
//merge all the preferences file in the correct order of precedence
HashMap mergePreferences(Map Preferences, Map platformPreferences, Map boardPreferences)
{
HashMap _map = new HashMap();
Iterator iterator = Preferences.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry pair = (Map.Entry)iterator.next();
if (pair.getValue() == null)
{
_map.put(pair.getKey(), "");
}
else
{
_map.put(pair.getKey(), pair.getValue());
}
}
System.out.println("Done: Preferences");
iterator = platformPreferences.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry pair = (Map.Entry)iterator.next();
if (pair.getValue() == null)
{
_map.put(pair.getKey(), "");
}
else
{
_map.put(pair.getKey(), pair.getValue());
}
//System.out.println(pair.getKey() + " = " + pair.getValue());
}
System.out.println("Done: platformPreferences");
iterator = boardPreferences.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry pair = (Map.Entry)iterator.next();
if (pair.getValue() == null)
{
_map.put(pair.getKey(), "");
}
else
{
_map.put(pair.getKey(), pair.getValue());
}
//System.out.println(pair.getKey() + " = " + pair.getValue());
}
System.out.println("Done: boardPreferences");
return _map;
}
}
|
package org.piwik.sdk;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Main tracking class
*/
public class Tracker implements Dispatchable<Integer> {
// Piwik default parameter values
private static final String defaultTrueValue = "1";
private static final String defaultRecordValue = defaultTrueValue;
private static final String defaultAPIVersionValue = "1";
// Default dispatcher values
private static final int piwikDefaultSessionTimeout = 30 * 60;
private static final int piwikDefaultDispatchTimer = 120;
private static final int piwikHTTPRequestTimeout = 5;
private static final int piwikQueryDefaultCapacity = 14;
// @todo: doc
private Piwik piwik;
private boolean isDispatching = false;
private int dispatchInterval = piwikDefaultDispatchTimer;
private DispatchingHandler dispatchingHandler;
private static String realScreenResolution;
private static String userAgent;
private static String userLanguage;
private static String userCountry;
private String lastEvent;
private int siteId;
private URL apiUrl;
private String userId;
private String authToken;
private long sessionTimeoutMillis;
private long sessionStartedMillis;
private ArrayList<String> queue = new ArrayList<String>();
private HashMap<String, String> queryParams;
private HashMap<String, CustomVariables> customVariables = new HashMap<String, CustomVariables>(2);
protected static final String LOGGER_TAG = Piwik.class.getName().toUpperCase();
/**
* Random object used for the request URl.
*/
private Random randomObject = new Random(new Date().getTime());
private Tracker(String url, int siteId) throws MalformedURLException {
clearQueryParams();
setAPIUrl(url);
setNewSession();
setSessionTimeout(piwikDefaultSessionTimeout);
setUserId(getRandomVisitorId());
reportUncaughtExceptions(true);
this.siteId = siteId;
}
protected Tracker(String url, int siteId, String authToken, Piwik piwik) throws MalformedURLException {
this(url, siteId);
this.authToken = authToken;
this.piwik = piwik;
}
/**
* Processes all queued events in background thread
*
* @return true if there are any queued events and opt out is inactive
*/
public boolean dispatch() {
if (!piwik.isOptOut() && queue.size() > 0) {
ArrayList<String> events = new ArrayList<String>(queue);
queue.clear();
TrackerBulkURLProcessor worker =
new TrackerBulkURLProcessor(this, piwikHTTPRequestTimeout, piwik.isDryRun());
worker.processBulkURLs(apiUrl, events, authToken);
return true;
}
return false;
}
/**
* Does dispatch immediately if dispatchInterval == 0
* if dispatchInterval is greater than zero auto dispatching will be launched
*/
private void tryDispatch() {
if (dispatchInterval == 0) {
dispatch();
} else if (dispatchInterval > 0) {
ensureAutoDispatching();
}
}
/**
* Starts infinity loop of dispatching process
* Auto invoked when any Tracker.track* method is called and dispatchInterval > 0
*/
private void ensureAutoDispatching() {
if (dispatchingHandler == null) {
dispatchingHandler = new DispatchingHandler(this);
}
dispatchingHandler.start();
}
/**
* Auto invoked when negative interval passed in setDispatchInterval
* or Activity is paused
*/
private void stopAutoDispatching() {
if (dispatchingHandler != null) {
dispatchingHandler.stop();
}
}
/**
* Set the interval to 0 to dispatch events as soon as they are queued.
* If a negative value is used the dispatch timer will never run, a manual dispatch must be used.
*
* @param dispatchInterval in seconds
*/
public Tracker setDispatchInterval(int dispatchInterval) {
this.dispatchInterval = dispatchInterval;
if (dispatchInterval < 1) {
stopAutoDispatching();
}
return this;
}
public int getDispatchInterval() {
return dispatchInterval;
}
@Override
public long getDispatchIntervalMillis() {
if (dispatchInterval > 0) {
return dispatchInterval * 1000;
}
return -1;
}
@Override
synchronized public void dispatchingCompleted(Integer count) {
isDispatching = false;
Log.d(Tracker.LOGGER_TAG, String.format("dispatched %s url(s)", count));
}
@Override
synchronized public void dispatchingStarted() {
isDispatching = true;
}
@Override
synchronized public boolean isDispatching() {
return isDispatching;
}
/**
* You can set any additional Tracking API Parameters within the SDK.
* This includes for example the local time (parameters h, m and s).
* <pre>
* tracker.set(QueryParams.HOURS, "10");
* tracker.set(QueryParams.MINUTES, "45");
* tracker.set(QueryParams.SECONDS, "30");
* </pre>
*
* @param key name
* @param value value
* @return tracker instance
*/
public Tracker set(String key, String value) {
if (value != null) {
queryParams.put(key, value);
}
return this;
}
public Tracker set(String key, Integer value) {
if (value != null) {
set(key, Integer.toString(value));
}
return this;
}
/**
* Defines the visitor ID for this request. You must set this value to exactly a 16 character
* hexadecimal string (containing only characters 01234567890abcdefABCDEF).
* When specified, the Visitor ID will be "enforced". This means that if there is no recent visit with
* this visitor ID, a new one will be created. If a visit is found in the last 30 minutes with your
* specified Visitor Id, then the new action will be recorded to this existing visit.
*
* @param userId any not 16 character hexadecimal string will be converted to md5 hash
*/
public Tracker setUserId(String userId) {
if (userId != null) {
if (userId.length() == 16 && userId.matches("^[0-9a-fA-F]{16}$")) {
this.userId = userId;
} else {
this.userId = md5(userId).substring(0, 16);
}
}
return this;
}
public Tracker setUserId(long userId) {
return setUserId(Long.toString(userId));
}
/**
* Sets the screen resolution of the browser which sends the request.
*
* @param width the screen width as an int value
* @param height the screen height as an int value
*/
public Tracker setResolution(final int width, final int height) {
return set(QueryParams.SCREEN_RESOLUTION, formatResolution(width, height));
}
private String formatResolution(final int width, final int height) {
return String.format("%sx%s", width, height);
}
public String getResolution() {
if (!queryParams.containsKey(QueryParams.SCREEN_RESOLUTION)) {
if (realScreenResolution == null) {
try {
DisplayMetrics dm = new DisplayMetrics();
WindowManager wm = (WindowManager) piwik.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(dm);
realScreenResolution = formatResolution(dm.widthPixels, dm.heightPixels);
} catch (Exception e) {
Log.w(Tracker.LOGGER_TAG, "Cannot grab resolution", e);
realScreenResolution = "unknown";
}
}
return realScreenResolution;
}
return queryParams.get(QueryParams.SCREEN_RESOLUTION);
}
public Tracker setUserCustomVariable(int index, String name, String value) {
return setCustomVariable(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES, index, name, value);
}
/**
* Does exactly the same as setUserCustomVariable but use screen scope
* You can track up to 5 custom variables for each screen view.
*/
public Tracker setScreenCustomVariable(int index, String name, String value) {
return setCustomVariable(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES, index, name, value);
}
/**
* Correspondents to action_name of Piwik Tracking API
*
* @param title string The title of the action being tracked. It is possible to use
* slashes / to set one or several categories for this action.
* For example, Help / Feedback will create the Action Feedback in the category Help.
*/
public Tracker setScreenTitle(String title) {
return set(QueryParams.ACTION_NAME, title);
}
/**
* Returns android system user agent
*
* @return well formatted user agent
*/
public String getUserAgent() {
if (userAgent == null) {
userAgent = System.getProperty("http.agent");
}
return userAgent;
}
/**
* Returns user language
*
* @return language
*/
public String getLanguage() {
if (userLanguage == null) {
userLanguage = Locale.getDefault().getLanguage();
}
return userLanguage;
}
/**
* Returns user country
*
* @return country
*/
public String getCountry() {
if (userCountry == null) {
userCountry = Locale.getDefault().getCountry();
}
return userCountry;
}
/**
* Set action_name param from activity's title and track view
*
* @param activity Current Activity instance
*/
public void activityStart(final Activity activity) {
if (activity != null) {
String breadcrumbs = getBreadcrumbs(activity);
trackScreenView(breadcrumbsToPath(breadcrumbs), breadcrumbs);
}
}
/**
* Force dispatching events if main activity is about to stop
*
* @param activity Current Activity instance
*/
public void activityStop(final Activity activity) {
if (activity != null && activity.isTaskRoot()) {
dispatch();
}
}
/**
* @param activity current activity
*/
public void activityPaused(final Activity activity) {
activityStop(activity);
}
/**
* Don't need to start auto dispatching
* due this will be started when any track event occurred
*
* @param activity current activity
*/
public void activityResumed(final Activity activity) {
activityStart(activity);
}
/**
* Session handling
*/
public void setNewSession() {
touchSession();
set(QueryParams.SESSION_START, defaultTrueValue);
}
private void touchSession() {
sessionStartedMillis = System.currentTimeMillis();
}
public void setSessionTimeout(int seconds) {
sessionTimeoutMillis = seconds * 1000;
}
protected void checkSessionTimeout() {
if (isExpired()) {
setNewSession();
}
}
protected boolean isExpired() {
return System.currentTimeMillis() - sessionStartedMillis > sessionTimeoutMillis;
}
/**
* Tracking methods
*
* @param path required tracking param, for example: "/user/settings/billing"
*/
public Tracker trackScreenView(String path) {
set(QueryParams.URL_PATH, path);
return doTrack();
}
/**
* @param path view path for example: "/user/settings/billing" or just empty string ""
* @param title string The title of the action being tracked. It is possible to use
* slashes / to set one or several categories for this action.
* For example, Help / Feedback will create the Action Feedback in the category Help.
*/
public Tracker trackScreenView(String path, String title) {
setScreenTitle(title);
return trackScreenView(path);
}
public Tracker trackEvent(String category, String action, String label, Integer value) {
if (category != null && action != null) {
set(QueryParams.EVENT_ACTION, action);
set(QueryParams.EVENT_CATEGORY, category);
set(QueryParams.EVENT_NAME, label);
set(QueryParams.EVENT_VALUE, value);
doTrack();
}
return this;
}
public Tracker trackEvent(String category, String action, String label) {
return trackEvent(category, action, label, null);
}
public Tracker trackEvent(String category, String action) {
return trackEvent(category, action, null, null);
}
/**
* By default, Goals in Piwik are defined as "matching" parts of the screen path or screen title.
* In this case a conversion is logged automatically. In some situations, you may want to trigger
* a conversion manually on other types of actions, for example:
* when a user submits a form
* when a user has stayed more than a given amount of time on the page
* when a user does some interaction in your Android application
*
* @param idGoal id of goal as defined in piwik goal settings
*/
public Tracker trackGoal(Integer idGoal) {
if (idGoal != null && idGoal > 0) {
set(QueryParams.GOAL_ID, idGoal);
return doTrack();
}
return this;
}
/**
* Tracking request will trigger a conversion for the goal of the website being tracked with this ID
*
* @param idGoal id of goal as defined in piwik goal settings
* @param revenue a monetary value that was generated as revenue by this goal conversion.
*/
public Tracker trackGoal(Integer idGoal, int revenue) {
set(QueryParams.REVENUE, revenue);
return trackGoal(idGoal);
}
/**
* Ensures that tracking application downloading will be fired only once
* by using SharedPreferences as flag storage
*/
public Tracker trackAppDownload() {
SharedPreferences prefs = piwik.getSharedPreferences(
Piwik.class.getPackage().getName(), Context.MODE_PRIVATE);
if (!prefs.getBoolean("downloaded", false)) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("downloaded", true);
editor.commit();
trackNewAppDownload();
}
return this;
}
/**
* Make sure to call this method only once per user
*/
public Tracker trackNewAppDownload() {
set(QueryParams.DOWNLOAD, getApplicationBaseURL());
set(QueryParams.ACTION_NAME, "application/downloaded");
set(QueryParams.URL_PATH, "/application/downloaded");
return trackEvent("Application", "downloaded");
}
/**
* Caught exceptions are errors in your app for which you've defined exception handling code,
* such as the occasional timeout of a network connection during a request for data.
*
* @param className $ClassName:$lineNumber
* @param description exception message
* @param isFatal true if it's RunTimeException
*/
public void trackException(String className, String description, boolean isFatal) {
className = className != null && className.length() > 0 ? className : "Unknown";
String actionName = "exception/" +
(isFatal ? "fatal/" : "") +
(className + "/") + description;
set(QueryParams.ACTION_NAME, actionName);
trackEvent("Exception", className, description, isFatal ? 1 : 0);
}
protected final Thread.UncaughtExceptionHandler customUEH =
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
String className;
try {
try {
StackTraceElement trace = ex.getStackTrace()[0];
className = trace.getClassName() + "/" + trace.getMethodName() + ":" + trace.getLineNumber();
} catch (Exception e) {
Log.w(Tracker.LOGGER_TAG, "Couldn't get stack info", e);
className = ex.getClass().getName();
}
boolean isFatal = className.startsWith("RuntimeException");
String excInfo = ex.getClass().getName() + " [" + ex.getMessage() + "]";
// track
trackException(className, excInfo, isFatal);
// dispatch immediately
dispatch();
} catch (Exception e) {
// fail silently
Log.e(Tracker.LOGGER_TAG, "Couldn't track uncaught exception", e);
} finally {
// re-throw critical exception further to the os (important)
if (Piwik.defaultUEH != null && Piwik.defaultUEH != customUEH) {
Piwik.defaultUEH.uncaughtException(thread, ex);
}
}
}
};
/**
* Uncaught exceptions are sent to Piwik automatically by default
*
* @param toggle true if reporting should be enabled
*/
public Tracker reportUncaughtExceptions(boolean toggle) {
if (toggle) {
// Setup handler for uncaught exception
Thread.setDefaultUncaughtExceptionHandler(customUEH);
} else {
Thread.setDefaultUncaughtExceptionHandler(Piwik.defaultUEH);
}
return this;
}
/**
* Set up required params
*/
protected void beforeTracking() {
set(QueryParams.API_VERSION, defaultAPIVersionValue);
set(QueryParams.SITE_ID, siteId);
set(QueryParams.RECORD, defaultRecordValue);
set(QueryParams.RANDOM_NUMBER, randomObject.nextInt(100000));
set(QueryParams.SCREEN_RESOLUTION, getResolution());
set(QueryParams.URL_PATH, getParamURL());
set(QueryParams.USER_AGENT, getUserAgent());
set(QueryParams.LANGUAGE, getLanguage());
set(QueryParams.COUNTRY, getCountry());
set(QueryParams.VISITOR_ID, userId);
set(QueryParams.ENFORCED_VISITOR_ID, userId);
set(QueryParams.DATETIME_OF_REQUEST, getCurrentDatetime());
set(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES, getCustomVariables(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES).toString());
set(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES, getCustomVariables(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES).toString());
checkSessionTimeout();
touchSession();
}
/**
* Builds URL, adds event to queue, clean all params after url was added
*/
protected Tracker doTrack() {
beforeTracking();
String event = getQuery();
if (piwik.isOptOut()) {
lastEvent = event;
Log.d(Tracker.LOGGER_TAG, String.format("URL omitted due to opt out: %s", event));
} else {
Log.d(Tracker.LOGGER_TAG, String.format("URL added to the queue: %s", event));
queue.add(event);
tryDispatch();
}
afterTracking();
return this;
}
/**
* Clean up params
*/
protected void afterTracking() {
clearQueryParams();
clearAllCustomVariables();
}
/**
*
* HELPERS
*
*/
/**
* Gets all custom vars from screen or visit scope
*
* @param namespace `_cvar` or `cvar` stored in
* QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES and
* QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES
* @return CustomVariables HashMap
*/
private CustomVariables getCustomVariables(String namespace) {
if (namespace == null) {
return null;
}
CustomVariables vars = customVariables.get(namespace);
if (vars == null) {
vars = new CustomVariables();
customVariables.put(namespace, vars);
}
return vars;
}
private void clearAllCustomVariables() {
getCustomVariables(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES).clear();
getCustomVariables(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES).clear();
}
private Tracker setCustomVariable(String namespace, int index, String name, String value) {
getCustomVariables(namespace).put(index, name, value);
return this;
}
private void clearQueryParams() {
if (queryParams != null) {
queryParams.clear();
}
queryParams = new HashMap<String, String>(piwikQueryDefaultCapacity);
}
private String getCurrentDatetime() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").format(new Date());
}
private String getBreadcrumbs(final Activity activity) {
Activity currentActivity = activity;
ArrayList<String> breadcrumbs = new ArrayList<String>();
while (currentActivity != null) {
breadcrumbs.add(currentActivity.getTitle().toString());
currentActivity = currentActivity.getParent();
}
return joinSlash(breadcrumbs);
}
private String joinSlash(List<String> sequence) {
if (sequence != null && sequence.size() > 0) {
return TextUtils.join("/", sequence);
}
return "";
}
private String breadcrumbsToPath(String breadcrumbs) {
return breadcrumbs.replaceAll("\\s", "");
}
protected String getQuery() {
return TrackerBulkURLProcessor.urlEncodeUTF8(queryParams);
}
/**
* For testing purposes
*
* @return query of the event ?r=1&sideId=1..
*/
protected String getLastEvent() {
return lastEvent;
}
protected void clearLastEvent() {
lastEvent = null;
}
private String getApplicationBaseURL() {
return String.format("http://%s", piwik.getApplicationDomain());
}
protected String getParamURL() {
String url = queryParams.get(QueryParams.URL_PATH);
if (url == null) {
url = "/";
} else if (url.startsWith("http:
return url;
} else if (!url.startsWith("/")) {
url = "/" + url;
}
return getApplicationBaseURL() + url;
}
protected String getUserId() {
return userId;
}
/**
* Sets the url of the piwik installation the dispatchable will track to.
* <p/>
* The given string should be in the format of RFC2396. The string will be converted to an url with no other url as
* its context.
*
* @param APIUrl as a string object
* @throws MalformedURLException
*/
protected final void setAPIUrl(final String APIUrl) throws MalformedURLException {
if (APIUrl == null) {
throw new MalformedURLException("You must provide the Piwik Tracker URL! e.g. http://piwik.website.org/piwik.php");
}
URL url = new URL(APIUrl);
String path = url.getPath();
if (path.endsWith("piwik.php") || path.endsWith("piwik-proxy.php")) {
this.apiUrl = url;
} else {
if (!path.endsWith("/")) {
path += "/";
}
this.apiUrl = new URL(url, path + "piwik.php");
}
}
protected String getAPIUrl() {
return apiUrl.toString();
}
private String getRandomVisitorId() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
}
public static String md5(String s) {
if (s == null) {
return null;
}
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(s.getBytes("UTF-8"), 0, s.length());
BigInteger i = new BigInteger(1, m.digest());
return String.format("%1$032x", i);
} catch (UnsupportedEncodingException e) {
Log.w(Tracker.LOGGER_TAG, s, e);
} catch (NoSuchAlgorithmException e) {
Log.w(Tracker.LOGGER_TAG, s, e);
}
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tracker tracker = (Tracker) o;
return siteId == tracker.siteId && apiUrl.equals(tracker.apiUrl);
}
@Override
public int hashCode() {
int result = siteId;
result = 31 * result + apiUrl.hashCode();
return result;
}
/**
* CONSTANTS
*/
public static class QueryParams {
public static final String SITE_ID = "idsite";
public static final String AUTHENTICATION_TOKEN = "token_auth";
public static final String RECORD = "rec";
public static final String API_VERSION = "apiv";
public static final String SCREEN_RESOLUTION = "res";
public static final String HOURS = "h";
public static final String MINUTES = "m";
public static final String SECONDS = "s";
public static final String ACTION_NAME = "action_name";
public static final String URL_PATH = "url";
public static final String USER_AGENT = "ua";
public static final String VISITOR_ID = "_id";
public static final String ENFORCED_VISITOR_ID = "cid";
public static final String VISIT_SCOPE_CUSTOM_VARIABLES = "_cvar";
public static final String SCREEN_SCOPE_CUSTOM_VARIABLES = "cvar";
public static final String RANDOM_NUMBER = "r";
public static final String FIRST_VISIT_TIMESTAMP = "_idts";
public static final String PREVIOUS_VISIT_TIMESTAMP = "_viewts";
public static final String TOTAL_NUMBER_OF_VISITS = "_idvc";
public static final String GOAL_ID = "idgoal";
public static final String REVENUE = "revenue";
public static final String SESSION_START = "new_visit";
public static final String LANGUAGE = "lang";
public static final String COUNTRY = "country";
public static final String LATITUDE = "lat";
public static final String LONGITUDE = "long";
public static final String SEARCH_KEYWORD = "search";
public static final String SEARCH_CATEGORY = "search_cat";
public static final String SEARCH_NUMBER_OF_HITS = "search_count";
public static final String REFERRER = "urlref";
public static final String DATETIME_OF_REQUEST = "cdt";
public static final String DOWNLOAD = "download";
// Campaign
static final String CAMPAIGN_NAME = "_rcn";
static final String CAMPAIGN_KEYWORD = "_rck";
// Events
static final String EVENT_CATEGORY = "e_c";
static final String EVENT_ACTION = "e_a";
static final String EVENT_NAME = "e_n";
static final String EVENT_VALUE = "e_v";
}
}
|
package org.eclipse.emf.emfstore.client.test.server;
import org.eclipse.emf.emfstore.client.model.ServerInfo;
import org.eclipse.emf.emfstore.client.model.Usersession;
import org.eclipse.emf.emfstore.client.model.Workspace;
import org.eclipse.emf.emfstore.client.model.WorkspaceManager;
import org.eclipse.emf.emfstore.client.model.connectionmanager.AbstractSessionProvider;
import org.eclipse.emf.emfstore.client.model.util.EMFStoreCommand;
import org.eclipse.emf.emfstore.client.test.SetupHelper;
import org.eclipse.emf.emfstore.server.exceptions.AccessControlException;
import org.eclipse.emf.emfstore.server.exceptions.EmfStoreException;
import org.junit.Assert;
public class TestSessionProvider extends AbstractSessionProvider {
private static Usersession usersession;
private static TestSessionProvider instance;
public static TestSessionProvider getInstance() {
if (instance == null) {
instance = new TestSessionProvider();
}
return instance;
}
public Usersession getDefaultUsersession() throws AccessControlException, EmfStoreException {
new EMFStoreCommand() {
@Override
protected void doRun() {
try {
usersession.logIn();
} catch (AccessControlException e) {
Assert.fail();
} catch (EmfStoreException e) {
Assert.fail();
}
}
}.run(false);
return usersession;
}
private TestSessionProvider() {
final Workspace workspace = WorkspaceManager.getInstance().getCurrentWorkspace();
usersession = org.eclipse.emf.emfstore.client.model.ModelFactory.eINSTANCE.createUsersession();
usersession.setServerInfo(SetupHelper.getServerInfo());
usersession.setUsername("super");
usersession.setPassword("super");
new EMFStoreCommand() {
@Override
protected void doRun() {
workspace.getUsersessions().add(usersession);
}
}.run(false);
workspace.save();
}
@Override
public Usersession provideUsersession(ServerInfo serverInfo) throws EmfStoreException {
return usersession;
}
@Override
public void login(Usersession usersession) throws EmfStoreException {
usersession.logIn();
}
}
|
package com.egzosn.pay.ali.bean;
import com.egzosn.pay.common.bean.TransferOrder;
import java.math.BigDecimal;
import java.util.TreeMap;
/**
* ()
*
* @author egan
* date 2020/5/18 21:08
* email [email protected]
*/
public class AliTransferOrder extends TransferOrder {
private String identity;
private String identityType;
/**
*
*
* @return
*/
public String getOutBizNo() {
return getOutNo();
}
public void setOutBizNo(String outBizNo) {
setOutNo(outBizNo);
}
/**
* STD_RED_PACKET[0.01,100000000]
* TRANS_ACCOUNT_NO_PWD[0.1,100000000]
*
* @return
*/
public BigDecimal getTransAmount() {
return getAmount();
}
public void setTransAmount(BigDecimal transAmount) {
setAmount(transAmount);
}
/**
*
*
* @return
*/
public String getOrderTitle() {
return (String) getAttr("order_title");
}
public void setOrderTitle(String orderTitle) {
addAttr("order_title", orderTitle);
}
/**
*
* DIRECT_TRANSFER/, B2C;
* PERSONAL_COLLECTIONC2C-
*
* @return
*/
public String getBizScene() {
return (String) getAttr("biz_scene");
}
public void setBizScene(String bizScene) {
addAttr("biz_scene", bizScene);
}
/**
*
*
* @return
*/
private TreeMap<String, Object> getPayeeinfo() {
Object payeeInfo = getAttr("payee_info");
if (null != payeeInfo && payeeInfo instanceof TreeMap){
return (TreeMap<String, Object>) payeeInfo;
}
TreeMap<String, Object> payee = new TreeMap<>();
addAttr("payee_info", payee);
return payee;
}
/**
*
*
* @return
*/
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
getPayeeinfo().put("identity", identity);
}
/**
*
* 1ALIPAY_USER_ID ID
* 2ALIPAY_LOGON_ID
*
* @return
*/
public String getIdentityType() {
return identityType;
}
public void setIdentityType(String identityType) {
this.identityType = identityType;
getPayeeinfo().put("identity_type", identityType);
}
/**
*
*
* @return
*/
public String getName() {
return getPayeeName();
}
public void setName(String name) {
setPayeeName(name);
getPayeeinfo().put("name", name);
}
/**
*
* 1sub_biz_scene REDPACKETC2CB2C
* <p>
* 2withdraw_timelinessT1T0T+0T1T+1T0T1
*
* @return
*/
public String getBusinessParams() {
return (String) getAttr("business_params");
}
public void setBusinessParams(String businessParams) {
addAttr("business_params", businessParams);
}
}
|
package cgeo.geocaching.utils;
import cgeo.geocaching.R;
import cgeo.geocaching.databinding.DialogTitleButtonButtonBinding;
import cgeo.geocaching.databinding.EmojiselectorBinding;
import cgeo.geocaching.maps.CacheMarker;
import cgeo.geocaching.storage.extension.EmojiLRU;
import cgeo.geocaching.storage.extension.OneTimeDialogs;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.functions.Action1;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Pair;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class EmojiUtils {
public static final int NO_EMOJI = 0;
// internal consts for calculated circles
private static final int COLOR_VALUES = 3; // supported # of different values per RGB
private static final int COLOR_SPREAD = 127;
private static final int COLOR_OFFSET = 0;
private static final int OPACITY_VALUES = 5;
private static final int OPACITY_SPREAD = 51;
private static final int CUSTOM_SET_SIZE_PER_OPACITY = COLOR_VALUES * COLOR_VALUES * COLOR_VALUES;
private static final int CUSTOM_SET_SIZE = CUSTOM_SET_SIZE_PER_OPACITY * OPACITY_VALUES;
// Unicode custom glyph area needed/supported by this class
private static final int CUSTOM_ICONS_START = 0xe000;
private static final int CUSTOM_ICONS_END = CUSTOM_ICONS_START + CUSTOM_SET_SIZE - 1; // max. possible value by Unicode definition: 0xf8ff;
private static final int CUSTOM_ICONS_START_CIRCLES = CUSTOM_ICONS_START;
private static final int VariationSelectorEmoji = 0xfe0f;
// list of emojis supported by the EmojiPopup
// should ideally be supported by the Android API level we have set as minimum (currently API 21 = Android 5),
// but starting with API 23 (Android 6) the app automatically filters out characters not supported by their fonts
private static final EmojiSet[] symbols = {
// category symbols
new EmojiSet(0x2764, new int[]{
/* hearts */ 0x2764, 0x1f9e1, 0x1f49b, 0x1f49a, 0x1f499, 0x1f49c, 0x1f90e, 0x1f5a4, 0x1f90d,
/* geometric */ 0x1f7e5, 0x1f7e7, 0x1f7e8, 0x1f7e9, 0x1f7e6, 0x1f7ea, 0x1f7eb, 0x2b1b, 0x2b1c,
/* geometric */ 0x1f536, 0x1f537,
/* events */ 0x1f383, 0x1f380, 0x1f384, 0x1f389,
/* award-medal */ 0x1f947, 0x1f948, 0x1f949, 0x1f3c6,
/* office */ 0x1f4c6,
/* warning */ 0x26a0, 0x26d4, 0x1f6ab, 0x1f6b3, 0x1f6d1, 0x2622,
/* av-symbol */ 0x1f505, 0x1f506,
/* other-symbol */ 0x2b55, 0x2705, 0x2611, 0x2714, 0x2716, 0x2795, 0x2796, 0x274c, 0x274e, 0x2733, 0x2734, 0x2747, 0x203c, 0x2049, 0x2753, 0x2757,
/* flags */ 0x1f3c1, 0x1f6a9, 0x1f3f4, 0x1f3f3
}),
// category custom symbols - will be filled dynamically below; has to be at position CUSTOM_GLYPHS_ID within EmojiSet[]
new EmojiSet(CUSTOM_ICONS_START_CIRCLES + 18 + CUSTOM_SET_SIZE_PER_OPACITY, new int[CUSTOM_SET_SIZE_PER_OPACITY]), // "18" to pick red circle instead of black
// category places
new EmojiSet(0x1f30d, new int[]{
/* globe */ 0x1f30d, 0x1f30e, 0x1f30f, 0x1f5fa,
/* geographic */ 0x26f0, 0x1f3d4, 0x1f3d6, 0x1f3dc, 0x1f3dd, 0x1f3de,
/* buildings */ 0x1f3e0, 0x1f3e1, 0x1f3e2, 0x1f3d9, 0x1f3eb, 0x1f3ea, 0x1F3ed, 0x1f3e5, 0x1f3da, 0x1f3f0,
/* other */ 0x1f5fd, 0x26f2, 0x2668, 0x1f6d2, 0x1f3ad, 0x1f3a8,
/* plants */ 0x1f332, 0x1f333, 0x1f334, 0x1f335, 0x1f340,
/* transport */ 0x1f682, 0x1f683, 0x1f686, 0x1f687, 0x1f68d, 0x1f695, 0x1f6b2, 0x1f697, 0x1f699, 0x2693, 0x26f5, 0x2708, 0x1f680,
/* transp.-sign */ 0x267f, 0x1f6bb,
/* time */ 0x23f3, 0x231a, 0x23f1, 0x1f324, 0x2600, 0x1f319, 0x1f318, 0x2728
}),
// category food
new EmojiSet(0x2615, new int[]{
/* fruits */ 0x1f34a, 0x1f34b, 0x1f34d, 0x1f34e, 0x1f34f, 0x1f95d, 0x1f336, 0x1f344,
/* other */ 0x1f968, 0x1f354, 0x1f355,
/* food-sweet */ 0x1f366, 0x1f370, 0x1f36d,
/* drink */ 0x1f964, 0x2615, 0x1f37a
}),
// category activity
new EmojiSet(0x1f3c3, new int[]{
/* person-sport */ 0x26f7, 0x1f3c4, 0x1f6a3, 0x1f3ca, 0x1f6b4,
/* p.-activity */ 0x1f6b5, 0x1f9d7,
/* person-role */ 0x1f575,
/* sport */ 0x26bd, 0x1f94e, 0x1f3c0, 0x1f3c8, 0x1f93f, 0x1f3bf, 0x1f3af, 0x1f9ff,
/* tool */ 0x1fa9c,
/* science */ 0x2697, 0x1f9ea, 0x1f52c,
/* other things */ 0x1f50e, 0x1f526, 0x1f4a1, 0x1f4d4, 0x1f4dc, 0x1f4ec, 0x1f3f7
}),
// category people
new EmojiSet(0x1f600, new int[]{
/* smileys */ 0x1f600, 0x1f60d, 0x1f641, 0x1f621, 0x1f9d0,
/* silhouettes */ 0x1f47b, 0x1f464, 0x1f465, 0x1f5e3,
/* people */ 0x1f466, 0x1f467, 0x1f468, 0x1f469, 0x1f474, 0x1f475, 0x1f46a,
/* hands */ 0x1f44d, 0x1f44e, 0x1f4aa, 0x270d
}),
};
private static final int CUSTOM_GLYPHS_ID = 1;
private static boolean fontIsChecked = false;
private static final Boolean lockGuard = false;
private static final SparseArray<CacheMarker> emojiCache = new SparseArray<>();
private static class EmojiSet {
public int tabSymbol;
public int remaining;
public int[] symbols;
EmojiSet(final int tabSymbol, final int[] symbols) {
this.tabSymbol = tabSymbol;
this.remaining = symbols.length;
this.symbols = symbols;
}
}
private EmojiUtils() {
// utility class
}
public static void selectEmojiPopup(final Context context, final int currentValue, @DrawableRes final int defaultRes, final Action1<Integer> setNewCacheIcon) {
// calc sizes for markers
final Pair<Integer, Integer> markerDimensionsTemp = DisplayUtils.getDrawableDimensions(context.getResources(), R.drawable.ic_menu_filter);
final int markerAvailable = (int) (markerDimensionsTemp.first * 0.5);
final Pair<Integer, Integer> markerDimensions = new Pair<>(markerAvailable, markerAvailable);
final EmojiPaint paint = new EmojiPaint(context.getResources(), markerDimensions, markerAvailable, 0, DisplayUtils.calculateMaxFontsize(35, 10, 150, markerAvailable));
// fill dynamic EmojiSet
prefillCustomCircles(0);
// check EmojiSet for characters not supported on this device
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
synchronized (lockGuard) {
if (!fontIsChecked) {
final Paint checker = new TextPaint();
checker.setTypeface(Typeface.DEFAULT);
for (EmojiSet symbol : symbols) {
int iPosNeu = 0;
for (int i = 0; i < symbol.symbols.length; i++) {
if (i != iPosNeu) {
symbol.symbols[iPosNeu] = symbol.symbols[i];
}
if ((symbol.symbols[i] >= CUSTOM_ICONS_START && symbol.symbols[i] <= CUSTOM_ICONS_END) || checker.hasGlyph(new String(Character.toChars(symbol.symbols[i])))) {
iPosNeu++;
}
}
symbol.remaining = iPosNeu;
}
fontIsChecked = true;
}
}
}
// create dialog
final EmojiselectorBinding dialogView = EmojiselectorBinding.inflate(LayoutInflater.from(context));
final DialogTitleButtonButtonBinding customTitle = DialogTitleButtonButtonBinding.inflate(LayoutInflater.from(context));
final AlertDialog dialog = Dialogs.newBuilder(context)
.setView(dialogView.getRoot())
.setCustomTitle(customTitle.getRoot())
.create();
final int maxCols = DisplayUtils.calculateNoOfColumns(context, 60);
dialogView.emojiGrid.setLayoutManager(new GridLayoutManager(context, maxCols));
final EmojiViewAdapter gridAdapter = new EmojiViewAdapter(context, paint, symbols[0].symbols, symbols[0].remaining, currentValue, false, newCacheIcon -> onItemSelected(dialog, setNewCacheIcon, newCacheIcon));
dialogView.emojiGrid.setAdapter(gridAdapter);
dialogView.emojiOpacity.setLayoutManager(new GridLayoutManager(context, OPACITY_VALUES));
final int[] emojiOpacities = new int[OPACITY_VALUES];
emojiOpacities[0] = CUSTOM_ICONS_START_CIRCLES + 18;
for (int i = 1; i < OPACITY_VALUES; i++) {
emojiOpacities[i] = emojiOpacities[i - 1] + CUSTOM_SET_SIZE_PER_OPACITY;
}
final EmojiViewAdapter opacityAdapter = new EmojiViewAdapter(context, paint, emojiOpacities, emojiOpacities.length, emojiOpacities[0], true, newgroup -> {
final int newOpacity = (newgroup - CUSTOM_ICONS_START_CIRCLES) / CUSTOM_SET_SIZE_PER_OPACITY;
prefillCustomCircles(newOpacity);
gridAdapter.notifyDataSetChanged();
});
dialogView.emojiOpacity.setAdapter(opacityAdapter);
dialogView.emojiGroups.setLayoutManager(new GridLayoutManager(context, symbols.length));
final int[] emojiGroups = new int[symbols.length];
for (int i = 0; i < symbols.length; i++) {
emojiGroups[i] = symbols[i].tabSymbol;
}
final EmojiViewAdapter groupsAdapter = new EmojiViewAdapter(context, paint, emojiGroups, emojiGroups.length, symbols[0].tabSymbol, true, newgroup -> {
int newGroupId = 0;
for (int i = 0; i < symbols.length; i++) {
if (symbols[i].tabSymbol == newgroup) {
gridAdapter.setData(symbols[i].symbols, symbols[i].remaining);
newGroupId = i;
}
dialogView.emojiOpacity.setVisibility(newGroupId == CUSTOM_GLYPHS_ID ? View.VISIBLE : View.GONE);
}
});
dialogView.emojiGroups.setAdapter(groupsAdapter);
dialogView.emojiLru.setLayoutManager(new GridLayoutManager(context, maxCols));
final int[] lru = EmojiLRU.getLRU();
final EmojiViewAdapter lruAdapter = new EmojiViewAdapter(context, paint, lru, lru.length, 0, false, newCacheIcon -> onItemSelected(dialog, setNewCacheIcon, newCacheIcon));
dialogView.emojiLru.setAdapter(lruAdapter);
customTitle.dialogTitleTitle.setText(R.string.select_icon);
// right button displays current value; clicking simply closes the dialog
customTitle.dialogButton2.setVisibility(View.VISIBLE);
if (currentValue == -1) {
customTitle.dialogButton2.setImageResource(R.drawable.ic_menu_mark);
} else if (currentValue != 0) {
customTitle.dialogButton2.setImageDrawable(getEmojiDrawable(paint, currentValue));
} else if (defaultRes != 0) {
customTitle.dialogButton2.setImageResource(defaultRes);
}
customTitle.dialogButton2.setOnClickListener(v -> dialog.dismiss());
// left button displays default value (if different from current value)
if (currentValue != 0 && defaultRes != currentValue) {
customTitle.dialogButton1.setVisibility(View.VISIBLE);
customTitle.dialogButton1.setImageResource(defaultRes == 0 ? R.drawable.ic_menu_reset : defaultRes);
customTitle.dialogButton1.setOnClickListener(v -> {
setNewCacheIcon.call(0);
dialog.dismiss();
});
}
dialog.show();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Dialogs.basicOneTimeMessage(context, OneTimeDialogs.DialogType.MISSING_UNICODE_CHARACTERS);
}
}
private static void onItemSelected(final AlertDialog dialog, final Action1<Integer> callback, final int selectedValue) {
dialog.dismiss();
EmojiLRU.add(selectedValue);
callback.call(selectedValue);
}
private static void prefillCustomCircles(final int opacity) {
for (int i = 0; i < CUSTOM_SET_SIZE_PER_OPACITY; i++) {
symbols[CUSTOM_GLYPHS_ID].symbols[i] = CUSTOM_ICONS_START_CIRCLES + i + opacity * CUSTOM_SET_SIZE_PER_OPACITY;
}
}
private static class EmojiViewAdapter extends RecyclerView.Adapter<EmojiViewAdapter.ViewHolder> {
private int[] data;
private int remaining;
private final LayoutInflater inflater;
private final Action1<Integer> callback;
private final EmojiPaint paint;
private int currentValue = 0;
private final boolean highlightCurrent;
EmojiViewAdapter(final Context context, final EmojiPaint paint, final int[] data, final int remaining, final int currentValue, final boolean hightlightCurrent, final Action1<Integer> callback) {
this.inflater = LayoutInflater.from(context);
this.paint = paint;
this.setData(data, remaining);
this.currentValue = currentValue;
this.highlightCurrent = hightlightCurrent;
this.callback = callback;
}
public void setData(final int[] data, final int remaining) {
this.data = data;
this.remaining = remaining;
notifyDataSetChanged();
}
@Override
@NonNull
public EmojiViewAdapter.ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
final View view = inflater.inflate(R.layout.emojiselector_item, parent, false);
return new EmojiViewAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final EmojiViewAdapter.ViewHolder holder, final int position) {
if (data[position] >= CUSTOM_ICONS_START && data[position] <= CUSTOM_ICONS_END) {
holder.iv.setImageDrawable(EmojiUtils.getEmojiDrawable(paint, data[position]));
holder.iv.setVisibility(View.VISIBLE);
holder.tv.setVisibility(View.GONE);
} else {
holder.tv.setText(getEmojiAsString(data[position]));
holder.iv.setVisibility(View.GONE);
holder.tv.setVisibility(View.VISIBLE);
}
if (highlightCurrent) {
holder.sep.setVisibility(currentValue == data[position] ? View.VISIBLE : View.INVISIBLE);
}
holder.itemView.setOnClickListener(v -> {
currentValue = data[position];
callback.call(currentValue);
if (highlightCurrent) {
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return remaining;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView tv;
protected ImageView iv;
protected View sep;
ViewHolder(final View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.info_text);
iv = itemView.findViewById(R.id.info_drawable);
sep = itemView.findViewById(R.id.separator);
}
}
}
/**
* get emoji string from codepoint
* @param emoji codepoint of the emoji to display
* @return string emoji with protection from rendering as black-and-white glyphs
*/
public static String getEmojiAsString(final int emoji) {
return new String(Character.toChars(emoji)) + new String(Character.toChars(VariationSelectorEmoji));
}
/**
* builds a drawable the size of a marker with a given text
* @param paint - paint data structure for Emojis
* @param emoji codepoint of the emoji to display
* @return drawable bitmap with text on it
*/
@NonNull
private static BitmapDrawable getEmojiDrawableHelper(final EmojiPaint paint, final int emoji) {
final Bitmap bm = Bitmap.createBitmap(paint.bitmapDimensions.first, paint.bitmapDimensions.second, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bm);
if (emoji >= CUSTOM_ICONS_START && emoji <= CUSTOM_ICONS_END) {
final int radius = paint.availableSize / 2;
final Paint cPaint = new Paint();
// calculate circle details
final int v = emoji - CUSTOM_ICONS_START_CIRCLES;
final int aIndex = v / (COLOR_VALUES * COLOR_VALUES * COLOR_VALUES);
final int rIndex = (v / (COLOR_VALUES * COLOR_VALUES)) % COLOR_VALUES;
final int gIndex = (v / COLOR_VALUES) % COLOR_VALUES;
final int bIndex = v % COLOR_VALUES;
final int color = Color.argb(
255 - (aIndex * OPACITY_SPREAD),
COLOR_OFFSET + rIndex * COLOR_SPREAD,
COLOR_OFFSET + gIndex * COLOR_SPREAD,
COLOR_OFFSET + bIndex * COLOR_SPREAD);
cPaint.setColor(color);
cPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle((int) (paint.bitmapDimensions.first / 2), (int) (paint.bitmapDimensions.second / 2) - paint.offsetTop, radius, cPaint);
} else {
final String text = getEmojiAsString(emoji);
final TextPaint tPaint = new TextPaint();
tPaint.setTextSize(paint.fontsize);
final StaticLayout lsLayout = new StaticLayout(text, tPaint, paint.availableSize, Layout.Alignment.ALIGN_CENTER, 1, 0, false);
canvas.translate((int) ((paint.bitmapDimensions.first - lsLayout.getWidth()) / 2), (int) ((paint.bitmapDimensions.second - lsLayout.getHeight()) / 2) - paint.offsetTop);
lsLayout.draw(canvas);
canvas.save();
canvas.restore();
}
return new BitmapDrawable(paint.res, bm);
}
/**
* get a drawable the size of a marker with a given text (either from cache or freshly built)
* @param paint - paint data structure for Emojis
* @param emoji codepoint of the emoji to display
* @return drawable bitmap with text on it
*/
@NonNull
public static BitmapDrawable getEmojiDrawable(final EmojiPaint paint, final int emoji) {
final int hashcode = new HashCodeBuilder()
.append(paint.bitmapDimensions.first)
.append(paint.availableSize)
.append(paint.fontsize)
.append(emoji)
.toHashCode();
synchronized (emojiCache) {
CacheMarker marker = emojiCache.get(hashcode);
if (marker == null) {
marker = new CacheMarker(hashcode, getEmojiDrawableHelper(paint, emoji));
emojiCache.put(hashcode, marker);
}
return (BitmapDrawable) marker.getDrawable();
}
}
/**
* configuration for getEmojiDrawable
*/
public static class EmojiPaint {
public final Resources res;
public final Pair<Integer, Integer> bitmapDimensions;
public final int availableSize;
public final int offsetTop;
public final int fontsize;
EmojiPaint(final Resources res, final Pair<Integer, Integer> bitmapDimensions, final int availableSize, final int offsetTop, final int fontsize) {
this.res = res;
this.bitmapDimensions = bitmapDimensions;
this.availableSize = availableSize;
this.offsetTop = offsetTop;
this.fontsize = fontsize;
}
}
}
|
package org.lamport.tla.toolbox.tool.prover.ui.dialog;
import java.util.ArrayList;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.FileEditorInput;
import org.lamport.tla.toolbox.editor.basic.TLAEditor;
import org.lamport.tla.toolbox.editor.basic.util.EditorUtil;
import org.lamport.tla.toolbox.tool.prover.ProverPreferenceInitializer;
import org.lamport.tla.toolbox.tool.prover.job.ITLAPMOptions;
import org.lamport.tla.toolbox.tool.prover.job.ProverJob;
import org.lamport.tla.toolbox.tool.prover.ui.ProverUIActivator;
import org.lamport.tla.toolbox.tool.prover.ui.preference.ProverSecondPreferencePage;
import org.lamport.tla.toolbox.tool.prover.ui.util.ProverHelper;
/**
* A dialog that allows the user to launch the prover
* with a general set of options selected.
*
* The method {@link #createDialogArea(Composite)} creates
* the widgets that makes up the dialog and initializes their
* values. The method {@link #okPressed()} does the work for
* storing the values in the dialog and launching the prover
* when the user presses OK.
*
* The default values for the options in this dialog are set in
* the method {@link ProverPreferenceInitializer#initializeDefaultPreferences()}.
*
* @author Daniel Ricketts
*
*/
public class LaunchProverDialog extends Dialog
{
/**
* The widget where the user can enter in arbitrary command line arguments
* for the tlapm.
*/
private Text extraOptionsText;
/*
* Buttons that control what prover to use.
*/
private Button isatool;
private Button isacheck;
private Button noisa;
/**
* Button that should be checked if
* the user wants the PM to be launched
* for status checking only.
*/
private Button noProving;
/**
* Button that should be checked if
* the user wants the PM to
* be launched with the
* {@link ITLAPMOptions#TOOLBOX} option.
*/
private Button toolboxMode;
/**
* Button that should be checked if the user
* wants the PM to be launched with
* the option {@link ITLAPMOptions#PARANOID}.
*/
private Button paranoid;
/**
* The widget for entering the number of threads.
*/
// private Text numThreadsText;
/**
* Button to be checked for normal fingerprint use.
*/
private Button fpNormal;
/**
* Button to be checked to erase all fingerprints and
* start fresh.
*/
private Button fpForgetAll;
/**
* Button to be checked to erase all fingerprints in
* the currently selected region.
*/
private Button fpForgetCurrent;
public static final String EXTRA_OPTIONS_KEY = "extra_options";
public static final String TOOLBOX_MODE_KEY = "toolbox_mode";
public static final String ISATOOL_KEY = "isatool";
public static final String STATUS_CHECK_KEY = "status_check";
public static final String ISACHECK_KEY = "isacheck";
public static final String NOISA_KEY = "noisa";
public static final String PARANOID_KEY = "paranoid";
// public static final String NUM_THREADS_KEY = "num_threads";
public static final String FP_NORMAL_KEY = "fpnormal";
public static final String FP_FORGET_ALL_KEY = "fpforgetall";
public static final String FP_FORGET_CURRENT_KEY = "fpforgetcurrent";
/**
* Creates a general prover launch dialog that allows
* the user to launch the prover with any possible set
* of options. See {@link #open()} for opening the
* dialog.
*
* @param parentShell
*/
public LaunchProverDialog(IShellProvider parentShell)
{
super(parentShell);
setBlockOnOpen(true);
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent)
{
/*
* We need the preference store for retrieving
* the of the dialog widgets from the last time
* the dialog was launched.
*/
IPreferenceStore store = ProverUIActivator.getDefault().getPreferenceStore();
/*
* The creates the composite that contains all widgets
* within the dialog. It has a grid layout for its children
* widgets with two columns.
*/
Composite topComposite = new Composite(parent, SWT.NONE);
GridData gd = new GridData();
topComposite.setLayoutData(gd);
topComposite.setLayout(new GridLayout(2, true));
/*
* This creates the label for the text field for
* entering command line arguments. It is set to span
* both columns.
*/
Label label = new Label(topComposite, SWT.NONE);
label.setText("Enter the prover options.");
gd = new GridData();
// spans both columns
gd.horizontalSpan = 2;
label.setLayoutData(gd);
/*
* This creates the text field for entering arbitrary
* command line arguments. It is set to span both columns.
*/
// extraOptionsText = new Text(topComposite, SWT.SINGLE);
// gd = new GridData(SWT.FILL, SWT.FILL, true, true);
// // spans both columns
// gd.horizontalSpan = 2;
// extraOptionsText.setLayoutData(gd);
// extraOptionsText.setText(store.getString(EXTRA_OPTIONS_KEY));
/*
* Below the text field there will be two columns of options
* that the user should select if he doesn't want to use
* the text field. These two columns are organized into
* a Group. Group is a subclass of composite
* that provides a border. Within this group, we create a
* composite for each column, named
* left and right.
*/
Group nonCommandLineGroup = new Group(topComposite, SWT.NONE);
gd = new GridData();
// spans both columns
gd.horizontalSpan = 2;
nonCommandLineGroup.setLayoutData(gd);
nonCommandLineGroup.setLayout(new GridLayout(2, true));
// sets the title of the group
// nonCommandLineGroup.setText("And/Or choose from this list of options for launching the prover:");
/*
* Now we create the left column composite and fill it
* with widgets.
*/
Composite left = new Composite(nonCommandLineGroup, SWT.NONE);
gd = new GridData();
left.setLayoutData(gd);
left.setLayout(new GridLayout(1, true));
/*
* Now we create some regular old check boxes in the left column
* for launching in toolbox mode and checking
* status.
*/
toolboxMode = new Button(left, SWT.CHECK);
toolboxMode.setText(" Launch in toolbox mode");
toolboxMode.setSelection(store.getBoolean(TOOLBOX_MODE_KEY));
/*
* We create a set of three mutually exclusive options.
* Buttons are made mutually exclusive by setting
* the style bit SWT.RADIO. I believe that for all radio buttons that
* are immediate children of a given composite, at most one
* is selectable at a given time. Thus, we put the three
* mutually exclusive options in a composite. A group is a
* subclass of composite that has a border.
*
* I don't know if this is useful for prover options, but
* just in case, I put it here.
*/
Group proverGroup = new Group(left, SWT.NONE);
proverGroup.setLayout(new GridLayout(1, false));
// sets the title of the group
proverGroup.setText("Choose prover(s) to use:");
isatool = new Button(proverGroup, SWT.RADIO);
isatool.setText(" Use Isabelle only if necessary.");
isatool.setSelection(store.getBoolean(ISATOOL_KEY));
noProving = new Button(proverGroup, SWT.RADIO);
noProving.setText(" No proving.");
noProving.setSelection(store.getBoolean(STATUS_CHECK_KEY));
isacheck = new Button(proverGroup, SWT.RADIO);
isacheck.setText(" Check Zenon proofs with Isabelle.");
isacheck.setSelection(store.getBoolean(ISACHECK_KEY));
noisa = new Button(proverGroup, SWT.RADIO);
noisa.setText(" Do not use Isabelle.");
noisa.setSelection(store.getBoolean(NOISA_KEY));
Group fpGroup = new Group(left, SWT.NONE);
fpGroup.setLayout(new GridLayout(1, false));
// sets the title of the group
fpGroup.setText("Using previous results:");
fpNormal = new Button(fpGroup, SWT.RADIO);
fpNormal.setText(" Use previous results.");
fpNormal.setSelection(store.getBoolean(FP_NORMAL_KEY));
fpForgetAll = new Button(fpGroup, SWT.RADIO);
fpForgetAll.setText(" Forget all previous results.");
fpForgetAll.setSelection(store.getBoolean(FP_FORGET_ALL_KEY));
fpForgetCurrent = new Button(fpGroup, SWT.RADIO);
fpForgetCurrent.setText(" Forget currently selected previous results.");
fpForgetCurrent.setSelection(store.getBoolean(FP_FORGET_CURRENT_KEY));
/*
* Add a listener that disables the paranoid button
* whenever the no proving button is selected. Unfortunately,
* this doesn't disable when the dialog is first created and
* "no proving" is selected.
*/
noProving.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e)
{
if (paranoid != null)
{
paranoid.setEnabled(!noProving.getSelection());
}
}
public void widgetDefaultSelected(SelectionEvent e)
{
if (paranoid != null)
{
paranoid.setEnabled(!noProving.getSelection());
}
}
});
/*
* Now we create the composite for the right column
* and fill it with widgets.
*/
Composite right = new Composite(nonCommandLineGroup, SWT.NONE);
gd = new GridData();
right.setLayoutData(gd);
right.setLayout(new GridLayout(1, true));
/*
* Create a check button for paranoid proving.
* These two widgets are contained within a composite.
*/
paranoid = new Button(right, SWT.CHECK);
paranoid.setText("Paranoid checking");
paranoid.setSelection(store.getBoolean(PARANOID_KEY));
paranoid.setEnabled(!noProving.getSelection());
/*
* Create the widget for entering the number of threads.
* This widget will be a composite consisting of a Label
* and a Text.
*/
Composite threadsComposite = new Composite(right, SWT.NONE);
gd = new GridData();
threadsComposite.setLayoutData(gd);
threadsComposite.setLayout(new GridLayout(2, false));
// Label threadsLabel = new Label(threadsComposite, SWT.NONE);
// threadsLabel.setText("Number of threads : ");
// numThreadsText = new Text(threadsComposite, SWT.SINGLE);
// numThreadsText.setText(store.getString(NUM_THREADS_KEY));
/**
* Field for additional command-line arguments
*/
label = new Label(topComposite, SWT.NONE);
label.setText("Enter additional tlapm command-line arguments.");
gd = new GridData();
// spans both columns
gd.horizontalSpan = 2;
label.setLayoutData(gd);
extraOptionsText = new Text(topComposite, SWT.SINGLE);
gd = new GridData(SWT.FILL, SWT.FILL, true, true);
// spans both columns
gd.horizontalSpan = 2;
extraOptionsText.setLayoutData(gd);
extraOptionsText.setText(store.getString(EXTRA_OPTIONS_KEY));
return topComposite;
}
/**
* This method is called by eclipse when the user presses OK.
* The current state of the dialog is saved in preferences
* so that it can be restored next time, and the PM is launched
* with the selected options.
*/
protected void okPressed()
{
/*
* Save the selections in the plugin's preference store so that they can be
* restored next time the dialog is opened.
*/
IPreferenceStore store = ProverUIActivator.getDefault().getPreferenceStore();
store.setValue(EXTRA_OPTIONS_KEY, extraOptionsText.getText());
store.setValue(TOOLBOX_MODE_KEY, toolboxMode.getSelection());
store.setValue(ISATOOL_KEY, isatool.getSelection());
store.setValue(STATUS_CHECK_KEY, noProving.getSelection());
store.setValue(ISACHECK_KEY, isacheck.getSelection());
store.setValue(NOISA_KEY, noisa.getSelection());
store.setValue(PARANOID_KEY, paranoid.getSelection());
// store.setValue(NUM_THREADS_KEY, numThreadsText.getText());
store.setValue(FP_NORMAL_KEY, fpNormal.getSelection());
store.setValue(FP_FORGET_ALL_KEY, fpForgetAll.getSelection());
store.setValue(FP_FORGET_CURRENT_KEY, fpForgetCurrent.getSelection());
/*
* Launch the prover with the arguments given.
*
* The list command will accumate a list of the arguments
* to be given to the PM. First, we add the options from the
* button widgets, and then we add any options the user has entered
* in the text field at the top of the dialog. Of course, this could
* be redundant, so maybe there should be some check for that.
*/
ArrayList command = new ArrayList();
/**
* Set option for which prover to use. Note that the no --proving option
* is added by the ProverJob constructor, and the "Don't use Isabelle"
* option is indicated by the absence of a command-line option.
*/
if (isatool.getSelection())
{
// Removed by Damien. This is now the default for the PM, so we don't
// need to pass anything. Note that this means the "Do not use Isabelle"
// button is obsolete: it does the same thing as "Use Isabelle only if
// necessary".
//command.add(ITLAPMOptions.ISAPROVE);
} else if (isacheck.getSelection())
{
command.add(ITLAPMOptions.ISACHECK);
}
/*
* Set option for fingerprint use. Note that normal fingerprint
* use is specified by no fingerprint option.
*/
if (fpForgetAll.getSelection())
{
command.add(ITLAPMOptions.FORGET_ALL);
} else if (fpForgetCurrent.getSelection())
{
command.add(ITLAPMOptions.FORGET_CURRENT);
}
if (paranoid.isEnabled() && paranoid.getSelection())
{
command.add(ITLAPMOptions.PARANOID);
}
/*
* Add threads option, if there is one.
*/
ProverHelper.setThreadsOption(command);
/*
* Add solver option, if there is one.
*/
ProverHelper.setSolverOption(command);
/*
* This adds the extra options from the text field at the top
* of the dialog.
*/
/*
* Add --safefp option, if there is one.
*/
ProverHelper.setSafeFPOption(command);
/* Split the string given by the user into an array of strings.
* The string is split on every space that is not within a pair of
* single-quote characters. Unlike the shell, we do not allow
* backslash-escapes, and we do not trigger an error in case of
* unclosed quote. This means there is no way to have a single-quote
* inside an argument.
* The parsing is done with a simple 3-state automaton.
*/
String extraOptions = extraOptionsText.getText();
StringBuilder argument = new StringBuilder();
int state = 0;
for (int j = 0; j < extraOptions.length(); j++)
{
char c = extraOptions.charAt(j);
switch (state){
case 0: // "space" state: between arguments
if (c == ' '){
// skip
}else if (c == '\''){
state = 2;
}else{
argument.append (c);
state = 1;
}
break;
case 1: // "unquoted" state: inside an argument but outside quotes
if (c == ' '){
command.add(argument.toString());
argument.setLength(0);
state = 0;
}else if (c == '\''){
state = 2;
}else{
argument.append (c);
}
break;
case 2: // "quoted" state : inside quotes
if (c == '\''){
state = 1;
}else{
argument.append (c);
}
break;
}
}
if (state == 1 || state == 2){
command.add(argument.toString());
}
TLAEditor editor = EditorUtil.getActiveTLAEditor();
Assert.isNotNull(editor,
"User attempted to run general prover dialog without a tla editor active. This is a bug.");
/*
* This launches the prover.
*/
ProverJob proverJob = new ProverJob(((FileEditorInput) editor.getEditorInput()).getFile(),
((ITextSelection) editor.getSelectionProvider().getSelection()).getOffset(), noProving.getSelection(),
(String[]) command.toArray(new String[command.size()]), toolboxMode.getSelection());
proverJob.setUser(true);
proverJob.schedule();
super.okPressed();
}
}
|
package com.redhat.ceylon.eclipse.code.quickfix;
import static com.redhat.ceylon.compiler.loader.AbstractModelLoader.JDK_MODULE_VERSION;
import static com.redhat.ceylon.compiler.typechecker.model.Util.intersectionType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.unionType;
import static com.redhat.ceylon.compiler.typechecker.tree.Util.formatPath;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ADD;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.ATTRIBUTE;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.CHANGE;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.CLASS;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.CORRECTION;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.INTERFACE;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.METHOD;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findNode;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findStatement;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getIdentifyingNode;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getProposals;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getRefinedProducedReference;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getRefinementTextFor;
import static com.redhat.ceylon.eclipse.code.quickfix.AddConstraintSatisfiesProposal.addConstraintSatisfiesProposals;
import static com.redhat.ceylon.eclipse.code.quickfix.AddParameterProposal.addParameterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AddParenthesesProposal.addAddParenthesesProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AddSpreadToVariadicParameterProposal.addEllipsisToSequenceParameterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AddThrowsAnnotationProposal.addThrowsAnnotationProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.AssignToLocalProposal.addAssignToLocalProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ChangeDeclarationProposal.addChangeDeclarationProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ChangeInitialCaseOfIdentifierInDeclaration.addChangeIdentifierCaseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ChangeMultilineStringIndentationProposal.addFixMultilineStringIndentation;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertGetterToMethodProposal.addConvertGetterToMethodProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertIfElseToThenElse.addConvertToThenElseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertMethodToGetterProposal.addConvertMethodToGetterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertThenElseToIfElse.addConvertToIfElseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertToBlockProposal.addConvertToBlockProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertToGetterProposal.addConvertToGetterProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ConvertToSpecifierProposal.addConvertToSpecifierProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.CreateLocalSubtypeProposal.addCreateLocalSubtypeProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.CreateObjectProposal.addCreateObjectProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ImplementFormalAndAmbiguouslyInheritedMembersProposal.addImplementFormalAndAmbiguouslyInheritedMembersProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.InvertIfElse.addReverseIfElseProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.ShadowReferenceProposal.addShadowReferenceProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.SpecifyTypeProposal.addSpecifyTypeProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.SplitDeclarationProposal.addSplitDeclarationProposal;
import static com.redhat.ceylon.eclipse.code.quickfix.Util.getLevenshteinDistance;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.PROBLEM_MARKER_ID;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getFile;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getProjectTypeChecker;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getUnits;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageProcessor;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.reorg.RenamePackageWizard;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.ltk.core.refactoring.DocumentChange;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.text.edits.InsertEdit;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.cmr.api.ModuleQuery;
import com.redhat.ceylon.cmr.api.ModuleSearchResult;
import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Import;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Identifier;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ImportPath;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.code.editor.CeylonAnnotation;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.editor.Util;
import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider;
import com.redhat.ceylon.eclipse.code.parse.CeylonParseController;
import com.redhat.ceylon.eclipse.core.builder.MarkerCreator;
import com.redhat.ceylon.eclipse.util.FindContainerVisitor;
import com.redhat.ceylon.eclipse.util.FindDeclarationNodeVisitor;
import com.redhat.ceylon.eclipse.util.FindDeclarationVisitor;
import com.redhat.ceylon.eclipse.util.FindStatementVisitor;
/**
* Popup quick fixes for problem annotations displayed in editor
* @author gavin
*/
public class CeylonQuickFixAssistant {
public boolean canFix(Annotation annotation) {
int code;
if (annotation instanceof CeylonAnnotation) {
code = ((CeylonAnnotation) annotation).getId();
}
else if (annotation instanceof MarkerAnnotation) {
code = ((MarkerAnnotation) annotation).getMarker()
.getAttribute(MarkerCreator.ERROR_CODE_KEY, 0);
}
else {
return false;
}
return code>0;
}
public boolean canAssist(IQuickAssistInvocationContext context) {
//oops, all this is totally useless, because
//this method never gets called by IMP
/*Tree.CompilationUnit cu = (CompilationUnit) context.getModel()
.getAST(new NullMessageHandler(), new NullProgressMonitor());
return CeylonSourcePositionLocator.findNode(cu, context.getOffset(),
context.getOffset()+context.getLength()) instanceof Tree.Term;*/
return true;
}
public String[] getSupportedMarkerTypes() {
return new String[] { PROBLEM_MARKER_ID };
}
public static String getIndent(Node node, IDocument doc) {
try {
IRegion region = doc.getLineInformation(node.getEndToken().getLine()-1);
String line = doc.get(region.getOffset(), region.getLength());
char[] chars = line.toCharArray();
for (int i=0; i<chars.length; i++) {
if (chars[i]!='\t' && chars[i]!=' ') {
return line.substring(0,i);
}
}
return line;
}
catch (BadLocationException ble) {
return "";
}
}
public void addProposals(IQuickAssistInvocationContext context,
CeylonEditor editor, Collection<ICompletionProposal> proposals) {
if (editor==null) return;
RenameRefactoringProposal.add(proposals, editor);
InlineRefactoringProposal.add(proposals, editor);
ExtractValueProposal.add(proposals, editor);
ExtractFunctionProposal.add(proposals, editor);
ConvertToClassProposal.add(proposals, editor);
ConvertToNamedArgumentsProposal.add(proposals, editor);
IDocument doc = context.getSourceViewer().getDocument();
IProject project = Util.getProject(editor.getEditorInput());
IFile file = Util.getFile(editor.getEditorInput());
Tree.CompilationUnit cu = editor.getParseController().getRootNode();
if (cu!=null) {
Node node = findNode(cu, context.getOffset(),
context.getOffset() + context.getLength());
addAssignToLocalProposal(context.getSourceViewer().getDocument(),
file, cu, proposals, node);
Tree.Declaration decNode = findDeclaration(cu, node);
if (decNode!=null) {
Declaration d = decNode.getDeclarationModel();
if (d!=null) {
if ((d.isClassOrInterfaceMember()||d.isToplevel()) &&
!d.isShared()) {
addMakeSharedDecProposal(proposals, project, decNode);
}
if (d.isClassOrInterfaceMember() &&
d.isShared() &&
!d.isDefault() && !d.isFormal() &&
!(d instanceof Interface)) {
addMakeDefaultDecProposal(proposals, project, decNode);
}
}
}
if (decNode instanceof Tree.TypedDeclaration &&
!(decNode instanceof Tree.ObjectDefinition) &&
!(decNode instanceof Tree.Variable)) {
Tree.Type type = ((Tree.TypedDeclaration) decNode).getType();
if (type instanceof Tree.LocalModifier) {
addSpecifyTypeProposal(cu, type, proposals, file);
}
}
else if (node instanceof Tree.LocalModifier) {
addSpecifyTypeProposal(cu, node, proposals, file);
}
if (decNode instanceof Tree.AttributeDeclaration) {
AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) decNode;
Tree.SpecifierOrInitializerExpression se = attDecNode.getSpecifierOrInitializerExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, decNode);
}
else {
addConvertToGetterProposal(doc, proposals, file, attDecNode);
}
}
if (decNode instanceof Tree.MethodDeclaration) {
Tree.SpecifierOrInitializerExpression se = ((Tree.MethodDeclaration) decNode).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, decNode);
}
}
if (decNode instanceof Tree.AttributeSetterDefinition) {
Tree.SpecifierOrInitializerExpression se = ((Tree.AttributeSetterDefinition) decNode).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, decNode);
}
Tree.Block b = ((Tree.AttributeSetterDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.AttributeGetterDefinition) {
Tree.Block b = ((Tree.AttributeGetterDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.MethodDefinition) {
Tree.Block b = ((Tree.MethodDefinition) decNode).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (decNode instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration attDecNode = (Tree.AttributeDeclaration) decNode;
Tree.SpecifierOrInitializerExpression sie = attDecNode.getSpecifierOrInitializerExpression();
if (sie!=null) {
addSplitDeclarationProposal(doc, cu, proposals, file, attDecNode);
}
addParameterProposal(doc, cu, proposals, file, attDecNode, sie, editor);
}
if (decNode instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration methDecNode = (Tree.MethodDeclaration) decNode;
Tree.SpecifierExpression sie = methDecNode.getSpecifierExpression();
if (sie!=null) {
addSplitDeclarationProposal(doc, cu, proposals, file, methDecNode);
}
addParameterProposal(doc, cu, proposals, file, methDecNode, sie, editor);
}
if (node instanceof Tree.MethodArgument) {
Tree.SpecifierOrInitializerExpression se = ((Tree.MethodArgument) node).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, node);
}
Tree.Block b = ((Tree.MethodArgument) node).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
if (node instanceof Tree.AttributeArgument) {
Tree.SpecifierOrInitializerExpression se = ((Tree.AttributeArgument) node).getSpecifierExpression();
if (se instanceof Tree.LazySpecifierExpression) {
addConvertToBlockProposal(doc, proposals, file,
(Tree.LazySpecifierExpression) se, node);
}
Tree.Block b = ((Tree.AttributeArgument) node).getBlock();
if (b!=null) {
addConvertToSpecifierProposal(doc, proposals, file, b);
}
}
addCreateObjectProposal(doc, cu, proposals, file, node);
addCreateLocalSubtypeProposal(doc, cu, proposals, file, node);
Tree.Statement statement = findStatement(cu, node);
addConvertToIfElseProposal(doc, proposals, file, statement);
addConvertToThenElseProposal(cu, doc, proposals, file, statement);
addReverseIfElseProposal(doc, proposals, file, statement);
addConvertGetterToMethodProposal(proposals, editor, file, node);
addConvertMethodToGetterProposal(proposals, editor, file, node);
addThrowsAnnotationProposal(proposals, statement, cu, file, doc);
}
CreateSubtypeProposal.add(proposals, editor);
MoveDeclarationProposal.add(proposals, editor);
RefineFormalMembersProposal.add(proposals, editor);
}
public static Tree.Declaration findDeclaration(Tree.CompilationUnit cu, Node node) {
FindDeclarationVisitor fcv = new FindDeclarationVisitor(node);
fcv.visit(cu);
return fcv.getDeclarationNode();
}
public void addProposals(IQuickAssistInvocationContext context, ProblemLocation problem,
IFile file, Tree.CompilationUnit cu, Collection<ICompletionProposal> proposals) {
if (file==null) return;
IProject project = file.getProject();
TypeChecker tc = getProjectTypeChecker(project);
Node node = findNode(cu, problem.getOffset(),
problem.getOffset() + problem.getLength());
switch ( problem.getProblemId() ) {
case 100:
case 102:
if (tc!=null) {
addImportProposals(cu, node, proposals, file);
}
addCreateEnumProposal(cu, node, problem, proposals,
project, tc, file);
addCreateProposals(cu, node, problem, proposals,
project, tc, file);
if (tc!=null) {
addRenameProposals(cu, node, problem, proposals, file);
}
break;
case 101:
addCreateParameterProposals(cu, node, problem, proposals,
project, tc, file);
if (tc!=null) {
addRenameProposals(cu, node, problem, proposals, file);
}
break;
case 200:
addSpecifyTypeProposal(cu, node, proposals, file);
break;
case 300:
case 350:
if (context.getSourceViewer()!=null) { //TODO: figure out some other way to get the Document!
addImplementFormalAndAmbiguouslyInheritedMembersProposal(cu, node, proposals, file,
context.getSourceViewer().getDocument());
}
addMakeAbstractProposal(proposals, project, node);
break;
case 400:
addMakeSharedProposal(proposals, project, node);
break;
case 500:
addMakeDefaultProposal(proposals, project, node);
break;
case 600:
addMakeActualProposal(proposals, project, node);
break;
case 701:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "actual", project, node);
break;
case 702:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 703:
addMakeSharedDecProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "default", project, node);
break;
case 800:
case 804:
addMakeVariableProposal(proposals, project, node);
break;
case 803:
addMakeVariableProposal(proposals, project, node);
break;
case 801:
addMakeVariableDecProposal(cu, proposals, project, node);
break;
case 802:
break;
case 905:
addMakeContainerAbstractProposal(proposals, project, node);
break;
case 900:
case 1100:
addMakeContainerAbstractProposal(proposals, project, node);
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 1000:
addAddParenthesesProposal(problem, file, proposals, node);
addChangeDeclarationProposal(problem, file, proposals, node);
break;
case 1200:
case 1201:
addRemoveAnnotationDecProposal(proposals, "shared", project, node);
break;
case 1300:
case 1301:
addRemoveAnnotationDecProposal(proposals, "actual", project, node);
break;
case 1302:
case 1312:
case 1307:
addRemoveAnnotationDecProposal(proposals, "formal", project, node);
break;
case 1303:
case 1313:
addRemoveAnnotationDecProposal(proposals, "default", project, node);
break;
case 1400:
case 1401:
addMakeFormalProposal(proposals, project, node);
break;
case 1500:
addRemoveAnnotationDecProposal(proposals, "variable", project, node);
break;
case 1600:
addRemoveAnnotationDecProposal(proposals, "abstract", project, node);
break;
case 2000:
addCreateParameterProposals(cu, node, problem, proposals,
project, tc, file);
break;
case 2100:
case 2102:
addChangeTypeProposals(cu, node, problem, proposals, project);
addConstraintSatisfiesProposals(cu, node, proposals, project);
break;
case 2101:
addEllipsisToSequenceParameterProposal(cu, node, proposals, file);
break;
case 3000:
if (context.getSourceViewer()!=null) {
addAssignToLocalProposal(context.getSourceViewer().getDocument(),
file, cu, proposals, node);
}
break;
case 3100:
if (context.getSourceViewer()!=null) {
addShadowReferenceProposal(context.getSourceViewer().getDocument(),
file, cu, proposals, node);
}
break;
case 5001:
case 5002:
addChangeIdentifierCaseProposal(node, proposals, file);
break;
case 6000:
addFixMultilineStringIndentation(proposals, file, cu, (Tree.StringLiteral)node);
break;
case 7000:
addModuleImportProposals(cu, proposals, project, tc, node);
break;
case 8000:
addRenameDescriptorProposal(cu, context, problem, proposals);
addMoveDirProposal(file, cu, project, proposals,
context.getSourceViewer().getTextWidget().getShell());
break;
}
}
protected void addMoveDirProposal(final IFile file, final Tree.CompilationUnit cu,
final IProject project, Collection<ICompletionProposal> proposals,
final Shell shell) {
Tree.ImportPath importPath;
if (cu.getPackageDescriptor()!=null) {
importPath = cu.getPackageDescriptor().getImportPath();
}
else if (cu.getModuleDescriptor()!=null) {
importPath = cu.getModuleDescriptor().getImportPath();
}
else {
return;
}
final String pn = formatPath(importPath.getIdentifiers());
final String cpn = cu.getUnit().getPackage().getNameAsString();
final IPath sourceDir = file.getProjectRelativePath()
.removeLastSegments(file.getProjectRelativePath().segmentCount()-1);
// final IPath relPath = sourceDir.append(pn.replace('.', '/'));
// final IPath newPath = project.getFullPath().append(relPath);
// if (!project.exists(newPath)) {
proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return CORRECTION; //TODO!!!!!
}
@Override
public String getDisplayString() {
return "Rename and move to '" + pn + "'";
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
IPackageFragment pfr = (IPackageFragment) JavaCore.create(project.getFolder(sourceDir.append(cpn.replace('.', '/'))));
RenamePackageProcessor processor = new RenamePackageProcessor(pfr);
processor.setNewElementName(pn);
new RefactoringStarter().activate(new RenamePackageWizard(new RenameRefactoring(processor)),
shell, "Rename Package", 4);
}
});
}
private void addRenameDescriptorProposal(Tree.CompilationUnit cu,
IQuickAssistInvocationContext context, ProblemLocation problem,
Collection<ICompletionProposal> proposals) {
String pn = cu.getUnit().getPackage().getNameAsString();
//TODO: DocumentChange doesn't work for Problems View
DocumentChange change = new DocumentChange("Rename", context.getSourceViewer().getDocument());
change.setEdit(new ReplaceEdit(problem.getOffset(), problem.getLength(), pn));
proposals.add(new ChangeCorrectionProposal("Rename to '" + pn + "'", change, 10, CHANGE));
}
private void addModuleImportProposals(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals, IProject project,
TypeChecker tc, Node node) {
List<Identifier> ids = ((ImportPath) node).getIdentifiers();
String pkg = formatPath(ids);
if (JDKUtils.isJDKAnyPackage(pkg)) {
for (String mod: JDKUtils.getJDKModuleNames()) {
if (JDKUtils.isJDKPackage(mod, pkg)) {
proposals.add(new AddModuleImportProposal(project, cu.getUnit(), mod,
JDK_MODULE_VERSION));
return;
}
}
}
for (int i=ids.size(); i>0; i
String pn = formatPath(ids.subList(0, i));
ModuleQuery q = new ModuleQuery(pn, ModuleQuery.Type.JVM); //TODO: Type.JS if JS compilation enabled!
q.setCount(2l);
ModuleSearchResult msr = tc.getContext().getRepositoryManager().searchModules(q);
ModuleDetails md = msr.getResult(pn);
if (md!=null) {
proposals.add(new AddModuleImportProposal(project, cu.getUnit(), md));
}
if (!msr.getResults().isEmpty()) break;
}
}
private void addMakeActualProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
boolean shared = decNode.getDeclarationModel().isShared();
addAddAnnotationProposal(node, shared ? "actual" : "shared actual",
shared ? "Make Actual" : "Make Shared Actual",
decNode.getDeclarationModel(), proposals, project);
}
private void addMakeDefaultProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
Declaration d = decNode.getDeclarationModel();
if (d.isClassOrInterfaceMember()) {
List<Declaration> rds = ((ClassOrInterface)d.getContainer()).getInheritedMembers(d.getName());
Declaration rd=null;
if (rds.isEmpty()) {
rd=d; //TODO: is this really correct? What case does it handle?
}
else {
for (Declaration r: rds) {
if (!r.isDefault()) {
//just take the first one :-/
//TODO: this is very wrong! Instead, make them all default!
rd = r;
break;
}
}
}
if (rd!=null) {
addAddAnnotationProposal(node, "default", "Make Default", rd,
proposals, project);
}
}
}
private void addMakeDefaultDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
Declaration d = decNode.getDeclarationModel();
addAddAnnotationProposal(node, "default", "Make Default", d,
proposals, project);
}
private void addMakeFormalProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
boolean shared = decNode.getDeclarationModel().isShared();
addAddAnnotationProposal(node, shared ? "formal" : "shared formal",
shared ? "Make Formal" : "Make Shared Formal",
decNode.getDeclarationModel(), proposals, project);
}
private void addMakeAbstractProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = (Declaration) ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node, "abstract", "Make Abstract", dec,
proposals, project);
}
private void addMakeContainerAbstractProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
Scope container = ((Tree.Declaration) node).getDeclarationModel().getContainer();
if (container instanceof Declaration) {
dec = (Declaration) container;
}
else {
return;
}
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node, "abstract", "Make Abstract", dec,
proposals, project);
}
private void addMakeVariableProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Term term;
if (node instanceof Tree.AssignmentOp) {
term = ((Tree.AssignOp) node).getLeftTerm();
}
else if (node instanceof Tree.UnaryOperatorExpression) {
term = ((Tree.PrefixOperatorExpression) node).getTerm();
}
else if (node instanceof Tree.MemberOrTypeExpression) {
term = (Tree.MemberOrTypeExpression) node;
}
else if (node instanceof Tree.SpecifierStatement) {
term = ((Tree.SpecifierStatement) node).getBaseMemberExpression();
}
else {
return;
}
if (term instanceof Tree.MemberOrTypeExpression) {
Declaration dec = ((Tree.MemberOrTypeExpression) term).getDeclaration();
addAddAnnotationProposal(node, "variable", "Make Variable",
dec, proposals, project);
}
}
private void addMakeVariableDecProposal(Tree.CompilationUnit cu,
Collection<ICompletionProposal> proposals, IProject project, Node node) {
final Tree.SpecifierOrInitializerExpression sie = (Tree.SpecifierOrInitializerExpression) node;
class GetInitializedVisitor extends Visitor {
Value dec;
@Override
public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
if (that.getSpecifierOrInitializerExpression()==sie) {
dec = that.getDeclarationModel();
}
}
}
GetInitializedVisitor v = new GetInitializedVisitor();
v.visit(cu);
addAddAnnotationProposal(node, "variable", "Make Variable", v.dec,
proposals, project);
}
private void addMakeSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec = null;
if (node instanceof Tree.StaticMemberOrTypeExpression) {
Tree.StaticMemberOrTypeExpression qmte = (Tree.StaticMemberOrTypeExpression) node;
dec = qmte.getDeclaration();
}
else if (node instanceof Tree.SimpleType) {
Tree.SimpleType qmte = (Tree.SimpleType) node;
dec = qmte.getDeclarationModel();
}
else if (node instanceof Tree.ImportMemberOrType) {
Tree.ImportMemberOrType imt = (Tree.ImportMemberOrType) node;
dec = imt.getDeclarationModel();
}
if (dec!=null) {
addAddAnnotationProposal(node, "shared", "Make Shared", dec,
proposals, project);
}
}
private void addMakeSharedDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
addAddAnnotationProposal(node, "shared", "Make Shared",
decNode.getDeclarationModel(), proposals, project);
}
private void addRemoveAnnotationDecProposal(Collection<ICompletionProposal> proposals,
String annotation, IProject project, Node node) {
Tree.Declaration decNode = (Tree.Declaration) node;
addRemoveAnnotationProposal(node, annotation, "Make Non" + annotation,
decNode.getDeclarationModel(), proposals, project);
}
/*public void addRefactoringProposals(IQuickFixInvocationContext context,
Collection<ICompletionProposal> proposals, Node node) {
try {
if (node instanceof Tree.Term) {
ExtractFunctionRefactoring efr = new ExtractFunctionRefactoring(context);
proposals.add( new ChangeCorrectionProposal("Extract function '" + efr.getNewName() + "'",
efr.createChange(new NullProgressMonitor()), 20, null));
ExtractValueRefactoring evr = new ExtractValueRefactoring(context);
proposals.add( new ChangeCorrectionProposal("Extract value '" + evr.getNewName() + "'",
evr.createChange(new NullProgressMonitor()), 20, null));
}
}
catch (CoreException ce) {}
}*/
private void addCreateEnumProposal(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
Node idn = getIdentifyingNode(node);
if (idn==null) return;
String brokenName = idn.getText();
if (brokenName.isEmpty()) return;
Tree.Declaration dec = findDeclaration(cu, node);
if (dec instanceof Tree.ClassDefinition) {
Tree.ClassDefinition cd = (Tree.ClassDefinition) dec;
if (cd.getCaseTypes()!=null) {
if (cd.getCaseTypes().getTypes().contains(node)) {
addCreateEnumProposal(proposals, project,
"class " + brokenName + parameters(cd.getTypeParameterList()) +
parameters(cd.getParameterList()) +
" extends " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) +
arguments(cd.getParameterList()) + " {}",
"class '"+ brokenName + parameters(cd.getTypeParameterList()) +
parameters(cd.getParameterList()) + "'",
CeylonLabelProvider.CLASS, cu, cd);
}
if (cd.getCaseTypes().getBaseMemberExpressions().contains(node)) {
addCreateEnumProposal(proposals, project,
"object " + brokenName +
" extends " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) +
arguments(cd.getParameterList()) + " {}",
"object '"+ brokenName + "'",
ATTRIBUTE, cu, cd);
}
}
}
if (dec instanceof Tree.InterfaceDefinition) {
Tree.InterfaceDefinition cd = (Tree.InterfaceDefinition) dec;
if (cd.getCaseTypes()!=null) {
if (cd.getCaseTypes().getTypes().contains(node)) {
addCreateEnumProposal(proposals, project,
"interface " + brokenName + parameters(cd.getTypeParameterList()) +
" satisfies " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) + " {}",
"interface '"+ brokenName + parameters(cd.getTypeParameterList()) + "'",
INTERFACE, cu, cd);
}
if (cd.getCaseTypes().getBaseMemberExpressions().contains(node)) {
addCreateEnumProposal(proposals, project,
"object " + brokenName +
" satisfies " + cd.getDeclarationModel().getName() +
parameters(cd.getTypeParameterList()) + " {}",
"object '"+ brokenName + "'",
ATTRIBUTE, cu, cd);
}
}
}
}
private static String parameters(Tree.ParameterList pl) {
StringBuilder result = new StringBuilder();
if (pl==null ||
pl.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
int len = pl.getParameters().size(), i=0;
for (Tree.Parameter p: pl.getParameters()) {
if (p!=null) {
if (p instanceof Tree.ParameterDeclaration) {
Tree.TypedDeclaration td = ((Tree.ParameterDeclaration) p).getTypedDeclaration();
result.append(td.getType().getTypeModel().getProducedTypeName())
.append(" ")
.append(td.getIdentifier().getText());
}
else if (p instanceof Tree.InitializerParameter) {
result.append(p.getParameterModel().getType().getProducedTypeName())
.append(" ")
.append(((Tree.InitializerParameter) p).getIdentifier().getText());
}
//TODO: easy to add back in:
/*if (p instanceof Tree.FunctionalParameterDeclaration) {
Tree.FunctionalParameterDeclaration fp = (Tree.FunctionalParameterDeclaration) p;
for (Tree.ParameterList ipl: fp.getParameterLists()) {
parameters(ipl, label);
}
}*/
}
if (++i<len) result.append(", ");
}
result.append(")");
}
return result.toString();
}
private static String parameters(Tree.TypeParameterList tpl) {
StringBuilder result = new StringBuilder();
if (tpl!=null &&
!tpl.getTypeParameterDeclarations().isEmpty()) {
result.append("<");
int len = tpl.getTypeParameterDeclarations().size(), i=0;
for (Tree.TypeParameterDeclaration p: tpl.getTypeParameterDeclarations()) {
result.append(p.getIdentifier().getText());
if (++i<len) result.append(", ");
}
result.append(">");
}
return result.toString();
}
private static String arguments(Tree.ParameterList pl) {
StringBuilder result = new StringBuilder();
if (pl==null ||
pl.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
int len = pl.getParameters().size(), i=0;
for (Tree.Parameter p: pl.getParameters()) {
if (p!=null) {
Tree.Identifier id;
if (p instanceof Tree.InitializerParameter) {
id = ((Tree.InitializerParameter) p).getIdentifier();
}
else if (p instanceof Tree.ParameterDeclaration) {
id = ((Tree.ParameterDeclaration) p).getTypedDeclaration().getIdentifier();
}
else {
continue;
}
result.append(id.getText());
//TODO: easy to add back in:
/*if (p instanceof Tree.FunctionalParameterDeclaration) {
Tree.FunctionalParameterDeclaration fp = (Tree.FunctionalParameterDeclaration) p;
for (Tree.ParameterList ipl: fp.getParameterLists()) {
parameters(ipl, label);
}
}*/
}
if (++i<len) result.append(", ");
}
result.append(")");
}
return result.toString();
}
private void addCreateProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
if (node instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression smte = (Tree.MemberOrTypeExpression) node;
String brokenName = getIdentifyingNode(node).getText();
if (brokenName.isEmpty()) return;
boolean isUpperCase = Character.isUpperCase(brokenName.charAt(0));
String def;
String desc;
Image image;
FindArgumentsVisitor fav = new FindArgumentsVisitor(smte);
cu.visit(fav);
ProducedType et = fav.expectedType;
List<ProducedType> paramTypes = null;
final boolean isVoid = et==null;
ProducedType returnType = isVoid ? null : node.getUnit().denotableType(et);
String stn = isVoid ? null : returnType.getProducedTypeName();
if (fav.positionalArgs!=null || fav.namedArgs!=null) {
StringBuilder params = new StringBuilder();
params.append("(");
if (fav.positionalArgs!=null) {
paramTypes = appendPositionalArgs(fav, params);
}
if (fav.namedArgs!=null) {
paramTypes = appendNamedArgs(fav, params);
}
if (params.length()>1) {
params.setLength(params.length()-2);
}
params.append(")");
List<TypeParameter> typeParams = new ArrayList<TypeParameter>();
StringBuilder typeParamDef = new StringBuilder("<");
StringBuilder typeParamConstDef = new StringBuilder();
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, returnType);
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, paramTypes);
if (typeParamDef.length() > 1) {
typeParamDef.setLength(typeParamDef.length() - 1);
typeParamDef.append(">");
} else {
typeParamDef.setLength(0);
}
if (isUpperCase) {
String supertype = "";
if (!isVoid) {
if (!stn.equals("unknown")) {
if (et.getDeclaration() instanceof Class) {
supertype = " extends " + stn + "()"; //TODO: arguments!
}
else {
supertype = " satisfies " + stn;
}
}
}
def = "class " + brokenName + typeParamDef + params + supertype + typeParamConstDef + " {\n";
if (!isVoid) {
for (DeclarationWithProximity dwp: et.getDeclaration()
.getMatchingMemberDeclarations(null, "", 0).values()) {
Declaration d = dwp.getDeclaration();
if (d.isFormal() /*&& td.isInheritedFromSupertype(d)*/) {
ProducedReference pr = getRefinedProducedReference(et, d);
def+= "$indent " + getRefinementTextFor(d, pr, false, "") + "\n";
}
}
}
def+="$indent}";
desc = "class '" + brokenName + params + supertype + "'";
image = CeylonLabelProvider.CLASS;
}
else {
String type = isVoid ? "void" :
stn.equals("unknown") ? "function" : stn;
String impl = isVoid ? " {}" : " { return nothing; }";
def = type + " " + brokenName + typeParamDef + params + typeParamConstDef + impl;
desc = "function '" + brokenName + params + "'";
image = METHOD;
}
}
else if (!isUpperCase) {
String type = isVoid ? "Anything" :
stn.equals("unknown") ? "value" : stn;
def = type + " " + brokenName + " = " + defaultValue(node.getUnit(), et) + ";";
desc = "value '" + brokenName + "'";
image = ATTRIBUTE;
}
else {
return;
}
if (smte instanceof Tree.QualifiedMemberOrTypeExpression) {
addCreateMemberProposals(proposals, project, "shared " + def, desc, image,
(Tree.QualifiedMemberOrTypeExpression) smte, returnType, paramTypes);
}
else {
addCreateLocalProposals(proposals, project, def, desc, image, cu, smte,
returnType, paramTypes);
ClassOrInterface container = findClassContainer(cu, smte);
if (container!=null &&
container!=smte.getScope()) { //if the statement appears directly in an initializer, propose a local, not a member
do {
addCreateMemberProposals(proposals, project, def, desc, image, container,
returnType, paramTypes);
if(container.getContainer() instanceof Declaration)
container = findClassContainer((Declaration) container.getContainer());
else
break;
}
while(container != null);
}
addCreateToplevelProposals(proposals, project, def, desc, image, cu, smte,
returnType, paramTypes);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals,
def.replace("$indent", ""), desc, image, file, brokenName,
returnType, paramTypes);
addCreateParameterProposal(proposals, project, cu, node, brokenName, def, returnType);
}
}
else if (node instanceof Tree.BaseType) {
Tree.BaseType bt = (Tree.BaseType) node;
String brokenName = bt.getIdentifier().getText();
String idef = "interface " + brokenName + " {}";
String idesc = "interface '" + brokenName + "'";
String cdef = "class " + brokenName + "() {}";
String cdesc = "class '" + brokenName + "()'";
//addCreateLocalProposals(proposals, project, idef, idesc, INTERFACE, cu, bt);
addCreateLocalProposals(proposals, project, cdef, cdesc, CLASS, cu, bt, null, null);
addCreateToplevelProposals(proposals, project, idef, idesc, INTERFACE, cu, bt, null, null);
addCreateToplevelProposals(proposals, project, cdef, cdesc, CLASS, cu, bt, null, null);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals, idef, idesc,
INTERFACE, file, brokenName, null, null);
CreateInNewUnitProposal.addCreateToplevelProposal(proposals, cdef, cdesc,
CLASS, file, brokenName, null, null);
}
}
private void appendTypeParams(List<TypeParameter> typeParams, StringBuilder typeParamDef, StringBuilder typeParamConstDef, List<ProducedType> pts) {
if (pts != null) {
for (ProducedType pt : pts) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, pt);
}
}
}
private void appendTypeParams(List<TypeParameter> typeParams, StringBuilder typeParamDef, StringBuilder typeParamConstDef, ProducedType pt) {
if (pt != null) {
if (pt.getDeclaration() instanceof UnionType) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, ((UnionType) pt.getDeclaration()).getCaseTypes());
}
else if (pt.getDeclaration() instanceof IntersectionType) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, ((IntersectionType) pt.getDeclaration()).getSatisfiedTypes());
}
else if (pt.getDeclaration() instanceof TypeParameter) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, (TypeParameter) pt.getDeclaration());
}
}
}
private void appendTypeParams(List<TypeParameter> typeParams, StringBuilder typeParamDef, StringBuilder typeParamConstDef, TypeParameter typeParam) {
if (typeParams.contains(typeParam)) {
return;
} else {
typeParams.add(typeParam);
}
if (typeParam.isContravariant()) {
typeParamDef.append("in ");
}
if (typeParam.isCovariant()) {
typeParamDef.append("out ");
}
typeParamDef.append(typeParam.getName());
if (typeParam.isDefaulted() && typeParam.getDefaultTypeArgument() != null) {
typeParamDef.append("=");
typeParamDef.append(typeParam.getDefaultTypeArgument().getProducedTypeName());
}
typeParamDef.append(",");
if (typeParam.isConstrained()) {
typeParamConstDef.append(" given ");
typeParamConstDef.append(typeParam.getName());
List<ProducedType> satisfiedTypes = typeParam.getSatisfiedTypes();
if (satisfiedTypes != null && !satisfiedTypes.isEmpty()) {
typeParamConstDef.append(" satisfies ");
boolean firstSatisfiedType = true;
for (ProducedType satisfiedType : satisfiedTypes) {
if (firstSatisfiedType) {
firstSatisfiedType = false;
} else {
typeParamConstDef.append("&");
}
typeParamConstDef.append(satisfiedType.getProducedTypeName());
}
}
List<ProducedType> caseTypes = typeParam.getCaseTypes();
if (caseTypes != null && !caseTypes.isEmpty()) {
typeParamConstDef.append(" of ");
boolean firstCaseType = true;
for (ProducedType caseType : caseTypes) {
if (firstCaseType) {
firstCaseType = false;
} else {
typeParamConstDef.append("|");
}
typeParamConstDef.append(caseType.getProducedTypeName());
}
}
if (typeParam.getParameterLists() != null) {
for (ParameterList paramList : typeParam.getParameterLists()) {
if (paramList != null && paramList.getParameters() != null) {
typeParamConstDef.append("(");
boolean firstParam = true;
for (Parameter param : paramList.getParameters()) {
if (firstParam) {
firstParam = false;
} else {
typeParamConstDef.append(",");
}
typeParamConstDef.append(param.getType().getProducedTypeName());
typeParamConstDef.append(" ");
typeParamConstDef.append(param.getName());
}
typeParamConstDef.append(")");
}
}
}
}
}
private ClassOrInterface findClassContainer(Tree.CompilationUnit cu, Node node){
FindContainerVisitor fcv = new FindContainerVisitor(node);
fcv.visit(cu);
Tree.Declaration declaration = fcv.getDeclaration();
if(declaration == null || declaration == node)
return null;
if(declaration instanceof Tree.ClassOrInterface)
return (ClassOrInterface) declaration.getDeclarationModel();
if(declaration instanceof Tree.MethodDefinition)
return findClassContainer(declaration.getDeclarationModel());
if(declaration instanceof Tree.ObjectDefinition)
return findClassContainer(declaration.getDeclarationModel());
return null;
}
private ClassOrInterface findClassContainer(Declaration declarationModel) {
do {
if(declarationModel == null)
return null;
if(declarationModel instanceof ClassOrInterface)
return (ClassOrInterface) declarationModel;
if(declarationModel.getContainer() instanceof Declaration)
declarationModel = (Declaration)declarationModel.getContainer();
else
return null;
}
while(true);
}
private void addCreateMemberProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.QualifiedMemberOrTypeExpression qmte, ProducedType returnType,
List<ProducedType> paramTypes) {
Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) qmte).getPrimary();
if (p.getTypeModel()!=null) {
Declaration typeDec = p.getTypeModel().getDeclaration();
addCreateMemberProposals(proposals, project, def, desc, image, typeDec,
returnType, paramTypes);
}
}
private void addCreateMemberProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image, Declaration typeDec,
ProducedType returnType, List<ProducedType> paramTypes) {
if (typeDec!=null && typeDec instanceof ClassOrInterface) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
//TODO: "object" declarations?
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
Tree.Body body = getBody(decNode);
if (body!=null) {
CreateProposal.addCreateMemberProposal(proposals, def, desc,
image, typeDec, unit, decNode, body, returnType,
paramTypes);
break;
}
}
}
}
}
private void addChangeTypeProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project) {
if (node instanceof Tree.SimpleType) {
TypeDeclaration decl = ((Tree.SimpleType)node).getDeclarationModel();
if( decl instanceof TypeParameter ) {
FindStatementVisitor fsv = new FindStatementVisitor(node, false);
fsv.visit(cu);
if( fsv.getStatement() instanceof Tree.AttributeDeclaration ) {
Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) fsv.getStatement();
Tree.SimpleType st = (Tree.SimpleType) ad.getType();
TypeParameter stTypeParam = null;
if( st.getTypeArgumentList() != null ) {
List<Tree.Type> stTypeArguments = st.getTypeArgumentList().getTypes();
for (int i = 0; i < stTypeArguments.size(); i++) {
Tree.SimpleType stTypeArgument = (Tree.SimpleType)stTypeArguments.get(i);
if (decl.getName().equals(
stTypeArgument.getDeclarationModel().getName())) {
TypeDeclaration stDecl = st.getDeclarationModel();
if( stDecl != null ) {
if( stDecl.getTypeParameters() != null && stDecl.getTypeParameters().size() > i ) {
stTypeParam = stDecl.getTypeParameters().get(i);
break;
}
}
}
}
}
if (stTypeParam != null && !stTypeParam.getSatisfiedTypes().isEmpty()) {
IntersectionType it = new IntersectionType(cu.getUnit());
it.setSatisfiedTypes(stTypeParam.getSatisfiedTypes());
addChangeTypeProposals(proposals, problem, project, node, it.canonicalize().getType(), decl, true);
}
}
}
}
if (node instanceof Tree.SpecifierExpression) {
Tree.Expression e = ((Tree.SpecifierExpression) node).getExpression();
if (e!=null) {
node = e.getTerm();
}
}
if (node instanceof Tree.Expression) {
node = ((Tree.Expression) node).getTerm();
}
if (node instanceof Tree.Term) {
ProducedType t = ((Tree.Term) node).getTypeModel();
if (t==null) return;
ProducedType type = node.getUnit().denotableType(t);
FindInvocationVisitor fav = new FindInvocationVisitor(node);
fav.visit(cu);
TypedDeclaration td = fav.parameter;
if (td!=null) {
if (node instanceof Tree.BaseMemberExpression){
addChangeTypeProposals(proposals, problem, project, node, td.getType(),
(TypedDeclaration) ((Tree.BaseMemberExpression) node).getDeclaration(), true);
}
if (node instanceof Tree.QualifiedMemberExpression){
addChangeTypeProposals(proposals, problem, project, node, td.getType(),
(TypedDeclaration) ((Tree.QualifiedMemberExpression) node).getDeclaration(), true);
}
addChangeTypeProposals(proposals, problem, project, node, type, td, false);
}
}
}
private void addChangeTypeProposals(Collection<ICompletionProposal> proposals,
ProblemLocation problem, IProject project, Node node, ProducedType type,
Declaration dec, boolean intersect) {
if (dec!=null) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
ProducedType t = null;
Node typeNode = null;
if( dec instanceof TypeParameter) {
t = ((TypeParameter) dec).getType();
typeNode = node;
}
if( dec instanceof TypedDeclaration ) {
TypedDeclaration typedDec = (TypedDeclaration)dec;
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typedDec);
getRootNode(unit).visit(fdv);
Tree.TypedDeclaration decNode = (Tree.TypedDeclaration) fdv.getDeclarationNode();
if (decNode!=null) {
typeNode = decNode.getType();
if (typeNode!=null) {
t=((Tree.Type)typeNode).getTypeModel();
}
}
}
if (t != null && typeNode != null) {
ProducedType newType = intersect ?
intersectionType(t, type, unit.getUnit()) : unionType(t, type, unit.getUnit());
ChangeTypeProposal.addChangeTypeProposal(typeNode, problem,
proposals, dec, newType, getFile(unit), unit.getCompilationUnit());
}
}
}
}
}
private void addCreateParameterProposal(Collection<ICompletionProposal> proposals, IProject project, Tree.CompilationUnit cu, Node node,
String brokenName, String def, ProducedType returnType) {
FindContainerVisitor fcv = new FindContainerVisitor(node);
fcv.visit(cu);
Tree.Declaration decl = fcv.getDeclaration();
if (decl == null || decl.getDeclarationModel() == null || decl.getDeclarationModel().isActual()) {
return;
}
Tree.ParameterList paramList = getParameters(decl);
if (paramList != null) {
String paramDef = (paramList.getParameters().isEmpty() ? "" : ", ") + def.substring(0, def.length() - 1);
String paramDesc = "parameter '" + brokenName + "'";
for (PhasedUnit unit : getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateParameterProposal(proposals, paramDef, paramDesc, ADD, decl.getDeclarationModel(), unit, decl, paramList, returnType);
break;
}
}
}
}
private void addCreateParameterProposals(Tree.CompilationUnit cu, Node node,
ProblemLocation problem, Collection<ICompletionProposal> proposals,
IProject project, TypeChecker tc, IFile file) {
FindInvocationVisitor fav = new FindInvocationVisitor(node);
fav.visit(cu);
if (fav.result==null) return;
Tree.Primary prim = fav.result.getPrimary();
if (prim instanceof Tree.MemberOrTypeExpression) {
ProducedReference pr = ((Tree.MemberOrTypeExpression) prim).getTarget();
if (pr!=null) {
Declaration d = pr.getDeclaration();
ProducedType t=null;
String n=null;
if (node instanceof Tree.Term) {
t = ((Tree.Term) node).getTypeModel();
n = t.getDeclaration().getName();
if (n!=null) {
n = Character.toLowerCase(n.charAt(0)) + n.substring(1)
.replace("?", "").replace("[]", "");
if ("string".equals(n)) {
n = "text";
}
}
}
else if (node instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument sa = (Tree.SpecifiedArgument) node;
Tree.SpecifierExpression se = sa.getSpecifierExpression();
if (se!=null && se.getExpression()!=null) {
t = se.getExpression().getTypeModel();
}
n = sa.getIdentifier().getText();
}
else if (node instanceof Tree.TypedArgument) {
Tree.TypedArgument ta = (Tree.TypedArgument) node;
t = ta.getType().getTypeModel();
n = ta.getIdentifier().getText();
}
if (t!=null && n!=null) {
t = node.getUnit().denotableType(t);
String dv = defaultValue(prim.getUnit(), t);
String tn = t.getProducedTypeName();
String def = tn + " " + n + " = " + dv;
String desc = "parameter '" + n +"'";
addCreateParameterProposals(proposals, project, def, desc, d, t);
String pdef = n + " = " + dv;
String adef = tn + " " + n + ";";
String padesc = "attribute '" + n +"'";
addCreateParameterAndAttributeProposals(proposals, project,
pdef, adef, padesc, d, t);
}
}
}
}
private static String defaultValue(Unit unit, ProducedType t) {
if (t==null) {
return "nothing";
}
String tn = t.getProducedTypeQualifiedName();
if (tn.equals("ceylon.language::Boolean")) {
return "false";
}
else if (tn.equals("ceylon.language::Integer")) {
return "0";
}
else if (tn.equals("ceylon.language::Float")) {
return "0.0";
}
else if (unit.isOptionalType(t)) {
return "null";
}
else if (tn.equals("ceylon.language::String")) {
return "\"\"";
}
else {
return "nothing";
}
}
private void addCreateParameterProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Declaration typeDec, ProducedType t) {
if (typeDec!=null && typeDec instanceof Functional) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
Tree.ParameterList paramList = getParameters(decNode);
if (paramList!=null) {
if (!paramList.getParameters().isEmpty()) {
def = ", " + def;
}
CreateProposal.addCreateParameterProposal(proposals, def, desc,
ADD, typeDec, unit, decNode, paramList, t);
break;
}
}
}
}
}
private void addCreateParameterAndAttributeProposals(Collection<ICompletionProposal> proposals,
IProject project, String pdef, String adef, String desc, Declaration typeDec, ProducedType t) {
if (typeDec!=null && typeDec instanceof ClassOrInterface) {
for (PhasedUnit unit: getUnits(project)) {
if (typeDec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(typeDec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
Tree.ParameterList paramList = getParameters(decNode);
Tree.Body body = getBody(decNode);
if (body!=null && paramList!=null) {
if (!paramList.getParameters().isEmpty()) {
pdef = ", " + pdef;
}
CreateProposal.addCreateParameterAndAttributeProposal(proposals, pdef,
adef, desc, ADD, typeDec, unit, decNode,
paramList, body, t);
}
}
}
}
}
private Tree.CompilationUnit getRootNode(PhasedUnit unit) {
IEditorPart ce = Util.getCurrentEditor();
if (ce instanceof CeylonEditor) {
CeylonParseController cpc = ((CeylonEditor) ce).getParseController();
if (cpc!=null) {
Tree.CompilationUnit rn = cpc.getRootNode();
if (rn!=null) {
Unit u = rn.getUnit();
if (u.equals(unit.getUnit())) {
return rn;
}
}
}
}
return unit.getCompilationUnit();
}
private static Tree.Body getBody(Tree.Declaration decNode) {
if (decNode instanceof Tree.ClassDefinition) {
return ((Tree.ClassDefinition) decNode).getClassBody();
}
else if (decNode instanceof Tree.InterfaceDefinition){
return ((Tree.InterfaceDefinition) decNode).getInterfaceBody();
}
else if (decNode instanceof Tree.ObjectDefinition){
return ((Tree.ObjectDefinition) decNode).getClassBody();
}
return null;
}
private static Tree.ParameterList getParameters(Tree.Declaration decNode) {
if (decNode instanceof Tree.AnyClass) {
return ((Tree.AnyClass) decNode).getParameterList();
}
else if (decNode instanceof Tree.AnyMethod){
List<Tree.ParameterList> pls = ((Tree.AnyMethod) decNode).getParameterLists();
return pls.isEmpty() ? null : pls.get(0);
}
return null;
}
private void addCreateEnumProposal(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.CompilationUnit cu, Tree.TypeDeclaration cd) {
for (PhasedUnit unit: getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateEnumProposal(proposals, def, desc, image, unit, cd);
break;
}
}
}
private void addCreateLocalProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.CompilationUnit cu, Node node, ProducedType returnType,
List<ProducedType> paramTypes) {
FindStatementVisitor fsv = new FindStatementVisitor(node, false);
cu.visit(fsv);
//if (!fsv.isToplevel()) {
Tree.Statement statement = fsv.getStatement();
for (PhasedUnit unit: getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateProposal(proposals, def, true, desc, image,
unit, statement, returnType, paramTypes);
break;
}
}
}
private void addCreateToplevelProposals(Collection<ICompletionProposal> proposals,
IProject project, String def, String desc, Image image,
Tree.CompilationUnit cu, Node node, ProducedType returnType,
List<ProducedType> paramTypes) {
FindStatementVisitor fsv = new FindStatementVisitor(node, true);
cu.visit(fsv);
Tree.Statement statement = fsv.getStatement();
for (PhasedUnit unit: getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
CreateProposal.addCreateProposal(proposals, def+"\n", false, desc, image,
unit, statement, returnType, paramTypes);
break;
}
}
}
private List<ProducedType> appendNamedArgs(FindArgumentsVisitor fav, StringBuilder params) {
List<ProducedType> types = new ArrayList<ProducedType>();
for (Tree.NamedArgument a: fav.namedArgs.getNamedArguments()) {
if (a instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument na = (Tree.SpecifiedArgument) a;
ProducedType t = a.getUnit()
.denotableType(na.getSpecifierExpression()
.getExpression().getTypeModel());
params.append( t
.getProducedTypeName() )
.append(" ")
.append(na.getIdentifier().getText());
params.append(", ");
types.add(t);
}
}
return types;
}
private List<ProducedType> appendPositionalArgs(FindArgumentsVisitor fav, StringBuilder params) {
List<ProducedType> types = new ArrayList<ProducedType>();
for (Tree.PositionalArgument pa: fav.positionalArgs.getPositionalArguments()) {
if (pa instanceof Tree.ListedArgument) {
Tree.Expression e = ((Tree.ListedArgument) pa).getExpression();
if (e.getTypeModel()!=null) {
ProducedType t = pa.getUnit()
.denotableType(e.getTypeModel());
params.append( t.getProducedTypeName() )
.append(" ");
if ( e.getTerm() instanceof Tree.StaticMemberOrTypeExpression ) {
params.append( ((Tree.StaticMemberOrTypeExpression) e.getTerm())
.getIdentifier().getText() );
}
else {
int loc = params.length();
params.append( e.getTypeModel().getDeclaration().getName() );
params.setCharAt(loc, Character.toLowerCase(params.charAt(loc)));
}
params.append(", ");
types.add(t);
}
}
}
return types;
}
private void addRenameProposals(Tree.CompilationUnit cu, Node node, ProblemLocation problem,
Collection<ICompletionProposal> proposals, IFile file) {
String brokenName = getIdentifyingNode(node).getText();
if (brokenName.isEmpty()) return;
for (DeclarationWithProximity dwp: getProposals(node, cu).values()) {
int dist = getLevenshteinDistance(brokenName, dwp.getName()); //+dwp.getProximity()/3;
//TODO: would it be better to just sort by dist, and
// then select the 3 closest possibilities?
if (dist<=brokenName.length()/3+1) {
RenameProposal.addRenameProposal(problem, proposals, file,
brokenName, dwp, dist, cu);
}
}
}
private void addImportProposals(Tree.CompilationUnit cu, Node node,
Collection<ICompletionProposal> proposals, IFile file) {
if (node instanceof Tree.BaseMemberOrTypeExpression ||
node instanceof Tree.SimpleType) {
Node id = getIdentifyingNode(node);
String brokenName = id.getText();
Module module = cu.getUnit().getPackage().getModule();
for (Declaration decl: findImportCandidates(module, brokenName, cu)) {
ICompletionProposal ip = createImportProposal(cu, file, decl);
if (ip!=null) proposals.add(ip);
}
}
}
private static Set<Declaration> findImportCandidates(Module module,
String name, Tree.CompilationUnit cu) {
Set<Declaration> result = new HashSet<Declaration>();
for (Package pkg: module.getAllPackages()) {
Declaration member = pkg.getMember(name, null, false);
if (member!=null) {
result.add(member);
}
}
/*if (result.isEmpty()) {
for (Package pkg: module.getAllPackages()) {
for (Declaration member: pkg.getMembers()) {
if (!isImported(member, cu)) {
int dist = getLevenshteinDistance(name, member.getName());
//TODO: would it be better to just sort by dist, and
// then select the 3 closest possibilities?
if (dist<=name.length()/3+1) {
result.add(member);
}
}
}
}
}*/
return result;
}
private static ICompletionProposal createImportProposal(Tree.CompilationUnit cu,
IFile file, Declaration declaration) {
TextFileChange change = new TextFileChange("Add Import", file);
List<InsertEdit> ies = importEdit(cu, Collections.singleton(declaration), null);
if (ies.isEmpty()) return null;
change.setEdit(new MultiTextEdit());
for (InsertEdit ie: ies) change.addEdit(ie);
String proposedName = declaration.getName();
/*String brokenName = id.getText();
if (!brokenName.equals(proposedName)) {
change.addEdit(new ReplaceEdit(id.getStartIndex(), brokenName.length(),
proposedName));
}*/
return new ChangeCorrectionProposal("Add import of '" + proposedName + "'" +
" in package " + declaration.getUnit().getPackage().getNameAsString(),
change, 50, CeylonLabelProvider.IMPORT);
}
public static List<InsertEdit> importEdit(Tree.CompilationUnit cu,
Iterable<Declaration> declarations,
Declaration declarationBeingDeleted) {
List<InsertEdit> result = new ArrayList<InsertEdit>();
Set<Package> packages = new HashSet<Package>();
for (Declaration declaration: declarations) {
packages.add(declaration.getUnit().getPackage());
}
for (Package p: packages) {
StringBuilder text = new StringBuilder();
for (Declaration d: declarations) {
if (d.getUnit().getPackage().equals(p)) {
text.append(", ").append(d.getName());
}
}
Tree.Import importNode = findImportNode(cu, p.getNameAsString());
if (importNode!=null) {
Tree.ImportMemberOrTypeList imtl = importNode.getImportMemberOrTypeList();
if (imtl.getImportWildcard()!=null) {
//Do nothing
}
else {
int insertPosition = getBestImportMemberInsertPosition(importNode);
if (declarationBeingDeleted!=null &&
imtl.getImportMemberOrTypes().size()==1 &&
imtl.getImportMemberOrTypes().get(0).getDeclarationModel()
.equals(declarationBeingDeleted)) {
text.delete(0, 2);
}
result.add(new InsertEdit(insertPosition, text.toString()));
}
}
else {
int insertPosition = getBestImportInsertPosition(cu);
text.delete(0, 2);
text.insert(0, "import " + p.getNameAsString() + " { ").append(" }");
if (insertPosition==0) {
text.append("\n");
}
else {
text.insert(0, "\n");
}
result.add(new InsertEdit(insertPosition, text.toString()));
}
}
return result;
}
private static int getBestImportInsertPosition(Tree.CompilationUnit cu) {
Integer stopIndex = cu.getImportList().getStopIndex();
if (stopIndex == null) return 0;
return stopIndex+1;
}
private static Tree.Import findImportNode(Tree.CompilationUnit cu, String packageName) {
FindImportNodeVisitor visitor = new FindImportNodeVisitor(packageName);
cu.visit(visitor);
return visitor.getResult();
}
private static int getBestImportMemberInsertPosition(Tree.Import importNode) {
Tree.ImportMemberOrTypeList imtl = importNode.getImportMemberOrTypeList();
if (imtl.getImportWildcard()!=null) {
return imtl.getImportWildcard().getStartIndex();
}
else {
List<Tree.ImportMemberOrType> imts = imtl.getImportMemberOrTypes();
if (imts.isEmpty()) {
return imtl.getStartIndex()+1;
}
else {
return imts.get(imts.size()-1).getStopIndex()+1;
}
}
}
private void addAddAnnotationProposal(Node node, String annotation, String desc,
Declaration dec, Collection<ICompletionProposal> proposals, IProject project) {
if (dec!=null) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(dec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
if (decNode!=null) {
AddAnnotionProposal.addAddAnnotationProposal(annotation, desc, dec,
proposals, unit, decNode);
}
break;
}
}
}
}
private void addRemoveAnnotationProposal(Node node, String annotation, String desc,
Declaration dec, Collection<ICompletionProposal> proposals, IProject project) {
if (dec!=null) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
//TODO: "object" declarations?
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(dec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode = fdv.getDeclarationNode();
if (decNode!=null) {
RemoveAnnotionProposal.addRemoveAnnotationProposal(annotation, desc, dec,
proposals, unit, decNode);
}
break;
}
}
}
}
public static int applyImports(TextChange change,
Set<Declaration> alreadyImported,
Tree.CompilationUnit cu) {
return applyImports(change, alreadyImported, null, cu);
}
public static int applyImports(TextChange change,
Set<Declaration> alreadyImported,
Declaration declarationBeingDeleted,
Tree.CompilationUnit cu) {
int il=0;
for (InsertEdit ie: importEdit(cu, alreadyImported, declarationBeingDeleted)) {
il+=ie.getText().length();
change.addEdit(ie);
}
return il;
}
public static void importSignatureTypes(Declaration declaration,
Tree.CompilationUnit rootNode, Set<Declaration> tc) {
if (declaration instanceof TypedDeclaration) {
importType(tc, ((TypedDeclaration) declaration).getType(), rootNode);
}
if (declaration instanceof Functional) {
for (ParameterList pl: ((Functional) declaration).getParameterLists()) {
for (Parameter p: pl.getParameters()) {
importType(tc, p.getType(), rootNode);
}
}
}
}
public static void importTypes(Set<Declaration> tfc,
Collection<ProducedType> types,
Tree.CompilationUnit rootNode) {
if (types==null) return;
for (ProducedType type: types) {
importType(tfc, type, rootNode);
}
}
public static void importType(Set<Declaration> tfc,
ProducedType type,
Tree.CompilationUnit rootNode) {
if (type==null) return;
if (type.getDeclaration() instanceof UnionType) {
for (ProducedType t: type.getDeclaration().getCaseTypes()) {
importType(tfc, t, rootNode);
}
}
else if (type.getDeclaration() instanceof IntersectionType) {
for (ProducedType t: type.getDeclaration().getSatisfiedTypes()) {
importType(tfc, t, rootNode);
}
}
else {
TypeDeclaration td = type.getDeclaration();
if (td instanceof ClassOrInterface &&
td.isToplevel()) {
importDeclaration(tfc, td, rootNode);
for (ProducedType arg: type.getTypeArgumentList()) {
importType(tfc, arg, rootNode);
}
}
}
}
public static void importDeclaration(Set<Declaration> declarations,
Declaration declaration, Tree.CompilationUnit rootNode) {
Package p = declaration.getUnit().getPackage();
if (!p.getNameAsString().isEmpty() &&
!p.equals(rootNode.getUnit().getPackage()) &&
!p.getNameAsString().equals(Module.LANGUAGE_MODULE_NAME)) {
if (!isImported(declaration, rootNode)) {
declarations.add(declaration);
}
}
}
public static boolean isImported(Declaration declaration,
Tree.CompilationUnit rootNode) {
for (Import i: rootNode.getUnit().getImports()) {
if (i.getDeclaration().equals(declaration)) {
return true;
}
}
return false;
}
}
|
package org.lispin.jlispin.test.interp;
import junit.framework.TestCase;
import org.lispin.jlispin.core.Exp;
import org.lispin.jlispin.core.InStream;
import org.lispin.jlispin.core.Linteger;
import org.lispin.jlispin.core.Lsymbol;
import org.lispin.jlispin.core.Parser;
import org.lispin.jlispin.core.StringInStream;
import org.lispin.jlispin.core.SymbolTable;
import org.lispin.jlispin.core.UngettableInStream;
import org.lispin.jlispin.interp.BuiltInCons;
import org.lispin.jlispin.interp.Environment;
public class EvalApplyTest extends TestCase {
public void testLambda1() throws Exception {
Environment env = new Environment(null);
env.defineVariable(new Lsymbol("cons"), new BuiltInCons());
SymbolTable table = new SymbolTable();
InStream input = new UngettableInStream( new StringInStream("((lambda (x) (cons x x)) 23)"));
Parser parser = new Parser(table, input);
Exp expression = parser.read();
Exp result = env.eval(expression);
assertEquals("(23 . 23)", result.toString());
}
void excerciseEval(String exp, String expected) throws Exception {
Environment env = new Environment(null);
SymbolTable table = new SymbolTable();
env.defineVariable(new Lsymbol("cons"), new BuiltInCons());
env.defineVariable(SymbolTable.quote, SymbolTable.quote);
env.defineVariable(SymbolTable.NIL, SymbolTable.NIL);
env.defineVariable(new Lsymbol("alpha"), new Linteger(23));
env.defineVariable(new Lsymbol("bravo"), new Linteger(45));
InStream input = new UngettableInStream( new StringInStream(exp));
Parser parser = new Parser(table, input);
Exp expression = parser.read();
Exp result = env.eval(expression);
assertEquals(expected, result.toString());
}
public void testLambdaVariables() throws Exception {
excerciseEval("alpha", "23");
excerciseEval("bravo", "45");
excerciseEval("(quote alpha)", "alpha");
excerciseEval("(cons alpha bravo)", "(23 . 45)");
excerciseEval("(cons alpha (cons bravo nil))", "(23 45)");
}
public void testLambdaBuitins() throws Exception {
excerciseEval("(cons 4 5)", "(4 . 5)");
excerciseEval("(cons 4 (cons 5 nil))", "(4 5)");
excerciseEval("(cons 4 nil)", "(4)");
excerciseEval("(quote 99)", "99");
excerciseEval("(quote (34)))", "(34)");
excerciseEval("(quote (foo)))", "(foo)");
}
public void testLambda2() throws Exception {
excerciseEval("((lambda (x) (cons x x)) 23)", "(23 . 23)");
excerciseEval("((lambda (x y) (cons x y)) 5 nil)", "(5)");
}
}
|
package org.commcare.tasks;
import android.content.Context;
import org.commcare.CommCareApp;
import org.commcare.CommCareApplication;
import org.commcare.dalvik.R;
import org.commcare.engine.resource.AndroidResourceManager;
import org.commcare.engine.resource.AppInstallStatus;
import org.commcare.engine.resource.ResourceInstallUtils;
import org.commcare.logging.AndroidLogger;
import org.commcare.resources.model.InstallCancelled;
import org.commcare.resources.model.InvalidResourceStructureException;
import org.commcare.resources.model.Resource;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.TableStateListener;
import org.commcare.utils.AndroidCommCarePlatform;
import org.commcare.views.dialogs.PinnedNotificationWithProgress;
import org.javarosa.core.services.Logger;
import org.javarosa.xml.util.InvalidStructureException;
import java.util.Vector;
/**
* Stages an update for the seated app in the background. Does not perform
* actual update. If the user opens the Update activity, this task will report
* its progress to that activity. Enforces the constraint that only one
* instance is ever running.
*
* Will be cancelled on user logout, but can still run if no user is logged in.
*
* @author Phillip Mates ([email protected])
*/
public class UpdateTask
extends SingletonTask<String, Integer, ResultAndError<AppInstallStatus>>
implements TableStateListener, InstallCancelled {
private static UpdateTask singletonRunningInstance = null;
private static final Object lock = new Object();
private final AndroidResourceManager resourceManager;
private final CommCareApp app;
private PinnedNotificationWithProgress pinnedNotificationProgress = null;
private Context ctx;
private String profileRef;
private boolean wasTriggeredByAutoUpdate = false;
private boolean taskWasCancelledByUser = false;
private int currentProgress = 0;
private int maxProgress = 0;
private int authority;
private UpdateTask() {
TAG = UpdateTask.class.getSimpleName();
app = CommCareApplication._().getCurrentApp();
AndroidCommCarePlatform platform = app.getCommCarePlatform();
authority = Resource.RESOURCE_AUTHORITY_REMOTE;
resourceManager =
new AndroidResourceManager(platform);
resourceManager.setUpgradeListeners(this, this);
}
public static UpdateTask getNewInstance() {
synchronized (lock) {
if (singletonRunningInstance == null) {
singletonRunningInstance = new UpdateTask();
return singletonRunningInstance;
} else {
throw new IllegalStateException("An instance of " + TAG + " already exists.");
}
}
}
public static UpdateTask getRunningInstance() {
synchronized (lock) {
if (singletonRunningInstance != null &&
singletonRunningInstance.getStatus() == Status.RUNNING) {
return singletonRunningInstance;
}
return null;
}
}
/**
* Attaches pinned notification with a progress bar the task, which will
* report updates to and close down the notification.
*
* @param ctx For launching notification and localizing text.
*/
public void startPinnedNotification(Context ctx) {
this.ctx = ctx;
pinnedNotificationProgress =
new PinnedNotificationWithProgress(ctx, "updates.pinned.download",
"updates.pinned.progress", R.drawable.update_download_icon);
}
@Override
protected final ResultAndError<AppInstallStatus> doInBackground(String... params) {
profileRef = params[0];
setupUpdate();
try {
return new ResultAndError<>(stageUpdate());
} catch (InvalidResourceStructureException e) {
ResourceInstallUtils.logInstallError(e,
"Structure error ocurred during install|");
String structureError = "CommCare found an issue with the '" + e.resourceName + "' resource:\n" + e.getMessage();
return new ResultAndError<>(AppInstallStatus.UnknownFailure, structureError);
} catch (Exception e) {
ResourceInstallUtils.logInstallError(e,
"Unknown error ocurred during install|");
return new ResultAndError<>(AppInstallStatus.UnknownFailure, e.getMessage());
}
}
private void setupUpdate() {
ResourceInstallUtils.recordUpdateAttemptTime(app);
if (wasTriggeredByAutoUpdate) {
ResourceInstallUtils.recordAutoUpdateStart(app);
}
resourceManager.incrementUpdateAttempts();
Logger.log(AndroidLogger.TYPE_RESOURCES,
"Beginning install attempt for profile " + profileRef);
}
private AppInstallStatus stageUpdate() {
Resource profile = resourceManager.getMasterProfile();
boolean appInstalled = (profile != null &&
profile.getStatus() == Resource.RESOURCE_STATUS_INSTALLED);
if (!appInstalled) {
return AppInstallStatus.UnknownFailure;
}
String profileRefWithParams =
ResourceInstallUtils.addParamsToProfileReference(profileRef);
return resourceManager.checkAndPrepareUpgradeResources(profileRefWithParams, authority);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (pinnedNotificationProgress != null) {
pinnedNotificationProgress.handleTaskUpdate(values);
}
}
@Override
protected void onPostExecute(ResultAndError<AppInstallStatus> resultAndError) {
super.onPostExecute(resultAndError);
if (!resultAndError.data.isUpdateInCompletedState()) {
resourceManager.processUpdateFailure(resultAndError.data, ctx, wasTriggeredByAutoUpdate);
} else if (wasTriggeredByAutoUpdate) {
// auto-update was successful or app was up-to-date.
ResourceInstallUtils.recordAutoUpdateCompletion(app);
}
if (pinnedNotificationProgress != null) {
pinnedNotificationProgress.handleTaskCompletion(resultAndError.data);
}
}
@Override
protected void onCancelled(ResultAndError<AppInstallStatus> resultAndError) {
super.onCancelled(resultAndError);
if (taskWasCancelledByUser && wasTriggeredByAutoUpdate) {
// task may have been cancelled by logout, in which case we want
// to keep trying to auto-update upon logging in again.
ResourceInstallUtils.recordAutoUpdateCompletion(app);
}
taskWasCancelledByUser = false;
if (pinnedNotificationProgress != null) {
pinnedNotificationProgress.handleTaskCancellation();
}
resourceManager.upgradeCancelled();
}
@Override
public void clearTaskInstance() {
synchronized (lock) {
singletonRunningInstance = null;
}
}
/**
* Calculate and report the resource install progress a table has made.
*/
@Override
public void compoundResourceAdded(ResourceTable table) {
Vector<Resource> resources =
AndroidResourceManager.getResourceListFromProfile(table);
currentProgress = 0;
for (Resource r : resources) {
int resourceStatus = r.getStatus();
if (resourceStatus == Resource.RESOURCE_STATUS_UPGRADE ||
resourceStatus == Resource.RESOURCE_STATUS_INSTALLED) {
currentProgress += 1;
}
}
maxProgress = resources.size();
incrementProgress(currentProgress, maxProgress);
}
@Override
public void simpleResourceAdded() {
incrementProgress(++currentProgress, maxProgress);
}
@Override
public void incrementProgress(int complete, int total) {
this.publishProgress(complete, total);
}
/**
* Allows resource installation process to check if this task was cancelled
*/
@Override
public boolean wasInstallCancelled() {
return isCancelled();
}
public int getProgress() {
return currentProgress;
}
public int getMaxProgress() {
return maxProgress;
}
/**
* Register task as triggered by auto update; used to determine retry behaviour.
*/
public void setAsAutoUpdate() {
wasTriggeredByAutoUpdate = true;
}
public void setLocalAuthority() {
authority = Resource.RESOURCE_AUTHORITY_LOCAL;
}
/**
* Record that task cancellation was triggered by user, not the app logging
* out. Useful for knowing if an auto-update should resume or not upon next
* login.
*/
public void cancelWasUserTriggered() {
taskWasCancelledByUser = true;
}
}
|
package imagej.core.commands.display.interactive.threshold;
import org.scijava.plugin.Plugin;
// NB - this plugin adapted from Gabriel Landini's code of his AutoThreshold
// plugin found in Fiji (version 1.14).
/**
* Implements a minimum threshold method by Prewitt & Mendelsohn.
*
* @author Barry DeZonia
* @author Gabriel Landini
*/
@Plugin(type = AutoThresholdMethod.class, name = "Minimum")
public class MinimumThresholdMethod implements AutoThresholdMethod {
private String errMsg;
@Override
public int getThreshold(long[] histogram) {
if (histogram.length < 2) return 0;
// J. M. S. Prewitt and M. L. Mendelsohn, "The analysis of cell images," in
// Annals of the New York Academy of Sciences, vol. 128, pp. 1035-1053,
// 1966.
// ported to ImageJ plugin by G.Landini from Antti Niemisto's Matlab code
// presentation and the original Matlab code.
// Assumes a bimodal histogram. The histogram needs is smoothed (using a
// running average of size 3, iteratively) until there are only two local
// maxima.
// Images with histograms having extremely unequal peaks or a broad and
// ??at valley are unsuitable for this method.
int iter = 0;
int max = -1;
double[] iHisto = new double[histogram.length];
for (int i = 0; i < histogram.length; i++) {
iHisto[i] = histogram[i];
if (histogram[i] > 0) max = i;
}
double[] tHisto = iHisto;
while (!Utils.bimodalTest(iHisto)) {
// smooth with a 3 point running mean filter
for (int i = 1; i < histogram.length - 1; i++)
tHisto[i] = (iHisto[i - 1] + iHisto[i] + iHisto[i + 1]) / 3;
// 0 outside
tHisto[0] = (iHisto[0] + iHisto[1]) / 3;
// 0 outside
tHisto[histogram.length - 1] =
(iHisto[histogram.length - 2] + iHisto[histogram.length - 1]) / 3;
iHisto = tHisto;
iter++;
if (iter > 10000) {
errMsg = "Minimum Threshold not found after 10000 iterations.";
return -1;
}
}
// The threshold is the minimum between the two peaks.
// NB - BDZ updated code to match HistThresh 1.0.3 implementation
double[] y = iHisto;
boolean peakFound = false;
for (int k = 1; k < max; k++) {
// IJ.log(" "+i+" "+iHisto[i]);
if (y[k - 1] < y[k] && y[k + 1] < y[k]) peakFound = true;
if (peakFound && y[k - 1] >= y[k] && y[k + 1] >= y[k]) return k;
}
return -1;
}
@Override
public String getMessage() {
return errMsg;
}
}
|
package org.postgresql.jdbc2;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
import org.postgresql.core.*;
import org.postgresql.Driver;
import org.postgresql.PGNotification;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
import org.postgresql.util.*;
import org.postgresql.copy.*;
import org.postgresql.core.Utils;
/**
* This class defines methods of the jdbc2 specification.
* The real Connection class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Connection
*/
public abstract class AbstractJdbc2Connection implements BaseConnection
{
// Driver-wide connection ID counter, used for logging
private static int nextConnectionID = 1;
// Data initialized on construction:
// Per-connection logger
private final Logger logger;
/* URL we were created via */
private final String creatingURL;
private Throwable openStackTrace;
/* Actual network handler */
private final ProtocolConnection protoConnection;
/* Compatible version as xxyyzz form */
private final int compatibleInt;
/* Query that runs COMMIT */
private final Query commitQuery;
/* Query that runs ROLLBACK */
private final Query rollbackQuery;
private TypeInfo _typeCache;
private boolean disableColumnSanitiser = false;
// Default statement prepare threshold.
protected int prepareThreshold;
// Default forcebinary option.
protected boolean forcebinary = false;
// Connection's autocommit state.
public boolean autoCommit = true;
// Connection's readonly state.
public boolean readOnly = false;
// Bind String to UNSPECIFIED or VARCHAR?
public final boolean bindStringAsVarchar;
// Current warnings; there might be more on protoConnection too.
public SQLWarning firstWarning = null;
/** Set of oids that use binary transfer when sending to server. */
private Set<Integer> useBinarySendForOids;
/** Set of oids that use binary transfer when receiving from server. */
private Set<Integer> useBinaryReceiveForOids;
public abstract DatabaseMetaData getMetaData() throws SQLException;
// Ctor.
protected AbstractJdbc2Connection(HostSpec[] hostSpecs, String user, String database, Properties info, String url) throws SQLException
{
this.creatingURL = url;
// Read loglevel arg and set the loglevel based on this value;
// In addition to setting the log level, enable output to
// standard out if no other printwriter is set
int logLevel = Driver.getLogLevel();
String connectionLogLevel = info.getProperty("loglevel");
if (connectionLogLevel != null) {
try {
logLevel = Integer.parseInt(connectionLogLevel);
} catch (Exception l_e) {
// XXX revisit
// invalid value for loglevel; ignore it
}
}
synchronized (AbstractJdbc2Connection.class) {
logger = new Logger(nextConnectionID++);
logger.setLogLevel(logLevel);
}
if (logLevel > 0)
enableDriverManagerLogging();
prepareThreshold = 5;
try
{
prepareThreshold = Integer.parseInt(info.getProperty("prepareThreshold", "5"));
// special value to set forceBinary to true
if (prepareThreshold == -1)
forcebinary = true;
}
catch (Exception e)
{
}
boolean binaryTransfer = true;
try
{
binaryTransfer = Boolean.valueOf(info.getProperty("binaryTransfer", "true")).booleanValue();
}
catch (Exception e)
{
}
//Print out the driver version number
if (logger.logInfo())
logger.info(Driver.getVersion());
// Now make the initial connection and set up local state
this.protoConnection = ConnectionFactory.openConnection(hostSpecs, user, database, info, logger);
int compat = Utils.parseServerVersionStr(info.getProperty("compatible"));
if (compat == 0)
compat = Driver.MAJORVERSION * 10000 + Driver.MINORVERSION * 100;
this.compatibleInt = compat;
// Set read-only early if requested
if (Boolean.valueOf(info.getProperty("readOnly", "false")))
{
setReadOnly(true);
}
// Formats that currently have binary protocol support
Set<Integer> binaryOids = new HashSet<Integer>();
if (binaryTransfer && protoConnection.getProtocolVersion() >= 3) {
binaryOids.add(Oid.BYTEA);
binaryOids.add(Oid.INT2);
binaryOids.add(Oid.INT4);
binaryOids.add(Oid.INT8);
binaryOids.add(Oid.FLOAT4);
binaryOids.add(Oid.FLOAT8);
binaryOids.add(Oid.TIME);
binaryOids.add(Oid.DATE);
binaryOids.add(Oid.TIMETZ);
binaryOids.add(Oid.TIMESTAMP);
binaryOids.add(Oid.TIMESTAMPTZ);
binaryOids.add(Oid.INT2_ARRAY);
binaryOids.add(Oid.INT4_ARRAY);
binaryOids.add(Oid.INT8_ARRAY);
binaryOids.add(Oid.FLOAT4_ARRAY);
binaryOids.add(Oid.FLOAT8_ARRAY);
binaryOids.add(Oid.FLOAT8_ARRAY);
binaryOids.add(Oid.VARCHAR_ARRAY);
binaryOids.add(Oid.TEXT_ARRAY);
binaryOids.add(Oid.POINT);
binaryOids.add(Oid.BOX);
binaryOids.add(Oid.UUID);
}
// the pre 8.0 servers do not disclose their internal encoding for
// time fields so do not try to use them.
if (!haveMinimumCompatibleVersion("8.0")) {
binaryOids.remove(Oid.TIME);
binaryOids.remove(Oid.TIMETZ);
binaryOids.remove(Oid.TIMESTAMP);
binaryOids.remove(Oid.TIMESTAMPTZ);
}
// driver supports only null-compatible arrays
if (!haveMinimumCompatibleVersion("8.3")) {
binaryOids.remove(Oid.INT2_ARRAY);
binaryOids.remove(Oid.INT4_ARRAY);
binaryOids.remove(Oid.INT8_ARRAY);
binaryOids.remove(Oid.FLOAT4_ARRAY);
binaryOids.remove(Oid.FLOAT8_ARRAY);
binaryOids.remove(Oid.FLOAT8_ARRAY);
binaryOids.remove(Oid.VARCHAR_ARRAY);
binaryOids.remove(Oid.TEXT_ARRAY);
}
binaryOids.addAll(getOidSet(info.getProperty("binaryTransferEnable", "")));
binaryOids.removeAll(getOidSet(info.getProperty("binaryTransferDisable", "")));
// split for receive and send for better control
useBinarySendForOids = new HashSet<Integer>();
useBinarySendForOids.addAll(binaryOids);
useBinaryReceiveForOids = new HashSet<Integer>();
useBinaryReceiveForOids.addAll(binaryOids);
/*
* Does not pass unit tests because unit tests expect setDate to have
* millisecond accuracy whereas the binary transfer only supports
* date accuracy.
*/
useBinarySendForOids.remove(Oid.DATE);
protoConnection.setBinaryReceiveOids(useBinaryReceiveForOids);
if (logger.logDebug())
{
logger.debug(" compatible = " + compatibleInt);
logger.debug(" loglevel = " + logLevel);
logger.debug(" prepare threshold = " + prepareThreshold);
logger.debug(" types using binary send = " + oidsToString(useBinarySendForOids));
logger.debug(" types using binary receive = " + oidsToString(useBinaryReceiveForOids));
logger.debug(" integer date/time = " + protoConnection.getIntegerDateTimes());
}
// String -> text or unknown?
String stringType = info.getProperty("stringtype");
if (stringType != null) {
if (stringType.equalsIgnoreCase("unspecified"))
bindStringAsVarchar = false;
else if (stringType.equalsIgnoreCase("varchar"))
bindStringAsVarchar = true;
else
throw new PSQLException(GT.tr("Unsupported value for stringtype parameter: {0}", stringType),
PSQLState.INVALID_PARAMETER_VALUE);
} else {
bindStringAsVarchar = haveMinimumCompatibleVersion("8.0");
}
// Initialize timestamp stuff
timestampUtils = new TimestampUtils(haveMinimumServerVersion("7.4"), haveMinimumServerVersion("8.2"),
!protoConnection.getIntegerDateTimes());
// Initialize common queries.
commitQuery = getQueryExecutor().createSimpleQuery("COMMIT");
rollbackQuery = getQueryExecutor().createSimpleQuery("ROLLBACK");
int unknownLength = Integer.MAX_VALUE;
String strLength = info.getProperty("unknownLength");
if (strLength != null) {
try {
unknownLength = Integer.parseInt(strLength);
} catch (NumberFormatException nfe) {
throw new PSQLException(GT.tr("unknownLength parameter value must be an integer"), PSQLState.INVALID_PARAMETER_VALUE, nfe);
}
}
// Initialize object handling
_typeCache = createTypeInfo(this, unknownLength);
initObjectTypes(info);
if (Boolean.valueOf(info.getProperty("logUnclosedConnections")).booleanValue()) {
openStackTrace = new Throwable("Connection was created at this point:");
enableDriverManagerLogging();
}
this.disableColumnSanitiser = Boolean.valueOf(info.getProperty(""
+ "disableColumnSanitiser", Boolean.FALSE.toString()));
String currentSchema = info.getProperty("currentSchema");
if (currentSchema != null)
{
setSchema(currentSchema);
}
}
private Set<Integer> getOidSet(String oidList) throws PSQLException {
Set oids = new HashSet();
StringTokenizer tokenizer = new StringTokenizer(oidList, ",");
while (tokenizer.hasMoreTokens()) {
String oid = tokenizer.nextToken();
oids.add(Oid.valueOf(oid));
}
return oids;
}
private String oidsToString(Set<Integer> oids) {
StringBuffer sb = new StringBuffer();
for (Integer oid : oids) {
sb.append(Oid.toString(oid));
sb.append(',');
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
} else {
sb.append(" <none>");
}
return sb.toString();
}
private final TimestampUtils timestampUtils;
public TimestampUtils getTimestampUtils() { return timestampUtils; }
/*
* The current type mappings
*/
protected java.util.Map typemap;
public java.sql.Statement createStatement() throws SQLException
{
// We now follow the spec and default to TYPE_FORWARD_ONLY.
return createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
{
return prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.CallableStatement prepareCall(String sql) throws SQLException
{
return prepareCall(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.util.Map getTypeMap() throws SQLException
{
checkClosed();
return typemap;
}
// Query executor associated with this connection.
public QueryExecutor getQueryExecutor() {
return protoConnection.getQueryExecutor();
}
/*
* This adds a warning to the warning chain.
* @param warn warning to add
*/
public void addWarning(SQLWarning warn)
{
// Add the warning to the chain
if (firstWarning != null)
firstWarning.setNextWarning(warn);
else
firstWarning = warn;
}
public ResultSet execSQLQuery(String s) throws SQLException {
return execSQLQuery(s, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
}
/**
* Simple query execution.
*/
public ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException {
BaseStatement stat = (BaseStatement) createStatement(resultSetType, resultSetConcurrency);
boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN);
while (!hasResultSet && stat.getUpdateCount() != -1)
hasResultSet = stat.getMoreResults();
if (!hasResultSet)
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
// Transfer warnings to the connection, since the user never
// has a chance to see the statement itself.
SQLWarning warnings = stat.getWarnings();
if (warnings != null)
addWarning(warnings);
return stat.getResultSet();
}
public void execSQLUpdate(String s) throws SQLException {
BaseStatement stmt = (BaseStatement) createStatement();
if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN))
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
// Transfer warnings to the connection, since the user never
// has a chance to see the statement itself.
SQLWarning warnings = stmt.getWarnings();
if (warnings != null)
addWarning(warnings);
stmt.close();
}
/*
* In SQL, a result table can be retrieved through a cursor that
* is named. The current row of a result can be updated or deleted
* using a positioned update/delete statement that references the
* cursor name.
*
* We do not support positioned update/delete, so this is a no-op.
*
* @param cursor the cursor name
* @exception SQLException if a database access error occurs
*/
public void setCursorName(String cursor) throws SQLException
{
checkClosed();
// No-op.
}
/*
* getCursorName gets the cursor name.
*
* @return the current cursor name
* @exception SQLException if a database access error occurs
*/
public String getCursorName() throws SQLException
{
checkClosed();
return null;
}
/*
* We are required to bring back certain information by
* the DatabaseMetaData class. These functions do that.
*
* Method getURL() brings back the URL (good job we saved it)
*
* @return the url
* @exception SQLException just in case...
*/
public String getURL() throws SQLException
{
return creatingURL;
}
/*
* Method getUserName() brings back the User Name (again, we
* saved it)
*
* @return the user name
* @exception SQLException just in case...
*/
public String getUserName() throws SQLException
{
return protoConnection.getUser();
}
/*
* This returns the Fastpath API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>It is primarily used by the LargeObject API
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.fastpath.*;
* ...
* Fastpath fp = ((org.postgresql.Connection)myconn).getFastpathAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return Fastpath object allowing access to functions on the org.postgresql
* backend.
* @exception SQLException by Fastpath when initialising for first time
*/
public Fastpath getFastpathAPI() throws SQLException
{
checkClosed();
if (fastpath == null)
fastpath = new Fastpath(this);
return fastpath;
}
// This holds a reference to the Fastpath API if already open
private Fastpath fastpath = null;
/*
* This returns the LargeObject API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.largeobject.*;
* ...
* LargeObjectManager lo = ((org.postgresql.Connection)myconn).getLargeObjectAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return LargeObject object that implements the API
* @exception SQLException by LargeObject when initialising for first time
*/
public LargeObjectManager getLargeObjectAPI() throws SQLException
{
checkClosed();
if (largeobject == null)
largeobject = new LargeObjectManager(this);
return largeobject;
}
// This holds a reference to the LargeObject API if already open
private LargeObjectManager largeobject = null;
/*
* This method is used internally to return an object based around
* org.postgresql's more unique data types.
*
* <p>It uses an internal HashMap to get the handling class. If the
* type is not supported, then an instance of org.postgresql.util.PGobject
* is returned.
*
* You can use the getValue() or setValue() methods to handle the returned
* object. Custom objects can have their own methods.
*
* @return PGobject for this type, and set to value
* @exception SQLException if value is not correct for this type
*/
public Object getObject(String type, String value, byte[] byteValue) throws SQLException
{
if (typemap != null)
{
Class c = (Class) typemap.get(type);
if (c != null)
{
// Handle the type (requires SQLInput & SQLOutput classes to be implemented)
throw new PSQLException(GT.tr("Custom type maps are not supported."), PSQLState.NOT_IMPLEMENTED);
}
}
PGobject obj = null;
if (logger.logDebug())
logger.debug("Constructing object from type=" + type + " value=<" + value + ">");
try
{
Class klass = _typeCache.getPGobject(type);
// If className is not null, then try to instantiate it,
// It must be basetype PGobject
// This is used to implement the org.postgresql unique types (like lseg,
// point, etc).
if (klass != null)
{
obj = (PGobject) (klass.newInstance());
obj.setType(type);
if (byteValue != null && obj instanceof PGBinaryObject) {
PGBinaryObject binObj = (PGBinaryObject) obj;
binObj.setByteValue(byteValue, 0);
} else {
obj.setValue(value);
}
}
else
{
// If className is null, then the type is unknown.
// so return a PGobject with the type set, and the value set
obj = new PGobject();
obj.setType( type );
obj.setValue( value );
}
return obj;
}
catch (SQLException sx)
{
// rethrow the exception. Done because we capture any others next
throw sx;
}
catch (Exception ex)
{
throw new PSQLException(GT.tr("Failed to create object for: {0}.", type), PSQLState.CONNECTION_FAILURE, ex);
}
}
protected TypeInfo createTypeInfo(BaseConnection conn, int unknownLength)
{
return new TypeInfoCache(conn, unknownLength);
}
public TypeInfo getTypeInfo()
{
return _typeCache;
}
public void addDataType(String type, String name)
{
try
{
addDataType(type, Class.forName(name));
}
catch (Exception e)
{
throw new RuntimeException("Cannot register new type: " + e);
}
}
public void addDataType(String type, Class klass) throws SQLException
{
checkClosed();
_typeCache.addDataType(type, klass);
}
// This initialises the objectTypes hash map
private void initObjectTypes(Properties info) throws SQLException
{
// Add in the types that come packaged with the driver.
// These can be overridden later if desired.
addDataType("box", org.postgresql.geometric.PGbox.class);
addDataType("circle", org.postgresql.geometric.PGcircle.class);
addDataType("line", org.postgresql.geometric.PGline.class);
addDataType("lseg", org.postgresql.geometric.PGlseg.class);
addDataType("path", org.postgresql.geometric.PGpath.class);
addDataType("point", org.postgresql.geometric.PGpoint.class);
addDataType("polygon", org.postgresql.geometric.PGpolygon.class);
addDataType("money", org.postgresql.util.PGmoney.class);
addDataType("interval", org.postgresql.util.PGInterval.class);
for (Enumeration e = info.propertyNames(); e.hasMoreElements(); )
{
String propertyName = (String)e.nextElement();
if (propertyName.startsWith("datatype."))
{
String typeName = propertyName.substring(9);
String className = info.getProperty(propertyName);
Class klass;
try
{
klass = Class.forName(className);
}
catch (ClassNotFoundException cnfe)
{
throw new PSQLException(GT.tr("Unable to load the class {0} responsible for the datatype {1}", new Object[] { className, typeName }),
PSQLState.SYSTEM_ERROR, cnfe);
}
addDataType(typeName, klass);
}
}
}
/**
* In some cases, it is desirable to immediately release a Connection's
* database and JDBC resources instead of waiting for them to be
* automatically released.
*
* <B>Note:</B> A Connection is automatically closed when it is
* garbage collected. Certain fatal errors also result in a closed
* connection.
*
* @exception SQLException if a database access error occurs
*/
public void close()
{
protoConnection.close();
openStackTrace = null;
}
/*
* A driver may convert the JDBC sql grammar into its system's
* native SQL grammar prior to sending it; nativeSQL returns the
* native form of the statement that the driver would have sent.
*
* @param sql a SQL statement that may contain one or more '?'
* parameter placeholders
* @return the native form of this statement
* @exception SQLException if a database access error occurs
*/
public String nativeSQL(String sql) throws SQLException
{
checkClosed();
StringBuffer buf = new StringBuffer(sql.length());
AbstractJdbc2Statement.parseSql(sql,0,buf,false,getStandardConformingStrings());
return buf.toString();
}
/*
* The first warning reported by calls on this Connection is
* returned.
*
* <B>Note:</B> Sebsequent warnings will be changed to this
* SQLWarning
*
* @return the first SQLWarning or null
* @exception SQLException if a database access error occurs
*/
public synchronized SQLWarning getWarnings()
throws SQLException
{
checkClosed();
SQLWarning newWarnings = protoConnection.getWarnings(); // NB: also clears them.
if (firstWarning == null)
firstWarning = newWarnings;
else
firstWarning.setNextWarning(newWarnings); // Chain them on.
return firstWarning;
}
/*
* After this call, getWarnings returns null until a new warning
* is reported for this connection.
*
* @exception SQLException if a database access error occurs
*/
public synchronized void clearWarnings()
throws SQLException
{
checkClosed();
protoConnection.getWarnings(); // Clear and discard.
firstWarning = null;
}
/*
* You can put a connection in read-only mode as a hunt to enable
* database optimizations
*
* <B>Note:</B> setReadOnly cannot be called while in the middle
* of a transaction
*
* @param readOnly - true enables read-only mode; false disables it
* @exception SQLException if a database access error occurs
*/
public void setReadOnly(boolean readOnly) throws SQLException
{
checkClosed();
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
throw new PSQLException(GT.tr("Cannot change transaction read-only property in the middle of a transaction."),
PSQLState.ACTIVE_SQL_TRANSACTION);
if (haveMinimumServerVersion("7.4") && readOnly != this.readOnly)
{
String readOnlySql = "SET SESSION CHARACTERISTICS AS TRANSACTION " + (readOnly ? "READ ONLY" : "READ WRITE");
execSQLUpdate(readOnlySql); // nb: no BEGIN triggered.
}
this.readOnly = readOnly;
}
/*
* Tests to see if the connection is in Read Only Mode.
*
* @return true if the connection is read only
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly() throws SQLException
{
checkClosed();
return readOnly;
}
/*
* If a connection is in auto-commit mode, than all its SQL
* statements will be executed and committed as individual
* transactions. Otherwise, its SQL statements are grouped
* into transactions that are terminated by either commit()
* or rollback(). By default, new connections are in auto-
* commit mode. The commit occurs when the statement completes
* or the next execute occurs, whichever comes first. In the
* case of statements returning a ResultSet, the statement
* completes when the last row of the ResultSet has been retrieved
* or the ResultSet has been closed. In advanced cases, a single
* statement may return multiple results as well as output parameter
* values. Here the commit occurs when all results and output param
* values have been retrieved.
*
* @param autoCommit - true enables auto-commit; false disables it
* @exception SQLException if a database access error occurs
*/
public void setAutoCommit(boolean autoCommit) throws SQLException
{
checkClosed();
if (this.autoCommit == autoCommit)
return ;
if (!this.autoCommit)
commit();
this.autoCommit = autoCommit;
}
/*
* gets the current auto-commit state
*
* @return Current state of the auto-commit mode
* @see setAutoCommit
*/
public boolean getAutoCommit() throws SQLException
{
checkClosed();
return this.autoCommit;
}
private void executeTransactionCommand(Query query) throws SQLException {
int flags = QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN;
if (prepareThreshold == 0) {
flags |= QueryExecutor.QUERY_ONESHOT;
}
getQueryExecutor().execute(query, null, new TransactionCommandHandler(),
0, 0, flags);
}
/*
* The method commit() makes all changes made since the previous
* commit/rollback permanent and releases any database locks currently
* held by the Connection. This method should only be used when
* auto-commit has been disabled.
*
* @exception SQLException if a database access error occurs,
* this method is called on a closed connection or
* this Connection object is in auto-commit mode
* @see setAutoCommit
*/
public void commit() throws SQLException
{
checkClosed();
if (autoCommit)
throw new PSQLException(GT.tr("Cannot commit when autoCommit is enabled."),
PSQLState.NO_ACTIVE_SQL_TRANSACTION);
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
executeTransactionCommand(commitQuery);
}
protected void checkClosed() throws SQLException {
if (isClosed())
throw new PSQLException(GT.tr("This connection has been closed."),
PSQLState.CONNECTION_DOES_NOT_EXIST);
}
/*
* The method rollback() drops all changes made since the previous
* commit/rollback and releases any database locks currently held by
* the Connection.
*
* @exception SQLException if a database access error occurs,
* this method is called on a closed connection or
* this Connection object is in auto-commit mode
* @see commit
*/
public void rollback() throws SQLException
{
checkClosed();
if (autoCommit)
throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."),
PSQLState.NO_ACTIVE_SQL_TRANSACTION);
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
executeTransactionCommand(rollbackQuery);
}
public int getTransactionState() {
return protoConnection.getTransactionState();
}
/*
* Get this Connection's current transaction isolation mode.
*
* @return the current TRANSACTION_* mode value
* @exception SQLException if a database access error occurs
*/
public int getTransactionIsolation() throws SQLException
{
checkClosed();
String level = null;
if (haveMinimumServerVersion("7.3"))
{
// 7.3+ returns the level as a query result.
ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered
if (rs.next())
level = rs.getString(1);
rs.close();
}
else
{
// 7.2 returns the level as an INFO message. Ew.
// We juggle the warning chains a bit here.
// Swap out current warnings.
SQLWarning saveWarnings = getWarnings();
clearWarnings();
// Run the query any examine any resulting warnings.
execSQLUpdate("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered
SQLWarning warning = getWarnings();
if (warning != null)
level = warning.getMessage();
// Swap original warnings back.
clearWarnings();
if (saveWarnings != null)
addWarning(saveWarnings);
}
// XXX revisit: throw exception instead of silently eating the error in unkwon cases?
if (level == null)
return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
level = level.toUpperCase(Locale.US);
if (level.indexOf("READ COMMITTED") != -1)
return Connection.TRANSACTION_READ_COMMITTED;
if (level.indexOf("READ UNCOMMITTED") != -1)
return Connection.TRANSACTION_READ_UNCOMMITTED;
if (level.indexOf("REPEATABLE READ") != -1)
return Connection.TRANSACTION_REPEATABLE_READ;
if (level.indexOf("SERIALIZABLE") != -1)
return Connection.TRANSACTION_SERIALIZABLE;
return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
}
/*
* You can call this method to try to change the transaction
* isolation level using one of the TRANSACTION_* values.
*
* <B>Note:</B> setTransactionIsolation cannot be called while
* in the middle of a transaction
*
* @param level one of the TRANSACTION_* isolation values with
* the exception of TRANSACTION_NONE; some databases may
* not support other values
* @exception SQLException if a database access error occurs
* @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel
*/
public void setTransactionIsolation(int level) throws SQLException
{
checkClosed();
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
throw new PSQLException(GT.tr("Cannot change transaction isolation level in the middle of a transaction."),
PSQLState.ACTIVE_SQL_TRANSACTION);
String isolationLevelName = getIsolationLevelName(level);
if (isolationLevelName == null)
throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", new Integer(level)), PSQLState.NOT_IMPLEMENTED);
String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName;
execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered
}
protected String getIsolationLevelName(int level)
{
boolean pg80 = haveMinimumServerVersion("8.0");
if (level == Connection.TRANSACTION_READ_COMMITTED)
{
return "READ COMMITTED";
}
else if (level == Connection.TRANSACTION_SERIALIZABLE)
{
return "SERIALIZABLE";
}
else if (pg80 && level == Connection.TRANSACTION_READ_UNCOMMITTED)
{
return "READ UNCOMMITTED";
}
else if (pg80 && level == Connection.TRANSACTION_REPEATABLE_READ)
{
return "REPEATABLE READ";
}
return null;
}
/*
* A sub-space of this Connection's database may be selected by
* setting a catalog name. If the driver does not support catalogs,
* it will silently ignore this request
*
* @exception SQLException if a database access error occurs
*/
public void setCatalog(String catalog) throws SQLException
{
checkClosed();
//no-op
}
/*
* Return the connections current catalog name, or null if no
* catalog name is set, or we dont support catalogs.
*
* @return the current catalog name or null
* @exception SQLException if a database access error occurs
*/
public String getCatalog() throws SQLException
{
checkClosed();
return protoConnection.getDatabase();
}
/*
* Overides finalize(). If called, it closes the connection.
*
* This was done at the request of Rachel Greenham
* <[email protected]> who hit a problem where multiple
* clients didn't close the connection, and once a fortnight enough
* clients were open to kill the postgres server.
*/
protected void finalize() throws Throwable
{
try
{
if (openStackTrace != null)
logger.log(GT.tr("Finalizing a Connection that was never closed:"), openStackTrace);
close();
}
finally
{
super.finalize();
}
}
/*
* Get server version number
*/
public String getDBVersionNumber()
{
return protoConnection.getServerVersion();
}
// Parse a "dirty" integer surrounded by non-numeric characters
private static int integerPart(String dirtyString)
{
int start, end;
for (start = 0; start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start)); ++start)
;
for (end = start; end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end)); ++end)
;
if (start == end)
return 0;
return Integer.parseInt(dirtyString.substring(start, end));
}
/*
* Get server major version
*/
public int getServerMajorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(protoConnection.getServerVersion(), "."); // aaXbb.ccYdd
return integerPart(versionTokens.nextToken()); // return X
}
catch (NoSuchElementException e)
{
return 0;
}
}
/*
* Get server minor version
*/
public int getServerMinorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(protoConnection.getServerVersion(), "."); // aaXbb.ccYdd
versionTokens.nextToken(); // Skip aaXbb
return integerPart(versionTokens.nextToken()); // return Y
}
catch (NoSuchElementException e)
{
return 0;
}
}
/**
* Is the server we are connected to running at least this version?
*/
public boolean haveMinimumServerVersion(String ver)
{
int requiredver = Utils.parseServerVersionStr(ver);
if (requiredver == 0)
/*
* Failed to parse input version. Fall back on legacy
* behaviour for BC.
*/
return (protoConnection.getServerVersion().compareTo(ver) >= 0);
else
return haveMinimumServerVersion(requiredver);
}
public boolean haveMinimumServerVersion(int ver)
{
return protoConnection.getServerVersionNum() >= ver;
}
/*
* This method returns true if the compatible level set in the connection
* (which can be passed into the connection or specified in the URL)
* is at least the value passed to this method. This is used to toggle
* between different functionality as it changes across different releases
* of the jdbc driver code. The values here are versions of the jdbc client
* and not server versions. For example in 7.1 get/setBytes worked on
* LargeObject values, in 7.2 these methods were changed to work on bytea
* values. This change in functionality could be disabled by setting the
* "compatible" level to be 7.1, in which case the driver will revert to
* the 7.1 functionality.
*
* Introduced in 9.4.
*/
public boolean haveMinimumCompatibleVersion(int ver)
{
return compatibleInt >= ver;
}
/* Prefer the int form */
public boolean haveMinimumCompatibleVersion(String ver)
{
return haveMinimumCompatibleVersion(Utils.parseServerVersionStr(ver));
}
public Encoding getEncoding() {
return protoConnection.getEncoding();
}
public byte[] encodeString(String str) throws SQLException {
try
{
return getEncoding().encode(str);
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."), PSQLState.DATA_ERROR, ioe);
}
}
public String escapeString(String str) throws SQLException {
return Utils.appendEscapedLiteral(null, str,
protoConnection.getStandardConformingStrings()).toString();
}
public boolean getStandardConformingStrings() {
return protoConnection.getStandardConformingStrings();
}
// This is a cache of the DatabaseMetaData instance for this connection
protected java.sql.DatabaseMetaData metadata;
/*
* Tests to see if a Connection is closed
*
* @return the status of the connection
* @exception SQLException (why?)
*/
public boolean isClosed() throws SQLException
{
return protoConnection.isClosed();
}
public void cancelQuery() throws SQLException
{
checkClosed();
protoConnection.sendQueryCancel();
}
public PGNotification[] getNotifications() throws SQLException
{
checkClosed();
getQueryExecutor().processNotifies();
// Backwards-compatibility hand-holding.
PGNotification[] notifications = protoConnection.getNotifications();
return (notifications.length == 0 ? null : notifications);
}
// Handler for transaction queries
private class TransactionCommandHandler implements ResultHandler {
private SQLException error;
public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor) {
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Connection.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (error == null)
error = newError;
else
error.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (error != null)
throw error;
}
}
public int getPrepareThreshold() {
return prepareThreshold;
}
public void setPrepareThreshold(int newThreshold) {
this.prepareThreshold = newThreshold;
}
public boolean getForceBinary() {
return forcebinary;
}
public void setForceBinary(boolean newValue) {
this.forcebinary = newValue;
}
public void setTypeMapImpl(java.util.Map map) throws SQLException
{
typemap = map;
}
public Logger getLogger()
{
return logger;
}
//Because the get/setLogStream methods are deprecated in JDBC2
//we use the get/setLogWriter methods here for JDBC2 by overriding
//the base version of this method
protected void enableDriverManagerLogging()
{
if (DriverManager.getLogWriter() == null)
{
DriverManager.setLogWriter(new PrintWriter(System.out, true));
}
}
public int getProtocolVersion()
{
return protoConnection.getProtocolVersion();
}
public boolean getStringVarcharFlag()
{
return bindStringAsVarchar;
}
private CopyManager copyManager = null;
public CopyManager getCopyAPI() throws SQLException
{
checkClosed();
if (copyManager == null)
copyManager = new CopyManager(this);
return copyManager;
}
public boolean binaryTransferSend(int oid) {
return useBinarySendForOids.contains(oid);
}
public int getBackendPID()
{
return protoConnection.getBackendPID();
}
public boolean isColumnSanitiserDisabled() {
return this.disableColumnSanitiser;
}
public void setDisableColumnSanitiser(boolean disableColumnSanitiser)
{
this.disableColumnSanitiser = disableColumnSanitiser;
}
public void setSchema(String schema) throws SQLException
{
checkClosed();
Statement stmt = createStatement();
try
{
if (schema != null)
{
stmt.executeUpdate("SET SESSION search_path TO '" + schema + "'");
}
else
{
stmt.executeUpdate("SET SESSION search_path TO DEFAULT");
}
}
finally
{
stmt.close();
}
}
protected void abort()
{
protoConnection.abort();
}
}
|
package com.intellij.testFramework;
import com.intellij.diagnostic.PerformanceWatcher;
import com.intellij.execution.process.ProcessIOExecutorService;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.impl.ProjectManagerImpl;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.openapi.vfs.newvfs.persistent.FlushingDaemon;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.io.NettyUtil;
import org.junit.Assert;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.TimeUnit;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* @author cdr
*/
public class ThreadTracker {
private static final Logger LOG = Logger.getInstance(ThreadTracker.class);
private final Collection<Thread> before;
private final boolean myDefaultProjectInitialized;
@TestOnly
public ThreadTracker() {
before = getThreads();
myDefaultProjectInitialized = ((ProjectManagerImpl)ProjectManager.getInstance()).isDefaultProjectInitialized();
}
private static final Method getThreads = ReflectionUtil.getDeclaredMethod(Thread.class, "getThreads");
@NotNull
public static Collection<Thread> getThreads() {
Thread[] threads;
try {
// faster than Thread.getAllStackTraces().keySet()
threads = (Thread[])getThreads.invoke(null);
}
catch (Exception e) {
throw new RuntimeException(e);
}
return ContainerUtilRt.newArrayList(threads);
}
private static final Set<String> wellKnownOffenders = new THashSet<>();
static {
wellKnownOffenders.add("AWT-EventQueue-");
wellKnownOffenders.add("AWT-Shutdown");
wellKnownOffenders.add("AWT-Windows");
wellKnownOffenders.add("CompilerThread0");
wellKnownOffenders.add("External compiler");
wellKnownOffenders.add("Finalizer");
wellKnownOffenders.add("IDEA Test Case Thread");
wellKnownOffenders.add("Image Fetcher ");
wellKnownOffenders.add("Java2D Disposer");
wellKnownOffenders.add("JobScheduler FJ pool ");
wellKnownOffenders.add("JPS thread pool");
wellKnownOffenders.add("Keep-Alive-Timer");
wellKnownOffenders.add("main");
wellKnownOffenders.add("Monitor Ctrl-Break");
wellKnownOffenders.add("Netty ");
wellKnownOffenders.add("ObjectCleanerThread");
wellKnownOffenders.add("Reference Handler");
wellKnownOffenders.add("RMI TCP Connection");
wellKnownOffenders.add("Signal Dispatcher");
wellKnownOffenders.add("timer-int"); //serverImpl
wellKnownOffenders.add("timer-sys"); //clientimpl
wellKnownOffenders.add("TimerQueue");
wellKnownOffenders.add("UserActivityMonitor thread");
wellKnownOffenders.add("VM Periodic Task Thread");
wellKnownOffenders.add("VM Thread");
wellKnownOffenders.add("YJPAgent-Telemetry");
wellKnownOffenders.add("Batik CleanerThread");
wellKnownOffenders.add(FlushingDaemon.NAME);
Application application = ApplicationManager.getApplication();
// LeakHunter might be accessed first time after Application is already disposed (during test framework shutdown).
if (!application.isDisposed()) {
longRunningThreadCreated(application,
"Periodic tasks thread",
"ApplicationImpl pooled thread ",
ProcessIOExecutorService.POOLED_THREAD_PREFIX);
}
try {
// init zillions of timers in e.g. MacOSXPreferencesFile
Preferences.userRoot().flush();
}
catch (BackingStoreException e) {
throw new RuntimeException(e);
}
}
// marks Thread with this name as long-running, which should be ignored from the thread-leaking checks
public static void longRunningThreadCreated(@NotNull Disposable parentDisposable,
@NotNull final String... threadNamePrefixes) {
wellKnownOffenders.addAll(Arrays.asList(threadNamePrefixes));
Disposer.register(parentDisposable, () -> wellKnownOffenders.removeAll(Arrays.asList(threadNamePrefixes)));
}
@TestOnly
public void checkLeak() throws AssertionError {
NettyUtil.awaitQuiescenceOfGlobalEventExecutor(100, TimeUnit.SECONDS);
ShutDownTracker.getInstance().waitFor(100, TimeUnit.SECONDS);
try {
if (myDefaultProjectInitialized != ((ProjectManagerImpl)ProjectManager.getInstance()).isDefaultProjectInitialized()) return;
Collection<Thread> after = new THashSet<>(getThreads());
after.removeAll(before);
for (final Thread thread : after) {
if (thread == Thread.currentThread()) continue;
ThreadGroup group = thread.getThreadGroup();
if (group != null && "system".equals(group.getName()))continue;
if (isWellKnownOffender(thread)) continue;
if (!thread.isAlive()) continue;
if (thread.getStackTrace().length == 0
// give thread a chance to run up to the completion
|| thread.getState() == Thread.State.RUNNABLE) {
thread.interrupt();
long start = System.currentTimeMillis();
while (thread.isAlive() && System.currentTimeMillis() < start + 10000) {
UIUtil.dispatchAllInvocationEvents(); // give blocked thread opportunity to die if it's stuck doing invokeAndWait()
}
}
StackTraceElement[] stackTrace = thread.getStackTrace();
if (stackTrace.length == 0) {
continue; // ignore threads with empty stack traces for now. Seems they are zombies unwilling to die.
}
if (isWellKnownOffender(thread)) continue; // check once more because the thread name may be set via race
if (isIdleApplicationPoolThread(thread, stackTrace)) continue;
if (isIdleCommonPoolThread(thread, stackTrace)) continue;
String trace = PerformanceWatcher.printStacktrace("Thread leaked", thread, stackTrace);
Assert.fail(trace);
}
}
finally {
before.clear();
}
}
private static boolean isWellKnownOffender(@NotNull Thread thread) {
final String name = thread.getName();
return ContainerUtil.exists(wellKnownOffenders, name::contains);
}
// true if somebody started new thread via "executeInPooledThread()" and then the thread is waiting for next task
private static boolean isIdleApplicationPoolThread(@NotNull Thread thread, @NotNull StackTraceElement[] stackTrace) {
if (!isWellKnownOffender(thread)) return false;
boolean insideTPEGetTask = Arrays.stream(stackTrace)
.anyMatch(element -> element.getMethodName().equals("getTask")
&& element.getClassName().equals("java.util.concurrent.ThreadPoolExecutor"));
return insideTPEGetTask;
}
private static boolean isIdleCommonPoolThread(@NotNull Thread thread, @NotNull StackTraceElement[] stackTrace) {
if (!ForkJoinWorkerThread.class.isAssignableFrom(thread.getClass())) {
return false;
}
boolean insideAwaitWork = Arrays.stream(stackTrace)
.anyMatch(element -> element.getMethodName().equals("awaitWork")
&& element.getClassName().equals("java.util.concurrent.ForkJoinPool"));
return insideAwaitWork;
}
public static void awaitJDIThreadsTermination(int timeout, @NotNull TimeUnit unit) {
awaitThreadTerminationWithParentParentGroup("JDI main", timeout, unit);
}
private static void awaitThreadTerminationWithParentParentGroup(@NotNull final String grandThreadGroup,
int timeout,
@NotNull TimeUnit unit) {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() < start + unit.toMillis(timeout)) {
Thread jdiThread = ContainerUtil.find(getThreads(), thread -> {
ThreadGroup group = thread.getThreadGroup();
return group != null && group.getParent() != null && grandThreadGroup.equals(group.getParent().getName());
});
if (jdiThread == null) {
break;
}
try {
long timeLeft = start + unit.toMillis(timeout) - System.currentTimeMillis();
LOG.debug("Waiting for the "+jdiThread+" for " + timeLeft+"ms");
jdiThread.join(timeLeft);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
|
package com.intellij.openapi.util;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.SystemProperties;
import com.intellij.util.concurrency.SequentialTaskExecutor;
import org.jetbrains.annotations.NotNull;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.NotificationListener;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryNotificationInfo;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.Consumer;
public final class LowMemoryWatcherManager implements Disposable {
@NotNull
private static Logger getLogger() {
return Logger.getInstance(LowMemoryWatcherManager.class);
}
private static final long MEM_THRESHOLD = 5 * 1024 * 1024;
@NotNull private final ExecutorService myExecutorService;
private Future<?> mySubmitted; // guarded by myJanitor
private final Future<?> myMemoryPoolMXBeansFuture;
private final Consumer<Boolean> myJanitor = new Consumer<Boolean>() {
@Override
public void accept(@NotNull Boolean afterGc) {
// null mySubmitted before all listeners called to avoid data race when listener added in the middle of the execution and is lost
// this may however cause listeners to execute more than once (potentially even in parallel)
synchronized (myJanitor) {
mySubmitted = null;
}
LowMemoryWatcher.onLowMemorySignalReceived(afterGc);
}
};
public LowMemoryWatcherManager(@NotNull ExecutorService backendExecutorService) {
// whether LowMemoryWatcher runnables should be executed on the same thread that the low memory events come
myExecutorService = SystemProperties.getBooleanProperty("low.memory.watcher.sync", false) ?
ConcurrencyUtil.newSameThreadExecutorService() :
SequentialTaskExecutor.createSequentialApplicationPoolExecutor("LowMemoryWatcherManager", backendExecutorService);
myMemoryPoolMXBeansFuture = initializeMXBeanListenersLater(backendExecutorService);
}
@NotNull
private Future<?> initializeMXBeanListenersLater(@NotNull ExecutorService backendExecutorService) {
// do it in the other thread to get it out of the way during startup
return backendExecutorService.submit(() -> {
try {
for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) {
if (bean.getType() == MemoryType.HEAP && bean.isCollectionUsageThresholdSupported() && bean.isUsageThresholdSupported()) {
long max = bean.getUsage().getMax();
long threshold = Math.min((long)(max * getOccupiedMemoryThreshold()), max - MEM_THRESHOLD);
if (threshold > 0) {
bean.setUsageThreshold(threshold);
bean.setCollectionUsageThreshold(threshold);
}
}
}
((NotificationEmitter)ManagementFactory.getMemoryMXBean()).addNotificationListener(myLowMemoryListener, null, null);
}
catch (Throwable e) {
// should not happen normally
getLogger().info("Errors initializing LowMemoryWatcher: ", e);
}
});
}
private final NotificationListener myLowMemoryListener = new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object __) {
if (LowMemoryWatcher.notificationsSuppressed()) return;
boolean memoryThreshold = MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED.equals(notification.getType());
boolean memoryCollectionThreshold = MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED.equals(notification.getType());
if (memoryThreshold || memoryCollectionThreshold) {
synchronized (myJanitor) {
if (mySubmitted == null) {
mySubmitted = myExecutorService.submit(() -> myJanitor.accept(memoryCollectionThreshold));
// maybe it's executed too fast or even synchronously
if (mySubmitted.isDone()) {
mySubmitted = null;
}
}
}
}
}
};
private static float getOccupiedMemoryThreshold() {
return SystemProperties.getFloatProperty("low.memory.watcher.notification.threshold", 0.95f);
}
@Override
public void dispose() {
try {
myMemoryPoolMXBeansFuture.get();
((NotificationEmitter)ManagementFactory.getMemoryMXBean()).removeNotificationListener(myLowMemoryListener);
}
catch (Exception e) {
getLogger().error(e);
}
synchronized (myJanitor) {
if (mySubmitted != null) {
mySubmitted.cancel(false);
mySubmitted = null;
}
}
LowMemoryWatcher.stopAll();
}
}
|
package org.yakindu.sct.statechart.diagram.wizards;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.OperationHistoryFactory;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.part.FileEditorInput;
import org.yakindu.sct.statechart.diagram.editor.StatechartDiagramEditor;
import org.yakindu.sct.statechart.diagram.factories.FactoryUtils;
public class CreationWizard extends Wizard implements INewWizard {
protected IStructuredSelection selection;
protected CreationWizardPage modelFilePage;
protected Resource diagram;
private final boolean openOnCreate = true;
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.selection = selection;
setWindowTitle("New YAKINDU Statechart");
setNeedsProgressMonitor(true);
}
@Override
public void addPages() {
modelFilePage = new CreationWizardPage("DiagramModelFile", getSelection(), "sct");
modelFilePage.setTitle("YAKINDU SCT Diagram");
modelFilePage.setDescription("Create a new YAKINDU SCT Diagram File");
addPage(modelFilePage);
}
@Override
public boolean performFinish() {
IRunnableWithProgress op = new WorkspaceModifyOperation(null) {
@Override
protected void execute(IProgressMonitor monitor) throws CoreException, InterruptedException {
diagram = createDiagram(modelFilePage.getURI(), modelFilePage.getURI(), monitor);
if (isOpenOnCreate() && diagram != null) {
try {
openDiagram(diagram);
} catch (PartInitException e) {
e.printStackTrace();
}
}
}
};
try {
getContainer().run(false, true, op);
} catch (Exception e) {
return false;
}
return diagram != null;
}
public static boolean openDiagram(Resource diagram) throws PartInitException {
String path = diagram.getURI().toPlatformString(true);
IResource workspaceResource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(path));
if (workspaceResource instanceof IFile) {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
return null != page.openEditor(new FileEditorInput((IFile) workspaceResource), StatechartDiagramEditor.ID);
}
return false;
}
public static Resource createDiagram(URI diagramURI, URI modelURI, IProgressMonitor progressMonitor) {
TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE.createEditingDomain();
progressMonitor.beginTask("Creating diagram file ...", 3);
final Resource resource = editingDomain.getResourceSet().createResource(modelURI);
AbstractTransactionalCommand command = new AbstractTransactionalCommand(editingDomain,
"Creating diagram file ...", Collections.EMPTY_LIST) {
@Override
protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
FactoryUtils.createStatechartModel(resource);
try {
resource.save(getSaveOptions());
} catch (IOException e) {
e.printStackTrace();
}
return CommandResult.newOKCommandResult();
}
};
try {
OperationHistoryFactory.getOperationHistory().execute(command, new SubProgressMonitor(progressMonitor, 1),
null);
} catch (ExecutionException e) {
e.printStackTrace();
}
setCharset(WorkspaceSynchronizer.getFile(resource));
return resource;
}
public static Map<String, String> getSaveOptions() {
Map<String, String> saveOptions = new HashMap<String, String>();
saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8");
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
return saveOptions;
}
public static void setCharset(IFile file) {
if (file == null) {
return;
}
try {
file.setCharset("UTF-8", new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
}
public IStructuredSelection getSelection() {
return selection;
}
public void setSelection(IStructuredSelection selection) {
this.selection = selection;
}
public boolean isOpenOnCreate() {
return openOnCreate;
}
}
|
/**
* @author Morten Beuchert
* */
package tictactoe.game;
import java.util.Hashtable;
import tictactoe.ai.Node;
import tictactoe.ai.PerfectPlayAI;
import tictactoe.game.GameState;
import tictactoe.util.Observable;
public class TicTacToe extends Observable {
private GameState gameState;
private Hashtable<String, Node> table;
private PerfectPlayAI ai;
private int x;
private int o;
// if player==true it's player1s turn, and if player==false it's player2s (computers) turn
private boolean player;
private boolean gameOver;
private int winner;
public TicTacToe() {
gameState = new GameState();
restart();
buildTranspositionTable();
}
private void buildTranspositionTable() {
table = new Hashtable<>();
int depth = 0;
Node n = ai.minimax(depth);
n.player = true;
put(toString(), n);
}
public void moveAI() {
if (isGameOver()) {
return;
}
int move = ai.move();
applyMove(move);
updateGameOver();
updateGameState();
}
public void applyMove(int square) {
if (isGameOver()) {
return;
}
int mask = 1;
mask <<= square;
// Player1s turn
if (player) {
if ((x & mask) == 0) {
x |= mask;
updateGameOver();
player = !player;
}
// Player2s turn
} else {
if ((o & mask) == 0) {
o |= mask;
updateGameOver();
player = !player;
}
}
updateGameState();
}
public void undoMove(int square) {
int mask = 1;
// it's player2s turn, meaning we have do indo player1s move
if (!player) {
mask <<= square;
if ((mask&x) > 0) {
mask = 1;
mask <<= square;
// Invert bits
mask = ~mask;
// Unset bit
x = x & mask;
gameOver = false;
winner = 0;
player = !player;
}
// it's player1s turn, meaning we have do indo player2s move
} else {
mask <<= square;
if ((mask&o) > 0) {
mask = 1;
mask <<= square;
// Invert bits
mask = ~mask;
// Unset bit
o = o & mask;
gameOver = false;
winner = 0;
player = !player;
}
}
updateGameState();
}
public boolean isLegalMove(int square) {
int mask = 1;
mask <<= square;
return (mask &= x | o) == 0;
}
public void updateGameOver() {
int row1 = 7;
int row2 = 56;
int row3 = 448;
int col1 = 73;
int col2 = 146;
int col3 = 292;
int diag1 = 273;
int diag2 = 84;
int fullboard = 511;
if ((x | o) == fullboard) {
gameOver = true;
}
if (player) {
if ((x & row1) == row1 || (x & row2) == row2 || (x & row3) == row3 || (x & col1) == col1 || (x & col2) == col2 || (x & col3) == col3 || (x & diag1) == diag1 || (x & diag2) == diag2) {
gameOver = true;
winner = 1;
}
} else if ((o & row1) == row1 || (o & row2) == row2 || (o & row3) == row3 || (o & col1) == col1 || (o & col2) == col2 || (o & col3) == col3 || (o & diag1) == diag1 || (o & diag2) == diag2) {
gameOver = true;
winner = -1;
}
}
public boolean isGameOver() {
return gameOver;
}
public int getWinner() {
return winner;
}
public boolean getTurn() {
return player;
}
public void printBoard() {
for (int i=0; i<9; i++) {
int mask = 1;
mask <<= i;
if ((x & mask) == mask) {
System.out.print("X ");
} else if ((o & mask) == mask) {
System.out.print("O ");
} else {
System.out.print("- ");
}
if ((i + 1) % 3 == 0) {
System.out.println();
}
}
System.out.println();
}
/**
* @return an array representation of board. 0: no piece. 1: cross. 2: nought.
*/
public int[] getBoard() {
int[] result = new int[9];
for (int i=0; i<9; i++) {
int mask = 1;
mask <<= i;
if ((x & mask) == mask) {
result[i] = 1;
} else if ((o & mask) == mask) {
result[i] = 2;
}
}
return result;
}
public boolean[] getLegalMoves() {
int board = x | o;
boolean[] result = new boolean[9];
int mask = 1;
for (int i=0; i<9; i++) {
mask = 1;
mask <<= i;
// Invert bits
mask = ~mask;
mask &= board;
if (mask == 0) {
result[i] = true;
}
}
return result;
}
public void restart() {
ai = new PerfectPlayAI(this);
player = true;
winner = 0;
gameOver = false;
o = 0;
x = 0;
updateGameState();
}
public void put(String key, Node value) {
table.put(key, value);
}
public Node get(String key) {
return table.get(key);
}
private void updateGameState() {
gameState.setBoard(getBoard());
gameState.setWinner(getWinner());
gameState.setPlayerTurn(player);
gameState.setGameOver(isGameOver());
notifyObservers();
}
public GameState getState() {
return gameState;
}
public String toString() {
StringBuilder res = new StringBuilder();
for (int i=0; i<9; i++) {
int mask = 1;
mask <<= i;
if ((x & mask) == mask) {
res.append("X");
} else if ((o & mask) == mask) {
res.append("O");
} else {
res.append("-");
}
}
return res.toString();
}
}
|
package org.opencps.dossiermgt.service.impl;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.opencps.dossiermgt.NoSuchDossierException;
import org.opencps.dossiermgt.NoSuchDossierStatusException;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierFile;
import org.opencps.dossiermgt.model.DossierPart;
import org.opencps.dossiermgt.model.DossierStatus;
import org.opencps.dossiermgt.model.DossierTemplate;
import org.opencps.dossiermgt.model.FileGroup;
import org.opencps.dossiermgt.service.base.DossierLocalServiceBaseImpl;
import org.opencps.paymentmgt.model.PaymentFile;
import org.opencps.processmgt.model.WorkflowOutput;
import org.opencps.servicemgt.model.ServiceInfo;
import org.opencps.util.DLFolderUtil;
import org.opencps.util.PortletConstants;
import org.opencps.util.PortletUtil;
import org.opencps.util.PortletUtil.SplitDate;
import org.opencps.util.WebKeys;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.kernel.util.ContentTypes;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextThreadLocal;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFolder;
/**
* The implementation of the dossier local service. <p> All custom service
* methods should be put in this class. Whenever methods are added, rerun
* ServiceBuilder to copy their definitions into the
* {@link org.opencps.dossiermgt.service.DossierLocalService} interface. <p>
* This is a local service. Methods of this service will not have security
* checks based on the propagated JAAS credentials because this service can only
* be accessed from within the same VM. </p>
*
* @author trungnt
* @see org.opencps.dossiermgt.service.base.DossierLocalServiceBaseImpl
* @see org.opencps.dossiermgt.service.DossierLocalServiceUtil
*/
public class DossierLocalServiceImpl extends DossierLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS: Never reference this interface directly. Always use
* {@link org.opencps.dossiermgt.service.DossierLocalServiceUtil} to access
* the dossier local service.
*/
/**
* @param userId
* @param ownerOrganizationId
* @param dossierTemplateId
* @param templateFileNo
* @param serviceConfigId
* @param serviceInfoId
* @param serviceDomainIndex
* @param govAgencyOrganizationId
* @param govAgencyCode
* @param govAgencyName
* @param serviceMode
* @param serviceAdministrationIndex
* @param cityCode
* @param cityName
* @param districtCode
* @param districtName
* @param wardName
* @param wardCode
* @param subjectName
* @param subjectId
* @param address
* @param contactName
* @param contactTelNo
* @param contactEmail
* @param note
* @param dossierSource
* @param dossierStatus
* @param parentFolderId
* @param serviceContext
* @return
* @throws SystemException
* @throws PortalException
*/
public Dossier addDossier(
long userId, long ownerOrganizationId, long dossierTemplateId,
String templateFileNo, long serviceConfigId, long serviceInfoId,
String serviceDomainIndex, long govAgencyOrganizationId,
String govAgencyCode, String govAgencyName, int serviceMode,
String serviceAdministrationIndex, String cityCode, String cityName,
String districtCode, String districtName, String wardName,
String wardCode, String subjectName, String subjectId, String address,
String contactName, String contactTelNo, String contactEmail,
String note, int dossierSource, String dossierStatus,
long parentFolderId, String redirectPaymentURL,
ServiceContext serviceContext)
throws SystemException, PortalException {
long dossierId = counterLocalService.increment(Dossier.class.getName());
Dossier dossier = dossierPersistence.create(dossierId);
int count =
dossierPersistence.countByG_U(
serviceContext.getScopeGroupId(), userId);
int dossierNo = count + 1;
Date now = new Date();
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
dossier.setUserId(userId);
dossier.setGroupId(serviceContext.getScopeGroupId());
dossier.setCompanyId(serviceContext.getCompanyId());
dossier.setCreateDate(now);
dossier.setModifiedDate(now);
dossier.setAddress(address);
dossier.setCityCode(cityCode);
dossier.setCityName(cityName);
dossier.setContactEmail(contactEmail);
dossier.setContactName(contactName);
dossier.setContactTelNo(contactTelNo);
dossier.setCounter(dossierNo);
dossier.setDistrictCode(districtCode);
dossier.setDistrictName(districtName);
dossier.setDossierSource(dossierSource);
dossier.setDossierStatus(dossierStatus);
dossier.setDossierTemplateId(dossierTemplateId);
dossier.setGovAgencyCode(govAgencyCode);
dossier.setGovAgencyName(govAgencyName);
dossier.setGovAgencyOrganizationId(govAgencyOrganizationId);
dossier.setNote(note);
dossier.setOwnerOrganizationId(ownerOrganizationId);
dossier.setServiceAdministrationIndex(serviceAdministrationIndex);
dossier.setServiceConfigId(serviceConfigId);
dossier.setServiceDomainIndex(serviceDomainIndex);
dossier.setServiceInfoId(serviceInfoId);
dossier.setServiceMode(serviceMode);
dossier.setSubjectId(subjectId);
dossier.setSubjectName(subjectName);
dossier.setOid(PortalUUIDUtil.generate());
dossier.setWardCode(wardCode);
dossier.setWardName(wardName);
dossier.setKeypayRedirectUrl(redirectPaymentURL);
DLFolder folder =
DLFolderUtil.getFolder(
serviceContext.getScopeGroupId(), parentFolderId,
dossier.getOid());
if (folder == null) {
folder =
dlFolderLocalService.addFolder(
userId, serviceContext.getScopeGroupId(),
serviceContext.getScopeGroupId(), false, parentFolderId,
dossier.getOid(), StringPool.BLANK, false, serviceContext);
}
dossier.setFolderId(folder.getFolderId());
dossier = dossierPersistence.update(dossier);
int actor = WebKeys.DOSSIER_ACTOR_CITIZEN;
long actorId = userId;
String actorName = StringPool.BLANK;
if (actorId != 0) {
User user = userPersistence.fetchByPrimaryKey(actorId);
actorName = user.getFullName();
}
dossierStatusLocalService.addDossierStatus(
userId,
dossierId,
0,
PortletConstants.DOSSIER_STATUS_NEW,
PortletUtil.getActionInfo(
PortletConstants.DOSSIER_STATUS_NEW, serviceContext.getLocale()),
PortletUtil.getMessageInfo(
PortletConstants.DOSSIER_STATUS_NEW, serviceContext.getLocale()),
now, PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC,
serviceContext);
// Update DossierLog with Actor
dossierLogLocalService.addDossierLog(
userId,
dossierId,
0,
PortletConstants.DOSSIER_STATUS_NEW,
actor,
actorId,
actorName,
PortletUtil.getActionInfo(
PortletConstants.DOSSIER_STATUS_NEW, serviceContext.getLocale()),
StringPool.BLANK,
now, PortletConstants.DOSSIER_LOG_NORMAL, serviceContext);
long classTypeId = 0;
assetEntryLocalService.updateEntry(
userId, serviceContext.getScopeGroupId(),
ServiceInfo.class.getName(), dossier.getDossierId(),
dossier.getOid(), classTypeId,
serviceContext.getAssetCategoryIds(),
serviceContext.getAssetTagNames(), false, now, null, null,
ContentTypes.TEXT_HTML, dossier.getSubjectName(), StringPool.BLANK,
StringPool.BLANK, null, null, 0, 0, 0, false);
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Dossier.class);
indexer.reindex(dossier);
return dossier;
}
/**
* @param groupId
* @return
* @throws SystemException
*/
public int countByGroupId(long groupId)
throws SystemException {
return dossierPersistence.countByGroupId(groupId);
}
/**
* @param dossierStatus
* @param serviceNo
* @param fromDate
* @param toDate
* @param username
* @return
*/
public int countDossierByDS_RD_SN_U(
String dossierStatus, String serviceNo, String fromDate, String toDate,
String username) {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
}
catch (SystemException e) {
// TODO Auto-generated catch block
}
if (Validator.isNull(username) || username.length() <= 0) {
userId = -1;
}
return dossierFinder.countDossierByDS_RD_SN_U(
userId, dossierStatus, serviceNo, fromDate, toDate);
}
/**
* @param groupId
* @param keyword
* @param domainCode
* @param dossierStatus
* @return
*/
public int countDossierByKeywordDomainAndStatus(
long groupId, String keyword, String domainCode,
List<String> govAgencyCodes, String dossierStatus) {
return dossierFinder.countDossierByKeywordDomainAndStatus(
groupId, keyword, domainCode, govAgencyCodes, dossierStatus);
};
/**
* @param processNo
* @param processStepNo
* @param username
* @return
*/
public int countDossierByP_PS_U(
String processNo, String processStepNo, String username)
throws NoSuchUserException {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
if (Validator.isNull(username) || username.length() <= 0) {
userId = -1;
}
else {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
catch (SystemException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
return dossierFinder.countDossierByP_PS_U(
processNo, processStepNo, userId);
};
/**
* @param processNo
* @param stepNo
* @param username
* @return
*/
public int countDossierByP_S_U(
String processNo, String stepNo, String username) {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
}
catch (SystemException e) {
// TODO Auto-generated catch block
}
return dossierFinder.countDossierByP_S_U(processNo, stepNo, userId);
}
/**
* @param processNo
* @param stepName
* @param username
* @return
*/
public int countDossierByP_SN_U(
String processNo, String stepName, String username) {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
}
catch (SystemException e) {
// TODO Auto-generated catch block
}
return dossierFinder.countDossierByP_SN_U(processNo, stepName, userId);
}
/**
* @param groupId
* @param dossierStatus
* @return
* @throws SystemException
*/
public int countDossierByStatus(long groupId, String dossierStatus)
throws SystemException {
return dossierPersistence.countByG_DS(groupId, dossierStatus);
}
/**
* @param groupId
* @param userId
* @param keyword
* @param serviceDomainTreeIndex
* @param dossierStatus
* @return
*/
public int countDossierByUser(
long groupId, long userId, String keyword,
String serviceDomainTreeIndex, String dossierStatus) {
return dossierFinder.countDossierByUser(
groupId, userId, keyword, serviceDomainTreeIndex, dossierStatus);
}
/**
* @param username
* @return
*/
public int countDossierByUserAssignProcessOrder(String username)
throws NoSuchUserException {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
catch (SystemException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
return dossierFinder.countDossierByUserAssignProcessOrder(userId);
}
/**
* @param dossiertype
* @param organizationcode
* @param status
* @param fromdate
* @param todate
* @param documentyear
* @param customername
* @return
*/
public int countDossierForRemoteService(
String dossiertype, String organizationcode, String processStepId,
String status, String fromdate, String todate, int documentyear,
String customername) {
return dossierFinder.countDossierForRemoteService(
dossiertype, organizationcode, processStepId, status, fromdate,
todate, documentyear, customername);
}
/**
* @param dossierId
* @param accountFolder
* @throws NoSuchDossierException
* @throws SystemException
* @throws PortalException
*/
public void deleteDossierByDossierId(long dossierId)
throws NoSuchDossierException, SystemException, PortalException {
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
List<FileGroup> fileGroups =
fileGroupLocalService.getFileGroupByDossierId(dossierId);
List<DossierFile> dossierFiles =
dossierFileLocalService.getDossierFileByDossierId(dossierId);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFileLocalService.deleteDossierFile(dossierFile);
}
}
if (fileGroups != null) {
for (FileGroup fileGroup : fileGroups) {
fileGroupLocalService.deleteFileGroup(fileGroup);
}
}
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Dossier.class);
indexer.delete(dossier);
DLFolder dlFolder = null;
try {
dlFolder = dlFolderLocalService.getDLFolder(dossier.getFolderId());
if (dlFolder != null) {
dlFolderLocalService.deleteDLFolder(dlFolder);
}
}
catch (Exception e) {
// TODO: handle exception
}
dossierPersistence.remove(dossier);
}
/**
* @param dossierId
* @param accountFolder
* @throws NoSuchDossierException
* @throws SystemException
* @throws PortalException
*/
public void deleteDossierByDossierId(long dossierId, DLFolder accountFolder)
throws NoSuchDossierException, SystemException, PortalException {
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
List<FileGroup> fileGroups =
fileGroupLocalService.getFileGroupByDossierId(dossierId);
List<DossierFile> dossierFiles =
dossierFileLocalService.getDossierFileByDossierId(dossierId);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFileLocalService.deleteDossierFile(dossierFile);
}
}
if (fileGroups != null) {
for (FileGroup fileGroup : fileGroups) {
fileGroupLocalService.deleteFileGroup(fileGroup);
}
}
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Dossier.class);
indexer.delete(dossier);
int counter = dossier.getCounter();
DLFolder dlFolder = null;
try {
dlFolder =
DLFolderUtil.getFolder(
dossier.getGroupId(), accountFolder.getFolderId(),
String.valueOf(counter));
if (dlFolder != null) {
dlFolderLocalService.deleteDLFolder(dlFolder);
}
}
catch (Exception e) {
// TODO: handle exception
}
dossierPersistence.remove(dossier);
}
/**
* @param userId
* @param dossierId
* @throws NoSuchDossierException
* @throws SystemException
* @throws PortalException
*/
public void deleteDossierByDossierId(long userId, long dossierId)
throws NoSuchDossierException, SystemException, PortalException {
Date now = new Date();
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
List<FileGroup> fileGroups =
fileGroupLocalService.getFileGroupByDossierId(dossierId);
List<DossierFile> dossierFiles =
dossierFileLocalService.getDossierFileByDossierId(dossierId);
if (fileGroups != null) {
for (FileGroup fileGroup : fileGroups) {
fileGroup.setRemoved(PortletConstants.DOSSIER_FILE_REMOVED);
fileGroup.setModifiedDate(now);
fileGroup.setUserId(userId);
fileGroupLocalService.updateFileGroup(fileGroup);
}
}
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setRemoved(PortletConstants.DOSSIER_FILE_REMOVED);
dossierFile.setModifiedDate(now);
dossierFile.setUserId(userId);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
dossier.setModifiedDate(now);
dossier.setUserId(userId);
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Dossier.class);
indexer.delete(dossier);
dossierPersistence.update(dossier);
}
public Dossier getByoid(String oid)
throws SystemException {
return dossierPersistence.fetchByOID(oid);
}
/**
* @param dossier
* @param userId
* @param govAgencyOrganizationId
* @param status
* @return
*/
protected Dossier getDossier(
Dossier dossier, long userId, long govAgencyOrganizationId,
String status) {
dossier.setUserId(userId);
dossier.setModifiedDate(new Date());
if (govAgencyOrganizationId >= 0) {
dossier.setGovAgencyOrganizationId(govAgencyOrganizationId);
}
dossier.setDossierStatus(status);
return dossier;
}
/**
* @param delayStatus
* @return
* @throws SystemException
*/
public List<Dossier> getDossierByDelayStatus(int delayStatus)
throws SystemException {
return dossierPersistence.findByDelayStatus(delayStatus);
}
/**
* @param delayStatus
* @param dossierStatus
* @return
* @throws SystemException
*/
public List<Dossier> getDossierByDelayStatusAndNotDossierStatus(
int delayStatus, String dossierStatus)
throws SystemException {
return dossierPersistence.findByDelayStatusAndNotDossierStatus(
delayStatus, dossierStatus);
}
/**
* @param groupId
* @return
* @throws SystemException
*/
public List<Dossier> getDossierByGroupId(long groupId)
throws SystemException {
return dossierPersistence.filterFindByGroupId(groupId);
}
/**
* @param receptionNo
* @return
* @throws SystemException
*/
public Dossier getDossierByReceptionNo(String receptionNo)
throws SystemException {
return dossierPersistence.fetchByReceptionNo(receptionNo);
}
/**
* @param groupId
* @param dossierStatus
* @param start
* @param end
* @param obc
* @return
* @throws SystemException
*/
public List<Dossier> getDossierByStatus(
long groupId, String dossierStatus, int start, int end,
OrderByComparator obc)
throws SystemException {
return dossierPersistence.findByG_DS(
groupId, dossierStatus, start, end, obc);
}
public List<Dossier> getDossierByStatus(long groupId, String dossierStatus)
throws SystemException {
return dossierPersistence.filterFindByG_DS(groupId, dossierStatus);
}
/**
* @param groupId
* @param userId
* @param keyword
* @param serviceDomainTreeIndex
* @param dossierStatus
* @param start
* @param end
* @param obc
* @return
*/
public List getDossierByUser(
long groupId, long userId, String keyword,
String serviceDomainTreeIndex, String dossierStatus, int start,
int end, OrderByComparator obc) {
return dossierFinder.searchDossierByUser(
groupId, userId, keyword, serviceDomainTreeIndex, dossierStatus,
start, end, obc);
}
/**
* @param dossierStatus
* @param userId
* @param govAgencyOrganizationId
* @param syncStatus
* @return
*/
protected DossierStatus getDossierStatus(
DossierStatus dossierStatus, long userId, long govAgencyOrganizationId,
int syncStatus) {
dossierStatus.setUserId(userId);
dossierStatus.setModifiedDate(new Date());
dossierStatus.setSyncStatus(syncStatus);
return dossierStatus;
}
/**
* @param dossierStatus
* @param serviceNo
* @param fromDate
* @param toDate
* @param username
* @return
*/
public List<Dossier> searchDossierByDS_RD_SN_U(
String dossierStatus, String serviceNo, String fromDate, String toDate,
String username, int start, int end) {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
}
catch (SystemException e) {
// TODO Auto-generated catch block
}
if (Validator.isNull(username) || username.length() <= 0) {
userId = -1;
}
return dossierFinder.searchDossierByDS_RD_SN_U(
dossierStatus, serviceNo, fromDate, toDate, userId, start, end);
}
/**
* @param groupId
* @param keyword
* @param domainCode
* @param dossierStatus
* @param start
* @param end
* @param obc
* @return
*/
public List<Dossier> searchDossierByKeywordDomainAndStatus(
long groupId, String keyword, String domainCode,
List<String> govAgencyCodes, String dossierStatus, int start, int end,
OrderByComparator obc) {
return dossierFinder.searchDossierByKeywordDomainAndStatus(
groupId, keyword, domainCode, govAgencyCodes, dossierStatus, start,
end, obc);
}
/**
* @param processNo
* @param processStepNo
* @param username
* @return
*/
public List<Dossier> searchDossierByP_PS_U(
String processNo, String processStepNo, String username, int start,
int end)
throws NoSuchUserException {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
if (Validator.isNull(username) || username.length() <= 0) {
userId = -1;
}
else {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
catch (SystemException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
return dossierFinder.searchDossierByP_PS_U(
processNo, processStepNo, userId, start, end);
}
/**
* @param processNo
* @param stepNo
* @param username
* @return
*/
public List<Dossier> searchDossierByP_S_U(
String processNo, String stepNo, String username, int start, int end) {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
}
catch (SystemException e) {
// TODO Auto-generated catch block
}
return dossierFinder.searchDossierByP_S_U(
processNo, stepNo, userId, start, end);
}
/**
* @param processNo
* @param stepName
* @param username
* @return
*/
public List<Dossier> searchDossierByP_SN_U(
String processNo, String stepName, String username, int start, int end) {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
}
catch (SystemException e) {
// TODO Auto-generated catch block
}
return dossierFinder.searchDossierByP_SN_U(
processNo, stepName, userId, start, end);
}
/**
* @param username
* @return
*/
public List<Dossier> searchDossierByUserAssignProcessOrder(
String username, int start, int end)
throws NoSuchUserException {
long userId = -1;
ServiceContext serviceContext =
ServiceContextThreadLocal.getServiceContext();
try {
User user =
UserLocalServiceUtil.getUserByScreenName(
serviceContext.getCompanyId(), username);
if (user != null) {
userId = user.getUserId();
}
}
catch (PortalException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
catch (SystemException e) {
// TODO Auto-generated catch block
throw new NoSuchUserException();
}
return dossierFinder.searchDossierByUserAssignByProcessOrder(
userId, start, end);
}
/**
* @param dossiertype
* @param organizationcode
* @param status
* @param fromdate
* @param todate
* @param documentyear
* @param customername
* @return
*/
public List<Dossier> searchDossierForRemoteService(
String dossiertype, String organizationcode, String processStepId,
String status, String fromdate, String todate, int documentyear,
String customername, int start, int end) {
return dossierFinder.searchDossierForRemoteService(
dossiertype, organizationcode, processStepId, status, fromdate,
todate, documentyear, customername, start, end);
}
/**
* @param syncDossier
* @param syncDossierFiles
* @param syncFileGroups
* @param syncFileGroupDossierPaths
* @param syncDLFileEntries
* @param data
* @param syncDossierTemplate
* @param serviceContext
* @return
* @throws SystemException
* @throws PortalException
* @throws Exception
*/
public Dossier syncDossier(
Dossier syncDossier,
LinkedHashMap<DossierFile, DossierPart> syncDossierFiles,
LinkedHashMap<String, FileGroup> syncFileGroups,
LinkedHashMap<Long, DossierPart> syncFileGroupDossierParts,
LinkedHashMap<String, DLFileEntry> syncDLFileEntries,
LinkedHashMap<String, byte[]> data,
DossierTemplate syncDossierTemplate, ServiceContext serviceContext)
throws SystemException, PortalException {
// Finder dossierTemplate by TemplateNo
DossierTemplate dossierTemplate =
dossierTemplateLocalService.getDossierTemplate(syncDossierTemplate.getTemplateNo());
long dossierId = counterLocalService.increment(Dossier.class.getName());
Dossier dossier = dossierPersistence.create(dossierId);
int dossierNo = syncDossier.getCounter();
Date now = new Date();
dossier.setUserId(0); // Sync from another system
dossier.setGroupId(serviceContext.getScopeGroupId());
dossier.setCompanyId(serviceContext.getCompanyId());
dossier.setCreateDate(now);
dossier.setModifiedDate(now);
dossier.setAddress(syncDossier.getAddress());
dossier.setCityCode(syncDossier.getCityCode());
dossier.setCityName(syncDossier.getCityName());
dossier.setContactEmail(syncDossier.getContactEmail());
dossier.setContactName(syncDossier.getContactName());
dossier.setContactTelNo(syncDossier.getContactTelNo());
dossier.setCounter(dossierNo);
dossier.setDistrictCode(syncDossier.getDistrictCode());
dossier.setDistrictName(syncDossier.getDistrictName());
dossier.setDossierSource(syncDossier.getDossierSource());
dossier.setDossierStatus(syncDossier.getDossierStatus());
dossier.setDossierTemplateId(syncDossier.getDossierTemplateId());
dossier.setGovAgencyCode(syncDossier.getGovAgencyCode());
dossier.setGovAgencyName(syncDossier.getGovAgencyName());
dossier.setGovAgencyOrganizationId(syncDossier.getGovAgencyOrganizationId());
dossier.setNote(syncDossier.getNote());
dossier.setOwnerOrganizationId(0);// Sync from another system
dossier.setReceptionNo(syncDossier.getReceptionNo());
//dossier.setReceiveDatetime(receiveDatetime);
dossier.setServiceAdministrationIndex(syncDossier.getServiceAdministrationIndex());
dossier.setServiceConfigId(syncDossier.getServiceConfigId());
dossier.setServiceDomainIndex(syncDossier.getServiceDomainIndex());
dossier.setServiceInfoId(syncDossier.getServiceInfoId());
dossier.setServiceMode(syncDossier.getServiceMode());
dossier.setSubjectId(syncDossier.getSubjectId());
dossier.setSubjectName(syncDossier.getSubjectName());
dossier.setOid(syncDossier.getOid());
dossier.setWardCode(syncDossier.getWardCode());
dossier.setWardName(syncDossier.getWardName());
dossier.setKeypayRedirectUrl(syncDossier.getKeypayRedirectUrl());
SplitDate splitDate = PortletUtil.splitDate(now);
/*
* String folderName = StringUtil.replace(syncDossier.getOid(),
* StringPool.DASH, StringPool.UNDERLINE);
*/
String dossierFolderDestination =
PortletUtil.getDossierDestinationFolder(
serviceContext.getScopeGroupId(), splitDate.getYear(),
splitDate.getMonth(), splitDate.getDayOfMoth(),
syncDossier.getOid());
System.out.println("SyncDossier Folder Destination
dossierFolderDestination);
DLFolder folder =
DLFolderUtil.getTargetFolder(
serviceContext.getUserId(), serviceContext.getScopeGroupId(),
serviceContext.getScopeGroupId(), false, 0,
dossierFolderDestination, StringPool.BLANK, false,
serviceContext);
if (syncDossierFiles != null) {
for (Map.Entry<DossierFile, DossierPart> entry : syncDossierFiles.entrySet()) {
DossierFile syncDossierFile = entry.getKey();
DossierPart syncDossierPart = entry.getValue();
// Finder DossierPart in current system
DossierPart dossierPart =
dossierPartLocalService.getDossierPartByT_PN(
dossierTemplate.getDossierTemplateId(),
syncDossierPart.getPartNo());
byte[] bytes = null;
if (data.containsKey(syncDossierFile.getOid())) {
bytes = data.get(syncDossierFile.getOid());
}
FileGroup syncFileGroup = null;
DossierPart groupDossierPart = null;
DLFileEntry syncDLFileEntry = null;
if (syncFileGroups.containsKey(syncDossierFile.getOid())) {
syncFileGroup =
syncFileGroups.get(syncDossierFile.getOid());
}
if (syncFileGroup != null) {
DossierPart synFileGroupDossierPath =
syncFileGroupDossierParts.get(syncFileGroup.getFileGroupId());
groupDossierPart =
dossierPartLocalService.getDossierPartByT_PN(
dossierTemplate.getDossierTemplateId(),
synFileGroupDossierPath.getPartNo());
}
if (syncDLFileEntries.containsKey(syncDossierFile.getOid())) {
syncDLFileEntry =
syncDLFileEntries.get(syncDossierFile.getOid());
}
if (bytes != null && syncDLFileEntry != null) {
System.out.println("SyncDossier Add Dossier File
dossierFileLocalService.addDossierFile(
serviceContext.getUserId(),
dossierId,
dossierPart.getDossierpartId(),
dossierTemplate.getTemplateNo(),
syncFileGroup != null
? syncFileGroup.getDisplayName() : StringPool.BLANK,
syncFileGroup != null
? syncFileGroup.getFileGroupId() : 0,
groupDossierPart != null
? groupDossierPart.getDossierpartId() : 0, 0, 0,
syncDossierFile.getDisplayName(),
syncDossierFile.getFormData(),
syncDossierFile.getDossierFileMark(),
syncDossierFile.getDossierFileType(),
syncDossierFile.getDossierFileNo(),
syncDossierFile.getDossierFileDate(),
syncDossierFile.getOriginal(),
syncDossierFile.getSyncStatus(), folder.getFolderId(),
syncDLFileEntry.getName() + StringPool.PERIOD +
syncDLFileEntry.getExtension(),
syncDLFileEntry.getMimeType(),
syncDLFileEntry.getTitle(),
syncDLFileEntry.getDescription(), StringPool.BLANK,
bytes, serviceContext);
}
}
}
dossierLogLocalService.addDossierLog(
serviceContext.getUserId(),
dossierId,
0,
PortletConstants.DOSSIER_STATUS_NEW,
"nltt",
PortletUtil.getActionInfo(
PortletConstants.DOSSIER_STATUS_NEW, serviceContext.getLocale()),
PortletUtil.getMessageInfo(
PortletConstants.DOSSIER_STATUS_NEW, serviceContext.getLocale()),
now, PortletConstants.DOSSIER_LOG_NORMAL, serviceContext);
dossier = dossierPersistence.update(dossier);
long classTypeId = 0;
assetEntryLocalService.updateEntry(
serviceContext.getUserId(), serviceContext.getScopeGroupId(),
ServiceInfo.class.getName(), dossier.getDossierId(),
dossier.getOid(), classTypeId,
serviceContext.getAssetCategoryIds(),
serviceContext.getAssetTagNames(), false, now, null, null,
ContentTypes.TEXT_HTML, dossier.getSubjectName(), StringPool.BLANK,
StringPool.BLANK, null, null, 0, 0, 0, false);
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Dossier.class);
indexer.reindex(dossier);
return dossier;
}
/**
* @param oid
* @param fileGroupId
* @param dossierStatus
* @param receptionNo
* @param estimateDatetime
* @param receiveDatetime
* @param finishDatetime
* @param actor
* @param requestCommand
* @param actionInfo
* @param messageInfo
* @param syncDossierFiles
* @param syncFileGroups
* @param syncFileGroupDossierParts
* @param syncDLFileEntries
* @param data
* @param paymentFile
* @param serviceContext
* @return
* @throws SystemException
* @throws PortalException
*/
public Dossier syncDossierStatus(
String oid, long fileGroupId, String dossierStatus, String receptionNo,
Date estimateDatetime, Date receiveDatetime, Date finishDatetime,
int actor, long actorId, String actorName, String requestCommand, String actionInfo,
String messageInfo,
LinkedHashMap<DossierFile, DossierPart> syncDossierFiles,
LinkedHashMap<String, FileGroup> syncFileGroups,
LinkedHashMap<Long, DossierPart> syncFileGroupDossierParts,
LinkedHashMap<String, DLFileEntry> syncDLFileEntries,
LinkedHashMap<String, byte[]> data, PaymentFile paymentFile,
ServiceContext serviceContext)
throws SystemException, PortalException {
Dossier dossier = dossierPersistence.findByOID(oid);
dossier.setReceptionNo(receptionNo);
dossier.setEstimateDatetime(estimateDatetime);
dossier.setReceiveDatetime(receiveDatetime);
dossier.setFinishDatetime(finishDatetime);
dossier.setDossierStatus(dossierStatus);
int level = 0;
if (dossier.getDossierStatus().equals(
PortletConstants.DOSSIER_STATUS_ERROR)) {
level = 2;
}
else if (dossier.getDossierStatus().equals(
PortletConstants.DOSSIER_STATUS_WAITING) ||
dossier.getDossierStatus().equals(
PortletConstants.DOSSIER_STATUS_PAYING)) {
level = 1;
}
// Finder dossierTemplate by TemplateNo
DossierTemplate dossierTemplate =
dossierTemplateLocalService.getDossierTemplate(dossier.getDossierTemplateId());
SplitDate splitDate = PortletUtil.splitDate(dossier.getCreateDate());
String folderName = dossier.getOid();
String dossierFolderDestination =
PortletUtil.getDossierDestinationFolder(
serviceContext.getScopeGroupId(), splitDate.getYear(),
splitDate.getMonth(), splitDate.getDayOfMoth(), folderName);
System.out.println("SyncDossierStatus Folder Destination
dossierFolderDestination);
DLFolder folder =
DLFolderUtil.getTargetFolder(
serviceContext.getUserId(), serviceContext.getScopeGroupId(),
serviceContext.getScopeGroupId(), false, 0,
dossierFolderDestination, StringPool.BLANK, false,
serviceContext);
if (syncDossierFiles != null) {
for (Map.Entry<DossierFile, DossierPart> entry : syncDossierFiles.entrySet()) {
DossierFile syncDossierFile = entry.getKey();
DossierPart syncDossierPart = entry.getValue();
// Finder DossierPart in current system
DossierPart dossierPart =
dossierPartLocalService.getDossierPartByT_PN(
dossierTemplate.getDossierTemplateId(),
syncDossierPart.getPartNo());
byte[] bytes = null;
if (data.containsKey(syncDossierFile.getOid())) {
bytes = data.get(syncDossierFile.getOid());
}
FileGroup syncFileGroup = null;
DossierPart groupDossierPart = null;
DLFileEntry syncDLFileEntry = null;
if (syncFileGroups.containsKey(syncDossierFile.getOid())) {
syncFileGroup =
syncFileGroups.get(syncDossierFile.getOid());
}
if (syncFileGroup != null) {
DossierPart synFileGroupDossierPath =
syncFileGroupDossierParts.get(syncFileGroup.getFileGroupId());
groupDossierPart =
dossierPartLocalService.getDossierPartByT_PN(
dossierTemplate.getDossierTemplateId(),
synFileGroupDossierPath.getPartNo());
}
if (syncDLFileEntries.containsKey(syncDossierFile.getOid())) {
syncDLFileEntry =
syncDLFileEntries.get(syncDossierFile.getOid());
}
if (bytes != null && syncDLFileEntry != null) {
System.out.println("SyncDossierStatus Add Dossier File
dossierFileLocalService.addDossierFile(
serviceContext.getUserId(),
dossier.getDossierId(),
dossierPart.getDossierpartId(),
dossierTemplate.getTemplateNo(),
syncFileGroup != null
? syncFileGroup.getDisplayName() : StringPool.BLANK,
syncFileGroup != null
? syncFileGroup.getFileGroupId() : 0,
groupDossierPart != null
? groupDossierPart.getDossierpartId() : 0, 0, 0,
syncDossierFile.getDisplayName(),
syncDossierFile.getFormData(),
syncDossierFile.getDossierFileMark(),
syncDossierFile.getDossierFileType(),
syncDossierFile.getDossierFileNo(),
syncDossierFile.getDossierFileDate(),
syncDossierFile.getOriginal(),
syncDossierFile.getSyncStatus(), folder.getFolderId(),
syncDLFileEntry.getName() + StringPool.PERIOD +
syncDLFileEntry.getExtension(),
syncDLFileEntry.getMimeType(),
syncDLFileEntry.getTitle(),
syncDLFileEntry.getDescription(), StringPool.BLANK,
bytes, serviceContext);
}
}
}
if (paymentFile != null) {
System.out.println("SyncDossierStatus Add Payment File
paymentFileLocalService.addPaymentFile(
dossier.getDossierId(), paymentFile.getFileGroupId(),
dossier.getUserId(), dossier.getOwnerOrganizationId(),
paymentFile.getGovAgencyOrganizationId(),
paymentFile.getPaymentName(), paymentFile.getRequestDatetime(),
paymentFile.getAmount(), paymentFile.getRequestNote(),
paymentFile.getPlaceInfo(), paymentFile.getPaymentOptions());
}
dossierLogLocalService.addDossierLog(
dossier.getUserId(), dossier.getGroupId(), dossier.getCompanyId(),
dossier.getDossierId(), fileGroupId, dossierStatus, actor, actorId, actorName,
requestCommand, actionInfo, messageInfo, level);
System.out.println("Done syncDossierStatus
dossierPersistence.update(dossier);
return dossier;
}
/**
* @param syncDossier
* @param syncDossierFiles
* @param syncFileGroups
* @param syncFileGroupDossierParts
* @param syncDLFileEntries
* @param data
* @param syncDossierTemplate
* @param serviceContext
* @return
* @throws SystemException
* @throws PortalException
*/
public Dossier syncReSubmitDossier(
Dossier syncDossier,
LinkedHashMap<DossierFile, DossierPart> syncDossierFiles,
LinkedHashMap<String, FileGroup> syncFileGroups,
LinkedHashMap<Long, DossierPart> syncFileGroupDossierParts,
LinkedHashMap<String, DLFileEntry> syncDLFileEntries,
LinkedHashMap<String, byte[]> data,
DossierTemplate syncDossierTemplate, ServiceContext serviceContext)
throws SystemException, PortalException {
// Finder dossier by OID
Dossier dossier = dossierPersistence.findByOID(syncDossier.getOid());
// Finder dossierTemplate by TemplateNo
DossierTemplate dossierTemplate =
dossierTemplateLocalService.getDossierTemplate(syncDossierTemplate.getTemplateNo());
Date now = new Date();
dossier.setModifiedDate(now);
dossier.setAddress(syncDossier.getAddress());
dossier.setCityCode(syncDossier.getCityCode());
dossier.setCityName(syncDossier.getCityName());
dossier.setContactEmail(syncDossier.getContactEmail());
dossier.setContactName(syncDossier.getContactName());
dossier.setContactTelNo(syncDossier.getContactTelNo());
dossier.setDistrictCode(syncDossier.getDistrictCode());
dossier.setDistrictName(syncDossier.getDistrictName());
dossier.setDossierSource(syncDossier.getDossierSource());
dossier.setDossierStatus(syncDossier.getDossierStatus());
dossier.setNote(syncDossier.getNote());
dossier.setSubjectId(syncDossier.getSubjectId());
dossier.setSubjectName(syncDossier.getSubjectName());
dossier.setWardCode(syncDossier.getWardCode());
dossier.setWardName(syncDossier.getWardName());
DLFolder folder = dlFolderLocalService.getFolder(dossier.getFolderId());
if (syncDossierFiles != null) {
for (Map.Entry<DossierFile, DossierPart> entry : syncDossierFiles.entrySet()) {
DossierFile syncDossierFile = entry.getKey();
DossierPart syncDossierPart = entry.getValue();
// Finder DossierPart in current system
DossierPart dossierPart =
dossierPartLocalService.getDossierPartByT_PN(
dossierTemplate.getDossierTemplateId(),
syncDossierPart.getPartNo());
byte[] bytes = null;
if (data.containsKey(syncDossierFile.getOid())) {
bytes = data.get(syncDossierFile.getOid());
}
FileGroup syncFileGroup = null;
DossierPart groupDossierPart = null;
DLFileEntry syncDLFileEntry = null;
if (syncFileGroups.containsKey(syncDossierFile.getOid())) {
syncFileGroup =
syncFileGroups.get(syncDossierFile.getOid());
}
if (syncFileGroup != null) {
DossierPart synFileGroupDossierPath =
syncFileGroupDossierParts.get(syncFileGroup.getFileGroupId());
groupDossierPart =
dossierPartLocalService.getDossierPartByT_PN(
dossierTemplate.getDossierTemplateId(),
synFileGroupDossierPath.getPartNo());
}
if (syncDLFileEntries.containsKey(syncDossierFile.getOid())) {
syncDLFileEntry =
syncDLFileEntries.get(syncDossierFile.getOid());
}
if (bytes != null && syncDLFileEntry != null) {
System.out.println("SyncDossier Add Dossier File
DossierFile oldDossierFile = null;
try {
oldDossierFile =
dossierFileLocalService.getByOid(syncDossierFile.getOid());
}
catch (Exception e) {
// TODO: handle exception
}
if (oldDossierFile != null) {
dossierFileLocalService.addDossierFile(
oldDossierFile.getDossierFileId(),
folder.getFolderId(),
syncDLFileEntry.getName() + StringPool.PERIOD +
syncDLFileEntry.getExtension(),
syncDLFileEntry.getMimeType(),
syncDLFileEntry.getTitle(),
syncDLFileEntry.getDescription(), StringPool.BLANK,
bytes, serviceContext);
}
else {
dossierFileLocalService.addDossierFile(
serviceContext.getUserId(),
dossier.getDossierId(),
dossierPart.getDossierpartId(),
dossierTemplate.getTemplateNo(),
syncFileGroup != null
? syncFileGroup.getDisplayName()
: StringPool.BLANK,
syncFileGroup != null
? syncFileGroup.getFileGroupId() : 0,
groupDossierPart != null
? groupDossierPart.getDossierpartId() : 0, 0,
0, syncDossierFile.getDisplayName(),
syncDossierFile.getFormData(),
syncDossierFile.getDossierFileMark(),
syncDossierFile.getDossierFileType(),
syncDossierFile.getDossierFileNo(),
syncDossierFile.getDossierFileDate(),
syncDossierFile.getOriginal(),
syncDossierFile.getSyncStatus(),
folder.getFolderId(),
syncDLFileEntry.getName() + StringPool.PERIOD +
syncDLFileEntry.getExtension(),
syncDLFileEntry.getMimeType(),
syncDLFileEntry.getTitle(),
syncDLFileEntry.getDescription(), StringPool.BLANK,
bytes, serviceContext);
}
}
}
}
dossierLogLocalService.addDossierLog(
serviceContext.getUserId(),
dossier.getDossierId(),
0,
PortletConstants.DOSSIER_STATUS_NEW,
"nltt",
PortletUtil.getActionInfo(
PortletConstants.DOSSIER_STATUS_NEW, serviceContext.getLocale()),
PortletUtil.getMessageInfo(
PortletConstants.DOSSIER_STATUS_NEW, serviceContext.getLocale()),
now, PortletConstants.DOSSIER_LOG_NORMAL, serviceContext);
dossier = dossierPersistence.update(dossier);
long classTypeId = 0;
assetEntryLocalService.updateEntry(
serviceContext.getUserId(), serviceContext.getScopeGroupId(),
ServiceInfo.class.getName(), dossier.getDossierId(),
dossier.getOid(), classTypeId,
serviceContext.getAssetCategoryIds(),
serviceContext.getAssetTagNames(), false, now, null, null,
ContentTypes.TEXT_HTML, dossier.getSubjectName(), StringPool.BLANK,
StringPool.BLANK, null, null, 0, 0, 0, false);
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Dossier.class);
indexer.reindex(dossier);
return dossier;
}
/**
* @param dossierId
* @param userId
* @param ownerOrganizationId
* @param dossierTemplateId
* @param templateFileNo
* @param serviceConfigId
* @param serviceInfoId
* @param serviceDomainIndex
* @param govAgencyOrganizationId
* @param govAgencyCode
* @param govAgencyName
* @param serviceMode
* @param serviceAdministrationIndex
* @param cityCode
* @param cityName
* @param districtCode
* @param districtName
* @param wardName
* @param wardCode
* @param subjectName
* @param subjectId
* @param address
* @param contactName
* @param contactTelNo
* @param contactEmail
* @param note
* @param dossierFolderId
* @param serviceContext
* @return
* @throws SystemException
* @throws PortalException
*/
public Dossier updateDossier(
long dossierId, long userId, long ownerOrganizationId,
long dossierTemplateId, String templateFileNo, long serviceConfigId,
long serviceInfoId, String serviceDomainIndex,
long govAgencyOrganizationId, String govAgencyCode,
String govAgencyName, int serviceMode,
String serviceAdministrationIndex, String cityCode, String cityName,
String districtCode, String districtName, String wardName,
String wardCode, String subjectName, String subjectId, String address,
String contactName, String contactTelNo, String contactEmail,
String note, long dossierFolderId, ServiceContext serviceContext)
throws SystemException, PortalException {
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
Date now = new Date();
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
dossier.setUserId(userId);
dossier.setModifiedDate(now);
dossier.setAddress(address);
dossier.setCityCode(cityCode);
dossier.setCityName(cityName);
dossier.setContactEmail(contactEmail);
dossier.setContactName(contactName);
dossier.setContactTelNo(contactTelNo);
dossier.setDistrictCode(districtCode);
dossier.setDistrictName(districtName);
dossier.setDossierTemplateId(dossierTemplateId);
dossier.setGovAgencyCode(govAgencyCode);
dossier.setGovAgencyName(govAgencyName);
dossier.setGovAgencyOrganizationId(govAgencyOrganizationId);
dossier.setNote(note);
dossier.setOwnerOrganizationId(ownerOrganizationId);
dossier.setServiceAdministrationIndex(serviceAdministrationIndex);
dossier.setServiceConfigId(serviceConfigId);
dossier.setServiceDomainIndex(serviceDomainIndex);
dossier.setServiceInfoId(serviceInfoId);
dossier.setServiceMode(serviceMode);
dossier.setSubjectId(subjectId);
dossier.setSubjectName(subjectName);
dossier.setOid(PortalUUIDUtil.generate());
dossier.setWardCode(wardCode);
dossier.setWardName(wardName);
dossier = dossierPersistence.update(dossier);
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Dossier.class);
indexer.reindex(dossier);
int actor = WebKeys.DOSSIER_ACTOR_CITIZEN;
long actorId = userId;
String actorName = StringPool.BLANK;
if (actorId != 0) {
User user = userPersistence.fetchByPrimaryKey(actorId);
actorName = user.getFullName();
}
dossierLogLocalService.addDossierLog(
userId,
dossierId,
0,
PortletConstants.DOSSIER_STATUS_NEW,
actor,
actorId,
actorName,
PortletUtil.getActionInfo(
PortletConstants.DOSSIER_STATUS_UPDATE, serviceContext.getLocale()),
StringPool.BLANK,
now, PortletConstants.DOSSIER_LOG_NORMAL, serviceContext);
return dossier;
}
/**
* @param userId
* @param dossierId
* @param syncStatus
* @param worklows
* @throws SystemException
* @throws NoSuchDossierStatusException
* @throws PortalException
*/
public void updateDossierStatus(
long userId, long dossierId, int syncStatus,
List<WorkflowOutput> worklows)
throws SystemException, NoSuchDossierStatusException, PortalException {
Date now = new Date();
for (WorkflowOutput output : worklows) {
DossierFile dossierFile =
dossierFileLocalService.getDossierFileInUse(
dossierId, output.getDossierPartId());
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
if (userId != 0) {
dossierFile.setUserId(userId);
}
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
/**
* @param userId
* @param dossierId
* @param syncStatus
* @throws SystemException
* @throws NoSuchDossierStatusException
* @throws PortalException
*/
public void updateDossierStatus(
long userId, long dossierId, long fileGroupId, int syncStatus)
throws SystemException, NoSuchDossierStatusException, PortalException {
Date now = new Date();
List<DossierFile> dossierFiles =
dossierFileLocalService.getDossierFileByD_GF(dossierId, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
if (userId != 0) {
dossierFile.setUserId(userId);
}
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
}
/**
* @param userId
* @param groupId
* @param companyId
* @param dossierId
* @param fileGroupId
* @param receptionNo
* @param estimateDatetime
* @param receiveDatetime
* @param finishDatetime
* @param dossierStatus
* @param actionInfo
* @param messageInfo
* @throws PortalException
* @throws SystemException
*/
public void updateDossierStatus(
long userId, long groupId, long companyId, long dossierId,
long fileGroupId, String receptionNo, Date estimateDatetime,
Date receiveDatetime, Date finishDatetime, String dossierStatus,
String actionInfo, String messageInfo)
throws PortalException, SystemException {
Dossier dossier = dossierPersistence.fetchByPrimaryKey(dossierId);
dossier.setReceptionNo(receptionNo);
dossier.setEstimateDatetime(estimateDatetime);
dossier.setReceiveDatetime(receiveDatetime);
dossier.setFinishDatetime(finishDatetime);
dossier.setDossierStatus(dossierStatus);
dossierPersistence.update(dossier);
// add DossierLog
dossierLogLocalService.addDossierLog(
userId, groupId, companyId, dossierId, fileGroupId,
PortletConstants.DOSSIER_STATUS_WAITING, actionInfo, messageInfo,
new Date(), 1);
}
/**
* @param userId
* @param dossierId
* @param govAgencyOrganizationId
* @param status
* @param syncStatus
* @param fileGroupId
* @param level
* @param locale
* @return
* @throws SystemException
* @throws NoSuchDossierStatusException
* @throws PortalException
*/
public Dossier updateDossierStatus(
long userId, long dossierId, long govAgencyOrganizationId,
String status, int syncStatus, long fileGroupId, int level,
Locale locale)
throws SystemException, NoSuchDossierStatusException, PortalException {
//TODO check again
Date now = new Date();
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
dossier = getDossier(dossier, userId, govAgencyOrganizationId, status);
int flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC;
if (syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCSUCCESS ||
syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCERROR) {
flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_REQUIREDSYNC;
}
if (fileGroupId > 0) {
FileGroup fileGroup =
fileGroupLocalService.getFileGroup(fileGroupId);
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(
fileGroupId, dossierId, flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFile.setUserId(userId);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
fileGroup.setSyncStatus(syncStatus);
fileGroup.setModifiedDate(now);
fileGroup.setUserId(userId);
fileGroupLocalService.updateFileGroup(fileGroup);
}
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(0, dossierId, flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFile.setUserId(userId);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
/* dossierLogLocalService.addDossierLog(
userId, dossier.getGroupId(), dossier.getCompanyId(), dossierId,
fileGroupId, status, PortletUtil.getActionInfo(status, locale),
PortletUtil.getMessageInfo(status, locale), now, level);
*/
dossierLogLocalService.addDossierLog(
userId, dossier.getGroupId(), dossier.getCompanyId(), dossierId,
fileGroupId, status, PortletUtil.getActionInfo(status, locale),
PortletUtil.getMessageInfo(status, locale), now, level);
dossierPersistence.update(dossier);
return dossier;
}
public Dossier updateDossierStatus(
long userId, long dossierId, long govAgencyOrganizationId,
String status, int syncStatus, long fileGroupId, int level,
Locale locale, int actor, long actorId, String actorName)
throws SystemException, NoSuchDossierStatusException, PortalException {
Date now = new Date();
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
dossier = getDossier(dossier, userId, govAgencyOrganizationId, status);
int flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC;
if (syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCSUCCESS ||
syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCERROR) {
flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_REQUIREDSYNC;
}
if (fileGroupId > 0) {
FileGroup fileGroup =
fileGroupLocalService.getFileGroup(fileGroupId);
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(
fileGroupId, dossierId, flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFile.setUserId(userId);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
fileGroup.setSyncStatus(syncStatus);
fileGroup.setModifiedDate(now);
fileGroup.setUserId(userId);
fileGroupLocalService.updateFileGroup(fileGroup);
}
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(0, dossierId, flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFile.setUserId(userId);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
dossierLogLocalService.addDossierLog(
userId, dossier.getGroupId(), dossier.getCompanyId(), dossierId,
fileGroupId, status, PortletUtil.getActionInfo(status, locale),
StringPool.BLANK, now, level);
dossierPersistence.update(dossier);
return dossier;
}
/**
* @param dossierId
* @param fileGroupId
* @param dossierStatus
* @param receptionNo
* @param estimateDatetime
* @param receiveDatetime
* @param finishDatetime
* @param actor
* @param requestCommand
* @param actionInfo
* @param messageInfo
* @return
*/
public boolean updateDossierStatus(
long dossierId, long fileGroupId, String dossierStatus,
String receptionNo, Date submitDatetime, Date estimateDatetime,
Date receiveDatetime, Date finishDatetime, int actor, long actorId, String actorName,
String requestCommand, String actionInfo, String messageInfo) {
boolean result = false;
try {
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
dossier.setReceptionNo(receptionNo);
dossier.setEstimateDatetime(estimateDatetime);
if (Validator.isNull(dossier.getReceiveDatetime())) {
dossier.setReceiveDatetime(receiveDatetime);
}
if (Validator.isNull(dossier.getSubmitDatetime())) {
dossier.setSubmitDatetime(submitDatetime);
}
dossier.setFinishDatetime(finishDatetime);
dossier.setDossierStatus(dossierStatus);
int level = 0;
if (dossier.getDossierStatus().equals(
PortletConstants.DOSSIER_STATUS_ERROR)) {
level = 2;
}
else if (dossier.getDossierStatus().equals(
PortletConstants.DOSSIER_STATUS_WAITING) ||
dossier.getDossierStatus().equals(
PortletConstants.DOSSIER_STATUS_PAYING)) {
level = 1;
}
dossierLogLocalService.addDossierLog(
dossier.getUserId(), dossier.getGroupId(),
dossier.getCompanyId(), dossierId, fileGroupId, dossierStatus,
actor, actorId, actorName, requestCommand, actionInfo, messageInfo, level);
dossierPersistence.update(dossier);
result = true;
}
catch (Exception e) {
result = false;
}
return result;
}
/**
* @param dossierId
* @param fileGroupId
* @param dossierStatus
* @param actor
* @param requestCommand
* @param actionInfo
* @param messageInfo
* @param syncStatus
* @param level
* @throws SystemException
* @throws PortalException
*/
public void updateDossierStatus(
long dossierId, long fileGroupId, String dossierStatus, int actor, long actorId, String actorName,
String requestCommand, String actionInfo, String messageInfo,
int syncStatus, int level)
throws SystemException, PortalException {
Date now = new Date();
Dossier dossier = dossierPersistence.findByPrimaryKey(dossierId);
int flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC;
if (syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCSUCCESS ||
syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCERROR) {
flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_REQUIREDSYNC;
}
if (fileGroupId > 0) {
FileGroup fileGroup =
fileGroupLocalService.getFileGroup(fileGroupId);
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(
fileGroupId, dossierId, flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
fileGroup.setSyncStatus(syncStatus);
fileGroup.setModifiedDate(now);
fileGroupLocalService.updateFileGroup(fileGroup);
}
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(0, dossierId, flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
dossier.setDossierStatus(dossierStatus);
dossier.setModifiedDate(new Date());
dossierLogLocalService.addDossierLog(
dossier.getUserId(), dossier.getGroupId(), dossier.getCompanyId(),
dossierId, fileGroupId, dossierStatus, actor, actorId, actorName, requestCommand,
actionInfo, messageInfo, level);
dossierPersistence.update(dossier);
}
/**
* @param oId
* @param fileGroupIds
* @param syncStatus
* @throws SystemException
* @throws NoSuchDossierStatusException
* @throws PortalException
*/
public void updateSyncStatus(
String oId, List<Long> fileGroupIds, int syncStatus)
throws SystemException, NoSuchDossierStatusException, PortalException {
Date now = new Date();
Dossier dossier = dossierLocalService.getByoid(oId);
int flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC;
if (syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCSUCCESS ||
syncStatus == PortletConstants.DOSSIER_FILE_SYNC_STATUS_SYNCERROR) {
flagStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_REQUIREDSYNC;
}
if (fileGroupIds != null) {
for (long fileGroupId : fileGroupIds) {
FileGroup fileGroup =
fileGroupLocalService.getFileGroup(fileGroupId);
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(
fileGroupId, dossier.getDossierId(), flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
fileGroup.setSyncStatus(syncStatus);
fileGroup.setModifiedDate(now);
fileGroupLocalService.updateFileGroup(fileGroup);
}
}
List<DossierFile> dossierFiles =
dossierFileLocalService.findByF_D_S_R(
0, dossier.getDossierId(), flagStatus, 0);
if (dossierFiles != null) {
for (DossierFile dossierFile : dossierFiles) {
dossierFile.setSyncStatus(syncStatus);
dossierFile.setModifiedDate(now);
dossierFileLocalService.updateDossierFile(dossierFile);
}
}
}
/**
* @param serviceinfoId
* @return
* @throws SystemException
*/
public List<Dossier> getDossiersByServiceInfo(long serviceinfoId)
throws SystemException {
return dossierPersistence.findByServiceInfoId(serviceinfoId);
}
public List<Dossier> getDossierByG_DS_U(
long groupId, String dossierStatus, long userId, int start, int end)
throws SystemException {
return dossierPersistence.findByG_DS_U(
groupId, dossierStatus, userId, start, end);
}
public int countDossierByG_DS_U(
long groupId, String dossierStatus, long userId)
throws SystemException {
return dossierPersistence.countByG_DS_U(groupId, dossierStatus, userId);
}
/**
* @param groupId
* @param userId
* @return
*/
public int countDossierByUserNewRequest(long groupId, long userId) {
return dossierFinder.countDossierByUserNewRequest(groupId, userId);
}
/**
* @param groupId
* @param userId
* @param start
* @param end
* @param obc
* @return
*/
public List getDossierByUserNewRequest(
long groupId, long userId, int start, int end, OrderByComparator obc) {
return dossierFinder.searchDossierByUserNewRequest(
groupId, userId, start, end, obc);
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.synchronization.net;
import com.kyloth.serleena.BuildConfig;
import com.kyloth.serleena.synchronization.AuthException;
import com.kyloth.serleena.synchronization.kylothcloud.IKylothIdSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, emulateSdk = 19)
public class SerleenaJSONNetProxyNotAuthorizedTest {
private SerleenaJSONNetProxy proxy;
private SerleenaConnectionFactory factory = mock(SerleenaConnectionFactory.class);
final String PREAUTH_TOKEN = "Foo";
final String KYLOTH_ID = "Bar";
final URL BASE_URL;
{URL BASE_URL1;
try {
BASE_URL1 = new URL("http://localhost");
} catch (MalformedURLException e) {
BASE_URL1 = null;
}
BASE_URL = BASE_URL1;
}
private HttpURLConnection urlConnection = mock(HttpURLConnection.class);
private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private void initializeMocks () throws IOException {
when(factory.createURLConnection(any(URL.class))).thenReturn(urlConnection);
when(urlConnection.getOutputStream()).thenReturn(outputStream);
when(urlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
when(urlConnection.getContentType()).thenReturn("text/plain");
when(urlConnection.getInputStream()).thenAnswer(
new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return new ByteArrayInputStream(PREAUTH_TOKEN.getBytes());
}
});
}
public SerleenaJSONNetProxyNotAuthorizedTest() {
try {
initializeMocks();
} catch (IOException e) {}
}
@Before
public void initialize() throws MalformedURLException {
IKylothIdSource entry = new IKylothIdSource() {
@Override
public String getKylothId() {
return KYLOTH_ID;
}
};
proxy = new SerleenaJSONNetProxy(new URL("http://localhost"), entry, factory);
}
@Test
public void preAuthTest() throws AuthException, IOException {
String preAuth = proxy.preAuth();
assertEquals(preAuth, PREAUTH_TOKEN);
}
/**
* Verifica che auth senza preauth sollevi una RuntimeException
*/
@Test(expected = RuntimeException.class)
public void testAuthWithoutPreauthNotAllowed() throws AuthException, IOException {
proxy.auth();
}
/**
* Verifica che chiamare auth due volte sollevi una RuntimeException
* @throws AuthException
* @throws IOException
*/
@Test(expected = RuntimeException.class)
public void testTwiceAuthNotAllowed() throws AuthException, IOException {
String preAuth = proxy.preAuth();
assertEquals(preAuth, PREAUTH_TOKEN);
proxy.auth();
proxy.auth();
}
/**
* Verifica che sia possibile ripetere preauth (ottenendo il reset).
* @throws AuthException
* @throws IOException
*/
@Test
public void testMultiplePreauthAllowed() throws AuthException, IOException {
String preAuth = proxy.preAuth();
assertEquals(preAuth, PREAUTH_TOKEN);
proxy.auth();
preAuth = proxy.preAuth();
assertEquals(preAuth, PREAUTH_TOKEN);
proxy.auth();
proxy.send();
}
/**
* Verifica che chiamare send() senza auth risulti in una AuthException.
* @throws AuthException
* @throws IOException
*/
@Test(expected = AuthException.class)
public void testSendWithoutAuthNotAllowed() throws AuthException, IOException {
proxy.send();
}
/**
* Verifica che se error 500 preauth sollevi AuthException
*/
@Test(expected = AuthException.class)
public void testPreauthAuthExceptionOn500() throws AuthException, IOException {
when(urlConnection.getResponseCode()).thenReturn(500);
proxy.preAuth();
}
/**
* Verifica che se error 403 preauth sollevi AuthException
*/
@Test(expected = AuthException.class)
public void testPreauthAuthExceptionOn403() throws AuthException, IOException {
when(urlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN);
proxy.preAuth();
}
/**
* Verifica che se urlConnection == null disconnect sollevi RuntimeException
*/
@Test(expected = RuntimeException.class)
public void testDisconnectRuntimeExcpetion () throws RuntimeException {
proxy.disconnect();
}
/**
* Verifica che se urlConnection != null get sollevi RuntimeException
*/
@Test(expected = RuntimeException.class)
public void testGetAuthException () throws IOException, AuthException {
proxy.preAuth();
proxy.auth();
proxy.get();
proxy.get();
}
/**
* Verifica che se contentType != text/plain preAuth sollevi IOException
*/
@Test(expected = IOException.class)
public void testPreAuthExcpetionOnWrongContentType () throws IOException, AuthException {
when(urlConnection.getContentType()).thenReturn("text/hidden");
proxy.preAuth();
}
/**
* Verifica che non sia possibile autenticarsi dopo una get
*/
@Test(expected = RuntimeException.class)
public void testAuthAfterGet () throws AuthException, IOException {
proxy.preAuth();
proxy.auth();
proxy.get();
proxy.auth();
}
/**
* Verifica che non sia possibile autenticarsi dopo una send
*/
@Test(expected = RuntimeException.class)
public void testAuthAfterSend () throws AuthException, IOException {
proxy.preAuth();
proxy.auth();
proxy.send();
proxy.auth();
}
}
|
package alda.repl;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jline.console.ConsoleReader;
import jline.console.completer.Completer;
import org.fusesource.jansi.AnsiConsole;
import org.fusesource.jansi.Ansi.Color;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
import alda.AldaServer;
import alda.AldaClient;
import alda.AldaResponse;
import alda.AldaResponse.AldaScore;
import alda.Util;
import alda.repl.commands.ReplCommand;
import alda.repl.commands.ReplCommandManager;
public class AldaRepl {
public static final String ASCII_ART =
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n";
public static final int ASCII_WIDTH = ASCII_ART.substring(0, ASCII_ART.indexOf('\n')).length();
public static final String HELP_TEXT = "Type :help for a list of available commands.";
public static final String PROMPT = "> ";
public static final int DEFAULT_NUMBER_OF_WORKERS = 2;
private AldaServer server;
private ConsoleReader r;
private boolean verbose;
private ReplCommandManager manager;
private StringBuffer history;
private String promptPrefix = "";
public AldaRepl(AldaServer server, boolean verbose) {
this.server = server;
server.setQuiet(true);
this.verbose = verbose;
history = new StringBuffer();
manager = new ReplCommandManager();
try {
r = new ConsoleReader();
} catch (IOException e) {
System.err.println("An error was detected when we tried to read a line.");
e.printStackTrace();
System.exit(1);
}
AnsiConsole.systemInstall();
}
/**
* Centers and colors text
* @param totalLen the total length to center to
* @param toFormat the string to format
* @param color the ANSI code to color. null will result in no color
*/
private String centerText(int totalLen, String toFormat, Color color) {
int offset = totalLen / 2 - toFormat.length() / 2;
String out = "";
if (offset > 0) {
// Print out spaces to center the version string
out = out + String.format("%1$"+offset+"s", " ");
}
out = out + toFormat;
if (color != null) {
out = ansi().fg(color).a(out).reset().toString();
}
return out;
}
/**
* Sanitizes instruments to remove their inst id.
* guitar-IrqxY becomes guitar
*/
public String sanitizeInstrument(String instrument) {
return instrument.replaceFirst("-\\w+$", "");
}
/**
* Converts the current instrument to it's prefix form
* For example, midi-square-wave becomes msw
*/
public String instrumentToPrefix(String instrument) {
// Split on non-words
String[] parts = instrument.split("\\W");
StringBuffer completedName = new StringBuffer();
// Build new name on first char of every part from the above split.
for (String s : parts) {
if (s.length() > 0)
completedName.append(s.charAt(0));
}
return completedName.toString();
}
public void setPromptPrefix(AldaScore score) {
if (score != null
&& score.currentInstruments() != null
&& score.currentInstruments().size() > 0) {
Set<String> instruments = score.currentInstruments();
boolean nicknameFound = false;
String newPrompt = null;
if (score.nicknames != null) {
// Convert nick -> inst map to inst -> nick
for (Map.Entry<String, Set<String>> entry : score.nicknames.entrySet()) {
// Check to see if we are playing any instruments from the nickname value set.
Set<String> val = entry.getValue();
// This destroys the nicknames value sets in the process.
val.retainAll(instruments);
if (val.size() > 0) {
// Remove a possible period seperator, IE: nickname.piano
newPrompt = entry.getKey().replaceFirst("\\.\\w+$", "");
newPrompt = instrumentToPrefix(newPrompt);
break;
}
}
}
// No groups found, translate instruments normally:
if (newPrompt == null) {
newPrompt =
score.currentInstruments().stream()
// Translate instruments to nicknames if available
.map(this::sanitizeInstrument)
// Translate midi-electric-piano-1 -> mep1
.map(this::instrumentToPrefix)
// Combine all instruments with /
.reduce("", (a, b) -> a + "/" + b)
// remove leading / (which is always present)
.substring(1);
}
if (newPrompt != null && newPrompt.length() > 0) {
promptPrefix = newPrompt;
return;
}
}
// If we failed anywhere, reset prompt (probably no instruments playing).
promptPrefix = "";
}
private void offerToStartServer() {
System.out.println("The server is down. Start server on port " +
server.port + "?");
try {
switch (Util.promptWithChoices(r, Arrays.asList("yes", "no", "quit"))) {
case "yes":
try {
System.out.println();
server.setQuiet(false);
server.upBg(DEFAULT_NUMBER_OF_WORKERS);
server.setQuiet(true);
} catch (Throwable e) {
System.err.println("Unable to start server:");
e.printStackTrace();
}
break;
case "no":
// do nothing
break;
case "quit":
System.exit(0);
default:
// this shouldn't happen; if it does, just move on
break;
}
} catch (IOException e) {
System.err.println("Error trying to read character:");
e.printStackTrace();
}
System.out.println();
}
public void run() {
System.out.println(ansi().fg(BLUE).a(ASCII_ART).reset());
System.out.println(centerText(ASCII_WIDTH, AldaClient.version(), CYAN));
System.out.println(centerText(ASCII_WIDTH, "repl session", CYAN));
System.out.println("\n" + ansi().fg(WHITE).bold().a(HELP_TEXT).reset() + "\n");
if (!server.checkForConnection()) {
offerToStartServer();
}
while (true) {
String input = "";
try {
// TODO add dynamic prompts based on the instrument
input = r.readLine(promptPrefix + PROMPT);
} catch (IOException e) {
System.err.println("An error was detected when we tried to read a line.");
e.printStackTrace();
System.exit(1);
}
// Check for quick quit keywords. input is null when we get EOF
if (input == null || input.matches("^:?(quit|exit|bye).*")) {
// If we got an EOF, we need to print a line, so we quit on a newline
if (input == null)
System.out.println();
// Let the master quit function handle this.
input = ":quit";
}
if (input.length() == 0) {
// Don't do anything if we get no input
continue;
}
// check for :keywords and act on them
if (input.charAt(0) == ':') {
// throw away ':'
input = input.substring(1);
// This limits size of splitString to 2 elements.
// All arguments will be in splitString[1]
String[] splitString = input.split("\\s", 2);
ReplCommand cmd = manager.get(splitString[0]);
if (cmd != null) {
// pass in empty string if we have no arguments
String arguments = splitString.length > 1 ? splitString[1] : "";
// Run the command
try {
cmd.act(arguments.trim(), history, server, r, this::setPromptPrefix);
} catch (alda.NoResponseException e) {
System.out.println();
offerToStartServer();
}
} else {
System.err.println("No command '" + splitString[0] + "' was found");
}
} else {
try {
// Play the stuff we just got, with history as context
AldaResponse playResponse = server.playFromRepl(
input, history.toString(), null, null, false
);
// If we have no exceptions, add to history
history.append(input);
history.append("\n");
// If we're good, we should check to see if we reset the instrument
if (playResponse != null) {
this.setPromptPrefix(playResponse.score);
}
} catch (alda.NoResponseException e) {
System.out.println();
offerToStartServer();
} catch (Throwable e) {
server.error(e.getMessage());
if (verbose) {
System.out.println();
e.printStackTrace();
}
}
}
}
}
}
|
package com.mkl.eu.service.service.domain.impl;
import com.mkl.eu.client.common.exception.IConstantsCommonException;
import com.mkl.eu.client.common.util.CommonUtil;
import com.mkl.eu.client.service.util.CounterUtil;
import com.mkl.eu.client.service.util.GameUtil;
import com.mkl.eu.client.service.vo.country.PlayableCountry;
import com.mkl.eu.client.service.vo.enumeration.*;
import com.mkl.eu.client.service.vo.tables.Exchequer;
import com.mkl.eu.client.service.vo.tables.Result;
import com.mkl.eu.client.service.vo.tables.TradeIncome;
import com.mkl.eu.service.service.domain.ICounterDomain;
import com.mkl.eu.service.service.domain.IStatusWorkflowDomain;
import com.mkl.eu.service.service.persistence.IGameDao;
import com.mkl.eu.service.service.persistence.board.ICounterDao;
import com.mkl.eu.service.service.persistence.eco.IEconomicalSheetDao;
import com.mkl.eu.service.service.persistence.oe.GameEntity;
import com.mkl.eu.service.service.persistence.oe.board.CounterEntity;
import com.mkl.eu.service.service.persistence.oe.board.StackEntity;
import com.mkl.eu.service.service.persistence.oe.country.PlayableCountryEntity;
import com.mkl.eu.service.service.persistence.oe.diff.DiffAttributesEntity;
import com.mkl.eu.service.service.persistence.oe.diff.DiffEntity;
import com.mkl.eu.service.service.persistence.oe.diplo.CountryInWarEntity;
import com.mkl.eu.service.service.persistence.oe.diplo.CountryOrderEntity;
import com.mkl.eu.service.service.persistence.oe.diplo.WarEntity;
import com.mkl.eu.service.service.persistence.oe.eco.EconomicalSheetEntity;
import com.mkl.eu.service.service.persistence.oe.military.BattleEntity;
import com.mkl.eu.service.service.persistence.oe.military.SiegeEntity;
import com.mkl.eu.service.service.persistence.oe.ref.province.AbstractProvinceEntity;
import com.mkl.eu.service.service.persistence.ref.IProvinceDao;
import com.mkl.eu.service.service.service.impl.AbstractBack;
import com.mkl.eu.service.service.util.DiffUtil;
import com.mkl.eu.service.service.util.IOEUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Domain for cross service methods around status workflow.
*
* @author MKL.
*/
@Component
public class StatusWorkflowDomainImpl extends AbstractBack implements IStatusWorkflowDomain {
/** Counter domain. */
@Autowired
private ICounterDomain counterDomain;
/** OeUtil. */
@Autowired
private IOEUtil oeUtil;
/** Province Dao. */
@Autowired
private IProvinceDao provinceDao;
/** Game DAO only for flush purpose because Hibernate poorly handles non technical ids and also to retrieve ids of created entities. */
@Autowired
private IGameDao gameDao;
/** Counter Dao. */
@Autowired
private ICounterDao counterDao;
/** EconomicalSheet DAO. */
@Autowired
private IEconomicalSheetDao economicalSheetDao;
/** {@inheritDoc} */
@Override
public List<DiffEntity> computeEndAdministrativeActions(GameEntity game) {
// TODO TG-18 check minors at war
return initMilitaryPhase(game);
}
/** {@inheritDoc} */
@Override
public List<DiffEntity> computeEndMinorLogistics(GameEntity game) {
return initMilitaryPhase(game);
}
/**
* Initialize the military phase.
*
* @param game the game.
* @return the List of Diff.
*/
private List<DiffEntity> initMilitaryPhase(GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
Map<PlayableCountryEntity, Integer> initiatives = game.getCountries().stream()
.filter(country -> StringUtils.isNotEmpty(country.getUsername()))
.collect(Collectors.toMap(Function.identity(), oeUtil::getInitiative));
/**
* First: we extract all groups (alliance in war = group) that will
* move at the same initiative.
*/
List<Alliance> alliances = new ArrayList<>();
for (WarEntity war : game.getWars()) {
List<PlayableCountryEntity> offCountries = new ArrayList<>();
List<PlayableCountryEntity> defCountries = new ArrayList<>();
war.getCountries().stream()
.filter(countryWar -> countryWar.getImplication() == WarImplicationEnum.FULL)
.forEach(countryWar -> {
PlayableCountryEntity country = game.getCountries().stream()
.filter(c -> StringUtils.equals(c.getName(), countryWar.getCountry().getName()))
.findFirst()
.orElse(null);
if (country != null) {
if (countryWar.isOffensive()) {
offCountries.add(country);
} else {
defCountries.add(country);
}
}
});
Alliance offAlliance = new Alliance(offCountries, offCountries.stream()
.map(initiatives::get)
.min(Comparator.naturalOrder())
.orElse(0));
alliances.add(offAlliance);
Alliance defAlliance = new Alliance(defCountries, defCountries.stream()
.map(initiatives::get)
.min(Comparator.naturalOrder())
.orElse(0));
alliances.add(defAlliance);
}
Alliance.fusion(alliances);
/**
* Then we add the countries that are not in war.
*/
game.getCountries().stream()
.filter(country -> StringUtils.isNotEmpty(country.getUsername()))
.forEach(country -> {
Alliance alliance = alliances.stream()
.filter(all -> all.getCountries().contains(country))
.findFirst()
.orElse(null);
if (alliance == null) {
alliance = new Alliance(Collections.singletonList(country), initiatives.get(country));
alliances.add(alliance);
}
});
/**
* Finally, previous order is removed.
*/
game.getOrders().clear();
/**
* Hibernate will delete old values after inserting new one.
* And since the PK is often the same, it will fail.
* We need to flush so that the old values are deleted before.
*/
this.gameDao.flush();
/**
* And the alliances are transformed into CountryOrder.
*/
Collections.sort(alliances, Comparator.comparing(Alliance::getInitiative).reversed());
for (int i = 0; i < alliances.size(); i++) {
for (PlayableCountryEntity country : alliances.get(i).getCountries()) {
CountryOrderEntity order = new CountryOrderEntity();
order.setGame(game);
order.setCountry(country);
order.setPosition(i);
game.getOrders().add(order);
}
}
diffs.addAll(nextRound(game, true));
return diffs;
}
/** {@inheritDoc} */
@Override
public List<DiffEntity> endMilitaryPhase(GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
// If we are in battle phase, are there still some battle left ?
if (game.getStatus() == GameStatusEnum.MILITARY_BATTLES &&
game.getBattles().stream().anyMatch(battle -> Objects.equals(battle.getTurn(), game.getTurn())
&& battle.getStatus() == BattleStatusEnum.NEW)) {
return diffs;
}
int currentPosition = game.getOrders().stream()
.filter(CountryOrderEntity::isActive)
.map(CountryOrderEntity::getPosition)
.findFirst()
.orElse(Integer.MAX_VALUE);
// If we are in siege phase, are there still some siege left ?
if (game.getStatus() == GameStatusEnum.MILITARY_SIEGES &&
game.getSieges().stream().anyMatch(siege -> Objects.equals(siege.getTurn(), game.getTurn())
&& siege.getStatus() == SiegeStatusEnum.NEW)) {
Integer activeSiege = game.getSieges().stream()
.filter(siege -> Objects.equals(siege.getTurn(), game.getTurn()) && siege.getStatus() == SiegeStatusEnum.NEW)
.map(siege -> getActiveOrder(siege.getWar(), siege.isBesiegingOffensive(), game))
.filter(Objects::nonNull)
.min(Comparator.<Integer>naturalOrder())
.orElse(null);
if (activeSiege != currentPosition) {
diffs.add(changeActivePlayers(activeSiege, game));
}
return diffs;
}
// Are there somme battles ?
List<String> provincesAtWar = game.getStacks().stream()
.filter(s -> s.getMovePhase() == MovePhaseEnum.FIGHTING)
.map(StackEntity::getProvince)
.distinct()
.collect(Collectors.toList());
if (!provincesAtWar.isEmpty()) {
// Yes -> battle phase !
game.setStatus(GameStatusEnum.MILITARY_BATTLES);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.MILITARY_BATTLES)));
for (String province : provincesAtWar) {
BattleEntity battle = new BattleEntity();
battle.setProvince(province);
battle.setTurn(game.getTurn());
battle.setStatus(BattleStatusEnum.NEW);
battle.setGame(game);
List<CounterEntity> phasingCounters = game.getStacks().stream()
.filter(s -> s.getMovePhase() == MovePhaseEnum.FIGHTING && StringUtils.equals(province, s.getProvince()))
.flatMap(s -> s.getCounters().stream())
.collect(Collectors.toList());
List<CounterEntity> nonPhasingCounters = game.getStacks().stream()
.filter(s -> s.getMovePhase() != MovePhaseEnum.FIGHTING && StringUtils.equals(province, s.getProvince()))
.flatMap(s -> s.getCounters().stream())
.filter(c -> CounterUtil.isArmy(c.getType()))
.collect(Collectors.toList());
Pair<WarEntity, Boolean> war = oeUtil.searchWar(phasingCounters, nonPhasingCounters, game);
battle.setWar(war.getLeft());
battle.setPhasingOffensive(war.getRight());
gameDao.persist(battle);
game.getBattles().add(battle);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.ADD, DiffTypeObjectEnum.BATTLE, battle.getId(),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.PROVINCE, province),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.TURN, game.getTurn()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, BattleStatusEnum.NEW),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ID_WAR, war.getLeft().getId()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.PHASING_OFFENSIVE, war.getRight())));
}
return diffs;
}
// Other cases: we check if there is another country in current phase of this round
Integer next = game.getOrders().stream()
.filter(o -> o.getPosition() > currentPosition)
.map(CountryOrderEntity::getPosition)
.min(Comparator.naturalOrder())
.orElse(null);
if (next != null) {
if (game.getStatus() == GameStatusEnum.MILITARY_SIEGES) {
Integer activeSiege = game.getSieges().stream()
.filter(siege -> Objects.equals(siege.getTurn(), game.getTurn()) && siege.getStatus() == SiegeStatusEnum.NEW)
.map(siege -> getActiveOrder(siege.getWar(), siege.isBesiegingOffensive(), game))
.filter(Objects::nonNull)
.min(Comparator.<Integer>naturalOrder())
.orElse(null);
if (activeSiege != null) {
diffs.add(changeActivePlayers(activeSiege, game));
} else {
diffs.addAll(nextRound(game));
}
} else {
if (game.getStatus() == GameStatusEnum.MILITARY_BATTLES) {
game.setStatus(GameStatusEnum.MILITARY_MOVE);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.MILITARY_MOVE)));
}
diffs.add(changeActivePlayers(next, game));
}
return diffs;
} else {
// There is no other country. If we are in move phase, check siege
if (game.getStatus() == GameStatusEnum.MILITARY_MOVE || game.getStatus() == GameStatusEnum.MILITARY_BATTLES) {
List<String> provincesAtSiege = game.getStacks().stream()
.filter(s -> s.getMovePhase() != null && s.getMovePhase().isBesieging())
.map(StackEntity::getProvince)
.distinct()
.collect(Collectors.toList());
if (!provincesAtSiege.isEmpty()) {
// Yes -> siege phase !
game.setStatus(GameStatusEnum.MILITARY_SIEGES);
for (String province : provincesAtSiege) {
SiegeEntity siege = new SiegeEntity();
siege.setProvince(province);
siege.setTurn(game.getTurn());
siege.setStatus(SiegeStatusEnum.NEW);
siege.setBreach(game.getSieges().stream()
.anyMatch(sie -> sie.isBreach() && Objects.equals(sie.getTurn(), game.getTurn()) && StringUtils.equals(sie.getProvince(), province)));
siege.setGame(game);
List<CounterEntity> besiegingCounters = game.getStacks().stream()
.filter(s -> s.getMovePhase() != null && s.getMovePhase().isBesieging() && StringUtils.equals(province, s.getProvince()))
.flatMap(s -> s.getCounters().stream())
.collect(Collectors.toList());
List<CounterEntity> besiegedCounters = game.getStacks().stream()
.filter(s -> s.isBesieged() && StringUtils.equals(province, s.getProvince()))
.flatMap(s -> s.getCounters().stream())
.filter(c -> CounterUtil.isArmy(c.getType()))
.collect(Collectors.toList());
besiegedCounters.add(createFakeControl(province, game));
Pair<WarEntity, Boolean> war = oeUtil.searchWar(besiegingCounters, besiegedCounters, game);
siege.setWar(war.getLeft());
siege.setBesiegingOffensive(war.getRight());
gameDao.persist(siege);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.ADD, DiffTypeObjectEnum.SIEGE, siege.getId(),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.PROVINCE, province),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.TURN, game.getTurn()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, SiegeStatusEnum.NEW),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ID_WAR, war.getLeft().getId()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.PHASING_OFFENSIVE, war.getRight())));
game.getSieges().add(siege);
}
Integer activeSiege = game.getSieges().stream()
.filter(siege -> Objects.equals(siege.getTurn(), game.getTurn()) && siege.getStatus() == SiegeStatusEnum.NEW)
.map(siege -> getActiveOrder(siege.getWar(), siege.isBesiegingOffensive(), game))
.filter(Objects::nonNull)
.min(Comparator.<Integer>naturalOrder())
.orElse(null);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.MILITARY_SIEGES)));
diffs.add(changeActivePlayers(activeSiege, game));
return diffs;
}
}
// If no siege or last country of siege round, compute next round
diffs.addAll(nextRound(game));
}
return diffs;
}
/**
* Change the active player in the non simultaneous phase.
*
* @param position the new position of the active player in the non simultaneous phase.
* @param game the game.
* @return the diff created.
*/
private DiffEntity changeActivePlayers(int position, GameEntity game) {
game.getOrders().stream()
.forEach(o -> {
o.setActive(false);
o.setReady(false);
});
game.getOrders().stream()
.filter(o -> o.getPosition() == position)
.forEach(o -> o.setActive(true));
return DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.TURN_ORDER,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ACTIVE, position),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.MILITARY_MOVE.name()));
}
/**
* @param province the province.
* @param game the game.
* @return a fake control counter owned by the controller of the province.
*/
private CounterEntity createFakeControl(String province, GameEntity game) {
AbstractProvinceEntity fullProvince = provinceDao.getProvinceByName(province);
String controller = oeUtil.getController(fullProvince, game);
CounterEntity fakeControlCounter = new CounterEntity();
fakeControlCounter.setCountry(controller);
fakeControlCounter.setType(CounterFaceTypeEnum.CONTROL);
return fakeControlCounter;
}
/**
* @param war the war.
* @param offensive the side.
* @param game the game.
* @return the active order of the offensive side of the war in this turn.
*/
private Integer getActiveOrder(WarEntity war, boolean offensive, GameEntity game) {
Predicate<CountryInWarEntity> filterPhasing;
if (offensive) {
filterPhasing = country -> country.isOffensive() && country.getImplication() == WarImplicationEnum.FULL;
} else {
filterPhasing = country -> !country.isOffensive() && country.getImplication() == WarImplicationEnum.FULL;
}
Function<CountryInWarEntity, Integer> toActiveOrder = country -> game.getOrders().stream()
.filter(order -> StringUtils.equals(country.getCountry().getName(), order.getCountry().getName()))
.map(CountryOrderEntity::getPosition)
.findAny()
.orElse(null);
return war.getCountries().stream()
.filter(filterPhasing)
.map(toActiveOrder)
.filter(Objects::nonNull)
.findAny()
.orElse(null);
}
/** {@inheritDoc} */
@Override
public List<DiffEntity> nextRound(GameEntity game) {
return nextRound(game, false);
}
/**
* Roll a die to go to next round (or first if init is <code>true</code>) and
* creates the diffs ot it.
* Does not handle good/bad weather at the moment.
*
* @param game to move to next round.
* @param init to know if it is the first round of the turn or not.
* @return the diffs representing the next round.
*/
protected List<DiffEntity> nextRound(GameEntity game, boolean init) {
List<DiffEntity> diffs = new ArrayList<>();
int die = oeUtil.rollDie(game, (PlayableCountryEntity) null);
if (init) {
String round;
switch (die) {
case 1:
round = "B_MR_W0";
break;
case 2:
case 3:
round = "B_MR_S1";
break;
case 4:
case 5:
round = "B_MR_S2";
break;
case 6:
round = "B_MR_W2";
break;
case 7:
case 8:
case 9:
case 10:
default:
round = "B_MR_S3";
break;
}
diffs.addAll(initNewRound(round, game));
} else {
String round = game.getStacks().stream()
.filter(stack -> GameUtil.isRoundBox(stack.getProvince()))
.flatMap(stack -> stack.getCounters().stream())
.filter(counter -> counter.getType() == CounterFaceTypeEnum.GOOD_WEATHER || counter.getType() == CounterFaceTypeEnum.BAD_WEATHER)
.map(counter -> counter.getOwner().getProvince())
.findFirst()
.orElse(null);
int roundNumber = GameUtil.getRoundBox(round);
String nextRound;
if (GameUtil.isWinterRoundBox(round)) {
if (die <= 7) {
nextRound = "B_MR_S" + (roundNumber + 1);
} else if (die == 8) {
nextRound = "B_MR_W" + (roundNumber + 1);
} else {
nextRound = "B_MR_S" + (roundNumber + 2);
}
} else {
if (die <= 5) {
nextRound = "B_MR_W" + roundNumber;
} else {
nextRound = "B_MR_S" + (roundNumber + 1);
}
}
switch (nextRound) {
case "B_MR_S6":
case "B_MR_W6":
case "B_MR_S7":
diffs.addAll(endRound(game));
break;
default:
diffs.addAll(initNewRound(nextRound, game));
break;
}
}
return diffs;
}
/**
* Computes the action at the end of a military round.
*
* @param nextRound the next season.
* @param game the game.
* @return the diffs created.
*/
private List<DiffEntity> initNewRound(String nextRound, GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
diffs.add(counterDomain.moveSpecialCounter(CounterFaceTypeEnum.GOOD_WEATHER, null, nextRound, game));
// Stacks move phase reset
game.getStacks().stream()
.filter(stack -> stack.getMovePhase() != null)
.forEach(stack -> {
stack.setMove(0);
if (stack.getMovePhase().isBesieging()) {
stack.setMovePhase(MovePhaseEnum.STILL_BESIEGING);
} else {
stack.setMovePhase(MovePhaseEnum.NOT_MOVED);
}
});
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.STACK,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.MOVE_PHASE, MovePhaseEnum.NOT_MOVED)));
// TODO TG-5 when leaders implemented, it will be MILITARY_HIERARCHY phase
game.setStatus(GameStatusEnum.MILITARY_MOVE);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
// TODO TG-5 when leaders implemented, it will be MILITARY_HIERARCHY phase
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.MILITARY_MOVE)));
// set the order of position 0 active
diffs.add(changeActivePlayers(0, game));
return diffs;
}
/**
* Computes the action at the end of the military phase.
*
* @param game the game.
* @return the diffs created.
*/
protected List<DiffEntity> endRound(GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
diffs.add(counterDomain.moveSpecialCounter(CounterFaceTypeEnum.GOOD_WEATHER, null, "B_MR_End", game));
game.setStatus(GameStatusEnum.REDEPLOYMENT);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.REDEPLOYMENT)));
// set the order of position 0 active
diffs.add(changeActivePlayers(0, game));
diffs.addAll(adjustPillages(game));
return diffs;
}
/**
* Remove one pillage from each province.
*
* @param game the game.
* @return the diffs involved.
*/
private List<DiffEntity> adjustPillages(GameEntity game) {
Map<String, List<CounterEntity>> pillagesPerProvince = game.getStacks().stream()
.flatMap(stack -> stack.getCounters().stream())
.filter(counter -> counter.getType() == CounterFaceTypeEnum.PILLAGE_MINUS || counter.getType() == CounterFaceTypeEnum.PILLAGE_PLUS)
.collect(Collectors.groupingBy(counter -> counter.getOwner().getProvince()));
List<DiffEntity> diffs = new ArrayList<>();
for (List<CounterEntity> pillages : pillagesPerProvince.values()) {
CounterEntity pillageMinus = pillages.stream()
.filter(counter -> counter.getType() == CounterFaceTypeEnum.PILLAGE_MINUS)
.findAny()
.orElse(null);
if (pillageMinus != null) {
diffs.add(counterDomain.removeCounter(pillageMinus.getId(), game));
} else {
CounterEntity pillagePlus = pillages.stream()
.filter(counter -> counter.getType() == CounterFaceTypeEnum.PILLAGE_PLUS)
.findAny()
.orElse(null);
if (pillagePlus != null) {
diffs.add(counterDomain.switchCounter(pillagePlus.getId(), CounterFaceTypeEnum.PILLAGE_MINUS, null, game));
}
}
}
return diffs;
}
/** {@inheritDoc} */
@Override
public List<DiffEntity> endRedeploymentPhase(GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
int currentPosition = game.getOrders().stream()
.filter(CountryOrderEntity::isActive)
.map(CountryOrderEntity::getPosition)
.findFirst()
.orElse(Integer.MAX_VALUE);
Integer next = game.getOrders().stream()
.filter(o -> o.getPosition() > currentPosition)
.map(CountryOrderEntity::getPosition)
.min(Comparator.naturalOrder())
.orElse(null);
if (next != null) {
diffs.add(changeActivePlayers(next, game));
} else {
diffs.addAll(adjustSiegeworks(game));
diffs.addAll(updateEcoSheet(game));
game.setStatus(GameStatusEnum.EXCHEQUER);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.EXCHEQUER),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ACTIVE, false)));
}
return diffs;
}
/**
* Only one siegework minus can remain if the province is still besieged.
*
* @param game the game.
* @return the diffs involved.
*/
private List<DiffEntity> adjustSiegeworks(GameEntity game) {
Map<String, List<CounterEntity>> siegeworksPerProvince = game.getStacks().stream()
.flatMap(stack -> stack.getCounters().stream())
.filter(counter -> counter.getType() == CounterFaceTypeEnum.SIEGEWORK_MINUS || counter.getType() == CounterFaceTypeEnum.SIEGEWORK_PLUS)
.collect(Collectors.groupingBy(counter -> counter.getOwner().getProvince()));
List<DiffEntity> diffs = new ArrayList<>();
for (String province : siegeworksPerProvince.keySet()) {
List<CounterEntity> siegeworks = siegeworksPerProvince.get(province);
boolean besieged = game.getStacks().stream()
.anyMatch(stack -> stack.getMovePhase() != null && stack.getMovePhase().isBesieging()
&& StringUtils.equals(province, stack.getProvince()));
if (!besieged) {
siegeworks.stream()
.forEach(siegework -> diffs.add(counterDomain.removeCounter(siegework.getId(), game)));
} else {
CounterEntity siegeworkRemain = siegeworks.stream()
.filter(counter -> counter.getType() == CounterFaceTypeEnum.SIEGEWORK_MINUS)
.findAny()
.orElse(siegeworks.stream()
.filter(counter -> counter.getType() == CounterFaceTypeEnum.SIEGEWORK_PLUS)
.findAny()
.orElse(null));
siegeworks.stream()
.filter(siegework -> !Objects.equals(siegeworkRemain.getId(), siegework.getId()))
.forEach(siegework -> diffs.add(counterDomain.removeCounter(siegework.getId(), game)));
if (siegeworkRemain.getType() == CounterFaceTypeEnum.SIEGEWORK_PLUS) {
diffs.add(counterDomain.switchCounter(siegeworkRemain.getId(), CounterFaceTypeEnum.SIEGEWORK_MINUS, null, game));
}
}
}
return diffs;
}
/**
* Compute the exceptional taxes and the exchequer test for each country.
*
* @param game the game.
* @return the diffs involved.
*/
private List<DiffEntity> updateEcoSheet(GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
for (PlayableCountryEntity country : game.getCountries()) {
EconomicalSheetEntity sheet = country.getEconomicalSheets().stream()
.filter(es -> Objects.equals(game.getTurn(), es.getTurn()))
.findAny()
.orElse(null);
if (sheet != null) {
List<DiffAttributesEntity> attributes = new ArrayList<>();
attributes.add(DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ID_COUNTRY, country.getId()));
attributes.addAll(computeExceptionalTaxes(sheet, country, game));
attributes.addAll(computeExchequer(sheet, country, game));
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.ECO_SHEET, sheet.getId(),
attributes.toArray(new DiffAttributesEntity[attributes.size()])));
country.setReady(false);
}
}
return diffs;
}
/**
* Compute the exceptional taxes for each country that has done one.
*
* @param sheet the economical sheet.
* @param country the country.
* @param game the game.
* @return the diffs involved.
*/
private List<DiffAttributesEntity> computeExceptionalTaxes(EconomicalSheetEntity sheet, PlayableCountryEntity country, GameEntity game) {
List<DiffAttributesEntity> diffs = new ArrayList<>();
if (sheet.getExcTaxesMod() != null) {
Integer die = oeUtil.rollDie(game, country);
sheet.setExcTaxes(10 * (die + sheet.getExcTaxesMod()));
diffs.add(DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXC_TAXES, sheet.getExcTaxes()));
}
return diffs;
}
/**
* Compute the exchequer test for each country.
*
* @param sheet the economical sheet.
* @param country the country.
* @param game the game.
* @return the diffs involved.
*/
private List<DiffAttributesEntity> computeExchequer(EconomicalSheetEntity sheet, PlayableCountryEntity country, GameEntity game) {
List<DiffAttributesEntity> diffs = new ArrayList<>();
sheet.setRtBefExch(CommonUtil.add(0, sheet.getRtDiplo(), sheet.getPillages(), sheet.getGoldRotw(), sheet.getExcTaxes()));
sheet.setExpenses(CommonUtil.add(0, sheet.getInterestExpense(), sheet.getMandRefundExpense(),
sheet.getAdmTotalExpense(), sheet.getMilitaryExpense()));
Integer stab = oeUtil.getStability(game, country.getName());
Integer exchequerMod = 0;
WarStatusEnum warStatus = oeUtil.getWarStatus(game, country);
if (warStatus == WarStatusEnum.PEACE) {
exchequerMod += 2;
}
// TODO TG-138 Loans and bankrupt
// TODO TG-18 loan treaty broken
Integer die = oeUtil.rollDie(game, country);
sheet.setExchequerColumn(stab);
sheet.setExchequerBonus(exchequerMod);
sheet.setExchequerDie(die);
int modifiedDie = Math.min(Math.max(die + exchequerMod, 1), 10);
ResultEnum result = getTables().getResults().stream()
.filter(res -> Objects.equals(stab, res.getColumn()) && Objects.equals(modifiedDie, res.getDie()))
.map(Result::getResult)
.findAny()
.orElseThrow(createTechnicalExceptionSupplier(IConstantsCommonException.MISSING_TABLE, MSG_MISSING_TABLE, "results", "column:" + stab + ",die:" + modifiedDie));
Exchequer exchequer = getTables().getExchequers().stream()
.filter(exc -> exc.getResult() == result)
.findAny()
.orElseThrow(createTechnicalExceptionSupplier(IConstantsCommonException.MISSING_TABLE, MSG_MISSING_TABLE, "exchequer", result.name()));
int grossIncome = sheet.getGrossIncome() != null ? sheet.getGrossIncome() : 0;
int regular = grossIncome * exchequer.getRegular() / 100;
int prestige = grossIncome * exchequer.getPrestige() / 100;
int loanRatio = exchequer.getNatLoan();
if (warStatus != WarStatusEnum.PEACE) {
loanRatio += 10;
}
// TODO TG-131 Spain +10 if expulsion
int loan = grossIncome * loanRatio / 100;
sheet.setRegularIncome(regular);
sheet.setPrestigeIncome(prestige);
sheet.setMaxNatLoan(loan);
// TODO TG-138 international loans
sheet.setRemainingExpenses(sheet.getExpenses() - sheet.getRegularIncome());
diffs.addAll(Arrays.asList(DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXCHEQUER_ROYAL_TREASURE, sheet.getRtBefExch()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXPENSES, sheet.getExpenses()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXCHEQUER_COL, sheet.getExchequerColumn()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXCHEQUER_MOD, sheet.getExchequerBonus()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXCHEQUER_DIE, sheet.getExchequerDie()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXCHEQUER_REGULAR, sheet.getRegularIncome()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXCHEQUER_PRESTIGE, sheet.getPrestigeIncome()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.EXCHEQUER_MAX_NAT_LOAN, sheet.getMaxNatLoan()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.REMAINING_EXPENSES, sheet.getRemainingExpenses())));
return diffs;
}
/** {@inheritDoc} */
@Override
public List<DiffEntity> endExchequerPhase(GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
for (PlayableCountryEntity country : game.getCountries()) {
EconomicalSheetEntity sheet = country.getEconomicalSheets().stream()
.filter(es -> Objects.equals(game.getTurn(), es.getTurn()))
.findAny()
.orElse(null);
if (sheet != null) {
int additionalIncomes = CommonUtil.add(0, sheet.getPrestigeSpent(), sheet.getNatLoan(), sheet.getInterLoan());
sheet.setRtBalance(additionalIncomes - sheet.getRemainingExpenses());
sheet.setRtAftExch(CommonUtil.add(sheet.getRtBefExch(), sheet.getRtBalance()));
sheet.setPrestigeVP(CommonUtil.subtract(sheet.getPrestigeIncome(), sheet.getPrestigeSpent()));
boolean firstTurnOfPeriod = getTables().getPeriods().stream()
.anyMatch(period -> Objects.equals(period.getBegin(), game.getTurn()));
sheet.setWealth(CommonUtil.add(sheet.getGrossIncome(), sheet.getPrestigeVP()));
if (firstTurnOfPeriod) {
sheet.setPeriodWealth(sheet.getWealth());
} else {
int previousWealth = country.getEconomicalSheets().stream()
.filter(es -> Objects.equals(game.getTurn() - 1, es.getTurn()))
.map(EconomicalSheetEntity::getPeriodWealth)
.findAny()
.orElse(0);
sheet.setPeriodWealth(CommonUtil.add(previousWealth, sheet.getWealth()));
}
sheet.setStabModifier(getStabilityModifier(country, game));
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.ECO_SHEET, sheet.getId(),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ID_COUNTRY, country.getId()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ROYAL_TREASURE_BALANCE, sheet.getRtBalance()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ROYAL_TREASURE_AFTER_EXCHEQUER, sheet.getRtAftExch()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.PRESTIGE_VPS, sheet.getPrestigeVP()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.WEALTH, sheet.getWealth()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.PERIOD_WEALTH, sheet.getPeriodWealth()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STAB_MODIFIER, sheet.getStabModifier())));
country.setReady(false);
}
}
game.setStatus(GameStatusEnum.STABILITY);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.STABILITY.name()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ACTIVE, false)));
return diffs;
}
/**
* Get stability modifier without investment part.
*
* @param country the country.
* @param game the game.
* @return the stability modifier.
*/
private int getStabilityModifier(PlayableCountryEntity country, GameEntity game) {
int modifier = oeUtil.getAdministrativeValue(country);
// TODO TG-18 wars
List<String> enemies = oeUtil.getEnemies(country, game);
// TODO TG-18 limited intervention
boolean warWithMajor = game.getCountries().stream()
.anyMatch(major -> StringUtils.isNotEmpty(major.getUsername()) && enemies.contains(major.getName()));
if (warWithMajor) {
modifier -= 3;
} else if (!enemies.isEmpty()) {
modifier -= 2;
}
// TODO -5 if enemy army in owned national province
if (!enemies.isEmpty()) {
List<String> provinces = counterDao.getNationalTerritoriesUnderAttack(country.getName(), enemies, game.getId());
if (!provinces.isEmpty()) {
if (StringUtils.equals(PlayableCountry.SPAIN, country.getName())) {
// TODO TG-13 some events will restore spain malus to -5
modifier -= 3;
} else {
modifier -= 5;
}
}
}
modifier += 3 * oeUtil.getProsperity(country, game);
// TODO TG-13 Events
return modifier;
}
/** {@inheritDoc} */
@Override
public List<DiffEntity> endStabilityPhase(GameEntity game) {
List<DiffEntity> diffs = new ArrayList<>();
int treshold = counterDao.getGoldExploitedRotw(game.getId()) >= 100 ? 3 : 7;
int rollDie = oeUtil.rollDie(game);
if (rollDie >= treshold) {
Optional<DiffEntity> diff = counterDomain.increaseInflation(game);
diff.ifPresent(diffs::add);
}
String inflationBox = oeUtil.getInflationBox(game);
for (PlayableCountryEntity country : game.getCountries()) {
EconomicalSheetEntity sheet = country.getEconomicalSheets().stream()
.filter(es -> Objects.equals(game.getTurn(), es.getTurn()))
.findAny()
.orElse(null);
if (sheet != null) {
sheet.setRtPeace(CommonUtil.toInt(sheet.getRtAftExch()) - CommonUtil.toInt(sheet.getStab()));
int americanGold = counterDao.getGoldExploitedAmerica(country.getName(), game.getId());
// TODO TG-131 Turkey before reforms has big inglation
int inflation = GameUtil.getInflation(inflationBox, americanGold > 0);
int computedInflation = (int) Math.ceil(((double) inflation * Math.abs(sheet.getRtPeace())) / 100);
int minInflation = oeUtil.getMinimalInflation(inflation, country.getName(), getTables(), game);
int actualInflation = Math.max(minInflation, computedInflation);
sheet.setInflation(actualInflation);
sheet.setRtEnd(sheet.getRtPeace() - actualInflation);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.ECO_SHEET, sheet.getId(),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ID_COUNTRY, country.getId()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ROYAL_TREASURE_PEACE, sheet.getRtPeace()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.INFLATION, sheet.getInflation()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ROYAL_TREASURE_END, sheet.getRtEnd())));
EconomicalSheetEntity nextSheet = new EconomicalSheetEntity();
nextSheet.setCountry(country);
nextSheet.setTurn(game.getTurn() + 1);
nextSheet.setRtStart(sheet.getRtEnd());
// TODO TG-13 events
nextSheet.setRtEvents(nextSheet.getRtStart());
// TODO TG-18 diplo phase
nextSheet.setRtDiplo(nextSheet.getRtStart());
economicalSheetDao.create(nextSheet);
country.getEconomicalSheets().add(nextSheet);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.ADD, DiffTypeObjectEnum.ECO_SHEET, nextSheet.getId(),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ID_COUNTRY, country.getId()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.TURN, nextSheet.getTurn()),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ROYAL_TREASURE_START, nextSheet.getRtStart())));
}
}
game.setTurn(game.getTurn() + 1);
diffs.add(counterDomain.moveSpecialCounter(CounterFaceTypeEnum.TURN, null, GameUtil.getTurnBox(game.getTurn()), game));
// TODO TG-13 events
game.setStatus(GameStatusEnum.ADMINISTRATIVE_ACTIONS_CHOICE);
diffs.add(DiffUtil.createDiff(game, DiffTypeEnum.MODIFY, DiffTypeObjectEnum.GAME,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.STATUS, GameStatusEnum.ADMINISTRATIVE_ACTIONS_CHOICE),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.ACTIVE, false),
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.TURN, game.getTurn())));
diffs.add(computeEconomicalSheets(game));
return diffs;
}
/** {@inheritDoc} */
public DiffEntity computeEconomicalSheets(GameEntity game) {
Map<String, List<CounterFaceTypeEnum>> tradeCenters = economicalSheetDao.getTradeCenters(game.getId());
for (PlayableCountryEntity country : game.getCountries()) {
if (StringUtils.isEmpty(country.getUsername())) {
continue;
}
EconomicalSheetEntity sheet = country.getEconomicalSheets().stream()
.filter(es -> Objects.equals(es.getTurn(), game.getTurn()))
.findAny()
.orElse(null);
if (sheet == null) {
sheet = new EconomicalSheetEntity();
sheet.setCountry(country);
sheet.setTurn(game.getTurn());
economicalSheetDao.create(sheet);
country.getEconomicalSheets().add(sheet);
}
String name = country.getName();
Map<String, Integer> allProvinces = new HashMap<>();
Map<String, Integer> provinces = economicalSheetDao.getOwnedAndControlledProvinces(name, game.getId());
sheet.setProvincesIncome(provinces.values().stream().collect(Collectors.summingInt(value -> value)));
Map<String, Integer> vassalProvinces = new HashMap<>();
List<String> vassals = counterDao.getVassals(name, game.getId());
for (String vassal : vassals) {
vassalProvinces.putAll(economicalSheetDao.getOwnedAndControlledProvinces(vassal, game.getId()));
}
sheet.setVassalIncome(vassalProvinces.values().stream().collect(Collectors.summingInt(value -> value)));
List<String> provinceNames = new ArrayList<>();
provinceNames.addAll(provinces.keySet());
provinceNames.addAll(vassalProvinces.keySet());
List<String> pillagedProvinces = economicalSheetDao.getPillagedProvinces(provinceNames, game.getId());
allProvinces.putAll(provinces);
allProvinces.putAll(vassalProvinces);
Integer pillagedIncome = pillagedProvinces.stream().collect(Collectors.summingInt(allProvinces::get));
sheet.setPillages(pillagedIncome);
Integer sum = CommonUtil.add(sheet.getProvincesIncome(), sheet.getVassalIncome(), sheet.getEventLandIncome());
if (sheet.getPillages() != null) {
sum -= sheet.getPillages();
}
sheet.setLandIncome(sum);
sheet.setMnuIncome(economicalSheetDao.getMnuIncome(name, pillagedProvinces, game.getId()));
List<String> provincesOwnedNotPilaged = provinces.keySet().stream().filter(s -> !pillagedProvinces.contains(s)).collect(Collectors.toList());
sheet.setGoldIncome(economicalSheetDao.getGoldIncome(provincesOwnedNotPilaged, game.getId()));
sheet.setIndustrialIncome(CommonUtil.add(sheet.getMnuIncome(), sheet.getGoldIncome()));
final Integer valueDom = CommonUtil.add(sheet.getProvincesIncome(), sheet.getVassalIncome());
TradeIncome tradeIncome = CommonUtil.findFirst(getTables().getDomesticTrades(), tradeIncome1 -> tradeIncome1.getCountryValue() == country.getDti()
&& (tradeIncome1.getMinValue() == null || tradeIncome1.getMinValue() <= valueDom)
&& (tradeIncome1.getMaxValue() == null || tradeIncome1.getMaxValue() >= valueDom)
);
if (tradeIncome != null) {
sheet.setDomTradeIncome(tradeIncome.getValue());
}
// TODO needs War to know the blocked trade
// TODO move elsewhere because we need to know the land income
// of all countries.
final Integer valueFor = 0;
tradeIncome = CommonUtil.findFirst(getTables().getForeignTrades(), tradeIncome1 -> tradeIncome1.getCountryValue() == country.getFti()
&& (tradeIncome1.getMinValue() == null || tradeIncome1.getMinValue() <= valueFor)
&& (tradeIncome1.getMaxValue() == null || tradeIncome1.getMaxValue() >= valueFor)
);
if (tradeIncome != null) {
sheet.setForTradeIncome(tradeIncome.getValue());
}
sheet.setFleetLevelIncome(economicalSheetDao.getFleetLevelIncome(name, game.getId()));
sheet.setFleetMonopIncome(economicalSheetDao.getFleetLevelMonopoly(name, game.getId()));
Integer tradeCentersIncome = 0;
if (tradeCenters.get(name) != null) {
for (CounterFaceTypeEnum tradeCenter : tradeCenters.get(name)) {
if (tradeCenter == CounterFaceTypeEnum.TRADE_CENTER_ATLANTIC) {
tradeCentersIncome += 100;
} else if (tradeCenter == CounterFaceTypeEnum.TRADE_CENTER_MEDITERRANEAN) {
tradeCentersIncome += 100;
} else if (tradeCenter == CounterFaceTypeEnum.TRADE_CENTER_INDIAN) {
tradeCentersIncome += 50;
}
}
}
sheet.setTradeCenterIncome(tradeCentersIncome);
sum = CommonUtil.add(sheet.getDomTradeIncome(), sheet.getForTradeIncome(), sheet.getFleetLevelIncome(), sheet.getFleetMonopIncome(), sheet.getTradeCenterIncome());
if (sheet.getTradeCenterLoss() != null) {
sum -= sheet.getTradeCenterLoss();
}
sheet.setTradeIncome(sum);
Pair<Integer, Integer> colTpIncome = economicalSheetDao.getColTpIncome(name, game.getId());
sheet.setColIncome(colTpIncome.getLeft());
sheet.setTpIncome(colTpIncome.getRight());
sheet.setExoResIncome(economicalSheetDao.getExoResIncome(name, game.getId()));
sheet.setRotwIncome(CommonUtil.add(sheet.getColIncome(), sheet.getTpIncome(), sheet.getExoResIncome()));
sheet.setIncome(CommonUtil.add(sheet.getLandIncome(), sheet.getIndustrialIncome(), sheet.getTradeIncome(), sheet.getRotwIncome(), sheet.getSpecialIncome()));
sheet.setGrossIncome(CommonUtil.add(sheet.getIncome(), sheet.getEventIncome()));
}
return DiffUtil.createDiff(game, DiffTypeEnum.INVALIDATE, DiffTypeObjectEnum.ECO_SHEET,
DiffUtil.createDiffAttributes(DiffAttributeTypeEnum.TURN, game.getTurn()));
}
}
|
package org.apache.cordova.screenshot;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Base64;
import android.view.View;
public class Screenshot extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
// starting on ICS, some WebView methods
// can only be called on UI threads
if (action.equals("saveScreenshot")) {
final String format = (String) args.get(0);
final Integer quality = (Integer) args.get(1);
final String fileName = (String)args.get(2);
final Integer x = (Integer) args.get(3);
final Integer y = (Integer) args.get(4);
final Integer width = (Integer) args.get(5);
final Integer height = (Integer) args.get(6);
super.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
View view = webView.getRootView();
try {
if(format.equals("png") || format.equals("jpg")){
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), x,y,width,height);
view.setDrawingCacheEnabled(false);
File folder = new File(Environment.getExternalStorageDirectory(), "Pictures");
if (!folder.exists()) {
folder.mkdirs();
}
File f = new File(folder, fileName + "."+format);
FileOutputStream fos = new FileOutputStream(f);
if(format.equals("png")){
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}
if(format.equals("jpg")){
bitmap.compress(Bitmap.CompressFormat.JPEG, quality == null?100:quality, fos);
}
JSONObject jsonRes = new JSONObject();
jsonRes.put("filePath",f.getAbsolutePath());
PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes);
callbackContext.sendPluginResult(result);
}else{
callbackContext.error("format "+format+" not found");
}
} catch (JSONException e) {
callbackContext.error(e.getMessage());
} catch (IOException e) {
callbackContext.error(e.getMessage());
}
}
});
return true;
}else if(action.equals("getScreenshotAsURI")){
final Integer quality = (Integer) args.get(0);
super.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
View view = webView.getRootView();
try {
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
if (bitmap.compress(CompressFormat.JPEG, quality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encode(code, Base64.NO_WRAP);
String js_out = new String(output);
js_out = "data:image/jpeg;base64," + js_out;
JSONObject jsonRes = new JSONObject();
jsonRes.put("URI", js_out);
PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes);
callbackContext.sendPluginResult(result);
js_out = null;
output = null;
code = null;
}
jpeg_data = null;
} catch (JSONException e) {
callbackContext.error(e.getMessage());
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
}
});
return true;
}
callbackContext.error("action not found");
return false;
}
}
|
package com.jetbrains.python.statistics;
import com.intellij.internal.statistic.AbstractApplicationUsagesCollector;
import com.intellij.internal.statistic.CollectUsagesException;
import com.intellij.internal.statistic.beans.GroupDescriptor;
import com.intellij.internal.statistic.beans.UsageDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.jetbrains.python.packaging.PyPIPackageUtil;
import com.jetbrains.python.packaging.PyPackageManagerImpl;
import com.jetbrains.python.packaging.PyRequirement;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.*;
/**
* @author yole
*/
public class PyPackageUsagesCollector extends AbstractApplicationUsagesCollector {
private static final String GROUP_ID = "py-packages";
@NotNull
@Override
public Set<UsageDescriptor> getProjectUsages(@NotNull Project project) throws CollectUsagesException {
final Set<UsageDescriptor> result = new HashSet<UsageDescriptor>();
for(final Module m: ModuleManager.getInstance(project).getModules()) {
Sdk pythonSdk = PythonSdkType.findPythonSdk(m);
if (pythonSdk != null) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
List<PyRequirement> requirements = PyPackageManagerImpl.getRequirements(m);
if (requirements != null) {
Collection<String> packages;
try {
packages = new HashSet<String>(PyPIPackageUtil.INSTANCE.getPackageNames());
}
catch (IOException e) {
return;
}
for (PyRequirement requirement : requirements) {
String name = requirement.getName();
if (packages.contains(name)) {
result.add(new UsageDescriptor(name, 1));
}
}
}
}
});
}
}
return result;
}
@NotNull
@Override
public GroupDescriptor getGroupId() {
return GroupDescriptor.create(GROUP_ID);
}
}
|
package org.rakam.collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.ContextAttributes;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Longs;
import io.airlift.log.Logger;
import io.airlift.slice.InputStreamSliceInput;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.cookie.Cookie;
import org.apache.avro.generic.GenericData;
import org.rakam.analysis.ApiKeyService;
import org.rakam.collection.Event.EventContext;
import org.rakam.config.ProjectConfig;
import org.rakam.plugin.EventMapper;
import org.rakam.plugin.EventStore;
import org.rakam.plugin.EventStore.CopyType;
import org.rakam.server.http.*;
import org.rakam.server.http.annotations.*;
import org.rakam.util.JsonHelper;
import org.rakam.util.LogUtil;
import org.rakam.util.RakamException;
import org.rakam.util.SuccessMessage;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static com.fasterxml.jackson.core.JsonToken.START_OBJECT;
import static com.google.common.base.Charsets.UTF_8;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.netty.handler.codec.http.cookie.ServerCookieEncoder.STRICT;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.rakam.analysis.ApiKeyService.AccessKeyType.MASTER_KEY;
import static org.rakam.plugin.EventMapper.COMPLETED_EMPTY_FUTURE;
import static org.rakam.plugin.EventStore.COMPLETED_FUTURE;
import static org.rakam.plugin.EventStore.CopyType.*;
import static org.rakam.plugin.EventStore.SUCCESSFUL_BATCH;
import static org.rakam.util.JsonHelper.encodeAsBytes;
import static org.rakam.util.StandardErrors.PARTIAL_ERROR_MESSAGE;
import static org.rakam.util.ValidationUtil.checkCollection;
@Path("/event")
@Api(value = "/event", nickname = "collectEvent", description = "Event collection", tags = "collect")
public class EventCollectionHttpService
extends HttpService {
private final static Logger LOGGER = Logger.get(EventCollectionHttpService.class);
private static final int[] FAILED_SINGLE_EVENT = new int[]{0};
private final byte[] OK_MESSAGE = "1".getBytes(UTF_8);
private final byte[] gif1x1 = Base64.getDecoder().decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
private final ObjectMapper jsonMapper;
private final ObjectMapper csvMapper;
private final EventStore eventStore;
private final List<EventMapper> eventMappers;
private final ApiKeyService apiKeyService;
private final AvroEventDeserializer avroEventDeserializer;
private final JsonEventDeserializer jsonEventDeserializer;
private final Set<String> excludedEvents;
@Inject
public EventCollectionHttpService(
ProjectConfig projectConfig,
EventStore eventStore,
ApiKeyService apiKeyService,
JsonEventDeserializer deserializer,
AvroEventDeserializer avroEventDeserializer,
EventListDeserializer eventListDeserializer,
CsvEventDeserializer csvEventDeserializer,
Set<EventMapper> mappers) {
this.eventStore = eventStore;
this.eventMappers = ImmutableList.copyOf(mappers);
this.apiKeyService = apiKeyService;
this.excludedEvents = projectConfig.getExcludeEvents() != null ? ImmutableSet.copyOf(projectConfig.getExcludeEvents()) : ImmutableSet.of();
jsonMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Event.class, deserializer);
module.addDeserializer(EventList.class, eventListDeserializer);
jsonMapper.registerModule(module);
jsonMapper.registerModule(new SimpleModule("swagger", Version.unknownVersion()) {
@Override
public void setupModule(SetupContext context) {
context.insertAnnotationIntrospector(new SwaggerJacksonAnnotationIntrospector());
}
});
this.avroEventDeserializer = avroEventDeserializer;
this.jsonEventDeserializer = deserializer;
csvMapper = new CsvMapper();
csvMapper.registerModule(new SimpleModule().addDeserializer(EventList.class, csvEventDeserializer));
}
public static CompletableFuture<List<Cookie>> mapEvent(List<EventMapper> eventMappers, Function<EventMapper, CompletableFuture<List<Cookie>>> mapperFunction) {
List<Cookie> cookies = new ArrayList<>();
CompletableFuture[] futures = null;
int futureIndex = 0;
for (int i = 0; i < eventMappers.size(); i++) {
EventMapper mapper = eventMappers.get(i);
CompletableFuture<List<Cookie>> mapperCookies = mapperFunction.apply(mapper);
if (COMPLETED_EMPTY_FUTURE.equals(mapperCookies)) {
if (futures != null) {
futures[futureIndex++] = COMPLETED_FUTURE;
}
} else {
CompletableFuture<Void> future = mapperCookies.thenAccept(cookies::addAll);
if (futures == null) {
futures = new CompletableFuture[eventMappers.size() - i];
}
futures[futureIndex++] = future;
}
}
if (futures == null) {
return COMPLETED_EMPTY_FUTURE;
} else {
return CompletableFuture.allOf(futures).thenApply(v -> cookies);
}
}
private static HttpServer.ErrorMessage returnError(String title) {
return new HttpServer.ErrorMessage(ImmutableList.of(HttpServer.JsonAPIError.title(title)), null);
}
public static void returnError(RakamHttpRequest request, String msg, HttpResponseStatus status) {
ByteBuf byteBuf = Unpooled.wrappedBuffer(JsonHelper.encodeAsBytes(returnError(msg)));
DefaultFullHttpResponse errResponse = new DefaultFullHttpResponse(HTTP_1_1, status, byteBuf);
setBrowser(request, errResponse);
request.response(errResponse).end();
}
public static void setBrowser(HttpRequest request, HttpResponse response) {
response.headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
if (request.headers().contains(ORIGIN)) {
response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, request.headers().get(ORIGIN));
}
String headerList = getHeaderList(request.headers().iterator());
if (headerList != null) {
response.headers().set(ACCESS_CONTROL_EXPOSE_HEADERS, headerList);
}
}
public static InetAddress getRemoteAddress(String socketAddress) {
try {
return InetAddress.getByName(socketAddress);
} catch (UnknownHostException e) {
return null;
}
}
public static String getHeaderList(Iterator<Map.Entry<String, String>> it) {
StringBuilder builder = new StringBuilder("cf-ray,server,status");
while (it.hasNext()) {
String key = it.next().getKey();
if (!key.equals(SET_COOKIE)) {
if (builder.length() != 0) {
builder.append(',');
}
builder.append(key.toLowerCase(Locale.ENGLISH));
}
}
return builder == null ? null : builder.toString();
}
@POST
@ApiOperation(value = "Collect event", response = Integer.class, request = Event.class)
@Path("/collect")
public void collectEvent(RakamHttpRequest request) {
String socketAddress = request.getRemoteAddress();
request.bodyHandler(buff -> {
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(OK_MESSAGE));
CompletableFuture<List<Cookie>> cookiesFuture;
try {
Event event = jsonMapper.readValue(buff, Event.class);
cookiesFuture = mapEvent(eventMappers, mapper -> mapper.mapAsync(event, new HttpRequestParams(request),
getRemoteAddress(socketAddress), response.trailingHeaders()))
.thenCombine(eventStore.storeAsync(event), (cookies, aVoid) -> cookies);
} catch (JsonMappingException e) {
String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
returnError(request, "JSON couldn't parsed: " + message, BAD_REQUEST);
LogUtil.logException(request, e);
return;
} catch (IOException e) {
returnError(request, "JSON couldn't parsed: " + e.getMessage(), BAD_REQUEST);
LogUtil.logException(request, e);
return;
} catch (RakamException e) {
returnError(request, e.getMessage(), e.getStatusCode());
LogUtil.logException(request, e);
return;
} catch (HttpRequestException e) {
returnError(request, e.getMessage(), e.getStatusCode());
return;
} catch (IllegalArgumentException e) {
returnError(request, e.getMessage(), BAD_REQUEST);
LogUtil.logException(request, e);
return;
} catch (Throwable e) {
LOGGER.error(e, "Error while collecting event");
LogUtil.logException(request, e);
returnError(request, "An error occurred", INTERNAL_SERVER_ERROR);
return;
}
String headerList = getHeaderList(response.headers().iterator());
if (headerList != null) {
response.headers().set(ACCESS_CONTROL_EXPOSE_HEADERS, headerList);
}
if (request.headers().contains(ORIGIN)) {
response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, request.headers().get(ORIGIN));
}
cookiesFuture.whenComplete((cookies, ex) -> {
if (ex != null) {
if (ex instanceof RakamException) {
LogUtil.logException(request, ex);
returnError(request, ex.getMessage(), ((RakamException) ex).getStatusCode());
} else {
LOGGER.error(ex, "Error while collecting event");
LogUtil.logException(request, ex);
returnError(request, "An error occurred", INTERNAL_SERVER_ERROR);
}
return;
}
if (cookies != null) {
response.headers().add(SET_COOKIE, STRICT.encode(cookies));
}
request.response(response).end();
});
});
}
@IgnoreApi
@POST
@ApiOperation(value = "Collect event via Pixel", request = Event.class)
@Path("/pixel")
public void pixelPost(RakamHttpRequest request) {
pixel(request);
}
@IgnoreApi
@GET
@ApiOperation(value = "Collect event via Pixel", request = Event.class)
@Path("/pixel")
public void pixel(RakamHttpRequest request) {
String socketAddress = request.getRemoteAddress();
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(OK_MESSAGE));
Map<String, Object> objectNode = new HashMap<>();
Map<String, Object> propertiesNode = new HashMap<>();
Map<String, Object> apiNode = new HashMap<>();
objectNode.put("properties", propertiesNode);
objectNode.put("api", apiNode);
for (Map.Entry<String, List<String>> entry : request.params().entrySet()) {
String value = entry.getValue().get(0);
if (entry.getKey().startsWith("prop.")) {
String attribute = entry.getKey().substring(5);
if (attribute.equals("_time")) {
Long longVal = Longs.tryParse(value);
if (longVal != null) {
propertiesNode.put(attribute, longVal);
continue;
}
}
propertiesNode.put(attribute, value);
} else if (entry.getKey().equals("api.api_key")) {
apiNode.put("api_key", value);
} else if (entry.getKey().equals("collection")) {
objectNode.put("collection", value);
}
}
CompletableFuture<List<Cookie>> cookiesFuture = null;
try {
Event event = jsonMapper.convertValue(objectNode, Event.class);
cookiesFuture = mapEvent(eventMappers, (mapper) -> mapper.mapAsync(event, new HttpRequestParams(request),
getRemoteAddress(socketAddress), response.trailingHeaders()));
cookiesFuture.thenAccept(v -> eventStore.store(event));
} catch (RakamException e) {
response.headers().add("server-error", e.getMessage());
} catch (HttpRequestException e) {
response.headers().add("server-error", e.getMessage());
} catch (IllegalArgumentException e) {
LogUtil.logException(request, e);
response.headers().add("server-error", e.getMessage());
} catch (Exception e) {
LOGGER.error(e, "Error while collecting event");
LogUtil.logException(request, e);
response.headers().add("server-error", "An error occurred");
return;
}
if (cookiesFuture != null) {
cookiesFuture.thenAccept(cookies -> {
if (cookies != null) {
response.headers().add(SET_COOKIE, STRICT.encode(cookies));
}
request.response(response).end();
});
}
request.headers().add(CONTENT_TYPE, "image/gif");
request.headers().add(CONTENT_LENGTH, "42");
request.response(gif1x1).end();
}
@POST
@ApiOperation(value = "Collect Bulk events", request = EventList.class, response = SuccessMessage.class, notes = "Bulk API requires master_key as api key and built for importing the data without any rate limiting unlike event/batch" +
"This endpoint accepts application/json and the data format is same as event/batch. Additionally it supports application/x-rawjson for JSON dump data, application/x-ndjson for newline delimited JSON, application/avro for AVRO and text/csv for CSV formats. You need need to set 'collection' and 'master_key' query parameters if the content-type is not application/json.")
@Path("/bulk")
public void bulkEvents(RakamHttpRequest request) {
bulkEvents(request, true);
}
public void bulkEvents(RakamHttpRequest request, boolean mapEvents) {
storeEventsSync(request,
buff -> {
String contentType = request.headers().get(CONTENT_TYPE);
// TODO: find a way to parse the content type
if (contentType == null || "application/json".equals(contentType) || "application/json; charset=utf-8".equals(contentType)) {
return jsonMapper.readerFor(EventList.class).readValue(buff);
} else if ("application/x-rawjson".equals(contentType) || "application/x-ndjson".equals(contentType)) {
String apiKey;
try {
apiKey = getParam(request.params(), MASTER_KEY.getKey());
} catch (Exception e) {
apiKey = request.headers().get(MASTER_KEY.getKey());
}
String project = apiKeyService.getProjectOfApiKey(apiKey, MASTER_KEY);
String collection = getParam(request.params(), "collection");
JsonParser parser = jsonMapper.getFactory().createParser(buff);
ArrayList<Event> events = new ArrayList<>();
JsonToken t = parser.nextToken();
if (t == JsonToken.START_OBJECT) {
while (t == JsonToken.START_OBJECT) {
Map.Entry<List<SchemaField>, GenericData.Record> entry = jsonEventDeserializer.parseProperties(project, collection, parser, true);
events.add(new Event(project, collection, null, entry.getKey(), entry.getValue()));
t = parser.nextToken();
}
} else if (t == JsonToken.START_ARRAY) {
t = parser.nextToken();
for (; t == START_OBJECT; t = parser.nextToken()) {
Map.Entry<List<SchemaField>, GenericData.Record> entry = jsonEventDeserializer.parseProperties(project, collection, parser, true);
events.add(new Event(project, collection, null, entry.getKey(), entry.getValue()));
}
} else {
throw new RakamException("The body must be an array of events or line-separated events", BAD_REQUEST);
}
return new EventList(EventContext.apiKey(apiKey), project, events);
} else if ("application/avro".equals(contentType)) {
String apiKey = getParam(request.params(), MASTER_KEY.getKey());
String project = apiKeyService.getProjectOfApiKey(apiKey, MASTER_KEY);
String collection = getParam(request.params(), "collection");
return avroEventDeserializer.deserialize(project, collection, new InputStreamSliceInput(buff));
} else if ("text/csv".equals(contentType)) {
String apiKey = getParam(request.params(), MASTER_KEY.getKey());
String project = apiKeyService.getProjectOfApiKey(apiKey, MASTER_KEY);
String collection = getParam(request.params(), "collection");
CsvSchema.Builder builder = CsvSchema.builder();
if (request.params().get("column_separator") != null) {
List<String> column_seperator = request.params().get("column_separator");
if (column_seperator != null && column_seperator.get(0).length() != 1) {
throw new RakamException("Invalid column separator", BAD_REQUEST);
}
builder.setColumnSeparator(column_seperator.get(0).charAt(0));
}
boolean useHeader = false;
if (request.params().get("use_header") != null) {
useHeader = Boolean.valueOf(request.params().get("use_header").get(0));
// do not set CsvSchema setUseHeader, it has extra overhead and the deserializer cannot handle that.
}
return csvMapper.readerFor(EventList.class)
.with(ContextAttributes.getEmpty()
.withSharedAttribute("project", project)
.withSharedAttribute("useHeader", useHeader)
.withSharedAttribute("collection", collection)
.withSharedAttribute("apiKey", apiKey))
.with(builder.build()).readValue(buff);
}
throw new RakamException("Unsupported content type: " + contentType, BAD_REQUEST);
},
(events, responseHeaders) -> {
if (events.size() > 0) {
try {
eventStore.storeBulk(events);
} catch (Throwable e) {
List<Event> sample = events.size() > 5 ? events.subList(0, 2) : events;
LOGGER.error(new RuntimeException("Error executing EventStore bulk method.",
new RuntimeException(sample.toString().substring(0, 200), e)),
"Error while storing event.");
return new HeaderDefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR,
Unpooled.wrappedBuffer(encodeAsBytes(returnError("An error occurred: " + e.getMessage()))),
responseHeaders);
}
}
return new HeaderDefaultFullHttpResponse(HTTP_1_1, OK,
Unpooled.wrappedBuffer(encodeAsBytes(SuccessMessage.success())),
responseHeaders);
}, mapEvents);
}
@POST
@ApiOperation(value = "Copy events directly to database", request = EventList.class, response = Integer.class)
@Path("/copy")
public void copyEvents(RakamHttpRequest request) {
bulkEvents(request, false);
}
@POST
@ApiOperation(value = "Collect bulk events from remote", request = BulkEventRemote.class, response = Integer.class)
@ApiResponses(value = {@ApiResponse(code = 409, message = PARTIAL_ERROR_MESSAGE, response = int[].class)})
@Path("/bulk/remote")
public void bulkEventsRemote(RakamHttpRequest request) {
bulkEventsRemote(request, true);
}
public void bulkEventsRemote(RakamHttpRequest request, boolean mapEvents) {
storeEventsSync(request,
buff -> {
BulkEventRemote query = JsonHelper.read(buff, BulkEventRemote.class);
String masterKey = Optional.ofNullable(request.params().get("master_key"))
.map((v) -> v.get(0))
.orElseGet(() -> request.headers().get("master_key"));
String project = apiKeyService.getProjectOfApiKey(masterKey, MASTER_KEY);
checkCollection(query.collection);
if (query.urls.size() != 1) {
throw new RakamException("Only one url is supported", BAD_REQUEST);
}
if (query.compression != null) {
throw new RakamException("Compression is not supported yet", BAD_REQUEST);
}
URL url = query.urls.get(0);
if (query.type == JSON) {
return jsonMapper.readValue(url, EventList.class);
} else if (query.type == CSV) {
CsvSchema.Builder builder = CsvSchema.builder();
if (request.headers().get("column_separator") != null) {
String column_seperator = request.headers().get("column_separator");
if (column_seperator.length() != 1) {
throw new RakamException("Invalid column separator", BAD_REQUEST);
}
builder.setColumnSeparator(column_seperator.charAt(0));
}
boolean useHeader = true;
if (request.headers().get("use_header") != null) {
useHeader = Boolean.valueOf(request.headers().get("use_header"));
// do not set CsvSchema setUseHeader, it has extra overhead and the deserializer cannot handle that.
}
return csvMapper.readerFor(EventList.class)
.with(ContextAttributes.getEmpty()
.withSharedAttribute("project", project)
.withSharedAttribute("useHeader", useHeader)
.withSharedAttribute("collection", query.collection)
.withSharedAttribute("apiKey", masterKey))
.with(builder.build()).readValue(url);
} else if (query.type == AVRO) {
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
return avroEventDeserializer.deserialize(project, query.collection,
new InputStreamSliceInput(conn.getInputStream()));
}
throw new RakamException("Unsupported or missing type.", BAD_REQUEST);
},
(events, responseHeaders) -> {
try {
eventStore.storeBulk(events);
} catch (Exception e) {
List<Event> sample = events.size() > 5 ? events.subList(0, 5) : events;
LOGGER.error(new RuntimeException("Error executing EventStore bulkRemote method.",
new RuntimeException(sample.toString().substring(0, 200), e)),
"Error while storing event.");
return new HeaderDefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR,
Unpooled.wrappedBuffer(encodeAsBytes(returnError("An error occurred"))),
responseHeaders);
}
return new HeaderDefaultFullHttpResponse(HTTP_1_1, OK,
Unpooled.wrappedBuffer(OK_MESSAGE),
responseHeaders);
}, mapEvents);
}
private String getParam(Map<String, List<String>> params, String param) {
List<String> strings = params.get(param);
if (strings == null || strings.size() == 0) {
throw new RakamException(String.format("%s query parameter is required", param), BAD_REQUEST);
}
return strings.get(strings.size() - 1);
}
@POST
@ApiOperation(notes = "Returns 1 if the events are collected.", value = "Collect multiple events", request = EventList.class, response = Integer.class)
@ApiResponses(value = {
@ApiResponse(code = 409, message = PARTIAL_ERROR_MESSAGE, response = int[].class)
})
@Path("/batch")
public void batchEvents(RakamHttpRequest request) {
storeEvents(request, buff -> {
if (buff.available() > 500000) {
throw new RakamException("The body is too big, use /bulk endpoint.", REQUEST_ENTITY_TOO_LARGE);
}
byte[] bytes = ByteStreams.toByteArray(buff);
return jsonMapper.readerFor(EventList.class).readValue(bytes);
},
(events, responseHeaders) -> {
CompletableFuture<int[]> errorIndexes;
// ignore excluded events
events = events.stream().filter(event -> !excludedEvents.contains(event.collection().toLowerCase())).collect(Collectors.toList());
if (events.size() > 0) {
boolean single = events.size() == 1;
try {
if (single) {
errorIndexes = eventStore.storeAsync(events.get(0))
.handle((aVoid, throwable) -> {
if (throwable != null) {
LOGGER.error(throwable, "Error while storing events");
return FAILED_SINGLE_EVENT;
}
return SUCCESSFUL_BATCH;
});
} else {
errorIndexes = eventStore.storeBatchAsync(events);
}
} catch (Exception e) {
List<Event> sample = events.size() > 5 ? events.subList(0, 5) : events;
LOGGER.error(new RuntimeException(sample.toString(), e), "Error executing EventStore " + (single ? "store" : "batch") + " method.");
return completedFuture(new HeaderDefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR,
Unpooled.wrappedBuffer(encodeAsBytes(returnError("An error occurred"))),
responseHeaders));
}
} else {
errorIndexes = EventStore.COMPLETED_FUTURE_BATCH;
}
return errorIndexes.thenApply(result -> {
if (result.length == 0) {
return new HeaderDefaultFullHttpResponse(HTTP_1_1, OK,
Unpooled.wrappedBuffer(OK_MESSAGE), responseHeaders);
} else {
return new HeaderDefaultFullHttpResponse(HTTP_1_1, CONFLICT,
Unpooled.wrappedBuffer(encodeAsBytes(result)), responseHeaders);
}
});
}, true
);
}
public void storeEventsSync(RakamHttpRequest request, ThrowableFunction mapper, BiFunction<List<Event>, HttpHeaders, FullHttpResponse> responseFunction, boolean mapEvents) {
storeEvents(request, mapper,
(events, entries) -> completedFuture(responseFunction.apply(events, entries)), mapEvents);
}
public void storeEvents(RakamHttpRequest request, ThrowableFunction mapper, BiFunction<List<Event>, HttpHeaders, CompletableFuture<FullHttpResponse>> responseFunction, boolean mapEvents) {
request.bodyHandler(buff -> {
DefaultHttpHeaders responseHeaders = new DefaultHttpHeaders();
responseHeaders.set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
if (request.headers().contains(ORIGIN)) {
responseHeaders.set(ACCESS_CONTROL_ALLOW_ORIGIN, request.headers().get(ORIGIN));
}
CompletableFuture<FullHttpResponse> response;
CompletableFuture<List<Cookie>> entries;
try {
EventList events = mapper.apply(buff);
InetAddress remoteAddress = getRemoteAddress(request.getRemoteAddress());
if (mapEvents) {
entries = mapEvent(eventMappers, (m) -> m.mapAsync(events, new HttpRequestParams(request),
remoteAddress, responseHeaders));
} else {
entries = EventMapper.COMPLETED_EMPTY_FUTURE;
}
response = responseFunction.apply(events.events, responseHeaders);
} catch (JsonMappingException | JsonParseException e) {
returnError(request, "JSON couldn't parsed: " + e.getOriginalMessage(), BAD_REQUEST);
return;
} catch (IOException e) {
returnError(request, "JSON couldn't parsed: " + e.getMessage(), BAD_REQUEST);
return;
} catch (RakamException e) {
LogUtil.logException(request, e);
returnError(request, e.getMessage(), e.getStatusCode());
return;
} catch (HttpRequestException e) {
returnError(request, e.getMessage(), e.getStatusCode());
return;
} catch (IllegalArgumentException e) {
LogUtil.logException(request, e);
returnError(request, e.getMessage(), BAD_REQUEST);
return;
} catch (Throwable e) {
LOGGER.error(e, "Error while collecting event");
LogUtil.logException(request, e);
returnError(request, "An error occurred", INTERNAL_SERVER_ERROR);
return;
}
String headerList = getHeaderList(responseHeaders.iterator());
if (headerList != null) {
responseHeaders.set(ACCESS_CONTROL_EXPOSE_HEADERS, headerList);
}
responseHeaders.add(CONTENT_TYPE, "application/json");
entries.thenAccept(value -> {
if (value != null) {
responseHeaders.add(SET_COOKIE, STRICT.encode(value));
}
});
response.whenComplete((resp, storeEx) -> {
if (storeEx != null) {
if (storeEx instanceof RakamException) {
LogUtil.logException(request, storeEx);
returnError(request, storeEx.getMessage(), ((RakamException) storeEx).getStatusCode());
} else {
LOGGER.error(storeEx, "Error while collecting events");
LogUtil.logException(request, storeEx);
returnError(request, "An error occurred", INTERNAL_SERVER_ERROR);
}
return;
}
entries.whenComplete((value, ex) -> {
if (ex != null) {
String message = "Error while processing event mappers";
LOGGER.error(ex, message);
request.response(JsonHelper.encode(returnError(message)),
INTERNAL_SERVER_ERROR);
} else {
if (value != null) {
responseHeaders.add(SET_COOKIE, STRICT.encode(value));
}
request.response(resp).end();
}
});
});
});
}
interface ThrowableFunction {
EventList apply(InputStream buffer)
throws IOException;
}
public static class HttpRequestParams
implements EventMapper.RequestParams {
private final RakamHttpRequest request;
public HttpRequestParams(RakamHttpRequest request) {
this.request = request;
}
@Override
public Collection<Cookie> cookies() {
return request.cookies();
}
@Override
public HttpHeaders headers() {
return request.headers();
}
}
public static class BulkEventRemote {
public final String collection;
public final List<URL> urls;
public final CopyType type;
public final EventStore.CompressionType compression;
public final Map<String, String> options;
@JsonCreator
public BulkEventRemote(@ApiParam("collection") String collection,
@ApiParam("urls") List<URL> urls,
@ApiParam("type") CopyType type,
@ApiParam(value = "compression", required = false) EventStore.CompressionType compression,
@ApiParam(value = "options", required = false) Map<String, String> options) {
this.collection = collection;
this.urls = urls;
this.type = type;
this.compression = compression;
this.options = Optional.ofNullable(options).orElse(ImmutableMap.of());
}
}
}
|
package org.endeavourhealth.core.messaging.pipeline.components;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Strings;
import org.apache.commons.io.FileUtils;
import org.endeavourhealth.common.cache.ParserPool;
import org.endeavourhealth.common.config.ConfigManager;
import org.endeavourhealth.common.fhir.schema.OrganisationType;
import org.endeavourhealth.common.ods.OdsOrganisation;
import org.endeavourhealth.common.ods.OdsWebService;
import org.endeavourhealth.common.utility.ExpiringCache;
import org.endeavourhealth.common.utility.SlackHelper;
import org.endeavourhealth.core.configuration.OpenEnvelopeConfig;
import org.endeavourhealth.core.database.dal.DalProvider;
import org.endeavourhealth.core.database.dal.admin.ServiceDalI;
import org.endeavourhealth.core.database.dal.admin.SystemHelper;
import org.endeavourhealth.core.database.dal.admin.models.Service;
import org.endeavourhealth.core.database.dal.audit.ExchangeDalI;
import org.endeavourhealth.core.database.dal.audit.models.*;
import org.endeavourhealth.core.database.dal.usermanager.caching.OrganisationCache;
import org.endeavourhealth.core.fhirStorage.ServiceInterfaceEndpoint;
import org.endeavourhealth.core.messaging.pipeline.PipelineComponent;
import org.endeavourhealth.core.messaging.pipeline.PipelineException;
import org.endeavourhealth.core.queueing.MessageFormat;
import org.endeavourhealth.core.xml.QueryDocument.System;
import org.endeavourhealth.core.xml.QueryDocument.TechnicalInterface;
import org.endeavourhealth.transform.common.AuditWriter;
import org.hl7.fhir.instance.model.Binary;
import org.hl7.fhir.instance.model.Bundle;
import org.hl7.fhir.instance.model.MessageHeader;
import org.hl7.fhir.instance.model.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
public class OpenEnvelope extends PipelineComponent {
private static final Logger LOG = LoggerFactory.getLogger(OpenEnvelope.class);
private static final String TAG_BULK = "Bulk received";
private OpenEnvelopeConfig config;
private static ServiceDalI serviceDal = DalProvider.factoryServiceDal();
private static ExpiringCache<String, Long> hmExchangeSizeBeforeBulk = new ExpiringCache<>(ExpiringCache.Duration.FiveMinutes);
public OpenEnvelope(OpenEnvelopeConfig config) {
this.config = config;
}
@Override
public void process(Exchange exchange) throws PipelineException {
// Extract envelope properties to exchange properties
String body = exchange.getBody();
String contentType = exchange.getHeader(HeaderKeys.ContentType);
try {
Bundle bundle = (Bundle)new ParserPool().parse(contentType, body);
List<Bundle.BundleEntryComponent> components = bundle.getEntry();
// find header and payload in bundle
MessageHeader messageHeader = null;
Binary binary = null;
for (Bundle.BundleEntryComponent component : components) {
if (component.hasResource()) {
Resource resource = component.getResource();
if (resource instanceof MessageHeader)
messageHeader = (MessageHeader) resource;
if (resource instanceof Binary)
binary = (Binary) resource;
}
}
if (messageHeader == null || binary == null) {
throw new PipelineException("Invalid bundle. Must contain both a MessageHeader and a Binary resource");
}
Service service = processHeader(exchange, messageHeader);
processBody(exchange, binary);
calculateLastDataDate(exchange); //work out when the data was from
populateBulkTag(exchange, service);
rerouteLargeExchanges(exchange, service);
//commit what we've just received to the DB
AuditWriter.writeExchange(exchange);
} catch (Exception e) {
throw new PipelineException(e.getMessage(), e);
}
LOG.debug("Message envelope processed");
}
/**
* if the total exchange file size is larger than a pre-configured limit, then it will attempt to route
* the data into one of the BULK processing queues. If data is already queued up, then it will change
* the publisher to AUTO-FAIL mode instead, since it will need some manual intervention
*/
private void rerouteLargeExchanges(Exchange exchange, Service service) throws Exception {
//find the configured endpoint on the service
UUID systemId = exchange.getSystemId();
ServiceInterfaceEndpoint matchingEndpoint = null;
List<ServiceInterfaceEndpoint> endpoints = service.getEndpointsList();
for (ServiceInterfaceEndpoint endpoint: endpoints) {
if (endpoint.getSystemUuid().equals(systemId)) {
matchingEndpoint = endpoint;
break;
}
}
//if we failed to find an endpoint (for whatever reason) or the endpoint isn't set in NORMAL mode then return
if (matchingEndpoint == null
|| !matchingEndpoint.getEndpoint().equals(ServiceInterfaceEndpoint.STATUS_NORMAL)) {
return;
}
//work out the size of the exchange itself
Long exchangeSize = exchange.getHeaderAsLong(HeaderKeys.TotalFileSize);
if (exchangeSize == null) {
return;
}
//work out the max size permitted
String sourceSoftware = exchange.getHeader(HeaderKeys.SourceSystem);
long maxSize = getMaxFileSizeForSystem(sourceSoftware);
//if below the max size, then do nothing
if (exchangeSize.longValue() <= maxSize) {
return;
}
//if above the max size, then we need to work out if it's safe to re-route to the bulk queue or we should auto-fail
UUID serviceId = exchange.getServiceId();
boolean inQueue = isAnythingInInboundQueue(serviceId, systemId);
if (inQueue) {
//if we currently have messages in the inbound queue it's not safe to route this new exchange
//to a bulk queue, so it's safter to just get everything to fail and let it be sorted manually
matchingEndpoint.setEndpoint(ServiceInterfaceEndpoint.STATUS_AUTO_FAIL);
} else {
//if nothing is currently being processed in the inbound queue, then route this exchange to the
//bulk queue
matchingEndpoint.setEndpoint(ServiceInterfaceEndpoint.STATUS_BULK_PROCESSING);
}
String msg = "" + service.getLocalId() + " " + service.getName() + " has sent exchange " + exchange.getId()
+ " sized " + FileUtils.byteCountToDisplaySize(exchangeSize.longValue()) + " which is larger than the "
+ sourceSoftware + " limit of " + FileUtils.byteCountToDisplaySize(maxSize)
+ "\r\n"
+ "The publisher has been set into " + matchingEndpoint.getEndpoint() + " mode to avoid blocking the regular queues";
SlackHelper.sendSlackMessage(SlackHelper.Channel.MessagingApi, msg);
LOG.info(msg);
service.setEndpointsList(endpoints);
serviceDal.save(service);
}
private static long getMaxFileSizeForSystem(String software) throws Exception {
Long maxSize = hmExchangeSizeBeforeBulk.get(software);
if (maxSize == null) {
JsonNode json = ConfigManager.getConfigurationAsJson("large_exchange_limits");
if (json != null
&& json.has(software)) {
long val = json.get(software).asLong();
maxSize = new Long(val);
}
if (maxSize == null) {
maxSize = new Long(Long.MAX_VALUE);
}
hmExchangeSizeBeforeBulk.put(software, maxSize);
}
return maxSize.longValue();
}
/**
* if the exchange is flagged as a bulk, then populate the tag on the service
*/
private void populateBulkTag(Exchange exchange, Service service) throws Exception {
Boolean isBulk = exchange.getHeaderAsBoolean(HeaderKeys.IsBulk);
if (isBulk == null
|| !isBulk.booleanValue()) {
return;
}
UUID serviceId = exchange.getServiceId();
Map<String, String> tags = service.getTags();
if (tags == null) {
tags = new HashMap<>();
}
//if this is another bulk, don't bother updating the service again
if (tags.containsKey(TAG_BULK)) {
return;
}
Date dataData = exchange.getHeaderAsDate(HeaderKeys.DataDate);
if (dataData == null) {
tags.put(TAG_BULK, "Exchange " + exchange.getId());
} else {
tags.put(TAG_BULK, new SimpleDateFormat("yyyy-MM-dd").format(dataData));
}
service.setTags(tags);
serviceDal.save(service);
}
private void calculateLastDataDate(Exchange exchange) throws PipelineException {
UUID serviceId = exchange.getServiceId();
UUID systemId = exchange.getSystemId();
if (serviceId == null
|| systemId == null) {
return;
}
String body = exchange.getBody();
if (Strings.isNullOrEmpty(body)) {
return;
}
try {
String software = exchange.getHeader(HeaderKeys.SourceSystem);
String version = exchange.getHeader(HeaderKeys.SystemVersion);
Date lastDataDate = calculateLastDataDate(software, version, body);
//sometimes we can't work out a date
if (lastDataDate == null) {
return;
}
//set the date in the exchange header
exchange.setHeaderAsDate(HeaderKeys.DataDate, lastDataDate);
//and save the date to the special table so we can retrieve it quicker
LastDataReceived obj = new LastDataReceived();
obj.setServiceId(serviceId);
obj.setSystemId(systemId);
obj.setExchangeId(exchange.getId());
obj.setReceivedDate(new Date());
obj.setDataDate(lastDataDate);
ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();
exchangeDal.save(obj);
} catch (Throwable t) {
//any exception, just log it out without throwing further up
LOG.error("Failed to work out last extract date for " + exchange.getId(), t);
}
}
/**
* works out the date of the newly published data, which is calculated from the exchange body
*/
public static Date calculateLastDataDate(String software, String version, String body) throws Exception {
//unlike all the others, the HL7 exchanges contain a FHIR resourse in JSON, with a timestamp in its body
if (software.equalsIgnoreCase(MessageFormat.HL7V2)) {
String timestampStr = findFirstElement(body, "timestamp");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return sdf.parse(timestampStr);
}
if (software.contains("HL7V2")) {
return new Date();
}
//all other systems have the body containing a list of files in JSON, which contain
//the date in the path somewhere
String dateFormat = null;
if (software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) {
//the custom extracts are one-off and receipt of them shouldn't interfere with the
//normal logging of when data is received, so return null for them
if (version.equalsIgnoreCase("CUSTOM")) {
return null;
}
dateFormat = "yyyy-MM-dd'T'HH.mm.ss";
} else if (software.equalsIgnoreCase(MessageFormat.BARTS_CSV)) {
dateFormat = "yyyy-MM-dd";
} else if (software.equalsIgnoreCase(MessageFormat.TPP_CSV)) {
dateFormat = "yyyy-MM-dd'T'HH.mm.ss";
} else if (software.equalsIgnoreCase(MessageFormat.HOMERTON_CSV)) {
dateFormat = "yyyy-MM-dd";
} else if (software.equalsIgnoreCase(MessageFormat.VISION_CSV)) {
dateFormat = "yyyy-MM-dd'T'HH'.'mm'.'ss";
} else if (software.equalsIgnoreCase(MessageFormat.ADASTRA_CSV)) {
dateFormat = "yyyy-MM-dd'T'HH'.'mm'.'ss";
} else if (software.equalsIgnoreCase(MessageFormat.BHRUT_CSV)) {
dateFormat = "yyyy-MM-dd'T'HH'.'mm'.'ss";
//NOTE: If adding support for a new publisher software, remember to add to the MessageTransformInbound class too
} else {
throw new Exception("Software [" + software + "} not supported for calculating last data date");
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//find the first file path in the JSON body and simply work down the path to find a directory
//named in a way that matches the date format appropriate for the published software
String firstFile = findFirstElement(body, "path"); //e.g. sftpReader/BARTSDW/2019-01-23/susecd.190259
File f = new File(firstFile);
while (f != null) {
String name = f.getName();
try {
Date d = sdf.parse(name);
return d;
} catch (Exception ex) {
f = f.getParentFile();
}
}
throw new Exception("Failed to work out data date from " + firstFile);
}
/**
* the exchange body is always JSON, but rather than parsing the entire string into a Json structure, this
* function will find the first element for a given name without needing to do all that parsing
*/
private static String findFirstElement(String json, String elementName) {
elementName = "\"" + elementName + "\"";
int index = json.indexOf(elementName);
index = json.indexOf("\"", index + elementName.length()+1);
int endIndex = json.indexOf("\"", index+1);
String elementValue = json.substring(index+1, endIndex);
return elementValue;
}
private Service processHeader(Exchange exchange, MessageHeader messageHeader) throws PipelineException {
//just carry over fields from the request to the exchange
exchange.setHeader(HeaderKeys.MessageId, messageHeader.getId());
exchange.setHeader(HeaderKeys.SenderLocalIdentifier, messageHeader.getSource().getName());
exchange.setHeader(HeaderKeys.SourceSystem, messageHeader.getSource().getSoftware());
exchange.setHeader(HeaderKeys.SystemVersion, messageHeader.getSource().getVersion());
exchange.setHeader(HeaderKeys.ResponseUri, messageHeader.getSource().getEndpoint());
exchange.setHeader(HeaderKeys.MessageEvent, messageHeader.getEvent().getCode());
//validate that the sender is one we know off
Service service = processSender(exchange);
//carry over any explicit destinations
processDestinations(exchange, messageHeader);
return service;
}
private Service processSender(Exchange exchange) throws PipelineException {
String organisationOds = exchange.getHeader(HeaderKeys.SenderLocalIdentifier);
String software = exchange.getHeader(HeaderKeys.SourceSystem);
String version = exchange.getHeader(HeaderKeys.SystemVersion);
//ensure we can match to a Service
Service service = findOrCreateService(organisationOds);
//ensure we can match to a System at that Service
UUID systemUuid = findSystemId(service, software, version);
exchange.setHeader(HeaderKeys.SenderServiceUuid, service.getId().toString());
exchange.setHeader(HeaderKeys.SenderSystemUuid, systemUuid.toString());
exchange.setServiceId(service.getId());
exchange.setSystemId(systemUuid);
return service;
}
private Service findOrCreateService(String organisationOds) throws PipelineException {
try {
//see if we've already got a service
Service s = serviceDal.getByLocalIdentifier(organisationOds);
if (s != null) {
return s;
}
//if no service already exists, then see if we can create one, but only if we have a DPA in the DSM
Boolean hasDpa = OrganisationCache.doesOrganisationHaveDPA(organisationOds);
if (!hasDpa.booleanValue()) {
throw new PipelineException("Data received for ODS code " + organisationOds + " but will not auto-create bacause no DPA exists");
}
OdsOrganisation odsOrg = OdsWebService.lookupOrganisationViaRest(organisationOds);
if (odsOrg == null) {
throw new PipelineException("Data received for ODS code " + organisationOds + " but could not find on ODS, so service needs manually setting up in DDS-UI");
}
s = new Service();
s.setLocalId(organisationOds);
String name = odsOrg.getOrganisationName();
s.setName(name);
String postcode = odsOrg.getPostcode();
s.setPostcode(postcode);
Set<OrganisationType> types = new HashSet<>(odsOrg.getOrganisationTypes());
types.remove(OrganisationType.PRESCRIBING_COST_CENTRE); //always remove so we match to the "better" type
if (types.size() == 1) {
OrganisationType type = types.iterator().next();
s.setOrganisationType(type);
} else {
LOG.warn("Could not select type for org " + odsOrg);
}
Map<String, OdsOrganisation> parents = odsOrg.getParents();
for (String parentOds: parents.keySet()) {
OdsOrganisation parent = parents.get(parentOds);
//only select parent if it's NOT a PCN
if (!parent.getOrganisationTypes().contains(OrganisationType.PRIMARY_CARE_NETWORK)) {
s.setCcgCode(parentOds);
break;
}
}
//set to empty list so the parser can read it without error
s.setEndpointsList(new ArrayList<>());
Map<String, String> hmTags = new HashMap<>();
hmTags.put("Notes", "Auto-created by Messaging API");
s.setTags(hmTags);
//tell us because we need to manually do a couple of steps
String msg = "Auto-created Service for ODS code " + organisationOds + " in Messaging API\r\n"
+ s.toString()
+ "\r\nPublisher config name and tags need setting in DDS-UI";
SlackHelper.sendSlackMessage(SlackHelper.Channel.QueueReaderAlerts, msg);
serviceDal.save(s);
return s;
} catch (PipelineException pe) {
//any pipeline exceptions, just throw them as is
throw pe;
} catch (Exception ex) {
//any other exception (e.g. from database error), then we need to wrap up
throw new PipelineException("Failed at auto-creating Service for ODS code " + organisationOds, ex);
}
}
private UUID findSystemId(Service service, String software, String messageVersion) throws PipelineException {
try {
ServiceInterfaceEndpoint endpoint = SystemHelper.findEndpointForSoftwareAndVersion(service, software, messageVersion);
if (endpoint == null) {
//create new draft service
createDraftEndpoint(service, software, messageVersion);
throw new PipelineException("Endpoint for " + service.getLocalId() + " " + software + " has been automatically added to service " + service.getLocalId() + " but in draft mode - manually change when data ready to process");
} else if (endpoint.getEndpoint() != null
&& endpoint.getEndpoint().equals(ServiceInterfaceEndpoint.STATUS_DRAFT)) {
//endpoint exists but is in DRAFT mode
throw new PipelineException("Endpoint for " + service.getLocalId() + " " + software + " already exists in draft mode - manually change to process data");
} else {
//endpoint exists and is OK
return endpoint.getSystemUuid();
}
} catch (PipelineException pe) {
//any pipeline exceptions, just throw them as is
throw pe;
} catch (Exception e) {
throw new PipelineException("Failed to find or create system for service " + service.getLocalId() + " " + software + " version " + messageVersion, e);
}
}
private void createDraftEndpoint(Service service, String software, String messageVersion) throws Exception {
System system = SystemHelper.findSystemForSoftwareAndVersion(software, messageVersion);
if (system == null) {
throw new Exception("No system configured for software [" + software + "] and version [" + messageVersion + "]");
}
TechnicalInterface technicalInterface = SystemHelper.getTechnicalInterface(system);
String technicalInterfaceId = technicalInterface.getUuid();
ServiceInterfaceEndpoint endpoint = new ServiceInterfaceEndpoint();
endpoint.setEndpoint(ServiceInterfaceEndpoint.STATUS_DRAFT); //set in draft mode
endpoint.setSystemUuid(UUID.fromString(system.getUuid()));
endpoint.setTechnicalInterfaceUuid(UUID.fromString(technicalInterfaceId));
List<ServiceInterfaceEndpoint> endpoints = service.getEndpointsList();
endpoints.add(endpoint);
service.setEndpointsList(endpoints);
serviceDal.save(service);
}
private void processBody(Exchange exchange, Binary binary) {
exchange.setHeader(HeaderKeys.MessageFormat, binary.getContentType());
if (binary.hasContent()) {
exchange.setBody(new String(binary.getContent()));
}
}
private void processDestinations(Exchange exchange, MessageHeader messageHeader) {
List<String> destinationUriList = new ArrayList<>();
if (messageHeader.hasDestination()) {
List<MessageHeader.MessageDestinationComponent> messageDestinationComponents = messageHeader.getDestination();
for (MessageHeader.MessageDestinationComponent messageDestinationComponent : messageDestinationComponents) {
destinationUriList.add(messageDestinationComponent.getEndpoint());
}
}
if (!destinationUriList.isEmpty()) {
exchange.setHeader(HeaderKeys.DestinationAddress, String.join(",", destinationUriList));
}
}
/**
* works out if there's anything in the inbound queue for the given service
* Note that this doesn't actually test RabbitMQ but looks at the transform audit of the most
* recent exchange to infer whether it is still in the queue or not
*/
public static boolean isAnythingInInboundQueue(UUID serviceId, UUID systemId) throws Exception {
ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal();
List<Exchange> mostRecentExchanges = exchangeDal.getExchangesByService(serviceId, systemId, 1);
if (mostRecentExchanges.isEmpty()) {
return false;
}
Exchange mostRecentExchange = mostRecentExchanges.get(0);
//if the most recent exchange is flagged for not queueing, then we need to go back to the last one not flagged like that
Boolean allowQueueing = mostRecentExchange.getHeaderAsBoolean(HeaderKeys.AllowQueueing);
if (allowQueueing != null
&& !allowQueueing.booleanValue()) {
mostRecentExchange = null;
mostRecentExchanges = exchangeDal.getExchangesByService(serviceId, systemId, 100);
for (Exchange exchange: mostRecentExchanges) {
allowQueueing = exchange.getHeaderAsBoolean(HeaderKeys.AllowQueueing);
if (allowQueueing == null
|| allowQueueing.booleanValue()) {
mostRecentExchange = exchange;
break;
}
}
//if we still didn't find one, after checking the last 100, then just assume we're OK
if (mostRecentExchange == null) {
return false;
}
}
ExchangeTransformAudit latestTransform = exchangeDal.getLatestExchangeTransformAudit(serviceId, systemId, mostRecentExchange.getId());
//if the exchange has never been transformed or the transform hasn't ended, we
//can infer that it's in the queue
if (latestTransform == null
|| latestTransform.getEnded() == null) {
LOG.debug("Exchange " + mostRecentExchange.getId() + " has never been transformed or hasn't finished yet");
return true;
} else {
Date transformFinished = latestTransform.getEnded();
List<ExchangeEvent> events = exchangeDal.getExchangeEvents(mostRecentExchange.getId());
if (!events.isEmpty()) {
ExchangeEvent mostRecentEvent = events.get(events.size() - 1);
String eventDesc = mostRecentEvent.getEventDesc();
Date eventDate = mostRecentEvent.getTimestamp();
if (eventDesc.startsWith("Manually pushed into EdsInbound")
&& eventDate.after(transformFinished)) {
LOG.debug("Exchange " + mostRecentExchange.getId() + " latest event is being inserted into queue");
return true;
}
}
}
return false;
}
}
|
package org.mtransit.parser.ca_st_john_s_metrobus_transit_bus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.Utils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
public class StJohnSMetrobusTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-st-john-s-metrobus-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new StJohnSMetrobusTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
MTLog.log("Generating Metrobus Transit bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
MTLog.log("Generating Metrobus Transit bus data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final long RID_ENDS_WITH_A = 10_000L;
private static final long RID_ENDS_WITH_B = 20_000L;
@Override
public long getRouteId(GRoute gRoute) {
String rsn = gRoute.getRouteShortName().trim();
if (!Utils.isDigitsOnly(rsn)) {
Matcher matcher = DIGITS.matcher(rsn);
if (matcher.find()) {
int digits = Integer.parseInt(matcher.group());
if (rsn.endsWith("A")) {
return digits + RID_ENDS_WITH_A;
} else if (rsn.endsWith("B")) {
return digits + RID_ENDS_WITH_B;
}
}
throw new MTLog.Fatal("Unexptected route ID for %s!", gRoute);
}
return Long.parseLong(rsn); // using route short name as route ID
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = CleanUtils.cleanSlashes(routeLongName);
return CleanUtils.cleanLabel(routeLongName);
}
@Override
public String getRouteShortName(GRoute gRoute) {
return gRoute.getRouteShortName().trim();
}
private static final String AGENCY_COLOR_BROWN = "A19153"; // BROWN (from old logo)
private static final String AGENCY_COLOR = AGENCY_COLOR_BROWN;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_F6863C = "F6863C";
private static final String COLOR_26A450 = "26A450";
private static final String COLOR_8FC74A = "8FC74A";
private static final String COLOR_F7ACB0 = "F7ACB0";
private static final String COLOR_933D40 = "933D40";
private static final String COLOR_8F44AD = "8F44AD";
private static final String COLOR_00BEF2 = "00BEF2";
private static final String COLOR_068C83 = "068C83";
private static final String COLOR_1A5B33 = "1A5B33";
private static final String COLOR_C4393C = "C4393C";
private static final String COLOR_691A5C = "691A5C";
private static final String COLOR_9D6743 = "9D6743";
private static final String COLOR_467C96 = "467C96";
private static final String COLOR_ED258F = "ED258F";
private static final String COLOR_FFCC2C = "FFCC2C";
private static final String COLOR_ADA425 = "ADA425";
private static final String COLOR_D6400E = "D6400E";
private static final String COLOR_A6787A = "A6787A";
private static final String COLOR_3E4095 = "3E4095";
private static final String COLOR_363435 = "363435";
private static final String COLOR_EECE20 = "EECE20";
@Override
public String getRouteColor(GRoute gRoute) {
String rsnS = gRoute.getRouteShortName().trim();
if (!Utils.isDigitsOnly(rsnS)) {
if ("3A".equalsIgnoreCase(rsnS)) {
return COLOR_8FC74A; // same as 3
} else if ("3B".equalsIgnoreCase(rsnS)) {
return COLOR_8FC74A; // same as 3
}
throw new MTLog.Fatal("Unexpected route color %s!", gRoute);
}
int rsn = Integer.parseInt(rsnS);
switch (rsn) {
// @formatter:off
case 1: return COLOR_F6863C;
case 2: return COLOR_26A450;
case 3: return COLOR_8FC74A;
case 5: return COLOR_F7ACB0;
case 6: return COLOR_933D40;
case 9: return COLOR_691A5C;
case 10: return COLOR_8F44AD;
case 11: return COLOR_3E4095;
case 12: return COLOR_00BEF2;
case 13: return COLOR_068C83;
case 14: return COLOR_1A5B33;
case 15: return COLOR_C4393C;
case 16: return COLOR_691A5C;
case 17: return COLOR_9D6743;
case 18: return COLOR_467C96;
case 19: return COLOR_ED258F;
case 20: return COLOR_FFCC2C;
case 21: return COLOR_ADA425;
case 22: return COLOR_D6400E;
case 23: return COLOR_A6787A;
case 24: return COLOR_363435;
case 25: return COLOR_3E4095;
case 26: return COLOR_363435;
case 27: return null; // TODO
case 30: return COLOR_EECE20;
// @formatter:on
default:
throw new MTLog.Fatal("Unexpected route color %s!", gRoute);
}
}
private static final HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<>();
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId());
}
private static final Pattern STARTS_WITH_AREA = Pattern.compile("(^(([\\w]+[\\.]? )+(\\- ))*)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_TO = Pattern.compile("(^(to ))", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_DASH = Pattern.compile("(^.*( )?(\\- ))", Pattern.CASE_INSENSITIVE);
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = STARTS_WITH_AREA.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = STARTS_WITH_TO.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = STARTS_WITH_DASH.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
if (mTrip.getRouteId() == 1L) {
if (Arrays.asList(
"MUN / CONA / MI",
"Institutes"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Institutes", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 2L) {
if (Arrays.asList(
"Vlg",
"Vlg Mall"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Vlg Mall", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 3L) {
if (Arrays.asList(
"Highland Dr / Kingsbridge / Vlg",
"Vlg Mall"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Vlg Mall", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 11L) {
if (Arrays.asList(
StringUtils.EMPTY,
"Avalon Mall"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Avalon Mall", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 27L) {
if (Arrays.asList(
"Sheraton / Quidi Vidi / Delta",
"Quidi Vidi / Delta"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Quidi Vidi / Delta", mTrip.getHeadsignId()); // Sheraton / Quidi Vidi / Delta
return true;
}
}
throw new MTLog.Fatal("Unexpected trips to merge: %s & %s!", mTrip, mTripToMerge);
}
private static final Pattern CIVIC_ADDRESS_ENDS_WITH = Pattern.compile("((\\s)*(\\- opposite|\\- opp|opposite|\\-)(\\s)*$)", Pattern.CASE_INSENSITIVE);
private static final Pattern DASH_P1 = Pattern.compile("((\\s)*(\\-)(\\s)*(\\())", Pattern.CASE_INSENSITIVE);
private static final String DASH_P1_REPLACEMENT = " (";
private static final Pattern CIVIC_ADDRESS = Pattern.compile("(([^\\#]*)#(\\s)*([0-9]{1,5})(.*))", Pattern.CASE_INSENSITIVE);
private static final String CIVIC_ADDRESS_REPLACEMENT = "$4, $2 $5";
private static final Pattern DASH = Pattern
.compile(
"((\\s)*(at |\\-[^-]*\\-|\\-[\\s]*at|\\-[\\s]*by|\\-[\\s]*east of|\\-[\\s]*near|\\-[\\s]*opp[\\s]*(near)?|\\-[\\s]*west of|\\-|by|east of|west of|opp|near)(\\s)*)",
Pattern.CASE_INSENSITIVE);
private static final String DASH_REPLACEMENT = " / ";
private static final Pattern AND = Pattern.compile("( and )", Pattern.CASE_INSENSITIVE);
private static final String AND_REPLACEMENT = " & ";
private static final Pattern APARTMENT = Pattern.compile("(apartment)", Pattern.CASE_INSENSITIVE);
private static final String APARTMENT_REPLACEMENT = "Apt";
@Override
public String cleanStopName(String gStopName) {
if (Utils.isUppercaseOnly(gStopName, true, true)) {
gStopName = gStopName.toLowerCase(Locale.ENGLISH);
}
gStopName = CIVIC_ADDRESS.matcher(gStopName).replaceAll(CIVIC_ADDRESS_REPLACEMENT);
gStopName = DASH_P1.matcher(gStopName).replaceAll(DASH_P1_REPLACEMENT);
gStopName = CIVIC_ADDRESS_ENDS_WITH.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = DASH.matcher(gStopName).replaceAll(DASH_REPLACEMENT);
gStopName = AND.matcher(gStopName).replaceAll(AND_REPLACEMENT);
gStopName = APARTMENT.matcher(gStopName).replaceAll(APARTMENT_REPLACEMENT);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
@Override
public int getStopId(GStop gStop) {
if (Utils.isDigitsOnly(gStop.getStopId())) {
return Integer.parseInt(gStop.getStopId());
}
Matcher matcher = DIGITS.matcher(gStop.getStopId());
if (matcher.find()) {
return Integer.parseInt(matcher.group());
}
throw new MTLog.Fatal("Unexpected stop ID for %s!", gStop);
}
}
|
package ca.corefacility.bioinformatics.irida.ria.unit.web.projects;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.ui.ExtendedModelMap;
import ca.corefacility.bioinformatics.irida.model.RemoteAPI;
import ca.corefacility.bioinformatics.irida.model.enums.ProjectRole;
import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectUserJoin;
import ca.corefacility.bioinformatics.irida.model.joins.impl.RelatedProjectJoin;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.model.remote.RemoteRelatedProject;
import ca.corefacility.bioinformatics.irida.model.user.Role;
import ca.corefacility.bioinformatics.irida.model.user.User;
import ca.corefacility.bioinformatics.irida.ria.web.projects.AssociatedProjectsController;
import ca.corefacility.bioinformatics.irida.ria.web.projects.ProjectControllerUtils;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import ca.corefacility.bioinformatics.irida.service.RemoteRelatedProjectService;
import ca.corefacility.bioinformatics.irida.service.user.UserService;
import com.google.common.collect.Lists;
public class AssociatedProjectControllerTest {
private static final String USER_NAME = "testme";
private ProjectService projectService;
private AssociatedProjectsController controller;
private UserService userService;
private ProjectControllerUtils projectUtils;
private RemoteRelatedProjectService remoteRelatedProjectService;
@Before
public void setUp() {
projectService = mock(ProjectService.class);
userService = mock(UserService.class);
projectUtils = mock(ProjectControllerUtils.class);
remoteRelatedProjectService = mock(RemoteRelatedProjectService.class);
controller = new AssociatedProjectsController(remoteRelatedProjectService, projectService, projectUtils,
userService);
}
@Test
public void testGetAssociatedProjectsPage() {
ExtendedModelMap model = new ExtendedModelMap();
Principal principal = () -> USER_NAME;
Long projectId = 1l;
User u = new User();
u.setSystemRole(Role.ROLE_ADMIN);
Project p = new Project("my project");
p.setId(projectId);
Project o = new Project("other project");
o.setId(2l);
List<RelatedProjectJoin> relatedProjects = Lists.newArrayList(new RelatedProjectJoin(p, o));
RemoteAPI remoteAPI = new RemoteAPI();
List<RemoteRelatedProject> remoteRelatedProjects = Lists.newArrayList(new RemoteRelatedProject(p, remoteAPI,
"http://somewhere"));
when(projectService.read(projectId)).thenReturn(p);
when(userService.getUserByUsername(USER_NAME)).thenReturn(u);
when(projectService.getRelatedProjects(p)).thenReturn(relatedProjects);
when(remoteRelatedProjectService.getRemoteProjectsForProject(p)).thenReturn(remoteRelatedProjects);
controller.getAssociatedProjectsPage(projectId, model, principal);
assertTrue(model.containsAttribute("isAdmin"));
assertTrue(model.containsAttribute("associatedProjects"));
assertTrue(model.containsAttribute("remoteProjectsByApi"));
verify(projectService).read(projectId);
verify(userService, times(2)).getUserByUsername(USER_NAME);
verify(projectService).getRelatedProjects(p);
verify(remoteRelatedProjectService).getRemoteProjectsForProject(p);
}
@SuppressWarnings("unchecked")
@Test
public void testGetPotentialAssociatedProjectsAsAdmin() {
Long projectId = 1l;
Principal principal = () -> USER_NAME;
int page = 1;
int count = 10;
String sortedBy = "id";
String sortDir = "ASC";
String projectName = "";
Project p1 = new Project("p1");
when(projectService.read(projectId)).thenReturn(p1);
User user = new User();
user.setSystemRole(Role.ROLE_ADMIN);
when(userService.getUserByUsername(USER_NAME)).thenReturn(user);
// (specification, page, count, sortDirection, sortedBy);
Project p2 = new Project("p2");
p2.setId(2l);
Project p3 = new Project("p3");
p3.setId(3l);
List<RelatedProjectJoin> relatedJoins = Lists.newArrayList(new RelatedProjectJoin(p1, p2));
when(projectService.getRelatedProjects(p1)).thenReturn(relatedJoins);
Page<Project> projectPage = new PageImpl<>(Lists.newArrayList(p2, p3));
when(projectService.search(any(Specification.class), eq(page), eq(count), any(Direction.class), eq(sortedBy)))
.thenReturn(projectPage);
Map<String, Object> potentialAssociatedProjects = controller.getPotentialAssociatedProjects(projectId,
principal, page, count, sortedBy, sortDir, projectName);
assertTrue(potentialAssociatedProjects.containsKey("associated"));
List<Map<String, String>> associated = (List<Map<String, String>>) potentialAssociatedProjects
.get("associated");
assertEquals(2, associated.size());
for (Map<String, String> pmap : associated) {
if (pmap.get("id").equals("2")) {
assertTrue(pmap.containsKey("associated"));
}
}
verify(projectService).read(projectId);
verify(userService).getUserByUsername(USER_NAME);
verify(projectService).getRelatedProjects(p1);
verify(projectService)
.search(any(Specification.class), eq(page), eq(count), any(Direction.class), eq(sortedBy));
}
@SuppressWarnings("unchecked")
@Test
public void testGetPotentialAssociatedProjectsAsUser() {
Long projectId = 1l;
Principal principal = () -> USER_NAME;
int page = 1;
int count = 10;
String sortedBy = "id";
String sortDir = "ASC";
String projectName = "";
Project p1 = new Project("p1");
when(projectService.read(projectId)).thenReturn(p1);
User user = new User();
user.setSystemRole(Role.ROLE_USER);
when(userService.getUserByUsername(USER_NAME)).thenReturn(user);
Project p2 = new Project("p2");
p2.setId(2l);
Project p3 = new Project("p3");
p3.setId(3l);
List<RelatedProjectJoin> relatedJoins = Lists.newArrayList(new RelatedProjectJoin(p1, p2));
when(projectService.getRelatedProjects(p1)).thenReturn(relatedJoins);
Page<ProjectUserJoin> projectPage = new PageImpl<>(Lists.newArrayList(new ProjectUserJoin(p2, user,
ProjectRole.PROJECT_OWNER), new ProjectUserJoin(p3, user, ProjectRole.PROJECT_OWNER)));
when(
projectService.searchProjectUsers(any(Specification.class), eq(page), eq(count), any(Direction.class),
eq("project." + sortedBy))).thenReturn(projectPage);
Map<String, Object> potentialAssociatedProjects = controller.getPotentialAssociatedProjects(projectId,
principal, page, count, sortedBy, sortDir, projectName);
assertTrue(potentialAssociatedProjects.containsKey("associated"));
List<Map<String, String>> associated = (List<Map<String, String>>) potentialAssociatedProjects
.get("associated");
assertEquals(2, associated.size());
for (Map<String, String> pmap : associated) {
if (pmap.get("id").equals("2")) {
assertTrue(pmap.containsKey("associated"));
}
}
verify(projectService).read(projectId);
verify(userService).getUserByUsername(USER_NAME);
verify(projectService).getRelatedProjects(p1);
verify(projectService).searchProjectUsers(any(Specification.class), eq(page), eq(count), any(Direction.class),
eq("project." + sortedBy));
}
@Test
public void testAddAssociatedProject() {
Long projectId = 1l;
Long associatedProjectId = 2l;
Project p1 = new Project();
Project p2 = new Project();
when(projectService.read(projectId)).thenReturn(p1);
when(projectService.read(associatedProjectId)).thenReturn(p2);
controller.addAssociatedProject(projectId, associatedProjectId);
verify(projectService).addRelatedProject(p1, p2);
}
@Test
public void testRemoveAssociatedProject() {
Long projectId = 1l;
Long associatedProjectId = 2l;
Project p1 = new Project();
Project p2 = new Project();
when(projectService.read(projectId)).thenReturn(p1);
when(projectService.read(associatedProjectId)).thenReturn(p2);
controller.removeAssociatedProject(projectId, associatedProjectId);
verify(projectService).removeRelatedProject(p1, p2);
}
@Test
public void testEditAssociatedProjectsForProject() {
Long projectId = 1l;
ExtendedModelMap model = new ExtendedModelMap();
Principal principal = () -> USER_NAME;
String editAssociatedProjectsForProject = controller.editAssociatedProjectsForProject(projectId, model,
principal);
assertEquals(AssociatedProjectsController.EDIT_ASSOCIATED_PROJECTS_PAGE, editAssociatedProjectsForProject);
}
}
|
package rlpark.plugin.rltoys.problems.mazes;
import java.awt.Point;
import rlpark.plugin.rltoys.algorithms.functions.states.Projector;
import rlpark.plugin.rltoys.envio.actions.Action;
import rlpark.plugin.rltoys.envio.actions.ActionArray;
import rlpark.plugin.rltoys.envio.observations.Legend;
import rlpark.plugin.rltoys.envio.rl.TRStep;
import rlpark.plugin.rltoys.math.vector.RealVector;
import rlpark.plugin.rltoys.math.vector.implementations.BVector;
import rlpark.plugin.rltoys.problems.ProblemDiscreteAction;
public class Maze implements ProblemDiscreteAction {
static private Legend legend = new Legend("x", "y");
public static final ActionArray Left = new ActionArray(-1, 0);
public static final ActionArray Right = new ActionArray(+1, 0);
public static final ActionArray Up = new ActionArray(0, +1);
public static final ActionArray Down = new ActionArray(0, -1);
public static final ActionArray Stop = new ActionArray(0, 0);
static final public Action[] Actions = { Left, Right, Stop, Up, Down };
private final byte[][] layout;
private final Point start;
private final boolean[][] endEpisode;
private final double[][] rewardFunction;
private TRStep step;
public Maze(byte[][] layout, double[][] rewardFunction, boolean[][] endEpisode, Point start) {
this.layout = layout;
this.rewardFunction = rewardFunction;
this.endEpisode = endEpisode;
this.start = start;
initialize();
}
@Override
public TRStep initialize() {
step = new TRStep(new double[] { start.x, start.y }, rewardFunction[start.x][start.y]);
return step;
}
@Override
public TRStep step(Action action) {
double[] actions = ((ActionArray) action).actions;
int newX = (int) (step.o_tp1[0] + actions[0]);
int newY = (int) (step.o_tp1[1] + actions[1]);
if (layout[newX][newY] != 0) {
newX = (int) step.o_tp1[0];
newY = (int) step.o_tp1[1];
}
step = new TRStep(step, action, new double[] { newX, newY }, rewardFunction[newX][newY]);
if (endEpisode[newX][newY])
forceEndEpisode();
return step;
}
@Override
public TRStep forceEndEpisode() {
step = step.createEndingStep();
return step;
}
@Override
public TRStep lastStep() {
return step;
}
@Override
public Legend legend() {
return legend;
}
@Override
public Action[] actions() {
return Actions;
}
public byte[][] layout() {
return layout;
}
public Point size() {
return new Point(layout.length, layout[0].length);
}
public boolean[][] endEpisode() {
return endEpisode;
}
@SuppressWarnings("serial")
public Projector getMarkovProjector() {
final Point size = size();
final BVector projection = new BVector(size.x * size.y);
return new Projector() {
@Override
public int vectorSize() {
return projection.size;
}
@Override
public double vectorNorm() {
return 1;
}
@Override
public RealVector project(double[] obs) {
projection.clear();
if (obs != null)
projection.setOn((int) (obs[0] * size.y + obs[1]));
return projection;
}
};
}
}
|
package ca.corefacility.bioinformatics.irida.web.controller.test.listeners;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
/**
* Global settings for all integration tests.
*
*/
public class IntegrationTestListener extends RunListener {
private static final Logger logger = LoggerFactory.getLogger(IntegrationTestListener.class);
public static final int DRIVER_TIMEOUT_IN_SECONDS = 3;
private static WebDriver driver;
/**
* {@inheritDoc}
*/
public void testRunStarted(Description description) throws Exception {
if (isRunningUITests()) {
driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1400, 900));
driver.manage().timeouts().implicitlyWait(DRIVER_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
}
logger.debug("Setting up RestAssured.");
RestAssured.requestContentType(ContentType.JSON);
RestAssured.port = Integer.valueOf(System.getProperty("jetty.port"));
}
/**
* For starting chrome only when running individual tests,
* running the ui_testing profile, or running all_testing
*
* Does this by reading the `active-profile.txt` file, which is output
* by the `help:active-profiles` maven plugin/goal
*
* Essentially preventing ChromeDriver from running when it
* isn't required for the tests.
*
* i.e. Black list profiles for when we don't want chrome to run
*
*/
public boolean isRunningUITests() {
try {
ArrayList<String> whitelist = new ArrayList<>();
whitelist.add("ui_testing");
whitelist.add("all_testing");
return Files.lines(Paths.get("src/test/resources/active-profile.txt"))
.map(line -> line.split("\\s+"))
.flatMap(Arrays::stream)
.anyMatch((str) -> whitelist.contains(str));
}
catch (Exception e) {
//If the file doesn't exist or we have problems reading the file, we don't want to stop
// execution just for this, since we're just checking whether or not to run ChromeDriver.
// So, by default, if there's an error we'll just continue with ChromeDriver set to run.
logger.error("ERROR: " + e.toString() + " -> running ChromeDriver by default");
}
return true;
}
/**
* {@inheritDoc}
*/
public void testRunFinished(Result result) throws Exception {
if (driver != null) {
driver.quit();
}
}
/**
* Get a reference to the {@link WebDriver} used in the tests.
* @return the instance of {@link WebDriver} used in the tests.
*/
public static WebDriver driver() {
return driver;
}
}
|
package se.sics.mspsim.core;
import se.sics.mspsim.util.Utils;
/**
* @author joakim
*
*/
public class Watchdog extends IOUnit {
private static final boolean DEBUG = false;
private static final int WDTCTL = 0x120;
private static final int WDTHOLD = 0x80;
private static final int WDTCNTCL = 0x08;
private static final int WDTSSEL = 0x04;
private static final int WDTISx = 0x03;
private static final int RESET_VECTOR = 15;
private static final int[] DELAY = {
32768, 8192, 512, 64
};
private int wdtctl;
private boolean wdtOn = true;
private boolean hold = false;
private MSP430Core cpu;
// The current "delay" when started/clered (or hold)
private int delay;
// The target time for this timer
private long targetTime;
// Timer ACLK
private boolean sourceACLK = false;
private TimeEvent wdtTrigger = new TimeEvent(0) {
public void execute(long t) {
triggerWDT(t);
}
};
public Watchdog(MSP430Core cpu) {
super(cpu.memory, 0x120);
this.cpu = cpu;
}
public String getName() {
return "Watchdog";
}
public void interruptServiced(int vector) {
cpu.flagInterrupt(RESET_VECTOR, this, false);
}
private void triggerWDT(long time) {
// Here the WDT triggered!!!
System.out.println("WDT trigger - will reset node!");
cpu.generateTrace(System.out);
cpu.flagInterrupt(RESET_VECTOR, this, true);
}
public int read(int address, boolean word, long cycles) {
if (address == WDTCTL) return wdtctl | 0x6900;
return 0;
}
public void write(int address, int value, boolean word, long cycles) {
if (address == WDTCTL) {
if ((value >> 8) == 0x5a) {
wdtctl = value & 0xff;
if (DEBUG) System.out.println(getName() + " Wrote to WDTCTL: " + Utils.hex8(wdtctl));
// Is it on?
wdtOn = (value & 0x80) == 0;
boolean lastACLK = sourceACLK;
sourceACLK = (value & WDTSSEL) != 0;
if ((value & WDTCNTCL) != 0) {
// Clear timer => reset the delay
delay = DELAY[value & WDTISx];
}
// Start it if it should be started!
if (wdtOn) {
if (DEBUG) System.out.println("Setting WDTCNT to count: " + delay);
if (sourceACLK) {
if (DEBUG) System.out.println("setting delay in ms (ACLK): " + 1000.0 * delay / cpu.aclkFrq);
targetTime = cpu.scheduleTimeEventMillis(wdtTrigger, 1000.0 * delay / cpu.aclkFrq);
} else {
if (DEBUG) System.out.println("setting delay in cycles");
cpu.scheduleCycleEvent(wdtTrigger, targetTime = cpu.cycles + delay);
}
} else {
// Stop it and remember current "delay" left!
wdtTrigger.remove();
}
} else {
// Trigger reset!!
cpu.flagInterrupt(RESET_VECTOR, this, true);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.